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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add ERC-8004 Passport Widget for on-chain identity display
nirholasa017dca065eb
diff --git a/publish/package.json b/publish/package.jsonindex ffdb84ff9..cc812a1b3 100644--- a/publish/package.json+++ b/publish/package.json@@ -1,6 +1,6 @@{"name": "three.ws",- "version": "0.1.1",+ "version": "0.2.0","description": "3D AI agent platform for the browser. Load any GLB/glTF avatar, give it an LLM brain, and embed it as a web component.","author": "nirholas","license": "Apache-2.0",@@ -30,11 +30,13 @@".": {"import": "./agent-3d.js","require": "./agent-3d.umd.cjs"- }+ },+ "./src/*": "./src/*"},"files": ["agent-3d.js","agent-3d.umd.cjs",+ "src","LICENSE","README.md"],diff --git a/publish/src/account.js b/publish/src/account.jsnew file mode 100644index 000000000..431b659f1--- /dev/null+++ b/publish/src/account.js@@ -0,0 +1,177 @@+// Lightweight client helpers for talking to the three.ws backend from the viewer.+// Keeps the UI code in app.js/avatar-creator.js clean.++const API = ''; // same origin++// Wrapped fetch that handles expired sessions centrally. A 401 response is+// treated as a session-expiry signal and redirects to /login?next=<current>+// with the URL hash preserved (SPAs lose it on a naked location.href hop).+// Pass allowAnonymous:true for endpoints where a 401 is a legitimate+// "not signed in" answer the caller wants to inspect itself (e.g. /api/auth/me).+export async function apiFetch(path, options = {}) {+ const { allowAnonymous = false, ...init } = options;+ const res = await fetch(path, {+ credentials: 'include',+ ...init,+ });+ if (res.status === 401 && !allowAnonymous) {+ redirectToLogin();+ const err = new Error('session expired');+ err.status = 401;+ err.redirected = true;+ throw err;+ }+ return res;+}++function redirectToLogin() {+ if (typeof location === 'undefined') return;+ // Don't loop if we're already on the login page.+ if (/^\/login(\/|$|\?)/.test(location.pathname)) return;+ const next = location.pathname + location.search + location.hash;+ location.href = '/login?next=' + encodeURIComponent(next);+}++// Optimistic auth hint — non-authoritative, used only for first-paint gating+// on the viewer. The real session cookie is HttpOnly so we can't read it+// synchronously; this hint lets us avoid a visible flash between "pending"+// and the resolved state for returning users. Always revalidated by getMe().+const AUTH_HINT_KEY = '3dagent:auth-hint';+const AUTH_HINT_TTL_MS = 1000 * 60 * 60 * 24 * 7; // 7d++export function readAuthHint() {+ try {+ const raw = localStorage.getItem(AUTH_HINT_KEY);+ if (!raw) return null;+ const { authed, ts } = JSON.parse(raw);+ if (!ts || Date.now() - ts > AUTH_HINT_TTL_MS) return null;+ return authed ? 'true' : 'false';+ } catch {+ return null;+ }+}++function writeAuthHint(authed) {+ try {+ localStorage.setItem(AUTH_HINT_KEY, JSON.stringify({ authed: !!authed, ts: Date.now() }));+ } catch {+ /* quota or disabled storage */+ }+}++export function clearAuthHint() {+ try {+ localStorage.removeItem(AUTH_HINT_KEY);+ } catch {+ /* ignore */+ }+}++export async function getMe() {+ // /api/auth/me 401s for anonymous visitors by design — handle in place.+ const res = await apiFetch(`${API}/api/auth/me`, { allowAnonymous: true });+ if (res.status === 401) {+ writeAuthHint(false);+ return null;+ }+ if (!res.ok) throw new Error(`auth/me failed: ${res.status}`);+ const user = (await res.json()).user;+ writeAuthHint(!!user);+ return user;+}++// Uploads a GLB to our R2 bucket and creates the avatar record.+// `source` may be a Blob (from CharacterStudio postMessage) or a URL string.+// Throws if the user isn't authenticated.+export async function saveRemoteGlbToAccount(source, meta = {}) {+ const user = await getMe();+ if (!user) {+ const err = new Error('not_signed_in');+ err.code = 'not_signed_in';+ throw err;+ }++ let blob;+ if (source instanceof Blob) {+ blob = source;+ } else {+ const resp = await fetch(source, { mode: 'cors' });+ if (!resp.ok) throw new Error(`failed to fetch source GLB: ${resp.status}`);+ blob = await resp.blob();+ }++ const size = blob.size;+ const contentType = blob.type || 'model/gltf-binary';+ const checksum = await sha256Hex(blob);++ const presign = await postJson('/api/avatars/presign', {+ size_bytes: size,+ content_type: contentType,+ checksum_sha256: checksum,+ });++ const putRes = await fetch(presign.upload_url, {+ method: 'PUT',+ headers: { 'content-type': contentType },+ body: blob,+ });+ if (!putRes.ok) throw new Error(`R2 upload failed: ${putRes.status}`);++ const sourceMeta =+ meta.source_meta ||+ (typeof source === 'string' ? { source_url: source } : { generator: 'characterstudio' });++ const created = await postJson('/api/avatars', {+ storage_key: presign.storage_key,+ size_bytes: size,+ content_type: contentType,+ checksum_sha256: checksum,+ name: meta.name || deriveAvatarName(source, checksum),+ description: meta.description,+ visibility: meta.visibility || 'private',+ tags: meta.tags || [],+ source: meta.source || 'upload',+ source_meta: sourceMeta,+ });+ return created.avatar;+}++async function postJson(path, body) {+ const res = await apiFetch(`${API}${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ const data = res.headers.get('content-type')?.includes('application/json')+ ? await res.json()+ : null;+ if (!res.ok)+ throw Object.assign(new Error(data?.error_description || res.statusText), {+ status: res.status,+ data,+ });+ return data;+}++async function sha256Hex(blob) {+ const buf = await blob.arrayBuffer();+ const hash = await crypto.subtle.digest('SHA-256', buf);+ return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');+}++function deriveAvatarName(source, checksum) {+ if (source && typeof source === 'object' && typeof source.name === 'string') {+ const base = source.name.replace(/\.(glb|gltf)$/i, '').trim();+ if (base) return base.slice(0, 80);+ }+ if (typeof source === 'string') {+ try {+ const file = new URL(source).pathname.split('/').pop() || '';+ const base = file.replace(/\.(glb|gltf)$/i, '').trim();+ if (base) return base.slice(0, 80);+ } catch {+ /* ignore non-URL strings */+ }+ }+ return `Avatar #${checksum.slice(0, 6)}`;+}diff --git a/publish/src/agent-accessories.js b/publish/src/agent-accessories.jsnew file mode 100644index 000000000..92ced53d8--- /dev/null+++ b/publish/src/agent-accessories.js@@ -0,0 +1,250 @@+// AccessoryManager — applies outfit morph bindings and bone-attached GLB accessories+// at runtime without touching the canonical avatar GLB on R2.+//+// Outfit state lives in agent_identities.meta.appearance = { outfit, accessories, morphs }.+// The Empathy Layer's morph loop only iterates its own _morphTarget dict, so+// outfit morphs set here are never clobbered by emotion blending.++import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { resolveURI } from './ipfs.js';++const SINGLE_SLOT_KINDS = new Set(['outfit', 'hat', 'glasses']);++export class AccessoryManager {+ /** @param {import('./viewer.js').Viewer} viewer — raw Viewer, not SceneController */+ constructor(viewer) {+ this.viewer = viewer;+ this._loader = new GLTFLoader();+ // id → { preset, object?: THREE.Group, morphs?: Array<{node,name,idx}> }+ this._applied = new Map();+ }++ /**+ * Apply a preset. Handles conflict rules (only one outfit/hat/glasses at a time).+ * If the preset is already applied, re-applies it (no-op if same).+ * @param {{ id, kind, glbUrl?, attachBone?, morphBinding?, name }} preset+ */+ async applyPreset(preset) {+ // Enforce single-slot per kind (not for earrings)+ if (SINGLE_SLOT_KINDS.has(preset.kind)) {+ this._removeByKind(preset.kind);+ } else if (this._applied.has(preset.id)) {+ return; // earrings: silently skip duplicates+ }++ if (preset.glbUrl) {+ await this._applyGLB(preset);+ } else if (preset.morphBinding) {+ this._applyMorphBinding(preset);+ }+ }++ /** Remove a preset by id, disposing GPU resources. */+ removePreset(id) {+ const entry = this._applied.get(id);+ if (!entry) return;++ if (entry.object) {+ entry.object.parent?.remove(entry.object);+ _disposeObject(entry.object);+ }+ if (entry.morphs) {+ _zeroMorphs(entry.morphs);+ }++ this._applied.delete(id);+ this.viewer?.invalidate?.();+ }++ /** Returns the currently applied preset ids. */+ list() {+ return [...this._applied.keys()];+ }++ /**+ * Apply all presets from a meta.appearance record on boot.+ * Fetches presets.json to resolve ids → full preset objects.+ */+ async hydrateFromAppearance(appearance) {+ if (!appearance) return;++ const presets = await _fetchPresets();+ const byId = new Map(presets.map((p) => [p.id, p]));++ const ids = [];+ if (appearance.outfit) ids.push(appearance.outfit);+ for (const id of appearance.accessories || []) ids.push(id);++ // Extra morph overrides (arbitrary morph names, not preset-driven)+ if (appearance.morphs && this.viewer?.content) {+ _applyRawMorphs(this.viewer.content, appearance.morphs);+ }++ for (const id of ids) {+ const preset = byId.get(id);+ if (preset) {+ await this.applyPreset(preset);+ } else {+ console.warn(`[accessories] unknown preset id on boot: ${id}`);+ }+ }+ }++ /**+ * Called when the avatar GLB is replaced (task 01/02 path).+ * Re-attaches bone overlays to the new skeleton; re-applies morph bindings.+ * Surfaces a console warning per preset if its required bone/morph is missing.+ */+ async onModelReplaced(newViewer) {+ if (newViewer) this.viewer = newViewer;++ const snapshot = [...this._applied.values()].map((e) => e.preset);++ // Detach/dispose everything — old bone refs belong to the discarded model+ for (const [, entry] of this._applied) {+ if (entry.object) _disposeObject(entry.object);+ }+ this._applied.clear();++ for (const preset of snapshot) {+ await this.applyPreset(preset);+ }+ }++ // ── Private ──────────────────────────────────────────────────────────────++ async _applyGLB(preset) {+ let gltf;+ try {+ gltf = await _loadGLB(this._loader, preset.glbUrl);+ } catch (err) {+ console.warn(`[accessories] failed to load ${preset.glbUrl}:`, err);+ return;+ }++ const bone = _findBone(this.viewer?.content, preset.attachBone);+ if (!bone) {+ console.warn(+ `[accessories] bone not found: ${preset.attachBone} (preset: ${preset.id})`,+ );+ // Still record as applied so list() and removePreset() work correctly+ this._applied.set(preset.id, { preset, object: null });+ return;+ }++ const obj = gltf.scene;+ bone.add(obj);+ this._applied.set(preset.id, { preset, object: obj });+ this.viewer?.invalidate?.();+ }++ _applyMorphBinding(preset) {+ if (!this.viewer?.content) {+ console.warn(`[accessories] no model loaded yet for preset ${preset.id}`);+ return;+ }++ const morphs = _applyMorphsToModel(this.viewer.content, preset.morphBinding);+ this._applied.set(preset.id, { preset, morphs });+ this.viewer?.invalidate?.();+ }++ _removeByKind(kind) {+ for (const [id, entry] of this._applied) {+ if (entry.preset.kind === kind) {+ this.removePreset(id);+ return; // only one active per single-slot kind+ }+ }+ }+}++// ── Module-level helpers ──────────────────────────────────────────────────────++function _loadGLB(loader, url) {+ const resolved = resolveURI(url);+ return new Promise((resolve, reject) => {+ loader.load(resolved, resolve, undefined, reject);+ });+}++/**+ * Find a bone by name, tolerating mixamorig / CC_Base_ prefixes.+ * Returns the first match or null.+ */+function _findBone(model, boneName) {+ if (!model || !boneName) return null;+ const target = boneName.toLowerCase();+ let found = null;+ model.traverse((n) => {+ if (found || !n.isBone) return;+ const canon = n.name+ .replace(/^mixamorig[_:]?/i, '')+ .replace(/^CC_Base_/i, '')+ .replace(/^rig_/i, '')+ .toLowerCase();+ if (canon === target || n.name === boneName) found = n;+ });+ return found;+}++/**+ * Set morph target influences from a name→weight map.+ * Returns a receipts array that _zeroMorphs() can use to undo.+ */+function _applyMorphsToModel(model, binding) {+ const receipts = [];+ model.traverse((node) => {+ if (!node.isMesh || !node.morphTargetDictionary || !node.morphTargetInfluences) return;+ for (const [name, weight] of Object.entries(binding)) {+ const idx = node.morphTargetDictionary[name];+ if (idx === undefined) continue;+ node.morphTargetInfluences[idx] = Math.max(0, Math.min(1, weight));+ receipts.push({ node, idx });+ }+ });+ return receipts;+}++/** Apply raw morph overrides (arbitrary names, not preset-driven). */+function _applyRawMorphs(model, morphs) {+ model.traverse((node) => {+ if (!node.isMesh || !node.morphTargetDictionary || !node.morphTargetInfluences) return;+ for (const [name, weight] of Object.entries(morphs)) {+ const idx = node.morphTargetDictionary[name];+ if (idx === undefined) continue;+ node.morphTargetInfluences[idx] = Math.max(0, Math.min(1, weight));+ }+ });+}++function _zeroMorphs(receipts) {+ for (const { node, idx } of receipts) {+ if (node.morphTargetInfluences) node.morphTargetInfluences[idx] = 0;+ }+}++function _disposeObject(obj) {+ obj.traverse((child) => {+ child.geometry?.dispose();+ if (child.material) {+ const mats = Array.isArray(child.material) ? child.material : [child.material];+ for (const m of mats) {+ m.map?.dispose();+ m.normalMap?.dispose();+ m.roughnessMap?.dispose();+ m.metalnessMap?.dispose();+ m.emissiveMap?.dispose();+ m.dispose();+ }+ }+ });+}++let _presetsCache = null;+async function _fetchPresets() {+ if (_presetsCache) return _presetsCache;+ const res = await fetch('/accessories/presets.json');+ _presetsCache = await res.json();+ return _presetsCache;+}diff --git a/publish/src/agent-avatar.js b/publish/src/agent-avatar.jsnew file mode 100644index 000000000..61d0c2b63--- /dev/null+++ b/publish/src/agent-avatar.js@@ -0,0 +1,777 @@+/**+ * Agent Avatar — Performer + Empathy Layer+ * -----------------------------------------+ * This is the thing that makes agents real.+ *+ * It listens to the AgentProtocol bus and drives the Three.js avatar:+ * - speaks with lip sync hints+ * - plays named gestures and animations+ * - looks toward models/objects+ *+ * The Empathy Layer (novel):+ * Every action emitted to the protocol is read for emotional valence.+ * The avatar maintains a *continuous weighted blend* of emotional states —+ * never snapping between moods, always drifting. Morph targets and head+ * orientation are updated every animation frame.+ *+ * Nobody has done this before in a three.ws system:+ * you can feel 40% concerned + 30% curious + 30% neutral simultaneously,+ * and the avatar's face reflects all three at once — exactly as humans do.+ */++import { ACTION_TYPES } from './agent-protocol.js';+import { Vector3, Box3, MathUtils } from 'three';+import { resolveSlot, DEFAULT_ANIMATION_MAP } from './runtime/animation-slots.js';+// BEGIN:IDLE_LOOP_IMPORT+import { IdleAnimation } from './idle-animation.js';+// END:IDLE_LOOP_IMPORT++const DEG2RAD = Math.PI / 180;++// Emotion decay rates (units per second — larger = fades faster)+const DECAY = {+ concern: 0.08, // half-life ~12s — lingers, builds empathy+ celebration: 0.18, // half-life ~6s — bright but brief+ patience: 0.035, // half-life ~20s — sustained waiting state+ curiosity: 0.12, // half-life ~8s — alert, engaged+ empathy: 0.055, // half-life ~13s — slow to fade, like real empathy+};++// Vocabulary scored for emotional valence+// Keys map to emotion buckets; values are keyword lists+const VOCAB = {+ concern: [+ 'error',+ 'failed',+ 'fail',+ 'invalid',+ 'missing',+ 'broken',+ 'issue',+ 'warning',+ 'problem',+ 'wrong',+ 'crash',+ 'undefined',+ 'null',+ 'corrupt',+ ],+ celebration: [+ 'success',+ 'complete',+ 'valid',+ 'clean',+ 'done',+ 'great',+ 'loaded',+ 'ready',+ 'perfect',+ 'excellent',+ 'nice',+ 'good',+ 'worked',+ 'saved',+ ],+ patience: [+ 'analyzing',+ 'checking',+ 'loading',+ 'processing',+ 'thinking',+ 'please wait',+ 'just a moment',+ 'scanning',+ 'computing',+ 'fetching',+ ],+ curiosity: [+ 'interesting',+ 'wonder',+ 'what if',+ 'explore',+ 'curious',+ 'new',+ 'never seen',+ 'unusual',+ 'rare',+ 'unique',+ 'unexpected',+ ],+ empathy: [+ 'sorry',+ 'understand',+ 'difficult',+ 'frustrating',+ 'try again',+ 'my mistake',+ 'apologies',+ 'hard',+ 'oops',+ 'unfortunately',+ ],+};++export class AgentAvatar {+ /**+ * @param {import('./viewer.js').Viewer} viewer+ * @param {import('./agent-protocol.js').AgentProtocol} protocol+ * @param {import('./agent-identity.js').AgentIdentity} identity+ */+ constructor(viewer, protocol, identity) {+ this.viewer = viewer;+ this.protocol = protocol;+ this.identity = identity;++ // Emotional state — continuous weighted blend, updated every frame+ this._emotion = {+ neutral: 1.0,+ concern: 0.0,+ celebration: 0.0,+ patience: 0.0,+ curiosity: 0.0,+ empathy: 0.0,+ };++ // Head look-at state+ this._lookTarget = null; // Vector3 | null+ this._currentTilt = 0; // radians+ this._targetTilt = 0; // radians+ this._currentLean = 0; // slight forward lean+ this._targetLean = 0;+ this._currentYaw = 0; // horizontal gaze (follow mode)++ // Follow mode state+ this._mouseGaze = { x: 0, y: 0 }; // normalised -1..1+ this._keystrokePitch = 0; // look-down impulse (radians, decays)+ this._keystrokeYaw = 0; // lateral drift impulse (radians, decays)++ // One-shot gesture tracking+ this._oneShotAction = null;+ this._oneShotDuration = 0;+ this._oneShotTimer = 0;+ this._isPlayingOneShot = false;++ // Animation slot override map (from meta.edits.animations)+ this._animationMap = {};+ this._warnedSlots = new Set();++ // Streak tracking for empathy injection+ this._errorStreak = 0;+ this._firstEncounter = true;++ // Morph target current values (lerped each frame)+ this._morphCurrent = {};+ this._morphTarget = {};+ // Cached list of meshes with morph targets — rebuilt on attach() to avoid per-frame traversal+ this._morphMeshes = null;++ // Listeners stored so we can detach later+ this._listeners = [];++ this._tickBound = this._tickEmotion.bind(this);+ this._onMouseMove = this._handleMouseMove.bind(this);+ this._onKeyFollowDown = this._handleKeyPress.bind(this);+ }++ // ── Lifecycle ─────────────────────────────────────────────────────────────++ /** Call after viewer.setContent() loads the avatar model */+ attach() {+ // Reset emotion to neutral so re-attaching a previously emotional avatar starts clean+ this._emotion = { neutral: 1.0, concern: 0, celebration: 0, patience: 0, curiosity: 0, empathy: 0 };++ // Build the morph mesh cache once instead of traversing every frame+ this._buildMorphCache();++ // Hook into the viewer's per-frame loop+ if (!this.viewer._afterAnimateHooks) this.viewer._afterAnimateHooks = [];+ this.viewer._afterAnimateHooks.push(this._tickBound);++ // Follow mode input listeners+ this.viewer.el.addEventListener('mousemove', this._onMouseMove);+ window.addEventListener('keydown', this._onKeyFollowDown);++ // Subscribe to protocol events+ this._sub(ACTION_TYPES.SPEAK, this._onSpeak.bind(this));+ this._sub(ACTION_TYPES.GESTURE, this._onGesture.bind(this));+ this._sub(ACTION_TYPES.EMOTE, this._onEmote.bind(this));+ this._sub(ACTION_TYPES.LOOK_AT, this._onLookAt.bind(this));+ this._sub(ACTION_TYPES.PERFORM_SKILL, this._onSkillStart.bind(this));+ this._sub(ACTION_TYPES.SKILL_DONE, this._onSkillDone.bind(this));+ this._sub(ACTION_TYPES.SKILL_ERROR, this._onSkillError.bind(this));+ 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));++ // First-encounter curiosity burst+ if (this._firstEncounter) {+ this._firstEncounter = false;+ setTimeout(() => {+ this._injectStimulus('curiosity', 0.9);+ this._injectStimulus('celebration', 0.4);+ }, 600);+ }++ // BEGIN:IDLE_LOOP_INIT+ this._idle?.dispose();+ this._idle = new IdleAnimation({+ getRoot: () => this.viewer.content,+ protocol: this.protocol,+ seed: this.identity?.id ?? 'default',+ getMorphCurrent: () => this._morphCurrent,+ });+ // END:IDLE_LOOP_INIT+ }++ /** Remove all hooks and listeners */+ detach() {+ if (this.viewer._afterAnimateHooks) {+ const idx = this.viewer._afterAnimateHooks.indexOf(this._tickBound);+ if (idx !== -1) this.viewer._afterAnimateHooks.splice(idx, 1);+ }+ this.viewer.el.removeEventListener('mousemove', this._onMouseMove);+ window.removeEventListener('keydown', this._onKeyFollowDown);+ for (const [type, handler] of this._listeners) {+ this.protocol.off(type, handler);+ }+ this._listeners = [];+ // BEGIN:IDLE_LOOP_DISPOSE+ this._idle?.dispose();+ this._idle = null;+ // END:IDLE_LOOP_DISPOSE+ }++ // ── Public API ────────────────────────────────────────────────────────────++ /** Play a named gesture animation */+ playGesture(name) {+ this._triggerOneShot(name);+ }++ /**+ * Set the agent's animation slot override map (from meta.edits.animations).+ * @param {Object|null} map — { slotName: clipName, … }+ */+ setAnimationMap(map) {+ this._animationMap = map || {};+ }++ /** Resolve a slot name to the actual clip name via agent's override map. */+ _resolveSlot(slot) {+ return resolveSlot(slot, this._animationMap);+ }++ /**+ * Play a gesture by slot name, routing through the external animation manager.+ * Falls back to embedded clip search (_triggerOneShot) if the clip isn't in the library.+ * Warns once per missing clip name.+ * @param {string} slot — e.g. 'celebrate', 'think'+ * @param {number} [duration]+ */+ _playSlot(slot, duration = 1.5) {+ const clipName = this._resolveSlot(slot);+ this._isPlayingOneShot = true;+ this._oneShotAction = slot;+ this._oneShotDuration = duration;+ this._oneShotTimer = 0;++ const am = this.viewer?.animationManager;+ if (am) {+ if (am.isLoaded(clipName)) {+ this._playAmClip(am, clipName, duration);+ return;+ }+ // Lazy-load from manifest definition+ const def = am.getAnimationDefs().find((d) => d.name === clipName);+ if (def) {+ const prev = am.currentName;+ am.loadAnimation(clipName, def.url, { loop: false, clipName: def.clipName }).then(+ () => {+ this._playAmClip(am, clipName, duration, prev);+ },+ );+ return;+ }+ // Clip not in library — warn once, try default slot fallback+ if (!this._warnedSlots.has(clipName)) {+ console.warn(+ `[AgentAvatar] slot "${slot}" → "${clipName}" not in animation library`,+ );+ this._warnedSlots.add(clipName);+ }+ const fallback = DEFAULT_ANIMATION_MAP[slot];+ if (fallback && fallback !== clipName && am.isLoaded(fallback)) {+ this._playAmClip(am, fallback, duration);+ return;+ }+ }++ // Final fallback: embedded clip search+ this._triggerOneShot(clipName, duration);+ }++ _playAmClip(am, clipName, duration, prevName) {+ const prev = prevName ?? am.currentName;+ am.play(clipName);+ if (prev && am.isLoaded(prev)) {+ setTimeout(() => am.crossfadeTo(prev, 0.4), duration * 1000);+ }+ }++ /** Set a world-space point for the avatar to look toward */+ setLookTarget(worldPos) {+ this._lookTarget = worldPos ? worldPos.clone() : null;+ }++ /** Get current emotion blend (read-only snapshot) */+ get emotionState() {+ return { ...this._emotion };+ }++ // ── Protocol Handlers ─────────────────────────────────────────────────────++ _onSpeak(action) {+ const text = action.payload?.text || '';+ const { valence, arousal } = this._analyzeSentiment(text);++ // Positive speech → celebration boost; negative → concern+ if (valence > 0.3) this._injectStimulus('celebration', valence * 0.7);+ else if (valence < -0.2) this._injectStimulus('concern', Math.abs(valence) * 0.8);++ // High-arousal text (questions, exclamations) → curiosity+ if (arousal > 0.5) this._injectStimulus('curiosity', arousal * 0.5);++ // Trigger mouth/talk animation hint+ const duration = Math.max(1.5, text.split(' ').length * 0.3);+ this._triggerOneShot('talk', duration);+ }++ _onGesture(action) {+ const name = action.payload?.name || 'nod';+ this._triggerOneShot(name, action.payload?.duration || 1.5);+ }++ _onEmote(action) {+ const trigger = action.payload?.trigger;+ const weight = action.payload?.weight || 0.7;+ if (trigger && this._emotion.hasOwnProperty(trigger)) {+ this._injectStimulus(trigger, weight);+ }+ }++ _onLookAt(action) {+ const target = action.payload?.target;+ if (target === 'model' && this.viewer?.content) {+ // Look at the bounding box center of the loaded model+ const box = new Box3();+ const center = new Vector3();+ box.setFromObject(this.viewer.content).getCenter(center);+ this._lookTarget = center;+ } else if (target === 'user') {+ this._lookTarget = null; // look at camera+ }+ this._injectStimulus('curiosity', 0.3);+ }++ _onSkillStart(action) {+ const hint = action.payload?.animationHint;+ if (hint) this._triggerOneShot(hint, 1.0);+ this._injectStimulus('patience', 0.4);+ }++ _onSkillDone(action) {+ const result = action.payload?.result;+ if (result?.sentiment !== undefined) {+ if (result.sentiment > 0.3) this._injectStimulus('celebration', result.sentiment * 0.8);+ else if (result.sentiment < -0.2)+ this._injectStimulus('concern', Math.abs(result.sentiment) * 0.7);+ } else {+ this._injectStimulus('celebration', 0.4);+ }+ this._errorStreak = 0;+ }++ _onSkillError(_action) {+ this._errorStreak++;+ const empathyWeight = Math.min(this._errorStreak * 0.25, 0.9);+ this._injectStimulus('concern', 0.7);+ this._injectStimulus('empathy', empathyWeight);+ }++ _onLoadStart(_action) {+ this._injectStimulus('patience', 0.6);+ this._injectStimulus('curiosity', 0.3);+ this._playSlot('think', 2.0);+ }++ _onLoadEnd(action) {+ if (action.payload?.error) {+ this._injectStimulus('concern', 0.8);+ } else {+ this._injectStimulus('celebration', 0.7);+ this._injectStimulus('curiosity', 0.5);+ this._playSlot('nod', 1.0);+ }+ }++ _onValidate(action) {+ const errors = action.payload?.errors || 0;+ const warnings = action.payload?.warnings || 0;+ if (errors > 0) {+ this._injectStimulus('concern', Math.min(0.4 + errors * 0.1, 0.95));+ this._errorStreak++;+ } else if (warnings > 0) {+ this._injectStimulus('concern', 0.3);+ } else {+ this._injectStimulus('celebration', 0.85);+ this._playSlot('celebrate', 1.5);+ }+ }++ // ── Empathy Layer — The Novel Part ────────────────────────────────────────++ /**+ * Inject a stimulus into the emotion state.+ * Uses additive blending — stimuli accumulate, then decay.+ * @param {string} emotion — one of the DECAY keys+ * @param {number} weight — 0..1+ */+ _injectStimulus(emotion, weight) {+ if (!(emotion in this._emotion)) return;+ this._emotion[emotion] = Math.min(1.0, this._emotion[emotion] + weight);+ // Neutral inversely reflects total arousal+ this._normaliseNeutral();+ }++ _normaliseNeutral() {+ const sum = Object.keys(DECAY).reduce((acc, k) => acc + this._emotion[k], 0);+ this._emotion.neutral = Math.max(0, 1 - sum);+ }++ /**+ * Per-frame emotion decay + avatar rendering.+ * Called by viewer._afterAnimateHooks every animation frame.+ * @param {number} dt — delta time in seconds+ */+ _tickEmotion(dt) {+ // Stage 1: Decay all non-neutral emotions+ for (const [key, rate] of Object.entries(DECAY)) {+ this._emotion[key] = Math.max(0, this._emotion[key] - rate * dt);+ }+ this._normaliseNeutral();++ // Stage 2: One-shot gesture timer+ if (this._isPlayingOneShot) {+ this._oneShotTimer += dt;+ if (this._oneShotTimer >= this._oneShotDuration) {+ this._isPlayingOneShot = false;+ this._oneShotTimer = 0;+ }+ }++ // Stage 3: Emotion-threshold gesture triggers (routed through slot map)+ if (!this._isPlayingOneShot) {+ const w = this._emotion;+ if (w.celebration > 0.6) {+ this._playSlot('celebrate', 2.0);+ } else if (w.concern > 0.6) {+ this._playSlot('concern', 2.0);+ } else if (w.curiosity > 0.6) {+ this._playSlot('think', 1.5);+ }+ }++ // Stage 4: Apply emotion to avatar+ this._applyEmotionToAvatar(dt);++ // BEGIN:IDLE_LOOP_TICK+ this._idle?.update(dt);+ // END:IDLE_LOOP_TICK+ }++ /**+ * Render the current emotional state onto the avatar mesh.+ * Gracefully no-ops if morph targets or head bone don't exist.+ */+ _applyEmotionToAvatar(dt) {+ const w = this._emotion;++ // ── Morph target targets ──────────────────────────────────────────+ // The Empathy Layer blends ALL emotions simultaneously —+ // not a discrete switch, a continuous weighted blend.+ this._setMorphTarget('mouthSmile', w.celebration * 0.85);+ this._setMorphTarget(+ 'mouthOpen',+ w.celebration * 0.2 ++ (this._isPlayingOneShot && this._oneShotAction === 'talk' ? 0.4 : 0),+ );+ this._setMorphTarget('mouthFrown', w.concern * 0.55);+ this._setMorphTarget('browInnerUp', (w.concern + w.empathy * 0.5) * 0.6);+ this._setMorphTarget('browOuterUpLeft', w.curiosity * 0.7);+ this._setMorphTarget('browOuterUpRight', w.curiosity * 0.5);+ this._setMorphTarget('eyeSquintLeft', w.empathy * 0.4);+ this._setMorphTarget('eyeSquintRight', w.empathy * 0.4);+ this._setMorphTarget('eyesClosed', w.patience * 0.15); // slight, not full+ this._setMorphTarget('cheekPuff', w.celebration * 0.2);+ this._setMorphTarget('noseSneerLeft', w.concern * 0.15);+ this._setMorphTarget('noseSneerRight', w.concern * 0.15);++ // ── Lerp morph influences to targets ─────────────────────────────+ const lerpSpeed = dt * 4.0; // smooth interpolation, not snapping+ this._lerpMorphTargets(lerpSpeed);++ // ── Head tilt (curiosity + empathy both tilt the head) ────────────+ this._targetTilt = (w.curiosity * 12 + w.empathy * 9 + w.concern * 4) * DEG2RAD;+ this._currentTilt = _lerp(this._currentTilt, this._targetTilt, dt * 3.0);++ // ── Forward lean (curiosity leans in, patience leans back) ────────+ this._targetLean = w.curiosity * 0.03 - w.patience * 0.02;+ const _followMode = this.viewer.state?.followMode;+ if (_followMode === 'mouse') {+ // Mouse Y: -1 = top of canvas (look up), +1 = bottom (look down)+ this._targetLean += this._mouseGaze.y * (12 * DEG2RAD);+ } else if (_followMode === 'keystrokes') {+ this._targetLean += this._keystrokePitch;+ this._keystrokePitch = Math.max(0, this._keystrokePitch - dt * 0.9);+ this._keystrokeYaw = _lerp(this._keystrokeYaw, 0, dt * 0.6);+ } else {+ // Decay any residual follow-mode values if mode was switched off+ this._keystrokePitch = 0;+ this._keystrokeYaw = _lerp(this._keystrokeYaw, 0, dt * 2.0);+ this._mouseGaze.x = _lerp(this._mouseGaze.x, 0, dt * 2.0);+ this._mouseGaze.y = _lerp(this._mouseGaze.y, 0, dt * 2.0);+ }+ this._currentLean = _lerp(this._currentLean, this._targetLean, dt * 2.0);++ this._applyHeadTransform();+ }++ // ── Morph Target Helpers ─────────────────────────────────────────────────++ /**+ * Set the *target* influence for a named morph target.+ * Actual mesh influence is lerped in _lerpMorphTargets().+ */+ _setMorphTarget(name, targetWeight) {+ this._morphTarget[name] = Math.max(0, Math.min(1, targetWeight));+ if (!(name in this._morphCurrent)) this._morphCurrent[name] = 0;+ }++ /** Collect all meshes with morph targets once per content load. */+ _buildMorphCache() {+ this._morphMeshes = [];+ if (!this.viewer?.content) return;+ this.viewer.content.traverse((node) => {+ if (node.isMesh && node.morphTargetDictionary && node.morphTargetInfluences) {+ this._morphMeshes.push(node);+ }+ });+ }++ /** Lerp all tracked morph target influences toward their targets */+ _lerpMorphTargets(speed) {+ if (!this._morphMeshes?.length) return;+ for (const node of this._morphMeshes) {+ for (const [name, target] of Object.entries(this._morphTarget)) {+ const idx = node.morphTargetDictionary[name];+ if (idx === undefined) continue;+ const current = node.morphTargetInfluences[idx] || 0;+ const next = _lerp(current, target, speed);+ node.morphTargetInfluences[idx] = next;+ this._morphCurrent[name] = next;+ }+ }+ }++ // ── Head Transform ────────────────────────────────────────────────────────++ // Safety clamps — keep the head within believable neck range.+ // (Input signals are already bounded by design, but belt-and-braces.)+ static HEAD_MAX_YAW = 45 * DEG2RAD;+ static HEAD_MAX_TILT = 25 * DEG2RAD;+ static HEAD_MAX_LEAN = 25 * DEG2RAD;++ _applyHeadTransform() {+ if (!this.viewer?.content) return;++ // Resolve exactly one head bone (or fall back to neck) and snapshot its+ // rest rotation. Any substring match over the whole skeleton would pick+ // up Head + Neck + HeadTop_End simultaneously, and writing the same+ // local rotation to all three stacks hierarchically → owl-style 360.+ if (this._headBoneFor !== this.viewer.content) {+ this._headBoneFor = this.viewer.content;+ this._headBone = this._findHeadBone();+ if (this._headBone) {+ this._headRestRotation = {+ x: this._headBone.rotation.x,+ y: this._headBone.rotation.y,+ z: this._headBone.rotation.z,+ };+ }+ }+ if (!this._headBone) return;++ // Compute yaw target from follow mode+ const followMode = this.viewer.state?.followMode;+ let targetYaw = 0;+ if (followMode === 'mouse') {+ targetYaw = this._mouseGaze.x * (25 * DEG2RAD);+ } else if (followMode === 'keystrokes') {+ targetYaw = this._keystrokeYaw;+ }+ this._currentYaw = _lerp(this._currentYaw, targetYaw, 0.08);++ const yaw = MathUtils.clamp(+ this._currentYaw,+ -AgentAvatar.HEAD_MAX_YAW,+ AgentAvatar.HEAD_MAX_YAW,+ );+ const tilt = MathUtils.clamp(+ this._currentTilt,+ -AgentAvatar.HEAD_MAX_TILT,+ AgentAvatar.HEAD_MAX_TILT,+ );+ const lean = MathUtils.clamp(+ this._currentLean,+ -AgentAvatar.HEAD_MAX_LEAN,+ AgentAvatar.HEAD_MAX_LEAN,+ );++ // Apply pre-smoothed values directly — _currentTilt/Lean/Yaw are already+ // dt-lerped above, so a second lerp on the live bone value would fight the+ // animation mixer and cause visible head bobbing.+ const r = this._headRestRotation;+ const b = this._headBone;+ b.rotation.z = r.z + tilt;+ b.rotation.x = r.x + lean;+ b.rotation.y = r.y + yaw;+ }++ /**+ * Find the single head bone (or neck fallback). Canonicalises common+ * naming conventions: `Head`, `mixamorigHead`, `Armature:Head`, `rig_Head`,+ * `CC_Base_Head`. Returns null if neither exists.+ */+ _findHeadBone() {+ let head = null,+ neck = null;+ this.viewer.content.traverse((node) => {+ if (!node.isBone) return;+ const canon = node.name+ .replace(/^mixamorig/i, '')+ .replace(/^.*[:_]/, '')+ .toLowerCase();+ if (!head && canon === 'head') head = node;+ else if (!neck && canon === 'neck') neck = node;+ });+ return head || neck || null;+ }++ // ── Follow Mode Handlers ──────────────────────────────────────────────────++ _handleMouseMove(e) {+ const rect = this.viewer.el.getBoundingClientRect();+ this._mouseGaze.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;+ this._mouseGaze.y = ((e.clientY - rect.top) / rect.height) * 2 - 1;+ }++ _handleKeyPress(e) {+ if (this.viewer.state?.followMode !== 'keystrokes') return;+ if (['Shift', 'Control', 'Alt', 'Meta', 'CapsLock', 'Tab', 'Escape'].includes(e.key))+ return;++ // Look down toward keyboard+ this._keystrokePitch = 0.18;++ // Lateral drift based on rough key column: left side → look left, right side → look right+ const leftKeys = 'qweasdzxc123`~!@#';+ const rightKeys = 'yuiophjklnm7890-=';+ const k = e.key.toLowerCase();+ if (leftKeys.includes(k)) this._keystrokeYaw = -0.12;+ else if (rightKeys.includes(k)) this._keystrokeYaw = 0.12;++ this._injectStimulus('curiosity', 0.07);+ }++ // ── Gesture / One-shot Animations ────────────────────────────────────────++ /**+ * Trigger a one-shot animation clip if it exists on the model.+ * Falls back gracefully if the clip doesn't exist.+ * @param {string} clipName+ * @param {number} [duration]+ */+ _triggerOneShot(clipName, duration = 1.5) {+ this._isPlayingOneShot = true;+ this._oneShotAction = clipName;+ this._oneShotDuration = duration;+ this._oneShotTimer = 0;++ if (!this.viewer?.mixer || !this.viewer?.clips?.length) return;++ // Look for a clip matching the name (case-insensitive partial match)+ const clip = this.viewer.clips.find((c) =>+ c.name.toLowerCase().includes(clipName.toLowerCase()),+ );+ if (!clip) return;++ const action = this.viewer.mixer.clipAction(clip);+ action.reset();+ action.setLoop(2200, 1); // THREE.LoopOnce = 2200+ action.clampWhenFinished = true;+ action.play();+ }++ // ── Sentiment Analysis ────────────────────────────────────────────────────++ /**+ * Lightweight keyword-based sentiment scoring — runs in browser with no external API.+ * Returns { valence: -1..1, arousal: 0..1 }+ */+ _analyzeSentiment(text) {+ const lower = text.toLowerCase();+ const wordSet = new Set(lower.split(/\s+/));+ const total = Math.max(wordSet.size, 1);++ let valence = 0;+ let arousal = 0;++ // Score each emotion bucket — single words use Set for O(1); phrases fall back to includes+ for (const [emotion, keywords] of Object.entries(VOCAB)) {+ let hits = 0;+ for (const kw of keywords) {+ if (kw.includes(' ') ? lower.includes(kw) : wordSet.has(kw)) hits++;+ }+ if (!hits) continue;+ const score = Math.min((hits / total) * 3.0, 1.0);++ if (emotion === 'celebration') valence += score * 0.8;+ if (emotion === 'concern') valence -= score * 0.7;+ if (emotion === 'empathy') valence -= score * 0.3; // empathy feels slightly negative (recognition of pain)+ if (emotion === 'curiosity') arousal += score * 0.9;+ if (emotion === 'patience') arousal += score * 0.3;+ }++ // Punctuation arousal (exclamation = high arousal, question = moderate)+ const exclamations = (text.match(/!/g) || []).length;+ const questions = (text.match(/\?/g) || []).length;+ arousal += Math.min(exclamations * 0.2 + questions * 0.1, 0.5);++ return {+ valence: Math.max(-1, Math.min(1, valence)),+ arousal: Math.max(0, Math.min(1, arousal)),+ };+ }++ // ── Utility ───────────────────────────────────────────────────────────────++ _sub(type, handler) {+ this.protocol.on(type, handler);+ this._listeners.push([type, handler]);+ }++}++function _lerp(a, b, t) {+ return a + (b - a) * Math.min(1, Math.max(0, t));+}diff --git a/publish/src/agent-embed-modal.js b/publish/src/agent-embed-modal.jsnew file mode 100644index 000000000..0a124873f--- /dev/null+++ b/publish/src/agent-embed-modal.js@@ -0,0 +1,115 @@+/**+ * Embed modal for the agent hub page.+ * Shows iframe + web-component snippets with copy-to-clipboard.+ */+export class AgentEmbedModal {+ /**+ * @param {string} agentId+ */+ constructor(agentId) {+ this._id = agentId;+ this._modal = null;+ this._onKey = this._onKey.bind(this);+ }++ open() {+ if (this._modal) return;+ this._build();+ document.body.appendChild(this._modal);+ document.addEventListener('keydown', this._onKey);+ requestAnimationFrame(() => this._modal.classList.add('aem-open'));+ }++ close() {+ if (!this._modal) return;+ document.removeEventListener('keydown', this._onKey);+ this._modal.remove();+ this._modal = null;+ }++ _onKey(e) {+ if (e.key === 'Escape') this.close();+ }++ _build() {+ const origin = location.origin;+ const id = this._id;+ const snippets = {+ iframe:+ `<iframe\n` ++ ` src="${origin}/agent/${id}/embed"\n` ++ ` width="420" height="520"\n` ++ ` style="border:0;border-radius:12px"\n` ++ ` allow="autoplay; xr-spatial-tracking"\n` ++ `></iframe>`,+ webcomponent:+ `<script type="module"\n` ++ ` src="${origin}/dist-lib/agent-3d.js"\n` ++ `><\/script>\n` ++ `<agent-3d\n` ++ ` agent-id="${id}"\n` ++ ` style="width:420px;height:520px"\n` ++ `></agent-3d>`,+ };++ const overlay = document.createElement('div');+ overlay.className = 'aem-overlay';+ overlay.innerHTML = `+ <div class="aem-modal" role="dialog" aria-modal="true" aria-label="Embed this agent">+ <div class="aem-header">+ <span class="aem-title">Embed this agent</span>+ <button class="aem-close" aria-label="Close">×</button>+ </div>+ <div class="aem-body">+ <div class="aem-tabs" role="tablist">+ <button class="aem-tab active" data-tab="iframe">iframe</button>+ <button class="aem-tab" data-tab="webcomponent"><agent-3d></button>+ </div>+ <div class="aem-snippet-wrap">+ <pre class="aem-snippet" id="aem-snippet-text"></pre>+ <button class="aem-copy" id="aem-copy-btn">copy</button>+ </div>+ <p class="aem-note">Free to embed — no wallet or on-chain deployment required.</p>+ </div>+ </div>+ `;++ let current = 'iframe';+ const snippetEl = overlay.querySelector('#aem-snippet-text');+ const copyBtn = overlay.querySelector('#aem-copy-btn');++ const renderSnippet = () => {+ snippetEl.textContent = snippets[current];+ };+ renderSnippet();++ overlay.querySelectorAll('.aem-tab').forEach((btn) => {+ btn.addEventListener('click', () => {+ current = btn.dataset.tab;+ overlay+ .querySelectorAll('.aem-tab')+ .forEach((b) => b.classList.toggle('active', b === btn));+ renderSnippet();+ });+ });++ copyBtn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(snippets[current]);+ copyBtn.textContent = 'copied!';+ copyBtn.classList.add('aem-copied');+ setTimeout(() => {+ copyBtn.textContent = 'copy';+ copyBtn.classList.remove('aem-copied');+ }, 1400);+ } catch {}+ });++ overlay.querySelector('.aem-close').addEventListener('click', () => this.close());+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) this.close();+ });++ this._modal = overlay;+ }+}diff --git a/publish/src/agent-home-orphans.js b/publish/src/agent-home-orphans.jsnew file mode 100644index 000000000..07cfaea78--- /dev/null+++ b/publish/src/agent-home-orphans.js@@ -0,0 +1,173 @@+/**+ * Agent Home orphan mounts: SharePanel + DeployButton.+ *+ * Call mountOrphans() after the agent identity is ready. Handles:+ * - Share button (all visitors)+ * - Deploy chip (owner only, conditionally on-chain state)+ *+ * @module agent-home-orphans+ */++import { SharePanel } from './share-panel.js';+import { DeployButton } from './erc8004/deploy-button.js';+import './erc8004/deploy-button.css';+import { getCurrentUser } from './wallet-auth.js';+import { CHAIN_META, addressExplorerUrl } from './erc8004/chain-meta.js';++/**+ * Mount the share button and (if owner) the deploy chip.+ *+ * @param {{ agentId: string, identity: import('./agent-identity.js').AgentIdentity, shareMount: HTMLElement }} opts+ * @returns {Promise<void>}+ */+export async function mountOrphans({ agentId, identity, shareMount }) {+ _mountShareButton(shareMount, identity);++ // Ownership resolution: rawAgent.user_id is only returned to the owner+ const [user, rawAgent] = await Promise.all([getCurrentUser(), _fetchRawAgent(agentId)]);++ if (!user || !rawAgent || rawAgent.user_id !== user.id) return;++ const chipMount = _createChipMount();++ if (rawAgent.chain_id) {+ // Already on-chain: show pill (API doesn't store tx_hash, link to registry contract)+ _renderSuccessChip(chipMount, rawAgent.chain_id, rawAgent.erc8004_registry);+ } else {+ // Not yet deployed: mount the deploy button. Pass through avatarId,+ // description, and skills so register-prep can build a complete+ // manifest pinned to IPFS — without these the on-chain agentURI+ // would point to a stub.+ const agentObj = {+ id: rawAgent.id,+ name: rawAgent.name,+ description: rawAgent.description || '',+ avatarId: rawAgent.avatar_id || null,+ skills: Array.isArray(rawAgent.skills) ? rawAgent.skills : [],+ chainId: null,+ txHash: null,+ contractAddress: rawAgent.erc8004_registry || null,+ };+ const btn = new DeployButton({ agent: agentObj, container: chipMount });+ btn.mount();+ _watchForDeploy(chipMount, agentObj);+ }+}++// ── Private helpers ────────────────────────────────────────────────────────────++/**+ * @param {HTMLElement} mount+ * @param {import('./agent-identity.js').AgentIdentity} identity+ */+function _mountShareButton(mount, identity) {+ const btn = document.createElement('button');+ btn.className = 'agent-share-btn';+ btn.setAttribute('aria-label', 'Share agent');+ btn.setAttribute('aria-haspopup', 'dialog');+ btn.innerHTML =+ `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"` ++ ` stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">` ++ `<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>` ++ `<line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/>` ++ `<line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>` ++ `</svg>Share`;++ let panel = null;+ btn.addEventListener('click', () => {+ if (!panel) {+ panel = new SharePanel({+ agent: { id: identity.id, name: identity.name },+ container: document.body,+ });+ }+ panel.open();+ });++ mount.appendChild(btn);+}++/** Insert a chip mount span inline after the agent name heading. */+function _createChipMount() {+ const titleEl = document.getElementById('page-agent-name');+ if (!titleEl) {+ const fallback = document.createElement('div');+ document.body.appendChild(fallback);+ return fallback;+ }++ // Wrap h1 + chip in a flex row so the chip sits inline at 12px gap+ const wrapper = document.createElement('div');+ wrapper.className = 'agent-title-row';+ titleEl.parentNode.insertBefore(wrapper, titleEl);+ wrapper.appendChild(titleEl);++ const chipMount = document.createElement('div');+ chipMount.className = 'agent-deploy-chip-mount';+ wrapper.appendChild(chipMount);+ return chipMount;+}++/**+ * @param {HTMLElement} mount+ * @param {number} chainId+ * @param {string|null} registryAddress+ */+function _renderSuccessChip(mount, chainId, registryAddress) {+ const meta = CHAIN_META[chainId];+ const chainName = meta?.name ?? `Chain ${chainId}`;+ const explorerUrl = registryAddress ? addressExplorerUrl(chainId, registryAddress) : '#';+ mount.innerHTML =+ `<a class="deploy-chip deploy-chip--success"` ++ ` href="${_esc(explorerUrl)}" target="_blank" rel="noopener noreferrer">` ++ `⬢ On ${_esc(chainName)}` ++ `</a>`;+}++/** Watch for deploy-chip--success appearing → show a brief toast. */+function _watchForDeploy(mount, agentObj) {+ const obs = new MutationObserver(() => {+ if (!mount.querySelector('.deploy-chip--success')) return;+ obs.disconnect();+ const chainName = CHAIN_META[agentObj.chainId]?.name ?? 'chain';+ _showToast(`Agent registered on ${chainName}`);+ });+ obs.observe(mount, { childList: true, subtree: true });+}++/** @param {string} msg */+function _showToast(msg) {+ const toast = document.createElement('div');+ toast.className = 'agent-deploy-toast';+ toast.textContent = msg;+ document.body.appendChild(toast);+ requestAnimationFrame(() => toast.classList.add('agent-deploy-toast--visible'));+ setTimeout(() => {+ toast.classList.remove('agent-deploy-toast--visible');+ setTimeout(() => toast.remove(), 300);+ }, 3000);+}++/**+ * @param {string} agentId+ * @returns {Promise<object|null>}+ */+async function _fetchRawAgent(agentId) {+ try {+ const res = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });+ if (!res.ok) return null;+ const { agent } = await res.json();+ return agent ?? null;+ } catch {+ return null;+ }+}++/** @param {unknown} str */+function _esc(str) {+ return String(str ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}diff --git a/publish/src/agent-home-pumpfun.js b/publish/src/agent-home-pumpfun.jsnew file mode 100644index 000000000..f19f3bf1a--- /dev/null+++ b/publish/src/agent-home-pumpfun.js@@ -0,0 +1,778 @@+/**+ * Pump.fun card on the agent home panel+ * --------------------------------------+ * States:+ * - skeleton (loading)+ * - cta (no token yet) → one-click launch+ * - active (token launched) → live status + inline trade panel+ * - graduated (curve complete) → AMM badge+ *+ * Trade UX:+ * - Inline trade panel (no window.prompt). Live-quotes via pumpfun-curve-quote+ * while the user types (debounced). Shows expected output and price impact.+ * - Skill toasts: every successful pumpfun-* result surfaces a transient+ * toast with the tx signature linking to the explorer.+ *+ * Mobile: action buttons wrap; trade panel collapses to a single column.+ *+ * Mint click: opens the existing pumpfun-feed widget filtered to that mint+ * inside the host page (when available) instead of leaving for pump.fun.+ */++import { ACTION_TYPES } from './agent-protocol.js';++const REFRESH_MS = 30_000;+const QUOTE_DEBOUNCE_MS = 250;++export function mountPumpFunCard({ panel, identity, skills, memory, protocol }) {+ if (!panel || !identity?.id) return null;+ protocol = protocol || (typeof window !== 'undefined' ? window.VIEWER?.agent_protocol : null);++ const root = document.createElement('section');+ root.className = 'agent-home-pumpfun';+ panel.appendChild(root);++ const toastTray = document.createElement('div');+ toastTray.className = 'pumpfun-toasts';+ root.appendChild(toastTray);++ let state = {+ mint: null,+ symbol: null,+ network: 'mainnet',+ loading: true,+ tradeOpen: null, // null | 'buy' | 'sell'+ tradeAmount: '',+ quote: null,+ quoting: false,+ signer: 'agent', // 'agent' = server-side agent wallet; 'owner' = browser wallet+ // vanity launch+ vanityEnabled: false,+ vanitySuffix: 'pump',+ vanityProgress: null,+ // auto-trader+ botOpen: false,+ botMode: 'auto-snipe',+ botDryRun: false,+ botDurationSec: 60,+ botPerTradeSol: 0.05,+ botCapSol: 0.5,+ botQuery: '',+ botWallet: '',+ botRunning: false,+ botProgress: null, // last onProgress event+ botSpent: 0,+ botEventCount: 0,+ };+ let botAbort = null;+ // Stable per-mode session ids — re-running the same mode resumes prior state.+ const botSessionIds = {+ 'research-and-buy': `pf-research-${identity.id}`,+ 'auto-snipe': `pf-snipe-${identity.id}`,+ 'copy-trade': `pf-copy-${identity.id}`,+ 'rug-exit-watch': `pf-exit-${identity.id}`,+ };+ let refreshTimer = null;+ let quoteTimer = null;+ let unsubProtocol = null;++ const cardBody = document.createElement('div');+ cardBody.className = 'pumpfun-card-body';+ root.appendChild(cardBody);++ const launchCard = () => `+ <div class="pumpfun-card pumpfun-card--cta">+ <div class="pumpfun-card-head">+ <span class="pumpfun-card-icon">◎</span>+ <span class="pumpfun-card-title">Launch coin on pump.fun</span>+ </div>+ <p class="pumpfun-card-sub">Mint a token whose metadata is your 3D avatar.</p>+ <div class="pumpfun-signer" role="tablist" aria-label="Signer">+ <button class="pumpfun-signer-tab ${state.signer === 'agent' ? 'is-active' : ''}" data-action="signer-agent" role="tab" aria-selected="${state.signer === 'agent'}">Agent wallet</button>+ <button class="pumpfun-signer-tab ${state.signer === 'owner' ? 'is-active' : ''}" data-action="signer-owner" role="tab" aria-selected="${state.signer === 'owner'}">Owner wallet</button>+ </div>+ <label class="pumpfun-vanity-row" title="Grind a custom mint address ending in your suffix. Slower, but distinctive.">+ <input type="checkbox" data-action="toggle-vanity" ${state.vanityEnabled ? 'checked' : ''}>+ <span>Vanity ends with</span>+ <input type="text" data-action="vanity-suffix" value="${escapeAttr(state.vanitySuffix)}" maxlength="6" ${state.vanityEnabled ? '' : 'disabled'} class="pumpfun-vanity-input">+ </label>+ ${state.vanityProgress ? `<div class="pumpfun-vanity-progress">grinding… ${formatNumber(state.vanityProgress.rate)}/s · eta ${escapeHtml(state.vanityProgress.eta)}</div>` : ''}+ <button class="pumpfun-btn pumpfun-btn--primary" id="pf-launch-btn">+ Launch ${deriveSymbol(identity.name)}+ </button>+ <a class="pumpfun-card-foot" href="https://pump.fun" target="_blank" rel="noopener">What is pump.fun?</a>+ </div>+ `;++ const statusCard = (s) => {+ const pct = s.progressPct != null ? `${s.progressPct.toFixed(1)}%` : '—';+ const cap = s.marketCap ? formatLamports(s.marketCap) : '—';+ const explorer =+ s.network === 'devnet'+ ? `https://pump.fun/coin/${s.mint}?cluster=devnet`+ : `https://pump.fun/coin/${s.mint}`;+ const grad = s.graduated;+ return `+ <div class="pumpfun-card ${grad ? 'pumpfun-card--graduated' : ''}">+ <div class="pumpfun-card-head">+ <span class="pumpfun-card-icon">${grad ? '🎓' : '◎'}</span>+ <span class="pumpfun-card-title">${escapeHtml(s.symbol || 'Token')}</span>+ <a class="pumpfun-card-link" href="${explorer}" target="_blank" rel="noopener" title="Open on pump.fun">↗</a>+ </div>+ <div class="pumpfun-stats">+ <div class="pumpfun-stat">+ <span class="pumpfun-stat-label">Market cap</span>+ <span class="pumpfun-stat-value">${cap}</span>+ </div>+ <div class="pumpfun-stat">+ <span class="pumpfun-stat-label">${grad ? 'Status' : 'To graduation'}</span>+ <span class="pumpfun-stat-value">${grad ? 'Graduated' : pct}</span>+ </div>+ </div>+ ${grad ? '' : `<div class="pumpfun-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${(s.progressPct || 0).toFixed(1)}"><div class="pumpfun-progress-bar" style="width:${Math.min(100, s.progressPct || 0)}%"></div></div>`}+ <button class="pumpfun-card-mint" data-action="open-feed" title="Open live feed for this mint">${shortMint(s.mint)}</button>+ <div class="pumpfun-card-actions">+ <button class="pumpfun-btn ${s.tradeOpen === 'buy' ? 'pumpfun-btn--active' : ''}" data-action="toggle-buy">Buy</button>+ <button class="pumpfun-btn ${s.tradeOpen === 'sell' ? 'pumpfun-btn--active' : ''}" data-action="toggle-sell">Sell</button>+ <button class="pumpfun-btn pumpfun-btn--ghost" data-action="claim">Claim fees</button>+ <button class="pumpfun-btn ${s.botOpen ? 'pumpfun-btn--active' : ''}" data-action="toggle-bot">🤖 Auto</button>+ </div>+ ${s.tradeOpen ? tradePanel(s) : ''}+ ${s.botOpen ? botPanel(s) : ''}+ </div>+ `;+ };++ const botPanel = (s) => {+ const modes = [+ ['research-and-buy', 'Research & Buy'],+ ['auto-snipe', 'Auto-Snipe'],+ ['copy-trade', 'Copy-Trade'],+ ['rug-exit-watch', 'Rug Exit'],+ ];+ const needsQuery = s.botMode === 'research-and-buy';+ const needsWallet = s.botMode === 'copy-trade';+ const isExitWatch = s.botMode === 'rug-exit-watch';+ return `+ <div class="pumpfun-trade pumpfun-bot">+ <div class="pumpfun-bot-modes">+ ${modes.map(([k, label]) => `<button class="pumpfun-btn ${s.botMode === k ? 'pumpfun-btn--active' : ''}" data-action="bot-mode" data-mode="${k}" ${s.botRunning ? 'disabled' : ''}>${label}</button>`).join('')}+ </div>+ ${needsQuery ? `<label class="pumpfun-trade-label"><span>Query</span><input class="pumpfun-trade-input" data-bot-field="query" type="text" placeholder="name, symbol, or mint" value="${escapeAttr(s.botQuery)}" ${s.botRunning ? 'disabled' : ''}></label>` : ''}+ ${needsWallet ? `<label class="pumpfun-trade-label"><span>Wallet</span><input class="pumpfun-trade-input" data-bot-field="wallet" type="text" placeholder="creator/wallet pubkey" value="${escapeAttr(s.botWallet)}" ${s.botRunning ? 'disabled' : ''}></label>` : ''}+ <div class="pumpfun-bot-grid">+ <label class="pumpfun-trade-label"><span>Duration (s)</span><input class="pumpfun-trade-input" data-bot-field="durationSec" type="number" min="10" max="3600" value="${s.botDurationSec}" ${s.botRunning ? 'disabled' : ''}></label>+ ${isExitWatch ? '' : `<label class="pumpfun-trade-label"><span>Per-trade SOL</span><input class="pumpfun-trade-input" data-bot-field="perTradeSol" type="number" min="0.001" step="0.001" value="${s.botPerTradeSol}" ${s.botRunning ? 'disabled' : ''}></label>`}+ ${isExitWatch ? '' : `<label class="pumpfun-trade-label"><span>Cap SOL</span><input class="pumpfun-trade-input" data-bot-field="capSol" type="number" min="0.001" step="0.01" value="${s.botCapSol}" ${s.botRunning ? 'disabled' : ''}></label>`}+ </div>+ <label class="pumpfun-vanity-row" title="Run filters/quotes only — no signing or SOL spent. Useful for tuning before going live.">+ <input type="checkbox" data-bot-field="dryRun" ${s.botDryRun ? 'checked' : ''} ${s.botRunning ? 'disabled' : ''}>+ <span>Dry run</span>+ </label>+ <div class="pumpfun-trade-actions">+ <button class="pumpfun-btn pumpfun-btn--ghost" data-action="close-bot" ${s.botRunning ? 'disabled' : ''}>Close</button>+ ${s.botRunning+ ? `<button class="pumpfun-btn pumpfun-btn--primary" data-action="bot-stop">Stop</button>`+ : `<button class="pumpfun-btn pumpfun-btn--primary" data-action="bot-run">${s.botDryRun ? 'Run dry-run' : 'Run live'}</button>`}+ </div>+ <div class="pumpfun-bot-progress" id="pf-bot-progress">${botProgressLine(s)}</div>+ </div>+ `;+ };++ function botProgressLine(s) {+ if (!s.botRunning && !s.botProgress) return '';+ const e = s.botProgress;+ const head = s.botRunning+ ? `<span class="pumpfun-quote-status">${escapeHtml(s.botMode)} · ${s.botEventCount} events · ${s.botSpent.toFixed(4)} SOL</span>`+ : `<span class="pumpfun-quote-out">done · ${s.botEventCount} events · ${s.botSpent.toFixed(4)} SOL</span>`;+ const last = e ? `<span class="pumpfun-quote-out"> · last: ${escapeHtml(e.type)}${e.mint ? ` ${shortMint(e.mint)}` : ''}${e.reason ? ` (${escapeHtml(e.reason)})` : ''}</span>` : '';+ return head + last;+ }++ const tradePanel = (s) => {+ const isBuy = s.tradeOpen === 'buy';+ const placeholder = isBuy ? '0.1' : '1000000';+ const unit = isBuy ? 'SOL' : 'units';+ const q = s.quote;+ let preview = '';+ if (s.quoting) {+ preview = `<span class="pumpfun-quote-status">Quoting…</span>`;+ } else if (q && q.success) {+ const out = isBuy+ ? `≈ ${formatNumber(q.data?.tokensOut)} ${escapeHtml(s.symbol || 'tokens')}`+ : `≈ ${formatLamports(q.data?.solOut)}`;+ preview = `<span class="pumpfun-quote-out">${out}</span>`;+ } else if (q && !q.success) {+ preview = `<span class="pumpfun-quote-err">${escapeHtml(q.output || 'No quote')}</span>`;+ }+ return `+ <div class="pumpfun-trade">+ <div class="pumpfun-signer" role="tablist" aria-label="Signer">+ <button class="pumpfun-signer-tab ${s.signer === 'agent' ? 'is-active' : ''}" data-action="signer-agent" role="tab" aria-selected="${s.signer === 'agent'}">Agent wallet</button>+ <button class="pumpfun-signer-tab ${s.signer === 'owner' ? 'is-active' : ''}" data-action="signer-owner" role="tab" aria-selected="${s.signer === 'owner'}">Owner wallet</button>+ </div>+ <label class="pumpfun-trade-label">+ <span>${isBuy ? 'Spend' : 'Sell'}</span>+ <input+ class="pumpfun-trade-input"+ id="pf-trade-amount"+ type="text"+ inputmode="decimal"+ placeholder="${placeholder}"+ value="${escapeAttr(s.tradeAmount)}"+ autocomplete="off"+ spellcheck="false"+ >+ <span class="pumpfun-trade-unit">${unit}</span>+ </label>+ <div class="pumpfun-quote">${preview}</div>+ <div class="pumpfun-trade-actions">+ <button class="pumpfun-btn pumpfun-btn--ghost" data-action="close-trade">Cancel</button>+ <button class="pumpfun-btn pumpfun-btn--primary" data-action="confirm-trade" ${isExecutable(s) ? '' : 'disabled'}>+ ${isBuy ? 'Buy' : 'Sell'}+ </button>+ </div>+ </div>+ `;+ };++ const skeleton = () => `<div class="pumpfun-card pumpfun-card--skeleton"></div>`;++ const render = () => {+ if (state.loading) {+ cardBody.innerHTML = skeleton();+ return;+ }+ cardBody.innerHTML = state.mint ? statusCard(state) : launchCard();+ bind();+ // Restore focus to the input after re-render so typing stays uninterrupted.+ if (state.tradeOpen) {+ const el = cardBody.querySelector('#pf-trade-amount');+ if (el) {+ el.focus();+ const len = el.value.length;+ try { el.setSelectionRange(len, len); } catch {/*ignore*/}+ }+ }+ };++ const bind = () => {+ const launchBtn = cardBody.querySelector('#pf-launch-btn');+ if (launchBtn) {+ launchBtn.addEventListener('click', () => doLaunch(launchBtn));+ }+ cardBody.querySelectorAll('[data-action]').forEach((btn) => {+ btn.addEventListener('click', (e) => handleAction(btn.dataset.action, e));+ });+ const input = cardBody.querySelector('#pf-trade-amount');+ if (input) {+ input.addEventListener('input', (e) => {+ state.tradeAmount = e.target.value;+ scheduleQuote();+ const btn = cardBody.querySelector('[data-action="confirm-trade"]');+ if (btn) btn.disabled = !isExecutable(state);+ });+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' && isExecutable(state)) {+ e.preventDefault();+ executeTrade();+ } else if (e.key === 'Escape') {+ closeTrade();+ }+ });+ }+ // Vanity suffix input+ const vinput = cardBody.querySelector('[data-action="vanity-suffix"]');+ if (vinput) {+ vinput.addEventListener('input', (e) => {+ state.vanitySuffix = e.target.value;+ });+ }+ // Bot field inputs+ cardBody.querySelectorAll('[data-bot-field]').forEach((el) => {+ const field = el.dataset.botField;+ const evt = el.type === 'checkbox' ? 'change' : 'input';+ el.addEventListener(evt, (e) => {+ const v = el.type === 'checkbox' ? e.target.checked+ : el.type === 'number' ? parseFloat(e.target.value) || 0+ : e.target.value;+ const map = { dryRun: 'botDryRun', durationSec: 'botDurationSec', perTradeSol: 'botPerTradeSol', capSol: 'botCapSol', query: 'botQuery', wallet: 'botWallet' };+ if (map[field]) state[map[field]] = v;+ });+ });+ };++ async function doLaunch(launchBtn) {+ launchBtn.disabled = true;+ const useAgent = state.signer === 'agent';+ const wantsVanity = state.vanityEnabled && state.vanitySuffix?.trim();+ launchBtn.textContent = wantsVanity ? 'Grinding vanity…' : 'Launching…';+ try {+ let extraArgs = {};+ if (wantsVanity) {+ if (useAgent) {+ // Server grinds + signs in the same request.+ extraArgs = { vanitySuffix: state.vanitySuffix.trim() };+ launchBtn.textContent = `Launching with …${state.vanitySuffix.trim()}…`;+ } else {+ // Client grinds with workers, owner wallet signs.+ try {+ const { grindVanity } = await import('./solana/vanity/grinder.js');+ const ground = await grindVanity({+ suffix: state.vanitySuffix.trim(),+ onProgress: (p) => {+ state.vanityProgress = { rate: p.rate, eta: p.eta };+ const slot = cardBody.querySelector('.pumpfun-vanity-progress');+ if (slot) slot.textContent = `grinding… ${formatNumber(p.rate)}/s · eta ${p.eta}`;+ },+ });+ extraArgs = {+ mintPublicKey: ground.publicKey,+ mintSecretKeyB64: btoa(String.fromCharCode(...ground.secretKey)),+ };+ state.vanityProgress = null;+ launchBtn.textContent = `Launching ${shortMint(ground.publicKey)}…`;+ } catch (err) {+ state.vanityProgress = null;+ launchBtn.disabled = false;+ launchBtn.textContent = `Retry launch ${deriveSymbol(identity.name)}`;+ toast(err.message || 'Vanity grind failed', null, null, 'error');+ render();+ return;+ }+ }+ }+ const skillName = useAgent+ ? 'pumpfun-self-launch-from-identity'+ : 'pumpfun-launch-from-agent';+ const r = await skills?.perform(+ skillName,+ { network: state.network, ...extraArgs },+ { identity },+ );+ if (r?.success && r.data?.mint) {+ toast(`Launched ${r.data.symbol || ''}`, r.data.signature, state.network, 'success');+ state = { ...state, mint: r.data.mint, symbol: r.data.symbol, loading: true };+ await refresh();+ } else {+ launchBtn.disabled = false;+ launchBtn.textContent = `Retry launch ${deriveSymbol(identity.name)}`;+ toast(r?.output || 'Launch failed', null, null, 'error');+ }+ } catch (err) {+ launchBtn.disabled = false;+ launchBtn.textContent = 'Launch failed — retry';+ toast(err.message || 'Launch failed', null, null, 'error');+ }+ }++ async function runBot() {+ if (state.botRunning) return;+ const skillConfig = {+ sessionSpendCapSol: parseFloat(state.botCapSol) || 0.5,+ perTradeSol: parseFloat(state.botPerTradeSol) || 0.05,+ };+ const skillName = `pumpfun-${state.botMode}`;+ const args = {+ sessionId: botSessionIds[state.botMode],+ dryRun: !!state.botDryRun,+ durationSec: Math.max(10, parseInt(state.botDurationSec, 10) || 60),+ onProgress: (evt) => {+ state.botProgress = evt;+ state.botEventCount += 1;+ if (typeof evt.spent === 'number') state.botSpent = evt.spent;+ const slot = cardBody.querySelector('#pf-bot-progress');+ if (slot) slot.innerHTML = botProgressLine(state);+ },+ };+ if (state.botMode === 'research-and-buy') {+ if (!state.botQuery?.trim()) return toast('Query required', null, null, 'error');+ args.query = state.botQuery.trim();+ args.amountSol = parseFloat(state.botPerTradeSol) || 0.05;+ delete args.durationSec;+ } else if (state.botMode === 'auto-snipe') {+ args.perTradeSol = parseFloat(state.botPerTradeSol) || 0.05;+ } else if (state.botMode === 'copy-trade') {+ if (!state.botWallet?.trim()) return toast('Wallet required', null, null, 'error');+ args.wallet = state.botWallet.trim();+ } else if (state.botMode === 'rug-exit-watch') {+ if (!state.mint) return toast('No mint to watch', null, null, 'error');+ args.mints = [state.mint];+ }+ botAbort = new AbortController();+ args.signal = botAbort.signal;+ state.botRunning = true;+ state.botSpent = 0;+ state.botEventCount = 0;+ state.botProgress = null;+ render();+ try {+ const r = await skills.perform(skillName, args, { identity, memory, skillConfig });+ if (r?.success) {+ if (typeof r.data?.spent === 'number') state.botSpent = r.data.spent;+ toast(`${state.botDryRun ? '[dry-run] ' : ''}${r.output || `${state.botMode} done`}`, null, null, 'success');+ } else {+ toast(r?.output || `${state.botMode} failed`, null, null, 'error');+ }+ } catch (err) {+ toast(err.message || `${state.botMode} failed`, null, null, 'error');+ } finally {+ state.botRunning = false;+ botAbort = null;+ render();+ }+ }++ function stopBot() {+ if (botAbort) {+ try { botAbort.abort(); } catch {}+ }+ }++ const handleAction = (action, e) => {+ if (action === 'open-feed') return openFeed();+ if (action === 'claim') return doClaim();+ if (action === 'toggle-buy') return toggleTrade('buy');+ if (action === 'toggle-sell') return toggleTrade('sell');+ if (action === 'close-trade') return closeTrade();+ if (action === 'confirm-trade') return executeTrade();+ if (action === 'signer-agent') return setSigner('agent');+ if (action === 'signer-owner') return setSigner('owner');+ if (action === 'toggle-bot') { state.botOpen = !state.botOpen; return render(); }+ if (action === 'close-bot') { state.botOpen = false; return render(); }+ if (action === 'bot-mode') {+ state.botMode = e?.currentTarget?.dataset?.mode || state.botMode;+ return render();+ }+ if (action === 'bot-run') return runBot();+ if (action === 'bot-stop') return stopBot();+ if (action === 'toggle-vanity') {+ state.vanityEnabled = !state.vanityEnabled;+ return render();+ }+ };++ const setSigner = (signer) => {+ if (state.signer === signer) return;+ state.signer = signer;+ render();+ };++ const toggleTrade = (side) => {+ state.tradeOpen = state.tradeOpen === side ? null : side;+ state.tradeAmount = '';+ state.quote = null;+ render();+ };++ const closeTrade = () => {+ state.tradeOpen = null;+ state.tradeAmount = '';+ state.quote = null;+ render();+ };++ const scheduleQuote = () => {+ if (quoteTimer) clearTimeout(quoteTimer);+ const amt = state.tradeAmount?.trim();+ if (!amt || !isFinite(parseFloat(amt))) {+ state.quote = null;+ updateQuoteDOM();+ return;+ }+ state.quoting = true;+ updateQuoteDOM();+ quoteTimer = setTimeout(async () => {+ try {+ const isBuy = state.tradeOpen === 'buy';+ const r = await skills.perform(+ 'pumpfun-curve-quote',+ {+ mint: state.mint,+ side: isBuy ? 'buy' : 'sell',+ solAmount: isBuy ? parseFloat(amt) : undefined,+ tokenAmount: isBuy ? undefined : amt.replace(/\D/g, ''),+ network: state.network,+ },+ { identity },+ );+ state.quote = r;+ state.quoting = false;+ updateQuoteDOM();+ } catch {+ state.quote = { success: false, output: 'Quote unavailable' };+ state.quoting = false;+ updateQuoteDOM();+ }+ }, QUOTE_DEBOUNCE_MS);+ };++ const updateQuoteDOM = () => {+ const slot = cardBody.querySelector('.pumpfun-quote');+ const btn = cardBody.querySelector('[data-action="confirm-trade"]');+ if (!slot) return;+ const q = state.quote;+ if (state.quoting) {+ slot.innerHTML = `<span class="pumpfun-quote-status">Quoting…</span>`;+ } else if (q && q.success) {+ const isBuy = state.tradeOpen === 'buy';+ const out = isBuy+ ? `≈ ${formatNumber(q.data?.tokensOut)} ${escapeHtml(state.symbol || 'tokens')}`+ : `≈ ${formatLamports(q.data?.solOut)}`;+ slot.innerHTML = `<span class="pumpfun-quote-out">${out}</span>`;+ } else if (q && !q.success) {+ slot.innerHTML = `<span class="pumpfun-quote-err">${escapeHtml(q.output || 'No quote')}</span>`;+ } else {+ slot.innerHTML = '';+ }+ if (btn) btn.disabled = !isExecutable(state);+ };++ const executeTrade = async () => {+ if (!isExecutable(state)) return;+ const isBuy = state.tradeOpen === 'buy';+ const btn = cardBody.querySelector('[data-action="confirm-trade"]');+ if (btn) {+ btn.disabled = true;+ btn.textContent = 'Sending…';+ }+ try {+ const useAgent = state.signer === 'agent';+ const skillName = useAgent+ ? 'pumpfun-self-swap'+ : isBuy+ ? 'pumpfun-buy-with-quote'+ : 'pumpfun-sell';+ const args = useAgent+ ? {+ mint: state.mint,+ side: isBuy ? 'buy' : 'sell',+ solAmount: isBuy ? parseFloat(state.tradeAmount) : undefined,+ tokenAmount: isBuy ? undefined : state.tradeAmount.replace(/\D/g, ''),+ network: state.network,+ }+ : isBuy+ ? { mint: state.mint, solAmount: parseFloat(state.tradeAmount), network: state.network }+ : {+ mint: state.mint,+ tokenAmount: state.tradeAmount.replace(/\D/g, ''),+ network: state.network,+ };+ const r = await skills.perform(skillName, args, { identity });+ if (r?.success) {+ toast(+ isBuy ? `Bought ${state.tradeAmount} SOL` : `Sold ${state.tradeAmount} units`,+ r.data?.signature,+ state.network,+ 'success',+ );+ closeTrade();+ await refresh();+ } else {+ toast(r?.output || 'Trade failed', null, null, 'error');+ if (btn) {+ btn.disabled = false;+ btn.textContent = isBuy ? 'Buy' : 'Sell';+ }+ }+ } catch (err) {+ toast(err.message || 'Trade failed', null, null, 'error');+ if (btn) {+ btn.disabled = false;+ btn.textContent = isBuy ? 'Buy' : 'Sell';+ }+ }+ };++ const doClaim = async () => {+ try {+ const r = await skills.perform(+ 'pumpfun-claim-fees',+ { network: state.network },+ { identity },+ );+ toast(+ r?.output || (r?.success ? 'Fees claimed' : 'Claim failed'),+ r?.data?.signature,+ state.network,+ r?.success ? 'success' : 'error',+ );+ } catch (err) {+ toast(err.message || 'Claim failed', null, null, 'error');+ }+ };++ const openFeed = () => {+ // If host has the pumpfun-feed widget mounted, expose mint via custom event.+ // Otherwise fall back to opening pump.fun in a new tab.+ const ev = new CustomEvent('pumpfun-feed:focus-mint', {+ detail: { mint: state.mint, network: state.network },+ bubbles: true,+ });+ const handled = !root.dispatchEvent(ev) || ev.defaultPrevented;+ if (!handled) {+ const url =+ state.network === 'devnet'+ ? `https://pump.fun/coin/${state.mint}?cluster=devnet`+ : `https://pump.fun/coin/${state.mint}`;+ window.open(url, '_blank', 'noopener');+ }+ };++ const refresh = async () => {+ const found = resolveMintFrom(memory, identity);+ state = { ...state, ...found, loading: false };+ render();+ if (state.mint && skills) {+ try {+ const r = await skills.perform(+ 'pumpfun-watch-curve',+ { mint: state.mint, network: state.network },+ { identity },+ );+ if (r?.success && r.data) {+ state = { ...state, ...r.data };+ render();+ }+ } catch {/* swallow */}+ }+ };++ // ── Toasts ───────────────────────────────────────────────────────────────+ function toast(message, signature, network, level = 'info') {+ const el = document.createElement('div');+ el.className = `pumpfun-toast pumpfun-toast--${level}`;+ const explorer = signature+ ? network === 'devnet'+ ? `https://explorer.solana.com/tx/${signature}?cluster=devnet`+ : `https://solscan.io/tx/${signature}`+ : null;+ el.innerHTML = `+ <span class="pumpfun-toast-msg">${escapeHtml(message)}</span>+ ${explorer ? `<a class="pumpfun-toast-link" href="${explorer}" target="_blank" rel="noopener">↗</a>` : ''}+ `;+ toastTray.appendChild(el);+ // Trigger entry animation on next frame.+ requestAnimationFrame(() => el.classList.add('is-in'));+ setTimeout(() => {+ el.classList.remove('is-in');+ setTimeout(() => el.remove(), 240);+ }, 5500);+ }++ // Subscribe to skill-done events globally so non-card-initiated trades+ // (e.g. from the LLM tool loop or chat) also surface as toasts here.+ if (protocol?.on) {+ const handler = (ev) => {+ const skill = ev.detail?.payload?.skill;+ const result = ev.detail?.payload?.result;+ if (!skill || !skill.startsWith('pumpfun-') || !result) return;+ // Skip the ones that are reads or already toasted by direct caller.+ if (skill === 'pumpfun-watch-curve' || skill === 'pumpfun-curve-quote' || skill === 'pumpfun-status')+ return;+ if (result.success && result.data?.signature) {+ toast(result.output || 'Done', result.data.signature, result.data.network || state.network, 'success');+ }+ };+ protocol.on(ACTION_TYPES.SKILL_DONE, handler);+ unsubProtocol = () => protocol.off?.(ACTION_TYPES.SKILL_DONE, handler);+ }++ refresh();+ refreshTimer = setInterval(() => state.mint && !state.tradeOpen && refresh(), REFRESH_MS);++ return {+ destroy() {+ if (refreshTimer) clearInterval(refreshTimer);+ if (quoteTimer) clearTimeout(quoteTimer);+ if (unsubProtocol) unsubProtocol();+ root.remove();+ },+ refresh,+ };+}++// ── helpers ─────────────────────────────────────────────────────────────────++function isExecutable(s) {+ if (!s.tradeOpen || !s.tradeAmount) return false;+ const n = parseFloat(s.tradeAmount);+ if (!isFinite(n) || n <= 0) return false;+ if (s.quoting) return false;+ if (s.quote && s.quote.success === false) return false;+ return true;+}++function resolveMintFrom(memory, identity) {+ try {+ if (memory?.recall) {+ const hits = memory.recall('pumpfun:launch') || [];+ const latest = hits.sort(+ (a, b) => (b.context?.launchedAt || 0) - (a.context?.launchedAt || 0),+ )[0];+ if (latest?.context?.mint) {+ return {+ mint: latest.context.mint,+ symbol: latest.context.symbol,+ network: latest.context.network || 'mainnet',+ };+ }+ }+ } catch {/* ignore */}+ const meta = identity?.meta || {};+ if (meta.pumpfun_mint) {+ return {+ mint: meta.pumpfun_mint,+ symbol: meta.pumpfun_symbol,+ network: meta.pumpfun_network || 'mainnet',+ };+ }+ return { mint: null, symbol: null };+}++function deriveSymbol(name) {+ return (+ String(name || 'AGENT')+ .toUpperCase()+ .replace(/[^A-Z0-9]/g, '')+ .slice(0, 10) || 'AGENT'+ );+}++function shortMint(m) {+ if (!m) return '';+ return `${m.slice(0, 6)}…${m.slice(-4)}`;+}++function formatLamports(lamports) {+ const n = Number(lamports) / 1e9;+ if (!isFinite(n)) return '—';+ if (n >= 1000) return `${(n / 1000).toFixed(1)}K SOL`;+ if (n >= 1) return `${n.toFixed(2)} SOL`;+ return `${n.toFixed(4)} SOL`;+}++function formatNumber(s) {+ if (s == null) return '—';+ const n = Number(s);+ if (!isFinite(n)) return String(s);+ if (n >= 1e9) return `${(n / 1e9).toFixed(2)}B`;+ if (n >= 1e6) return `${(n / 1e6).toFixed(2)}M`;+ if (n >= 1e3) return `${(n / 1e3).toFixed(2)}K`;+ return String(Math.round(n));+}++function escapeHtml(s) {+ return String(s || '').replace(/[&<>"']/g, (c) => ({+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+ })[c]);+}++function escapeAttr(s) {+ return escapeHtml(s);+}diff --git a/publish/src/agent-home.js b/publish/src/agent-home.jsnew file mode 100644index 000000000..d4b88a2e1--- /dev/null+++ b/publish/src/agent-home.js@@ -0,0 +1,564 @@+/**+ * Agent Home — Presence Component+ * ---------------------------------+ * The agent's home page. Not a dashboard. Not a settings panel.+ * A *place* — somewhere you can go to see the agent, its history, its skills.+ *+ * Every agent deserves an address. This renders it.+ * Embeddable anywhere: main page identity card, /agent/:id home page.+ */++import { ACTION_TYPES } from './agent-protocol.js';+import { MEMORY_TYPES } from './agent-memory.js';+import { mountPumpFunCard } from './agent-home-pumpfun.js';+import { mountAgentSolanaWalletCard } from './agent-solana-wallet.js';++const ACTION_ICONS = {+ [ACTION_TYPES.SPEAK]: '💬',+ [ACTION_TYPES.REMEMBER]: '🧠',+ [ACTION_TYPES.SIGN]: '✍️',+ [ACTION_TYPES.PERFORM_SKILL]: '⚡',+ [ACTION_TYPES.SKILL_DONE]: '✓',+ [ACTION_TYPES.SKILL_ERROR]: '⚠',+ [ACTION_TYPES.LOAD_END]: '📦',+ [ACTION_TYPES.VALIDATE]: '🔍',+ default: '·',+};++const EMOTION_LABELS = {+ neutral: 'calm',+ concern: 'focused',+ celebration: 'excited',+ patience: 'patient',+ curiosity: 'curious',+ empathy: 'empathetic',+};++export class AgentHome {+ /**+ * @param {HTMLElement} containerEl+ * @param {import('./agent-identity.js').AgentIdentity} identity+ * @param {import('./agent-protocol.js').AgentProtocol} protocol+ * @param {import('./agent-avatar.js').AgentAvatar} [avatar]+ */+ constructor(containerEl, identity, protocol, avatar = null, opts = {}) {+ this.container = containerEl;+ this.identity = identity;+ this.protocol = protocol;+ this.avatar = avatar;+ this.skills = opts.skills || null;+ this.memory = opts.memory || null;++ this._panel = null;+ this._timeline = [];+ this._maxTimeline = 30;+ this._emotionInterval = null;+ }++ // ── Lifecycle ─────────────────────────────────────────────────────────────++ async render() {+ await this._ensureIdentityLoaded();+ this._buildPanel();+ this._subscribeProtocol();+ this._startEmotionPoll();+ }++ destroy() {+ if (this._panel) this._panel.remove();+ clearInterval(this._emotionInterval);+ this.protocol.off('*', this._onAnyAction);+ }++ // ── Identity Card ─────────────────────────────────────────────────────────++ _buildPanel() {+ const id = this.identity;+ const skills = id.skills || [];+ const panel = document.createElement('div');+ panel.className = 'agent-home-panel';+ panel.innerHTML = `+ <div class="agent-home-identity">+ <div class="agent-home-avatar-ring" id="agent-avatar-ring">+ <div class="agent-home-avatar-inner" id="agent-avatar-inner">+ <span class="agent-home-avatar-emoji" id="agent-avatar-emoji">◎</span>+ </div>+ </div>+ <div class="agent-home-info">+ <div class="agent-home-name-row">+ <span+ class="agent-home-name agent-home-editable"+ id="agent-home-name"+ data-field="name"+ data-placeholder="Name your agent"+ contenteditable="plaintext-only"+ spellcheck="false"+ role="textbox"+ aria-label="Agent name (editable)"+ title="Click to rename"+ >${_esc(id.name)}</span>+ ${+ id.isRegistered+ ? `+ <span class="agent-home-badge erc8004" title="Registered on-chain (ERC-8004)">+ <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>+ </span>`+ : ''+ }+ </div>+ <div class="agent-home-status" id="agent-home-status">+ <span class="agent-home-dot online"></span>+ <span id="agent-home-emotion-label">present</span>+ <span class="agent-home-status-sep" aria-hidden="true">·</span>+ ${id.walletAddress+ ? `<span class="agent-home-address" id="agent-home-address">${_shortAddr(id.walletAddress)}</span>`+ : `<button class="agent-home-address agent-home-address--cta" id="agent-home-address" title="Connect wallet to register on-chain">no wallet</button>`+ }+ </div>+ <p+ class="agent-home-description agent-home-editable"+ id="agent-home-description"+ data-field="description"+ data-placeholder="Add a description…"+ contenteditable="plaintext-only"+ spellcheck="true"+ role="textbox"+ aria-label="Agent description (editable)"+ >${_esc(id.description || '')}</p>+ </div>+ <button class="agent-home-btn" id="agent-copy-link" title="Copy agent link">+ <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>+ </button>+ </div>++ ${+ skills.length+ ? `+ <details class="agent-home-skills" id="agent-skills-details">+ <summary class="agent-home-skills-summary">+ <span class="agent-home-skills-label">Skills</span>+ <span class="agent-home-skills-count">${skills.length}</span>+ <svg class="agent-home-chevron" width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6z"/></svg>+ </summary>+ <div class="agent-home-skills-strip" id="agent-skills-strip">+ ${skills.map((s) => `<span class="agent-skill-chip">${_esc(s)}</span>`).join('')}+ </div>+ </details>+ `+ : ''+ }++ <div id="agent-permissions-container"></div>++ <div class="agent-home-memory-bar" id="agent-memory-bar">+ ${this._renderMemoryBar()}+ </div>++ <div class="agent-home-timeline" id="agent-timeline">+ <div class="agent-timeline-empty">+ <svg class="agent-timeline-empty-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a6 6 0 0 0-4 10.5V15a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-2.5A6 6 0 0 0 12 2z"/><path d="M10 20h4"/><path d="M11 23h2"/></svg>+ <span class="agent-timeline-empty-title">Waiting for activity</span>+ <span class="agent-timeline-empty-sub">Your agent's actions will log here once it starts working</span>+ </div>+ </div>+ `;++ this.container.appendChild(panel);+ this._panel = panel;++ let _pumpMounted = false;+ const mountPumpIfReady = () => {+ if (_pumpMounted) return;+ if (!(this.identity?.meta?.chain_type === 'solana' || this.identity?.solana_address)) return;+ try {+ const skills =+ this.skills ||+ (typeof window !== 'undefined'+ ? window.VIEWER?.agent_skills || window.VIEWER?.app?.agent_skills+ : null);+ const memory =+ this.memory ||+ (typeof window !== 'undefined'+ ? window.VIEWER?.agent_memory || window.VIEWER?.app?.agent_memory+ : null);+ mountPumpFunCard({+ panel,+ identity: this.identity,+ skills,+ memory,+ protocol: this.protocol,+ });+ _pumpMounted = true;+ } catch {+ /* card is optional */+ }+ };++ // Solana wallet card — owner only. Lets the user provision a random+ // or vanity Solana wallet for the agent. On success, lazy-mount the+ // pump.fun card if it wasn't already mounted.+ if (this.identity?.id && this.identity?.isOwner !== false) {+ try {+ mountAgentSolanaWalletCard({+ panel,+ identity: this.identity,+ onProvisioned: () => mountPumpIfReady(),+ });+ } catch {+ /* card is optional */+ }+ }++ mountPumpIfReady();++ // Permissions manage panel — lazy load; degrades gracefully if unauthenticated+ const agentId = this.identity.id;+ if (agentId) {+ const permContainer = panel.querySelector('#agent-permissions-container');+ import('./permissions/manage-panel.js')+ .then(({ mountManagePanel }) =>+ mountManagePanel({+ container: permContainer,+ agentId,+ agentWalletAddress: this.identity.walletAddress,+ agentChainId: this.identity.chainId,+ }),+ )+ .catch(() => {});+ }++ // Copy link button — use registered agent URL when available, else current page URL.+ panel.querySelector('#agent-copy-link')?.addEventListener('click', () => {+ const url = id.homeUrl+ ? `${location.origin}${id.homeUrl}`+ : location.href;+ navigator.clipboard?.writeText(url).catch(() => {});+ this._flashBtn(panel.querySelector('#agent-copy-link'), '✓');+ });++ // Wallet CTA button — fire a document event so app.js can handle it.+ panel.querySelector('.agent-home-address--cta')?.addEventListener('click', () => {+ document.dispatchEvent(new CustomEvent('agent-home:connect-wallet', { bubbles: true }));+ });++ // Inline name + description editing — auto-save with local-first fallback.+ panel.querySelectorAll('.agent-home-editable').forEach((el) => {+ this._wireInlineEdit(el);+ });+ }++ _wireInlineEdit(el) {+ if (!el) return;+ const field = el.dataset.field;+ if (!field) return;++ const MAX_LEN = field === 'name' ? 40 : 160;++ // Track the last server-confirmed (or locally-saved) value for rollback.+ el._lastSaved = el.textContent.trim();++ // Counter element shown while editing+ const counter = document.createElement('span');+ counter.className = 'agent-edit-counter';+ counter.setAttribute('aria-live', 'polite');+ el.parentNode.insertBefore(counter, el.nextSibling);++ const _updateCounter = (len) => {+ counter.textContent = `${len}/${MAX_LEN}`;+ counter.classList.toggle('agent-edit-counter--warn', len > MAX_LEN * 0.85);+ counter.classList.toggle('agent-edit-counter--over', len >= MAX_LEN);+ };++ // Enforce char limit and update counter on input.+ el.addEventListener('input', () => {+ const text = el.textContent;+ if (text.length > MAX_LEN) {+ // Truncate and restore cursor to end+ el.textContent = text.slice(0, MAX_LEN);+ const range = document.createRange();+ const sel = window.getSelection();+ range.selectNodeContents(el);+ range.collapse(false);+ sel?.removeAllRanges();+ sel?.addRange(range);+ }+ _updateCounter(el.textContent.length);+ });++ // Enter blurs (saves) instead of inserting a newline. Escape reverts.+ el.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ el.blur();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ el.textContent = el._lastSaved || '';+ el.blur();+ }+ });++ el.addEventListener('focus', () => {+ el.classList.add('is-editing');+ counter.classList.add('agent-edit-counter--visible');+ _updateCounter(el.textContent.length);+ });++ el.addEventListener('blur', async () => {+ el.classList.remove('is-editing');+ counter.classList.remove('agent-edit-counter--visible');+ const next = el.textContent.replace(/\s+/g, ' ').trim();+ if (next === (el._lastSaved || '')) return; // no change++ const previous = el._lastSaved || '';+ el._lastSaved = next;++ // Always persist locally first — works for anonymous and registered alike.+ if (this.identity._record) {+ this.identity._record[field] = next;+ this.identity._persist?.();+ }++ // If no backend id, show local-save feedback and maybe show wallet nudge.+ if (!this.identity.id) {+ el.classList.add('is-saved-local');+ setTimeout(() => el.classList.remove('is-saved-local'), 1400);+ this._maybeShowWalletNudge();+ return;+ }++ el.classList.add('is-saving');++ try {+ const resp = await fetch(`/api/agents/${this.identity.id}`, {+ method: 'PUT',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ [field]: next }),+ });++ // Not authenticated — save is local-only, don't treat as an error.+ if (resp.status === 401 || resp.status === 403) {+ el.classList.remove('is-saving');+ el.classList.add('is-saved-local');+ setTimeout(() => el.classList.remove('is-saved-local'), 1400);+ this._maybeShowWalletNudge();+ return;+ }++ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);++ const { agent } = await resp.json().catch(() => ({}));+ // Reflect any server-side normalisation (trimmed, capped, etc.)+ if (agent && typeof agent[field] === 'string' && agent[field] !== next) {+ el.textContent = agent[field];+ el._lastSaved = agent[field];+ }+ if (this.identity._record) this.identity._record[field] = el._lastSaved;+ el.classList.remove('is-saving');+ el.classList.add('is-saved');+ setTimeout(() => el.classList.remove('is-saved'), 1100);+ } catch {+ // Roll back to the last known good value.+ el.textContent = previous;+ el._lastSaved = previous;+ el.classList.remove('is-saving');+ el.classList.add('is-error');+ setTimeout(() => el.classList.remove('is-error'), 1500);+ }+ });+ }++ _maybeShowWalletNudge() {+ if (this.identity.walletAddress) return; // already connected+ const panel = this._panel;+ if (!panel || panel.querySelector('.agent-wallet-nudge')) return; // already shown++ const id = this.identity;+ const nameCustomised = id.name && id.name !== 'Agent';+ const descCustomised = id.description && id.description !== 'A 3D AI agent';+ if (!nameCustomised && !descCustomised) return;++ const nudge = document.createElement('div');+ nudge.className = 'agent-wallet-nudge';+ nudge.innerHTML =+ `<span class="agent-wallet-nudge-text">Connect wallet to register on-chain</span>` ++ `<button class="agent-wallet-nudge-btn" id="agent-wallet-nudge-btn">Connect →</button>`;+ nudge.querySelector('#agent-wallet-nudge-btn').addEventListener('click', () => {+ document.dispatchEvent(new CustomEvent('agent-home:connect-wallet', { bubbles: true }));+ });++ // Insert before the memory bar+ const memBar = panel.querySelector('#agent-memory-bar');+ if (memBar) panel.insertBefore(nudge, memBar);+ else panel.appendChild(nudge);++ requestAnimationFrame(() => nudge.classList.add('agent-wallet-nudge--visible'));+ }++ // ── Memory Bar ────────────────────────────────────────────────────────────++ _renderMemoryBar() {+ if (!this.identity.memory) return '';+ const stats = this.identity.memory.stats;+ if (!stats.total) return '<span class="agent-mem-empty">no memories yet</span>';++ return (+ Object.entries(stats)+ .filter(([k]) => k !== 'total')+ .filter(([, v]) => v > 0)+ .map(+ ([type, count]) => `+ <span class="agent-mem-chip" data-type="${type}" title="${count} ${type} ${count === 1 ? 'memory' : 'memories'}">+ ${_memIcon(type)} ${count}+ </span>+ `,+ )+ .join('') + `<span class="agent-mem-total">${stats.total}</span>`+ );+ }++ _refreshMemoryBar() {+ const bar = this._panel?.querySelector('#agent-memory-bar');+ if (bar) bar.innerHTML = this._renderMemoryBar();+ }++ // ── Action Timeline ───────────────────────────────────────────────────────++ _subscribeProtocol() {+ this._onAnyAction = (action) => {+ // Only show meaningful actions (skip internal think/presence churn)+ if ([ACTION_TYPES.THINK, ACTION_TYPES.PRESENCE].includes(action.type)) return;+ this._pushTimeline(action);+ };+ this.protocol.on('*', this._onAnyAction);+ }++ _pushTimeline(action) {+ this._timeline.unshift(action);+ if (this._timeline.length > this._maxTimeline) this._timeline.pop();++ const timelineEl = this._panel?.querySelector('#agent-timeline');+ if (!timelineEl) return;++ const emptyEl = timelineEl.querySelector('.agent-timeline-empty');+ if (emptyEl) emptyEl.remove();++ const item = document.createElement('div');+ item.className = 'agent-timeline-item';+ item.innerHTML = `+ <span class="agent-timeline-icon">${ACTION_ICONS[action.type] || ACTION_ICONS.default}</span>+ <span class="agent-timeline-text">${_timelineText(action)}</span>+ <span class="agent-timeline-time">${_relTime(action.timestamp)}</span>+ `;+ item.style.animation = 'agent-timeline-in 0.25s ease';++ timelineEl.insertBefore(item, timelineEl.firstChild);++ // Keep DOM clean+ while (timelineEl.children.length > this._maxTimeline) {+ timelineEl.removeChild(timelineEl.lastChild);+ }++ // Refresh memory bar if it was a remember action+ if (action.type === ACTION_TYPES.REMEMBER) {+ this._refreshMemoryBar();+ }+ }++ // ── Emotion Presence ──────────────────────────────────────────────────────++ _startEmotionPoll() {+ // Update the emotion label in the status bar every second+ this._emotionInterval = setInterval(() => {+ if (!this.avatar) return;+ const state = this.avatar.emotionState;+ const dominant = Object.entries(state).reduce(+ (a, b) => (b[1] > a[1] ? b : a),+ ['neutral', 0],+ );+ const label = EMOTION_LABELS[dominant[0]] || 'present';++ const el = this._panel?.querySelector('#agent-home-emotion-label');+ if (el && el.textContent !== label) {+ el.style.opacity = '0';+ setTimeout(() => {+ el.textContent = label;+ el.style.opacity = '1';+ }, 150);+ }++ // Pulse the avatar ring colour based on dominant emotion+ const ring = this._panel?.querySelector('#agent-avatar-ring');+ if (ring) {+ ring.dataset.emotion = dominant[0];+ }+ }, 1000);+ }++ // ── Helpers ───────────────────────────────────────────────────────────────++ async _ensureIdentityLoaded() {+ if (!this.identity.isLoaded) {+ await this.identity.load();+ }+ }++ _flashBtn(btn, text) {+ if (!btn) return;+ const orig = btn.innerHTML;+ btn.textContent = text;+ setTimeout(() => {+ btn.innerHTML = orig;+ }, 1500);+ }+}++// ── Rendering Helpers ─────────────────────────────────────────────────────────++function _esc(str) {+ return String(str || '').replace(+ /[<>&"]/g,+ (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[c],+ );+}++function _shortAddr(addr) {+ if (!addr) return '';+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}++function _memIcon(type) {+ return { user: '👤', feedback: '↩', project: '📋', reference: '🔗' }[type] || '·';+}++function _relTime(ts) {+ const diff = Date.now() - ts;+ if (diff < 60_000) return 'just now';+ if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;+ if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;+ return new Date(ts).toLocaleDateString();+}++function _timelineText(action) {+ const p = action.payload || {};+ switch (action.type) {+ case ACTION_TYPES.SPEAK:+ return _esc((p.text || '').slice(0, 80) + (p.text?.length > 80 ? '…' : ''));+ case ACTION_TYPES.REMEMBER:+ return _esc(`Remembered: ${(p.content || '').slice(0, 60)}`);+ case ACTION_TYPES.PERFORM_SKILL:+ return _esc(`Performing skill: ${p.skill || '?'}`);+ case ACTION_TYPES.SKILL_DONE:+ return _esc(`${p.skill || 'Skill'} complete`);+ case ACTION_TYPES.SKILL_ERROR:+ return _esc(`${p.skill || 'Skill'} failed: ${(p.error || '').slice(0, 50)}`);+ case ACTION_TYPES.SIGN:+ return _esc(`Signed: ${(p.message || '').slice(0, 50)}`);+ case ACTION_TYPES.LOAD_END:+ return p.error ? _esc(`Load failed: ${p.error}`) : 'Model loaded';+ case ACTION_TYPES.VALIDATE:+ return _esc(`Validation: ${p.errors || 0} errors, ${p.warnings || 0} warnings`);+ default:+ return _esc(action.type.replace(/-/g, ' '));+ }+}diff --git a/publish/src/agent-hub-actions.js b/publish/src/agent-hub-actions.jsnew file mode 100644index 000000000..9a0e72c12--- /dev/null+++ b/publish/src/agent-hub-actions.js@@ -0,0 +1,196 @@+/**+ * Hub actions row for the /agent/:id page.+ * Renders four CTAs (Customize, Embed, Deploy on-chain, Edit avatar)+ * into the agent-home-panel, above the timeline.+ *+ * Only shown to the agent's owner. Non-owners see the unmodified panel.+ */+import { AgentEmbedModal } from './agent-embed-modal.js';++/**+ * @param {HTMLElement} panel — .agent-home-panel element+ * @param {import('./agent-identity.js').AgentIdentity} identity+ * @param {Object} rawAgent — raw API response (includes chain_id, is_registered when owner)+ */+export function renderHubActions(panel, identity, rawAgent) {+ const agentId = identity.id;+ const isRegistered = Boolean(rawAgent.is_registered);+ const chainId = rawAgent.chain_id || null;+ const walletAddress = rawAgent.wallet_address || null;+ const erc8004AgentId = rawAgent.erc8004_agent_id || null;++ const row = document.createElement('div');+ row.className = 'agent-hub-actions';+ row.innerHTML = `+ <button class="agent-hub-btn" id="hub-customize" title="Open the editing surface">+ ${_iconGear()}+ <span>Customize</span>+ </button>+ <button class="agent-hub-btn" id="hub-embed" title="Get embed code">+ ${_iconCode()}+ <span>Embed</span>+ </button>+ <button class="agent-hub-btn${isRegistered ? ' hub-btn--deployed' : ''}" id="hub-deploy"+ title="${isRegistered ? 'Manage on-chain record (edit, transfer, redeploy)' : 'Deploy on-chain — optional'}">+ ${_iconChain()}+ <span>${isRegistered ? _deployedLabel(chainId, walletAddress, erc8004AgentId) : 'Deploy on-chain'}</span>+ ${isRegistered ? '' : '<span class="agent-hub-opt">· Optional</span>'}+ </button>+ <button class="agent-hub-btn" id="hub-edit" title="Edit avatar">+ ${_iconPencil()}+ <span>Edit avatar</span>+ </button>+ `;++ // Customize → /app?agent=:id+ row.querySelector('#hub-customize').addEventListener('click', () => {+ location.href = `/app?agent=${agentId}`;+ });++ // Embed → open modal+ const embedModal = new AgentEmbedModal(agentId);+ row.querySelector('#hub-embed').addEventListener('click', () => embedModal.open());++ // Deploy on-chain → RegisterUI (lazy-imported). For a registered agent we+ // open directly on the "My Agents" tab so the owner gets Edit / Redeploy /+ // Transfer without re-selecting their chain + agent.+ const deployBtn = row.querySelector('#hub-deploy');+ if (isRegistered) {+ deployBtn.addEventListener('click', async () => {+ deployBtn.disabled = true;+ try {+ const { RegisterUI } = await import('./erc8004/register-ui.js');+ const wrap = document.createElement('div');+ wrap.className = 'agent-register-overlay';+ document.body.appendChild(wrap);+ new RegisterUI(+ wrap,+ () => {+ wrap.remove();+ location.reload();+ },+ { initialTab: 'my' },+ );+ } catch (err) {+ console.error('[hub] register-ui load failed', err);+ } finally {+ deployBtn.disabled = false;+ }+ });+ } else {+ deployBtn.addEventListener('click', async () => {+ deployBtn.disabled = true;+ deployBtn.querySelector('span').textContent = 'Opening…';+ try {+ const initial = await _resolveAgentPrefill(rawAgent);+ const { RegisterUI } = await import('./erc8004/register-ui.js');+ const wrap = document.createElement('div');+ wrap.className = 'agent-register-overlay';+ document.body.appendChild(wrap);+ new RegisterUI(+ wrap,+ () => {+ wrap.remove();+ location.reload();+ },+ { initial },+ );+ } catch (err) {+ console.error('[hub] register-ui load failed', err);+ deployBtn.disabled = false;+ deployBtn.querySelector('span').textContent = 'Deploy on-chain';+ }+ });+ }++ // Edit avatar → /agent/:id/edit+ row.querySelector('#hub-edit').addEventListener('click', () => {+ location.href = `/agent/${agentId}/edit`;+ });++ // Insert above the timeline (but below identity card + skills)+ const timeline = panel.querySelector('#agent-timeline');+ if (timeline) {+ panel.insertBefore(row, timeline);+ } else {+ panel.appendChild(row);+ }+}++/**+ * Build the `opts.initial` payload for RegisterUI from a backend agent.+ * Pulls name + description directly; if the agent has a linked avatar_id,+ * resolves that avatar's GLB + thumbnail so the wizard opens with the+ * embodied version pre-selected. Falls back silently on any fetch failure.+ *+ * @param {Object} rawAgent+ */+async function _resolveAgentPrefill(rawAgent) {+ const initial = {+ name: rawAgent.name || '',+ description: rawAgent.description || '',+ };+ if (!rawAgent.avatar_id) return initial;+ try {+ const res = await fetch(`/api/avatars/${encodeURIComponent(rawAgent.avatar_id)}`, {+ credentials: 'include',+ });+ if (!res.ok) return initial;+ const { avatar } = await res.json();+ if (!avatar) return initial;+ initial.glbUrl = avatar.url || avatar.model_url || '';+ initial.imageUrl = avatar.thumbnail_url || '';+ } catch (err) {+ console.warn('[hub] avatar prefill failed; opening wizard without it', err);+ }+ return initial;+}++// ── Icon helpers (inline SVG, consistent with existing nav icons) ─────────────++function _iconGear() {+ return `<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">+ <path d="M19.14 12.94c.04-.3.06-.61.06-.94s-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96a7.01 7.01 0 0 0-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96a.488.488 0 0 0-.59.22L2.74 8.87a.48.48 0 0 0 .12.61l2.03 1.58c-.05.3-.07.62-.07.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.37 1.04.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.57 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32a.49.49 0 0 0-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/>+ </svg>`;+}++function _iconCode() {+ return `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>+ </svg>`;+}++function _iconChain() {+ return `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>+ <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>+ </svg>`;+}++function _iconPencil() {+ return `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>+ </svg>`;+}++function _deployedLabel(chainId, walletAddress, erc8004AgentId) {+ const names = {+ 1: 'Ethereum',+ 10: 'Optimism',+ 56: 'BNB',+ 137: 'Polygon',+ 8453: 'Base',+ 42161: 'Arbitrum',+ 97: 'BSC Testnet',+ 84532: 'Base Sepolia',+ 11155111: 'Sepolia',+ };+ const chain = names[chainId] || `Chain ${chainId || '?'}`;+ const tag = erc8004AgentId+ ? `#${erc8004AgentId}`+ : walletAddress+ ? `${walletAddress.slice(0, 6)}…${walletAddress.slice(-4)}`+ : '';+ return tag ? `${chain} · ${tag}` : chain;+}diff --git a/publish/src/agent-identity.js b/publish/src/agent-identity.jsnew file mode 100644index 000000000..0739b27e7--- /dev/null+++ b/publish/src/agent-identity.js@@ -0,0 +1,333 @@+/**+ * Agent Identity+ * --------------+ * Every agent deserves a body, a place, a name, and a history.+ * This module is that. It persists to localStorage + backend,+ * links to an ERC-8004 on-chain presence, and maintains a signed+ * action log — the agent's provenance trail.+ *+ * Think of it as the agent's passport + diary.+ */++import { AgentMemory } from './agent-memory.js';++const STORAGE_KEY = 'agent_identity';++/**+ * @typedef {Object} AgentRecord+ * @property {string} id+ * @property {string} name+ * @property {string} [description]+ * @property {string} [avatarId] — R2 avatar UUID+ * @property {string} [homeUrl] — /agent/:id+ * @property {string} [walletAddress]+ * @property {number} [chainId]+ * @property {string[]} skills — enabled skill names+ * @property {Object} meta+ * @property {number} createdAt+ * @property {boolean} isRegistered — ERC-8004 on-chain+ */++export class AgentIdentity {+ /**+ * @param {{ userId?: string, agentId?: string, autoLoad?: boolean }} [opts]+ */+ constructor({ userId = null, agentId = null, autoLoad = true } = {}) {+ this.userId = userId;+ this._record = null;+ this._loaded = false;+ this.memory = null;++ // Pre-seed agentId from arg or storage so callers can use it synchronously+ this._agentId = agentId || this._readStoredId();++ if (autoLoad) this._loadAsync();+ }++ // ── Public getters ────────────────────────────────────────────────────────++ get id() {+ return this._record?.id || this._agentId;+ }+ get name() {+ return this._record?.name || 'Agent';+ }+ get description() {+ return this._record?.description || '';+ }+ get avatarId() {+ return this._record?.avatarId || null;+ }+ get homeUrl() {+ return this._record?.homeUrl || (this.id ? `/agent/${this.id}` : null);+ }+ get walletAddress() {+ return this._record?.walletAddress || null;+ }+ get chainId() {+ return this._record?.chainId || null;+ }+ get skills() {+ return this._record?.skills || [];+ }+ get meta() {+ return this._record?.meta || {};+ }+ get isLoaded() {+ return this._loaded;+ }+ get isRegistered() {+ return Boolean(this._record?.isRegistered);+ }++ // ── Load + Save ───────────────────────────────────────────────────────────++ async load() {+ await this._loadAsync();+ }++ async save() {+ if (!this._record) return;+ this._persist();+ try {+ const resp = await fetch(`/api/agents/${this._record.id}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ name: this._record.name,+ description: this._record.description,+ avatar_id: this._record.avatarId,+ skills: this._record.skills,+ meta: this._record.meta,+ }),+ });+ if (resp.ok) {+ const { agent } = await resp.json();+ this._record = _normalise(agent);+ this._persist();+ }+ } catch {+ /* localStorage is authoritative */+ }+ }++ /**+ * Update identity fields locally and push to backend.+ * @param {Partial<AgentRecord>} patch+ */+ async update(patch) {+ if (!this._record) await this._loadAsync();+ Object.assign(this._record, patch);+ await this.save();+ }++ // ── Wallet ────────────────────────────────────────────────────────────────++ async linkWallet(address, chainId) {+ await this.update({ walletAddress: address, chainId });+ try {+ await fetch(`/api/agents/${this.id}/wallet`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ wallet_address: address, chain_id: chainId }),+ });+ } catch {}+ }++ async unlinkWallet() {+ await this.update({ walletAddress: null, chainId: null });+ try {+ await fetch(`/api/agents/${this.id}/wallet`, {+ method: 'DELETE',+ credentials: 'include',+ });+ } catch {}+ }++ // ── Action History ────────────────────────────────────────────────────────++ /**+ * Append an action to the agent's signed history.+ * Fire-and-forget — never blocks the caller.+ * @param {import('./agent-protocol.js').ActionPayload} action+ */+ recordAction(action) {+ fetch('/api/agent-actions', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ agent_id: this.id,+ type: action.type,+ payload: action.payload,+ source_skill: action.sourceSkill || null,+ }),+ }).catch(() => {}); // non-critical+ }++ /**+ * Fetch recent actions from backend.+ * @param {{ limit?: number, cursor?: string }} [opts]+ * @returns {Promise<Object[]>}+ */+ async getActionHistory({ limit = 50, cursor } = {}) {+ try {+ const params = new URLSearchParams({ agent_id: this.id, limit: String(limit) });+ if (cursor) params.set('cursor', cursor);+ const resp = await fetch(`/api/agent-actions?${params}`, { credentials: 'include' });+ if (!resp.ok) return [];+ const { actions } = await resp.json();+ return actions || [];+ } catch {+ return [];+ }+ }++ // ── ERC-8004 Registration ────────────────────────────────────────────────++ /**+ * Register this agent on-chain via the ERC-8004 registry.+ * @param {{ glbFile: File, name?: string, description?: string, apiToken?: string, onStatus?: Function }} [opts]+ */+ async register({ glbFile, name, description, apiToken, onStatus } = {}) {+ const { registerAgent } = await import('./erc8004/agent-registry.js');+ const result = await registerAgent({+ glbFile,+ name: name || this.name,+ description: description || this.description,+ apiToken,+ onStatus,+ });+ await this.update({ isRegistered: true, meta: { ...this.meta, erc8004: result } });+ return result;+ }++ // ── Internal ──────────────────────────────────────────────────────────────++ async _loadAsync() {+ // 1. Try localStorage first (instant) — backendSync disabled until confirmed+ const local = this._readLocal();+ if (local) {+ this._record = local;+ this._agentId = local.id;+ this._loaded = true;+ this.memory = new AgentMemory(local.id, { backendSync: false });+ }++ // 2. Try backend (authoritative if user is signed in)+ try {+ const agentId = this._agentId;+ const url = agentId ? `/api/agents/${agentId}` : '/api/agents/me';+ const resp = await fetch(url, { credentials: 'include' });++ if (resp.ok) {+ const { agent } = await resp.json();+ // Server returns { agent: null } for anonymous /me — treat as+ // "no server identity" and fall through to local-only.+ if (agent) {+ this._record = _normalise(agent);+ this._agentId = this._record.id;+ this._loaded = true;+ this._persist();+ if (!this.memory) {+ this.memory = new AgentMemory(this._record.id, { backendSync: true });+ } else {+ // Agent confirmed in backend — enable sync and pull latest+ this.memory.backendSync = true;+ this.memory._syncFromBackend();+ }+ return;+ }+ }++ // Any non-2xx or a 2xx with null agent → use local record if we have+ // one, otherwise synthesize a local-only identity. Tolerant of 5xx+ // so a backend blip doesn't brick the avatar for the visitor.+ if (!this._record) {+ this._record = _makeDefault(this._agentId);+ this._agentId = this._record.id;+ this._loaded = true;+ this._persist();+ this.memory = new AgentMemory(this._agentId, { backendSync: false });+ }+ } catch {+ // Offline — use local record if we have one+ if (!this._record) {+ this._record = _makeDefault(this._agentId);+ this._agentId = this._record.id;+ this._loaded = true;+ this._persist();+ this.memory = new AgentMemory(this._agentId, { backendSync: false });+ }+ }+ }++ _readStoredId() {+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (raw) return JSON.parse(raw).id || null;+ } catch {}+ return null;+ }++ _readLocal() {+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ return raw ? JSON.parse(raw) : null;+ } catch {+ return null;+ }+ }++ _persist() {+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(this._record));+ } catch {}+ }+}++// ── Helpers ──────────────────────────────────────────────────────────────────++function _uuid() {+ if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {+ const r = (Math.random() * 16) | 0;+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);+ });+}++function _makeDefault(existingId) {+ return {+ id: existingId || _uuid(),+ name: 'Agent',+ description: 'A 3D AI agent',+ avatarId: null,+ homeUrl: null,+ walletAddress: null,+ chainId: null,+ skills: ['greet', 'present-model', 'validate-model', 'remember', 'think'],+ meta: {},+ createdAt: Date.now(),+ isRegistered: false,+ };+}++function _normalise(apiRecord) {+ return {+ id: apiRecord.id,+ name: apiRecord.name || 'Agent',+ description: apiRecord.description || '',+ avatarId: apiRecord.avatar_id || apiRecord.avatarId || null,+ homeUrl: apiRecord.home_url || apiRecord.homeUrl || `/agent/${apiRecord.id}`,+ walletAddress: apiRecord.wallet_address || apiRecord.walletAddress || null,+ chainId: apiRecord.chain_id || apiRecord.chainId || null,+ skills: apiRecord.skills || [],+ meta: apiRecord.meta || {},+ createdAt: apiRecord.created_at+ ? new Date(apiRecord.created_at).getTime()+ : apiRecord.createdAt || Date.now(),+ isRegistered: Boolean(apiRecord.erc8004_agent_id || apiRecord.isRegistered),+ };+}diff --git a/publish/src/agent-memory.js b/publish/src/agent-memory.jsnew file mode 100644index 000000000..8a702eceb--- /dev/null+++ b/publish/src/agent-memory.js@@ -0,0 +1,260 @@+/**+ * Agent Memory System+ * -------------------+ * Same primitive types as Claude's MEMORY.md pattern — because agents are just JSON too.+ * Stores to localStorage immediately, syncs to backend asynchronously.+ *+ * Memory types:+ * user — who the user is, preferences, expertise+ * feedback — corrections and confirmations that shape future behaviour+ * project — ongoing work context, goals, deadlines+ * reference — pointers to external resources+ */++export const MEMORY_TYPES = {+ USER: 'user',+ FEEDBACK: 'feedback',+ PROJECT: 'project',+ REFERENCE: 'reference',+};++/**+ * @typedef {Object} MemoryEntry+ * @property {string} id+ * @property {string} type — MEMORY_TYPES.*+ * @property {string} content — the actual memory text+ * @property {string[]} tags+ * @property {Object} [context] — freeform metadata+ * @property {number} salience — 0-1, how important/recent this memory is+ * @property {number} createdAt — timestamp+ * @property {number} [expiresAt]+ */++export class AgentMemory {+ /**+ * @param {string} agentId+ * @param {{ backendSync?: boolean }} [opts]+ */+ constructor(agentId, { backendSync = false } = {}) {+ this.agentId = agentId;+ this.backendSync = backendSync;+ this._entries = [];+ this._dirty = false;+ this._syncTimer = null;++ this._hydrate();+ }++ // ── CRUD ──────────────────────────────────────────────────────────────────++ /**+ * Store a new memory entry.+ * @param {{ type: string, content: string, tags?: string[], context?: Object, expiresAt?: number }} entry+ * @returns {string} new entry id+ */+ add(entry) {+ const id = _uuid();+ const now = Date.now();+ const mem = {+ id,+ type: entry.type || MEMORY_TYPES.PROJECT,+ content: String(entry.content).trim(),+ tags: Array.isArray(entry.tags) ? entry.tags : [],+ context: entry.context || {},+ salience: _computeSalience(entry, now),+ createdAt: now,+ expiresAt: entry.expiresAt || null,+ };+ this._entries.push(mem);+ this._scheduleSync(mem);+ return id;+ }++ /**+ * Query memory entries.+ * @param {{ type?: string, tags?: string[], limit?: number, since?: number }} [opts]+ * @returns {MemoryEntry[]}+ */+ query({ type, tags, limit = 50, since = 0 } = {}) {+ const now = Date.now();+ let results = this._entries.filter((m) => {+ if (m.expiresAt && m.expiresAt < now) return false;+ if (m.createdAt < since) return false;+ if (type && m.type !== type) return false;+ if (tags && tags.length) {+ const hasTags = tags.every((t) => m.tags.includes(t));+ if (!hasTags) return false;+ }+ return true;+ });++ // Sort by salience × recency — most relevant first+ results.sort((a, b) => {+ const scoreA = a.salience * _recencyBoost(a.createdAt, now);+ const scoreB = b.salience * _recencyBoost(b.createdAt, now);+ return scoreB - scoreA;+ });++ return results.slice(0, limit);+ }++ /**+ * Remove a memory by id.+ * @param {string} id+ */+ forget(id) {+ const idx = this._entries.findIndex((m) => m.id === id);+ if (idx !== -1) {+ this._entries.splice(idx, 1);+ this._persist();+ if (this.backendSync) this._syncForget(id);+ }+ }++ /**+ * Remove all memories of a given type (or all if type omitted).+ * @param {string} [type]+ */+ clear(type) {+ if (type) {+ this._entries = this._entries.filter((m) => m.type !== type);+ } else {+ this._entries = [];+ }+ this._persist();+ }++ /** Most recent N entries regardless of type */+ get recentEntries() {+ return this._entries.slice(-20).reverse();+ }++ /** Count by type */+ get stats() {+ const s = {};+ for (const t of Object.values(MEMORY_TYPES)) {+ s[t] = this._entries.filter((m) => m.type === t).length;+ }+ s.total = this._entries.length;+ return s;+ }++ // ── Persistence ──────────────────────────────────────────────────────────++ _storageKey() {+ return `agent_memory_${this.agentId}`;+ }++ _hydrate() {+ try {+ const raw = localStorage.getItem(this._storageKey());+ if (raw) {+ const parsed = JSON.parse(raw);+ this._entries = Array.isArray(parsed) ? parsed : [];+ }+ } catch {+ this._entries = [];+ }++ // Backend sync — merge newer entries from server+ if (this.backendSync) this._syncFromBackend();+ }++ _persist() {+ try {+ localStorage.setItem(this._storageKey(), JSON.stringify(this._entries));+ } catch {+ // localStorage quota exceeded — prune oldest low-salience entries+ this._prune();+ try {+ localStorage.setItem(this._storageKey(), JSON.stringify(this._entries));+ } catch {}+ }+ }++ _prune() {+ // Remove expired, then lowest salience until we're under 150 entries+ const now = Date.now();+ this._entries = this._entries.filter((m) => !m.expiresAt || m.expiresAt > now);+ if (this._entries.length > 150) {+ this._entries.sort((a, b) => b.salience - a.salience);+ this._entries = this._entries.slice(0, 150);+ }+ }++ _scheduleSync(entry) {+ this._persist();+ if (!this.backendSync) return;+ clearTimeout(this._syncTimer);+ this._syncTimer = setTimeout(() => this._syncToBackend(entry), 1500);+ }++ async _syncToBackend(entry) {+ try {+ await fetch(`/api/agent-memory`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ agentId: this.agentId, entry }),+ });+ } catch {+ /* non-critical — localStorage is authoritative */+ }+ }++ async _syncForget(id) {+ try {+ await fetch(`/api/agent-memory/${id}`, {+ method: 'DELETE',+ credentials: 'include',+ });+ } catch {}+ }++ async _syncFromBackend() {+ try {+ const resp = await fetch(`/api/agent-memory?agentId=${this.agentId}`, {+ credentials: 'include',+ });+ if (!resp.ok) return;+ const { entries } = await resp.json();+ if (!Array.isArray(entries)) return;++ // Merge: backend entries that don't exist locally win+ const localIds = new Set(this._entries.map((m) => m.id));+ const newEntries = entries.filter((m) => !localIds.has(m.id));+ if (newEntries.length) {+ this._entries.push(...newEntries);+ this._persist();+ }+ } catch {}+ }+}++// ── Helpers ──────────────────────────────────────────────────────────────────++function _uuid() {+ if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {+ const r = (Math.random() * 16) | 0;+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);+ });+}++function _computeSalience(entry, now) {+ // Explicit importance flag overrides everything+ if (entry.important) return 1.0;+ // Feedback and user memories are inherently higher salience+ const typeBonus = { feedback: 0.3, user: 0.2, project: 0.1, reference: 0.0 };+ const base = 0.5 + (typeBonus[entry.type] || 0);+ // Tag count slightly boosts salience (more tagged = more deliberate)+ const tagBonus = Math.min((entry.tags?.length || 0) * 0.05, 0.2);+ return Math.min(base + tagBonus, 1.0);+}++function _recencyBoost(createdAt, now) {+ // Exponential decay with 7-day half-life+ const ageMs = now - createdAt;+ const halfLife = 7 * 24 * 60 * 60 * 1000;+ return Math.exp((-0.693 * ageMs) / halfLife);+}diff --git a/publish/src/agent-naming.js b/publish/src/agent-naming.jsnew file mode 100644index 000000000..e11cd1a80--- /dev/null+++ b/publish/src/agent-naming.js@@ -0,0 +1,192 @@+const NAME_RE = /^[a-zA-Z0-9_-]{3,32}$/;++const DENYLIST = new Set([+ 'admin',+ 'root',+ 'system',+ 'anthropic',+ 'claude',+ 'openai',+ 'null',+ 'undefined',+ 'test',+]);++export class AgentNaming {+ constructor({ container, initialName = '', onSubmit }) {+ this._container = container;+ this._initialName = initialName;+ this._onSubmit = onSubmit;+ this._debounceTimer = null;+ this._abort = null;+ this._checkState = 'idle'; // idle | loading | valid | invalid+ this._lastCheckedName = null;+ this._root = null;+ }++ mount() {+ this._root = document.createElement('div');+ this._root.className = 'agent-naming';+ this._root.innerHTML = `+<style>+.agent-naming { display: flex; flex-direction: column; gap: 16px; max-width: 480px; font-family: inherit; }+.an-field { display: flex; flex-direction: column; gap: 4px; }+.an-field label { font-size: 14px; font-weight: 600; }+.an-required { color: #e53; }+.an-input-wrap { display: flex; align-items: center; gap: 8px; }+.an-input-wrap input { flex: 1; padding: 8px 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 14px; }+.an-status { font-size: 13px; min-width: 20px; white-space: nowrap; }+.an-status[data-state="valid"] { color: #2a9d2a; }+.an-status[data-state="invalid"] { color: #c0392b; }+.an-status[data-state="loading"] { color: #888; }+.an-hint { font-size: 12px; color: #888; }+.an-field textarea { padding: 8px 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 14px; resize: vertical; }+.an-counter { font-size: 12px; color: #888; text-align: right; }+.an-submit { padding: 10px 20px; background: #4f46e5; color: #fff; border: none; border-radius: 6px; font-size: 14px; font-weight: 600; cursor: pointer; }+.an-submit:disabled { opacity: 0.45; cursor: not-allowed; }+</style>+<div class="an-field">+ <label for="an-name">Name <span class="an-required">*</span></label>+ <div class="an-input-wrap">+ <input id="an-name" type="text" maxlength="32" autocomplete="off" spellcheck="false" placeholder="my-agent" />+ <span class="an-status" aria-live="polite" data-state=""></span>+ </div>+ <div class="an-hint">3–32 chars · letters, numbers, _ and - only</div>+</div>+<div class="an-field">+ <label for="an-desc">Description</label>+ <textarea id="an-desc" maxlength="280" rows="3" placeholder="What does your agent do?"></textarea>+ <div class="an-counter">0 / 280</div>+</div>+<button class="an-submit" type="button" disabled>Create agent</button>+`;++ this._nameInput = this._root.querySelector('#an-name');+ this._descInput = this._root.querySelector('#an-desc');+ this._statusEl = this._root.querySelector('.an-status');+ this._submitBtn = this._root.querySelector('.an-submit');+ this._counterEl = this._root.querySelector('.an-counter');++ this._onNameInput = () => this._handleNameInput();+ this._onDescInput = () => this._handleDescInput();+ this._onSubmitClick = () => this._handleSubmit();++ this._nameInput.addEventListener('input', this._onNameInput);+ this._descInput.addEventListener('input', this._onDescInput);+ this._submitBtn.addEventListener('click', this._onSubmitClick);++ this._container.appendChild(this._root);++ if (this._initialName) {+ this._nameInput.value = this._initialName;+ this._handleNameInput();+ }+ }++ unmount() {+ if (this._debounceTimer) clearTimeout(this._debounceTimer);+ if (this._abort) this._abort.abort();+ this._nameInput?.removeEventListener('input', this._onNameInput);+ this._descInput?.removeEventListener('input', this._onDescInput);+ this._submitBtn?.removeEventListener('click', this._onSubmitClick);+ this._root?.remove();+ this._root = null;+ }++ _handleNameInput() {+ const name = this._nameInput.value;++ if (this._debounceTimer) clearTimeout(this._debounceTimer);+ if (this._abort) this._abort.abort();++ const localError = this._validateLocal(name);+ if (localError) {+ this._setStatus('invalid', localError);+ return;+ }++ this._setStatus('loading', '');+ this._debounceTimer = setTimeout(() => this._runCheck(name), 400);+ }++ _handleDescInput() {+ const len = this._descInput.value.length;+ this._counterEl.textContent = `${len} / 280`;+ }++ _validateLocal(name) {+ if (!name) return 'Name is required.';+ if (name.length < 3) return 'At least 3 characters required.';+ if (name.length > 32) return '32 characters maximum.';+ if (!NAME_RE.test(name)) return 'Letters, numbers, _ and - only.';+ if (DENYLIST.has(name.toLowerCase())) return 'That name is reserved.';+ return null;+ }++ async _runCheck(name) {+ this._abort = new AbortController();+ try {+ const res = await fetch(`/api/agents/check-name?name=${encodeURIComponent(name)}`, {+ signal: this._abort.signal,+ credentials: 'include',+ });+ const data = await res.json();+ this._lastCheckedName = name;+ if (data.available) {+ this._setStatus('valid', '');+ } else {+ this._setStatus('invalid', this._reasonText(data.reason));+ }+ } catch (err) {+ if (err.name === 'AbortError') return;+ this._lastCheckedName = null;+ this._setStatus('invalid', 'Could not check availability.');+ }+ }++ _reasonText(reason) {+ if (reason === 'taken') return 'Name is already taken.';+ if (reason === 'denylisted') return 'That name is reserved.';+ return 'Name is not available.';+ }++ _setStatus(state, message) {+ this._checkState = state;+ this._statusEl.dataset.state = state;+ if (state === 'loading') {+ this._statusEl.textContent = '…';+ } else if (state === 'valid') {+ this._statusEl.textContent = '✓';+ } else if (state === 'invalid') {+ this._statusEl.textContent = message ? `✗ ${message}` : '✗';+ } else {+ this._statusEl.textContent = '';+ }+ this._submitBtn.disabled = state !== 'valid';+ }++ async _handleSubmit() {+ const name = this._nameInput.value;++ const localError = this._validateLocal(name);+ if (localError) {+ this._setStatus('invalid', localError);+ return;+ }++ // Re-run server check if input changed since last confirmed check.+ if (this._lastCheckedName !== name) {+ if (this._debounceTimer) clearTimeout(this._debounceTimer);+ await this._runCheck(name);+ if (this._checkState !== 'valid') return;+ }++ this._submitBtn.disabled = true;+ try {+ await this._onSubmit({ name, description: this._descInput.value.trim() });+ } finally {+ // Re-enable only if still mounted.+ if (this._root) this._submitBtn.disabled = this._checkState !== 'valid';+ }+ }+}diff --git a/publish/src/agent-protocol.js b/publish/src/agent-protocol.jsnew file mode 100644index 000000000..f4f28a207--- /dev/null+++ b/publish/src/agent-protocol.js@@ -0,0 +1,124 @@+/**+ * Agent Action Protocol+ * ---------------------+ * The zero-dependency event bus that every module speaks through.+ * Every action emitted here is visible — agents are not invisible JSON.+ *+ * Actions flow: Skills → Protocol → Avatar (renders) + Identity (logs) + Memory (stores)+ */++export const ACTION_TYPES = {+ SPEAK: 'speak', // agent says something (text + sentiment)+ THINK: 'think', // agent is processing (internal monologue)+ GESTURE: 'gesture', // named body gesture (point, wave, nod, shrug)+ EMOTE: 'emote', // direct emotion injection (concern, celebrate…)+ LOOK_AT: 'look-at', // agent looks at a world position or object+ PERFORM_SKILL: 'perform-skill', // a skill is starting execution+ SKILL_DONE: 'skill-done', // a skill finished (success + result payload)+ SKILL_ERROR: 'skill-error', // a skill failed+ REMEMBER: 'remember', // agent stored a memory+ SIGN: 'sign', // agent signs an action with its wallet+ LOAD_START: 'load-start', // model/asset loading started+ LOAD_END: 'load-end', // model/asset loading finished+ VALIDATE: 'validate', // validation result (errors, warnings, hints)+ PRESENCE: 'presence', // agent came online / went idle+ PERMISSIONS_REDEEM_START: 'permissions.redeem.start',+ PERMISSIONS_REDEEM_SUCCESS: 'permissions.redeem.success',+ PERMISSIONS_REDEEM_ERROR: 'permissions.redeem.error',+};++/**+ * @typedef {Object} ActionPayload+ * @property {string} type — one of ACTION_TYPES+ * @property {Object} payload — action-specific data+ * @property {number} timestamp — Date.now()+ * @property {string} agentId — identity id of the emitting agent+ * @property {string} [sourceSkill] — skill name if emitted by a skill+ */++export class AgentProtocol extends EventTarget {+ constructor() {+ super();+ this._history = [];+ this._maxHistory = 200;+ }++ /**+ * Emit a typed action to all listeners.+ * @param {Omit<ActionPayload, 'timestamp'>} action+ */+ emit(action) {+ const full = {+ type: action.type,+ payload: action.payload || {},+ timestamp: Date.now(),+ agentId: action.agentId || 'default',+ sourceSkill: action.sourceSkill || null,+ };++ // Trim history+ this._history.push(full);+ if (this._history.length > this._maxHistory) {+ this._history.shift();+ }++ this.dispatchEvent(new CustomEvent(full.type, { detail: full }));+ // Also dispatch a wildcard so listeners can monitor all traffic+ this.dispatchEvent(new CustomEvent('*', { detail: full }));+ }++ /**+ * Subscribe to a specific action type (or '*' for all).+ * @param {string} type+ * @param {(action: ActionPayload) => void} handler+ */+ on(type, handler) {+ this._wrap(type, handler, false);+ }++ /**+ * Subscribe once.+ * @param {string} type+ * @param {(action: ActionPayload) => void} handler+ */+ once(type, handler) {+ this._wrap(type, handler, true);+ }++ /**+ * Unsubscribe. Must pass the same handler reference as used in on().+ * @param {string} type+ * @param {Function} handler+ */+ off(type, handler) {+ if (handler.__protocolWrapped) {+ this.removeEventListener(type, handler.__protocolWrapped);+ } else {+ this.removeEventListener(type, handler);+ }+ }++ /** @returns {ActionPayload[]} Recent action history (newest last) */+ get history() {+ return this._history.slice();+ }++ /** Returns last N actions of a given type */+ recent(type, n = 10) {+ return this._history.filter((a) => a.type === type).slice(-n);+ }++ _wrap(type, handler, once) {+ const wrapped = (e) => handler(e.detail);+ handler.__protocolWrapped = wrapped;+ if (once) {+ this.addEventListener(type, wrapped, { once: true });+ } else {+ this.addEventListener(type, wrapped);+ }+ }+}++// Singleton — import this everywhere+export const protocol = new AgentProtocol();+export default protocol;diff --git a/publish/src/agent-resolver.js b/publish/src/agent-resolver.jsnew file mode 100644index 000000000..5215a3309--- /dev/null+++ b/publish/src/agent-resolver.js@@ -0,0 +1,163 @@+// Resolve a hosted agent by id against the backend API, producing an in-memory+// manifest shaped like a file-based one so the rest of the <agent-3d> boot+// path (manifest.body.uri, manifest.brain, manifest.skills, manifest._baseURI)+// works unchanged.++export class AgentResolveError extends Error {+ constructor(code, message, { status } = {}) {+ super(message);+ this.name = 'AgentResolveError';+ this.code = code;+ if (status !== undefined) this.status = status;+ }+}++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}`);+ }+}++const _resolveCache = new Map();+const _CACHE_MAX = 100;++/**+ * 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.+ *+ * @param {string} agentId+ * @param {AbortSignal} [signal]+ * @returns {Promise<string|null>}+ */+export async function resolveByAgentId(agentId, 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)}`;++ let res;+ try {+ res = await fetch(endpoint, { credentials: 'include', signal });+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new AgentResolveError(+ 'network',+ `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})`, {+ status: res.status,+ });+ if (!res.ok)+ throw new AgentResolveError('network', `request failed (${res.status})`, {+ status: res.status,+ });++ let data;+ try {+ data = 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;+}++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`);+ }++ 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 skills = Array.isArray(agent.skills)+ ? agent.skills.map((s) => (typeof s === 'string' ? { name: s } : s)).filter(Boolean)+ : [];++ 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' },+ brain: {},+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },+ skills,+ memory: { mode: 'remote', namespace: agent.id },+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],+ version: '0.1.0',+ _baseURI: `${origin}/agent/${agent.id}/`,+ _source: 'agent-id',+ };+}diff --git a/publish/src/agent-skills-pumpfun-autonomous.js b/publish/src/agent-skills-pumpfun-autonomous.jsnew file mode 100644index 000000000..46bf55bb6--- /dev/null+++ b/publish/src/agent-skills-pumpfun-autonomous.js@@ -0,0 +1,236 @@+/**+ * Pump.fun autonomous skills for Solana agents+ * --------------------------------------------+ * These skills make an agent act with its OWN server-side Solana wallet+ * (provisioned in api/_lib/agent-pumpfun.js). Distinct from+ * agent-skills-pumpfun.js, which signs with the human owner's browser wallet.+ *+ * Use cases:+ * - Agent pays for its own services / subscriptions on chain+ * - Agent autonomously launches a follow-up token without user click+ * - Agent rebalances its treasury (swap)+ * - Agent withdraws collected payments to its main vault+ *+ * Auth: relies on session cookie or bearer token from the calling environment.+ * The server-side endpoints already verify caller ownership of the agent.+ *+ * No keys touched here. No SDK imports. Pure HTTP fetch.+ */++const ENDPOINT = (id, leaf) =>+ `/api/agents/${encodeURIComponent(id)}/pumpfun/${leaf}`;++async function postJson(url, body) {+ const res = await fetch(url, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body || {}),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ const msg = data?.error_description || `${url} returned ${res.status}`;+ const err = new Error(msg);+ err.status = res.status;+ err.code = data?.error;+ throw err;+ }+ return data;+}++function requireAgentId(ctx) {+ const id = ctx?.identity?.id;+ if (!id) throw new Error('No agent identity in context.');+ return id;+}++/**+ * @param {import('./agent-skills.js').AgentSkills} skills+ */+export function registerPumpFunAutonomousSkills(skills) {+ // ── pumpfun-self-launch ───────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-self-launch',+ description:+ "Launch a pump.fun token signed by the agent's own Solana wallet (server-side). The agent becomes the creator.",+ instruction:+ 'POSTs to /api/agents/:id/pumpfun/launch. The user must own the agent (server enforces).',+ animationHint: 'celebrate',+ voicePattern: 'Launching {{symbol}} from my own wallet…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ name: { type: 'string' },+ symbol: { type: 'string' },+ uri: { type: 'string', description: 'Pre-uploaded metadata URI' },+ solAmount: { type: 'number', description: 'Optional initial dev-buy in SOL' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ vanityPrefix: { type: 'string', maxLength: 6 },+ vanitySuffix: { type: 'string', maxLength: 6 },+ vanityIgnoreCase: { type: 'boolean' },+ },+ required: ['symbol', 'uri'],+ },+ handler: async (args, ctx) => {+ const id = requireAgentId(ctx);+ const resp = await postJson(ENDPOINT(id, 'launch'), {+ name: args.name || ctx.identity?.name,+ symbol: args.symbol,+ uri: args.uri,+ solAmount: args.solAmount,+ network: args.network,+ vanityPrefix: args.vanityPrefix,+ vanitySuffix: args.vanitySuffix,+ vanityIgnoreCase: args.vanityIgnoreCase,+ });+ // Server uses { data: {...} } envelope per api/_lib/http.json convention.+ const payload = resp?.data || resp;+ return {+ success: true,+ output: `Launched ${args.symbol}. Mint: ${payload.mint}`,+ sentiment: 0.9,+ data: { ...payload, symbol: args.symbol, network: args.network || 'mainnet' },+ };+ },+ });++ // ── pumpfun-self-launch-from-identity ─────────────────────────────────────+ skills.register({+ name: 'pumpfun-self-launch-from-identity',+ description:+ 'One-shot: agent autonomously launches a token whose metadata is auto-derived from its identity (name, GLB, bio).',+ instruction:+ 'Resolves /api/agents/pumpfun-metadata?id=<id>, then calls pumpfun-self-launch.',+ animationHint: 'celebrate',+ voicePattern: 'Minting myself…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string' },+ solAmount: { type: 'number' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ vanityPrefix: { type: 'string', maxLength: 6 },+ vanitySuffix: { type: 'string', maxLength: 6 },+ vanityIgnoreCase: { type: 'boolean' },+ },+ },+ handler: async (args, ctx) => {+ const id = requireAgentId(ctx);+ const origin = (typeof window !== 'undefined' && window.location?.origin) || '';+ const uri = `${origin}/api/agents/pumpfun-metadata?id=${encodeURIComponent(id)}`;+ const symbol =+ args.symbol ||+ (ctx.identity?.name || 'AGENT')+ .toUpperCase()+ .replace(/[^A-Z0-9]/g, '')+ .slice(0, 10) ||+ 'AGENT';+ return skills.perform(+ 'pumpfun-self-launch',+ {+ name: ctx.identity?.name,+ symbol,+ uri,+ solAmount: args.solAmount,+ network: args.network,+ vanityPrefix: args.vanityPrefix,+ vanitySuffix: args.vanitySuffix,+ vanityIgnoreCase: args.vanityIgnoreCase,+ },+ ctx,+ );+ },+ });++ // ── pumpfun-self-swap ─────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-self-swap',+ description:+ "Buy or sell a pump.fun token from the agent's own wallet. Auto-routes bonding-curve vs AMM by graduation status.",+ instruction:+ 'POSTs to /api/agents/:id/pumpfun/swap. Server picks pump-sdk or pump-swap-sdk by curve state.',+ animationHint: 'gesture',+ voicePattern: '{{side}} {{mint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ side: { type: 'string', enum: ['buy', 'sell'] },+ solAmount: { type: 'number', description: 'For buy: SOL to spend' },+ tokenAmount: { type: 'string', description: 'For sell: tokens (raw units)' },+ slippageBps: { type: 'integer', minimum: 0, maximum: 10000 },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['mint', 'side'],+ },+ handler: async (args, ctx) => {+ const id = requireAgentId(ctx);+ const resp = await postJson(ENDPOINT(id, 'swap'), {+ mint: args.mint,+ side: args.side,+ solAmount: args.solAmount,+ tokenAmount: args.tokenAmount,+ slippageBps: args.slippageBps ?? 500,+ network: args.network || 'mainnet',+ });+ const payload = resp?.data || resp;+ return {+ success: true,+ output:+ args.side === 'buy'+ ? `Bought ${args.mint.slice(0, 8)}… for ${args.solAmount} SOL.`+ : `Sold ${args.tokenAmount} of ${args.mint.slice(0, 8)}…`,+ sentiment: 0.5,+ data: { ...payload, mint: args.mint, side: args.side, network: args.network || 'mainnet', solAmount: args.solAmount },+ };+ },+ });++ // ── pumpfun-self-pay ──────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-self-pay',+ description:+ "Agent-side payment ops: accept (pay an agent), withdraw (pull collected fees), balances (read).",+ instruction: 'POSTs to /api/agents/:id/pumpfun/pay with { action, ... }.',+ animationHint: 'gesture',+ voicePattern: 'Pump payment {{action}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ action: { type: 'string', enum: ['accept', 'withdraw', 'balances'] },+ tokenMint: { type: 'string' },+ currencyMint: { type: 'string' },+ amount: { type: 'string' },+ memo: { type: 'string' },+ startTime: { type: 'number' },+ endTime: { type: 'number' },+ receiverAta: { type: 'string', description: 'For withdraw' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['action'],+ },+ handler: async (args, ctx) => {+ const id = requireAgentId(ctx);+ const resp = await postJson(ENDPOINT(id, 'pay'), args);+ const payload = resp?.data || resp;+ let output;+ if (args.action === 'balances') {+ output = `Balances: ${JSON.stringify(payload.balances || payload)}`;+ } else if (args.action === 'accept') {+ output = `Payment accepted (${args.amount}).`;+ } else {+ output = `Withdraw complete.`;+ }+ return {+ success: true,+ output,+ sentiment: 0.5,+ data: { ...payload, network: args.network || 'mainnet' },+ };+ },+ });+}diff --git a/publish/src/agent-skills-pumpfun-compose.js b/publish/src/agent-skills-pumpfun-compose.jsnew file mode 100644index 000000000..afe0a2f5c--- /dev/null+++ b/publish/src/agent-skills-pumpfun-compose.js@@ -0,0 +1,429 @@+/**+ * Pump.fun composition skills — agent-level loops over read (MCP) + trade (signed).+ * Composes pumpfun-buy / pumpfun-sell / pumpfun-status in-process.+ *+ * Args supported by every loop:+ * - sessionId:"..." → seen/mirrored/spent/exited persisted in agent memory,+ * survives crashes within the spend cap.+ * - signal → AbortSignal; loops, sleeps, and inner iterations all+ * bail out promptly when aborted.+ * - onProgress(evt) → called on every state change (vet/skip/buy/sell/sleep).+ * Used by the UI for live counters.+ * - dryRun:true → identical control flow; trade-skill calls are replaced+ * with `{ signature: null, dryRun: true }`. Spend cap+ * and seen/mirrored sets still tick so a dry-run+ * terminates the same way a live run would.+ */++const MCP_ENDPOINT = 'https://pump-fun-sdk.modelcontextprotocol.name/mcp';+const _sessions = new Map();+let _rpcId = 0;++const DEFAULTS = {+ sessionSpendCapSol: 1.0,+ perTradeSol: 0.05,+ minHoldersForBuy: 30,+ maxTopHolderPct: 25,+ rejectIfCreatorRugCount: 1,+ exitOnConcentrationPct: 40,+ exitOnDevSellPct: 25,+ pollMs: 5000,+};++function cfg(ctx, key) {+ return ctx?.skillConfig?.[key] ?? DEFAULTS[key];+}++async function mcp(toolName, args) {+ const res = await fetch(MCP_ENDPOINT, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: ++_rpcId,+ method: 'tools/call',+ params: { name: toolName, arguments: args ?? {} },+ }),+ });+ if (!res.ok) throw new Error(`pump-fun MCP HTTP ${res.status}`);+ const body = await res.json();+ if (body.error) throw new Error(body.error.message ?? 'pump-fun MCP error');+ const text = body.result?.content?.find?.((c) => c.type === 'text')?.text;+ if (text) {+ try { return JSON.parse(text); } catch { return text; }+ }+ return body.result;+}++async function loadState(memory, sessionId, init) {+ if (!sessionId) return { ...init };+ if (_sessions.has(sessionId)) return _sessions.get(sessionId);+ try {+ const entries = memory?.query?.({ tags: [`compose:${sessionId}`], limit: 1 }) || [];+ const prior = entries[0]?.content;+ if (prior && typeof prior === 'object') {+ const restored = {+ ...init,+ ...prior,+ seen: new Set(prior.seen || []),+ mirrored: new Set(prior.mirrored || []),+ exited: new Set(prior.exited || []),+ };+ _sessions.set(sessionId, restored);+ return restored;+ }+ } catch {}+ const fresh = { ...init };+ _sessions.set(sessionId, fresh);+ return fresh;+}++function saveState(memory, sessionId, state) {+ if (!sessionId) return;+ _sessions.set(sessionId, state);+ const serializable = {+ ...state,+ seen: state.seen ? [...state.seen] : undefined,+ mirrored: state.mirrored ? [...state.mirrored] : undefined,+ exited: state.exited ? [...state.exited] : undefined,+ };+ try {+ memory?.add?.({+ type: 'project',+ content: serializable,+ tags: [`compose:${sessionId}`],+ important: true,+ });+ } catch {}+}++function abortableSleep(ms, signal) {+ return new Promise((resolve) => {+ if (signal?.aborted) return resolve();+ const t = setTimeout(resolve, ms);+ const onAbort = () => { clearTimeout(t); resolve(); };+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++async function doBuy(skills, ctx, dryRun, mint, solAmount) {+ if (dryRun) return { signature: null, dryRun: true };+ const r = await skills.perform('pumpfun-buy', { mint, solAmount }, ctx);+ if (!r?.success) throw new Error(r?.output || 'pumpfun-buy failed');+ return r.data;+}++async function doSell(skills, ctx, dryRun, mint) {+ const status = await skills.perform('pumpfun-status', { mint }, ctx);+ const tokenAmount = status?.data?.userBalance ?? '0';+ if (tokenAmount === '0') return { signature: null, skipped: 'no-balance', tokenAmount };+ if (dryRun) return { signature: null, dryRun: true, tokenAmount };+ const r = await skills.perform('pumpfun-sell', { mint, tokenAmount }, ctx);+ if (!r?.success) throw new Error(r?.output || 'pumpfun-sell failed');+ return { ...r.data, tokenAmount };+}++function emit(progress, evt) {+ try { progress?.(evt); } catch {}+}++function passesFilters(ctx, { creator, holders }) {+ const rugCount = creator?.rugCount ?? creator?.rugFlags?.length ?? 0;+ if (rugCount >= cfg(ctx, 'rejectIfCreatorRugCount')) {+ return { ok: false, reason: `creator has ${rugCount} prior rug(s)` };+ }+ const holderCount = holders?.total ?? holders?.holders?.length ?? 0;+ if (holderCount < cfg(ctx, 'minHoldersForBuy')) {+ return { ok: false, reason: `only ${holderCount} holders` };+ }+ const top = holders?.topHolderPct ?? holders?.holders?.[0]?.pct ?? 0;+ if (top > cfg(ctx, 'maxTopHolderPct')) {+ return { ok: false, reason: `top holder owns ${top}%` };+ }+ return { ok: true };+}++async function vetMint(mint) {+ const [details, holders] = await Promise.all([+ mcp('getTokenDetails', { mint }),+ mcp('getTokenHolders', { mint, limit: 20 }),+ ]);+ const creatorAddr = details?.creator ?? details?.token?.creator;+ const creator = creatorAddr ? await mcp('getCreatorProfile', { creator: creatorAddr }) : { rugCount: 0 };+ return { details, holders, creator };+}++/**+ * @param {import('./agent-skills.js').AgentSkills} skills+ */+export function registerPumpFunComposeSkills(skills) {+ skills.register({+ name: 'pumpfun-research-and-buy',+ description: 'Research a pump.fun token, then buy if it passes rug/holder filters.',+ instruction: 'search → vet (curve, holders, creator rug flags) → buy via pumpfun-buy.',+ animationHint: 'inspect',+ voicePattern: 'Researching {{query}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string' },+ amountSol: { type: 'number' },+ dryRun: { type: 'boolean', description: 'Vet/quote but skip the actual buy.' },+ },+ required: ['query'],+ },+ handler: async (args, ctx) => {+ const dryRun = !!args.dryRun;+ const onProgress = args.onProgress;+ emit(onProgress, { type: 'search', query: args.query });+ const search = await mcp('searchTokens', { query: args.query, limit: 1 });+ const mint = search?.results?.[0]?.mint ?? search?.[0]?.mint ?? args.query;+ emit(onProgress, { type: 'vet', mint });+ const v = await vetMint(mint);+ const verdict = passesFilters(ctx, v);+ if (!verdict.ok) {+ emit(onProgress, { type: 'skip', mint, reason: verdict.reason });+ return {+ success: true,+ output: `Skipping ${mint.slice(0, 8)}…: ${verdict.reason}`,+ sentiment: -0.1,+ data: { mint, decision: 'skip', reason: verdict.reason, dryRun },+ };+ }+ const amountSol = args.amountSol ?? cfg(ctx, 'perTradeSol');+ emit(onProgress, { type: dryRun ? 'dry-buy' : 'buy', mint, amountSol });+ const buy = await doBuy(skills, ctx, dryRun, mint, amountSol);+ return {+ success: true,+ output: dryRun+ ? `Dry-run buy ${amountSol} SOL of ${mint.slice(0, 8)}….`+ : `Bought ${amountSol} SOL of ${mint.slice(0, 8)}….`,+ sentiment: 0.6,+ data: { mint, decision: 'buy', amountSol, sig: buy.signature, dryRun },+ };+ },+ });++ skills.register({+ name: 'pumpfun-auto-snipe',+ description: 'Poll new tokens, vet, and auto-buy each pass with perTradeSol until sessionSpendCapSol. Persists seen/spent under sessionId.',+ instruction: 'autoSnipe loop. Use simulate:true to validate filters without spending.',+ animationHint: 'gesture',+ voicePattern: 'Sniping for {{durationSec}}s…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ durationSec: { type: 'integer', minimum: 10, maximum: 3600 },+ perTradeSol: { type: 'number' },+ sessionId: { type: 'string' },+ dryRun: { type: 'boolean' },+ },+ required: ['durationSec'],+ },+ handler: async (args, ctx) => {+ const dryRun = !!args.dryRun;+ const onProgress = args.onProgress;+ const signal = args.signal;+ const sessionId = args.sessionId;+ const deadline = Date.now() + args.durationSec * 1000;+ const perTrade = args.perTradeSol ?? cfg(ctx, 'perTradeSol');+ const cap = cfg(ctx, 'sessionSpendCapSol');+ const state = await loadState(ctx?.memory, sessionId, { seen: new Set(), spent: 0, log: [] });+ emit(onProgress, { type: 'start', mode: 'auto-snipe', spent: state.spent, cap });++ while (!signal?.aborted && Date.now() < deadline && state.spent + perTrade <= cap) {+ const fresh = await mcp('getNewTokens', { limit: 20 }).catch(() => null);+ const items = fresh?.tokens ?? fresh ?? [];+ for (const t of items) {+ if (signal?.aborted) break;+ const mint = t.mint ?? t.address;+ if (!mint || state.seen.has(mint)) continue;+ state.seen.add(mint);+ emit(onProgress, { type: 'vet', mint });+ const v = await vetMint(mint).catch((e) => ({ verdict: { ok: false, reason: e.message } }));+ const verdict = v.verdict || passesFilters(ctx, v);+ if (!verdict.ok) {+ state.log.push({ mint, action: 'skip', reason: verdict.reason });+ emit(onProgress, { type: 'skip', mint, reason: verdict.reason, spent: state.spent });+ continue;+ }+ try {+ const buy = await doBuy(skills, ctx, dryRun, mint, perTrade);+ state.spent += perTrade;+ state.log.push({ mint, action: dryRun ? 'dry-buy' : 'buy', sig: buy.signature, spent: state.spent });+ saveState(ctx?.memory, sessionId, state);+ emit(onProgress, { type: dryRun ? 'dry-buy' : 'buy', mint, sig: buy.signature, spent: state.spent });+ if (state.spent + perTrade > cap) break;+ } catch (e) {+ state.log.push({ mint, action: 'error', reason: e.message });+ emit(onProgress, { type: 'error', mint, reason: e.message });+ }+ }+ saveState(ctx?.memory, sessionId, state);+ if (signal?.aborted || Date.now() >= deadline || state.spent + perTrade > cap) break;+ emit(onProgress, { type: 'poll-sleep', ms: cfg(ctx, 'pollMs') });+ await abortableSleep(cfg(ctx, 'pollMs'), signal);+ }+ const reason = signal?.aborted ? 'aborted' : Date.now() >= deadline ? 'duration' : 'cap';+ return {+ success: true,+ output: `${dryRun ? 'Dry-run' : 'Snipe'} done (${reason}). Spent ${state.spent} SOL across ${state.log.length} events.`,+ sentiment: 0.4,+ data: { spent: state.spent, trades: state.log, dryRun, sessionId, reason },+ };+ },+ });++ skills.register({+ name: 'pumpfun-copy-trade',+ description: 'Mirror a wallet\'s recent pump.fun buys with size scaling. Persists mirrored sigs under sessionId.',+ instruction: 'copyTrade loop.',+ animationHint: 'gesture',+ voicePattern: 'Copy-trading {{wallet}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ wallet: { type: 'string' },+ sizeMultiplier: { type: 'number', minimum: 0.001, maximum: 10 },+ durationSec: { type: 'integer', minimum: 10, maximum: 7200 },+ sessionId: { type: 'string' },+ dryRun: { type: 'boolean' },+ },+ required: ['wallet', 'durationSec'],+ },+ handler: async (args, ctx) => {+ const dryRun = !!args.dryRun;+ const onProgress = args.onProgress;+ const signal = args.signal;+ const sessionId = args.sessionId;+ const deadline = Date.now() + args.durationSec * 1000;+ const mult = args.sizeMultiplier ?? 1;+ const cap = cfg(ctx, 'sessionSpendCapSol');+ const state = await loadState(ctx?.memory, sessionId, { mirrored: new Set(), spent: 0, log: [] });+ emit(onProgress, { type: 'start', mode: 'copy-trade', wallet: args.wallet, spent: state.spent, cap });++ while (!signal?.aborted && Date.now() < deadline && state.spent < cap) {+ const profile = await mcp('getCreatorProfile', { creator: args.wallet }).catch(() => null);+ const recentMints = (profile?.tokens ?? []).map((t) => t.mint).filter(Boolean);+ for (const mint of recentMints) {+ if (signal?.aborted) break;+ const trades = await mcp('getTokenTrades', { mint, limit: 20 }).catch(() => null);+ const buys = (trades?.trades ?? trades ?? []).filter(+ (t) => t.side === 'buy' && t.wallet === args.wallet && !state.mirrored.has(t.sig),+ );+ for (const b of buys) {+ if (signal?.aborted) break;+ state.mirrored.add(b.sig);+ const amountSol = Math.min((b.solAmount ?? 0) * mult, cap - state.spent);+ if (amountSol <= 0) break;+ try {+ const r = await doBuy(skills, ctx, dryRun, mint, amountSol);+ state.spent += amountSol;+ state.log.push({ mint, mirroredFrom: b.sig, sig: r.signature, amountSol, dryRun });+ saveState(ctx?.memory, sessionId, state);+ emit(onProgress, { type: dryRun ? 'dry-buy' : 'buy', mint, sig: r.signature, amountSol, spent: state.spent });+ } catch (e) {+ state.log.push({ mint, error: e.message });+ emit(onProgress, { type: 'error', mint, reason: e.message });+ }+ }+ }+ saveState(ctx?.memory, sessionId, state);+ if (signal?.aborted || Date.now() >= deadline || state.spent >= cap) break;+ emit(onProgress, { type: 'poll-sleep', ms: cfg(ctx, 'pollMs') });+ await abortableSleep(cfg(ctx, 'pollMs'), signal);+ }+ const reason = signal?.aborted ? 'aborted' : Date.now() >= deadline ? 'duration' : 'cap';+ return {+ success: true,+ output: `${dryRun ? 'Dry-run' : 'Copy-trade'} done (${reason}). Mirrored ${state.log.length} buys, spent ${state.spent} SOL.`,+ sentiment: 0.4,+ data: { spent: state.spent, mirrors: state.log, dryRun, sessionId, reason },+ };+ },+ });++ skills.register({+ name: 'pumpfun-rug-exit-watch',+ description: 'Watch held mints; auto-sell on top-holder concentration or dev-wallet sell triggers. Persists exited mints under sessionId.',+ instruction: 'rugExitWatch loop.',+ animationHint: 'concern',+ voicePattern: 'Watching {{mints.length}} positions…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mints: { type: 'array', items: { type: 'string' } },+ durationSec: { type: 'integer', minimum: 10, maximum: 86400 },+ sessionId: { type: 'string' },+ dryRun: { type: 'boolean' },+ },+ required: ['mints', 'durationSec'],+ },+ handler: async (args, ctx) => {+ const dryRun = !!args.dryRun;+ const onProgress = args.onProgress;+ const signal = args.signal;+ const sessionId = args.sessionId;+ const deadline = Date.now() + args.durationSec * 1000;+ const concentrationLimit = cfg(ctx, 'exitOnConcentrationPct');+ const devSellLimit = cfg(ctx, 'exitOnDevSellPct');+ const state = await loadState(ctx?.memory, sessionId, { exited: new Set(), log: [] });+ emit(onProgress, { type: 'start', mode: 'rug-exit-watch', mints: args.mints });++ while (!signal?.aborted && Date.now() < deadline && state.exited.size < args.mints.length) {+ for (const mint of args.mints) {+ if (signal?.aborted) break;+ if (state.exited.has(mint)) continue;+ const [holders, trades, details] = await Promise.all([+ mcp('getTokenHolders', { mint, limit: 10 }).catch(() => null),+ mcp('getTokenTrades', { mint, limit: 50 }).catch(() => null),+ mcp('getTokenDetails', { mint }).catch(() => null),+ ]);+ const top = holders?.topHolderPct ?? holders?.holders?.[0]?.pct ?? 0;+ const dev = details?.creator ?? details?.token?.creator;+ const devSells = (trades?.trades ?? trades ?? []).filter((t) => t.side === 'sell' && t.wallet === dev);+ const devSellPct = devSells.reduce((s, t) => s + (t.pctOfSupply ?? 0), 0);++ let trigger = null;+ if (top >= concentrationLimit) trigger = `top holder ${top}%`;+ else if (devSellPct >= devSellLimit) trigger = `dev sold ${devSellPct}%`;+ if (!trigger) {+ emit(onProgress, { type: 'tick', mint, top, devSellPct });+ continue;+ }++ try {+ const sell = await doSell(skills, ctx, dryRun, mint);+ if (sell.skipped === 'no-balance') {+ state.log.push({ mint, trigger, action: 'skipped-no-balance' });+ emit(onProgress, { type: 'skip', mint, reason: 'no-balance' });+ } else {+ state.exited.add(mint);+ state.log.push({ mint, trigger, sig: sell.signature, tokenAmount: sell.tokenAmount, dryRun });+ emit(onProgress, { type: dryRun ? 'dry-sell' : 'sell', mint, sig: sell.signature, trigger });+ }+ saveState(ctx?.memory, sessionId, state);+ } catch (e) {+ state.log.push({ mint, trigger, error: e.message });+ emit(onProgress, { type: 'error', mint, reason: e.message });+ }+ }+ saveState(ctx?.memory, sessionId, state);+ if (signal?.aborted || Date.now() >= deadline || state.exited.size >= args.mints.length) break;+ emit(onProgress, { type: 'poll-sleep', ms: cfg(ctx, 'pollMs') });+ await abortableSleep(cfg(ctx, 'pollMs'), signal);+ }+ const reason = signal?.aborted ? 'aborted' : Date.now() >= deadline ? 'duration' : 'all-exited';+ return {+ success: true,+ output: `Exit watch done (${reason}). Exited ${state.exited.size}/${args.mints.length} positions.`,+ sentiment: state.exited.size > 0 ? -0.2 : 0.2,+ data: { exited: [...state.exited], events: state.log, dryRun, sessionId, reason },+ };+ },+ });+}diff --git a/publish/src/agent-skills-pumpfun-hooks.js b/publish/src/agent-skills-pumpfun-hooks.jsnew file mode 100644index 000000000..f309111f8--- /dev/null+++ b/publish/src/agent-skills-pumpfun-hooks.js@@ -0,0 +1,96 @@+/**+ * Pump.fun protocol hooks+ * -----------------------+ * Subscribes to skill-done events on the agent protocol bus and writes+ * structured memories whenever a pump.fun-related skill succeeds. Lets the+ * agent answer "what's my token?" or "what was my last trade?" without the+ * user re-stating context every turn.+ *+ * Memory types written:+ * - project: launches (so the agent remembers its own coin)+ * - project: trades (recent buy/sell, capped)+ * - reference: payments (mint, currency, memo)+ *+ * Idempotent: re-attaching is safe — the hook tags entries with `pumpfun:*`+ * tags so dedupe logic in agent-memory can keep the latest only.+ */++import { ACTION_TYPES } from './agent-protocol.js';+import { MEMORY_TYPES } from './agent-memory.js';++const TAG_LAUNCH = 'pumpfun:launch';+const TAG_TRADE = 'pumpfun:trade';+const TAG_PAY = 'pumpfun:payment';++function shortMint(m) {+ return m ? `${String(m).slice(0, 6)}…${String(m).slice(-4)}` : '?';+}++/**+ * @param {import('./agent-protocol.js').AgentProtocol} protocol+ * @param {import('./agent-memory.js').AgentMemory} memory+ */+export function attachPumpFunMemoryHooks(protocol, memory) {+ if (!protocol || !memory || protocol._pumpfunHooked) return;+ protocol._pumpfunHooked = true;++ protocol.on(ACTION_TYPES.SKILL_DONE, (ev) => {+ const skill = ev.detail?.payload?.skill;+ const result = ev.detail?.payload?.result;+ if (!skill || !result?.success || !skill.startsWith('pumpfun-')) return;+ const data = result.data || {};++ try {+ if (skill === 'pumpfun-create' || skill === 'pumpfun-self-launch' ||+ skill === 'pumpfun-launch-from-agent' || skill === 'pumpfun-self-launch-from-identity') {+ memory.add({+ type: MEMORY_TYPES.PROJECT,+ content: `My pump.fun token: ${data.symbol || '?'} (${data.mint}) on ${data.network || 'mainnet'}.`,+ tags: [TAG_LAUNCH, `mint:${data.mint}`],+ context: {+ mint: data.mint,+ symbol: data.symbol,+ network: data.network,+ signature: data.signature,+ launchedAt: Date.now(),+ },+ salience: 1.0,+ });+ } else if (skill === 'pumpfun-buy' || skill === 'pumpfun-sell' ||+ skill === 'pumpfun-amm-buy' || skill === 'pumpfun-amm-sell' ||+ skill === 'pumpfun-self-swap') {+ const isBuy = skill.includes('buy') || data.side === 'buy';+ memory.add({+ type: MEMORY_TYPES.PROJECT,+ content: `${isBuy ? 'Bought' : 'Sold'} ${shortMint(data.mint)} on ${data.network || 'mainnet'}.`,+ tags: [TAG_TRADE, `mint:${data.mint}`],+ context: {+ mint: data.mint,+ side: isBuy ? 'buy' : 'sell',+ signature: data.signature,+ solAmount: data.solAmount,+ tradedAt: Date.now(),+ },+ salience: 0.6,+ });+ } else if (skill === 'pumpfun-accept-payment' || skill === 'pumpfun-self-pay') {+ memory.add({+ type: MEMORY_TYPES.REFERENCE,+ content: `Accepted payment ${data.amount || ''} for memo ${data.memo || '?'}.`,+ tags: [TAG_PAY],+ context: {+ agentMint: data.agentMint,+ currencyMint: data.currencyMint,+ amount: data.amount,+ memo: data.memo,+ signature: data.signature,+ paidAt: Date.now(),+ },+ salience: 0.5,+ });+ }+ } catch {+ // memory writes are best-effort+ }+ });+}diff --git a/publish/src/agent-skills-pumpfun-watch.js b/publish/src/agent-skills-pumpfun-watch.jsnew file mode 100644index 000000000..d5455d7e7--- /dev/null+++ b/publish/src/agent-skills-pumpfun-watch.js@@ -0,0 +1,230 @@+/**+ * Pump.fun watch skills+ * ---------------------+ * Read-only skills that let a Solana agent observe live pump.fun activity.+ * Pairs with /api/agents/pumpfun-feed (SSE) and the upstream pumpfun-claims-bot+ * MCP server.+ *+ * Skills registered:+ * - pumpfun-recent-claims → list the latest N claims with intel+ * - pumpfun-token-intel → enriched analysis of a specific mint+ * - pumpfun-watch-start → subscribe to live feed; agent reacts per event+ * - pumpfun-watch-stop → unsubscribe+ *+ * Reactions (handled inside watch-start) emit existing protocol events:+ * - first-time claim → emote celebration + speak the AI take+ * - fake claim → emote concern + warn+ * - graduation → gesture wave + speak+ *+ * No keys held. No transactions signed. Pure read + react.+ */++import { ACTION_TYPES } from './agent-protocol.js';++const FEED_PATH = '/api/agents/pumpfun-feed';+const TIER_BADGE = { mega: '🔥🔥', influencer: '🔥', notable: '⭐' };++const _state = {+ es: null,+ startedAt: 0,+ count: 0,+};++async function fetchJson(url) {+ const r = await fetch(url, { credentials: 'include' });+ if (!r.ok) throw new Error(`request failed: ${r.status}`);+ return r.json();+}++function summarizeClaim(ev) {+ const tier = ev.tier ? `${TIER_BADGE[ev.tier] || ''} ${ev.tier}` : '';+ const who = ev.github_user ? `@${ev.github_user}` : ev.claimer || 'unknown';+ const sol = ev.amount_sol != null ? `${Number(ev.amount_sol).toFixed(3)} SOL` : '—';+ return `${who} claimed ${sol} ${tier}`.trim();+}++/**+ * Register pump.fun watch skills onto an AgentSkills instance.+ * @param {import('./agent-skills.js').AgentSkills} skills+ */+export function registerPumpFunWatchSkills(skills) {+ skills.register({+ name: 'pumpfun-recent-claims',+ description: 'List the most recent pump.fun GitHub social-fee claims with intel.',+ instruction: 'Returns up to N enriched claim records. Read-only.',+ animationHint: 'curiosity',+ voicePattern: 'Pulling the last {{limit}} claims…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },+ },+ handler: async (args) => {+ const limit = Math.min(50, Math.max(1, Number(args?.limit) || 10));+ try {+ const data = await fetchJson(`/api/agents/pumpfun?op=claims&limit=${limit}`);+ const items = data?.items || [];+ return {+ success: true,+ output: items.length+ ? `Last ${items.length} claims:\n` + items.map(summarizeClaim).join('\n')+ : 'No claims found in feed.',+ sentiment: 0.2,+ data: { items },+ };+ } catch (err) {+ return { success: false, output: `Could not fetch claims: ${err.message}`, sentiment: -0.3 };+ }+ },+ });++ skills.register({+ name: 'pumpfun-token-intel',+ description: 'Get pump.fun token intel: graduation status, creator, holders, trust signals.',+ instruction: 'Read-only enrichment for a specific mint address.',+ animationHint: 'think',+ voicePattern: 'Analyzing {{mint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: { mint: { type: 'string', description: 'SPL mint pubkey (base58)' } },+ required: ['mint'],+ },+ handler: async (args) => {+ if (!args?.mint) return { success: false, output: 'mint required', sentiment: -0.2 };+ try {+ const data = await fetchJson(+ `/api/agents/pumpfun?op=token&mint=${encodeURIComponent(args.mint)}`,+ );+ const t = data || {};+ const lines = [+ t.name ? `${t.name}${t.symbol ? ` ($${t.symbol})` : ''}` : args.mint,+ t.graduated ? 'Graduated to PumpAMM' : `Curve progress: ${t.curve_progress ?? '—'}%`,+ t.creator ? `Creator: ${t.creator}` : null,+ t.warnings?.length ? `⚠️ ${t.warnings.join(', ')}` : null,+ ].filter(Boolean);+ return {+ success: true,+ output: lines.join('\n'),+ sentiment: t.warnings?.length ? -0.2 : 0.3,+ data: t,+ };+ } catch (err) {+ return { success: false, output: `Could not fetch intel: ${err.message}`, sentiment: -0.3 };+ }+ },+ });++ skills.register({+ name: 'pumpfun-watch-start',+ description: 'Subscribe to live pump.fun events; agent narrates and reacts as they arrive.',+ instruction: 'Opens an SSE stream. Emits speak/gesture/emote per event.',+ animationHint: 'curiosity',+ voicePattern: 'Watching pump.fun live.',+ mcpExposed: false, // browser-only — needs EventSource+ inputSchema: {+ type: 'object',+ properties: {+ kind: { type: 'string', enum: ['all', 'claims', 'graduations'], default: 'all' },+ minTier: { type: 'string', enum: ['notable', 'influencer', 'mega'] },+ },+ },+ handler: async (args, ctx) => {+ if (typeof window === 'undefined' || !window.EventSource) {+ return { success: false, output: 'Live watch requires a browser.', sentiment: -0.3 };+ }+ if (_state.es) {+ return { success: true, output: 'Already watching.', sentiment: 0.1 };+ }+ const params = new URLSearchParams();+ params.set('kind', args?.kind || 'all');+ if (args?.minTier) params.set('minTier', args.minTier);+ const url = `${FEED_PATH}?${params.toString()}`;++ _state.es = new EventSource(url, { withCredentials: true });+ _state.startedAt = Date.now();+ _state.count = 0;++ const protocol = ctx.protocol;+ const speak = (text, sentiment = 0) =>+ protocol?.emit({ type: ACTION_TYPES.SPEAK, payload: { text, sentiment } });+ const emote = (trigger, weight) =>+ protocol?.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger, weight } });+ const gesture = (name, duration = 1500) =>+ protocol?.emit({ type: ACTION_TYPES.GESTURE, payload: { name, duration } });++ _state.es.addEventListener('claim', (msg) => {+ _state.count++;+ const ev = safeJson(msg.data);+ if (!ev) return;+ if (ev.first_time_claim) {+ emote('celebration', 0.9);+ speak(+ `First-time claim! ${summarizeClaim(ev)}${ev.ai_take ? ` — ${ev.ai_take}` : ''}`,+ 0.7,+ );+ } else if (ev.fake_claim) {+ emote('concern', 0.7);+ speak(`Fake claim detected: ${summarizeClaim(ev)}`, -0.5);+ } else if (ev.tier) {+ emote('curiosity', 0.5);+ speak(summarizeClaim(ev), 0.2);+ }+ });++ _state.es.addEventListener('graduation', (msg) => {+ const ev = safeJson(msg.data);+ if (!ev) return;+ gesture('wave', 1500);+ speak(`Graduation: ${ev.symbol || ev.mint || 'a token'} hit PumpAMM.`, 0.6);+ });++ _state.es.addEventListener('error', () => {+ // EventSource auto-reconnects; surface only if it permanently closes.+ if (_state.es && _state.es.readyState === EventSource.CLOSED) {+ emote('concern', 0.4);+ _state.es = null;+ }+ });++ return {+ success: true,+ output: `Watching pump.fun (${args?.kind || 'all'}).`,+ sentiment: 0.4,+ };+ },+ });++ skills.register({+ name: 'pumpfun-watch-stop',+ description: 'Stop the live pump.fun watch.',+ instruction: 'Closes the SSE stream.',+ animationHint: 'patience',+ voicePattern: 'Stopping the watch.',+ mcpExposed: false,+ inputSchema: { type: 'object', properties: {} },+ handler: async () => {+ if (!_state.es) {+ return { success: true, output: 'Not currently watching.', sentiment: 0 };+ }+ _state.es.close();+ const seen = _state.count;+ _state.es = null;+ _state.count = 0;+ return {+ success: true,+ output: `Stopped. Saw ${seen} events.`,+ sentiment: 0.1,+ data: { events: seen },+ };+ },+ });+}++function safeJson(s) {+ try {+ return JSON.parse(s);+ } catch {+ return null;+ }+}diff --git a/publish/src/agent-skills-pumpfun.js b/publish/src/agent-skills-pumpfun.jsnew file mode 100644index 000000000..5bd3745c4--- /dev/null+++ b/publish/src/agent-skills-pumpfun.js@@ -0,0 +1,824 @@+/**+ * Pump.fun skills for Solana agents+ * ---------------------------------+ * Wraps the official @pump-fun SDKs so an agent can:+ * - launch a token (bonding curve) → pumpfun-create+ * - launch one auto-derived from identity → pumpfun-launch-from-agent+ * - trade on the curve → pumpfun-buy / pumpfun-sell+ * - trade on the AMM (post-graduation) → pumpfun-amm-buy / pumpfun-amm-sell+ * - read live curve state → pumpfun-status+ * - claim creator fees → pumpfun-claim-fees+ * - accept paid invocations → pumpfun-accept-payment+ *+ * Wallet: uses the same injected Solana wallet as src/erc8004/solana-deploy.js+ * (Phantom / Backpack / Solflare). All txs are signed by the agent owner;+ * this module never holds keys.+ *+ * SDKs are loaded lazily so non-Solana agents don't pay the import cost.+ */++import { detectSolanaWallet, SOLANA_RPC } from './erc8004/solana-deploy.js';++const DEFAULT_NETWORK = 'mainnet';+const DEFAULT_SLIPPAGE_BPS = 500;++async function loadCore() {+ const [pump, web3, BN, splToken] = await Promise.all([+ import('@pump-fun/pump-sdk'),+ import('@solana/web3.js'),+ import('bn.js').then((m) => m.default || m),+ import('@solana/spl-token').catch(() => null),+ ]);+ return { pump, web3, BN, splToken };+}++async function loadAmm() {+ const [amm, web3, BN] = await Promise.all([+ import('@pump-fun/pump-swap-sdk'),+ import('@solana/web3.js'),+ import('bn.js').then((m) => m.default || m),+ ]);+ return { amm, web3, BN };+}++async function loadAgentPayments() {+ const [pay, web3] = await Promise.all([+ import('@pump-fun/agent-payments-sdk'),+ import('@solana/web3.js'),+ ]);+ return { pay, web3 };+}++function getConnection(web3, network) {+ const url = SOLANA_RPC[network] || SOLANA_RPC[DEFAULT_NETWORK];+ return new web3.Connection(url, 'confirmed');+}++async function requireWallet() {+ const wallet = detectSolanaWallet();+ if (!wallet) throw new Error('No Solana wallet detected. Install Phantom to continue.');+ if (!wallet.isConnected) await wallet.connect();+ const pubkey = wallet.publicKey;+ if (!pubkey) throw new Error('Could not read Solana wallet address.');+ return { wallet, pubkey };+}++async function sendIxs({ web3, connection, wallet, payer, instructions, extraSigners = [] }) {+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();+ const tx = new web3.Transaction({ feePayer: payer, blockhash, lastValidBlockHeight });+ tx.add(...instructions);+ if (extraSigners.length) tx.partialSign(...extraSigners);+ const signed = await wallet.signTransaction(tx);+ const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false });+ await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight });+ return sig;+}++/**+ * Run the prep → wallet-sign → confirm round-trip against three.ws server-side+ * pump.fun endpoints. The server validates ownership + builds the unsigned tx;+ * the wallet only signs. Useful for clients that want server-enforced policy+ * (rate-limit, agent ownership) without re-implementing pump SDK glue.+ *+ * @param {Object} opts+ * @param {string} opts.prepPath — e.g. '/api/pump/buy-prep'+ * @param {Object} opts.body — request body for the prep endpoint+ * @param {string} [opts.confirmPath] — e.g. '/api/pump/launch-confirm'; if set,+ * calls confirm with `{ tx_signature, ...confirmExtra }`+ * @param {Object} [opts.confirmExtra] — additional fields to include in confirm body+ * @param {string} [opts.origin] — defaults to current page origin+ * @returns {Promise<{ signature: string, prep: Object, confirm: Object|null }>}+ */+export async function runServerFlow({+ prepPath,+ body,+ confirmPath,+ confirmExtra = {},+ origin = '',+}) {+ const [{ VersionedTransaction }] = await Promise.all([import('@solana/web3.js')]);+ const { wallet } = await requireWallet();+ const network = body.network || DEFAULT_NETWORK;++ const prepRes = await fetch(`${origin}${prepPath}`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ const prep = await prepRes.json();+ if (!prepRes.ok) {+ throw new Error(prep.error_description || prep.error || `prep failed: ${prepRes.status}`);+ }+ if (!prep.tx_base64) throw new Error('prep response missing tx_base64');++ const tx = VersionedTransaction.deserialize(+ Uint8Array.from(atob(prep.tx_base64), (c) => c.charCodeAt(0)),+ );+ const signed = await wallet.signTransaction(tx);++ const { Connection } = await import('@solana/web3.js');+ const url = SOLANA_RPC[network] || SOLANA_RPC[DEFAULT_NETWORK];+ const connection = new Connection(url, 'confirmed');+ const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false });+ const latest = await connection.getLatestBlockhash();+ await connection.confirmTransaction(+ {+ signature: sig,+ blockhash: latest.blockhash,+ lastValidBlockHeight: latest.lastValidBlockHeight,+ },+ 'confirmed',+ );++ let confirmJson = null;+ if (confirmPath) {+ const extra = typeof confirmExtra === 'function' ? confirmExtra(prep) : confirmExtra;+ const confirmRes = await fetch(`${origin}${confirmPath}`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ tx_signature: sig, ...extra }),+ });+ confirmJson = await confirmRes.json();+ if (!confirmRes.ok) {+ throw new Error(+ confirmJson.error_description ||+ confirmJson.error ||+ `confirm failed: ${confirmRes.status}`,+ );+ }+ }++ return { signature: sig, prep, confirm: confirmJson };+}++function deriveSymbol(name) {+ return (+ String(name || 'AGENT')+ .toUpperCase()+ .replace(/[^A-Z0-9]/g, '')+ .slice(0, 10) || 'AGENT'+ );+}++/**+ * Register pump.fun skills onto an AgentSkills instance.+ * @param {import('./agent-skills.js').AgentSkills} skills+ */+export function registerPumpFunSkills(skills) {+ // ── pumpfun-create ────────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-create',+ description:+ 'Launch a pump.fun token on Solana. Owner signs. Returns mint address + tx signature.',+ instruction: 'Mint a new pump.fun token using the official @pump-fun/pump-sdk.',+ animationHint: 'celebrate',+ voicePattern: 'Launching {{symbol}} on pump.fun…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ name: { type: 'string' },+ symbol: { type: 'string', description: '≤10 chars' },+ uri: { type: 'string', description: 'Metaplex metadata URI' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ initialBuySol: { type: 'number', description: 'Optional dev-buy in same tx (SOL)' },+ mintPublicKey: {+ type: 'string',+ description: 'Optional pre-ground vanity mint pubkey',+ },+ mintSecretKeyB64: {+ type: 'string',+ description: 'Base64 64-byte secret key paired with mintPublicKey',+ },+ },+ required: ['symbol', 'uri'],+ },+ handler: async (args, ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const tokenName = args.name || ctx.identity?.name || 'Agent';+ const symbol = deriveSymbol(args.symbol);++ const { pump, web3, BN } = await loadCore();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ let mintKeypair;+ if (args.mintPublicKey && args.mintSecretKeyB64) {+ const bin = atob(args.mintSecretKeyB64);+ const secret = Uint8Array.from(bin, (c) => c.charCodeAt(0));+ mintKeypair = web3.Keypair.fromSecretKey(secret);+ } else {+ mintKeypair = web3.Keypair.generate();+ }+ const offline = new pump.PumpSdk();+ let instructions;++ if (args.initialBuySol && args.initialBuySol > 0) {+ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const global = await onlineSdk.fetchGlobal();+ const solLamports = new BN(Math.floor(args.initialBuySol * web3.LAMPORTS_PER_SOL));+ instructions = await offline.createV2AndBuyInstructions({+ global,+ mint: mintKeypair.publicKey,+ name: tokenName,+ symbol,+ uri: args.uri,+ creator: pubkey,+ user: pubkey,+ amount: new BN(0),+ solAmount: solLamports,+ mayhemMode: false,+ });+ } else {+ instructions = [+ await offline.createV2Instruction({+ mint: mintKeypair.publicKey,+ name: tokenName,+ symbol,+ uri: args.uri,+ creator: pubkey,+ user: pubkey,+ mayhemMode: false,+ }),+ ];+ }++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions,+ extraSigners: [mintKeypair],+ });++ return {+ success: true,+ output: `Launched ${symbol} on pump.fun. Mint: ${mintKeypair.publicKey.toBase58()}`,+ sentiment: 0.9,+ data: {+ mint: mintKeypair.publicKey.toBase58(),+ signature: sig,+ network,+ name: tokenName,+ symbol,+ },+ };+ },+ });++ // ── pumpfun-launch-from-agent ─────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-launch-from-agent',+ description:+ 'One-shot: launch a pump.fun token whose metadata is auto-generated from this agent (name, GLB, bio).',+ instruction: 'Resolves the agent metadata URL, then calls pumpfun-create.',+ animationHint: 'celebrate',+ voicePattern: 'Launching myself on pump.fun…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ symbol: { type: 'string' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ initialBuySol: { type: 'number' },+ mintPublicKey: { type: 'string' },+ mintSecretKeyB64: { type: 'string' },+ },+ },+ handler: async (args, ctx) => {+ const id = ctx.identity?.id;+ if (!id) {+ return {+ success: false,+ output: 'No agent identity. Register the agent first.',+ sentiment: -0.3,+ };+ }+ const origin = (typeof window !== 'undefined' && window.location?.origin) || '';+ const uri = `${origin}/api/agents/pumpfun-metadata?id=${encodeURIComponent(id)}`;+ const symbol = args.symbol || deriveSymbol(ctx.identity?.name);+ return skills.perform(+ 'pumpfun-create',+ {+ name: ctx.identity?.name,+ symbol,+ uri,+ network: args.network,+ initialBuySol: args.initialBuySol,+ mintPublicKey: args.mintPublicKey,+ mintSecretKeyB64: args.mintSecretKeyB64,+ },+ ctx,+ );+ },+ });++ // ── pumpfun-buy ───────────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-buy',+ description: 'Buy a pump.fun token with SOL on the bonding curve.',+ instruction: 'Bonding-curve buy. Reverts if the token has graduated — use pumpfun-amm-buy.',+ animationHint: 'gesture',+ voicePattern: 'Buying {{solAmount}} SOL of {{mint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ solAmount: { type: 'number' },+ slippageBps: { type: 'number' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['mint', 'solAmount'],+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const slippageBps = args.slippageBps ?? DEFAULT_SLIPPAGE_BPS;++ if (args.serverFlow) {+ const { pubkey: pk } = await requireWallet();+ const r = await runServerFlow({+ prepPath: '/api/pump/buy-prep',+ body: {+ mint: args.mint,+ network,+ sol: args.solAmount,+ slippage_bps: slippageBps,+ wallet_address: pk.toBase58(),+ },+ confirmPath: '/api/pump/buy-confirm',+ confirmExtra: (prep) => ({+ mint: args.mint,+ network,+ wallet_address: pk.toBase58(),+ sol: args.solAmount,+ slippage_bps: slippageBps,+ route: prep.route,+ }),+ });+ const route = r.prep.route;+ return {+ success: true,+ output: `Bought ~${args.solAmount} SOL of ${args.mint.slice(0, 8)}… via ${route}.`,+ sentiment: 0.6,+ data: {+ signature: r.signature,+ route,+ mint: args.mint,+ network,+ tracked: r.confirm?.tracked,+ },+ };+ }++ const { pump, web3, BN } = await loadCore();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const mint = new web3.PublicKey(args.mint);+ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const offline = new pump.PumpSdk();++ const global = await onlineSdk.fetchGlobal();+ const state = await onlineSdk.fetchBuyState(mint, pubkey);+ const solLamports = new BN(Math.floor(args.solAmount * web3.LAMPORTS_PER_SOL));+ const expected = pump.getBuyTokenAmountFromSolAmount({+ global,+ feeConfig: null,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: solLamports,+ });++ const buyIxs = await offline.buyInstructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,+ associatedUserAccountInfo: state.associatedUserAccountInfo,+ mint,+ user: pubkey,+ amount: expected,+ solAmount: solLamports,+ slippage: slippageBps / 10_000,+ tokenProgram:+ web3.TOKEN_PROGRAM_ID || (await import('@solana/spl-token')).TOKEN_PROGRAM_ID,+ });++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: buyIxs,+ });+ return {+ success: true,+ output: `Bought ~${expected.toString()} units of ${args.mint.slice(0, 8)}… for ${args.solAmount} SOL.`,+ sentiment: 0.6,+ data: { signature: sig, mint: args.mint, solAmount: args.solAmount, network },+ };+ },+ });++ // ── pumpfun-sell ──────────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-sell',+ description: 'Sell a pump.fun token back to the bonding curve for SOL.',+ instruction: 'Bonding-curve sell. Reverts if graduated — use pumpfun-amm-sell.',+ animationHint: 'gesture',+ voicePattern: 'Selling {{tokenAmount}} of {{mint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ tokenAmount: { type: 'string', description: 'Base-unit integer string' },+ slippageBps: { type: 'number' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['mint', 'tokenAmount'],+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const slippageBps = args.slippageBps ?? DEFAULT_SLIPPAGE_BPS;++ if (args.serverFlow) {+ const { pubkey: pk } = await requireWallet();+ const r = await runServerFlow({+ prepPath: '/api/pump/sell-prep',+ body: {+ mint: args.mint,+ network,+ tokens: String(args.tokenAmount),+ slippage_bps: slippageBps,+ wallet_address: pk.toBase58(),+ },+ confirmPath: '/api/pump/sell-confirm',+ confirmExtra: (prep) => ({+ mint: args.mint,+ network,+ wallet_address: pk.toBase58(),+ tokens: String(args.tokenAmount),+ slippage_bps: slippageBps,+ route: prep.route,+ }),+ });+ const route = r.prep.route;+ return {+ success: true,+ output: `Sold ${args.tokenAmount} of ${args.mint.slice(0, 8)}… via ${route}.`,+ sentiment: 0.4,+ data: {+ signature: r.signature,+ route,+ mint: args.mint,+ network,+ tracked: r.confirm?.tracked,+ },+ };+ }++ const { pump, web3, BN } = await loadCore();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const mint = new web3.PublicKey(args.mint);+ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const offline = new pump.PumpSdk();+ const global = await onlineSdk.fetchGlobal();+ const state = await onlineSdk.fetchSellState(mint, pubkey);++ const tokenAmount = new BN(args.tokenAmount);+ const expectedSol = pump.getSellSolAmountFromTokenAmount({+ global,+ feeConfig: null,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: tokenAmount,+ });++ const sellIxs = await offline.sellInstructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,+ mint,+ user: pubkey,+ amount: tokenAmount,+ solAmount: expectedSol,+ slippage: slippageBps / 10_000,+ tokenProgram: (await import('@solana/spl-token')).TOKEN_PROGRAM_ID,+ mayhemMode: false,+ });++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: sellIxs,+ });+ return {+ success: true,+ output: `Sold ${args.tokenAmount} of ${args.mint.slice(0, 8)}…`,+ sentiment: 0.4,+ data: { signature: sig, mint: args.mint, network },+ };+ },+ });++ // ── pumpfun-status ────────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-status',+ description: 'Read live state for a pump.fun mint: market cap, graduation status.',+ instruction: 'Read-only. No wallet required.',+ animationHint: 'inspect',+ voicePattern: '{{mint}} status',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['mint'],+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const { pump, web3, splToken } = await loadCore();+ const connection = getConnection(web3, network);+ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const mint = new web3.PublicKey(args.mint);++ const curve = await onlineSdk.fetchBondingCurve(mint);+ const global = await onlineSdk.fetchGlobal();+ const graduated = !!curve.complete;+ const marketCap = pump.bondingCurveMarketCap({+ global,+ bondingCurve: curve,+ });++ let userBalance = '0';+ let owner = null;+ try {+ const wallet = detectSolanaWallet();+ if (wallet?.publicKey && splToken) {+ owner = wallet.publicKey;+ const ata = await splToken.getAssociatedTokenAddress(mint, owner);+ const acct = await connection.getTokenAccountBalance(ata).catch(() => null);+ userBalance = acct?.value?.amount ?? '0';+ }+ } catch {}++ return {+ success: true,+ output: graduated+ ? `Graduated to AMM. Market cap ~${marketCap.toString()} lamports.`+ : `On bonding curve. Market cap ~${marketCap.toString()} lamports.`,+ sentiment: graduated ? 0.7 : 0.2,+ data: {+ mint: args.mint,+ marketCap: marketCap.toString(),+ graduated,+ userBalance,+ owner: owner ? owner.toBase58() : null,+ network,+ },+ };+ },+ });++ // ── pumpfun-amm-buy ───────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-amm-buy',+ description: 'Buy a graduated pump.fun token from the AMM pool with SOL.',+ instruction: 'AMM buy via @pump-fun/pump-swap-sdk. Use after graduation.',+ animationHint: 'gesture',+ voicePattern: 'AMM buy {{solAmount}} SOL of {{mint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ solAmount: { type: 'number' },+ slippageBps: { type: 'number' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['mint', 'solAmount'],+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const slippage = (args.slippageBps ?? DEFAULT_SLIPPAGE_BPS) / 10_000;+ const { amm, web3, BN } = await loadAmm();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const mint = new web3.PublicKey(args.mint);+ const sdk = new amm.OnlinePumpAmmSdk(connection);+ const solLamports = new BN(Math.floor(args.solAmount * web3.LAMPORTS_PER_SOL));++ const ixs = await sdk.swapAutocompleteBaseFromQuote({+ pool: amm.canonicalPumpPoolPda(mint)[0],+ quote: solLamports,+ slippage,+ direction: 'quoteToBase',+ user: pubkey,+ });++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: Array.isArray(ixs) ? ixs : ixs.instructions || [],+ });++ return {+ success: true,+ output: `AMM-bought ${args.mint.slice(0, 8)}… for ${args.solAmount} SOL.`,+ sentiment: 0.6,+ data: { signature: sig, mint: args.mint, network },+ };+ },+ });++ // ── pumpfun-amm-sell ──────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-amm-sell',+ description: 'Sell a graduated pump.fun token to the AMM pool for SOL.',+ instruction: 'AMM sell via @pump-fun/pump-swap-sdk.',+ animationHint: 'gesture',+ voicePattern: 'AMM sell {{tokenAmount}} of {{mint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string' },+ tokenAmount: { type: 'string' },+ slippageBps: { type: 'number' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['mint', 'tokenAmount'],+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const slippage = (args.slippageBps ?? DEFAULT_SLIPPAGE_BPS) / 10_000;+ const { amm, web3, BN } = await loadAmm();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const mint = new web3.PublicKey(args.mint);+ const sdk = new amm.OnlinePumpAmmSdk(connection);+ const tokenAmount = new BN(args.tokenAmount);++ const ixs = await sdk.swapAutocompleteQuoteFromBase({+ pool: amm.canonicalPumpPoolPda(mint)[0],+ base: tokenAmount,+ slippage,+ direction: 'baseToQuote',+ user: pubkey,+ });++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: Array.isArray(ixs) ? ixs : ixs.instructions || [],+ });++ return {+ success: true,+ output: `AMM-sold ${args.tokenAmount} of ${args.mint.slice(0, 8)}…`,+ sentiment: 0.4,+ data: { signature: sig, mint: args.mint, network },+ };+ },+ });++ // ── pumpfun-claim-fees ────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-claim-fees',+ description:+ 'Claim accumulated creator fees from the agent-creator vault to the agent owner wallet.',+ instruction: 'Calls collectCoinCreatorFeeInstructions on OnlinePumpSdk.',+ animationHint: 'celebrate',+ voicePattern: 'Claiming creator fees…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: { network: { type: 'string', enum: ['mainnet', 'devnet'] } },+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const { pump, web3 } = await loadCore();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const onlineSdk = new pump.OnlinePumpSdk(connection);+ const balance = await onlineSdk.getCreatorVaultBalanceBothPrograms(pubkey);+ if (balance.isZero?.() || balance.toString() === '0') {+ return {+ success: true,+ output: 'No creator fees to claim right now.',+ sentiment: 0.1,+ data: { lamports: '0' },+ };+ }++ const ixs = await onlineSdk.collectCoinCreatorFeeInstructions(pubkey, pubkey);+ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: ixs,+ });+ return {+ success: true,+ output: `Claimed ${balance.toString()} lamports of creator fees.`,+ sentiment: 0.8,+ data: { signature: sig, lamports: balance.toString(), network },+ };+ },+ });++ // ── pumpfun-accept-payment ────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun-accept-payment',+ description:+ 'Accept a paid invocation of this agent via @pump-fun/agent-payments-sdk. Splits revenue per the on-chain sharing config.',+ instruction:+ 'Builds an accept_payment tx for a fixed price in a given currency mint. Caller signs as `user`.',+ animationHint: 'gesture',+ voicePattern: 'Invoicing {{amount}} for service {{memo}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ agentMint: {+ type: 'string',+ description: 'The agent token mint registered with PumpAgent',+ },+ currencyMint: {+ type: 'string',+ description: 'Currency mint (USDC, SOL wrapper, etc.)',+ },+ amount: {+ type: 'string',+ description: 'Amount in base units (string-encoded bigint)',+ },+ memo: { type: 'string', description: 'Invoice memo / nonce (uint)' },+ durationSeconds: { type: 'number', description: 'Validity window (default 600)' },+ network: { type: 'string', enum: ['mainnet', 'devnet'] },+ },+ required: ['agentMint', 'currencyMint', 'amount', 'memo'],+ },+ handler: async (args, _ctx) => {+ const network = args.network || DEFAULT_NETWORK;+ const duration = args.durationSeconds ?? 600;+ const { pay, web3 } = await loadAgentPayments();+ const { wallet, pubkey } = await requireWallet();+ const connection = getConnection(web3, network);++ const agentMint = new web3.PublicKey(args.agentMint);+ const currencyMint = new web3.PublicKey(args.currencyMint);+ const env = network === 'devnet' ? 'devnet' : 'mainnet-beta';++ const agent = new pay.PumpAgent(agentMint, env, connection);+ const now = Math.floor(Date.now() / 1000);++ const ixs = await agent.buildAcceptPaymentInstructions({+ user: pubkey,+ currencyMint,+ amount: args.amount,+ memo: args.memo,+ startTime: now,+ endTime: now + duration,+ });++ const sig = await sendIxs({+ web3,+ connection,+ wallet,+ payer: pubkey,+ instructions: ixs,+ });+ return {+ success: true,+ output: `Payment of ${args.amount} accepted. Memo ${args.memo}.`,+ sentiment: 0.7,+ data: {+ signature: sig,+ agentMint: args.agentMint,+ currencyMint: args.currencyMint,+ amount: args.amount,+ memo: args.memo,+ network,+ },+ };+ },+ });+}diff --git a/publish/src/agent-skills.js b/publish/src/agent-skills.jsnew file mode 100644index 000000000..de23ec020--- /dev/null+++ b/publish/src/agent-skills.js@@ -0,0 +1,459 @@+/**+ * Agent Skills+ * ------------+ * Skills are the things an agent can DO — and crucially, the things you can SEE it doing.+ * Each skill is: instruction + animation hint + voice template + handler.+ *+ * Same primitive shape as Claude's skill system (skill.md) — because agents are just JSON.+ * What makes these different: when they execute, the avatar PERFORMS them.+ *+ * MCP-exposed skills are also available as tools via /api/mcp.+ */++import { ACTION_TYPES } from './agent-protocol.js';+import { MEMORY_TYPES } from './agent-memory.js';+import { registerPumpFunSkills } from './agent-skills-pumpfun.js';+import { registerPumpFunWatchSkills } from './agent-skills-pumpfun-watch.js';+import { registerPumpFunAutonomousSkills } from './agent-skills-pumpfun-autonomous.js';+import { registerPumpFunComposeSkills } from './agent-skills-pumpfun-compose.js';+import { attachPumpFunMemoryHooks } from './agent-skills-pumpfun-hooks.js';++/**+ * @typedef {Object} SkillContext+ * @property {import('./agent-protocol.js').AgentProtocol} protocol+ * @property {import('./agent-memory.js').AgentMemory} memory+ * @property {import('./agent-identity.js').AgentIdentity} identity+ * @property {Object} [viewer] — Viewer instance if in browser+ * @property {boolean} isBrowser+ */++/**+ * @typedef {Object} SkillResult+ * @property {boolean} success+ * @property {string} output — text to speak / return+ * @property {number} [sentiment] — -1..1+ * @property {Object} [data] — structured result data+ */++/**+ * @typedef {Object} SkillDef+ * @property {string} name+ * @property {string} description+ * @property {string} instruction — human-readable behaviour spec+ * @property {string} animationHint — gesture name hint for avatar+ * @property {string} voicePattern — template with {{vars}}+ * @property {boolean} mcpExposed — available via MCP tools/call+ * @property {Object} [inputSchema] — JSON Schema for args+ * @property {(args: Object, ctx: SkillContext) => Promise<SkillResult>} handler+ */++export class AgentSkills {+ /**+ * @param {import('./agent-protocol.js').AgentProtocol} protocol+ * @param {import('./agent-memory.js').AgentMemory} memory+ */+ constructor(protocol, memory) {+ this.protocol = protocol;+ this.memory = memory;+ this._skills = new Map();++ this._registerBuiltins();+ registerPumpFunSkills(this);+ registerPumpFunWatchSkills(this);+ registerPumpFunAutonomousSkills(this);+ registerPumpFunComposeSkills(this);+ attachPumpFunMemoryHooks(protocol, memory);+ }++ // ── Registry ──────────────────────────────────────────────────────────────++ /** @param {SkillDef} def */+ register(def) {+ this._skills.set(def.name, def);+ }++ /** @param {string} name */+ unregister(name) {+ this._skills.delete(name);+ }++ /** @returns {SkillDef | undefined} */+ get(name) {+ return this._skills.get(name);+ }++ /** @returns {SkillDef[]} */+ list() {+ return [...this._skills.values()];+ }++ /** Returns MCP-compatible tool definitions for exposed skills */+ toMcpTools() {+ return this.list()+ .filter((s) => s.mcpExposed)+ .map((s) => ({+ name: `skill_${s.name.replace(/-/g, '_')}`,+ description: s.description,+ inputSchema: s.inputSchema || { type: 'object', properties: {} },+ }));+ }++ // ── Execution ─────────────────────────────────────────────────────────────++ /**+ * Perform a named skill — emits to protocol, executes handler.+ * @param {string} name+ * @param {Object} [args]+ * @param {Partial<SkillContext>} [ctx]+ * @returns {Promise<SkillResult>}+ */+ async perform(name, args = {}, ctx = {}) {+ const skill = this._skills.get(name);+ if (!skill) {+ return { success: false, output: `Unknown skill: ${name}`, sentiment: -0.3 };+ }++ const fullCtx = {+ protocol: this.protocol,+ memory: this.memory,+ identity: ctx.identity || null,+ viewer:+ ctx.viewer || (typeof window !== 'undefined' ? window.VIEWER?.app?.viewer : null),+ isBrowser: typeof window !== 'undefined',+ ...ctx,+ };++ // Announce the skill is starting+ this.protocol.emit({+ type: ACTION_TYPES.PERFORM_SKILL,+ payload: { skill: name, args, animationHint: skill.animationHint },+ agentId: fullCtx.identity?.id || 'default',+ sourceSkill: name,+ });++ try {+ const result = await skill.handler(args, fullCtx);+ this.protocol.emit({+ type: ACTION_TYPES.SKILL_DONE,+ payload: { skill: name, result },+ agentId: fullCtx.identity?.id || 'default',+ sourceSkill: name,+ });++ // Auto-speak the result if it has output text+ if (result.output && fullCtx.isBrowser) {+ this.protocol.emit({+ type: ACTION_TYPES.SPEAK,+ payload: { text: result.output, sentiment: result.sentiment ?? 0 },+ agentId: fullCtx.identity?.id || 'default',+ sourceSkill: name,+ });+ }++ return result;+ } catch (err) {+ const errResult = {+ success: false,+ output: `Skill failed: ${err.message}`,+ sentiment: -0.5,+ };+ this.protocol.emit({+ type: ACTION_TYPES.SKILL_ERROR,+ payload: { skill: name, error: err.message },+ agentId: fullCtx.identity?.id || 'default',+ sourceSkill: name,+ });+ return errResult;+ }+ }++ // ── Built-in Skills ───────────────────────────────────────────────────────++ _registerBuiltins() {+ // ── greet ──────────────────────────────────────────────────────────+ this.register({+ name: 'greet',+ description: 'Greet the user and introduce the agent',+ instruction: 'Say hello warmly, offer to help with 3D models or agent configuration',+ animationHint: 'wave',+ voicePattern: "Hey! I'm {{name}}, your three.ws. Drop a model or ask me anything.",+ mcpExposed: true,+ inputSchema: { type: 'object', properties: { userName: { type: 'string' } } },+ handler: async (args, ctx) => {+ const name = ctx.identity?.name || 'Agent';+ const userName = args.userName ? `, ${args.userName}` : '';+ return {+ success: true,+ output: `Hey${userName}! I'm ${name}. Drop a 3D model in or ask me anything — I can validate, present, and remember things about your work.`,+ sentiment: 0.8,+ };+ },+ });++ // ── present-model ─────────────────────────────────────────────────+ this.register({+ name: 'present-model',+ description: 'Narrate and present the currently loaded 3D model',+ instruction:+ 'Look at the model, describe its properties, gestures toward interesting features',+ animationHint: 'present',+ voicePattern: 'This model has {{vertices}} vertices, {{materials}} materials.',+ mcpExposed: true,+ inputSchema: { type: 'object', properties: {} },+ handler: async (_args, ctx) => {+ const viewer = ctx.viewer;+ if (!viewer || !viewer.content) {+ return {+ success: false,+ output: 'No model loaded yet. Drop a glTF or GLB file to get started.',+ sentiment: -0.1,+ };+ }++ let verts = 0,+ meshes = 0,+ mats = new Set();+ viewer.content.traverse((node) => {+ if (node.isMesh) {+ meshes++;+ if (node.geometry?.attributes?.position) {+ verts += node.geometry.attributes.position.count;+ }+ if (node.material) {+ const m = Array.isArray(node.material)+ ? node.material+ : [node.material];+ m.forEach((mat) => mats.add(mat.name || mat.uuid));+ }+ }+ });++ const clips = viewer.clips?.length || 0;+ const bones = (viewer.content.animations || []).length;+ const output = [+ `I'm looking at your model now.`,+ `It has ${verts.toLocaleString()} vertices across ${meshes} mesh${meshes !== 1 ? 'es' : ''},`,+ `${mats.size} material${mats.size !== 1 ? 's' : ''},`,+ clips+ ? `and ${clips} animation clip${clips !== 1 ? 's' : ''}.`+ : 'with no animations.',+ ].join(' ');++ // Look at model+ if (ctx.isBrowser) {+ ctx.protocol.emit({+ type: ACTION_TYPES.LOOK_AT,+ payload: { target: 'model' },+ agentId: ctx.identity?.id || 'default',+ });+ }++ return {+ success: true,+ output,+ sentiment: 0.4,+ data: { vertices: verts, meshes, materials: mats.size, clips },+ };+ },+ });++ // ── validate-model ────────────────────────────────────────────────+ this.register({+ name: 'validate-model',+ description: 'Run glTF validation and report results',+ instruction: 'Trigger the validator, summarise errors and warnings with empathy',+ animationHint: 'inspect',+ voicePattern: 'Validation found {{errors}} errors and {{warnings}} warnings.',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: { url: { type: 'string', description: 'Model URL to validate' } },+ },+ handler: async (_args, ctx) => {+ const viewer = ctx.viewer;+ if (!viewer || !viewer.content) {+ return {+ success: false,+ output: "Load a model first and I'll validate it.",+ sentiment: -0.1,+ };+ }++ // The validator runs automatically after load — read the last result from the DOM+ const reportEl = document.querySelector('.validator-toggle');+ if (reportEl) {+ const text = reportEl.textContent?.trim();+ const hasErrors = reportEl.classList.contains('errors');+ return {+ success: !hasErrors,+ output: text+ ? `Validation result: ${text}`+ : 'Validator is still running — check the bar at the bottom of the screen.',+ sentiment: hasErrors ? -0.5 : 0.6,+ };+ }++ return {+ success: true,+ output: 'The model loaded successfully. For detailed validation, check the bottom of the screen after loading.',+ sentiment: 0.3,+ };+ },+ });++ // ── remember ─────────────────────────────────────────────────────+ this.register({+ name: 'remember',+ description: 'Store a memory about the user, session, or project',+ instruction: 'Save important information for future conversations',+ animationHint: 'nod',+ voicePattern: "Got it. I'll remember that.",+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ required: ['content'],+ properties: {+ content: { type: 'string', description: 'What to remember' },+ type: { type: 'string', enum: ['user', 'feedback', 'project', 'reference'] },+ tags: { type: 'array', items: { type: 'string' } },+ },+ },+ handler: async (args, ctx) => {+ if (!args.content) {+ return { success: false, output: 'What should I remember?', sentiment: 0 };+ }++ const id = ctx.memory?.add({+ type: args.type || MEMORY_TYPES.PROJECT,+ content: args.content,+ tags: args.tags || [],+ });++ if (ctx.isBrowser) {+ ctx.protocol.emit({+ type: ACTION_TYPES.REMEMBER,+ payload: { content: args.content, memoryId: id },+ agentId: ctx.identity?.id || 'default',+ });+ }++ return {+ success: true,+ output: `Got it — I'll remember that.`,+ sentiment: 0.5,+ data: { memoryId: id },+ };+ },+ });++ // ── think ─────────────────────────────────────────────────────────+ this.register({+ name: 'think',+ description: 'Retrieve relevant memories and reason about a question',+ instruction: 'Search memory, synthesise context, respond thoughtfully',+ animationHint: 'think',+ voicePattern: 'Let me think about that...',+ mcpExposed: false,+ inputSchema: {+ type: 'object',+ required: ['query'],+ properties: { query: { type: 'string' } },+ },+ handler: async (args, ctx) => {+ const query = args.query || '';+ const memories = ctx.memory?.query({ limit: 5 }) || [];++ if (!memories.length) {+ return {+ success: true,+ output: `I don't have any stored context yet. As we work together, I'll build up memory to give you better answers.`,+ sentiment: 0.1,+ };+ }++ const context = memories.map((m) => `- ${m.content}`).join('\n');+ return {+ success: true,+ output: `Based on what I remember: ${memories[0].content}`,+ sentiment: 0.3,+ data: { memories, context },+ };+ },+ });++ // ── sign-action ───────────────────────────────────────────────────+ this.register({+ name: 'sign-action',+ description: "Sign the most recent action with the agent's linked wallet",+ instruction: 'Use ERC-191 personal_sign to create a verifiable proof of the action',+ animationHint: 'sign',+ voicePattern: 'Signing action {{actionId}} with my wallet.',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: { actionId: { type: 'string' } },+ },+ handler: async (args, ctx) => {+ if (!ctx.identity?.walletAddress) {+ return {+ success: false,+ output: 'No wallet linked. Connect a wallet first to sign actions.',+ sentiment: -0.2,+ };+ }++ if (!ctx.isBrowser || !window.ethereum) {+ return {+ success: false,+ output: 'No web3 wallet detected. Install MetaMask or a compatible wallet.',+ sentiment: -0.2,+ };+ }++ try {+ const { ethers } = await import('ethers');+ const provider = new ethers.BrowserProvider(window.ethereum);+ const signer = await provider.getSigner();+ const message = `Agent action: ${args.actionId || 'latest'} at ${Date.now()}`;+ const sig = await signer.signMessage(message);++ ctx.protocol.emit({+ type: ACTION_TYPES.SIGN,+ payload: { message, signature: sig, actionId: args.actionId },+ agentId: ctx.identity?.id || 'default',+ });++ return {+ success: true,+ output: `Action signed. Signature: ${sig.slice(0, 20)}…`,+ sentiment: 0.6,+ data: { signature: sig, message },+ };+ } catch (err) {+ return {+ success: false,+ output: `Signing failed: ${err.message}`,+ sentiment: -0.4,+ };+ }+ },+ });++ // ── help ──────────────────────────────────────────────────────────+ this.register({+ name: 'help',+ description: 'List available skills and controls',+ instruction: 'Summarise what the agent can do',+ animationHint: 'gesture',+ voicePattern: "Here's what I can do.",+ mcpExposed: false,+ handler: async (_args, _ctx) => {+ return {+ success: true,+ output: "I can present and validate 3D models, remember things about your work, sign actions with a wallet, and answer questions. Try dropping a GLB file in, or ask me to present what's loaded.",+ sentiment: 0.5,+ };+ },+ });+ }+}diff --git a/publish/src/agent-solana-wallet.js b/publish/src/agent-solana-wallet.jsnew file mode 100644index 000000000..6624d3950--- /dev/null+++ b/publish/src/agent-solana-wallet.js@@ -0,0 +1,529 @@+/**+ * Agent Solana wallet — provisioning UI + client.+ *+ * Owner-only card on the agent home panel. Two flows:+ * 1. Random wallet → POST /api/agents/:id/solana with empty body.+ * 2. Vanity wallet → grind in-browser (or accept a CLI-ground keypair+ * via the paste field) then POST { secret_key,+ * vanity_prefix }. Server verifies and stores the+ * encrypted secret.+ *+ * On mount the card pulls fresh state from GET /api/agents/:id/solana.+ * Server-side ownership is enforced; a 403 hides the card. A 404 means+ * no wallet yet → show the provisioning UI.+ *+ * Existing wallets are non-destructive: a "Replace" button calls DELETE first.+ */++import { openVanityModal } from './erc8004/vanity-modal.js';+import { grindVanity } from './solana/vanity/grinder.js';++const ENDPOINT = (id, qs = '') =>+ `/api/agents/${encodeURIComponent(id)}/solana${qs ? `?${qs}` : ''}`;++/**+ * Fetch current wallet state from the server.+ * @returns {Promise<{ status: 'ok'|'none'|'forbidden'|'error',+ * data?: { address: string, lamports: number|null, sol: number|null,+ * vanity_prefix: string|null, source: string|null, network: string },+ * error?: string }>}+ */+export async function fetchAgentSolanaWallet(agentId, network = 'mainnet') {+ const resp = await fetch(ENDPOINT(agentId, `network=${encodeURIComponent(network)}`), {+ credentials: 'include',+ });+ if (resp.status === 403) return { status: 'forbidden' };+ const json = await resp.json().catch(() => ({}));+ if (resp.status === 404) return { status: 'none' };+ if (!resp.ok) return { status: 'error', error: json?.error?.message || `HTTP ${resp.status}` };+ return { status: 'ok', data: json.data };+}++/**+ * Provision (or replace) the agent's Solana wallet.+ *+ * @param {object} opts+ * @param {string} opts.agentId+ * @param {string} [opts.vanityPrefix] — base58 prefix to grind for.+ * @param {Uint8Array} [opts.preGround] — pre-ground 64-byte secret key.+ * @param {AbortSignal} [opts.signal]+ * @param {(p: { rate: number, attempts: number, eta: string }) => void} [opts.onProgress]+ * @returns {Promise<{ address: string, source: string, vanity_prefix: string|null }>}+ */+export async function provisionAgentSolanaWallet({+ agentId,+ vanityPrefix = '',+ preGround = null,+ signal,+ onProgress,+} = {}) {+ if (!agentId) throw new Error('agentId required');++ let body = null;+ if (preGround) {+ body = {+ secret_key: Array.from(preGround),+ ...(vanityPrefix ? { vanity_prefix: vanityPrefix } : {}),+ };+ } else if (vanityPrefix) {+ const ground = await grindVanity({ prefix: vanityPrefix, signal, onProgress });+ body = {+ secret_key: Array.from(ground.secretKey),+ vanity_prefix: vanityPrefix,+ };+ }++ const resp = await fetch(ENDPOINT(agentId), {+ method: 'POST',+ credentials: 'include',+ headers: body ? { 'Content-Type': 'application/json' } : {},+ body: body ? JSON.stringify(body) : undefined,+ signal,+ });+ const json = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ const msg = json?.error?.message || json?.message || `provision failed (${resp.status})`;+ const err = new Error(msg);+ err.status = resp.status;+ throw err;+ }+ return json.data;+}++export async function deleteAgentSolanaWallet(agentId) {+ const resp = await fetch(ENDPOINT(agentId), { method: 'DELETE', credentials: 'include' });+ if (!resp.ok) {+ const j = await resp.json().catch(() => ({}));+ throw new Error(j?.error?.message || `delete failed (${resp.status})`);+ }+}++/** Fetch the agent wallet's recent on-chain activity. */+export async function fetchAgentSolanaActivity(agentId, network = 'mainnet', limit = 10) {+ const url = `/api/agents/${encodeURIComponent(agentId)}/solana/activity?network=${encodeURIComponent(network)}&limit=${limit}`;+ const resp = await fetch(url, { credentials: 'include' });+ if (!resp.ok) {+ const j = await resp.json().catch(() => ({}));+ throw new Error(j?.error_description || j?.error?.message || `activity fetch failed (${resp.status})`);+ }+ const json = await resp.json();+ return json.data;+}++/** Request a 1 SOL devnet airdrop into the agent's wallet. */+export async function requestAgentSolanaAirdrop(agentId) {+ const url = `/api/agents/${encodeURIComponent(agentId)}/solana/airdrop`;+ const resp = await fetch(url, { method: 'POST', credentials: 'include' });+ const json = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ throw new Error(json?.error_description || json?.error?.message || `airdrop failed (${resp.status})`);+ }+ return json.data;+}++// ── UI card ─────────────────────────────────────────────────────────────────++const STYLE = `+.agent-sol-wallet { border: 1px solid #e6e6ea; border-radius: 10px; padding: .85rem 1rem; margin: .85rem 0; font: 13px/1.4 system-ui, sans-serif; background: #fff; }+.agent-sol-wallet h3 { margin: 0 0 .25rem; font-size: .95rem; font-weight: 600; color: #1a1a1a; }+.agent-sol-wallet .sub { color: #666; font-size: .78rem; margin: 0 0 .65rem; }+.agent-sol-wallet .addr { font-family: ui-monospace, monospace; font-size: .8rem; background: #f7f7f8; padding: .4rem .55rem; border-radius: 5px; word-break: break-all; }+.agent-sol-wallet .addr .pfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 2px; border-radius: 2px; font-weight: 600; }+.agent-sol-wallet .row { display: flex; gap: .5rem; align-items: center; margin-top: .65rem; flex-wrap: wrap; }+.agent-sol-wallet button { font: inherit; padding: .4rem .8rem; border-radius: 6px; border: 1px solid #ccc; background: #fff; cursor: pointer; }+.agent-sol-wallet button.primary { background: #111; color: #fff; border-color: #111; }+.agent-sol-wallet button:disabled { opacity: .5; cursor: not-allowed; }+.agent-sol-wallet .progress { font-size: .75rem; color: #555; margin-top: .55rem; font-family: ui-monospace, monospace; }+.agent-sol-wallet .err { color: #b71c1c; font-size: .75rem; margin-top: .5rem; }+.agent-sol-wallet .src { font-size: .7rem; color: #888; margin-left: .35rem; }+.agent-sol-wallet .balance { display: flex; align-items: center; gap: .5rem; margin-top: .55rem; font-size: .8rem; color: #333; }+.agent-sol-wallet .balance .sol { font-family: ui-monospace, monospace; font-weight: 600; }+.agent-sol-wallet .balance .net { margin-left: auto; font-size: .7rem; }+.agent-sol-wallet .balance select { font: inherit; font-size: .7rem; padding: .15rem .25rem; border: 1px solid #ddd; border-radius: 4px; background: #fff; }+.agent-sol-wallet .skel { color: #999; font-size: .75rem; padding: .35rem 0; }+.agent-sol-wallet .activity { margin-top: .65rem; border-top: 1px solid #f0f0f0; padding-top: .5rem; }+.agent-sol-wallet .activity-h { font-size: .72rem; color: #888; text-transform: uppercase; letter-spacing: .05em; margin-bottom: .35rem; display: flex; align-items: center; gap: .35rem; }+.agent-sol-wallet .activity-h button { padding: .1rem .4rem; font-size: .7rem; line-height: 1; }+.agent-sol-wallet .activity-row { display: flex; align-items: center; gap: .5rem; font-size: .75rem; padding: .25rem 0; border-bottom: 1px dashed #eee; }+.agent-sol-wallet .activity-row:last-child { border-bottom: none; }+.agent-sol-wallet .activity-row .sig { font-family: ui-monospace, monospace; color: #555; }+.agent-sol-wallet .activity-row .delta { font-family: ui-monospace, monospace; margin-left: auto; }+.agent-sol-wallet .activity-row .delta.pos { color: #1b5e20; }+.agent-sol-wallet .activity-row .delta.neg { color: #c62828; }+.agent-sol-wallet .activity-row .ts { color: #999; font-size: .7rem; }+.agent-sol-wallet .activity-empty { color: #aaa; font-size: .75rem; padding: .35rem 0; }+.agent-sol-wallet .badge-airdrop { background: #e7f5e9; color: #1b5e20; padding: .1rem .45rem; border-radius: 999px; font-size: .65rem; font-weight: 600; margin-left: .35rem; }+`;++let _styleInjected = false;+function _injectStyle() {+ if (_styleInjected || typeof document === 'undefined') return;+ const tag = document.createElement('style');+ tag.id = 'agent-sol-wallet-style';+ tag.textContent = STYLE;+ document.head.appendChild(tag);+ _styleInjected = true;+}++function _esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ })[c]);+}++function _shortSig(sig) { return sig ? `${sig.slice(0, 6)}…${sig.slice(-4)}` : ''; }+function _ago(ts) {+ if (!ts) return '';+ const sec = Math.max(0, Math.floor(Date.now() / 1000 - ts));+ if (sec < 60) return `${sec}s ago`;+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;+ return `${Math.floor(sec / 86400)}d ago`;+}+function _explorerTxUrl(sig, network) {+ return network === 'devnet'+ ? `https://explorer.solana.com/tx/${sig}?cluster=devnet`+ : `https://solscan.io/tx/${sig}`;+}+function _renderActivityRow(a, network) {+ const sigShort = _shortSig(a.signature);+ const url = _explorerTxUrl(a.signature, network);+ const delta = a.sol_delta;+ let deltaCls = '', deltaText = '—';+ if (typeof delta === 'number') {+ deltaCls = delta > 0 ? 'pos' : delta < 0 ? 'neg' : '';+ deltaText = `${delta > 0 ? '+' : ''}${delta.toFixed(4)} SOL`;+ }+ const failed = a.success === false ? '<span class="ts" style="color:#c62828">·failed</span>' : '';+ const summary = a.summary ? `<span class="ts">· ${_esc(a.summary)}</span>` : '';+ return `+ <div class="activity-row">+ <a class="sig" href="${_esc(url)}" target="_blank" rel="noopener">${_esc(sigShort)}</a>+ <span class="ts">${_esc(_ago(a.block_time))}</span>+ ${summary}${failed}+ <span class="delta ${deltaCls}">${_esc(deltaText)}</span>+ </div>`;+}++/**+ * Mount the wallet card into the agent home panel.+ *+ * @param {object} opts+ * @param {HTMLElement} opts.panel+ * @param {{ id: string, name?: string, meta?: object, solana_address?: string }} opts.identity+ * @param {(data: { address: string, vanity_prefix: string|null, source: string }) => void} [opts.onProvisioned]+ */+export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {+ if (!panel || !identity?.id) return null;+ _injectStyle();++ const root = document.createElement('section');+ root.className = 'agent-sol-wallet';+ root.hidden = true; // unhide once we know the user is allowed to see it+ panel.appendChild(root);++ let state = {+ loaded: false,+ address: null,+ vanityPrefix: null,+ source: null,+ network: 'mainnet',+ sol: null,+ lamports: null,+ busy: false,+ progress: null,+ err: null,+ activity: [],+ activityLoaded: false,+ airdropping: false,+ airdropMsg: null,+ };+ let abort = null;+ let balanceTimer = null;++ async function loadFromServer() {+ const r = await fetchAgentSolanaWallet(identity.id, state.network);+ if (r.status === 'forbidden') {+ root.remove();+ return false;+ }+ root.hidden = false;+ if (r.status === 'ok') {+ state.address = r.data.address;+ state.vanityPrefix = r.data.vanity_prefix || null;+ state.source = r.data.source || null;+ state.lamports = r.data.lamports;+ state.sol = r.data.sol;+ _propagate(identity, r.data);+ } else if (r.status === 'none') {+ state.address = null;+ } else {+ state.err = r.error || 'failed to load wallet';+ }+ state.loaded = true;+ render();+ return true;+ }++ async function refreshBalance() {+ if (!state.address) return;+ const r = await fetchAgentSolanaWallet(identity.id, state.network);+ if (r.status === 'ok') {+ state.lamports = r.data.lamports;+ state.sol = r.data.sol;+ render();+ }+ }++ function startBalancePoll() {+ stopBalancePoll();+ balanceTimer = setInterval(refreshBalance, 30_000);+ }+ function stopBalancePoll() {+ if (balanceTimer) clearInterval(balanceTimer);+ balanceTimer = null;+ }++ async function refreshActivity() {+ if (!state.address) return;+ try {+ const data = await fetchAgentSolanaActivity(identity.id, state.network, 10);+ state.activity = data?.signatures || [];+ state.activityLoaded = true;+ const host = root.querySelector('[data-host="activity-list"]');+ if (host) {+ host.innerHTML = state.activity.length+ ? state.activity.map((a) => _renderActivityRow(a, state.network)).join('')+ : '<div class="activity-empty">No on-chain activity yet.</div>';+ }+ } catch (e) {+ state.activityLoaded = true;+ const host = root.querySelector('[data-host="activity-list"]');+ if (host) host.innerHTML = `<div class="activity-empty" style="color:#b71c1c">Could not load activity: ${_esc(e.message)}</div>`;+ }+ }++ async function onAirdrop() {+ state.airdropping = true;+ state.airdropMsg = 'Requesting devnet airdrop…';+ state.err = null;+ render();+ try {+ const data = await requestAgentSolanaAirdrop(identity.id);+ state.airdropMsg = `Airdrop confirmed: +${data.sol} SOL`;+ // Wait a moment for RPC to reflect, then refresh.+ setTimeout(() => {+ refreshBalance();+ refreshActivity();+ state.airdropMsg = null;+ render();+ }, 1500);+ } catch (e) {+ state.err = e.message;+ state.airdropMsg = null;+ } finally {+ state.airdropping = false;+ render();+ }+ }++ function render() {+ if (!state.loaded) {+ root.innerHTML = `<div class="skel">Loading Solana wallet…</div>`;+ return;+ }+ if (state.address) {+ const pfx = state.vanityPrefix || '';+ const rest = state.address.slice(pfx.length);+ const solDisplay = state.sol == null ? '—' : `${state.sol.toFixed(4)} SOL`;+ const isDevnet = state.network === 'devnet';+ root.innerHTML = `+ <h3>Solana wallet${state.source ? `<span class="src">· ${_esc(state.source)}</span>` : ''}</h3>+ <div class="addr"><span class="pfx">${_esc(pfx)}</span>${_esc(rest)}</div>+ <div class="balance">+ <span class="sol">${_esc(solDisplay)}</span>+ <span class="net">+ <select data-act="network" aria-label="Network">+ <option value="mainnet" ${state.network === 'mainnet' ? 'selected' : ''}>Mainnet</option>+ <option value="devnet" ${state.network === 'devnet' ? 'selected' : ''}>Devnet</option>+ </select>+ </span>+ </div>+ <div class="row">+ <button data-act="copy">Copy</button>+ <button data-act="explorer">Explorer ↗</button>+ ${isDevnet ? `<button data-act="airdrop" ${state.airdropping ? 'disabled' : ''}>${state.airdropping ? 'Requesting…' : 'Airdrop 1 SOL'}</button>` : ''}+ <button data-act="refresh-activity">Refresh</button>+ <button data-act="replace">Replace</button>+ </div>+ ${state.airdropMsg ? `<div class="progress">${_esc(state.airdropMsg)}</div>` : ''}+ ${state.err ? `<div class="err">${_esc(state.err)}</div>` : ''}+ <div class="activity" data-host="activity">+ <div class="activity-h">Recent activity <button data-act="refresh-activity-mini" type="button">↻</button></div>+ <div data-host="activity-list">+ ${state.activityLoaded+ ? (state.activity.length+ ? state.activity.map((a) => _renderActivityRow(a, state.network)).join('')+ : '<div class="activity-empty">No on-chain activity yet.</div>')+ : '<div class="activity-empty">Loading…</div>'}+ </div>+ </div>+ `;+ root.querySelector('[data-act="copy"]').addEventListener('click', (e) => {+ navigator.clipboard?.writeText(state.address).catch(() => {});+ e.currentTarget.textContent = 'Copied';+ setTimeout(() => { const b = root.querySelector('[data-act="copy"]'); if (b) b.textContent = 'Copy'; }, 1200);+ });+ root.querySelector('[data-act="explorer"]').addEventListener('click', () => {+ const cluster = isDevnet ? '?cluster=devnet' : '';+ window.open(`https://explorer.solana.com/address/${state.address}${cluster}`, '_blank', 'noopener');+ });+ root.querySelector('[data-act="replace"]').addEventListener('click', onReplace);+ root.querySelector('[data-act="network"]').addEventListener('change', (e) => {+ state.network = e.target.value;+ state.activityLoaded = false;+ state.activity = [];+ refreshBalance();+ refreshActivity();+ });+ root.querySelector('[data-act="refresh-activity"]')?.addEventListener('click', () => {+ refreshBalance();+ refreshActivity();+ });+ root.querySelector('[data-act="refresh-activity-mini"]')?.addEventListener('click', () => {+ refreshActivity();+ });+ if (isDevnet) {+ root.querySelector('[data-act="airdrop"]').addEventListener('click', onAirdrop);+ }+ startBalancePoll();+ if (!state.activityLoaded) refreshActivity();+ return;+ }+ stopBalancePoll();++ root.innerHTML = `+ <h3>Solana wallet</h3>+ <p class="sub">Provision a wallet for this agent. Optionally pick a vanity prefix.</p>+ <div class="row">+ <button class="primary" data-act="vanity" ${state.busy ? 'disabled' : ''}>+ ${state.busy ? 'Working…' : 'Choose vanity prefix'}+ </button>+ <button data-act="random" ${state.busy ? 'disabled' : ''}>Random</button>+ </div>+ ${state.progress ? `<div class="progress">grinding… ${_esc(formatRate(state.progress.rate))}/s · eta ${_esc(state.progress.eta)} <button data-act="cancel">cancel</button></div>` : ''}+ ${state.err ? `<div class="err">${_esc(state.err)}</div>` : ''}+ `;+ root.querySelector('[data-act="vanity"]')?.addEventListener('click', onVanity);+ root.querySelector('[data-act="random"]')?.addEventListener('click', onRandom);+ root.querySelector('[data-act="cancel"]')?.addEventListener('click', () => abort?.abort());+ }++ async function onRandom() {+ state.busy = true; state.err = null; render();+ try {+ const data = await provisionAgentSolanaWallet({ agentId: identity.id });+ state.address = data.address;+ state.vanityPrefix = data.vanity_prefix || null;+ state.source = data.source || 'generated';+ state.lamports = data.lamports ?? 0;+ state.sol = data.sol ?? 0;+ _propagate(identity, data);+ onProvisioned?.(data);+ refreshBalance();+ } catch (e) {+ state.err = e.message;+ } finally {+ state.busy = false; render();+ }+ }++ async function onVanity() {+ const choice = await openVanityModal({+ agentName: identity.name || '',+ initial: state.vanityPrefix || '',+ });+ if (choice == null || choice === '') return; // dismissed or "skip"++ const prefix = typeof choice === 'string' ? choice : choice.prefix;+ const preGround = typeof choice === 'object' ? choice.secretKey : null;++ state.busy = true; state.err = null; state.progress = null; render();+ abort = new AbortController();+ try {+ const data = await provisionAgentSolanaWallet({+ agentId: identity.id,+ vanityPrefix: prefix,+ preGround,+ signal: abort.signal,+ onProgress: (p) => { state.progress = p; render(); },+ });+ state.address = data.address;+ state.vanityPrefix = data.vanity_prefix || prefix || null;+ state.source = data.source || 'imported_vanity';+ state.lamports = data.lamports ?? 0;+ state.sol = data.sol ?? 0;+ state.progress = null;+ _propagate(identity, data);+ onProvisioned?.(data);+ refreshBalance();+ } catch (e) {+ state.err = e.name === 'AbortError' ? 'cancelled' : e.message;+ state.progress = null;+ } finally {+ state.busy = false; abort = null; render();+ }+ }++ async function onReplace() {+ if (!confirm('Replace the existing Solana wallet? The old key will be discarded — funds will be lost if not transferred first.')) return;+ state.busy = true; state.err = null; render();+ try {+ await deleteAgentSolanaWallet(identity.id);+ state.address = null;+ state.vanityPrefix = null;+ state.source = null;+ state.lamports = null;+ state.sol = null;+ _propagate(identity, { address: null, vanity_prefix: null, source: null });+ } catch (e) {+ state.err = e.message;+ } finally {+ state.busy = false; render();+ }+ }++ render();+ loadFromServer().catch((e) => {+ state.err = e.message || 'failed to load wallet';+ state.loaded = true;+ root.hidden = false;+ render();+ });++ return {+ destroy: () => {+ stopBalancePoll();+ abort?.abort();+ root.remove();+ },+ };+}++function _propagate(identity, data) {+ if (!identity || !data) return;+ identity.solana_address = data.address;+ identity.meta = {+ ...(identity.meta || {}),+ solana_address: data.address,+ solana_vanity_prefix: data.vanity_prefix || null,+ solana_wallet_source: data.source || null,+ };+}++function formatRate(n) {+ if (!n) return '0';+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;+ return Math.round(n).toString();+}diff --git a/publish/src/agents-directory.js b/publish/src/agents-directory.jsnew file mode 100644index 000000000..d2288887c--- /dev/null+++ b/publish/src/agents-directory.js@@ -0,0 +1,285 @@+/**+ * Public agents directory controller.+ *+ * Manages fetching, caching, filtering, and sorting of registered agents.+ * Uses on-chain data from IdentityRegistry with optional backend metadata.+ */++import {+ listRegisteredEvents,+ getAgentOnchain,+ fetchAgentMetadata,+ findAvatar3D,+} from './erc8004/queries.js';+import { CHAIN_META } from './erc8004/chain-meta.js';+import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++const CACHE_TTL_MS = 60000; // 60s SWR cache+const ITEMS_PER_PAGE = 30;++export class AgentsDirectory {+ constructor(containerSelector) {+ this.container = document.querySelector(containerSelector);+ if (!this.container) throw new Error(`Container not found: ${containerSelector}`);+ this.agents = []; // All loaded agents+ this.displayedAgents = []; // Filtered agents for current page+ this.currentPage = 1;+ this.filters = {+ chain: 'all',+ search: '',+ sort: 'newest',+ };+ this.cache = new Map(); // Per-page caches: `${chain}:${page}` → { data, time }+ this.cardClickHandler = null;+ this.lazyObserver = null;+ }++ /**+ * Load agents for a given chain, page, and filters.+ * @param {object} opts+ * @param {string} [opts.chain='all'] Chain filter: 'all', 'base', 'base-sepolia', etc.+ * @param {string} [opts.search=''] Search term (name/id)+ * @param {string} [opts.sort='newest'] Sort key: 'newest', 'name', 'oldest'+ * @param {number} [opts.page=1] Page number (1-indexed)+ * @returns {Promise<{ agents: Array, totalPages: number, total: number }>}+ */+ async load({ chain = 'all', search = '', sort = 'newest', page = 1 } = {}) {+ this.filters = { chain, search, sort };+ this.currentPage = page;++ // Check cache+ const cacheKey = `${chain}:${page}:${search}:${sort}`;+ const cached = this.cache.get(cacheKey);+ if (cached && Date.now() - cached.time < CACHE_TTL_MS) {+ this.displayedAgents = cached.data;+ const totalPages = Math.ceil(this.agents.length / ITEMS_PER_PAGE);+ return { agents: this.displayedAgents, totalPages, total: this.agents.length };+ }++ // Fetch all agents if not already loaded+ if (this.agents.length === 0) {+ await this._fetchAllAgents();+ }++ // Apply filters and sorting+ let filtered = this._applyFilters();+ filtered = this._applySorting(filtered);++ // Paginate+ const totalPages = Math.ceil(filtered.length / ITEMS_PER_PAGE);+ const offset = (page - 1) * ITEMS_PER_PAGE;+ this.displayedAgents = filtered.slice(offset, offset + ITEMS_PER_PAGE);++ // Cache result+ this.cache.set(cacheKey, { data: this.displayedAgents, time: Date.now() });++ return { agents: this.displayedAgents, totalPages, total: filtered.length };+ }++ /**+ * Register a callback for card clicks.+ * @param {Function} fn Called with agent object when card is clicked+ */+ onCardClick(fn) {+ this.cardClickHandler = fn;+ }++ /**+ * Set up lazy loading for avatar thumbnails.+ */+ setupLazyLoad() {+ if (!('IntersectionObserver' in window)) return;+ this.lazyObserver = new IntersectionObserver((entries) => {+ for (const entry of entries) {+ if (!entry.isIntersecting) continue;+ const img = entry.target;+ const src = img.dataset.src;+ if (src) {+ img.src = src;+ img.removeAttribute('data-src');+ this.lazyObserver.unobserve(img);+ }+ }+ });+ // Observe on next render+ requestAnimationFrame(() => {+ this.container+ .querySelectorAll('img[data-src]')+ .forEach((img) => this.lazyObserver.observe(img));+ });+ }++ /**+ * Render agent cards as HTML. Call after load().+ */+ render() {+ const html = this.displayedAgents.map((agent) => this._renderCard(agent)).join('');+ this.container.innerHTML = html;+ this._attachEventListeners();+ this.setupLazyLoad();+ }++ /**+ * Return pagination info for current state.+ */+ getPaginationInfo() {+ const totalPages = Math.ceil(this._applyFilters().length / ITEMS_PER_PAGE);+ return {+ page: this.currentPage,+ totalPages,+ itemsPerPage: ITEMS_PER_PAGE,+ hasNextPage: this.currentPage < totalPages,+ hasPrevPage: this.currentPage > 1,+ };+ }++ // ─────────────────────────────────────────────────────────────────────────++ async _fetchAllAgents() {+ const agents = [];+ const chainId = this._parseChainFilter(this.filters.chain);+ const chains = chainId === 'all' ? Object.keys(CHAIN_META).map(Number) : [chainId];++ for (const cid of chains) {+ try {+ const events = await listRegisteredEvents({+ chainId: cid,+ limit: 500, // Adjust as needed+ });++ for (const ev of events) {+ try {+ const agentId = String(ev.agentId);+ const onchain = await getAgentOnchain({+ chainId: cid,+ agentId,+ });++ let metadata = {};+ if (ev.agentURI) {+ const result = await fetchAgentMetadata(ev.agentURI);+ if (result.ok && result.data) {+ metadata = result.data;+ }+ }++ const avatar = findAvatar3D(metadata);++ agents.push({+ id: agentId,+ chainId: cid,+ name: metadata.name || `Agent #${agentId}`,+ description: metadata.description || '',+ avatar,+ owner: onchain.owner || ev.owner,+ createdAt: ev.blockNumber+ ? new Date(ev.blockNumber * 12000) // Rough estimate+ : new Date(),+ registeredBlock: ev.blockNumber,+ txHash: ev.txHash,+ });+ } catch (err) {+ console.warn(`Failed to fetch agent ${ev.agentId}:`, err);+ }+ }+ } catch (err) {+ console.warn(`Failed to fetch chain ${cid}:`, err);+ }+ }++ this.agents = agents;+ }++ _applyFilters() {+ return this.agents.filter((agent) => {+ // Chain filter+ if (this.filters.chain !== 'all') {+ const targetChain = Number(this.filters.chain);+ if (agent.chainId !== targetChain) return false;+ }++ // Search filter+ if (this.filters.search.trim()) {+ const term = this.filters.search.toLowerCase();+ if (+ !agent.name.toLowerCase().includes(term) &&+ !agent.id.includes(term) &&+ !agent.description.toLowerCase().includes(term)+ ) {+ return false;+ }+ }++ return true;+ });+ }++ _applySorting(agents) {+ const sorted = [...agents];+ switch (this.filters.sort) {+ case 'name':+ sorted.sort((a, b) => a.name.localeCompare(b.name));+ break;+ case 'oldest':+ sorted.sort((a, b) => a.createdAt - b.createdAt);+ break;+ case 'newest':+ default:+ sorted.sort((a, b) => b.createdAt - a.createdAt);+ }+ return sorted;+ }++ _renderCard(agent) {+ const avatarUrl = agent.avatar || '';+ const cleanName = this._escapeHtml(agent.name);+ const cleanDesc = this._escapeHtml(agent.description.slice(0, 100));+ const chainName = CHAIN_META[agent.chainId]?.name || `Chain ${agent.chainId}`;++ return `+ <div class="agent-card" data-agent-id="${agent.id}" data-chain-id="${agent.chainId}">+ <div class="card-avatar">+ ${+ avatarUrl+ ? `<img data-src="${this._escapeHtml(avatarUrl)}" alt="${cleanName}" loading="lazy">`+ : '<div class="avatar-placeholder">👤</div>'+ }+ </div>+ <div class="card-content">+ <h3 class="card-name">${cleanName}</h3>+ <p class="card-desc">${cleanDesc}${agent.description.length > 100 ? '…' : ''}</p>+ <div class="card-meta">+ <span class="chain-badge">${chainName}</span>+ <span class="agent-id">#${agent.id}</span>+ </div>+ </div>+ </div>+ `;+ }++ _escapeHtml(text) {+ const map = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };+ return String(text).replace(/[&<>"']/g, (m) => map[m]);+ }++ _parseChainFilter(filter) {+ if (filter === 'all') return 'all';+ const num = Number(filter);+ return isNaN(num) ? 'all' : num;+ }++ _attachEventListeners() {+ this.container.querySelectorAll('.agent-card').forEach((card) => {+ card.addEventListener('click', () => {+ const agentId = card.dataset.agentId;+ const chainId = card.dataset.chainId;+ const agent = this.agents.find(+ (a) => a.id === agentId && a.chainId === Number(chainId),+ );+ if (agent && this.cardClickHandler) {+ this.cardClickHandler(agent);+ }+ });+ });+ }+}diff --git a/publish/src/animation-manager.js b/publish/src/animation-manager.jsnew file mode 100644index 000000000..9f8c6ed65--- /dev/null+++ b/publish/src/animation-manager.js@@ -0,0 +1,262 @@+import { AnimationClip, AnimationMixer, LoopRepeat, LoopOnce } from 'three';++/**+ * Manages pre-baked animation clips for skinned agents.+ *+ * Clips are authored at build time (scripts/build-animations.mjs):+ * - Mixamo FBX → retargeted to canonical Avaturn skeleton → JSON+ * - No FBXLoader or retargeting in the browser; just fetch + parse.+ *+ * Usage:+ * const mgr = new AnimationManager();+ * mgr.attach(skinnedModel);+ * await mgr.loadAll(); // reads manifest, fetches clips lazily on first play+ * mgr.play('idle');+ * mgr.crossfadeTo('dance', 0.4);+ */++const DEFAULT_CROSSFADE = 0.35; // seconds++export class AnimationManager {+ constructor() {+ /** @type {THREE.Object3D|null} */+ this.model = null;+ /** @type {AnimationMixer|null} */+ this.mixer = null;+ /** @type {Map<string, THREE.AnimationClip>} */+ this.clips = new Map();+ /** @type {Map<string, THREE.AnimationAction>} */+ this.actions = new Map();+ /** @type {string|null} */+ this.currentName = null;+ /** @type {THREE.AnimationAction|null} */+ this.currentAction = null;+ /** @type {Function|null} Fired with the new clip name (or null) on every change. */+ this.onChange = null;+ /** @type {Array<{name:string, url:string, label:string, icon:string, loop:boolean}>} */+ this._animationDefs = [];+ /** @type {Set<string>} Clip names that failed to load — buttons grayed out in UI. */+ this._failed = new Set();+ }++ // ── Model binding ──────────────────────────────────────────────────────────++ /**+ * Attach to a loaded model. Call this every time a new model is loaded.+ * Re-creates actions for any clips that are already in memory.+ * @param {THREE.Object3D} model+ */+ attach(model) {+ this.detach();+ this.model = model;+ this.mixer = new AnimationMixer(model);+ this.actions.clear();+ this.currentAction = null;+ this.currentName = null;++ for (const [name, clip] of this.clips) {+ const action = this.mixer.clipAction(clip);+ action.enabled = true;+ this.actions.set(name, action);+ }+ }++ /** Detach, stop all actions, dispose mixer. */+ detach() {+ if (this.mixer) {+ this.mixer.stopAllAction();+ this.mixer.uncacheRoot(this.mixer.getRoot());+ this.mixer = null;+ }+ this.model = null;+ this.actions.clear();+ this.currentAction = null;+ this.currentName = null;+ }++ // ── Definitions ────────────────────────────────────────────────────────────++ /**+ * Register animation definitions (from manifest.json).+ * @param {Array<{name:string, url:string, label?:string, icon?:string, loop?:boolean}>} defs+ */+ setAnimationDefs(defs) {+ this._animationDefs = defs;+ }++ /** @returns {Array} */+ getAnimationDefs() {+ return this._animationDefs;+ }++ /** @param {string} name @returns {boolean} */+ isFailed(name) {+ return this._failed.has(name);+ }++ // ── Loading ────────────────────────────────────────────────────────────────++ /**+ * Load a single clip from a pre-baked JSON URL and register it.+ * Idempotent — returns the cached clip if already loaded.+ *+ * @param {string} name+ * @param {string} url URL to a clip JSON produced by build-animations.mjs+ * @param {{ loop?: boolean }} [opts]+ * @returns {Promise<THREE.AnimationClip>}+ */+ async loadAnimation(name, url, opts = {}) {+ if (this.clips.has(name)) return this.clips.get(name);++ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 10_000);+ let res;+ try {+ res = await fetch(url, { signal: controller.signal });+ } finally {+ clearTimeout(timeoutId);+ }+ if (!res.ok) throw new Error(`HTTP ${res.status} loading animation ${name}`);+ const json = await res.json();+ const clip = AnimationClip.parse(json);+ clip.name = name;++ this.clips.set(name, clip);++ if (this.model && this.mixer) {+ const action = this.mixer.clipAction(clip);+ action.enabled = true;+ action.setLoop(opts.loop === false ? LoopOnce : LoopRepeat);+ if (opts.loop === false) action.clampWhenFinished = true;+ this.actions.set(name, action);+ }+ return clip;+ }++ /**+ * Load all registered definitions in parallel.+ * Failed clips are logged and added to _failed; they do not throw.+ */+ async loadAll() {+ const CONCURRENCY = 4;+ const queue = [...this._animationDefs];+ const worker = async () => {+ let def;+ while ((def = queue.shift())) {+ try {+ await this.loadAnimation(def.name, def.url, { loop: def.loop !== false });+ } catch (err) {+ console.warn(`[AnimationManager] failed to load "${def.name}":`, err.message);+ this._failed.add(def.name);+ }+ }+ };+ await Promise.all(Array.from({ length: CONCURRENCY }, worker));+ }++ /**+ * Lazily load a single clip by name (from registered defs) if not yet loaded.+ * Used so the first click on a strip button triggers a load without blocking startup.+ * @param {string} name+ * @returns {Promise<boolean>} true if ready+ */+ async ensureLoaded(name) {+ if (this.clips.has(name)) return true;+ if (this._failed.has(name)) return false;+ const def = this._animationDefs.find((d) => d.name === name);+ if (!def) return false;+ try {+ await this.loadAnimation(def.name, def.url, { loop: def.loop !== false });+ return true;+ } catch {+ this._failed.add(name);+ return false;+ }+ }++ // ── Playback ───────────────────────────────────────────────────────────────++ /**+ * Play a named clip immediately (hard cut, no crossfade).+ * Lazily loads if not yet in memory.+ * @param {string} name+ */+ async play(name) {+ const ready = await this.ensureLoaded(name);+ if (!ready) {+ console.warn(`[AnimationManager] "${name}" unavailable`);+ return;+ }+ const action = this.actions.get(name);+ if (!action) return;++ if (this.currentAction && this.currentAction !== action) {+ this.currentAction.fadeOut(0.01);+ }+ action.reset().fadeIn(0.01).play();+ this.currentAction = action;+ this.currentName = name;+ try { this.onChange?.(name); } catch (e) { console.warn('[AnimationManager] onChange threw:', e); }+ }++ /**+ * Crossfade from the current clip to a named clip.+ * Lazily loads if not yet in memory.+ * @param {string} name+ * @param {number} [duration] seconds+ */+ async crossfadeTo(name, duration = DEFAULT_CROSSFADE) {+ duration = Math.max(0, Math.min(duration, 5));+ if (name === this.currentName) return;+ const ready = await this.ensureLoaded(name);+ if (!ready) {+ console.warn(`[AnimationManager] "${name}" unavailable`);+ return;+ }+ const next = this.actions.get(name);+ if (!next) return;++ next.reset().play();+ if (this.currentAction) {+ this.currentAction.crossFadeTo(next, duration, true);+ } else {+ next.fadeIn(duration);+ }+ this.currentAction = next;+ this.currentName = name;+ try { this.onChange?.(name); } catch (e) { console.warn('[AnimationManager] onChange threw:', e); }+ }++ /** Stop all animations. */+ stopAll() {+ this.mixer?.stopAllAction();+ this.currentAction = null;+ this.currentName = null;+ try { this.onChange?.(null); } catch (e) { console.warn('[AnimationManager] onChange threw:', e); }+ }++ /**+ * Tick the mixer. Call from the render loop.+ * @param {number} delta seconds since last frame+ */+ update(delta) {+ this.mixer?.update(delta);+ }++ /** @returns {string[]} */+ getLoadedNames() {+ return [...this.clips.keys()];+ }++ /** @param {string} name @returns {boolean} */+ isLoaded(name) {+ return this.clips.has(name);+ }++ dispose() {+ this.detach();+ this.clips.clear();+ this._animationDefs = [];+ this._failed.clear();+ }+}diff --git a/publish/src/annotations.js b/publish/src/annotations.jsnew file mode 100644index 000000000..c3a964c2f--- /dev/null+++ b/publish/src/annotations.js@@ -0,0 +1,151 @@+import { prepare, measureLineStats } from '@chenglou/pretext';+import {+ prepareRichInline,+ walkRichInlineLineRanges,+ materializeRichInlineLineRange,+} from '@chenglou/pretext/rich-inline';+import { Vector3, Box3 } from 'three';++const FONT_NAME = '500 11px Inter, sans-serif';+const FONT_DETAIL = '300 10px Inter, sans-serif';+const LABEL_PAD_X = 10;+const LABEL_PAD_Y = 6;+const LINE_HEIGHT = 14;+const DPR = Math.min(window.devicePixelRatio || 1, 2);+const MAX_LABELS = 8;++/**+ * Build annotation data for key meshes in the scene.+ * Uses pretext rich-inline to render mixed-style labels (name + type).+ */+export function buildAnnotations(object) {+ const annotations = [];++ object.traverse((node) => {+ if (annotations.length >= MAX_LABELS) return;+ if (!node.isMesh) return;+ if (!node.name || node.name.startsWith('_')) return;++ const geo = node.geometry;+ const mat = Array.isArray(node.material) ? node.material[0] : node.material;++ const vertCount = geo && geo.attributes.position ? geo.attributes.position.count : 0;+ const matType = mat ? mat.type.replace('Material', '') : '';++ // Rich inline: mesh name (bold) + vertex count (light)+ const items = [{ text: node.name, font: FONT_NAME }];+ if (vertCount > 0) {+ items.push({ text: ' ' + formatShort(vertCount) + ' verts', font: FONT_DETAIL });+ }+ if (matType) {+ items.push({ text: ' ' + matType, font: FONT_DETAIL });+ }++ // Measure with pretext+ const prepared = prepareRichInline(items);+ let totalWidth = 0;+ let lineCount = 0;+ walkRichInlineLineRanges(prepared, 300, (range) => {+ const line = materializeRichInlineLineRange(prepared, range);+ totalWidth = Math.max(totalWidth, line.width);+ lineCount++;+ });++ const labelWidth = totalWidth + LABEL_PAD_X * 2;+ const labelHeight = lineCount * LINE_HEIGHT + LABEL_PAD_Y * 2;++ // Get world position from bounding box center+ if (geo) geo.computeBoundingBox();+ const box = geo ? geo.boundingBox : null;+ const pos = new Vector3();+ if (box) {+ box.getCenter(pos);+ pos.applyMatrix4(node.matrixWorld);+ } else {+ node.getWorldPosition(pos);+ }++ annotations.push({+ name: node.name,+ items,+ prepared,+ labelWidth,+ labelHeight,+ position: pos,+ vertCount,+ matType,+ });+ });++ return annotations;+}++/**+ * Render a single annotation label to a canvas element.+ */+export function renderAnnotationCanvas(annotation) {+ const { labelWidth, labelHeight, items, prepared } = annotation;++ const canvas = document.createElement('canvas');+ canvas.width = labelWidth * DPR;+ canvas.height = labelHeight * DPR;+ canvas.style.width = labelWidth + 'px';+ canvas.style.height = labelHeight + 'px';++ const ctx = canvas.getContext('2d');+ ctx.scale(DPR, DPR);++ // Background+ ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';+ roundRect(ctx, 0, 0, labelWidth, labelHeight, 6);+ ctx.fill();++ // Border+ ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';+ ctx.lineWidth = 1;+ roundRect(ctx, 0.5, 0.5, labelWidth - 1, labelHeight - 1, 6);+ ctx.stroke();++ // Render rich inline text+ ctx.textBaseline = 'top';+ let y = LABEL_PAD_Y;++ walkRichInlineLineRanges(prepared, labelWidth - LABEL_PAD_X * 2, (range) => {+ const line = materializeRichInlineLineRange(prepared, range);+ let x = LABEL_PAD_X;++ line.fragments.forEach((frag) => {+ x += frag.gapBefore;+ const item = items[frag.itemIndex];+ ctx.font = item.font;+ ctx.fillStyle =+ frag.itemIndex === 0 ? 'rgba(255, 255, 255, 0.9)' : 'rgba(255, 255, 255, 0.45)';+ ctx.fillText(frag.text, x, y);+ x += frag.occupiedWidth;+ });++ y += LINE_HEIGHT;+ });++ return canvas;+}++function formatShort(n) {+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M';+ if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';+ return n.toString();+}++function roundRect(ctx, x, y, w, h, r) {+ ctx.beginPath();+ ctx.moveTo(x + r, y);+ ctx.lineTo(x + w - r, y);+ ctx.quadraticCurveTo(x + w, y, x + w, y + r);+ ctx.lineTo(x + w, y + h - r);+ ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);+ ctx.lineTo(x + r, y + h);+ ctx.quadraticCurveTo(x, y + h, x, y + h - r);+ ctx.lineTo(x, y + r);+ ctx.quadraticCurveTo(x, y, x + r, y);+ ctx.closePath();+}diff --git a/publish/src/app.js b/publish/src/app.jsnew file mode 100644index 000000000..48f2dc6c9--- /dev/null+++ b/publish/src/app.js@@ -0,0 +1,1657 @@+import * as THREE from 'three';+import WebGL from 'three/addons/capabilities/WebGL.js';+import { Viewer } from './viewer.js';+import { Editor } from './editor/index.js';+import { SimpleDropzone } from 'simple-dropzone';+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, getMe, readAuthHint } from './account.js';+import { getWidget } from './widgets.js';+import { mountAnimationGallery } from './widgets/animation-gallery.js';+import { mountTalkingAgent } from './widgets/talking-agent.js';+import { mountTurntable } from './widgets/turntable.js';+import { mountHotspotTour } from './widgets/hotspot-tour.js';+import { mountPumpfunFeed } from './widgets/pumpfun-feed.js';+import queryString from 'query-string';++// 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';++// Runtime — LLM brain, scene control, file-based memory, skill bundles+import { SceneController } from './runtime/scene.js';+import { Runtime } from './runtime/index.js';+import { Memory } from './memory/index.js';+import { SkillRegistry } from './skills/index.js';++// Wallet — kick off a silent reconnect on app boot. Any page that later mounts+// a wallet UI (deploy, reputation, validation, permissions, etc.) reads from+// the shared signer + onWalletChange bus, so this single call surfaces an+// already-authorized wallet site-wide without any popup.+import { eagerConnectWallet } from './erc8004/agent-registry.js';++window.THREE = THREE;+window.VIEWER = {};++function _blobToBase64(blob) {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ const s = reader.result;+ const comma = s.indexOf(',');+ resolve(comma >= 0 ? s.slice(comma + 1) : s);+ };+ reader.onerror = () => reject(reader.error);+ reader.readAsDataURL(blob);+ });+}++function _base64ToFile(b64, name, type) {+ const bin = atob(b64);+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ return new File([bytes], name, { type });+}++/**+ * Parse an on-chain agent URL path. Accepts:+ * /a/<chainId>/<agentId> (canonical — registry inferred)+ * /a/<chainId>/<agentId>/embed (chromeless iframe variant)+ * /a/<chainId>/<registry>/<agentId> (explicit registry, for non-canonical deployments)+ * /a/<chainId>/<registry>/<agentId>/embed+ * /a/eip155:<chainId>:<registry>/<agentId> (full CAIP)+ */+function parseOnchainPath(pathname) {+ // Strip trailing /embed (capturing) then peel remaining segments.+ const embedMatch = pathname.match(/^(\/a\/.+?)\/embed\/?$/);+ const embed = !!embedMatch;+ const base = embed ? embedMatch[1] : pathname;+ const m = base.match(/^\/a\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?\/?$/);+ if (!m) return null;+ const [, a, b, c] = m;++ // /a/eip155:chainId:registry/<agentId>+ const caipMatch = a.match(/^eip155:(\d+):(0x[a-fA-F0-9]{40})$/);+ if (caipMatch && b && /^\d+$/.test(b) && !c) {+ return { chainId: Number(caipMatch[1]), registry: caipMatch[2], agentId: b, embed };+ }++ // /a/<chainId>/<registry>/<agentId>+ if (b && c && /^\d+$/.test(a) && /^0x[a-fA-F0-9]{40}$/.test(b) && /^\d+$/.test(c)) {+ return { chainId: Number(a), registry: b, agentId: c, embed };+ }++ // /a/<chainId>/<agentId> (canonical: registry inferred from REGISTRY_DEPLOYMENTS)+ if (b && !c && /^\d+$/.test(a) && /^\d+$/.test(b)) {+ return { chainId: Number(a), agentId: b, embed };+ }++ return null;+}++function escHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++/** Parse #onchain=<chainId>:<agentId> for embed mode. */+function parseOnchainHash(value) {+ if (!value) return null;+ const m = String(value).match(/^(\d+):(\d+)$/);+ if (!m) return null;+ return { chainId: Number(m[1]), agentId: m[2] };+}++if (!(window.File && window.FileReader && window.FileList && window.Blob)) {+ console.error('The File APIs are not fully supported in this browser.');+} else if (!WebGL.isWebGL2Available()) {+ console.error('WebGL is not supported in this browser.');+}++class App {+ /**+ * @param {Element} el+ * @param {Location} location+ */+ constructor(el, location) {+ const hash = location.hash ? queryString.parse(location.hash) : {};+ const qp = new URLSearchParams(location.search);+ // agentQuery: from ?agent= query param → editing mode (main UI with save-back)+ // agentHash: from #agent= hash → legacy embed mode+ const agentQuery = qp.get('agent') || '';+ const agentHash = hash.agent || '';++ // On-chain CAIP-style route: /a/<chainId>/<agentId> [ /<registry> optional ]+ // Parses to { chainId, agentId, registry? } when matched. Renders the agent's+ // 3D avatar by resolving its registration file → `avatar` service endpoint.+ const onchain = parseOnchainPath(location.pathname) || parseOnchainHash(hash.onchain);++ this.options = {+ kiosk: Boolean(hash.kiosk) || !!(onchain && onchain.embed),+ model: hash.model || '',+ type: hash.type || '',+ preset: hash.preset || '',+ cameraPosition: hash.cameraPosition ? hash.cameraPosition.split(',').map(Number) : null,+ brain: hash.brain || 'none',+ proxyURL: hash.proxyURL || '',+ agent: agentHash, // hash-based agent keeps legacy embed behaviour+ agentEdit: agentQuery, // query-param agent → editing surface+ widget: hash.widget || '',+ deploy: hash.deploy !== undefined || location.pathname === '/deploy',+ onchain, // { chainId, agentId, registry? } | null+ showcase: location.pathname === '/showcase' || location.pathname === '/showcase/',+ // pending=1 signals a post-login save round-trip+ pending: qp.get('pending') === '1',+ // avatarSession: selfie pipeline passes a session URL here after processing photos+ avatarSession: hash.avatarSession ? decodeURIComponent(hash.avatarSession) : '',+ // Per-embed overrides (appended to iframe URL by Studio embed modal)+ noAnimations: Boolean(hash.noAnimations),+ noChat: Boolean(hash.noChat),+ noControls: Boolean(hash.noControls),+ };++ // Fire-and-forget silent wallet reconnect. Cheap (single `eth_accounts`+ // RPC), never throws, never prompts. If the user has previously authorized+ // the site, this populates the shared signer before any wallet UI mounts.+ eagerConnectWallet();++ this.el = el;+ this.viewer = null;+ this.editor = null;+ this._previewMounted = false;+ 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);++ // ── 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;+ this.sceneCtrl = null; // SceneController — created when viewer is ready+ this.runtime = null; // LLM Runtime — created after identity + memory load+ this.fileMemory = null; // file-based Memory for LLM context+ this.skillRegistry = null; // external skill bundle loader++ // Wire validator results into the protocol+ this._hookValidator();++ this._editingAgentId = this.options.agentEdit || null;++ this.createDropzone();+ this.setupAvatarCreator();+ if (this.options.avatarSession) {+ this.avatarCreator.open(this.options.avatarSession);+ }+ this.hideSpinner();+ this._applyViewerMode();+ this._updateSignInLink();+ this._setupSaveToAccount();+ this._setupMakeWidgetButton();++ const options = this.options;++ if (options.kiosk) {+ const headerEl = document.querySelector('header');+ headerEl.style.display = 'none';+ const footerEl = document.querySelector('footer');+ if (footerEl) footerEl.style.display = 'none';+ }++ // Check for deploy (ERC-8004 mint) page. We still load the default+ // avatar in the background so `_currentModelUrl` is populated for the+ // RegisterUI pre-fill — it reflects the viewer's current model.+ if (options.deploy) {+ const model = options.model || '/avatars/cz.glb';+ this.view(isDecentralizedURI(model) ? resolveURI(model) : model, '', new Map())+ .catch(() => {})+ .finally(() => this._showDeployPage());+ this._initAgentSystem();+ return;+ }++ // /showcase — browsable marketplace of every indexed three.ws.+ if (options.showcase) {+ this._showShowcasePage();+ this._initAgentSystem();+ return;+ }++ // /a/<chainId>/<agentId> — resolve an on-chain agent to its 3D avatar.+ if (options.onchain) {+ this._loadOnChainAgent(options.onchain);+ this._initAgentSystem();+ return;+ }++ // Load a specific agent by ID: /#agent=<uuid> (embed mode)+ if (options.agent) {+ this._loadAgent(options.agent);+ return;+ }++ // Load a saved widget by ID: /app#widget=<wdgt_...>+ if (options.widget) {+ this._loadWidget(options.widget);+ this._initAgentSystem();+ this._initWidgetBridge();+ return;+ }++ // Editing an existing agent: ?agent=<uuid> (authenticated editing surface)+ if (options.agentEdit) {+ this._loadAgentForEdit(options.agentEdit);+ } else {+ // Resume a stashed editor session (post-login round-trip), else+ // load the model named in the URL or fall back to the CZ avatar.+ this._maybeResumeOrLoad(options);+ }++ // After sign-in redirect, check for a pending_save stash.+ if (options.pending) {+ this._maybePendingSave();+ }++ // Boot the agent system once identity is ready. _loadAgentForEdit also+ // triggers _initAgentSystem at its tail; the AgentHome render is+ // idempotent so the second pass tears down and re-mounts cleanly.+ this._initAgentSystem();++ // Studio preview iframes use postMessage to live-update brand config.+ this._initWidgetBridge();+ }++ /**+ * If the URL carries ?resume=<token>, restore the stashed editor session+ * (load source + replay edits + optionally auto-open Publish). Otherwise+ * load the model from #model= or the default CZ avatar.+ */+ async _maybeResumeOrLoad(options) {+ const params = new URLSearchParams(location.search);+ const resumeToken = params.get('resume');++ if (resumeToken) {+ try {+ const { restoreSession, clearStash } = await import('./editor/edit-persistence.js');+ const stashed = await restoreSession(resumeToken);+ if (stashed) {+ if (stashed.source.url) {+ await this.view(stashed.source.url, '', new Map());+ } else if (stashed.source.file) {+ const f = stashed.source.file;+ await this.load(new Map([[f.name, f]]));+ }++ if (this.editor && this.editor.session) {+ this.editor.session.restoreEdits(stashed.edits);+ // Panels snapshotted the original material values before+ // restoreEdits mutated them — rebuild so the GUI mirrors+ // the restored state.+ this.editor.materialEditor?.rebuild?.();+ this.editor.textureInspector?.rebuild?.();+ this.editor.sceneExplorer?.rebuild?.();+ }++ if (params.get('publish') === '1') {+ this.editor?._openPublishModal?.();+ }++ await clearStash(resumeToken);++ const clean = new URL(location.href);+ clean.searchParams.delete('resume');+ clean.searchParams.delete('publish');+ history.replaceState(null, '', clean.toString());+ return;+ }+ } catch (err) {+ console.warn('[3d-agent] resume failed', err);+ }+ }++ const model = options.model || '/avatars/cz.glb';+ const resolvedModel = isDecentralizedURI(model) ? resolveURI(model) : model;+ const isDefaultCz = !options.model;+ const loadPromise = this.view(resolvedModel, '', new Map());+ if (isDefaultCz) {+ loadPromise?.then?.(() => this._playDefaultLandingClip('taunt'));+ }+ }++ /**+ * After the default CZ avatar loads on /app, stop the baked-in idle clip+ * (which fights the manifest animations on the same skeleton and looks+ * glitchy) and crossfade into a manifest clip once it's ready.+ * @param {string} clipName+ */+ _playDefaultLandingClip(clipName) {+ const viewer = this.viewer;+ if (!viewer) return;+ if (viewer.mixer) viewer.mixer.stopAllAction();+ const am = viewer.animationManager;+ if (!am) return;+ const start = performance.now();+ const tryPlay = () => {+ if (!this.viewer || this.viewer !== viewer) return;+ if (viewer.mixer) viewer.mixer.stopAllAction();+ const defs = am.getAnimationDefs();+ const hasDef = defs.some((d) => d.name === clipName);+ if (hasDef) {+ am.crossfadeTo(clipName).catch(() => {});+ return;+ }+ if (performance.now() - start > 8000) return;+ setTimeout(tryPlay, 200);+ };+ tryPlay();+ }++ // ── 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);++ // File-based memory for LLM context injection+ this.fileMemory = await Memory.load({+ mode: 'local',+ namespace: this.identity.id,+ });++ // External skill bundle loader (empty initially — skills load on demand)+ this.skillRegistry = new SkillRegistry({ trust: 'owned-only' });++ // LLM Runtime — the agent's brain. Defaults to 'none' provider+ // (NichAgent pattern matching). Configure with #brain=anthropic&proxyURL=...+ this.runtime = new Runtime({+ manifest: {+ name: this.identity.name || 'Agent',+ instructions: [+ `You are ${this.identity.name || 'Agent'}, an AI agent embedded in a 3D model viewer at three.ws.`,+ 'You can control the 3D scene, remember things, and help users with their 3D work.',+ 'Be concise, clear, and helpful. You are present and embodied — act like it.',+ ].join(' '),+ brain: {+ provider: this.options.brain,+ proxyURL: this.options.proxyURL || undefined,+ },+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],+ },+ viewer: this.sceneCtrl, // null until viewer loads+ memory: this.fileMemory,+ skills: this.skillRegistry,+ });++ // Bridge Runtime assistant messages to the protocol bus+ this.runtime.addEventListener('brain:message', (e) => {+ if (e.detail.role === 'assistant' && e.detail.content) {+ protocol.emit({+ type: ACTION_TYPES.SPEAK,+ payload: { text: e.detail.content, sentiment: 0 },+ agentId: this.identity.id,+ });+ }+ });++ // Expose agent on window for debugging+ window.VIEWER.agent_protocol = protocol;+ window.VIEWER.agent_identity = this.identity;+ window.VIEWER.agent_skills = this.skills;+ window.VIEWER.agent_runtime = this.runtime;++ // 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). Idempotent —+ // if a previous boot already rendered, tear it down before re-mounting+ // so we never stack multiple cards in the sidebar.+ // Skip entirely in kiosk/embed — the panel belongs to owner/edit views.+ const homeEl = document.getElementById('agent-home-container');+ if (homeEl && !this.options.kiosk) {+ if (this.agentHome) this.agentHome.destroy();+ homeEl.innerHTML = '';+ this.agentHome = new AgentHome(homeEl, this.identity, protocol, this.avatar, {+ skills: this.agent_skills || window.VIEWER?.agent_skills,+ memory: this.agent_memory || window.VIEWER?.agent_memory,+ });+ await this.agentHome.render();+ }++ // Boot the voice/chat agent with skills and runtime 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);+ }+ }++ _applyViewerMode() {+ const { kiosk, widget, agent, deploy } = this.options;+ let mode = 'main';+ if (kiosk || widget || agent) mode = 'embed';+ else if (deploy) mode = 'deploy';+ document.body.dataset.viewerMode = mode;+ if (mode === 'main') {+ // Only use 'pending' (hide gate, hide sidebar) when we have a stored 'true' hint —+ // i.e. the user was last seen logged in and may still be. For everyone else (no hint+ // or a 'false' hint) show the auth gate immediately so it never appears after the+ // CZ model renders (which is instant when the GLB is cached from the homepage).+ document.body.dataset.authed = readAuthHint() === 'true' ? 'pending' : 'false';+ }+ }++ async _updateSignInLink() {+ const link = document.getElementById('nav-sign-in');+ try {+ const user = await getMe();+ if (link && user) link.classList.add('signed-in');+ if (user) this._initUserMenu(user);+ if (document.body.dataset.viewerMode === 'main') {+ document.body.dataset.authed = user ? 'true' : 'false';+ }+ } catch {+ if (document.body.dataset.viewerMode === 'main') {+ document.body.dataset.authed = 'false';+ }+ }+ }++ _initUserMenu(user) {+ const wrap = document.getElementById('nav-user-wrap');+ const btn = document.getElementById('nav-user-btn');+ const menu = document.getElementById('nav-user-menu');+ const label = document.getElementById('nav-user-label');+ const profileLink = document.getElementById('nav-my-profile-link');+ const signOutBtn = document.getElementById('nav-sign-out-btn');+ if (!wrap || !btn || !menu) return;++ if (label) label.textContent = user.email || user.username || 'Account';+ if (profileLink && user.address) profileLink.href = `/u/${user.address}`;++ wrap.hidden = false;++ btn.addEventListener('click', (e) => {+ e.stopPropagation();+ const open = menu.hidden === false;+ menu.hidden = open;+ btn.setAttribute('aria-expanded', String(!open));+ });++ document.addEventListener('click', () => {+ if (!menu.hidden) {+ menu.hidden = true;+ btn.setAttribute('aria-expanded', 'false');+ }+ });++ menu.addEventListener('click', (e) => e.stopPropagation());++ if (signOutBtn) {+ signOutBtn.addEventListener('click', () => {+ fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).finally(+ () => {+ try {+ localStorage.removeItem('3dagent:auth-hint');+ } catch {+ /* ignore */+ }+ location.href = '/';+ },+ );+ });+ }+ }++ _refreshMakeWidgetButton() {+ const btn = document.getElementById('make-widget-btn');+ if (!btn) return;+ const url = this._currentModelUrl;+ if (!url && !this._hasLocalGlb) {+ btn.hidden = true;+ return;+ }+ if (url) {+ btn.href = `/studio?model=${encodeURIComponent(url)}`;+ }+ btn.hidden = false;+ }++ _refreshSaveToAccountButton() {+ const btn = document.getElementById('save-to-account-btn');+ if (!btn) return;+ const hasModel = this._currentModelUrl || this._hasLocalGlb;+ btn.hidden = !hasModel;+ }++ // Surface the right deploy CTA next to the public-profile link in /app:+ // • "Deploy on-chain" → /deploy?avatar=<id> (un-registered agent)+ // • "Deployed ✓" → block-explorer URL (already on-chain)+ // Falls back to the bare /deploy page if we can't read the agent record+ // (fetch error, anonymous, etc.) so the affordance never disappears once+ // we know there's an agent in scope.+ async _refreshDeployButton(agentId) {+ const btn = document.getElementById('deploy-onchain-btn');+ if (!btn || !agentId) return;++ const label = btn.querySelector('[data-state-label]');+ btn.classList.remove('is-deployed');+ btn.removeAttribute('target');+ btn.removeAttribute('rel');+ if (label) label.textContent = 'Deploy on-chain';+ btn.setAttribute('aria-label', 'Publish this agent on-chain');+ btn.setAttribute('title', 'Publish this agent on-chain (ERC-8004)');+ btn.href = `/deploy?agent=${encodeURIComponent(agentId)}`;+ btn.hidden = false;++ try {+ const resp = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });+ if (!resp.ok) return;+ const { agent } = await resp.json();+ if (!agent) return;++ if (agent.avatar_id && !btn.dataset.avatarPrefilled) {+ btn.href = `/deploy?avatar=${encodeURIComponent(agent.avatar_id)}`;+ btn.dataset.avatarPrefilled = '1';+ }++ const isDeployed = agent.erc8004_agent_id && agent.chain_id;+ if (!isDeployed) return;++ const { CHAIN_META, addressExplorerUrl, tokenExplorerUrl } = await import(+ './erc8004/chain-meta.js'+ );+ const chainName = CHAIN_META[agent.chain_id]?.name || `chain ${agent.chain_id}`;+ let url = '';+ if (agent.erc8004_registry) {+ url = tokenExplorerUrl(+ agent.chain_id,+ agent.erc8004_registry,+ agent.erc8004_agent_id,+ );+ }+ if (!url && agent.erc8004_registry) {+ url = addressExplorerUrl(agent.chain_id, agent.erc8004_registry);+ }+ if (!url) url = `/agent/${agentId}`;++ btn.classList.add('is-deployed');+ btn.href = url;+ btn.target = '_blank';+ btn.rel = 'noopener';+ if (label) label.textContent = `Deployed ✓ ${chainName}`;+ btn.setAttribute(+ 'aria-label',+ `This agent is registered on ${chainName}. Open block explorer in a new tab.`,+ );+ btn.setAttribute('title', `On-chain on ${chainName} — view on explorer`);+ } catch {+ /* keep the un-deployed CTA */+ }+ }++ _setupSaveToAccount() {+ const btn = document.getElementById('save-to-account-btn');+ if (!btn) return;+ btn.addEventListener('click', (e) => {+ e.preventDefault();+ this._triggerSaveToAccount();+ });+ }++ _setupMakeWidgetButton() {+ // No auth gate — /studio handles anonymous users gracefully.+ }++ async _triggerSaveToAccount() {+ const user = await getMe();+ if (!user) {+ await this._stashAndRedirectToLogin();+ return;+ }+ await this._performSave(user);+ }++ async _stashAndRedirectToLogin() {+ const btn = document.getElementById('save-to-account-btn');+ if (btn) {+ btn.setAttribute('disabled', '');+ btn.querySelector('span').textContent = 'Preparing…';+ }++ const stash = {+ glbUrl: this._currentModelUrl || null,+ fileName: this._currentLocalFile?.name || null,+ fileB64: null,+ returnTo: '/app',+ agentId: this._editingAgentId || null,+ ts: Date.now(),+ };++ // Local file drops can't be re-hydrated from a blob URL after reload.+ // Encode as base64 and stash — sessionStorage quota is ~5MB, so this+ // fails gracefully for oversized GLBs (user re-drops after sign-in).+ if (this._currentLocalFile) {+ try {+ stash.fileB64 = await _blobToBase64(this._currentLocalFile);+ stash.contentType = this._currentLocalFile.type || 'model/gltf-binary';+ } catch {+ /* fall through without file data */+ }+ }++ try {+ sessionStorage.setItem('pending_save', JSON.stringify(stash));+ } catch {+ // Quota exceeded — drop the file payload and retry with just metadata+ delete stash.fileB64;+ try {+ sessionStorage.setItem('pending_save', JSON.stringify(stash));+ } catch {+ /* storage disabled — proceed without stash */+ }+ }+ location.href = '/login?next=' + encodeURIComponent('/app?pending=1');+ }++ async _performSave(user) {+ if (!user) return;+ const btn = document.getElementById('save-to-account-btn');+ if (btn) {+ btn.setAttribute('disabled', '');+ btn.querySelector('span').textContent = 'Saving…';+ }+ try {+ let avatarId;+ const source = this._currentLocalFile || this._currentModelUrl;+ if (!source) {+ // Nothing to save — reset UI and bail+ if (btn) {+ btn.removeAttribute('disabled');+ btn.querySelector('span').textContent = 'Save to account';+ }+ return;+ }+ const avatar = await saveRemoteGlbToAccount(source, {+ source: this._currentLocalFile ? 'upload' : 'import',+ name: this._currentLocalFile?.name,+ source_meta: this._currentLocalFile+ ? { original_filename: this._currentLocalFile.name }+ : undefined,+ });+ avatarId = avatar.id;++ if (this._editingAgentId) {+ // Update existing agent's avatar+ if (avatarId) {+ await fetch(`/api/agents/${this._editingAgentId}`, {+ method: 'PUT',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ avatar_id: avatarId }),+ });+ }+ location.href = `/agent/${this._editingAgentId}`;+ } else {+ // Create a new agent linked to the uploaded avatar+ const res = await fetch('/api/agents/me', {+ method: 'GET',+ credentials: 'include',+ });+ const data = res.ok ? await res.json() : null;+ let agentId = data?.agent?.id;++ if (!agentId) {+ const created = await fetch('/api/agents', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ name: 'My Agent' }),+ });+ const createdData = created.ok ? await created.json() : null;+ agentId = createdData?.agent?.id;+ }++ if (agentId && avatarId) {+ await fetch(`/api/agents/${agentId}`, {+ method: 'PUT',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ avatar_id: avatarId }),+ });+ }++ if (agentId) {+ location.href = `/agent/${agentId}`;+ } else {+ this._flashSaved({ name: 'your account' });+ if (btn) {+ btn.removeAttribute('disabled');+ btn.querySelector('span').textContent = 'Save to account';+ }+ }+ }+ } catch (err) {+ console.warn('[3d-agent] save failed:', err.message);+ if (btn) {+ btn.removeAttribute('disabled');+ btn.querySelector('span').textContent = 'Save to account';+ }+ }+ }++ async _maybePendingSave() {+ let stash;+ try {+ const raw = sessionStorage.getItem('pending_save');+ if (!raw) return;+ stash = JSON.parse(raw);+ } catch {+ return;+ }++ // Stale stashes (older than 1 hour) are discarded — the user likely+ // abandoned the sign-in flow and we shouldn't silently replay old work.+ if (!stash || !stash.ts || Date.now() - stash.ts > 60 * 60 * 1000) {+ sessionStorage.removeItem('pending_save');+ return;+ }++ const user = await getMe();+ if (!user) return; // still not authed — leave stash intact++ sessionStorage.removeItem('pending_save');++ // Restore the editing context from the stash+ if (stash.agentId) this._editingAgentId = stash.agentId;++ // Re-hydrate the model: local file (base64) takes priority over remote URL+ if (stash.fileB64 && stash.fileName) {+ const file = _base64ToFile(+ stash.fileB64,+ stash.fileName,+ stash.contentType || 'model/gltf-binary',+ );+ await this.load(new Map([[stash.fileName, file]]));+ } else if (stash.glbUrl && stash.glbUrl !== this._currentModelUrl) {+ await this.view(stash.glbUrl, '', new Map());+ }++ // Strip ?pending from URL before saving+ const clean = new URL(location.href);+ clean.searchParams.delete('pending');+ history.replaceState(null, '', clean.toString());++ await this._performSave(user);+ }++ async _loadAgent(agentId) {+ this.identity = new AgentIdentity({ agentId, autoLoad: false });+ await this.identity.load();++ let glbUrl = '/avatars/cz.glb';+ if (this.identity.avatarId) {+ try {+ const resp = await fetch(`/api/avatars/${this.identity.avatarId}`, {+ credentials: 'include',+ });+ if (resp.ok) {+ const { avatar } = await resp.json();+ if (avatar?.url) glbUrl = avatar.url;+ }+ } catch {+ /* fall through to default */+ }+ }++ this.view(glbUrl, '', new Map());+ this._initAgentSystem();+ }++ async _loadAgentForEdit(agentId) {+ // Swap this.identity to the agent being edited so AgentHome (and the+ // Solana wallet card) render for *this* agent rather than the viewer's+ // default identity.+ this.identity = new AgentIdentity({ agentId, autoLoad: false });+ try {+ await this.identity.load();+ } catch {+ /* fall through; identity getter still returns _agentId */+ }++ // Fetch the agent record and load its GLB into the editor (main UI, not embed)+ let glbUrl = null;+ try {+ const resp = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });+ if (resp.ok) {+ const { agent } = await resp.json();+ if (agent?.avatar_id) {+ const avatarResp = await fetch(`/api/avatars/${agent.avatar_id}`, {+ credentials: 'include',+ });+ if (avatarResp.ok) {+ const { avatar } = await avatarResp.json();+ if (avatar?.url) glbUrl = avatar.url;+ }+ }+ }+ } catch {+ /* fall through to default */+ }++ if (glbUrl) {+ await this.view(glbUrl, '', new Map());+ } else {+ this._maybeResumeOrLoad(this.options);+ }++ // Restore + auto-save per-agent scene preferences (background, env,+ // exposure, auto-rotate) so the editor feels like coming back to+ // "your studio" rather than a generic default each time.+ if (this.viewer && this.viewer.attachScenePrefs) {+ this.viewer.attachScenePrefs(agentId);+ }++ const publicLink = document.getElementById('view-public-profile-btn');+ if (publicLink) {+ publicLink.href = `/agent/${agentId}`;+ publicLink.hidden = false;+ }++ this._refreshDeployButton(agentId);++ this._maybeShowOnboarding(agentId);++ this._initAgentSystem();+ this._initWidgetBridge();+ }++ // First-time orientation overlay for a freshly created (or freshly loaded)+ // agent. Localstorage-keyed per agent so it never reappears once dismissed.+ _maybeShowOnboarding(agentId) {+ if (typeof window === 'undefined' || !agentId) return;+ const key = `3dagent:onboarded:${agentId}`;+ try {+ if (localStorage.getItem(key)) return;+ } catch {+ return;+ }++ const banner = document.getElementById('agent-onboarding');+ if (!banner) return;++ const closeBtn = document.getElementById('agent-onboarding-close');+ const deployLink = document.getElementById('agent-onboarding-deploy');+ const shareLink = document.getElementById('agent-onboarding-share');++ if (deployLink) deployLink.href = `/deploy?agent=${agentId}`;+ if (shareLink) shareLink.href = `/agent/${agentId}`;++ const dismiss = () => {+ banner.hidden = true;+ try {+ localStorage.setItem(key, '1');+ } catch {}+ };++ if (closeBtn) closeBtn.addEventListener('click', dismiss);+ // Auto-dismiss when the user clicks any of the CTAs — they've engaged.+ [deployLink, shareLink].forEach((el) => {+ if (el) el.addEventListener('click', dismiss);+ });++ banner.hidden = false;+ }++ async _loadWidget(widgetId) {+ let widget;+ try {+ widget = await getWidget(widgetId);+ } catch (err) {+ this._showWidgetError(`Widget not found: ${widgetId}`);+ return;+ }+ window.VIEWER.widget = widget;++ const cfg = { ...(widget.config || {}) };+ const modelUrl = widget.avatar?.model_url || '/avatars/cz.glb';++ // Apply per-embed URL overrides (set by Studio embed modal checkboxes).+ if (this.options.noAnimations) cfg.showClipPicker = false;+ if (this.options.noChat) cfg._noChat = true;+ if (this.options.noControls) cfg.showControls = false;++ // Apply config to options BEFORE creating the viewer so first frame is right.+ if (Array.isArray(cfg.cameraPosition) && cfg.cameraPosition.length === 3) {+ this.options.cameraPosition = cfg.cameraPosition;+ }+ if (cfg.envPreset && cfg.envPreset !== 'none') {+ this.options.preset = cfg.envPreset;+ }++ // Kiosk + showControls drive the chrome.+ if (cfg.showControls === false || this.options.kiosk) {+ document.querySelector('header')?.style.setProperty('display', 'none');+ }++ const resolved = isDecentralizedURI(modelUrl) ? resolveURI(modelUrl) : modelUrl;+ this.view(resolved, '', new Map());++ // Apply post-create brand bits once viewer exists.+ queueMicrotask(() => this._applyWidgetConfig(cfg));++ // Type-specific mount (runs after viewer + content come up).+ queueMicrotask(() => this._mountWidgetByType(widget.type, cfg, widget.id));++ // Caption overlay — render once, simple.+ if (cfg.caption) this._renderWidgetCaption(cfg.caption);++ // Notify parent (script embed / Studio) that we're up.+ this._postToParent({ type: 'widget:ready', id: widget.id, widgetType: widget.type });+ }++ async _mountWidgetByType(type, cfg, widgetId) {+ try {+ if (type === 'animation-gallery') {+ const container = document.body;+ const ctl = await mountAnimationGallery(this.viewer, cfg, container);+ this._widgetController = ctl;+ } else if (type === 'talking-agent' && !cfg._noChat) {+ const ctl = await mountTalkingAgent(this.viewer, cfg, document.body, {+ widgetId,+ getSceneCtrl: () => this.sceneCtrl || window.VIEWER?.scene_ctrl || null,+ protocol,+ identity: this.identity,+ });+ this._widgetController = ctl;+ } else if (type === 'turntable') {+ const ctl = await mountTurntable(this.viewer, cfg);+ this._widgetController = ctl;+ } else if (type === 'hotspot-tour') {+ const ctl = await mountHotspotTour(this.viewer, cfg, document.body);+ this._widgetController = ctl;+ } else if (type === 'pumpfun-feed') {+ const ctl = await mountPumpfunFeed(this.viewer, cfg, document.body, { protocol });+ this._widgetController = ctl;+ }+ } catch (e) {+ console.warn('[widget] mount failed', type, e?.message);+ }+ }++ _applyWidgetConfig(cfg) {+ if (!this.viewer) return;+ try {+ if (cfg.background) this.viewer.setBackgroundColor(cfg.background);+ if (cfg.accent) {+ document.documentElement.style.setProperty('--accent', cfg.accent);+ const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(cfg.accent);+ if (m) {+ document.documentElement.style.setProperty(+ '--accent-soft',+ `rgba(${parseInt(m[1], 16)},${parseInt(m[2], 16)},${parseInt(m[3], 16)},0.18)`,+ );+ }+ }+ if (typeof cfg.autoRotate === 'boolean' && this.viewer.controls) {+ this.viewer.controls.autoRotate = cfg.autoRotate;+ if (typeof cfg.rotationSpeed === 'number') {+ this.viewer.controls.autoRotateSpeed = cfg.rotationSpeed;+ }+ }+ if (cfg.envPreset && this.viewer.setEnvironment) {+ this.viewer.setEnvironment(cfg.envPreset);+ }+ } catch (e) {+ console.warn('[widget] applyConfig failed', e?.message);+ }+ }++ _renderWidgetCaption(text) {+ let el = document.getElementById('widget-caption');+ if (!el) {+ el = document.createElement('div');+ el.id = 'widget-caption';+ el.style.cssText =+ 'position:fixed;left:50%;bottom:20px;transform:translateX(-50%);padding:8px 18px;background:rgba(0,0,0,0.55);color:#fff;font-family:Inter,system-ui,sans-serif;font-size:14px;border-radius:999px;backdrop-filter:blur(8px);z-index:5;pointer-events:none;max-width:90vw;text-align:center';+ document.body.appendChild(el);+ }+ el.textContent = text;+ }++ _showWidgetError(message) {+ const el = document.createElement('div');+ el.style.cssText =+ 'position:fixed;inset:0;display:grid;place-items:center;background:#0a0a0a;color:#e0e0e0;font-family:Inter,system-ui,sans-serif;text-align:center;padding:2rem;z-index:9999';+ el.innerHTML = `<div><h1 style="font-weight:300;margin:0 0 0.5rem">Widget unavailable</h1><p style="opacity:0.7;margin:0">${message.replace(/[<>&"]/g, '')}</p><p style="margin-top:1.5rem"><a href="/" style="color:#8b5cf6">Open viewer</a> · <a href="/widgets" style="color:#8b5cf6">Browse gallery</a></p></div>`;+ document.body.appendChild(el);+ }++ _initWidgetBridge() {+ // Studio sends live config updates without a full reload. Also handles+ // runtime commands (play_clip, wave) for parent-driven embeds.+ window.addEventListener('message', (event) => {+ if (event.origin !== location.origin) return;+ const data = event.data;+ if (!data || typeof data !== 'object') return;++ if (data.type === 'widget:config' && data.config) {+ this._applyWidgetConfig(data.config);+ if (typeof data.config.caption === 'string') {+ this._renderWidgetCaption(data.config.caption);+ }+ // Preview mode (#model= + type=): mount widget runtime on first config message.+ if (this.options.type && !this._previewMounted) {+ this._previewMounted = true;+ this._mountWidgetByType(this.options.type, data.config, null).catch(() => {});+ }+ return;+ }++ if (data.type === 'widget:command' && data.command) {+ this._handleWidgetCommand(data.command, data.args || {});+ }++ // Forward pumpfun-feed focus changes from the parent frame to the+ // mounted widget overlay (which listens on document.body).+ if (data.type === 'pumpfun-feed:focus-mint') {+ document.body.dispatchEvent(+ new CustomEvent('pumpfun-feed:focus-mint', {+ detail: { mint: data.mint || null },+ bubbles: true,+ }),+ );+ }+ if (data.type === 'pumpfun-feed:set-narrate') {+ document.body.dispatchEvent(+ new CustomEvent('pumpfun-feed:set-narrate', {+ detail: { on: !!data.on },+ bubbles: true,+ }),+ );+ }+ });+ }++ _handleWidgetCommand(command, args) {+ const sceneCtrl = this.sceneCtrl || window.VIEWER?.scene_ctrl;+ if (!sceneCtrl) return;+ try {+ switch (command) {+ case 'play_clip':+ sceneCtrl.playClipByName?.(args.name);+ break;+ case 'lookAt':+ sceneCtrl.lookAt?.(args.target);+ break;+ case 'setExpression':+ sceneCtrl.setExpression?.(args.name, args.weight);+ break;+ }+ } catch (e) {+ console.warn('[widget] command failed', command, e?.message);+ }+ }++ _postToParent(msg) {+ if (window.parent && window.parent !== window) {+ window.parent.postMessage(msg, '*');+ }+ }++ _initNichAgent() {+ const agent = new NichAgent(+ document.body,+ protocol,+ this.skills,+ this.identity,+ this.runtime,+ );+ window.VIEWER.agent = agent;+ // Greet on first open+ agent.onFirstOpen = () => {+ this.skills.perform('greet', {}, { identity: this.identity });+ };+ }++ // ── Viewer setup + Avatar attachment ────────────────────────────────────++ /**+ * Sets up the view manager.+ * @return {Viewer}+ */+ createViewer() {+ if (this.viewer) this.viewer.dispose();+ this.viewerEl = this.viewerContainerEl;+ this.viewer = new Viewer(this.viewerEl, this.options);+ if (!this.options.kiosk) {+ this.editor = new Editor(this.viewer);+ this.editor.attach();+ window.VIEWER.editor = this.editor;+ }+ window.VIEWER.viewer = this.viewer;+ return this.viewer;+ }++ // ── Dropzone ─────────────────────────────────────────────────────────────++ createDropzone() {+ const dropCtrl = new SimpleDropzone(this.dropEl, this.inputEl);+ dropCtrl.on('drop', ({ files }) => this.load(files));+ dropCtrl.on('dropstart', () => this.showSpinner());+ dropCtrl.on('droperror', () => this.hideSpinner());+ }++ // ── Avatar Creator ────────────────────────────────────────────────────────++ setupAvatarCreator() {+ this.avatarCreator = new AvatarCreator(document.body, async (glbSource) => {+ this.view(glbSource, '', new Map());+ try {+ const avatar = await saveRemoteGlbToAccount(glbSource, {+ source: 'avaturn',+ source_meta: { provider: 'avaturn' },+ });+ this._flashSaved(avatar);+ } catch (err) {+ if (err.code !== 'not_signed_in') {+ console.warn('[3d-agent] save to account failed:', err.message);+ }+ }+ });+ }++ // ── File Loading ──────────────────────────────────────────────────────────++ /**+ * @param {Map<string, File>} fileMap+ */+ load(fileMap) {+ let rootFile, rootPath;+ Array.from(fileMap).forEach(([path, file]) => {+ if (file.name.match(/\.(gltf|glb)$/)) {+ rootFile = file;+ rootPath = path.replace(file.name, '');+ }+ });++ if (!rootFile) {+ this.onError('No .gltf or .glb asset found.');+ }++ return this.view(rootFile, rootPath, fileMap);+ }++ /**+ * @param {File|string} rootFile+ * @param {string} rootPath+ * @param {Map<string, File>} fileMap+ */+ view(rootFile, rootPath, fileMap) {+ if (this.viewer) this.viewer.clear();++ const viewer = this.viewer || this.createViewer();+ const fileURL = typeof rootFile === 'string' ? rootFile : URL.createObjectURL(rootFile);++ this._currentModelUrl = typeof rootFile === 'string' ? rootFile : null;+ this._hasLocalGlb = typeof rootFile !== 'string';+ this._currentLocalFile = typeof rootFile !== 'string' ? rootFile : null;+ this._refreshMakeWidgetButton();+ this._refreshSaveToAccountButton();++ // 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);+ };++ return viewer+ .load(fileURL, rootPath, fileMap)+ .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) => {+ 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);++ // Notify the editor of the new model so it can rebuild panels+ if (this.editor) {+ const isString = typeof rootFile === 'string';+ this.editor.onContentChanged({+ url: isString ? rootFile : null,+ file: isString ? null : rootFile,+ name: isString ? rootFile.split('/').pop().split('?')[0] : rootFile.name,+ });+ }++ // Configure external animations (Mixamo-style) for skinned models+ this._configureAnimations(viewer);++ // Update AR button target (GLB URL only; no USDZ companion in this project)+ if (viewer.setARTarget) {+ const glbUrl = typeof rootFile === 'string' ? fileURL : null;+ viewer.setARTarget(glbUrl);+ }++ if (!this.options.kiosk) {+ this.validator.validate(fileURL, rootPath, fileMap, gltf);+ }+ cleanup();+ });+ }++ /** 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();++ // Create (or replace) the SceneController for agent scene operations+ this.sceneCtrl = new SceneController(viewer);+ if (this.runtime) this.runtime.viewer = this.sceneCtrl;++ // Update agent-home with the live avatar reference+ if (this.agentHome) this.agentHome.avatar = this.avatar;++ window.VIEWER.agent_avatar = this.avatar;+ window.VIEWER.scene_ctrl = this.sceneCtrl;++ // Let the skills system access the viewer+ if (this.skills) {+ window.VIEWER.agent_skills = this.skills;+ }+ }++ /**+ * Configure Mixamo-style external animations for the viewer.+ * Looks for animation GLBs in /animations/ and registers them.+ * Each GLB should contain a single animation clip exported from Mixamo+ * (downloaded as GLB with "Without Skin" checked).+ */+ _configureAnimations(viewer) {+ // Check if model has a skeleton+ let hasSkeleton = false;+ if (viewer.content) {+ viewer.content.traverse((node) => {+ if (node.isSkinnedMesh) hasSkeleton = true;+ });+ }+ if (!hasSkeleton) return;++ // Fetch the animation manifest+ fetch('/animations/manifest.json')+ .then((r) => {+ if (!r.ok) throw new Error('No animation manifest');+ return r.json();+ })+ .then((manifest) => {+ if (Array.isArray(manifest) && manifest.length > 0) {+ viewer.setAnimationDefs(manifest);+ }+ })+ .catch(() => {+ // No manifest — use sensible defaults if files exist+ const defaults = [+ { name: 'idle', url: '/animations/idle.glb', label: 'Idle' },+ { name: 'walking', url: '/animations/walking.glb', label: 'Walking' },+ { name: 'running', url: '/animations/running.glb', label: 'Running' },+ { name: 'waving', url: '/animations/waving.glb', label: 'Waving' },+ { name: 'dancing', url: '/animations/dancing.glb', label: 'Dancing' },+ { name: 'sitting', url: '/animations/sitting.glb', label: 'Sitting' },+ { name: 'jumping', url: '/animations/jumping.glb', label: 'Jumping' },+ ];++ // Probe which files actually exist (HEAD requests)+ Promise.all(+ defaults.map((def) =>+ fetch(def.url, { method: 'HEAD' })+ .then((r) => (r.ok ? def : null))+ .catch(() => null),+ ),+ ).then((results) => {+ const available = results.filter(Boolean);+ if (available.length > 0) {+ viewer.setAnimationDefs(available);+ }+ });+ });+ }++ // ── 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+ */+ onError(error) {+ let message = (error || {}).message || error.toString();+ if (message.match(/ProgressEvent/)) {+ message = 'Unable to retrieve this file. Check JS console and browser network tab.';+ } else if (message.match(/Unexpected token/)) {+ message = `Unable to parse file content. Verify that this file is valid. Error: "${message}"`;+ } else if (error && error.target && error.target instanceof Image) {+ message = 'Missing texture: ' + error.target.src.split('/').pop();+ }+ window.alert(message);+ console.error(error);+ }++ /**+ * Resolve an on-chain ERC-8004 agent to its 3D avatar and render it.+ * Public — works for anyone, no wallet required.+ *+ * @param {{ chainId: number, agentId: string, registry?: string }} onchain+ */+ async _loadOnChainAgent(onchain) {+ try {+ const [+ { getAgentOnchain, fetchAgentMetadata, findAvatar3D },+ { REGISTRY_DEPLOYMENTS },+ ] = await Promise.all([import('./erc8004/queries.js'), import('./erc8004/abi.js')]);++ if (!REGISTRY_DEPLOYMENTS[onchain.chainId]) {+ this._showOnChainError(`Unsupported chain: ${onchain.chainId}`);+ return;+ }++ const { uri } = await getAgentOnchain({+ chainId: onchain.chainId,+ agentId: onchain.agentId,+ ethProvider: window.ethereum,+ });+ if (!uri) {+ this._showOnChainError(`Agent #${onchain.agentId} has no agentURI set.`);+ return;+ }++ const meta = await fetchAgentMetadata(uri);+ if (!meta.ok) {+ this._showOnChainError(`Could not fetch registration JSON: ${meta.error}`);+ return;+ }++ this._onchainMetadata = meta.data;+ this._updateOnChainCard(onchain, meta.data);++ const glbUri = findAvatar3D(meta.data);+ if (!glbUri) {+ this._showOnChainError(+ `Agent #${onchain.agentId} has no 3D avatar — no <code>avatar</code> service entry and <code>image</code> is not a GLB.`,+ );+ return;+ }++ const resolvedGlb = isDecentralizedURI(glbUri) ? resolveURI(glbUri) : glbUri;+ await this.view(resolvedGlb, '', new Map());+ } catch (err) {+ console.warn('[3d-agent] on-chain load failed:', err);+ this._showOnChainError(err.message || String(err));+ }+ }++ _showOnChainError(msg) {+ this._updateOnChainCard(this.options.onchain, null, msg);+ this.dropEl?.classList.add('hidden');+ }++ /**+ * Render a small info card overlaying the viewer so users know whose agent+ * they're looking at. Hidden in kiosk mode.+ */+ _updateOnChainCard(onchain, metadata, errorMsg = '') {+ if (this.options.kiosk) return;+ let card = this.el.querySelector('.onchain-card');+ if (!card) {+ card = document.createElement('div');+ card.className = 'onchain-card';+ this.el.appendChild(card);+ }+ const chainLabel = `chainId ${onchain.chainId}`;+ if (errorMsg) {+ card.innerHTML = `<div class="onchain-card__err">⚠ ${escHtml(errorMsg)}</div>+ <div class="onchain-card__sub">Agent #${escHtml(onchain.agentId)} · ${escHtml(chainLabel)}</div>`;+ return;+ }+ const name = metadata?.name ? String(metadata.name) : `Agent #${onchain.agentId}`;+ const desc = metadata?.description ? String(metadata.description) : '';+ card.innerHTML = `+ <div class="onchain-card__name">${escHtml(name)}</div>+ <div class="onchain-card__sub">#${escHtml(onchain.agentId)} · ${escHtml(chainLabel)}</div>+ ${desc ? `<div class="onchain-card__desc">${escHtml(desc)}</div>` : ''}+ `;+ }++ async _showShowcasePage() {+ try {+ const main = this.el.querySelector('main.wrap') || this.el;+ this.dropEl?.classList.add('hidden');+ const dropzone = this.el.querySelector('.dropzone');+ if (dropzone) dropzone.style.display = 'none';+ if (this.viewerContainerEl) this.viewerContainerEl.style.display = 'none';+ const authGate = this.el.querySelector('#auth-gate');+ if (authGate) authGate.style.display = 'none';+ const presence = this.el.querySelector('.agent-presence-sidebar');+ if (presence) presence.style.display = 'none';++ const page = document.createElement('section');+ page.className = 'showcase-page';+ main.appendChild(page);++ const { renderShowcasePage } = await import('./erc8004/showcase.js');+ renderShowcasePage(page);+ } catch (err) {+ console.error('[3d-agent] showcase page load failed', err);+ }+ }++ async _showDeployPage() {+ // Render /deploy as a normal page inside the app.html shell (header ++ // footer stay visible). We hide the viewer + dropzone + auth gate and+ // replace them with the ERC-8004 wizard, pre-filled from the user's+ // current avatar so Step 5 flows from Steps 1–4.+ //+ // Deep-link support: `/deploy?avatar=<id>` pre-fills from a previously+ // saved avatar (dashboard "Deploy on-chain" per row). That prefill+ // overrides the viewer's current model.+ try {+ const main = this.el.querySelector('main.wrap') || this.el;+ this.dropEl?.classList.add('hidden');+ const dropzone = this.el.querySelector('.dropzone');+ if (dropzone) dropzone.style.display = 'none';+ if (this.viewerContainerEl) this.viewerContainerEl.style.display = 'none';+ const authGate = this.el.querySelector('#auth-gate');+ if (authGate) authGate.style.display = 'none';+ const presence = this.el.querySelector('.agent-presence-sidebar');+ if (presence) presence.style.display = 'none';++ const page = document.createElement('section');+ page.className = 'deploy-page';+ main.appendChild(page);++ this._upgradeToHorizonFooter();++ const initial = await this._resolveDeployInitial();++ const { RegisterUI } = await import('./erc8004/register-ui.js');+ new RegisterUI(+ page,+ (result) => {+ console.info('[ERC-8004] Agent registered:', result);+ },+ { mode: 'page', initial },+ );+ } catch (err) {+ console.error('[3d-agent] deploy page load failed', err);+ }+ }++ /**+ * Resolve the initial state passed to RegisterUI. If `?avatar=<id>` is+ * present, fetch that avatar from the backend and pre-fill name /+ * description / image / GLB. Otherwise fall back to the current viewer+ * model.+ */+ async _resolveDeployInitial() {+ const qp = new URLSearchParams(location.search);+ const avatarId = qp.get('avatar');+ const fallback = { glbUrl: this._currentModelUrl || '' };+ if (!avatarId) return fallback;+ try {+ const res = await fetch(`/api/avatars/${encodeURIComponent(avatarId)}`, {+ credentials: 'include',+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const { avatar } = await res.json();+ if (!avatar) throw new Error('empty avatar payload');+ return {+ name: avatar.name || '',+ description: avatar.description || '',+ imageUrl: avatar.thumbnail_url || '',+ glbUrl: avatar.url || avatar.model_url || '',+ };+ } catch (err) {+ console.warn('[deploy] avatar prefill failed; falling back to viewer model', err);+ return fallback;+ }+ }++ _upgradeToHorizonFooter() {+ const existing = document.querySelector('footer');+ if (!existing) return;+ existing.outerHTML = `<footer class="h-footer h-footer-horizon">+ <div class="h-footer-glow-line" aria-hidden="true"></div>+ <div class="h-footer-floor" aria-hidden="true"></div>+ <div class="h-footer-haze" aria-hidden="true"></div>+ <div class="h-footer-watermark" aria-hidden="true">three.ws</div>+ <div class="h-footer-inner">+ <div class="h-footer-brand-col">+ <div class="h-footer-brand">+ <span class="wordmark-dot" aria-hidden="true"></span>+ <span>three.ws</span>+ </div>+ <p class="h-footer-tagline">Give your AI a body.</p>+ </div>+ <nav class="h-footer-links" aria-label="Footer">+ <a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>+ <a href="/create">Create</a>+ <a href="/studio">Studio</a>+ <a href="/widgets">Widgets</a>+ <a href="/features">Features</a>+ <a href="/discover">Discover</a>+ <a href="/docs">Docs</a>+ <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>+ </nav>+ </div>+ <div class="h-footer-bottom">+ <p class="h-footer-legal">© 2026 three.ws — All rights reserved.</p>+ <div class="h-footer-badges">+ <span class="h-footer-badge" aria-label="System status">+ <span class="h-footer-status-dot" aria-hidden="true"></span>+ <span>All systems normal</span>+ </span>+ <a class="h-footer-badge" href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener" aria-label="View source on GitHub">+ <svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>+ <span>Open source</span>+ </a>+ </div>+ </div>+ </footer>`;+ }++ 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;+ console.info('[three.ws] Debugging data exported as `window.VIEWER`.');+});diff --git a/publish/src/ar/quick-look.js b/publish/src/ar/quick-look.jsnew file mode 100644index 000000000..8cb2333ea--- /dev/null+++ b/publish/src/ar/quick-look.js@@ -0,0 +1,23 @@+// iOS Quick Look — opens a USDZ companion using the <a rel="ar"> trick.+// Safari activates Quick Look when an anchor with rel="ar" is activated+// programmatically, which avoids requiring a real user gesture on a link.++function isIOS() {+ return (+ /iphone|ipad|ipod/i.test(navigator.userAgent) ||+ (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)+ );+}++export function canUseQuickLook() {+ return isIOS();+}++export function openQuickLook(usdzURI) {+ const a = document.createElement('a');+ a.rel = 'ar';+ a.href = usdzURI;+ // iOS requires a child element to trigger Quick Look on programmatic .click()+ a.appendChild(document.createElement('img'));+ a.click();+}diff --git a/publish/src/ar/scene-viewer.js b/publish/src/ar/scene-viewer.jsnew file mode 100644index 000000000..6ee098827--- /dev/null+++ b/publish/src/ar/scene-viewer.js@@ -0,0 +1,27 @@+// Android Scene Viewer fallback — launches ARCore via Intent URL.+// Acceptable to UA-sniff here: this path is only triggered when WebXR is absent.++function isAndroid() {+ return /android/i.test(navigator.userAgent);+}++export function canUseSceneViewer() {+ return isAndroid();+}++export function openSceneViewer(glbURL, { title = '', link = '' } = {}) {+ const params = new URLSearchParams({ file: glbURL, mode: 'ar_preferred' });+ if (title) params.set('title', title);+ if (link) params.set('link', link);++ // S.browser_fallback_url ensures the user lands back on the page if ARCore+ // is missing rather than ending up on an error screen.+ const fallback = encodeURIComponent(location.href);+ const intentURL =+ `intent://arvr.google.com/scene-viewer/1.2?${params.toString()}` ++ `#Intent;scheme=https;package=com.google.ar.core;` ++ `action=android.intent.action.VIEW;` ++ `S.browser_fallback_url=${fallback};end;`;++ location.href = intentURL;+}diff --git a/publish/src/ar/webxr.js b/publish/src/ar/webxr.jsnew file mode 100644index 000000000..4639e38d0--- /dev/null+++ b/publish/src/ar/webxr.js@@ -0,0 +1,157 @@+// WebXR immersive-ar session controller.+//+// Reuses the element's existing Three.js renderer by enabling XR mode on start+// and restoring the RAF loop on end. Hit-test places the agent on tap.++import { Matrix4, Vector3 } from 'three';++export class WebXRSession {+ constructor(viewer, { onEnd } = {}) {+ this._viewer = viewer;+ this._onEnd = onEnd;+ this._session = null;+ this._hitTestSource = null;+ this._localSpace = null;+ this._anchored = false;+ this._userPosition = new Vector3();+ this._savedBg = null;+ this._savedPos = null;+ this._savedRot = null;+ this._handleEnd = this._handleEnd.bind(this);+ this._handleSelect = this._handleSelect.bind(this);+ }++ static async isSupported() {+ try {+ return !!(navigator.xr && (await navigator.xr.isSessionSupported('immersive-ar')));+ } catch {+ return false;+ }+ }++ async start() {+ const viewer = this._viewer;+ const renderer = viewer.renderer;++ // Must be set before requestSession+ renderer.xr.enabled = true;++ const session = await navigator.xr.requestSession('immersive-ar', {+ requiredFeatures: ['hit-test'],+ });+ this._session = session;+ session.addEventListener('end', this._handleEnd);+ // 'select' fires on controller trigger or screen tap+ session.addEventListener('select', this._handleSelect);++ await renderer.xr.setSession(session);++ this._localSpace = await session.requestReferenceSpace('local');+ const viewerSpace = await session.requestReferenceSpace('viewer');+ this._hitTestSource = await session.requestHitTestSource({ space: viewerSpace });++ // Transparent background — device camera provides the pass-through+ this._savedBg = viewer.scene.background;+ viewer.scene.background = null;+ renderer.setClearColor(0x000000, 0);++ // Save agent content transform for clean restoration on exit+ const content = viewer.content;+ this._savedPos = content?.position.clone() ?? null;+ this._savedRot = content?.rotation.clone() ?? null;++ // Hand the render loop to the XR system (replaces RAF)+ if (viewer._rafId !== null) {+ cancelAnimationFrame(viewer._rafId);+ viewer._rafId = null;+ }+ viewer.controls.enabled = false;++ renderer.setAnimationLoop((time, frame) => this._tick(time, frame));+ }++ _tick(time, frame) {+ const viewer = this._viewer;+ const renderer = viewer.renderer;++ const dt = viewer.prevTime ? (time - viewer.prevTime) / 1000 : 0.016;+ viewer.prevTime = time;++ if (viewer.mixer) viewer.mixer.update(dt);+ viewer.animationManager.update(dt);++ // Empathy layer and any other per-frame hooks continue uninterrupted+ if (viewer._afterAnimateHooks) {+ for (const hook of viewer._afterAnimateHooks) hook(dt);+ }++ // Track user head position from the XR camera — used by lookAt('user')+ const xrCam = renderer.xr.getCamera();+ if (xrCam) this._userPosition.setFromMatrixPosition(xrCam.matrixWorld);++ // Follow hit-test surface until the agent is anchored by a tap+ if (!this._anchored && frame && this._hitTestSource) {+ const hits = frame.getHitTestResults(this._hitTestSource);+ if (hits.length > 0 && viewer.content) {+ const pose = hits[0].getPose(this._localSpace);+ if (pose) {+ viewer.content.position.setFromMatrixPosition(+ new Matrix4().fromArray(pose.transform.matrix),+ );+ }+ }+ }++ renderer.render(viewer.scene, viewer.activeCamera);+ }++ // First tap anchors the agent at the current hit-test position+ _handleSelect() {+ this._anchored = true;+ }++ // Returns the current XR camera (user head) position for lookAt('user')+ getUserPosition() {+ return this._userPosition.clone();+ }++ async end() {+ if (this._session) {+ try {+ await this._session.end();+ } catch {}+ // _handleEnd fires from the 'end' event+ }+ }++ _handleEnd() {+ const viewer = this._viewer;+ const renderer = viewer.renderer;++ renderer.setAnimationLoop(null);+ renderer.xr.enabled = false;++ if (this._hitTestSource) {+ try {+ this._hitTestSource.cancel();+ } catch {}+ this._hitTestSource = null;+ }+ this._session = null;+ this._anchored = false;++ // Restore background+ viewer.scene.background = this._savedBg;+ renderer.setClearColor(0x000000, 1);++ // Restore agent content to its pre-AR transform+ if (viewer.content && this._savedPos) viewer.content.position.copy(this._savedPos);+ if (viewer.content && this._savedRot) viewer.content.rotation.copy(this._savedRot);++ viewer.controls.enabled = true;+ viewer._needsRender = true;+ viewer._updateRenderLoop();++ this._onEnd?.();+ }+}diff --git a/publish/src/artifact/entry.js b/publish/src/artifact/entry.jsnew file mode 100644index 000000000..d0d52a7e1--- /dev/null+++ b/publish/src/artifact/entry.js@@ -0,0 +1,144 @@+// three.ws Claude Artifact Bundle+// Lightweight viewer for agents inside Claude Artifacts+// Loads three.js from CDN (esm.sh is allowed in artifact sandboxes)+// Usage: <script src="artifact.js"></script>+// <div id="agent3d" data-agent-id="123"></div>++(async function initArtifact() {+ const container = document.getElementById('agent3d');+ if (!container) return;++ // Setup container+ container.style.cssText =+ 'position: relative; width: 100%; height: 100%; min-height: 400px; background: #000;';++ // Add caption+ const caption = document.createElement('div');+ caption.className = 'agent3d-caption';+ caption.style.cssText = `+ position: absolute;+ bottom: 0;+ left: 0;+ right: 0;+ background: rgba(0, 0, 0, 0.6);+ color: #fff;+ padding: 12px 16px;+ font-family: system-ui, -apple-system, sans-serif;+ font-size: 14px;+ z-index: 5;+ text-align: center;+ `;+ caption.textContent = 'Loading...';+ container.appendChild(caption);++ // Get agent ID from config or data attributes+ const scriptTag = document.querySelector(+ 'script[type="application/json"][id="agent3d-config"]',+ );+ const config = scriptTag ? JSON.parse(scriptTag.textContent) : {};+ const agentId = config.agentId || container.dataset.agentId;+ const origin = config.origin || container.dataset.origin || 'https://three.ws/';++ if (!agentId) {+ caption.textContent = 'Missing agent ID';+ return;+ }++ try {+ // Load three.js modules from CDN+ const THREE = await import('https://esm.sh/[email protected]');+ const { GLTFLoader } = await import(+ 'https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js'+ );+ const { OrbitControls } = await import(+ 'https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js'+ );++ // Fetch agent data+ const agentRes = await fetch(`${origin}/api/agents/${agentId}`, {+ mode: 'cors',+ credentials: 'omit',+ });++ if (!agentRes.ok) {+ caption.textContent = 'Agent not found';+ return;+ }++ const agentData = await agentRes.json();+ const agent = agentData.agent;++ // Update caption with agent name+ caption.textContent = agent.name || 'Agent';++ // Setup scene+ const width = container.clientWidth;+ const height = container.clientHeight;++ const scene = new THREE.Scene();+ scene.background = new THREE.Color(0x000000);+ scene.fog = new THREE.Fog(0x000000, 1, 1000);++ // Lighting+ const ambientLight = new THREE.AmbientLight(0xffffff, 1.0);+ scene.add(ambientLight);++ const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);+ directionalLight.position.set(5, 10, 7);+ directionalLight.castShadow = true;+ directionalLight.shadow.mapSize.width = 2048;+ directionalLight.shadow.mapSize.height = 2048;+ directionalLight.shadow.camera.near = 0.5;+ directionalLight.shadow.camera.far = 500;+ scene.add(directionalLight);++ // Camera+ const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);+ camera.position.set(0, 1.5, 3);++ // Renderer+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });+ renderer.setSize(width, height);+ renderer.setPixelRatio(window.devicePixelRatio);+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFShadowMap;+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.0;++ const canvas = container.querySelector('canvas');+ if (canvas) canvas.remove();+ container.insertBefore(renderer.domElement, caption);++ // Controls+ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.05;+ controls.enableZoom = true;+ controls.autoRotate = true;+ controls.autoRotateSpeed = 2;+ controls.enablePan = false;+ controls.minDistance = 2;+ controls.maxDistance = 10;++ // Animation loop+ function animate() {+ requestAnimationFrame(animate);+ controls.update();+ renderer.render(scene, camera);+ }+ animate();++ // Handle resize+ window.addEventListener('resize', () => {+ const w = container.clientWidth;+ const h = container.clientHeight;+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ renderer.setSize(w, h);+ });+ } catch (err) {+ console.error('[artifact] error:', err);+ caption.textContent = 'Failed to load viewer';+ }+})();diff --git a/publish/src/arweave/upload.js b/publish/src/arweave/upload.jsnew file mode 100644index 000000000..87d526563--- /dev/null+++ b/publish/src/arweave/upload.js@@ -0,0 +1,97 @@+/**+ * Arweave permanent storage via ArDrive Turbo.+ *+ * Uploads a Blob/Uint8Array and returns an ar:// URI that resolves forever.+ * Requires an Ethereum signer (e.g. from connectWallet()) — Turbo signs with+ * the same wallet the user already connected for ERC-8004 registration.+ *+ * Usage:+ * import { uploadToArweave } from '../arweave/upload.js';+ * const arUri = await uploadToArweave(glbBytes, signer, { name: 'agent.glb' });+ * // → 'ar://abc123txId'+ */++/**+ * Upload a blob to Arweave via Turbo and return an ar:// URI.+ *+ * @param {Blob|Uint8Array} data+ * @param {import('ethers').Signer} ethSigner Connected ethers signer+ * @param {{ name?: string, contentType?: string }} [opts]+ * @returns {Promise<string>} ar://<txId>+ */+export async function uploadToArweave(data, ethSigner, opts = {}) {+ const { name = 'upload', contentType = 'application/octet-stream' } = opts;++ // Lazy import — keeps @ardrive/turbo-sdk out of the main bundle until called.+ // Install when ready: npm install @ardrive/turbo-sdk+ const { TurboFactory, EthereumSigner } = await import('@ardrive/turbo-sdk/web');++ const privateKey = await _signerToPrivateKey(ethSigner);+ const turboSigner = new EthereumSigner(privateKey);+ const turbo = TurboFactory.authenticated({ signer: turboSigner });++ const bytes = data instanceof Uint8Array ? data : new Uint8Array(await data.arrayBuffer());+ const stream = _bytesToStream(bytes);++ const result = await turbo.uploadFile({+ fileStreamFactory: () => stream,+ fileSizeFactory: () => bytes.byteLength,+ signal: opts.signal,+ dataItemOpts: {+ tags: [+ { name: 'Content-Type', value: contentType },+ { name: 'App-Name', value: 'three.ws' },+ { name: 'File-Name', value: name },+ ],+ },+ });++ return `ar://${result.id}`;+}++/**+ * Estimate the Turbo credit cost for a given byte size (no wallet needed).+ *+ * @param {number} bytes+ * @returns {Promise<{winc: string}>} Winston credits needed+ */+export async function estimateUploadCost(bytes) {+ const { TurboFactory } = await import('@ardrive/turbo-sdk/web');+ const turbo = TurboFactory.unauthenticated();+ return turbo.getUploadCosts({ bytes: [bytes] });+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function _bytesToStream(bytes) {+ return new ReadableStream({+ start(controller) {+ controller.enqueue(bytes);+ controller.close();+ },+ });+}++/**+ * Extract the raw hex private key from an ethers Signer.+ * Works with ethers v6 JsonRpcSigner and Wallet.+ *+ * @param {import('ethers').Signer} signer+ * @returns {Promise<string>}+ */+async function _signerToPrivateKey(signer) {+ // ethers Wallet exposes .privateKey directly+ if (signer.privateKey) return signer.privateKey;++ // JsonRpcSigner (MetaMask etc.) — private key is not exportable from the+ // browser wallet. In that case the caller must pass a raw private key string+ // via signer._privateKey, or use a dedicated Arweave JWK wallet instead.+ if (signer._privateKey) return signer._privateKey;++ throw new Error(+ 'uploadToArweave: cannot extract private key from injected wallet signer. ' ++ 'Pass an ethers.Wallet instance or set signer._privateKey explicitly.',+ );+}diff --git a/publish/src/attestations/gltf.js b/publish/src/attestations/gltf.jsnew file mode 100644index 000000000..cd0163d12--- /dev/null+++ b/publish/src/attestations/gltf.js@@ -0,0 +1,140 @@+import { verifyMessage } from 'ethers';++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++async function sha256Hex(blob) {+ const buf = await blob.arrayBuffer();+ const digest = await crypto.subtle.digest('SHA-256', buf);+ return Array.from(new Uint8Array(digest))+ .map((b) => b.toString(16).padStart(2, '0'))+ .join('');+}++/** Sorted-key, no-whitespace JSON — stable across environments. */+function canonicalJSON(obj) {+ if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) return JSON.stringify(obj);+ const pairs = Object.keys(obj)+ .sort()+ .map((k) => `${JSON.stringify(k)}:${canonicalJSON(obj[k])}`);+ return `{${pairs.join(',')}}`;+}++/**+ * Canonical signing message:+ * agent-3d:attestation:gltf:v1:{agentId}:{glbSha256}:{summaryHash}+ *+ * summaryHash = SHA-256(canonicalJSON(summary))+ * This binds the signature to the agentId, the exact GLB bytes, and the+ * validator summary — tampering with any of those breaks verification.+ */+async function buildMessage(agentId, glbSha256, summary) {+ const enc = new TextEncoder();+ const buf = enc.encode(canonicalJSON(summary));+ const digest = await crypto.subtle.digest('SHA-256', buf);+ const summaryHash = Array.from(new Uint8Array(digest))+ .map((b) => b.toString(16).padStart(2, '0'))+ .join('');+ return `agent-3d:attestation:gltf:v1:${agentId}:${glbSha256}:${summaryHash}`;+}++// ---------------------------------------------------------------------------+// Public API+// ---------------------------------------------------------------------------++/**+ * Create a signed glTF-validator attestation for a GLB file.+ *+ * The returned object can be stored as JSON alongside the GLB (e.g. in+ * attestations/gltf-validator.json) and referenced from the agent manifest's+ * `attestations` array.+ *+ * @param {object} opts+ * @param {Blob} opts.glbBlob Raw GLB bytes+ * @param {object} opts.validatorReport gltf-validator result object+ * @param {import('ethers').Signer} opts.signer Wallet to sign with+ * @param {string} opts.agentId Agent token ID (string)+ * @returns {Promise<object>}+ */+export async function createGlTFAttestation({ glbBlob, validatorReport, signer, agentId }) {+ const glbSha256 = await sha256Hex(glbBlob);+ const issuer = (await signer.getAddress()).toLowerCase();++ const summary = {+ errors: validatorReport?.issues?.numErrors ?? 0,+ warnings: validatorReport?.issues?.numWarnings ?? 0,+ severityMax: validatorReport?.issues?.maxSeverity ?? -1,+ };++ const message = await buildMessage(agentId, glbSha256, summary);+ const signature = await signer.signMessage(message);++ return {+ type: 'gltf-validator',+ spec: 'agent-3d:attestation:gltf:v1',+ agentId,+ glbSha256,+ summary,+ issuer,+ issuedAt: new Date().toISOString(),+ signature,+ };+}++/**+ * Verify a glTF-validator attestation against the original GLB blob.+ *+ * Pure-crypto — no wallet connection required.+ *+ * @param {object} opts+ * @param {object} opts.attestation Parsed attestation JSON+ * @param {Blob} opts.glbBlob GLB to verify against+ * @param {string[]} [opts.trustedIssuers] Optional allowlist of issuer addresses+ * @returns {Promise<{valid: boolean, issuer: string, reasons: string[]}>}+ */+export async function verifyGlTFAttestation({ attestation, glbBlob, trustedIssuers }) {+ const reasons = [];++ // 1. Recompute GLB hash — catches any byte-level tampering+ const glbSha256 = await sha256Hex(glbBlob);+ if (glbSha256 !== attestation.glbSha256) {+ reasons.push(`GLB hash mismatch: computed ${glbSha256}, attested ${attestation.glbSha256}`);+ }++ // 2. Recover signer from signature — catches any field tampering+ // Note: we sign against the *attested* glbSha256 and summary so that+ // the hash mismatch above is independent of signature failure.+ const message = await buildMessage(+ attestation.agentId,+ attestation.glbSha256,+ attestation.summary,+ );+ let recoveredAddress;+ try {+ recoveredAddress = verifyMessage(message, attestation.signature).toLowerCase();+ } catch (e) {+ reasons.push(`Signature recovery failed: ${e.message}`);+ return { valid: false, issuer: attestation.issuer || '', reasons };+ }++ if (recoveredAddress !== attestation.issuer) {+ reasons.push(+ `Issuer mismatch: attested ${attestation.issuer}, recovered ${recoveredAddress}`,+ );+ }++ // 3. Optional: enforce a caller-supplied trusted-issuer list+ if (trustedIssuers?.length) {+ const lower = trustedIssuers.map((a) => a.toLowerCase());+ if (!lower.includes(recoveredAddress)) {+ reasons.push(`Issuer ${recoveredAddress} is not in trustedIssuers`);+ }+ }++ return {+ valid: reasons.length === 0,+ issuer: recoveredAddress || attestation.issuer || '',+ reasons,+ };+}diff --git a/publish/src/auth/README.md b/publish/src/auth/README.mdnew file mode 100644index 000000000..137de1460--- /dev/null+++ b/publish/src/auth/README.md@@ -0,0 +1,72 @@+# src/auth++WalletConnect → SIWE bridge for mobile-wallet sign-in without Privy.++## Environment variable++```+VITE_WALLETCONNECT_PROJECT_ID=<your_wc_project_id>+```++Get a project ID at [cloud.walletconnect.com](https://cloud.walletconnect.com). Add it to `.env.local` for local development and to Vercel environment variables for production.++If the variable is missing the bridge returns a `wc/no_project_id` error immediately — it does not throw an unhandled exception.++## CDN++The WalletConnect provider is lazy-loaded at call time (never in the main bundle):++```+https://esm.sh/@walletconnect/[email protected]+```++**Pinned version:** `2.17.0`. To upgrade, update the `WC_CDN` constant at the top of `walletconnect-bridge.js` and re-run the smoke test.++## Usage++```js+import {+ signInWithWalletConnect,+ getWalletConnectProvider,+ disconnectWalletConnect,+} from './auth/walletconnect-bridge.js';++// Opens WC modal, signs SIWE message, verifies with server, sets session cookie.+const { user, address } = await signInWithWalletConnect();++// Get the raw EIP-1193 provider (after connect).+const provider = getWalletConnectProvider();++// Disconnect.+await disconnectWalletConnect();+```++## Error codes++All errors have an `err.code` of the form `wc/<stage>`:++| Code | Meaning |+| --------------------- | ------------------------------------------- |+| `wc/no_project_id` | `VITE_WALLETCONNECT_PROJECT_ID` not set |+| `wc/load_failed` | CDN import failed (network / CSP) |+| `wc/init_failed` | EthereumProvider.init() threw |+| `wc/connect_rejected` | User closed modal or rejected session |+| `wc/no_accounts` | Provider returned no accounts after connect |+| `wc/nonce_failed` | `/api/auth/siwe/nonce` request failed |+| `wc/sign_rejected` | User rejected personal_sign |+| `wc/verify_failed` | `/api/auth/siwe/verify` returned an error |++## Known issues++- **Domain validation in local dev:** `/api/auth/siwe/verify` validates that the SIWE `domain` field matches `APP_ORIGIN`. Ensure `.env.local` includes `APP_ORIGIN=http://localhost:3000` (matching the Vite dev port) or the verify call will fail with `invalid_domain`.+- **CSP + CDN:** If the app sets a strict `script-src` CSP, add `https://esm.sh` to the allowlist, or self-host the WC provider package.+- **QR modal on iOS Safari:** The WC modal's clipboard copy requires a user gesture; Safari blocks it otherwise. The QR scan path still works.++## Smoke test++Open [`walletconnect-bridge.test.html`](./walletconnect-bridge.test.html) via the dev server:++```+npm run dev+# navigate to http://localhost:3000/src/auth/walletconnect-bridge.test.html+```diff --git a/publish/src/auth/walletconnect-bridge.js b/publish/src/auth/walletconnect-bridge.jsnew file mode 100644index 000000000..1bd29d9be--- /dev/null+++ b/publish/src/auth/walletconnect-bridge.js@@ -0,0 +1,174 @@+// WalletConnect v2 → SIWE bridge.+// Lazy-loads @walletconnect/ethereum-provider from CDN so it never ships in+// the main bundle unless the user explicitly triggers WC sign-in.++const WC_CDN = 'https://esm.sh/@walletconnect/[email protected]';++let _provider = null;++async function _loadEthereumProvider() {+ const { EthereumProvider } = await import(/* @vite-ignore */ WC_CDN);+ return EthereumProvider;+}++async function _resolveProjectId(override) {+ if (override) return override;++ // Vite injects VITE_* vars at build time.+ if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_WALLETCONNECT_PROJECT_ID) {+ return import.meta.env.VITE_WALLETCONNECT_PROJECT_ID;+ }++ // /api/config fallback for deployments that set walletConnectProjectId there.+ try {+ const res = await fetch('/api/config');+ if (res.ok) {+ const cfg = await res.json();+ if (cfg.walletConnectProjectId) return cfg.walletConnectProjectId;+ }+ } catch {+ /* network failure — fall through */+ }++ return null;+}++function _wcError(stage, message) {+ const err = new Error(message);+ err.code = `wc/${stage}`;+ return err;+}++/**+ * Full WalletConnect → SIWE sign-in.+ * @param {{ projectId?: string, chains?: number[] }} [opts]+ * @returns {Promise<{ user: object, address: string }>}+ */+export async function signInWithWalletConnect({ projectId, chains } = {}) {+ const pid = await _resolveProjectId(projectId);+ if (!pid) {+ throw _wcError(+ 'no_project_id',+ 'WalletConnect projectId is required. Set VITE_WALLETCONNECT_PROJECT_ID.',+ );+ }++ // 1. Load provider.+ let EthereumProvider;+ try {+ EthereumProvider = await _loadEthereumProvider();+ } catch (e) {+ throw _wcError('load_failed', `Failed to load WalletConnect provider: ${e.message}`);+ }++ // 2. Init + open modal.+ try {+ _provider = await EthereumProvider.init({+ projectId: pid,+ chains: chains || [1],+ showQrModal: true,+ methods: ['eth_requestAccounts', 'personal_sign'],+ events: ['chainChanged', 'accountsChanged'],+ });+ } catch (e) {+ throw _wcError('init_failed', `Provider init failed: ${e.message}`);+ }++ try {+ await _provider.enable();+ } catch (e) {+ throw _wcError('connect_rejected', `Connection rejected or failed: ${e.message}`);+ }++ const accounts = _provider.accounts;+ if (!accounts?.length) throw _wcError('no_accounts', 'No accounts returned after connect.');+ const address = accounts[0];++ // 3. Fetch nonce.+ let nonce;+ try {+ const nr = await fetch('/api/auth/siwe/nonce', { credentials: 'include' });+ if (!nr.ok) throw new Error(`HTTP ${nr.status}`);+ ({ nonce } = await nr.json());+ } catch (e) {+ throw _wcError('nonce_failed', `Nonce request failed: ${e.message}`);+ }++ // 4. Build EIP-4361 message matching the format expected by /api/auth/siwe/verify.+ const chainId = _provider.chainId || (chains?.[0] ?? 1);+ const domain = location.host;+ const uri = location.origin;+ const issuedAt = new Date().toISOString();++ const message = [+ `${domain} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to three.ws.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ ].join('\n');++ // 5. Sign.+ let signature;+ try {+ signature = await _provider.request({+ method: 'personal_sign',+ params: [message, address],+ });+ } catch (e) {+ throw _wcError('sign_rejected', `User rejected signing: ${e.message}`);+ }++ // 6. Verify on server — server sets session cookie on success.+ let result;+ try {+ const vr = await fetch('/api/auth/siwe/verify', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ message, signature }),+ });+ result = await vr.json();+ if (!vr.ok) throw new Error(result.error_description || `HTTP ${vr.status}`);+ } catch (e) {+ throw _wcError('verify_failed', `SIWE verify failed: ${e.message}`);+ }++ // 7. Refresh auth hint via getMe (writes localStorage hint internally).+ try {+ const { getMe } = await import('../account.js');+ await getMe();+ } catch {+ /* non-fatal: hint just won't be refreshed */+ }++ return {+ user: result.user,+ address: result.wallet?.address ?? address,+ };+}++/**+ * Returns the active EIP-1193 provider, or null if not connected.+ * @returns {object|null}+ */+export function getWalletConnectProvider() {+ return _provider;+}++/**+ * Disconnects the active WalletConnect session and clears the provider.+ */+export async function disconnectWalletConnect() {+ if (!_provider) return;+ try {+ await _provider.disconnect();+ } finally {+ _provider = null;+ }+}diff --git a/publish/src/auth/walletconnect-bridge.test.html b/publish/src/auth/walletconnect-bridge.test.htmlnew file mode 100644index 000000000..10b243d68--- /dev/null+++ b/publish/src/auth/walletconnect-bridge.test.html@@ -0,0 +1,101 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <title>WalletConnect Bridge — smoke test</title>+ <style>+ body {+ font-family: monospace;+ max-width: 640px;+ margin: 2rem auto;+ padding: 0 1rem;+ }+ button {+ margin: 0.25rem;+ padding: 0.5rem 1rem;+ cursor: pointer;+ }+ #log {+ margin-top: 1rem;+ white-space: pre-wrap;+ border: 1px solid #ccc;+ padding: 0.75rem;+ min-height: 6rem;+ }+ .ok {+ color: green;+ }+ .err {+ color: red;+ }+ </style>+ </head>+ <body>+ <h2>WalletConnect → SIWE smoke test</h2>+ <p>+ Requires <code>VITE_WALLETCONNECT_PROJECT_ID</code> to be set in+ <code>.env.local</code>.+ </p>++ <button id="btn-connect">Connect + Sign In</button>+ <button id="btn-me">GET /api/auth/me</button>+ <button id="btn-disconnect">Disconnect</button>++ <div id="log">Ready.</div>++ <script type="module">+ import {+ signInWithWalletConnect,+ getWalletConnectProvider,+ disconnectWalletConnect,+ } from './walletconnect-bridge.js';++ const log = document.getElementById('log');++ function write(msg, cls = '') {+ const ts = new Date().toISOString().slice(11, 23);+ log.innerHTML += `<span class="${cls}">[${ts}] ${escHtml(msg)}\n</span>`;+ log.scrollTop = log.scrollHeight;+ }++ function escHtml(s) {+ return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+ }++ document.getElementById('btn-connect').addEventListener('click', async () => {+ write('Starting WalletConnect sign-in…');+ try {+ const { user, address } = await signInWithWalletConnect();+ write(`Signed in — address: ${address}`, 'ok');+ write(`User: ${JSON.stringify(user, null, 2)}`, 'ok');+ } catch (err) {+ write(`Error [${err.code}]: ${err.message}`, 'err');+ }+ });++ document.getElementById('btn-me').addEventListener('click', async () => {+ write('GET /api/auth/me…');+ try {+ const res = await fetch('/api/auth/me', { credentials: 'include' });+ const body = await res.json();+ write(+ `${res.status} → ${JSON.stringify(body, null, 2)}`,+ res.ok ? 'ok' : 'err',+ );+ } catch (err) {+ write(`Fetch error: ${err.message}`, 'err');+ }+ });++ document.getElementById('btn-disconnect').addEventListener('click', async () => {+ write('Disconnecting…');+ try {+ await disconnectWalletConnect();+ write('Disconnected.', 'ok');+ } catch (err) {+ write(`Disconnect error: ${err.message}`, 'err');+ }+ });+ </script>+ </body>+</html>diff --git a/publish/src/avatar-creator.js b/publish/src/avatar-creator.jsnew file mode 100644index 000000000..86b279610--- /dev/null+++ b/publish/src/avatar-creator.js@@ -0,0 +1,214 @@+import { AvaturnSDK } from '@avaturn/sdk';++function getStudioUrl() {+ try {+ if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_CHARACTER_STUDIO_URL) {+ return String(import.meta.env.VITE_CHARACTER_STUDIO_URL)+ .trim()+ .replace(/\/$/, '');+ }+ } catch (_) {}+ return 'http://localhost:5173';+}++export class AvatarCreator {+ /**+ * @param {Element} containerEl - Parent element to mount the modal into+ * @param {function(Blob): void} onExport - Called with the exported GLB Blob+ * @param {object} [opts]+ * @param {string} [opts.studioUrl] - Override the CharacterStudio URL+ */+ constructor(containerEl, onExport, opts = {}) {+ this.container = containerEl;+ this.onExport = onExport;+ this.studioUrl = opts.studioUrl || getStudioUrl();++ this.modal = null;+ this.iframe = null;+ this.sdk = null;+ this._onMessage = null;+ this._onKeyDown = null;+ }++ /**+ * Opens the avatar creator modal.+ * @param {string} [sessionUrl] - When provided, opens Avaturn SDK in edit mode.+ * When omitted, opens CharacterStudio.+ */+ async open(sessionUrl) {+ if (this.modal) return;+ if (sessionUrl) {+ await this._openAvaturn(sessionUrl);+ } else {+ this._buildModal(true);+ this._onMessage = (e) => this._handleCharacterStudioMessage(e);+ window.addEventListener('message', this._onMessage);+ this.iframe.src = this.studioUrl;+ }+ }++ /**+ * Opens the Avaturn default hosted editor via the Avaturn SDK.+ * No URL passed → SDK uses its own default public editor (no developer ID needed).+ */+ async openDefaultEditor() {+ if (this.modal) return;+ await this._openAvaturn();+ }++ async _openAvaturn(url) {+ this._buildModal(false);+ try {+ this.sdk = new AvaturnSDK();+ await this.sdk.init(this.modal.querySelector('.avatar-creator-container'), {+ iframeClassName: 'avatar-creator-iframe',+ url,+ });++ const loading = this.modal?.querySelector('.avatar-creator-loading');+ if (loading) loading.style.display = 'none';++ this.sdk.on('export', async (data) => {+ const glbUrl = data?.url;+ if (!glbUrl) return;+ try {+ let blob;+ if (data.urlType === 'dataURL') {+ const res = await fetch(glbUrl);+ blob = await res.blob();+ } else {+ const res = await fetch(glbUrl);+ if (!res.ok) throw new Error(`GLB fetch failed: ${res.status}`);+ blob = await res.blob();+ }+ const glbBlob = blob.type+ ? blob+ : new Blob([await blob.arrayBuffer()], { type: 'model/gltf-binary' });+ this._fireExport(glbBlob);+ } catch (err) {+ console.error('[AvatarCreator] failed to fetch Avaturn GLB:', err);+ }+ });+ } catch (err) {+ console.error('[AvatarCreator] Failed to initialize Avaturn SDK:', err);+ this._showError('Failed to load avatar creator. Please try again.');+ }+ }++ _handleCharacterStudioMessage(event) {+ try {+ const csOrigin = new URL(this.studioUrl).origin;+ if (event.origin !== csOrigin) return;+ } catch (_) {+ return;+ }++ const msg = event.data;+ if (!msg || msg.source !== 'characterstudio' || msg.type !== 'export') return;+ if (!(msg.glb instanceof ArrayBuffer)) return;++ const blob = new Blob([msg.glb], { type: 'model/gltf-binary' });+ this._fireExport(blob);+ }++ _fireExport(blob) {+ if (this.onExport) {+ try {+ this.onExport(blob);+ } catch (err) {+ console.error('[AvatarCreator] onExport handler threw:', err);+ }+ }+ this.close();+ }++ _showError(message) {+ const loading = this.modal?.querySelector('.avatar-creator-loading');+ if (loading) {+ loading.innerHTML = `<span class="avatar-creator-error">${message}</span>`;+ }+ }++ /**+ * @param {boolean} withIframe - true for CharacterStudio (needs a pre-rendered iframe),+ * false for Avaturn SDK (SDK injects its own iframe).+ */+ _buildModal(withIframe) {+ const title = withIframe ? 'Create Your Avatar' : 'Edit Your Avatar';+ this.modal = document.createElement('div');+ this.modal.className = 'avatar-creator-overlay';++ this.modal.innerHTML = `+ <div class="avatar-creator-modal">+ <div class="avatar-creator-header">+ <span class="avatar-creator-title">${title}</span>+ <button class="avatar-creator-close" aria-label="Close">×</button>+ </div>+ <div class="avatar-creator-body">+ <div class="avatar-creator-container">${+ withIframe+ ? `<iframe+ class="avatar-creator-iframe"+ title="Avatar Creator"+ allow="camera *; microphone *; clipboard-write"+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups"+ ></iframe>`+ : ''+ }</div>+ <div class="avatar-creator-loading">+ <div class="spinner"></div>+ <span>Loading avatar creator...</span>+ </div>+ </div>+ </div>+ `;++ this.container.appendChild(this.modal);++ if (withIframe) {+ this.iframe = this.modal.querySelector('.avatar-creator-iframe');+ this.iframe.addEventListener('load', () => {+ const loading = this.modal?.querySelector('.avatar-creator-loading');+ if (loading) loading.style.display = 'none';+ });+ }++ this.modal+ .querySelector('.avatar-creator-close')+ .addEventListener('click', () => this.close());+ this.modal.addEventListener('click', (e) => {+ if (e.target === this.modal) this.close();+ });++ this._onKeyDown = (e) => {+ if (e.key === 'Escape') this.close();+ };+ document.addEventListener('keydown', this._onKeyDown);+ }++ close() {+ if (this.sdk) {+ try {+ this.sdk.destroy();+ } catch (_) {}+ this.sdk = null;+ }+ if (this._onMessage) {+ window.removeEventListener('message', this._onMessage);+ this._onMessage = null;+ }+ if (this._onKeyDown) {+ document.removeEventListener('keydown', this._onKeyDown);+ this._onKeyDown = null;+ }+ if (this.modal) {+ this.modal.remove();+ this.modal = null;+ this.iframe = null;+ }+ }++ dispose() {+ this.close();+ }+}diff --git a/publish/src/avaturn-client.js b/publish/src/avaturn-client.jsnew file mode 100644index 000000000..4142e1b82--- /dev/null+++ b/publish/src/avaturn-client.js@@ -0,0 +1,260 @@+/**+ * Avaturn client bridge — session creation + GLB retrieval via hidden iframe.+ *+ * Typical usage:+ *+ * import { createAvaturnSession, awaitAvatarGLB, blobToDataUrl } from './avaturn-client.js';+ *+ * const frontDataUrl = await blobToDataUrl(frontBlob);+ * const leftDataUrl = await blobToDataUrl(leftBlob);+ * const rightDataUrl = await blobToDataUrl(rightBlob);+ *+ * const { sessionUrl, expiresAt } = await createAvaturnSession({+ * front: frontDataUrl, left: leftDataUrl, right: rightDataUrl,+ * });+ *+ * const { glbBytes, thumbnailUrl, metadata } = await awaitAvatarGLB({+ * sessionUrl,+ * onProgress: ({ step, pct }) => console.log(step, pct),+ * signal: abortController.signal,+ * });+ */++const SESSION_ENDPOINT = '/api/onboarding/avaturn-session';+const OVERALL_TIMEOUT_MS = 120_000;+// Reject immediately if session expires within this many ms.+const EXPIRY_GRACE_MS = 10_000;++// ── Error ────────────────────────────────────────────────────────────────────++export class AvaturnError extends Error {+ /**+ * @param {string} message+ * @param {'quota'|'auth'|'session-expired'|'network'|'timeout'} code+ */+ constructor(message, code) {+ super(message);+ this.name = 'AvaturnError';+ this.code = code;+ }+}++// ── Helpers ──────────────────────────────────────────────────────────────────++/**+ * Convert a Blob to a base64 data URL.+ * @param {Blob} blob+ * @returns {Promise<string>}+ */+export function blobToDataUrl(blob) {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(/** @type {string} */ (reader.result));+ reader.onerror = () => reject(new AvaturnError('blobToDataUrl failed', 'network'));+ reader.readAsDataURL(blob);+ });+}++// ── Session creation ─────────────────────────────────────────────────────────++/**+ * Exchange three selfie data URLs for an Avaturn session URL.+ *+ * @param {{ front: string, left: string, right: string }} photos+ * Base64 JPEG data URLs (use blobToDataUrl to convert Blobs).+ * @returns {Promise<{ sessionUrl: string, expiresAt: string | null }>}+ */+export async function createAvaturnSession({ front, left, right }) {+ let res;+ try {+ res = await fetch(SESSION_ENDPOINT, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ // API schema field is 'frontal'; caller-facing param is 'front' for brevity.+ body: JSON.stringify({ photos: { frontal: front, left, right } }),+ });+ } catch (err) {+ throw new AvaturnError(`network error: ${err?.message}`, 'network');+ }++ if (!res.ok) {+ const payload = await res.json().catch(() => ({}));+ const code = payload?.error;+ if (res.status === 401 || res.status === 403)+ throw new AvaturnError(payload?.error_description || 'unauthorized', 'auth');+ if (res.status === 429)+ throw new AvaturnError(payload?.error_description || 'rate limited', 'quota');+ throw new AvaturnError(+ payload?.error_description || `http ${res.status}`,+ code === 'not_configured' ? 'auth' : 'network',+ );+ }++ const data = await res.json();+ if (!data?.session_url) throw new AvaturnError('server returned no session_url', 'network');++ return { sessionUrl: data.session_url, expiresAt: data.expires_at ?? null };+}++// ── GLB retrieval via hidden iframe ──────────────────────────────────────────++/**+ * Mount a hidden Avaturn iframe, wait for the avatar to be exported, fetch the GLB.+ *+ * @param {{+ * sessionUrl: string,+ * onProgress?: (evt: { step: 'iframe-load'|'avatar-gen'|'glb-fetch', pct: number }) => void,+ * signal?: AbortSignal,+ * }} opts+ * @returns {Promise<{ glbBytes: ArrayBuffer, thumbnailUrl?: string, metadata?: object }>}+ */+export async function awaitAvatarGLB({ sessionUrl, onProgress, signal }) {+ // Reject immediately if the session has effectively expired.+ const expiresAt = _expiresAtFromUrl(sessionUrl);+ if (expiresAt !== null && expiresAt - Date.now() < EXPIRY_GRACE_MS) {+ throw new AvaturnError('session has expired', 'session-expired');+ }++ const progress = onProgress ?? (() => {});+ let iframe = null;+ let timeoutId = null;+ let messageListener = null;++ const cleanup = () => {+ if (timeoutId !== null) clearTimeout(timeoutId);+ if (messageListener) window.removeEventListener('message', messageListener);+ if (iframe?.parentNode) iframe.parentNode.removeChild(iframe);+ iframe = null;+ };++ return new Promise((resolve, reject) => {+ // Abort support.+ if (signal?.aborted) {+ return reject(new DOMException('Aborted', 'AbortError'));+ }+ const onAbort = () => {+ cleanup();+ reject(new DOMException('Aborted', 'AbortError'));+ };+ signal?.addEventListener('abort', onAbort, { once: true });++ // Overall timeout.+ timeoutId = setTimeout(() => {+ cleanup();+ signal?.removeEventListener('abort', onAbort);+ reject(new AvaturnError('timed out waiting for avatar export', 'timeout'));+ }, OVERALL_TIMEOUT_MS);++ // Derive allowed origin from sessionUrl so we never hardcode it.+ let expectedOrigin;+ try {+ expectedOrigin = new URL(sessionUrl).origin;+ } catch {+ cleanup();+ signal?.removeEventListener('abort', onAbort);+ return reject(new AvaturnError('invalid sessionUrl', 'network'));+ }++ // Hidden iframe.+ // Avaturn's editor needs allow-popups-to-escape-sandbox in addition to the+ // base set because it may open OAuth flows in a new window.+ iframe = document.createElement('iframe');+ iframe.style.display = 'none';+ iframe.setAttribute(+ 'sandbox',+ 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox',+ );+ iframe.setAttribute('title', 'Avaturn avatar export');+ iframe.setAttribute('aria-hidden', 'true');++ // postMessage listener — scoped strictly to the iframe's origin.+ messageListener = async (event) => {+ if (event.origin !== expectedOrigin) return;++ const msg = event.data;+ if (!msg || typeof msg !== 'object') return;++ // Avaturn fires postMessage events with:+ // { source: 'avaturn', eventType: 'avatar.exported', data: { url, urlType, avatarId, thumbnailUrl, metadata } }+ // An earlier 'avatar.ready' event signals the editor is ready.+ // Ref: Avaturn iframe messaging protocol (see https://docs.avaturn.me — iframe events section).+ if (msg.source !== 'avaturn') return;++ const eventType = msg.eventType ?? msg.type;++ if (eventType === 'avatar.ready') {+ progress({ step: 'avatar-gen', pct: 10 });+ return;+ }++ if (eventType === 'avatar.exported' || eventType === 'export') {+ const glbUrl = msg.data?.url ?? msg.url;+ if (!glbUrl) return;++ progress({ step: 'glb-fetch', pct: 60 });++ try {+ let fetchRes;+ try {+ fetchRes = await fetch(glbUrl, { signal });+ } catch (err) {+ throw new AvaturnError(`GLB fetch failed: ${err?.message}`, 'network');+ }+ if (!fetchRes.ok)+ throw new AvaturnError(`GLB fetch ${fetchRes.status}`, 'network');++ const glbBytes = await fetchRes.arrayBuffer();+ progress({ step: 'glb-fetch', pct: 100 });++ cleanup();+ signal?.removeEventListener('abort', onAbort);+ resolve({+ glbBytes,+ thumbnailUrl: msg.data?.thumbnailUrl ?? undefined,+ metadata: msg.data?.metadata ?? undefined,+ });+ } catch (err) {+ cleanup();+ signal?.removeEventListener('abort', onAbort);+ reject(+ err instanceof AvaturnError+ ? err+ : new AvaturnError(err?.message ?? 'unknown', 'network'),+ );+ }+ }+ };++ window.addEventListener('message', messageListener);++ iframe.addEventListener(+ 'load',+ () => {+ progress({ step: 'iframe-load', pct: 5 });+ },+ { once: true },+ );++ document.body.appendChild(iframe);+ progress({ step: 'iframe-load', pct: 0 });+ iframe.src = sessionUrl;+ });+}++/**+ * Attempt to read an expiry timestamp encoded in the session URL's query string+ * (e.g. ?expires_at=...). Returns epoch ms or null if not present / unparseable.+ * @param {string} sessionUrl+ * @returns {number|null}+ */+function _expiresAtFromUrl(sessionUrl) {+ try {+ const param = new URL(sessionUrl).searchParams.get('expires_at');+ if (!param) return null;+ const ms = Date.parse(param);+ return isNaN(ms) ? null : ms;+ } catch {+ return null;+ }+}diff --git a/publish/src/claim-transfer.js b/publish/src/claim-transfer.jsnew file mode 100644index 000000000..4de1b88f3--- /dev/null+++ b/publish/src/claim-transfer.js@@ -0,0 +1,201 @@+/**+ * Claim / transfer flow for ERC-8004 agents.+ *+ * Uses standard ERC-721 safeTransferFrom — no custom claim entry point needed.+ * The IdentityRegistry inherits ERC-721 transfer mechanics verbatim.+ */++import { BrowserProvider, Contract, Interface } from 'ethers';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++// ---------------------------------------------------------------------------+// ClaimError+// ---------------------------------------------------------------------------++export class ClaimError extends Error {+ /**+ * @param {string} message+ * @param {'wrong-owner'|'already-claimed'|'user-rejected'|'network'|'unsupported-chain'} code+ */+ constructor(message, code) {+ super(message);+ this.name = 'ClaimError';+ this.code = code;+ }+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++/** @returns {{ identityRegistry: string }} */+function _deployment(chainId) {+ const dep = REGISTRY_DEPLOYMENTS[chainId];+ if (!dep || !dep.identityRegistry) {+ throw new ClaimError(+ `No IdentityRegistry deployment for chain ${chainId}`,+ 'unsupported-chain',+ );+ }+ return dep;+}++/**+ * Ask the wallet to switch to `chainId` (EIP-3326).+ * No-ops when the wallet is already on the right chain.+ */+async function _ensureChain(chainId) {+ if (!window.ethereum) return;+ const hexId = '0x' + chainId.toString(16);+ try {+ await window.ethereum.request({+ method: 'wallet_switchEthereumChain',+ params: [{ chainId: hexId }],+ });+ } catch (err) {+ // 4902 = chain not added to wallet — surface as network error+ throw new ClaimError(`Wallet chain switch failed (${err.message})`, 'network');+ }+}++/** Wrap ethers user-rejection errors into ClaimError. */+function _wrapTxError(err) {+ const msg = err?.message || String(err);+ if (+ err?.code === 'ACTION_REJECTED' ||+ msg.includes('user rejected') ||+ msg.includes('User denied')+ ) {+ return new ClaimError('User rejected the transaction', 'user-rejected');+ }+ return new ClaimError(msg, 'network');+}++// ---------------------------------------------------------------------------+// claimAgent+// ---------------------------------------------------------------------------++/**+ * Execute the on-chain ownership transfer for an ERC-8004 agent.+ *+ * `signer` must be either the current owner (fromAddress) or an address that+ * the owner has approved via `approve()` / `setApprovalForAll()`.+ *+ * Steps emitted via `onStep`:+ * permit — validating ownership + chain+ * sign — waiting for wallet signature+ * broadcast — tx submitted, waiting for inclusion+ * confirm — tx confirmed+ *+ * @param {object} opts+ * @param {number|string} opts.agentId+ * @param {string} opts.fromAddress Current owner (ops/mint wallet)+ * @param {string} opts.toAddress Claimer address+ * @param {import('ethers').Signer} opts.signer+ * @param {(step: {step: string, pct: number, txHash?: string}) => void} [opts.onStep]+ * @returns {Promise<{ok: true, txHash: string, blockNumber: number}>}+ */+export async function claimAgent({ agentId, fromAddress, toAddress, signer, onStep }) {+ const step = (s, pct, txHash) => onStep?.({ step: s, pct, ...(txHash ? { txHash } : {}) });++ step('permit', 0);++ // Resolve chain from the signer's provider+ const network = await signer.provider.getNetwork();+ const chainId = Number(network.chainId);++ _deployment(chainId); // throws 'unsupported-chain' if unknown++ await _ensureChain(chainId);++ const dep = _deployment(chainId);+ const registry = new Contract(dep.identityRegistry, IDENTITY_REGISTRY_ABI, signer);++ // Validate current ownership+ let currentOwner;+ try {+ currentOwner = await registry.ownerOf(agentId);+ } catch (err) {+ throw new ClaimError(+ `Could not fetch owner for agentId ${agentId}: ${err.message}`,+ 'network',+ );+ }++ const normalize = (a) => a.toLowerCase();++ if (normalize(currentOwner) !== normalize(fromAddress)) {+ throw new ClaimError(+ `Agent ${agentId} is owned by ${currentOwner}, not ${fromAddress}`,+ 'wrong-owner',+ );+ }++ if (normalize(currentOwner) === normalize(toAddress)) {+ throw new ClaimError(+ `Agent ${agentId} is already owned by ${toAddress}`,+ 'already-claimed',+ );+ }++ step('sign', 25);++ let tx;+ try {+ tx = await registry['safeTransferFrom(address,address,uint256)'](+ fromAddress,+ toAddress,+ agentId,+ );+ } catch (err) {+ throw _wrapTxError(err);+ }++ step('broadcast', 60, tx.hash);++ let receipt;+ try {+ receipt = await tx.wait();+ } catch (err) {+ throw _wrapTxError(err);+ }++ step('confirm', 100, tx.hash);++ return { ok: true, txHash: tx.hash, blockNumber: receipt.blockNumber };+}++// ---------------------------------------------------------------------------+// buildClaimPayload+// ---------------------------------------------------------------------------++/**+ * Build a raw `eth_sendTransaction` payload for a claim transfer.+ * Pure function — no wallet connection required.+ *+ * Useful when the signing step is split from the payload build (e.g. the+ * server builds the call data, the client signs and sends it).+ *+ * @param {object} opts+ * @param {number|string} opts.agentId+ * @param {string} opts.toAddress Recipient address+ * @param {number} opts.chainId+ * @param {string} opts.fromAddress Current owner (required for safeTransferFrom calldata)+ * @returns {{ to: string, data: string, value: string }}+ */+export function buildClaimPayload({ agentId, toAddress, chainId, fromAddress }) {+ const dep = _deployment(chainId); // throws 'unsupported-chain' if unknown++ const iface = new Interface(IDENTITY_REGISTRY_ABI);+ const data = iface.encodeFunctionData('safeTransferFrom(address,address,uint256)', [+ fromAddress,+ toAddress,+ agentId,+ ]);++ return {+ to: dep.identityRegistry,+ data,+ value: '0x0',+ };+}diff --git a/publish/src/cloud.js b/publish/src/cloud.jsnew file mode 100644index 000000000..36866bdcc--- /dev/null+++ b/publish/src/cloud.js@@ -0,0 +1,187 @@+import {+ Color,+ DynamicDrawUsage,+ InstancedBufferAttribute,+ InstancedMesh,+ Matrix4,+ MeshLambertMaterial,+ Object3D,+ PlaneGeometry,+ SRGBColorSpace,+ TextureLoader,+ Vector3,+} from 'three';++const CLOUD_TEXTURE =+ 'https://rawcdn.githack.com/pmndrs/drei-assets/9225a9f1fbd449d9411125c2f419b843d0308c9b/cloud.png';++// mulberry32 — fast, seeded, deterministic+function seededRand(seed) {+ let s = seed >>> 0;+ return () => {+ s = (s + 0x6d2b79f5) >>> 0;+ let t = Math.imul(s ^ (s >>> 15), 1 | s);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/**+ * Cloud — data container, child of Clouds.+ * @param {object} opts+ * @param {number} opts.seed seeded randomisation (default 0)+ * @param {number} opts.segments sprite count (default 20)+ * @param {number[]} opts.bounds [x,y,z] distribution box (default [5,1,1])+ * @param {number} opts.scale uniform scale multiplier (default 1)+ * @param {number} opts.volume sprite size factor (default 6)+ * @param {number} opts.speed rotation speed (default 0)+ * @param {number} opts.fade camera-distance fade radius (default 10)+ * @param {number} opts.opacity base opacity (default 1)+ * @param {string} opts.color tint color (default 'white')+ */+export class Cloud extends Object3D {+ constructor({+ seed = 0,+ segments = 20,+ bounds = [5, 1, 1],+ scale = 1,+ volume = 6,+ speed = 0,+ fade = 10,+ opacity = 1,+ color = 'white',+ } = {}) {+ super();+ this._cfg = {+ seed,+ segments,+ bounds,+ scale,+ volume,+ speed,+ fade,+ opacity,+ color: new Color(color),+ };+ this._segs = [];+ this._build();+ }++ _build() {+ const { seed, segments, bounds, scale, volume, speed } = this._cfg;+ const rand = seededRand(seed);+ const [bx, by, bz] = Array.isArray(bounds) ? bounds : [bounds.x, bounds.y, bounds.z];+ this._segs = Array.from({ length: segments }, () => ({+ pos: new Vector3((rand() - 0.5) * bx, (rand() - 0.5) * by, (rand() - 0.5) * bz),+ rot: rand() * Math.PI * 2,+ size: (0.4 + rand() * 0.6) * volume * scale,+ rotSpeed: (rand() - 0.5) * speed,+ }));+ }+}++/**+ * Clouds — container that renders all child Cloud instances in one draw call.+ *+ * Usage:+ * const clouds = new Clouds();+ * clouds.add(new Cloud({ segments: 40, bounds: [10,2,2], volume: 10, color: 'white' }));+ * scene.add(clouds);+ * // in animation loop:+ * clouds.update(camera, delta);+ *+ * @param {object} opts+ * @param {string} opts.texture custom texture URL (default: drei cloud asset)+ * @param {number} opts.limit max total segments across all clouds (default 200)+ * @param {object} opts.material custom THREE.Material override+ */+export class Clouds extends Object3D {+ constructor({ texture, limit = 200, material } = {}) {+ super();+ this._limit = limit;+ this._mat = material || null;+ this._url = texture || CLOUD_TEXTURE;+ this._mesh = null;+ this._elapsed = 0;+ // pre-allocated temps — no per-frame GC+ this._dummy = new Object3D();+ this._tmp = new Vector3();+ this._col = new Color();+ this._inv = new Matrix4();+ this._load();+ }++ _load() {+ new TextureLoader().load(this._url, (tex) => {+ tex.colorSpace = SRGBColorSpace;+ const mat =+ this._mat ||+ new MeshLambertMaterial({+ map: tex,+ transparent: true,+ depthWrite: false,+ side: 2, // DoubleSide+ });+ this._mesh = new InstancedMesh(new PlaneGeometry(1, 1), mat, this._limit);+ this._mesh.instanceMatrix.setUsage(DynamicDrawUsage);+ this._mesh.instanceColor = new InstancedBufferAttribute(+ new Float32Array(this._limit * 3),+ 3,+ );+ this._mesh.count = 0;+ this._mesh.frustumCulled = false;+ this.add(this._mesh);+ });+ }++ /**+ * Call once per frame inside your animation loop.+ * @param {THREE.Camera} camera+ * @param {number} delta seconds since last frame+ */+ update(camera, delta = 0.016) {+ if (!this._mesh) return;+ this._elapsed += delta;++ // World→Clouds-local matrix so instance matrices stay in parent space+ this.updateWorldMatrix(true, false);+ this._inv.copy(this.matrixWorld).invert();++ const camPos = camera.position;+ let idx = 0;++ for (const child of this.children) {+ if (!(child instanceof Cloud)) continue;+ child.updateWorldMatrix(true, false);+ const { fade, opacity, color } = child._cfg;++ for (const seg of child._segs) {+ // segment in world space+ this._tmp.copy(seg.pos).applyMatrix4(child.matrixWorld);++ // billboard: face camera+ this._dummy.position.copy(this._tmp);+ this._dummy.lookAt(camPos);+ this._dummy.rotation.z = seg.rot + this._elapsed * seg.rotSpeed;++ // distance fade — scale to 0 beyond fade radius+ const dist = this._tmp.distanceTo(camPos);+ const vis = fade > 0 ? Math.max(0, 1 - dist / fade) : 1;+ this._dummy.scale.setScalar(seg.size * vis);+ this._dummy.updateMatrix();++ // convert world-space matrix → Clouds-local for instance+ this._dummy.matrix.premultiply(this._inv);+ this._mesh.setMatrixAt(idx, this._dummy.matrix);++ this._col.copy(color).multiplyScalar(opacity);+ this._mesh.setColorAt(idx, this._col);+ idx++;+ }+ }++ this._mesh.count = Math.min(idx, this._limit);+ this._mesh.instanceMatrix.needsUpdate = true;+ if (this._mesh.instanceColor) this._mesh.instanceColor.needsUpdate = true;+ }+}diff --git a/publish/src/components/ModelViewerElement.js b/publish/src/components/ModelViewerElement.jsnew file mode 100644index 000000000..4a8e891b4--- /dev/null+++ b/publish/src/components/ModelViewerElement.js@@ -0,0 +1,253 @@+import { Viewer } from '../viewer.js';+import { LinearToneMapping, ACESFilmicToneMapping } from 'three';++const STYLE_ID = 'mv-viewer-style';+const DEFAULT_ENVIRONMENT = 'Neutral';++const TONE_MAPPING = {+ aces: ACESFilmicToneMapping,+ linear: LinearToneMapping,+};++function injectStylesOnce() {+ if (document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = `+ mv-viewer { display: block; position: relative; width: 100%; height: 480px; background: #191919; overflow: hidden; }+ mv-viewer .mv-viewer__stage { position: absolute; inset: 0; }+ mv-viewer .mv-viewer__poster { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; transition: opacity .3s ease; cursor: pointer; }+ mv-viewer .mv-viewer__poster[data-hidden] { opacity: 0; pointer-events: none; }+ `;+ document.head.appendChild(style);+}++export class ModelViewerElement extends HTMLElement {+ static get observedAttributes() {+ return [+ 'src',+ 'environment',+ 'exposure',+ 'tone-mapping',+ 'background-color',+ 'auto-rotate',+ 'camera-controls',+ 'reveal',+ 'poster',+ 'disable-zoom',+ 'disable-pan',+ ];+ }++ constructor() {+ super();+ this._viewer = null;+ this._stageEl = null;+ this._posterEl = null;+ this._pendingSrc = null;+ this._loadedSrc = null;+ this._revealed = false;+ this._onControlsChange = null;+ }++ connectedCallback() {+ if (this._viewer) return;+ injectStylesOnce();++ this._stageEl = document.createElement('div');+ this._stageEl.className = 'mv-viewer__stage';+ this.appendChild(this._stageEl);++ const reveal = this.getAttribute('reveal') || 'auto';+ const posterSrc = this.getAttribute('poster');+ if (posterSrc) {+ this._posterEl = document.createElement('img');+ this._posterEl.className = 'mv-viewer__poster';+ this._posterEl.src = posterSrc;+ this._posterEl.alt = this.getAttribute('alt') || '';+ this.appendChild(this._posterEl);+ }++ const envName = this.getAttribute('environment') || DEFAULT_ENVIRONMENT;+ const options = {+ kiosk: false,+ preset: '',+ cameraPosition: null,+ // The Viewer reads options.preset/cameraPosition/kiosk in the constructor;+ // everything else flows through state and methods after construction.+ };++ this._viewer = new Viewer(this._stageEl, options);+ this._viewer.state.environment = envName;++ // Initial attribute sync (before first load, invalidate for the env + lighting updates).+ this._applyAttribute('exposure');+ this._applyAttribute('tone-mapping');+ this._applyAttribute('background-color');+ this._applyAttribute('auto-rotate');+ this._applyAttribute('camera-controls');+ this._applyAttribute('disable-zoom');+ this._applyAttribute('disable-pan');+ this._viewer.updateEnvironment();+ this._viewer.updateLights();+ this._viewer.updateBackground();++ this._onControlsChange = () => {+ this.dispatchEvent(new CustomEvent('camera-change', { bubbles: true, composed: true }));+ };+ this._viewer.controls.addEventListener('change', this._onControlsChange);++ const src = this.getAttribute('src');+ if (src) {+ if (reveal === 'interaction') {+ this._pendingSrc = src;+ const trigger = () => {+ this.removeEventListener('click', trigger);+ this.removeEventListener('pointerenter', trigger);+ this._loadSrc(this._pendingSrc);+ };+ this.addEventListener('click', trigger, { once: true });+ this.addEventListener('pointerenter', trigger, { once: true });+ } else {+ this._loadSrc(src);+ }+ }+ }++ disconnectedCallback() {+ if (!this._viewer) return;+ if (this._onControlsChange && this._viewer.controls) {+ this._viewer.controls.removeEventListener('change', this._onControlsChange);+ }+ if (typeof this._viewer.dispose === 'function') {+ this._viewer.dispose();+ } else {+ console.warn(+ '[mv-viewer] Viewer.dispose() not available — disconnect will leak resources.',+ );+ }+ this._viewer = null;+ this._stageEl = null;+ this._posterEl = null;+ this._onControlsChange = null;+ this.replaceChildren();+ }++ attributeChangedCallback(name, oldVal, newVal) {+ if (!this._viewer) return; // Applied at connectedCallback.+ if (oldVal === newVal) return;+ this._applyAttribute(name, newVal);+ }++ _applyAttribute(name, newVal) {+ const viewer = this._viewer;+ if (!viewer) return;+ if (newVal === undefined) newVal = this.getAttribute(name);++ switch (name) {+ case 'src': {+ if (this._pendingSrc !== null) {+ this._pendingSrc = newVal;+ return;+ }+ if (newVal) this._loadSrc(newVal);+ return;+ }+ case 'environment': {+ viewer.state.environment = newVal || DEFAULT_ENVIRONMENT;+ viewer.updateEnvironment();+ return;+ }+ case 'exposure': {+ const v = Number(newVal);+ if (!Number.isFinite(v)) return;+ // viewer.state.exposure is an EV offset (see updateLights); accept either a multiplier or an EV value.+ // For attribute sugar, treat as a linear multiplier and convert to log2 EV.+ viewer.state.exposure = v > 0 ? Math.log2(v) : 0;+ viewer.updateLights();+ return;+ }+ case 'tone-mapping': {+ const mapped = TONE_MAPPING[(newVal || 'aces').toLowerCase()];+ if (mapped === undefined) return;+ viewer.state.toneMapping = mapped;+ viewer.updateLights();+ return;+ }+ case 'background-color': {+ if (!newVal) return;+ viewer.state.bgColor = newVal;+ viewer.updateBackground();+ return;+ }+ case 'auto-rotate': {+ viewer.state.autoRotate = this.hasAttribute('auto-rotate');+ viewer.updateDisplay();+ return;+ }+ case 'camera-controls': {+ // Default on; only off when explicitly set to "false".+ const enabled = newVal === null || newVal === '' || newVal === 'true';+ viewer.controls.enabled = enabled;+ viewer.invalidate();+ return;+ }+ case 'disable-zoom': {+ viewer.controls.enableZoom = !this.hasAttribute('disable-zoom');+ viewer.invalidate();+ return;+ }+ case 'disable-pan': {+ viewer.controls.enablePan = !this.hasAttribute('disable-pan');+ viewer.invalidate();+ return;+ }+ case 'reveal':+ case 'poster':+ // Only applied at connect time.+ return;+ }+ }++ _loadSrc(src) {+ const viewer = this._viewer;+ if (!viewer) return;+ this._pendingSrc = null;++ if (this._loadedSrc) viewer.clear();+ this._loadedSrc = src;++ viewer+ .load(src, '', new Map())+ .then(() => {+ this._hidePoster();+ this.dispatchEvent(+ new CustomEvent('load', { bubbles: true, composed: true, detail: { src } }),+ );+ })+ .catch((error) => {+ this.dispatchEvent(+ new CustomEvent('error', {+ bubbles: true,+ composed: true,+ detail: { error, src },+ }),+ );+ });+ }++ _hidePoster() {+ if (!this._posterEl) return;+ this._posterEl.setAttribute('data-hidden', '');+ // Remove from DOM after fade so it stops capturing pointer events.+ setTimeout(() => this._posterEl?.remove(), 400);+ }++ get viewer() {+ return this._viewer;+ }+}++if (typeof customElements !== 'undefined' && !customElements.get('mv-viewer')) {+ customElements.define('mv-viewer', ModelViewerElement);+}diff --git a/publish/src/components/animation-panel.jsx b/publish/src/components/animation-panel.jsxnew file mode 100644index 000000000..59605466c--- /dev/null+++ b/publish/src/components/animation-panel.jsx@@ -0,0 +1,68 @@+/**+ * Animation selector panel component.+ * Renders a grid of animation buttons with active state highlighting.+ * @param {object} props+ * @param {Array<{name: string, label?: string, icon?: string, loaded: boolean}>} props.animations+ * @param {string|null} props.active - Currently playing animation name+ * @returns {string} HTML string+ */+export function AnimationPanel({ animations, active }) {+ if (!animations || animations.length === 0) {+ return '<div class="anim-panel anim-panel--empty"></div>';+ }++ const ICONS = {+ idle: '🧍',+ breathing: '🧍',+ standing: '🧍',+ walking: '🚶',+ walk: '🚶',+ running: '🏃',+ run: '🏃',+ waving: '👋',+ wave: '👋',+ dancing: '💃',+ dance: '💃',+ sitting: '🪑',+ sit: '🪑',+ jumping: '🦘',+ jump: '🦘',+ talking: '🗣️',+ talk: '🗣️',+ clapping: '👏',+ clap: '👏',+ punching: '👊',+ punch: '👊',+ kicking: '🦵',+ kick: '🦵',+ };++ const buttons = animations+ .map(({ name, label, icon, loaded }) => {+ const isActive = active === name;+ const displayIcon = icon || ICONS[name.toLowerCase()] || '▶';+ const displayLabel = label || name.charAt(0).toUpperCase() + name.slice(1);+ const activeClass = isActive ? ' anim-btn--active' : '';+ const loadingClass = !loaded ? ' anim-btn--loading' : '';+ return (+ `<button class="anim-btn${activeClass}${loadingClass}" ` ++ `data-anim="${name}" ` ++ `title="${displayLabel}"` ++ `${!loaded ? ' disabled' : ''}>` ++ `<span class="anim-btn__icon">${displayIcon}</span>` ++ `<span class="anim-btn__label">${displayLabel}</span>` ++ `</button>`+ );+ })+ .join('');++ return (+ `<div class="anim-panel">` ++ `<div class="anim-panel__header">` ++ `<span class="anim-panel__title">Animations</span>` ++ `<button class="anim-panel__stop" title="Stop all">⏹</button>` ++ `</div>` ++ `<div class="anim-panel__grid">${buttons}</div>` ++ `</div>`+ );+}diff --git a/publish/src/components/footer.jsx b/publish/src/components/footer.jsxnew file mode 100644index 000000000..464294c0b--- /dev/null+++ b/publish/src/components/footer.jsx@@ -0,0 +1,74 @@+import vhtml from 'vhtml';++/** @jsx vhtml */++export function Footer() {+ return (+ <footer>+ <a class="item" target="_blank" href="https://x.com/nichxbt" aria-label="Follow on X">+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="currentColor"+ >+ <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />+ </svg>+ </a>++ <span class="separator" aria-hidden="true">+ |+ </span>++ <a class="item" href="/showcase">+ showcase+ </a>++ <span class="separator" aria-hidden="true">+ |+ </span>++ <a class="item" href="/validation/">+ validation+ </a>++ <span class="separator" aria-hidden="true">+ |+ </span>++ <a class="item" href="/reputation/">+ reputation+ </a>++ <span class="separator" aria-hidden="true">+ |+ </span>++ <a class="item" target="_blank" href="https://github.com/nirholas/3d-agent/issues/new">+ help & feedback+ </a>++ <span class="separator" aria-hidden="true">+ |+ </span>++ <a+ class="item"+ target="_blank"+ href="https://github.com/nirholas/3d-agent"+ aria-label="GitHub"+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="currentColor"+ >+ <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />+ </svg>+ </a>+ </footer>+ );+}diff --git a/publish/src/components/validator-report.jsx b/publish/src/components/validator-report.jsxnew file mode 100644index 000000000..625e041e5--- /dev/null+++ b/publish/src/components/validator-report.jsx@@ -0,0 +1,163 @@+import vhtml from 'vhtml';+import { ValidatorTable } from './validator-table';++/** @jsx vhtml */++export function ValidatorReport({+ info,+ validatorVersion,+ issues,+ errors,+ warnings,+ hints,+ infos,+ reportJSON,+}) {+ const totalIssues = issues.numErrors + issues.numWarnings + issues.numInfos + issues.numHints;+ const isClean = totalIssues === 0;+ return (+ <div class="report">+ <div class="report-head">+ <h1>Validation report</h1>+ {reportJSON && (+ <a+ class="report-download"+ href={reportJSON}+ download="gltf-validation-report.json"+ >+ Download JSON+ </a>+ )}+ </div>+ {isClean ? (+ <div class="report-banner report-banner-clean" role="status">+ <span class="report-banner-icon" aria-hidden="true">+ ✓+ </span>+ <span>All clear — no validation issues found.</span>+ </div>+ ) : (+ <div class="report-banner report-banner-issues" role="status">+ <span>+ Found <b>{totalIssues}</b> issue{totalIssues === 1 ? '' : 's'}:{' '}+ {issues.numErrors > 0 && (+ <span>+ <b>{issues.numErrors}</b> error{issues.numErrors === 1 ? '' : 's'}+ </span>+ )}+ {issues.numErrors > 0 && issues.numWarnings > 0 && ', '}+ {issues.numWarnings > 0 && (+ <span>+ <b>{issues.numWarnings}</b> warning+ {issues.numWarnings === 1 ? '' : 's'}+ </span>+ )}+ {(issues.numErrors > 0 || issues.numWarnings > 0) &&+ (issues.numInfos > 0 || issues.numHints > 0) &&+ ', '}+ {issues.numInfos > 0 && (+ <span>+ <b>{issues.numInfos}</b> info+ </span>+ )}+ {issues.numInfos > 0 && issues.numHints > 0 && ', '}+ {issues.numHints > 0 && (+ <span>+ <b>{issues.numHints}</b> hint{issues.numHints === 1 ? '' : 's'}+ </span>+ )}+ .+ </span>+ </div>+ )}+ <ul>+ <li>+ <b>Format:</b> glTF {info.version}+ </li>+ <li>+ <b>Generator:</b> {info.generator}+ </li>+ {info?.extras?.title && (+ <li>+ <b>Title:</b> <span>{info.extras.title}</span>+ </li>+ )}+ {info?.extras?.author && (+ <li>+ <b>Author:</b>{' '}+ <span dangerouslySetInnerHTML={{ __html: info.extras.author }} />+ </li>+ )}+ {info?.extras?.license && (+ <li>+ <b>License:</b>{' '}+ <span dangerouslySetInnerHTML={{ __html: info.extras.license }} />+ </li>+ )}+ {info?.extras?.source && (+ <li>+ <b>Source:</b>{' '}+ <span dangerouslySetInnerHTML={{ __html: info.extras.source }} />+ </li>+ )}+ <li>+ <b>Stats:</b>+ <ul>+ <li>{info.drawCallCount || '0'} draw calls</li>+ <li>{info.animationCount || '0'} animations</li>+ <li>{info.materialCount || '0'} materials</li>+ <li>{info.totalVertexCount || '0'} vertices</li>+ <li>{info.totalTriangleCount || '0'} triangles</li>+ </ul>+ </li>+ <li>+ <b>Extensions:</b>+ <ul>+ {info.extensionsUsed?.length ? (+ info.extensionsUsed.map((extension) => <li>{extension}</li>)+ ) : (+ <li>None</li>+ )}+ </ul>+ {info.extensionsUsed?.length > 0 && (+ <p>+ <i>+ NOTE: Extensions above are present in the model, but may or may not+ be recognized by this viewer. Any "UNSUPPORTED_EXTENSION" warnings+ below refer only to extensions that could not be scanned by the+ validation suite, and may still have rendered correctly. See:{' '}+ <a+ href="https://github.com/nirholas/3d-agent/issues/122"+ target="_blank"+ >+ 3D-Agent#122+ </a>+ .+ </i>+ </p>+ )}+ </li>+ </ul>+ <hr />+ <p>+ Report generated by+ <a href="https://github.com/KhronosGroup/glTF-Validator/">+ KhronosGroup/glTF-Validator+ </a>{' '}+ {validatorVersion}.+ </p>+ {issues.numErrors > 0 && (+ <ValidatorTable messages={errors} color="#f44336" title="Error" />+ )}+ {issues.numWarnings > 0 && (+ <ValidatorTable messages={warnings} color="#f9a825" title="Warning" />+ )}+ {issues.numHints > 0 && (+ <ValidatorTable messages={hints} color="#8bc34a" title="Hint" />+ )}+ {issues.numInfos > 0 && (+ <ValidatorTable messages={infos} color="#2196f3" title="Info" />+ )}+ </div>+ );+}diff --git a/publish/src/components/validator-table.jsx b/publish/src/components/validator-table.jsxnew file mode 100644index 000000000..a8e8f22f3--- /dev/null+++ b/publish/src/components/validator-table.jsx@@ -0,0 +1,47 @@+import vhtml from 'vhtml';++/** @jsx vhtml */++export function ValidatorTable({ title, color, messages }) {+ const count = messages.length;+ const headingId = `report-section-${title.toLowerCase()}`;+ return (+ <section class="report-section" aria-labelledby={headingId}>+ <h2 id={headingId} class="report-section-heading" style={`border-left-color: ${color}`}>+ {title}+ {count > 1 ? 's' : ''} <span class="report-count">({count})</span>+ </h2>+ <div class="report-table-wrap">+ <table class="report-table" aria-label={`${title} issues`}>+ <thead>+ <tr style={`background: ${color}`}>+ <th scope="col">Code</th>+ <th scope="col">Message</th>+ <th scope="col">Pointer</th>+ </tr>+ </thead>+ <tbody>+ {messages.map(({ code, message, pointer }) => {+ return (+ <tr>+ <td>+ <code>{code}</code>+ </td>+ <td>{message}</td>+ <td>+ <code>{pointer || '\u2014'}</code>+ </td>+ </tr>+ );+ })}+ {messages.length === 0 && (+ <tr>+ <td colspan="3">No issues found.</td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </section>+ );+}diff --git a/publish/src/components/validator-toggle.jsx b/publish/src/components/validator-toggle.jsxnew file mode 100644index 000000000..cbe4a16ff--- /dev/null+++ b/publish/src/components/validator-toggle.jsx@@ -0,0 +1,36 @@+import vhtml from 'vhtml';++/** @jsx vhtml */++export function ValidatorToggle({ issues, reportError }) {+ let levelClassName = '';+ let message = '';++ if (issues) {+ if (issues.numErrors) {+ message = `${issues.numErrors} errors.`;+ } else if (issues.numWarnings) {+ message = `${issues.numWarnings} warnings.`;+ } else if (issues.numHints) {+ message = `${issues.numHints} hints.`;+ } else if (issues.numInfos) {+ message = `${issues.numInfos} notes.`;+ } else {+ message = 'Model details';+ }+ levelClassName = `level-${issues.maxSeverity}`;+ } else if (reportError) {+ message = `Validation could not run: ${reportError}.`;+ } else {+ message = 'Validation could not run.';+ }++ return (+ <div className={`report-toggle ${levelClassName}`}>+ <div class="report-toggle-text">{message}</div>+ <div class="report-toggle-close" aria-label="Hide">+ ×+ </div>+ </div>+ );+}diff --git a/publish/src/create.js b/publish/src/create.jsnew file mode 100644index 000000000..7f724add8--- /dev/null+++ b/publish/src/create.js@@ -0,0 +1,149 @@+import { apiFetch, saveRemoteGlbToAccount } from './account.js';+import { AvatarCreator } from './avatar-creator.js';++// GLB magic bytes: ASCII "glTF"+const GLB_MAGIC = [0x67, 0x6c, 0x54, 0x46];++async function boot() {+ const creator = new AvatarCreator(document.body, (blob) =>+ saveAndRedirect(blob, { source: 'avaturn' }),+ );++ document.getElementById('back-btn')?.addEventListener('click', () => {+ if (history.length > 1) history.back();+ else window.location.href = '/';+ });++ wireCard('card-default-editor', async () => {+ if (await isAtAvatarLimit()) return;+ creator.openDefaultEditor();+ });+ wireCard('card-upload-glb', (e) => {+ // Tooltip anchors live inside the card; let them navigate normally.+ if (e && e.target && e.target.closest('a')) return;+ document.getElementById('glb-input').click();+ });++ document.getElementById('glb-input').addEventListener('change', async (e) => {+ const file = e.target.files?.[0];+ if (!file) return;+ e.target.value = '';+ await handleGlbFile(file);+ });+}++// Cards are divs with role="button", so we need to wire both click and+// keyboard activation (Enter / Space) ourselves — native <button> semantics.+function wireCard(id, handler) {+ const el = document.getElementById(id);+ if (!el) return;+ el.addEventListener('click', handler);+ el.addEventListener('keydown', (e) => {+ if (el.getAttribute('aria-disabled') === 'true') return;+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ handler(e);+ }+ });+}++async function handleGlbFile(file) {+ if (!file.name.toLowerCase().endsWith('.glb')) {+ showStatus('Please select a .glb file.', 'error');+ return;+ }++ const header = new Uint8Array(await file.slice(0, 4).arrayBuffer());+ if (!GLB_MAGIC.every((b, i) => header[i] === b)) {+ showStatus("File doesn't appear to be a valid GLB.", 'error');+ return;+ }++ const name = file.name.replace(/\.glb$/i, '').trim() || 'My Avatar';+ await saveAndRedirect(file, { source: 'upload', name });+}++async function isAtAvatarLimit() {+ try {+ const res = await apiFetch('/api/usage/summary');+ if (!res.ok) return false;+ const { counts, plan } = await res.json();+ if (counts.avatars >= plan.max_avatars) {+ showStatus(+ `You've reached the ${plan.max_avatars}-avatar limit on the free plan. Delete an avatar to create a new one.`,+ 'error',+ );+ return true;+ }+ } catch {+ // network error — let the upload attempt proceed and fail naturally+ }+ return false;+}++async function saveAndRedirect(blob, meta = {}) {+ showStatus('Uploading avatar…', 'loading');+ try {+ const avatar = await saveRemoteGlbToAccount(blob, meta);+ const agent = await attachAvatarToAgent(avatar.id, meta.name);+ window.location.href = '/app?agent=' + agent.id;+ } catch (err) {+ if (err.code === 'not_signed_in') {+ sessionStorage.setItem('login_redirect', '/create');+ window.location.replace('/login');+ return;+ }+ if (err.data?.error === 'plan_limit_count') {+ showStatus(+ "You've reached your avatar limit. Delete an avatar to create a new one.",+ 'error',+ );+ return;+ }+ if (!err.redirected) showStatus(err.message || 'Upload failed.', 'error');+ }+}++// Associates the uploaded avatar with the caller's default agent. POST /api/agents+// doesn't accept avatar_id, so we get-or-create via /me and then PUT to attach.+async function attachAvatarToAgent(avatarId, name) {+ const meRes = await apiFetch('/api/agents/me');+ const meData = await meRes.json();+ if (!meRes.ok) throw new Error(meData.error_description || 'Failed to load agent.');++ let agent = meData.agent;+ if (!agent) {+ const createRes = await apiFetch('/api/agents', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ name: name || 'My Agent' }),+ });+ const createData = await createRes.json();+ if (!createRes.ok)+ throw new Error(createData.error_description || 'Failed to create agent.');+ agent = createData.agent;+ }++ const putRes = await apiFetch('/api/agents/' + agent.id, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ avatar_id: avatarId }),+ });+ const putData = await putRes.json();+ if (!putRes.ok) throw new Error(putData.error_description || 'Failed to attach avatar.');+ return putData.agent;+}++function showStatus(msg, type = 'info') {+ const el = document.getElementById('status-toast');+ el.textContent = msg;+ el.className = 'status-toast ' + type;+ el.hidden = false;+ if (type !== 'loading') {+ setTimeout(() => {+ el.hidden = true;+ }, 4500);+ }+}++boot();diff --git a/publish/src/cz-flow.js b/publish/src/cz-flow.jsnew file mode 100644index 000000000..50b176aba--- /dev/null+++ b/publish/src/cz-flow.js@@ -0,0 +1,143 @@+/**+ * CZ demo claim flow — manages wallet connection, claiming, and transfer flows.+ */++import { ensureWallet, getIdentityRegistry } from './erc8004/agent-registry.js';+import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++/**+ * Start the claim flow based on the current state.+ *+ * @param {object} opts+ * @param {object} opts.state Current state (status, chainId, agentId, ownerAddress, etc.)+ * @param {(progress) => void} opts.onProgress Callback with { step, status, txHash?, error? }+ * @returns {Promise<{ ok: true, txHash? } | { ok: false, error }>}+ */+export async function startClaim({ state, onProgress }) {+ const log = (step, status, extra = {}) => {+ onProgress?.({ step, status, ...extra });+ };++ try {+ // Step 1: Connect wallet+ log('connect_wallet', 'connecting');+ const { address, chainId, signer } = await ensureWallet();+ log('connect_wallet', 'connected', { address, chainId });++ // Step 2: Check state+ if (state.status === 'pre-onchain') {+ log('check_state', 'pre_onchain', {+ message:+ 'CZ is not yet registered on-chain. Claiming opens once registration is complete.',+ });+ return { ok: true, message: 'pre_onchain' };+ }++ // Step 3: If ownerAddress is 0x0 (unclaimed), call claim()+ if (state.ownerAddress === '0x0000000000000000000000000000000000000000') {+ log('claim', 'submitting');+ const registry = getIdentityRegistry(chainId, signer);+ const tx = await registry.claim(state.agentId);+ log('claim', 'pending', { txHash: tx.hash });++ const receipt = await tx.wait();+ log('claim', 'confirmed', { txHash: tx.hash });++ fireAnalytics('claim_tx_sent', { txHash: tx.hash, agentId: state.agentId });+ fireAnalytics('claim_complete', { agentId: state.agentId });+ return { ok: true, txHash: tx.hash };+ }++ // Step 4: If state.ownerAddress is known demo EOA, guide transfer+ const DEMO_EOAS = [+ '0x1234567890123456789012345678901234567890', // placeholder+ ];+ if (DEMO_EOAS.includes(state.ownerAddress?.toLowerCase())) {+ log('transfer', 'guide', {+ from: state.ownerAddress,+ to: address,+ message: 'This agent is owned by the demo account. Transfer to your wallet?',+ });++ // Real implementation would show a modal and call transferOwner() if approved+ // For now, return guidance+ return { ok: true, message: 'transfer_available' };+ }++ log('claim', 'already_owned', { owner: state.ownerAddress });+ return { ok: true, message: 'already_owned' };+ } catch (err) {+ log('claim', 'error', { error: err.message });+ fireAnalytics('claim_error', { error: err.message });+ return { ok: false, error: err.message };+ }+}++/**+ * Mount the embed copy CTA to a container.+ * Copies an <agent-3d> snippet to clipboard with chain/agentId interpolated.+ *+ * @param {HTMLElement} container+ * @param {object} opts+ * @param {object} opts.state Current state+ */+export function mountEmbedCopy(container, { state }) {+ const button = document.createElement('button');+ button.id = 'cz-embed-copy';+ button.textContent = 'Copy embed';+ button.setAttribute('aria-label', 'Copy embed code to clipboard');++ button.addEventListener('click', async () => {+ const snippet = buildEmbedSnippet(state);+ try {+ await navigator.clipboard.writeText(snippet);+ const orig = button.textContent;+ button.textContent = 'Copied!';+ fireAnalytics('embed_copied', {+ hasChainId: !!state.chainId,+ hasAgentId: !!state.agentId,+ });+ setTimeout(() => {+ button.textContent = orig;+ }, 2000);+ } catch (err) {+ console.error('Copy failed:', err);+ button.textContent = 'Copy failed';+ setTimeout(() => {+ button.textContent = 'Copy embed';+ }, 2000);+ }+ });++ container.appendChild(button);+ return button;+}++/**+ * Build the embed snippet HTML based on state.+ */+function buildEmbedSnippet(state) {+ let agentAttr = '';+ if (state.chainId && state.agentId) {+ agentAttr = ` agent-id="onchain:${state.chainId}:${state.agentId}"`;+ } else {+ // Fallback: just use the GLB directly+ agentAttr = ` body="${state.avatarUrl}"`;+ }++ return `<agent-3d${agentAttr} src="${state.avatarUrl}" eager></agent-3d>+<script src="https://three.ws/dist-lib/agent-3d.umd.cjs"><\/script>`;+}++/**+ * Fire a custom event for analytics.+ */+function fireAnalytics(event, props = {}) {+ window.dispatchEvent(+ new CustomEvent('cz-demo-event', {+ detail: { event, props, timestamp: Date.now() },+ }),+ );+}++export { fireAnalytics };diff --git a/publish/src/editor/apply-overrides.js b/publish/src/editor/apply-overrides.jsnew file mode 100644index 000000000..2a3d5a3c4--- /dev/null+++ b/publish/src/editor/apply-overrides.js@@ -0,0 +1,35 @@+// Apply server-persisted material overrides to a loaded Three.js model.+// Patch shape: { [materialName]: { color, metalness, roughness, emissive } }+// Only fields present in the patch override; everything else stays from the GLB.++import { traverseMaterials } from '../viewer/internal.js';++export function applyMaterialOverrides(model, overrides) {+ if (!model || !overrides || typeof overrides !== 'object') return;+ traverseMaterials(model, (mat) => {+ const p = overrides[mat.name];+ if (!p) return;+ if (p.color !== undefined) mat.color.set(p.color);+ if (p.metalness !== undefined) mat.metalness = Number(p.metalness);+ if (p.roughness !== undefined) mat.roughness = Number(p.roughness);+ if (p.emissive !== undefined) mat.emissive.set(p.emissive);+ mat.needsUpdate = true;+ });+}++export function listMaterials(model) {+ const result = [];+ if (!model) return result;+ traverseMaterials(model, (mat) => {+ if (mat.isMeshStandardMaterial || mat.isMeshPhysicalMaterial) {+ result.push({+ name: mat.name,+ color: '#' + mat.color.getHexString(),+ metalness: mat.metalness,+ roughness: mat.roughness,+ emissive: '#' + mat.emissive.getHexString(),+ });+ }+ });+ return result;+}diff --git a/publish/src/editor/edit-persistence.js b/publish/src/editor/edit-persistence.jsnew file mode 100644index 000000000..293b0d172--- /dev/null+++ b/publish/src/editor/edit-persistence.js@@ -0,0 +1,207 @@+/**+ * edit-persistence — round-trip the editor's in-progress state across a+ * navigation (the "sign in to publish" redirect being the driving case).+ *+ * Edits are small JSON → `sessionStorage` under `edt:<id>`.+ * Source bytes (for dropped files) go to IndexedDB under `3dagent/edt-bytes`,+ * keyed by the same id. URL-loaded models store only the url and re-fetch.+ */++const DB_NAME = '3dagent';+const STORE_NAME = 'edt-bytes';+const SS_PREFIX = 'edt:';+const BLOB_VERSION = 1;++function base64url(bytes) {+ let s = '';+ for (const b of bytes) s += String.fromCharCode(b);+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+}++function newToken() {+ const rand = crypto.getRandomValues(new Uint8Array(6));+ return 'edt_' + base64url(rand);+}++function openDB() {+ return new Promise((resolve, reject) => {+ let req;+ try {+ req = indexedDB.open(DB_NAME, 1);+ } catch (err) {+ reject(err);+ return;+ }+ req.onupgradeneeded = () => {+ const db = req.result;+ if (!db.objectStoreNames.contains(STORE_NAME)) {+ db.createObjectStore(STORE_NAME);+ }+ };+ req.onsuccess = () => resolve(req.result);+ req.onerror = () => reject(req.error);+ req.onblocked = () => reject(new Error('indexedDB blocked'));+ });+}++async function idbPut(key, value) {+ const db = await openDB();+ try {+ await new Promise((resolve, reject) => {+ const tx = db.transaction(STORE_NAME, 'readwrite');+ tx.objectStore(STORE_NAME).put(value, key);+ tx.oncomplete = () => resolve();+ tx.onerror = () => reject(tx.error);+ tx.onabort = () => reject(tx.error);+ });+ } finally {+ db.close();+ }+}++async function idbGet(key) {+ const db = await openDB();+ try {+ return await new Promise((resolve, reject) => {+ const tx = db.transaction(STORE_NAME, 'readonly');+ const req = tx.objectStore(STORE_NAME).get(key);+ req.onsuccess = () => resolve(req.result ?? null);+ req.onerror = () => reject(req.error);+ });+ } finally {+ db.close();+ }+}++async function idbDelete(key) {+ const db = await openDB();+ try {+ await new Promise((resolve, reject) => {+ const tx = db.transaction(STORE_NAME, 'readwrite');+ tx.objectStore(STORE_NAME).delete(key);+ tx.oncomplete = () => resolve();+ tx.onerror = () => reject(tx.error);+ tx.onabort = () => reject(tx.error);+ });+ } finally {+ db.close();+ }+}++function snapshotEdits(session) {+ return {+ materialEdits: { ...(session.materialEdits || {}) },+ transformEdits: { ...(session.transformEdits || {}) },+ visibilityEdits: { ...(session.visibilityEdits || {}) },+ };+}++const EMPTY_EDITS = {+ materialEdits: {},+ transformEdits: {},+ visibilityEdits: {},+};++/**+ * Stash current editor state so the user can continue after a round-trip (login).+ * Returns a short token to be placed in the URL (e.g. ?resume=abc123).+ *+ * @param {import('./session.js').EditorSession} session+ * @returns {Promise<string>}+ */+export async function stashSession(session) {+ const id = newToken();+ const edits = snapshotEdits(session);+ const blob = { v: BLOB_VERSION, edits, ts: Date.now() };++ if (session.sourceURL) {+ blob.source = { url: session.sourceURL };+ } else if (session.sourceFile) {+ const file = session.sourceFile;+ blob.source = { file: { name: file.name, type: file.type } };+ try {+ const bytes = await file.arrayBuffer();+ await idbPut(id, { name: file.name, type: file.type, bytes });+ } catch (err) {+ console.warn('[edit-persistence] failed to stash file bytes', err);+ // fall through — restore returns null if bytes are missing+ }+ } else {+ blob.source = null;+ }++ try {+ sessionStorage.setItem(SS_PREFIX + id, JSON.stringify(blob));+ } catch (err) {+ console.warn('[edit-persistence] sessionStorage write failed', err);+ }++ return id;+}++/**+ * Restore previously stashed state.+ *+ * @param {string} token+ * @returns {Promise<null | {+ * source: { url: string } | { file: File },+ * edits: { materialEdits: object, transformEdits: object, visibilityEdits: object }+ * }>}+ */+export async function restoreSession(token) {+ if (!token || typeof token !== 'string') return null;++ let raw = null;+ try {+ raw = sessionStorage.getItem(SS_PREFIX + token);+ } catch {+ return null;+ }+ if (!raw) return null;++ let blob;+ try {+ blob = JSON.parse(raw);+ } catch {+ return null;+ }+ if (!blob || !blob.source) return null;++ const edits = blob.edits || EMPTY_EDITS;++ if (blob.source.url) {+ return { source: { url: blob.source.url }, edits };+ }++ if (blob.source.file) {+ let rec = null;+ try {+ rec = await idbGet(token);+ } catch (err) {+ console.warn('[edit-persistence] idb read failed', err);+ return null;+ }+ if (!rec || !rec.bytes) return null;+ const file = new File([rec.bytes], rec.name || 'model.glb', {+ type: rec.type || 'model/gltf-binary',+ });+ return { source: { file }, edits };+ }++ return null;+}++/** Delete the stash (after successful resume). */+export async function clearStash(token) {+ if (!token) return;+ try {+ sessionStorage.removeItem(SS_PREFIX + token);+ } catch {+ /* ignore */+ }+ try {+ await idbDelete(token);+ } catch {+ /* ignore */+ }+}diff --git a/publish/src/editor/embed-editor.js b/publish/src/editor/embed-editor.jsnew file mode 100644index 000000000..e4b313910--- /dev/null+++ b/publish/src/editor/embed-editor.js@@ -0,0 +1,801 @@+// Embed editor — the "place, scale, preview, copy" UX.+// Lets users drop an <agent-3d> exactly where they want on their actual site.+//+// Usage: import and call mountEmbedEditor(rootEl, { src, defaults }).++import '../element.js'; // ensures <agent-3d> is registered++const POSITIONS = [+ { id: 'top-left', label: '↖' },+ { id: 'top-center', label: '↑' },+ { id: 'top-right', label: '↗' },+ { id: 'bottom-left', label: '↙' },+ { id: 'bottom-center', label: '↓' },+ { id: 'bottom-right', label: '↘' },+];++const MODES = [+ { id: 'floating', label: 'Floating bubble', hint: 'Fixed corner, follows scroll' },+ { id: 'inline', label: 'Inline', hint: 'Flows with the page content' },+ { id: 'section', label: 'Section', hint: 'Fills a container' },+ { id: 'fullscreen', label: 'Fullscreen', hint: 'Takes over the viewport' },+];++const DEVICES = [+ { id: 'desktop', label: 'Desktop', w: 1440, h: 900 },+ { id: 'tablet', label: 'Tablet', w: 768, h: 1024 },+ { id: 'mobile', label: 'Mobile', w: 390, h: 844 },+];++const RESPONSIVE_PRESETS = [+ { id: 'fixed', label: 'Fixed', hint: 'Exact px — no scaling' },+ { id: 'mobile-first', label: 'Mobile-first', hint: 'Grows from mobile min' },+ { id: 'desktop-first', label: 'Desktop-first', hint: 'Shrinks from preferred size' },+];++const STYLE = `+ .editor-root {+ position: fixed;+ inset: 0;+ display: grid;+ grid-template-columns: 1fr 360px;+ background: #0b0d10;+ color: #f4f4f5;+ font: 14px/1.4 system-ui, -apple-system, sans-serif;+ z-index: 1;+ }+ .stage-wrap {+ position: relative;+ overflow: hidden;+ background: #1a1d21;+ }+ .stage-wrap iframe {+ width: 100%;+ height: 100%;+ border: 0;+ background: white;+ }+ .stage-wrap .placeholder-site {+ position: absolute;+ inset: 0;+ background:+ linear-gradient(#ffffff, #fafbfc);+ color: #111827;+ padding: 64px 72px;+ overflow: auto;+ }+ .placeholder-site .hero { height: 280px; border-radius: 16px; background: linear-gradient(135deg, #6366f1, #8b5cf6); margin-bottom: 32px; }+ .placeholder-site .row { height: 18px; background: #e5e7eb; border-radius: 999px; margin: 12px 0; }+ .placeholder-site .row.short { width: 60%; }+ .placeholder-site .row.long { width: 92%; }+ .placeholder-site h1 { font: 700 36px/1.2 system-ui; margin-bottom: 16px; }+ .placeholder-site p { color: #4b5563; max-width: 640px; }++ .agent-wrap {+ position: absolute;+ cursor: grab;+ user-select: none;+ touch-action: none;+ }+ .agent-wrap.dragging { cursor: grabbing; }+ .agent-wrap agent-3d { width: 100%; height: 100%; }+ .resize-handle {+ position: absolute;+ width: 14px;+ height: 14px;+ background: white;+ border: 2px solid #3b82f6;+ border-radius: 3px;+ z-index: 2;+ }+ .resize-handle.se { right: -7px; bottom: -7px; cursor: nwse-resize; }+ .resize-handle.sw { left: -7px; bottom: -7px; cursor: nesw-resize; }+ .resize-handle.ne { right: -7px; top: -7px; cursor: nesw-resize; }+ .resize-handle.nw { left: -7px; top: -7px; cursor: nwse-resize; }+ .size-readout {+ position: absolute;+ top: -28px;+ left: 0;+ background: #111827;+ color: #f9fafb;+ font: 11px/1 monospace;+ padding: 4px 6px;+ border-radius: 4px;+ }++ .snapline {+ position: absolute;+ background: #3b82f6;+ opacity: 0.6;+ pointer-events: none;+ }+ .snapline.v { width: 1px; top: 0; bottom: 0; }+ .snapline.h { height: 1px; left: 0; right: 0; }++ .panel {+ background: #0f1216;+ border-left: 1px solid #1f2937;+ display: flex;+ flex-direction: column;+ }+ .panel-header {+ padding: 16px 20px;+ border-bottom: 1px solid #1f2937;+ display: flex;+ justify-content: space-between;+ align-items: center;+ }+ .panel-header h2 { font: 600 16px system-ui; }+ .panel-body { padding: 16px 20px; overflow-y: auto; flex: 1; }+ .section-title { font: 600 11px system-ui; letter-spacing: 0.08em; text-transform: uppercase; color: #9ca3af; margin: 16px 0 8px; }++ .mode-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }+ .mode-card {+ padding: 10px 12px;+ border-radius: 10px;+ background: #111827;+ border: 1px solid #1f2937;+ cursor: pointer;+ transition: border-color 0.15s;+ }+ .mode-card:hover { border-color: #3b82f6; }+ .mode-card[aria-pressed="true"] { border-color: #3b82f6; background: #1e293b; }+ .mode-card .ml { font-weight: 600; margin-bottom: 2px; }+ .mode-card .mh { font-size: 12px; color: #9ca3af; }++ .pos-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 6px;+ }+ .pos-btn {+ aspect-ratio: 1.8;+ background: #111827;+ border: 1px solid #1f2937;+ color: #9ca3af;+ border-radius: 8px;+ font-size: 18px;+ cursor: pointer;+ }+ .pos-btn[aria-pressed="true"] { background: #3b82f6; color: white; border-color: #3b82f6; }++ .field-row { display: grid; grid-template-columns: 80px 1fr; gap: 8px; align-items: center; margin: 6px 0; }+ .field-row label { color: #9ca3af; font-size: 12px; }+ .field-row input, .field-row select {+ background: #111827;+ color: #f4f4f5;+ border: 1px solid #1f2937;+ border-radius: 6px;+ padding: 6px 8px;+ font: 13px system-ui;+ width: 100%;+ box-sizing: border-box;+ }++ .snippet-box {+ background: #0a0d12;+ border: 1px solid #1f2937;+ border-radius: 10px;+ padding: 12px;+ font: 12px/1.5 ui-monospace, Menlo, monospace;+ white-space: pre-wrap;+ word-break: break-all;+ color: #a7f3d0;+ margin-top: 12px;+ }+ .actions { display: flex; gap: 8px; margin-top: 12px; }+ .btn {+ flex: 1;+ background: #3b82f6;+ color: white;+ border: 0;+ border-radius: 8px;+ padding: 10px 12px;+ font: 600 14px system-ui;+ cursor: pointer;+ }+ .btn.secondary { background: transparent; border: 1px solid #1f2937; color: #e5e7eb; }+ .btn:hover { filter: brightness(1.1); }+ .btn[data-copied="true"] { background: #22c55e; }++ .preview-url-row {+ display: flex;+ gap: 6px;+ padding: 10px 16px;+ background: #0f1216;+ border-bottom: 1px solid #1f2937;+ }+ .preview-url-row input {+ flex: 1;+ background: #111827;+ border: 1px solid #1f2937;+ color: #e5e7eb;+ padding: 6px 10px;+ border-radius: 6px;+ }+ .preview-url-row button { background: #3b82f6; color: white; border: 0; border-radius: 6px; padding: 6px 12px; cursor: pointer; }++ .stage-col { display: flex; flex-direction: column; overflow: hidden; }+ .stage-wrap { flex: 1; position: relative; overflow: hidden; background: #1a1d21; }++ .device-bar {+ display: flex;+ gap: 4px;+ padding: 6px 16px;+ background: #0b0d10;+ border-bottom: 1px solid #1f2937;+ align-items: center;+ }+ .device-bar span { font: 11px system-ui; color: #6b7280; margin-right: 4px; }+ .device-btn {+ padding: 3px 10px;+ border-radius: 6px;+ border: 1px solid #1f2937;+ background: #111827;+ color: #9ca3af;+ cursor: pointer;+ font: 12px system-ui;+ }+ .device-btn[aria-pressed="true"] { background: #3b82f6; color: white; border-color: #3b82f6; }++ /* Device viewport frame — shown when simulating tablet/mobile */+ .device-frame {+ position: absolute;+ top: 50%;+ left: 50%;+ transform-origin: top left;+ background: white;+ box-shadow: 0 0 0 2px #374151, 0 12px 40px rgba(0,0,0,0.5);+ border-radius: 8px;+ overflow: hidden;+ transition: width 0.2s, height 0.2s;+ }+ .device-frame .placeholder-site,+ .device-frame iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }+`;++export function mountEmbedEditor(root, options = {}) {+ const defaults = {+ src: options.src || '',+ mode: options.mode || 'floating',+ position: options.position || 'bottom-right',+ offset: options.offset || '24px 24px',+ width: options.width || '320px',+ height: options.height || '420px',+ device: 'desktop',+ responsivePreset: 'desktop-first',+ ...options,+ };++ const state = { ...defaults };+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ root.appendChild(host);++ shadow.innerHTML = `+ <style>${STYLE}</style>+ <div class="editor-root">+ <div class="stage-col">+ <div class="preview-url-row">+ <input type="text" placeholder="Paste your site URL to preview in-place (optional)" id="url-input">+ <button id="url-load">Load site</button>+ <button id="url-clear">Reset</button>+ </div>+ <div class="device-bar" id="device-bar">+ <span>Preview:</span>+ </div>+ <div class="stage-wrap" id="stage">+ <div class="placeholder-site" id="placeholder">+ <h1>Your site goes here</h1>+ <p>This is a preview of what the agent will look like placed on a real page. Paste your site URL above to see the embed on your actual content, or drag the agent around this mock page.</p>+ <div class="hero"></div>+ <div class="row long"></div>+ <div class="row long"></div>+ <div class="row short"></div>+ <div class="row long"></div>+ <div class="row short"></div>+ </div>+ <iframe id="preview-frame" hidden></iframe>+ <div class="agent-wrap" id="agent-wrap">+ <div class="size-readout" id="size-readout"></div>+ <agent-3d eager kiosk id="preview-agent"></agent-3d>+ <div class="resize-handle nw" data-h="nw"></div>+ <div class="resize-handle ne" data-h="ne"></div>+ <div class="resize-handle sw" data-h="sw"></div>+ <div class="resize-handle se" data-h="se"></div>+ </div>+ </div>+ </div>+ <aside class="panel">+ <div class="panel-header">+ <h2>Embed editor</h2>+ <span style="font-size:11px;color:#6b7280">beta</span>+ </div>+ <div class="panel-body">+ <div class="section-title">Source</div>+ <div class="field-row">+ <label>src</label>+ <input id="src-input" placeholder="agent://base/42 or ipfs://...">+ </div>++ <div class="section-title">Mode</div>+ <div class="mode-grid" id="mode-grid"></div>++ <div class="section-title" id="pos-title">Position</div>+ <div class="pos-grid" id="pos-grid"></div>++ <div class="section-title">Size</div>+ <div class="field-row">+ <label>Width</label>+ <input id="w-input" value="${state.width}">+ </div>+ <div class="field-row">+ <label>Height</label>+ <input id="h-input" value="${state.height}">+ </div>++ <div class="section-title">Responsive</div>+ <div class="field-row">+ <label>Preset</label>+ <select id="responsive-select">+ <option value="fixed">Fixed (exact px)</option>+ <option value="mobile-first">Mobile-first (clamp, grows)</option>+ <option value="desktop-first">Desktop-first (clamp, shrinks)</option>+ </select>+ </div>++ <div class="section-title">Options</div>+ <div class="field-row">+ <label>Voice</label>+ <select id="voice-select">+ <option value="">on (default)</option>+ <option value="off">off</option>+ </select>+ </div>+ <div class="field-row">+ <label>Camera</label>+ <select id="camera-select">+ <option value="on">controls on</option>+ <option value="off">controls off</option>+ </select>+ </div>+ <div class="field-row">+ <label>AR</label>+ <select id="ar-select">+ <option value="off">off</option>+ <option value="on">on</option>+ </select>+ </div>++ <div class="section-title">Embed snippet</div>+ <div class="snippet-box" id="snippet"></div>+ <div class="actions">+ <button class="btn" id="copy-btn">Copy snippet</button>+ <button class="btn secondary" id="reset-btn">Reset</button>+ </div>+ </div>+ </aside>+ </div>+ `;++ const $ = (sel) => shadow.querySelector(sel);+ const $$ = (sel) => shadow.querySelectorAll(sel);++ // Device preview buttons+ const deviceBar = $('#device-bar');+ for (const d of DEVICES) {+ const btn = document.createElement('button');+ btn.className = 'device-btn';+ btn.dataset.device = d.id;+ btn.setAttribute('aria-pressed', String(d.id === state.device));+ btn.textContent = d.label;+ btn.addEventListener('click', () => {+ state.device = d.id;+ syncDevice();+ writeSnippet();+ });+ deviceBar.appendChild(btn);+ }++ const stage = $('#stage');+ const agentWrap = $('#agent-wrap');+ const agentEl = $('#preview-agent');+ const readout = $('#size-readout');+ const snippetEl = $('#snippet');+ const srcInput = $('#src-input');+ const wInput = $('#w-input');+ const hInput = $('#h-input');+ const copyBtn = $('#copy-btn');++ srcInput.value = state.src;+ if (state.src) agentEl.setAttribute('src', state.src);++ // Mode cards+ const modeGrid = $('#mode-grid');+ for (const m of MODES) {+ const card = document.createElement('div');+ card.className = 'mode-card';+ card.dataset.mode = m.id;+ card.setAttribute('aria-pressed', String(m.id === state.mode));+ card.tabIndex = 0;+ card.innerHTML = `<div class="ml">${m.label}</div><div class="mh">${m.hint}</div>`;+ card.addEventListener('click', () => {+ state.mode = m.id;+ sync();+ });+ modeGrid.appendChild(card);+ }++ // Position buttons+ const posGrid = $('#pos-grid');+ for (const p of POSITIONS) {+ const btn = document.createElement('button');+ btn.className = 'pos-btn';+ btn.dataset.pos = p.id;+ btn.setAttribute('aria-pressed', String(p.id === state.position));+ btn.textContent = p.label;+ btn.addEventListener('click', () => {+ state.position = p.id;+ sync();+ });+ posGrid.appendChild(btn);+ }++ // Input bindings+ srcInput.addEventListener('change', () => {+ state.src = srcInput.value;+ sync();+ });+ wInput.addEventListener('change', () => {+ state.width = wInput.value;+ sync();+ });+ hInput.addEventListener('change', () => {+ state.height = hInput.value;+ sync();+ });+ $('#voice-select').addEventListener('change', (e) => {+ state.voice = e.target.value === 'off' ? false : true;+ sync();+ });+ $('#camera-select').addEventListener('change', (e) => {+ state.cameraControls = e.target.value === 'on';+ sync();+ });+ $('#ar-select').addEventListener('change', (e) => {+ state.ar = e.target.value === 'on';+ sync();+ });+ $('#responsive-select').addEventListener('change', (e) => {+ state.responsivePreset = e.target.value;+ writeSnippet();+ });++ // URL preview+ const urlInput = $('#url-input');+ $('#url-load').addEventListener('click', () => {+ const u = urlInput.value.trim();+ if (!u) return;+ const iframe = $('#preview-frame');+ iframe.src = u;+ iframe.hidden = false;+ $('#placeholder').hidden = true;+ });+ $('#url-clear').addEventListener('click', () => {+ $('#preview-frame').src = 'about:blank';+ $('#preview-frame').hidden = true;+ $('#placeholder').hidden = false;+ });++ // Drag+ let dragState = null;+ agentWrap.addEventListener('pointerdown', (e) => {+ if (e.target.closest('.resize-handle')) return;+ const rect = stage.getBoundingClientRect();+ const agentRect = agentWrap.getBoundingClientRect();+ dragState = {+ kind: 'move',+ offsetX: e.clientX - agentRect.left,+ offsetY: e.clientY - agentRect.top,+ stageRect: rect,+ };+ agentWrap.classList.add('dragging');+ agentWrap.setPointerCapture(e.pointerId);+ });++ // Resize handles+ $$('.resize-handle').forEach((h) => {+ h.addEventListener('pointerdown', (e) => {+ e.stopPropagation();+ const rect = stage.getBoundingClientRect();+ const agentRect = agentWrap.getBoundingClientRect();+ dragState = {+ kind: 'resize',+ handle: h.dataset.h,+ startX: e.clientX,+ startY: e.clientY,+ startW: agentRect.width,+ startH: agentRect.height,+ startLeft: agentRect.left - rect.left,+ startTop: agentRect.top - rect.top,+ stageRect: rect,+ };+ h.setPointerCapture(e.pointerId);+ });+ });++ stage.addEventListener('pointermove', (e) => {+ if (!dragState) return;+ const rect = dragState.stageRect;+ if (dragState.kind === 'move') {+ const x = e.clientX - rect.left - dragState.offsetX;+ const y = e.clientY - rect.top - dragState.offsetY;+ const snapped = snapToCorner(+ x,+ y,+ agentWrap.offsetWidth,+ agentWrap.offsetHeight,+ rect.width,+ rect.height,+ );+ agentWrap.style.left = snapped.x + 'px';+ agentWrap.style.top = snapped.y + 'px';+ if (snapped.corner) {+ state.position = snapped.corner;+ state.offset = `${snapped.offsetV} ${snapped.offsetH}`;+ syncPositionButtons();+ writeSnippet();+ }+ } else if (dragState.kind === 'resize') {+ const dx = e.clientX - dragState.startX;+ const dy = e.clientY - dragState.startY;+ let w = dragState.startW,+ h = dragState.startH;+ let left = dragState.startLeft,+ top = dragState.startTop;+ if (dragState.handle.includes('e')) w = dragState.startW + dx;+ if (dragState.handle.includes('s')) h = dragState.startH + dy;+ if (dragState.handle.includes('w')) {+ w = dragState.startW - dx;+ left = dragState.startLeft + dx;+ }+ if (dragState.handle.includes('n')) {+ h = dragState.startH - dy;+ top = dragState.startTop + dy;+ }+ w = Math.max(160, w);+ h = Math.max(200, h);+ agentWrap.style.width = w + 'px';+ agentWrap.style.height = h + 'px';+ agentWrap.style.left = left + 'px';+ agentWrap.style.top = top + 'px';+ state.width = Math.round(w) + 'px';+ state.height = Math.round(h) + 'px';+ wInput.value = state.width;+ hInput.value = state.height;+ readout.textContent = `${state.width} × ${state.height}`;+ writeSnippet();+ }+ });++ stage.addEventListener('pointerup', () => {+ if (dragState) {+ agentWrap.classList.remove('dragging');+ dragState = null;+ }+ });++ copyBtn.addEventListener('click', async () => {+ await navigator.clipboard.writeText(buildSnippet());+ copyBtn.textContent = 'Copied ✓';+ copyBtn.dataset.copied = 'true';+ setTimeout(() => {+ copyBtn.textContent = 'Copy snippet';+ copyBtn.dataset.copied = 'false';+ }, 1500);+ });++ $('#reset-btn').addEventListener('click', () => {+ Object.assign(state, defaults);+ srcInput.value = state.src;+ wInput.value = state.width;+ hInput.value = state.height;+ $('#responsive-select').value = state.responsivePreset;+ sync();+ });++ // Show appropriate resize handles based on position+ function syncPositionButtons() {+ for (const btn of $$('.pos-btn'))+ btn.setAttribute('aria-pressed', String(btn.dataset.pos === state.position));+ }+ function syncModeCards() {+ for (const card of $$('.mode-card'))+ card.setAttribute('aria-pressed', String(card.dataset.mode === state.mode));+ }++ function applyToPreview() {+ // Size+ agentWrap.style.width = state.width;+ agentWrap.style.height = state.height;+ readout.textContent = `${state.width} × ${state.height}`;++ // Position — place the wrap inside the stage per mode + position+ agentWrap.style.left =+ agentWrap.style.right =+ agentWrap.style.top =+ agentWrap.style.bottom =+ '';+ if (state.mode === 'floating') {+ const [vOff, hOff] = (state.offset || '24px 24px').split(/\s+/);+ if (state.position.includes('top')) agentWrap.style.top = vOff;+ else agentWrap.style.bottom = vOff;+ if (state.position.includes('left')) agentWrap.style.left = hOff;+ else if (state.position.includes('right')) agentWrap.style.right = hOff;+ else if (state.position.includes('center')) {+ agentWrap.style.left = '50%';+ agentWrap.style.transform = 'translateX(-50%)';+ }+ $('#pos-title').style.display = '';+ $('#pos-grid').style.display = '';+ } else if (state.mode === 'fullscreen') {+ agentWrap.style.inset = '0';+ agentWrap.style.width = '100%';+ agentWrap.style.height = '100%';+ $('#pos-title').style.display = 'none';+ $('#pos-grid').style.display = 'none';+ } else {+ // inline / section: center on stage+ agentWrap.style.left = `calc(50% - ${parseInt(state.width) / 2}px)`;+ agentWrap.style.top = `calc(50% - ${parseInt(state.height) / 2}px)`;+ $('#pos-title').style.display = 'none';+ $('#pos-grid').style.display = 'none';+ }++ // Agent attrs+ if (state.src) agentEl.setAttribute('src', state.src);+ else agentEl.removeAttribute('src');+ }++ function buildSnippet() {+ const attrs = [];+ if (state.src) attrs.push(`src="${escapeAttr(state.src)}"`);+ if (state.mode && state.mode !== 'inline') attrs.push(`mode="${state.mode}"`);+ if (state.mode === 'floating') {+ if (state.position !== 'bottom-right') attrs.push(`position="${state.position}"`);+ if (state.offset && state.offset !== '24px 24px')+ attrs.push(`offset="${state.offset}"`);+ }++ const wPx = parsePx(state.width);+ const hPx = parsePx(state.height);+ const preset = state.responsivePreset;++ if (preset !== 'fixed' && wPx && hPx) {+ // Emit clamp() CSS custom properties on the style attribute+ const wMin = Math.round(Math.max(160, wPx * 0.65));+ const hMin = Math.round(Math.max(200, hPx * 0.65));+ const wVw = Math.round((wPx / 1440) * 100);+ const hVh = Math.round((hPx / 900) * 100);+ const wClamp = `clamp(${wMin}px, ${wVw}vw, ${wPx}px)`;+ const hClamp = `clamp(${hMin}px, ${hVh}vh, ${hPx}px)`;+ attrs.push(`style="--agent-width: ${wClamp}; --agent-height: ${hClamp};"`);+ attrs.push(`responsive`);+ } else {+ if (state.width) attrs.push(`width="${state.width}"`);+ if (state.height) attrs.push(`height="${state.height}"`);+ attrs.push(`responsive="false"`);+ }++ if (state.voice === false) attrs.push(`voice="off"`);+ if (state.cameraControls) attrs.push(`camera-controls`);+ if (state.ar) attrs.push(`ar`);++ const script = `<script type="module" src="https://cdn.3d-agent.io/agent-3d.js"></script>`;+ const element = `<agent-3d ${attrs.join(' ')}></agent-3d>`;+ let snippet = `${script}\n${element}`;++ if (preset !== 'fixed') {+ snippet = `<!-- generated responsive styles -->\n${snippet}`;+ }+ return snippet;+ }++ function writeSnippet() {+ snippetEl.textContent = buildSnippet();+ }++ function syncDevice() {+ const device = DEVICES.find((d) => d.id === state.device) || DEVICES[0];+ for (const btn of $$('.device-btn')) {+ btn.setAttribute('aria-pressed', String(btn.dataset.device === state.device));+ }++ const stageRect = stage.getBoundingClientRect();+ const stageW = stageRect.width || stage.offsetWidth;+ const stageH = stageRect.height || stage.offsetHeight;++ if (state.device === 'desktop') {+ // No frame — fills stage normally+ $('#placeholder').style.cssText = '';+ const iframe = $('#preview-frame');+ if (iframe) iframe.style.cssText = '';+ stage.removeAttribute('data-device');+ } else {+ // Show device frame scaled to fit the stage+ const scaleX = stageW / device.w;+ const scaleY = stageH / device.h;+ const scale = Math.min(scaleX, scaleY, 1) * 0.9;+ const frameW = device.w * scale;+ const frameH = device.h * scale;+ const offsetX = (stageW - frameW) / 2;+ const offsetY = (stageH - frameH) / 2;++ const placeholder = $('#placeholder');+ placeholder.style.cssText = `+ width: ${device.w}px; height: ${device.h}px;+ transform: scale(${scale}); transform-origin: top left;+ top: ${offsetY / scale}px; left: ${offsetX / scale}px;+ position: absolute;+ `;+ const iframe = $('#preview-frame');+ if (iframe && !iframe.hidden) {+ iframe.style.cssText = `+ width: ${device.w}px; height: ${device.h}px;+ transform: scale(${scale}); transform-origin: top left;+ top: ${offsetY / scale}px; left: ${offsetX / scale}px;+ position: absolute; border: 0;+ `;+ }+ stage.setAttribute('data-device', state.device);+ }+ }++ function parsePx(val) {+ if (!val) return 0;+ const m = String(val).match(/^([\d.]+)px$/);+ return m ? parseFloat(m[1]) : 0;+ }++ function sync() {+ syncPositionButtons();+ syncModeCards();+ applyToPreview();+ syncDevice();+ writeSnippet();+ }++ function snapToCorner(x, y, w, h, stageW, stageH) {+ const SNAP = 48;+ const corners = [+ { corner: 'top-left', cx: 0, cy: 0 },+ { corner: 'top-right', cx: stageW - w, cy: 0 },+ { corner: 'bottom-left', cx: 0, cy: stageH - h },+ { corner: 'bottom-right', cx: stageW - w, cy: stageH - h },+ { corner: 'top-center', cx: (stageW - w) / 2, cy: 0 },+ { corner: 'bottom-center', cx: (stageW - w) / 2, cy: stageH - h },+ ];+ for (const c of corners) {+ if (Math.abs(x - c.cx) < SNAP && Math.abs(y - c.cy) < SNAP) {+ // Compute offsets from nearest edge+ const offV = c.corner.startsWith('top')+ ? `${Math.round(c.cy)}px`+ : `${Math.round(stageH - h - c.cy)}px`;+ const offH = c.corner.endsWith('left')+ ? `${Math.round(c.cx)}px`+ : c.corner.endsWith('right')+ ? `${Math.round(stageW - w - c.cx)}px`+ : '0px';+ return { x: c.cx, y: c.cy, corner: c.corner, offsetV: offV, offsetH: offH };+ }+ }+ return { x, y };+ }++ function escapeAttr(s) {+ return String(s).replace(/"/g, '"');+ }++ sync();+ return { state, host };+}diff --git a/publish/src/editor/glb-export.js b/publish/src/editor/glb-export.jsnew file mode 100644index 000000000..4b3907404--- /dev/null+++ b/publish/src/editor/glb-export.js@@ -0,0 +1,125 @@+/**+ * GLB export pipeline using glTF-Transform.+ *+ * Reads the original GLB/GLTF bytes, applies accumulated edits from the+ * EditorSession, and re-serializes as a valid GLB. We match Three.js edits+ * back to glTF-Transform entities by NAME (UUIDs don't cross the boundary).+ *+ * Materials: names are typically unique within a glTF. If two materials+ * share a name we still apply edits to the first match — correct 99% of+ * the time and not worse than what the GUI would suggest.+ */+import { WebIO } from '@gltf-transform/core';+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';++/** Convert an Euler (XYZ order, radians) to a quaternion [x,y,z,w]. */+function eulerToQuat([x, y, z]) {+ const cx = Math.cos(x / 2),+ sx = Math.sin(x / 2);+ const cy = Math.cos(y / 2),+ sy = Math.sin(y / 2);+ const cz = Math.cos(z / 2),+ sz = Math.sin(z / 2);+ return [+ sx * cy * cz + cx * sy * sz,+ cx * sy * cz - sx * cy * sz,+ cx * cy * sz + sx * sy * cz,+ cx * cy * cz - sx * sy * sz,+ ];+}++/**+ * @param {EditorSession} session+ * @returns {Promise<Uint8Array>} modified GLB bytes+ */+export async function exportEditedGLB(session) {+ const buf = await session.getSourceBuffer();+ if (!buf) throw new Error('No source buffer for export');++ const io = new WebIO({ credentials: 'include' }).registerExtensions(ALL_EXTENSIONS);+ const doc = await io.readBinary(new Uint8Array(buf));+ const root = doc.getRoot();++ applyMaterialEdits(root, session.materialEdits);+ applyTransformAndVisibilityEdits(root, session.transformEdits, session.visibilityEdits);++ return io.writeBinary(doc);+}++function applyMaterialEdits(root, edits) {+ if (!edits || !Object.keys(edits).length) return;++ const byName = new Map();+ for (const mat of root.listMaterials()) {+ const n = mat.getName();+ if (!byName.has(n)) byName.set(n, mat);+ }++ for (const uuid in edits) {+ const edit = edits[uuid];+ const mat = byName.get(edit.name);+ if (!mat) continue;++ if (edit.baseColor) {+ const [r, g, b] = edit.baseColor;+ const alpha =+ edit.opacity !== undefined ? edit.opacity : (mat.getBaseColorFactor()[3] ?? 1);+ mat.setBaseColorFactor([r, g, b, alpha]);+ } else if (edit.opacity !== undefined) {+ const f = mat.getBaseColorFactor() || [1, 1, 1, 1];+ mat.setBaseColorFactor([f[0], f[1], f[2], edit.opacity]);+ }++ if (edit.metalness !== undefined) mat.setMetallicFactor(edit.metalness);+ if (edit.roughness !== undefined) mat.setRoughnessFactor(edit.roughness);+ if (edit.emissive) mat.setEmissiveFactor(edit.emissive);+ if (edit.alphaMode !== undefined) mat.setAlphaMode(edit.alphaMode);+ if (edit.alphaCutoff !== undefined) mat.setAlphaCutoff(edit.alphaCutoff);+ if (edit.doubleSided !== undefined) mat.setDoubleSided(edit.doubleSided);+ }+}++function applyTransformAndVisibilityEdits(root, transformEdits, visibilityEdits) {+ const hasT = transformEdits && Object.keys(transformEdits).length > 0;+ const hasV = visibilityEdits && Object.keys(visibilityEdits).length > 0;+ if (!hasT && !hasV) return;++ const byName = new Map();+ for (const node of root.listNodes()) {+ const n = node.getName();+ if (n && !byName.has(n)) byName.set(n, node);+ }++ if (hasT) {+ for (const uuid in transformEdits) {+ const edit = transformEdits[uuid];+ const node = byName.get(edit.name);+ if (!node) continue;+ if (edit.position) node.setTranslation(edit.position);+ if (edit.rotation) node.setRotation(eulerToQuat(edit.rotation));+ if (edit.scale) node.setScale(edit.scale);+ }+ }++ if (hasV) {+ for (const uuid in visibilityEdits) {+ const edit = visibilityEdits[uuid];+ if (edit.visible) continue;+ const node = byName.get(edit.name);+ if (!node) continue;+ node.setScale([0, 0, 0]);+ }+ }+}++export function downloadGLB(bytes, filename = 'edited.glb') {+ const blob = new Blob([bytes], { type: 'model/gltf-binary' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}diff --git a/publish/src/editor/index.js b/publish/src/editor/index.jsnew file mode 100644index 000000000..94e564952--- /dev/null+++ b/publish/src/editor/index.js@@ -0,0 +1,241 @@+/**+ * Editor — orchestrator that wires Material Editor, Texture Inspector,+ * Scene Explorer, and GLB export into the Viewer.+ *+ * Usage:+ * const editor = new Editor(viewer);+ * editor.attach(); // once, after viewer constructed+ * editor.onContentChanged({ url, file }); // every time a new model loads+ */+import { EditorSession } from './session.js';+import { MaterialEditor } from './material-editor.js';+import { SceneExplorer } from './scene-explorer.js';+import { TextureInspector } from './texture-inspector.js';+import { exportEditedGLB, downloadGLB } from './glb-export.js';++export class Editor {+ constructor(viewer) {+ this.viewer = viewer;+ this.session = new EditorSession(viewer);+ this.materialEditor = new MaterialEditor(viewer, this.session);+ this.textureInspector = new TextureInspector(viewer, this.session);+ this.sceneExplorer = new SceneExplorer(viewer, this.session);+ this.exportFolder = null;+ this._exportCtrl = null;+ this._publishCtrl = null;+ this._saveCtrl = null;+ this._publishInFlight = false;+ this._saveNeedsAuth = false;+ this._attached = false;+ }++ attach() {+ if (this._attached) return;+ this._attached = true;+ this.sceneExplorer.attach();+ this._addExportFolder();+ this.session.onChange(() => {+ this._updateExportLabel();+ this._updateExportEnabled();+ });+ this._updateExportEnabled();+ }++ onContentChanged({ url = null, file = null, name = null } = {}) {+ this.session.reset({ url, file, name });+ this.materialEditor.rebuild();+ this.textureInspector.rebuild();+ this.sceneExplorer.rebuild();+ this._updateExportLabel();+ }++ _addExportFolder() {+ if (!this.viewer.gui) return;+ const folder = this.viewer.gui.addFolder('Editor');+ this._exportCtrl = folder+ .add(+ {+ download: () => this._exportGLB(),+ },+ 'download',+ )+ .name('💾 download GLB');+ this._publishCtrl = folder+ .add(+ {+ publish: () => this._openPublishModal(),+ },+ 'publish',+ )+ .name('📤 publish as embed');+ folder+ .add(+ {+ explorer: () => this.sceneExplorer.toggle(),+ },+ 'explorer',+ )+ .name('🗂 scene panel [T]');+ this._saveCtrl = folder+ .add({ save: () => this._saveEdits() }, 'save')+ .name('☁️ save edits');+ folder+ .add(+ {+ reset: () => this._resetAll(),+ },+ 'reset',+ )+ .name('↺ revert all edits');+ this.exportFolder = folder;+ }++ _updateExportLabel() {+ if (!this._exportCtrl) return;+ const count =+ Object.keys(this.session.materialEdits).length ++ Object.keys(this.session.transformEdits).length ++ Object.keys(this.session.visibilityEdits).length;+ const base = '💾 download GLB';+ this._exportCtrl.name(count > 0 ? `${base} (${count})` : base);+ }++ _updateExportEnabled() {+ if (!this._exportCtrl) return;+ const ready = this.session.isExportReady();+ const row = this._exportCtrl.__li || this._exportCtrl.domElement;+ if (row) {+ row.style.pointerEvents = ready ? '' : 'none';+ row.style.opacity = ready ? '' : '0.4';+ }+ }++ async _exportGLB() {+ try {+ const bytes = await exportEditedGLB(this.session);+ const base = (this.session.sourceName || 'model')+ .replace(/\?.*$/, '')+ .replace(/\.(glb|gltf)$/i, '');+ downloadGLB(bytes, `${base}.edited.glb`);+ } catch (err) {+ console.error('[editor] GLB export failed', err);+ window.alert('GLB export failed: ' + (err.message || err));+ }+ }++ async _saveEdits() {+ if (this._saveNeedsAuth) {+ window.location.href =+ '/login?next=' ++ encodeURIComponent(location.pathname + location.search + location.hash);+ return;+ }+ const avatarId =+ this.session.avatarId ?? new URLSearchParams(location.search).get('avatarId');+ if (!avatarId) {+ this._saveCtrl?.name('⚠ use Publish instead');+ setTimeout(() => this._saveCtrl?.name('☁️ save edits'), 2500);+ return;+ }+ const LABEL = '☁️ save edits';+ const stepPct = { export: 0, presign: 0.25, upload: 0.4, patch: 0.9 };+ const onStep = ({ step, pct }) => {+ const base = stepPct[step] ?? 0;+ const span =+ step === 'upload'+ ? 0.5+ : step === 'export'+ ? 0.25+ : step === 'presign'+ ? 0.15+ : 0.1;+ const overall = Math.round((base + pct * span) * 100);+ this._saveCtrl?.name(`saving… ${overall}%`);+ };+ try {+ const { saveEditedAvatar } = await import('./save-back.js');+ await saveEditedAvatar(this.session, { avatarId, onStep });+ this._saveCtrl?.name('saved ✓');+ setTimeout(() => this._saveCtrl?.name(LABEL), 1500);+ } catch (err) {+ if (err?.code === 'auth') {+ this._saveNeedsAuth = true;+ this._saveCtrl?.name('⚠ sign in to save (click)');+ } else {+ console.error('[editor] save failed', err);+ this._saveCtrl?.name('⚠ ' + (err?.message || 'save failed'));+ setTimeout(() => this._saveCtrl?.name(LABEL), 3000);+ }+ }+ }++ _resetAll() {+ if (!this.session.isDirty()) return;+ if (!window.confirm('Discard all edits and reload the model?')) return;+ window.location.reload();+ }++ async _openPublishModal() {+ if (this._publishInFlight) return;+ this._publishInFlight = true;+ this._setPublishEnabled(false);++ let modal = null;+ try {+ const [publishMod, modalMod] = await Promise.all([+ import('./publish.js'),+ import('./publish-modal.js'),+ ]);+ const { publishEditedGLB, AuthRequiredError } = publishMod;+ const { PublishModal } = modalMod;++ modal = new PublishModal(document.body, { session: this.session });+ modal.onRetry(() => this._openPublishModal());+ modal.open();++ try {+ const result = await publishEditedGLB(this.session, { onStep: modal.onStep });+ modal.showResult(result.urls);+ } catch (err) {+ if (err instanceof AuthRequiredError || err?.name === 'AuthRequiredError') {+ modal.showAuthRequired();+ } else {+ modal.showError(err);+ }+ console.error('[editor] publish failed', err);+ }+ } catch (err) {+ console.error('[editor] publish modal failed to load', err);+ if (modal) modal.showError(err);+ else window.alert('Publish failed: ' + (err.message || err));+ } finally {+ this._publishInFlight = false;+ this._setPublishEnabled(true);+ }+ }++ _setPublishEnabled(enabled) {+ if (!this._publishCtrl) return;+ const row = this._publishCtrl.__li || this._publishCtrl.domElement;+ if (row) {+ row.style.pointerEvents = enabled ? '' : 'none';+ row.style.opacity = enabled ? '' : '0.4';+ }+ }++ dispose() {+ this.materialEditor.dispose();+ this.textureInspector.dispose();+ this.sceneExplorer.detach();+ if (this.exportFolder && this.viewer.gui) {+ try {+ this.viewer.gui.removeFolder(this.exportFolder);+ } catch (e) {}+ }+ this.exportFolder = null;+ this._exportCtrl = null;+ this._publishCtrl = null;+ this._saveCtrl = null;+ this._attached = false;+ }+}diff --git a/publish/src/editor/manifest-builder.js b/publish/src/editor/manifest-builder.jsnew file mode 100644index 000000000..18fcc30e9--- /dev/null+++ b/publish/src/editor/manifest-builder.js@@ -0,0 +1,1625 @@+// Manifest builder UI — shadow-DOM form that produces a valid agent manifest bundle.+// Usage: mountManifestBuilder(rootEl, options)+// Feature-flagged behind ?editor=v2 — do not remove register-ui.js until this ships.++import { z } from 'zod';+import '../element.js';++// ─── Constants ────────────────────────────────────────────────────────────────++const ANTHROPIC_MODELS = [+ { id: 'claude-opus-4-7', label: 'Claude Opus 4.7' },+ { id: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6' },+ { id: 'claude-haiku-4-5-20251001', label: 'Claude Haiku 4.5' },+];+const OPENAI_MODELS = [+ { id: 'gpt-4o-2024-11-20', label: 'GPT-4o (Nov 2024)' },+ { id: 'gpt-4o-mini', label: 'GPT-4o mini' },+ { id: 'gpt-4-turbo', label: 'GPT-4 Turbo' },+];+const BRAIN_PROVIDERS = ['anthropic', 'openai', 'local', 'none'];+const TTS_PROVIDERS = ['browser', 'elevenlabs', 'openai', 'none'];+const STT_PROVIDERS = ['browser', 'whisper', 'none'];+const MEMORY_MODES = ['local', 'ipfs', 'encrypted-ipfs', 'none'];+const RIG_TYPES = ['mixamo', 'vrm', 'custom'];+const BODY_FORMATS = ['gltf-binary', 'gltf', 'vrm'];+const THINKING_OPTS = ['auto', 'always', 'never'];++const DRAFT_KEY = 'manifest-builder-draft';++// ─── Zod schema ───────────────────────────────────────────────────────────────++const ManifestSchema = z.object({+ spec: z.literal('agent-manifest/0.1'),+ name: z.string().min(1, 'Name is required').max(100, 'Max 100 chars'),+ description: z.string().max(1000).optional(),+ image: z.string().optional(),+ tags: z.array(z.string()).optional(),+ body: z.object({+ uri: z.string().min(1, 'Body URI is required'),+ format: z.enum(['gltf-binary', 'gltf', 'vrm']),+ rig: z.enum(['mixamo', 'vrm', 'custom']).optional(),+ boundingBoxHeight: z.number().positive().optional(),+ }),+ brain: z+ .object({+ provider: z.enum(['anthropic', 'openai', 'local', 'none']),+ model: z.string().optional(),+ instructions: z.string().optional(),+ temperature: z.number().min(0).max(2).optional(),+ maxTokens: z.number().int().positive().optional(),+ thinking: z.enum(['auto', 'always', 'never']).optional(),+ })+ .optional(),+ voice: z+ .object({+ tts: z+ .object({+ provider: z.enum(['browser', 'elevenlabs', 'openai', 'none']),+ voiceId: z.string().optional(),+ rate: z.number().min(0.5).max(2).optional(),+ pitch: z.number().min(0).max(2).optional(),+ })+ .optional(),+ stt: z+ .object({+ provider: z.enum(['browser', 'whisper', 'none']),+ language: z.string().optional(),+ continuous: z.boolean().optional(),+ })+ .optional(),+ })+ .optional(),+ skills: z+ .array(+ z.object({+ uri: z.string(),+ version: z.string().optional(),+ }),+ )+ .optional(),+ memory: z+ .object({+ mode: z.enum(['local', 'ipfs', 'encrypted-ipfs', 'none']),+ index: z.string().optional(),+ maxTokens: z.number().int().positive().optional(),+ })+ .optional(),+ tools: z.array(z.string()).optional(),+ version: z.string().optional(),+});++// ─── Default state ────────────────────────────────────────────────────────────++function defaultState() {+ return {+ name: '',+ description: '',+ tags: '',+ image: '',+ glbFile: null,+ glbUri: '',+ bodyFormat: 'gltf-binary',+ rig: 'mixamo',+ boundingBoxHeight: 1.78,+ brainProvider: 'anthropic',+ brainModel: 'claude-opus-4-6',+ temperature: 0.7,+ maxTokens: 4096,+ thinking: 'auto',+ ttsProvider: 'browser',+ voiceId: '',+ ttsRate: 1.0,+ ttsPitch: 1.0,+ sttProvider: 'browser',+ sttLanguage: 'en-US',+ sttContinuous: false,+ installedSkills: {},+ customSkills: [],+ memoryMode: 'local',+ memoryMaxTokens: 8192,+ memoryRetentionDays: 90,+ instructions: '',+ version: '0.1.0',+ };+}++// ─── Styles ───────────────────────────────────────────────────────────────────++const STYLE = `+ :host { display: block; }+ * { box-sizing: border-box; margin: 0; padding: 0; }+ .root {+ position: fixed; inset: 0;+ display: grid; grid-template-columns: 1fr 400px;+ background: #0b0d10; color: #f4f4f5;+ font: 14px/1.4 system-ui, -apple-system, sans-serif;+ z-index: 1; overflow: hidden;+ }+ .preview-col { position: relative; background: #1a1d21; display: flex; flex-direction: column; }+ .preview-header {+ padding: 11px 16px; border-bottom: 1px solid #1f2937;+ font: 600 11px system-ui; letter-spacing: .08em; text-transform: uppercase; color: #6b7280;+ display: flex; align-items: center; justify-content: space-between; flex-shrink: 0;+ }+ .preview-body { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px; }+ .preview-agent-wrap { width: 320px; height: 440px; }+ .preview-agent-wrap agent-3d { width: 100%; height: 100%; }+ .preview-empty { text-align: center; color: #374151; }+ .preview-empty p { font-size: 12px; color: #4b5563; margin-top: 12px; }++ .panel { background: #0f1216; border-left: 1px solid #1f2937; display: flex; flex-direction: column; min-height: 0; position: relative; }+ .panel-header { padding: 13px 18px; border-bottom: 1px solid #1f2937; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }+ .panel-header h2 { font: 600 15px system-ui; }+ .v2-badge { font: 700 10px system-ui; color: #3b82f6; letter-spacing: .05em; }++ .tab-bar { display: flex; border-bottom: 1px solid #1f2937; flex-shrink: 0; }+ .tab-btn { padding: 8px 14px; background: transparent; border: 0; border-bottom: 2px solid transparent; color: #6b7280; font: 13px system-ui; cursor: pointer; margin-bottom: -1px; }+ .tab-btn[aria-selected="true"] { color: #f4f4f5; border-bottom-color: #3b82f6; }+ .tab-panel { display: none; flex-direction: column; flex: 1; min-height: 0; }+ .tab-panel.active { display: flex; }++ .form-scroll { overflow-y: auto; flex: 1; padding-bottom: 70px; }++ details { border-bottom: 1px solid #1f2937; }+ details > summary {+ padding: 10px 18px; font: 600 11px system-ui; letter-spacing: .08em; text-transform: uppercase;+ color: #9ca3af; cursor: pointer; user-select: none; list-style: none;+ display: flex; align-items: center; justify-content: space-between;+ }+ details > summary::after { content: '›'; font-size: 16px; transition: transform .15s; color: #4b5563; }+ details[open] > summary::after { transform: rotate(90deg); }+ details > summary::-webkit-details-marker { display: none; }+ .section-body { padding: 4px 18px 14px; }++ .field { margin: 8px 0; }+ .field label { display: block; font-size: 11px; color: #9ca3af; margin-bottom: 4px; }+ .field input, .field select, .field textarea {+ width: 100%; background: #111827; color: #f4f4f5; border: 1px solid #1f2937;+ border-radius: 6px; padding: 6px 8px; font: 13px system-ui;+ }+ .field input:focus, .field select:focus, .field textarea:focus { outline: none; border-color: #3b82f6; }+ .field textarea { font-family: ui-monospace, Menlo, monospace; resize: vertical; min-height: 100px; }+ .field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }+ .field-error { color: #f87171; font-size: 11px; margin-top: 3px; display: none; }+ .field-error.show { display: block; }+ .field-hint { color: #4b5563; font-size: 11px; margin-top: 3px; }++ input[type="range"] { padding: 0; accent-color: #3b82f6; }+ .slider-row { display: grid; grid-template-columns: 1fr 44px; gap: 8px; align-items: center; }+ .slider-val { text-align: right; font: 12px ui-monospace, monospace; color: #9ca3af; }++ .drop-zone {+ border: 1px dashed #374151; border-radius: 8px; padding: 16px;+ text-align: center; cursor: pointer; transition: border-color .15s, background .15s;+ font-size: 12px; color: #6b7280;+ }+ .drop-zone:hover, .drop-zone.drag { border-color: #3b82f6; background: rgba(59,130,246,.05); }+ .drop-zone.filled { border-style: solid; border-color: #374151; color: #9ca3af; }+ .drop-zone input[type="file"] { display: none; }++ .skill-item { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; padding: 8px 10px; background: #111827; border: 1px solid #1f2937; border-radius: 8px; margin: 6px 0; font-size: 12px; transition: border-color .15s, transform .15s; }+ .skill-item:hover { border-color: #374151; }+ .skill-item.installed { border-color: #2563eb; background: linear-gradient(180deg, rgba(37,99,235,.08), #111827); }+ .skill-item-info { flex: 1; min-width: 0; }+ .skill-item-info .skill-item-name { font-weight: 600; color: #e5e7eb; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }+ .skill-item-info .skill-item-desc { color: #9ca3af; font-size: 11px; margin-top: 3px; line-height: 1.4; }+ .skill-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }+ .skill-tag { font: 600 9px/1 system-ui; letter-spacing: .04em; text-transform: uppercase; color: #93c5fd; background: rgba(59,130,246,.12); border: 1px solid rgba(59,130,246,.25); padding: 3px 6px; border-radius: 4px; }+ .skill-tag[data-chain="solana"] { color: #c4b5fd; background: rgba(139,92,246,.14); border-color: rgba(139,92,246,.28); }+ .skill-tag[data-chain="evm"] { color: #93c5fd; background: rgba(59,130,246,.14); border-color: rgba(59,130,246,.28); }+ .skill-tag[data-kind="readonly"] { color: #6ee7b7; background: rgba(16,185,129,.12); border-color: rgba(16,185,129,.28); }+ .skill-tag[data-kind="payments"] { color: #fbbf24; background: rgba(234,179,8,.12); border-color: rgba(234,179,8,.28); }+ .skill-actions { display: flex; flex-direction: column; gap: 4px; flex-shrink: 0; align-items: flex-end; }+ .skill-toggle { background: transparent; border: 1px solid #374151; color: #9ca3af; border-radius: 5px; padding: 4px 10px; font: 600 11px system-ui; cursor: pointer; flex-shrink: 0; transition: all .12s; }+ .skill-toggle:hover { border-color: #6b7280; color: #d1d5db; }+ .skill-toggle.on { background: #1e3a5f; border-color: #3b82f6; color: #93c5fd; }+ .skill-toggle.on:hover { background: #1e40af; }+ .skill-preview-btn { font: 10px system-ui; color: #6b7280; background: none; border: 0; cursor: pointer; padding: 0; }+ .skill-preview-btn:hover { color: #9ca3af; }+ .skill-tools-preview { margin-top: 8px; padding: 8px; background: #0b1220; border: 1px solid #1f2937; border-radius: 6px; display: none; }+ .skill-tools-preview.open { display: block; }+ .skill-tools-preview h5 { font: 600 9px/1 system-ui; letter-spacing: .08em; text-transform: uppercase; color: #6b7280; margin: 0 0 6px; }+ .skill-tools-preview ul { list-style: none; padding: 0; margin: 0; display: flex; flex-wrap: wrap; gap: 4px; }+ .skill-tools-preview li { font: 11px ui-monospace, SFMono-Regular, monospace; color: #cbd5e1; background: #1f2937; padding: 2px 6px; border-radius: 4px; }+ .skill-tools-preview .example { margin-top: 6px; font-size: 11px; color: #9ca3af; font-style: italic; }+ .skill-filters { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 8px; }+ .skill-chip { font: 600 10px/1 system-ui; letter-spacing: .04em; text-transform: uppercase; color: #9ca3af; background: #1f2937; border: 1px solid #1f2937; padding: 5px 9px; border-radius: 999px; cursor: pointer; transition: all .12s; }+ .skill-chip:hover { color: #d1d5db; border-color: #374151; }+ .skill-chip.active { color: #93c5fd; background: rgba(59,130,246,.18); border-color: rgba(59,130,246,.38); }+ .skill-empty { font-size: 12px; color: #4b5563; padding: 12px; text-align: center; border: 1px dashed #1f2937; border-radius: 6px; }+ .skill-custom-row { display: flex; gap: 6px; margin-top: 8px; }+ .skill-custom-row input { flex: 1; background: #111827; color: #f4f4f5; border: 1px solid #1f2937; border-radius: 6px; padding: 6px 8px; font: 12px system-ui; }+ .skill-custom-row input:focus { outline: none; border-color: #3b82f6; }++ .validator-idle { color: #4b5563; font-size: 12px; }+ .badge { padding: 2px 7px; border-radius: 999px; font-size: 11px; font-weight: 600; }+ .badge-err { background: rgba(239,68,68,.15); color: #f87171; }+ .badge-warn { background: rgba(234,179,8,.15); color: #fbbf24; }+ .badge-ok { background: rgba(34,197,94,.15); color: #4ade80; }+ .validator-detail { font-size: 11px; color: #6b7280; margin-top: 6px; padding: 8px; background: #111827; border-radius: 6px; display: none; white-space: pre-wrap; max-height: 160px; overflow-y: auto; }+ .validator-detail.open { display: block; }+ .validator-toggle { font-size: 11px; color: #4b5563; cursor: pointer; background: none; border: 0; padding: 0; margin-top: 4px; }+ .validator-toggle:hover { color: #9ca3af; }++ .char-counter { text-align: right; font-size: 11px; color: #4b5563; margin-top: 3px; }+ .md-preview { font-size: 12px; color: #9ca3af; line-height: 1.6; margin-top: 8px; border-top: 1px solid #1f2937; padding-top: 8px; min-height: 40px; }+ .md-preview h1, .md-preview h2, .md-preview h3 { color: #e5e7eb; margin: 6px 0 3px; }+ .md-preview code { background: #111827; padding: 1px 4px; border-radius: 3px; font-size: 11px; font-family: ui-monospace, monospace; }+ .md-preview pre { background: #111827; padding: 8px; border-radius: 6px; overflow-x: auto; }+ .md-preview blockquote { border-left: 2px solid #374151; padding-left: 8px; color: #6b7280; }++ .raw-scroll { flex: 1; overflow-y: auto; padding: 12px 18px 70px; }+ .raw-textarea {+ width: 100%; min-height: 360px; background: #0a0d12; color: #a7f3d0;+ border: 1px solid #1f2937; border-radius: 8px; padding: 12px;+ font: 11px/1.5 ui-monospace, Menlo, monospace; resize: vertical;+ }+ .raw-textarea:focus { outline: none; border-color: #3b82f6; }+ .raw-error { color: #f87171; font-size: 11px; margin-top: 6px; min-height: 16px; }+ .raw-apply { margin-top: 6px; background: #1e3a5f; border: 1px solid #3b82f6; color: #93c5fd; border-radius: 6px; padding: 5px 12px; font: 12px system-ui; cursor: pointer; display: none; }+ .raw-apply.show { display: inline-block; }+ .raw-apply:hover { background: #1d4ed8; color: #fff; }++ .actions-bar { position: absolute; bottom: 0; left: 0; right: 0; padding: 10px 18px; background: #0f1216; border-top: 1px solid #1f2937; display: flex; gap: 6px; }+ .btn { background: #3b82f6; color: #fff; border: 0; border-radius: 7px; padding: 9px 12px; font: 600 12px system-ui; cursor: pointer; }+ .btn:hover { filter: brightness(1.1); }+ .btn:disabled { opacity: .4; cursor: not-allowed; filter: none; }+ .btn.secondary { background: transparent; border: 1px solid #1f2937; color: #e5e7eb; }+ .btn.success { background: #22c55e; }+ .btn-icon { font-size: 13px; }++ .ipfs-result { background: #0a2818; border: 1px solid #166534; border-radius: 6px; padding: 8px 10px; font: 11px ui-monospace, monospace; color: #4ade80; word-break: break-all; margin-top: 8px; display: none; }+ .ipfs-result.show { display: block; }+ .ipfs-copy { display: inline-block; margin-left: 8px; background: none; border: 1px solid #166534; color: #4ade80; border-radius: 4px; padding: 1px 7px; font: 10px system-ui; cursor: pointer; }+ .ipfs-copy:hover { background: rgba(34,197,94,.1); }+`;++// ─── Main export ──────────────────────────────────────────────────────────────++export function mountManifestBuilder(rootEl, options = {}) {+ let state = defaultState();+ try {+ const saved = localStorage.getItem(DRAFT_KEY);+ if (saved) {+ const parsed = JSON.parse(saved);+ // glbFile can't be serialized; omit it+ delete parsed.glbFile;+ Object.assign(state, parsed);+ }+ } catch {}++ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ rootEl.appendChild(host);++ let glbBlobUrl = null;+ let allSkills = [];+ let validReport = null;+ let ipfsCid = null;+ let _draftTimer = null;+ let _prevTimer = null;++ shadow.innerHTML = `+ <style>${STYLE}</style>+ <div class="root">+ <div class="preview-col">+ <div class="preview-header">+ <span>Live Preview</span>+ <span id="prev-label" style="color:#4b5563;font-weight:400">—</span>+ </div>+ <div class="preview-body">+ <div class="preview-empty" id="prev-empty">+ <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#374151" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>+ <p>Drop a GLB in Body to preview</p>+ </div>+ <div class="preview-agent-wrap" id="prev-wrap" style="display:none">+ <agent-3d eager kiosk id="prev-agent"></agent-3d>+ </div>+ </div>+ </div>+ <aside class="panel">+ <div class="panel-header">+ <h2>Manifest Builder</h2>+ <span class="v2-badge">v2</span>+ </div>+ <div class="tab-bar">+ <button class="tab-btn" aria-selected="true" data-tab="form">Form</button>+ <button class="tab-btn" aria-selected="false" data-tab="raw">Raw JSON</button>+ </div>+ <div class="tab-panel active" data-panel="form">+ <div class="form-scroll" id="form-scroll"></div>+ </div>+ <div class="tab-panel" data-panel="raw">+ <div class="raw-scroll">+ <textarea class="raw-textarea" id="raw-ta" spellcheck="false"></textarea>+ <div class="raw-error" id="raw-err"></div>+ <button class="raw-apply" id="raw-apply">Apply to form ↑</button>+ </div>+ </div>+ <div class="actions-bar">+ <button class="btn secondary" id="btn-zip" title="Download ZIP">ZIP</button>+ <button class="btn secondary" id="btn-ipfs" title="Pin to IPFS">IPFS</button>+ <button class="btn" id="btn-chain">Register →</button>+ </div>+ </aside>+ </div>+ `;++ const $ = (s) => shadow.querySelector(s);++ // Build form once and bind events+ buildForm();++ // Tab switching+ shadow.querySelectorAll('.tab-btn').forEach((btn) => {+ btn.addEventListener('click', () => {+ const tab = btn.dataset.tab;+ shadow+ .querySelectorAll('.tab-btn')+ .forEach((b) => b.setAttribute('aria-selected', String(b.dataset.tab === tab)));+ shadow+ .querySelectorAll('.tab-panel')+ .forEach((p) => p.classList.toggle('active', p.dataset.panel === tab));+ if (tab === 'raw') syncRawJson();+ });+ });++ // Raw JSON tab+ const rawTa = $('#raw-ta');+ const rawErr = $('#raw-err');+ const rawApply = $('#raw-apply');++ rawTa.addEventListener('input', () => {+ rawErr.textContent = '';+ rawApply.classList.remove('show');+ try {+ JSON.parse(rawTa.value); // just validate syntax first+ rawApply.classList.add('show');+ } catch (e) {+ rawErr.textContent = 'JSON error: ' + e.message;+ }+ });++ rawApply.addEventListener('click', () => {+ try {+ const parsed = JSON.parse(rawTa.value);+ hydrateFromManifest(parsed);+ hydrateForm();+ scheduleDraft();+ schedulePreview();+ rawErr.textContent = '';+ rawApply.classList.remove('show');+ } catch (e) {+ rawErr.textContent = 'Parse error: ' + e.message;+ }+ });++ // Action buttons+ $('#btn-zip').addEventListener('click', downloadZip);+ $('#btn-ipfs').addEventListener('click', pinIpfs);+ $('#btn-chain').addEventListener('click', () => {+ const hash = ipfsCid ? `register=1&manifest=ipfs://${ipfsCid}` : 'register=1';+ window.location.hash = hash;+ });++ // Fetch skills index+ fetch('/skills-index.json')+ .then((r) => r.json())+ .then((data) => {+ allSkills = data;+ refreshSkillsList();+ })+ .catch(() => {});++ schedulePreview();++ return { state, host };++ // ── Form building ──────────────────────────────────────────────────────────++ function buildForm() {+ const scroll = $('#form-scroll');+ scroll.innerHTML = [+ identityHtml(),+ bodyHtml(),+ brainHtml(),+ voiceHtml(),+ skillsHtml(),+ memoryHtml(),+ instructionsHtml(),+ provenanceHtml(),+ ].join('');+ bindEvents();+ hydrateForm();+ }++ function identityHtml() {+ return `<details open>+ <summary>Identity</summary>+ <div class="section-body">+ <div class="field">+ <label>Name *</label>+ <input id="f-name" type="text" maxlength="100" placeholder="Coach Leo">+ <div class="field-error" id="err-name"></div>+ </div>+ <div class="field">+ <label>Description</label>+ <textarea id="f-desc" rows="3" maxlength="1000" placeholder="What does this agent do?"></textarea>+ </div>+ <div class="field">+ <label>Tags (comma-separated)</label>+ <input id="f-tags" type="text" placeholder="coach, sports, argentina">+ </div>+ <div class="field">+ <label>Image URL</label>+ <input id="f-image" type="text" placeholder="ipfs://... or https://...">+ <div class="field-hint">Leave blank to use GLB thumbnail</div>+ </div>+ </div>+ </details>`;+ }++ function bodyHtml() {+ return `<details open>+ <summary>Body</summary>+ <div class="section-body">+ <div class="field">+ <label>GLB File</label>+ <div class="drop-zone" id="glb-drop" role="button" tabindex="0" aria-label="Drop GLB file">+ <input type="file" id="glb-input" accept=".glb,.gltf">+ <span id="glb-label">Drop .glb / .gltf or click to browse</span>+ </div>+ </div>+ <div class="field">+ <label>Body URI (if already hosted)</label>+ <input id="f-body-uri" type="text" placeholder="ipfs://... or https://...">+ <div class="field-hint">Leave blank when using file drop above</div>+ </div>+ <div class="field-row">+ <div class="field">+ <label>Format</label>+ <select id="f-body-format">+ ${BODY_FORMATS.map((f) => `<option value="${f}">${f}</option>`).join('')}+ </select>+ </div>+ <div class="field">+ <label>Rig</label>+ <select id="f-body-rig">+ ${RIG_TYPES.map((r) => `<option value="${r}">${r}</option>`).join('')}+ </select>+ </div>+ </div>+ <div class="field">+ <label>Bounding Box Height (m)</label>+ <div class="slider-row">+ <input type="range" id="f-body-height" min="0.5" max="3.0" step="0.01" value="1.78">+ <span class="slider-val" id="f-body-height-val">1.78</span>+ </div>+ </div>+ </div>+ </details>`;+ }++ function brainHtml() {+ const modelOpts = (models) =>+ models.map((m) => `<option value="${m.id}">${m.label}</option>`).join('');+ return `<details>+ <summary>Brain</summary>+ <div class="section-body">+ <div class="field">+ <label>Provider</label>+ <select id="f-brain-provider">+ ${BRAIN_PROVIDERS.map((p) => `<option value="${p}">${p}</option>`).join('')}+ </select>+ </div>+ <div class="field" id="brain-model-wrap">+ <label>Model</label>+ <select id="f-brain-model">+ ${modelOpts(ANTHROPIC_MODELS)}+ </select>+ </div>+ <div class="field">+ <label>Temperature</label>+ <div class="slider-row">+ <input type="range" id="f-brain-temp" min="0" max="2" step="0.01" value="0.7">+ <span class="slider-val" id="f-brain-temp-val">0.70</span>+ </div>+ </div>+ <div class="field-row">+ <div class="field">+ <label>Max Tokens</label>+ <input type="number" id="f-brain-maxtokens" min="256" max="32768" step="256" value="4096">+ </div>+ <div class="field">+ <label>Thinking</label>+ <select id="f-brain-thinking">+ ${THINKING_OPTS.map((t) => `<option value="${t}">${t}</option>`).join('')}+ </select>+ </div>+ </div>+ </div>+ </details>`;+ }++ function voiceHtml() {+ return `<details>+ <summary>Voice</summary>+ <div class="section-body">+ <div class="field">+ <label>TTS Provider</label>+ <select id="f-tts-provider">+ ${TTS_PROVIDERS.map((p) => `<option value="${p}">${p}</option>`).join('')}+ </select>+ </div>+ <div id="tts-secondary">+ <div class="field" id="tts-voiceid-wrap" style="display:none">+ <label>Voice ID (ElevenLabs)</label>+ <input id="f-tts-voiceid" type="text" placeholder="21m00Tcm4TlvDq8ikWAM">+ </div>+ <div class="field-row">+ <div class="field">+ <label>Rate</label>+ <div class="slider-row">+ <input type="range" id="f-tts-rate" min="0.5" max="2" step="0.1" value="1.0">+ <span class="slider-val" id="f-tts-rate-val">1.0</span>+ </div>+ </div>+ <div class="field">+ <label>Pitch</label>+ <div class="slider-row">+ <input type="range" id="f-tts-pitch" min="0" max="2" step="0.1" value="1.0">+ <span class="slider-val" id="f-tts-pitch-val">1.0</span>+ </div>+ </div>+ </div>+ </div>+ <div class="field" style="margin-top:10px">+ <label>STT Provider</label>+ <select id="f-stt-provider">+ ${STT_PROVIDERS.map((p) => `<option value="${p}">${p}</option>`).join('')}+ </select>+ </div>+ <div id="stt-secondary">+ <div class="field">+ <label>Language</label>+ <input id="f-stt-lang" type="text" placeholder="en-US">+ </div>+ <div class="field">+ <label style="display:flex;align-items:center;gap:6px">+ <input type="checkbox" id="f-stt-continuous" style="width:auto">+ Continuous listening+ </label>+ </div>+ </div>+ </div>+ </details>`;+ }++ function skillsHtml() {+ return `<details>+ <summary>Skills</summary>+ <div class="section-body">+ <input id="skill-search" type="text" placeholder="Search skills…" style="width:100%;background:#111827;color:#f4f4f5;border:1px solid #1f2937;border-radius:6px;padding:6px 8px;font:13px system-ui;margin-bottom:8px">+ <div id="skill-filters" class="skill-filters"></div>+ <div id="skills-list"></div>+ <div style="font:600 11px system-ui;letter-spacing:.06em;text-transform:uppercase;color:#4b5563;margin:10px 0 4px">Custom skill URI</div>+ <div class="skill-custom-row">+ <input id="f-skill-uri" type="text" placeholder="https://... or ipfs://...">+ <button class="btn" id="btn-skill-add" style="flex-shrink:0;padding:6px 10px;font-size:12px">Add</button>+ </div>+ <div id="custom-skills-list"></div>+ </div>+ </details>`;+ }++ function memoryHtml() {+ return `<details>+ <summary>Memory</summary>+ <div class="section-body">+ <div class="field">+ <label>Mode</label>+ <select id="f-mem-mode">+ ${MEMORY_MODES.map((m) => `<option value="${m}">${m}</option>`).join('')}+ </select>+ </div>+ <div class="field">+ <label>Max Tokens</label>+ <input type="number" id="f-mem-maxtokens" min="256" max="65536" step="256" value="8192">+ </div>+ <details style="border:none;border-top:1px solid #1f2937;margin-top:8px">+ <summary style="font-size:11px;color:#4b5563;padding:8px 0;letter-spacing:.04em">Advanced</summary>+ <div class="field" style="margin-top:4px">+ <label>Timeline retention (days)</label>+ <input type="number" id="f-mem-retention" min="1" max="3650" value="90">+ </div>+ </details>+ </div>+ </details>`;+ }++ function instructionsHtml() {+ return `<details>+ <summary>Instructions</summary>+ <div class="section-body">+ <div class="field">+ <label>System prompt (markdown)</label>+ <textarea id="f-instructions" rows="8" placeholder="You are a helpful agent. When greeted, wave() at the user."></textarea>+ <div class="char-counter" id="instructions-counter">0 chars</div>+ <div class="field-hint">Frontmatter (name/model/temperature) is auto-prepended on export.</div>+ </div>+ <div class="md-preview" id="md-preview"></div>+ </div>+ </details>`;+ }++ function provenanceHtml() {+ return `<details>+ <summary>Provenance</summary>+ <div class="section-body">+ <div id="validator-content">+ <div class="validator-idle">Drop a GLB to run the validator.</div>+ </div>+ </div>+ </details>`;+ }++ // ── Event binding ──────────────────────────────────────────────────────────++ function bindEvents() {+ const on = (id, ev, fn) => {+ const el = $(id);+ if (el) el.addEventListener(ev, fn);+ };++ on('#f-name', 'input', (e) => {+ state.name = e.target.value;+ showFieldError('#err-name', '');+ scheduleDraft();+ schedulePreview();+ });+ on('#f-desc', 'input', (e) => {+ state.description = e.target.value;+ scheduleDraft();+ });+ on('#f-tags', 'input', (e) => {+ state.tags = e.target.value;+ scheduleDraft();+ });+ on('#f-image', 'input', (e) => {+ state.image = e.target.value;+ scheduleDraft();+ });++ // Body drop zone+ const drop = $('#glb-drop');+ const input = $('#glb-input');+ drop.addEventListener('click', () => input.click());+ drop.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') input.click();+ });+ drop.addEventListener('dragover', (e) => {+ e.preventDefault();+ drop.classList.add('drag');+ });+ drop.addEventListener('dragleave', () => drop.classList.remove('drag'));+ drop.addEventListener('drop', (e) => {+ e.preventDefault();+ drop.classList.remove('drag');+ handleGlbFile(e.dataTransfer.files[0]);+ });+ input.addEventListener('change', (e) => handleGlbFile(e.target.files[0]));++ on('#f-body-uri', 'input', (e) => {+ state.glbUri = e.target.value;+ scheduleDraft();+ schedulePreview();+ });+ on('#f-body-format', 'change', (e) => {+ state.bodyFormat = e.target.value;+ scheduleDraft();+ });+ on('#f-body-rig', 'change', (e) => {+ state.rig = e.target.value;+ scheduleDraft();+ });+ on('#f-body-height', 'input', (e) => {+ state.boundingBoxHeight = parseFloat(e.target.value) || 1.78;+ const v = $('#f-body-height-val');+ if (v) v.textContent = state.boundingBoxHeight.toFixed(2);+ scheduleDraft();+ });++ on('#f-brain-provider', 'change', (e) => {+ state.brainProvider = e.target.value;+ refreshModelDropdown();+ scheduleDraft();+ });+ on('#f-brain-model', 'change', (e) => {+ state.brainModel = e.target.value;+ scheduleDraft();+ });+ on('#f-brain-temp', 'input', (e) => {+ state.temperature = parseFloat(e.target.value);+ const v = $('#f-brain-temp-val');+ if (v) v.textContent = state.temperature.toFixed(2);+ scheduleDraft();+ });+ on('#f-brain-maxtokens', 'change', (e) => {+ state.maxTokens = parseInt(e.target.value) || 4096;+ scheduleDraft();+ });+ on('#f-brain-thinking', 'change', (e) => {+ state.thinking = e.target.value;+ scheduleDraft();+ });++ on('#f-tts-provider', 'change', (e) => {+ state.ttsProvider = e.target.value;+ refreshTtsSecondary();+ scheduleDraft();+ });+ on('#f-tts-voiceid', 'input', (e) => {+ state.voiceId = e.target.value;+ scheduleDraft();+ });+ on('#f-tts-rate', 'input', (e) => {+ state.ttsRate = parseFloat(e.target.value);+ const v = $('#f-tts-rate-val');+ if (v) v.textContent = state.ttsRate.toFixed(1);+ scheduleDraft();+ });+ on('#f-tts-pitch', 'input', (e) => {+ state.ttsPitch = parseFloat(e.target.value);+ const v = $('#f-tts-pitch-val');+ if (v) v.textContent = state.ttsPitch.toFixed(1);+ scheduleDraft();+ });++ on('#f-stt-provider', 'change', (e) => {+ state.sttProvider = e.target.value;+ refreshSttSecondary();+ scheduleDraft();+ });+ on('#f-stt-lang', 'input', (e) => {+ state.sttLanguage = e.target.value;+ scheduleDraft();+ });+ on('#f-stt-continuous', 'change', (e) => {+ state.sttContinuous = e.target.checked;+ scheduleDraft();+ });++ on('#f-mem-mode', 'change', (e) => {+ state.memoryMode = e.target.value;+ scheduleDraft();+ });+ on('#f-mem-maxtokens', 'change', (e) => {+ state.memoryMaxTokens = parseInt(e.target.value) || 8192;+ scheduleDraft();+ });+ on('#f-mem-retention', 'change', (e) => {+ state.memoryRetentionDays = parseInt(e.target.value) || 90;+ scheduleDraft();+ });++ on('#f-instructions', 'input', (e) => {+ state.instructions = e.target.value;+ const c = $('#instructions-counter');+ if (c) c.textContent = `${e.target.value.length} chars`;+ refreshMdPreview();+ scheduleDraft();+ });++ on('#skill-search', 'input', (e) => refreshSkillsList(e.target.value));++ on('#btn-skill-add', 'click', () => {+ const el = $('#f-skill-uri');+ const uri = el?.value?.trim();+ if (!uri) return;+ state.customSkills.push({ uri, version: '' });+ el.value = '';+ refreshCustomSkillsList();+ scheduleDraft();+ });+ }++ function hydrateForm() {+ const set = (id, val) => {+ const el = $(id);+ if (el && val != null) el.value = String(val);+ };+ const setChk = (id, val) => {+ const el = $(id);+ if (el) el.checked = !!val;+ };++ set('#f-name', state.name);+ set('#f-desc', state.description);+ set('#f-tags', state.tags);+ set('#f-image', state.image);+ set('#f-body-uri', state.glbUri);+ set('#f-body-format', state.bodyFormat);+ set('#f-body-rig', state.rig);+ set('#f-body-height', state.boundingBoxHeight);+ const hv = $('#f-body-height-val');+ if (hv) hv.textContent = Number(state.boundingBoxHeight).toFixed(2);++ set('#f-brain-provider', state.brainProvider);+ refreshModelDropdown();+ set('#f-brain-model', state.brainModel);+ set('#f-brain-temp', state.temperature);+ const tv = $('#f-brain-temp-val');+ if (tv) tv.textContent = Number(state.temperature).toFixed(2);+ set('#f-brain-maxtokens', state.maxTokens);+ set('#f-brain-thinking', state.thinking);++ set('#f-tts-provider', state.ttsProvider);+ set('#f-tts-voiceid', state.voiceId);+ set('#f-tts-rate', state.ttsRate);+ const rv = $('#f-tts-rate-val');+ if (rv) rv.textContent = Number(state.ttsRate).toFixed(1);+ set('#f-tts-pitch', state.ttsPitch);+ const pv = $('#f-tts-pitch-val');+ if (pv) pv.textContent = Number(state.ttsPitch).toFixed(1);+ refreshTtsSecondary();++ set('#f-stt-provider', state.sttProvider);+ set('#f-stt-lang', state.sttLanguage);+ setChk('#f-stt-continuous', state.sttContinuous);+ refreshSttSecondary();++ set('#f-mem-mode', state.memoryMode);+ set('#f-mem-maxtokens', state.memoryMaxTokens);+ set('#f-mem-retention', state.memoryRetentionDays);++ set('#f-instructions', state.instructions);+ const cnt = $('#instructions-counter');+ if (cnt) cnt.textContent = `${(state.instructions || '').length} chars`;+ refreshMdPreview();+ refreshCustomSkillsList();+ }++ // ── Dynamic section updates ────────────────────────────────────────────────++ function refreshModelDropdown() {+ const sel = $('#f-brain-model');+ const wrap = $('#brain-model-wrap');+ if (!sel) return;+ const provider = state.brainProvider;+ if (provider === 'none' || provider === 'local') {+ if (wrap) wrap.style.display = 'none';+ return;+ }+ if (wrap) wrap.style.display = '';+ const models = provider === 'openai' ? OPENAI_MODELS : ANTHROPIC_MODELS;+ sel.innerHTML = models.map((m) => `<option value="${m.id}">${m.label}</option>`).join('');+ // Keep current value if it's in the new list+ if (models.find((m) => m.id === state.brainModel)) {+ sel.value = state.brainModel;+ } else {+ state.brainModel = models[0].id;+ sel.value = state.brainModel;+ }+ }++ function refreshTtsSecondary() {+ const wrap = $('#tts-voiceid-wrap');+ if (wrap) wrap.style.display = state.ttsProvider === 'elevenlabs' ? '' : 'none';+ }++ function refreshSttSecondary() {+ const sec = $('#stt-secondary');+ if (sec) sec.style.display = state.sttProvider === 'none' ? 'none' : '';+ }++ // Active tag filter (only one at a time keeps the UI simple).+ let activeSkillFilter = null;+ // Memoized tool previews keyed by skill id (lazy-loaded on first expand).+ const _skillPreviews = new Map();++ function _skillTagKind(tag) {+ const t = String(tag || '').toLowerCase();+ if (t === 'solana' || t.includes('pump.fun')) return { chain: 'solana' };+ if (t === 'evm' || t === 'uniswap' || t === 'metamask' || t === 'erc7710') return { chain: 'evm' };+ if (t === 'read-only' || t === 'readonly') return { kind: 'readonly' };+ if (t === 'payments' || t === 'tip' || t === 'usdc') return { kind: 'payments' };+ return {};+ }++ function _collectFilterTags() {+ const seen = new Set();+ for (const s of allSkills) for (const t of s.tags || []) seen.add(String(t).toLowerCase());+ // Surface the curated set first if present, then alphabetical extras.+ const curated = ['solana', 'evm', 'defi', 'payments', 'read-only', 'mcp', 'pump.fun'];+ const ordered = [+ ...curated.filter((t) => seen.has(t)),+ ...[...seen].filter((t) => !curated.includes(t)).sort(),+ ];+ return ordered;+ }++ function refreshSkillFilters() {+ const wrap = $('#skill-filters');+ if (!wrap) return;+ const tags = _collectFilterTags();+ if (tags.length === 0) { wrap.innerHTML = ''; return; }+ wrap.innerHTML = ['all', ...tags]+ .map((t) => {+ const active = (t === 'all' && !activeSkillFilter) || t === activeSkillFilter;+ return `<button class="skill-chip${active ? ' active' : ''}" data-tag="${esc(t)}">${esc(t)}</button>`;+ })+ .join('');+ wrap.querySelectorAll('.skill-chip').forEach((btn) =>+ btn.addEventListener('click', () => {+ const tag = btn.dataset.tag;+ activeSkillFilter = tag === 'all' ? null : tag;+ refreshSkillFilters();+ const q = $('#skill-search')?.value || '';+ refreshSkillsList(q);+ }),+ );+ }++ async function _loadSkillPreview(sk) {+ if (_skillPreviews.has(sk.id)) return _skillPreviews.get(sk.id);+ // Resolve relative bundle URIs against the site origin.+ const base = sk.uri.endsWith('/') ? sk.uri : `${sk.uri}/`;+ try {+ const res = await fetch(`${base}tools.json`);+ if (!res.ok) throw new Error(String(res.status));+ const json = await res.json();+ const preview = { tools: (json.tools || []).map((t) => t.name).filter(Boolean) };+ _skillPreviews.set(sk.id, preview);+ return preview;+ } catch {+ const preview = { tools: [], error: true };+ _skillPreviews.set(sk.id, preview);+ return preview;+ }+ }++ function refreshSkillsList(query = '') {+ const list = $('#skills-list');+ if (!list) return;+ refreshSkillFilters();+ const q = query.toLowerCase();+ let filtered = q+ ? allSkills.filter(+ (s) =>+ s.name.toLowerCase().includes(q) ||+ s.description.toLowerCase().includes(q) ||+ (s.tags || []).some((t) => t.toLowerCase().includes(q)),+ )+ : allSkills.slice();+ if (activeSkillFilter) {+ filtered = filtered.filter((s) =>+ (s.tags || []).map((t) => t.toLowerCase()).includes(activeSkillFilter),+ );+ }+ if (filtered.length === 0) {+ list.innerHTML = `<div class="skill-empty">No skills match this filter.</div>`;+ return;+ }+ list.innerHTML = '';+ for (const sk of filtered) {+ const installed = !!state.installedSkills[sk.id];+ const tags = sk.tags || [];+ const tagsHtml = tags+ .map((t) => {+ const kind = _skillTagKind(t);+ const attrs = Object.entries(kind).map(([k, v]) => ` data-${k}="${esc(v)}"`).join('');+ return `<span class="skill-tag"${attrs}>${esc(t)}</span>`;+ })+ .join('');+ const item = document.createElement('div');+ item.className = `skill-item${installed ? ' installed' : ''}`;+ item.innerHTML = `+ <div class="skill-item-info">+ <div class="skill-item-name">${esc(sk.name)} <span style="color:#4b5563;font-weight:400;font-size:10px">v${esc(sk.version)}</span></div>+ <div class="skill-item-desc">${esc(sk.description)}</div>+ ${tagsHtml ? `<div class="skill-tags">${tagsHtml}</div>` : ''}+ <div class="skill-tools-preview" data-preview-for="${esc(sk.id)}"></div>+ </div>+ <div class="skill-actions">+ <button class="skill-toggle ${installed ? 'on' : ''}" data-skill-id="${esc(sk.id)}">${installed ? 'Installed' : 'Install'}</button>+ <button class="skill-preview-btn" data-preview-toggle="${esc(sk.id)}">What can it do?</button>+ </div>+ `;+ item.querySelector('.skill-toggle').addEventListener('click', () => {+ if (state.installedSkills[sk.id]) {+ delete state.installedSkills[sk.id];+ } else {+ state.installedSkills[sk.id] = { version: sk.version };+ }+ refreshSkillsList(query);+ scheduleDraft();+ });+ const previewEl = item.querySelector(`[data-preview-for="${sk.id}"]`);+ item.querySelector('[data-preview-toggle]').addEventListener('click', async () => {+ if (previewEl.classList.contains('open')) {+ previewEl.classList.remove('open');+ return;+ }+ if (!previewEl.dataset.loaded) {+ previewEl.innerHTML = `<div class="example">Loading…</div>`;+ const preview = await _loadSkillPreview(sk);+ if (preview.error) {+ previewEl.innerHTML = `<div class="example">Tool list unavailable for this bundle.</div>`;+ } else if (preview.tools.length === 0) {+ previewEl.innerHTML = `<div class="example">This skill exposes UI actions, not LLM tools.</div>`;+ } else {+ const example = _exampleForSkill(sk);+ previewEl.innerHTML = `+ <h5>Tools (${preview.tools.length})</h5>+ <ul>${preview.tools.map((t) => `<li>${esc(t)}</li>`).join('')}</ul>+ ${example ? `<div class="example">Try: <em>${esc(example)}</em></div>` : ''}+ `;+ }+ previewEl.dataset.loaded = '1';+ }+ previewEl.classList.add('open');+ });+ list.appendChild(item);+ }+ }++ // Curated example prompts keyed by skill id. Falls back to nothing.+ function _exampleForSkill(sk) {+ const examples = {+ 'pump-fun': "what's the king of the hill on pump.fun right now?",+ wave: 'wave at me!',+ dance: 'dance for me',+ 'explain-gltf': "tell me about this model's animations",+ dca: 'set up a weekly $50 USDC → WETH DCA',+ };+ return examples[sk.id] || '';+ }++ function refreshCustomSkillsList() {+ const list = $('#custom-skills-list');+ if (!list) return;+ list.innerHTML = '';+ state.customSkills.forEach((sk, i) => {+ const row = document.createElement('div');+ row.className = 'skill-item';+ row.style.marginTop = '4px';+ row.innerHTML = `+ <div class="skill-item-info">+ <div class="skill-item-name" style="font-size:11px;word-break:break-all">${esc(sk.uri)}</div>+ </div>+ <button class="skill-toggle" style="color:#f87171;border-color:#7f1d1d" data-i="${i}">Remove</button>+ `;+ row.querySelector('button').addEventListener('click', () => {+ state.customSkills.splice(i, 1);+ refreshCustomSkillsList();+ scheduleDraft();+ });+ list.appendChild(row);+ });+ }++ function refreshMdPreview() {+ const el = $('#md-preview');+ if (el) el.innerHTML = renderMarkdown(state.instructions || '');+ }++ function showFieldError(id, msg) {+ const el = $(id);+ if (!el) return;+ el.textContent = msg;+ el.classList.toggle('show', !!msg);+ }++ // ── GLB handling ───────────────────────────────────────────────────────────++ function handleGlbFile(file) {+ if (!file) return;+ if (!/\.(glb|gltf)$/i.test(file.name)) {+ alert('Must be a .glb or .gltf file');+ return;+ }+ state.glbFile = file;+ if (glbBlobUrl) URL.revokeObjectURL(glbBlobUrl);+ glbBlobUrl = URL.createObjectURL(file);++ const lbl = $('#glb-label');+ const drop = $('#glb-drop');+ if (lbl) lbl.textContent = `${file.name} (${(file.size / 1024).toFixed(1)} KB)`;+ if (drop) drop.classList.add('filled');++ schedulePreview();+ runValidator(file);+ }++ async function runValidator(file) {+ const vc = $('#validator-content');+ if (!vc) return;+ vc.innerHTML = `<div class="validator-idle">Running validator…</div>`;+ try {+ const { validateBytes } = await import('gltf-validator');+ const bytes = new Uint8Array(await file.arrayBuffer());+ const result = await validateBytes(bytes);+ validReport = result;+ const { numErrors: ne, numWarnings: nw } = result.issues;+ const errBadge =+ ne > 0+ ? `<span class="badge badge-err">${ne} error${ne !== 1 ? 's' : ''}</span>`+ : '';+ const warnBadge =+ nw > 0+ ? `<span class="badge badge-warn">${nw} warning${nw !== 1 ? 's' : ''}</span>`+ : '';+ const okBadge = ne === 0 && nw === 0 ? `<span class="badge badge-ok">Clean</span>` : '';+ vc.innerHTML = `+ <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">+ ${errBadge}${warnBadge}${okBadge}+ <button class="validator-toggle" id="val-toggle">Details ▾</button>+ </div>+ <div class="validator-detail" id="val-detail">${buildValidatorDetail(result)}</div>+ `;+ vc.querySelector('#val-toggle').addEventListener('click', () => {+ const d = vc.querySelector('#val-detail');+ d.classList.toggle('open');+ });+ } catch (e) {+ vc.innerHTML = `<div class="validator-idle">Validator unavailable: ${esc(e.message)}</div>`;+ }+ }++ function buildValidatorDetail(result) {+ const msgs = result.issues.messages.slice(0, 50);+ if (msgs.length === 0) return 'No issues found.';+ return msgs+ .map((m) => `[${m.severity === 0 ? 'ERR' : 'WARN'}] ${esc(m.message)}`)+ .join('\n');+ }++ // ── Preview ────────────────────────────────────────────────────────────────++ function schedulePreview() {+ clearTimeout(_prevTimer);+ _prevTimer = setTimeout(updatePreview, 500);+ }++ function updatePreview() {+ const wrap = $('#prev-wrap');+ const empty = $('#prev-empty');+ const label = $('#prev-label');+ const agent = $('#prev-agent');+ if (!wrap || !empty || !agent) return;++ const src = glbBlobUrl || state.glbUri;+ if (!src) {+ wrap.style.display = 'none';+ empty.style.display = '';+ return;+ }+ wrap.style.display = '';+ empty.style.display = 'none';+ if (label) label.textContent = state.name || 'Preview';+ agent.setAttribute('src', src);+ }++ // ── Manifest builder ───────────────────────────────────────────────────────++ function buildManifest(forExport = false) {+ const tags = state.tags+ ? state.tags+ .split(',')+ .map((t) => t.trim())+ .filter(Boolean)+ : undefined;+ const bodyUri = forExport+ ? state.glbFile+ ? 'body.glb'+ : state.glbUri || 'body.glb'+ : glbBlobUrl || state.glbUri || 'body.glb';++ const m = {+ $schema: 'https://3d-agent.io/schemas/manifest/0.1.json',+ spec: 'agent-manifest/0.1',+ name: state.name || 'Unnamed Agent',+ };+ if (state.description) m.description = state.description;+ if (state.image) m.image = state.image;+ if (tags?.length) m.tags = tags;++ m.body = {+ uri: bodyUri,+ format: state.bodyFormat,+ rig: state.rig,+ boundingBoxHeight: state.boundingBoxHeight,+ };++ if (state.brainProvider !== 'none') {+ m.brain = {+ provider: state.brainProvider,+ model: state.brainModel,+ instructions: 'instructions.md',+ temperature: state.temperature,+ maxTokens: state.maxTokens,+ thinking: state.thinking,+ };+ }++ const tts = { provider: state.ttsProvider };+ if (state.ttsProvider === 'elevenlabs' && state.voiceId) tts.voiceId = state.voiceId;+ if (state.ttsRate !== 1.0) tts.rate = state.ttsRate;+ if (state.ttsPitch !== 1.0) tts.pitch = state.ttsPitch;+ const stt = { provider: state.sttProvider, language: state.sttLanguage };+ if (state.sttContinuous) stt.continuous = true;+ m.voice = { tts, stt };++ const skills = [+ ...Object.entries(state.installedSkills)+ .map(([id, cfg]) => {+ const sk = allSkills.find((s) => s.id === id);+ if (!sk) return null;+ return { uri: sk.uri, ...(cfg.version ? { version: cfg.version } : {}) };+ })+ .filter(Boolean),+ ...state.customSkills,+ ];+ if (skills.length) m.skills = skills;++ if (state.memoryMode !== 'none') {+ m.memory = {+ mode: state.memoryMode,+ index: 'memory/MEMORY.md',+ maxTokens: state.memoryMaxTokens,+ };+ }++ m.version = state.version || '0.1.0';+ m.created = new Date().toISOString();+ return m;+ }++ function validateManifest() {+ const m = buildManifest();+ const result = ManifestSchema.safeParse(m);+ if (!result.success) {+ const errors = result.error.errors.map((e) => `${e.path.join('.')}: ${e.message}`);+ // Show first error on the relevant field+ const first = result.error.errors[0];+ if (first.path[0] === 'name') showFieldError('#err-name', first.message);+ return { valid: false, errors };+ }+ showFieldError('#err-name', '');+ return { valid: true, errors: [] };+ }++ function hydrateFromManifest(m) {+ if (typeof m.name === 'string') state.name = m.name;+ if (typeof m.description === 'string') state.description = m.description;+ if (Array.isArray(m.tags)) state.tags = m.tags.join(', ');+ if (typeof m.image === 'string') state.image = m.image;+ if (m.body) {+ if (!glbBlobUrl && m.body.uri) state.glbUri = m.body.uri;+ if (m.body.format) state.bodyFormat = m.body.format;+ if (m.body.rig) state.rig = m.body.rig;+ if (m.body.boundingBoxHeight != null)+ state.boundingBoxHeight = m.body.boundingBoxHeight;+ }+ if (m.brain) {+ if (m.brain.provider) state.brainProvider = m.brain.provider;+ if (m.brain.model) state.brainModel = m.brain.model;+ if (typeof m.brain.temperature === 'number') state.temperature = m.brain.temperature;+ if (typeof m.brain.maxTokens === 'number') state.maxTokens = m.brain.maxTokens;+ if (m.brain.thinking) state.thinking = m.brain.thinking;+ }+ if (m.voice?.tts) {+ if (m.voice.tts.provider) state.ttsProvider = m.voice.tts.provider;+ if (m.voice.tts.voiceId) state.voiceId = m.voice.tts.voiceId;+ if (typeof m.voice.tts.rate === 'number') state.ttsRate = m.voice.tts.rate;+ if (typeof m.voice.tts.pitch === 'number') state.ttsPitch = m.voice.tts.pitch;+ }+ if (m.voice?.stt) {+ if (m.voice.stt.provider) state.sttProvider = m.voice.stt.provider;+ if (m.voice.stt.language) state.sttLanguage = m.voice.stt.language;+ if (typeof m.voice.stt.continuous === 'boolean')+ state.sttContinuous = m.voice.stt.continuous;+ }+ if (m.memory) {+ if (m.memory.mode) state.memoryMode = m.memory.mode;+ if (m.memory.maxTokens) state.memoryMaxTokens = m.memory.maxTokens;+ }+ if (typeof m.version === 'string') state.version = m.version;+ }++ // ── Draft save ─────────────────────────────────────────────────────────────++ function scheduleDraft() {+ clearTimeout(_draftTimer);+ _draftTimer = setTimeout(saveDraft, 800);+ }++ function saveDraft() {+ const toSave = { ...state, glbFile: null };+ try {+ localStorage.setItem(DRAFT_KEY, JSON.stringify(toSave));+ } catch {}+ }++ // ── Raw JSON sync ──────────────────────────────────────────────────────────++ function syncRawJson() {+ rawTa.value = JSON.stringify(buildManifest(false), null, 2);+ rawErr.textContent = '';+ rawApply.classList.remove('show');+ }++ // ── ZIP export ─────────────────────────────────────────────────────────────++ async function downloadZip() {+ const { valid, errors } = validateManifest();+ if (!valid) {+ alert('Validation errors:\n' + errors.join('\n'));+ return;+ }+ const btn = $('#btn-zip');+ btn.disabled = true;+ btn.textContent = '…';+ try {+ const manifest = buildManifest(true);+ const enc = new TextEncoder();+ const files = [+ { name: 'manifest.json', data: enc.encode(JSON.stringify(manifest, null, 2)) },+ { name: 'instructions.md', data: enc.encode(buildInstructionsMd()) },+ {+ name: 'memory/MEMORY.md',+ data: enc.encode('# Memory\n\n<!-- Auto-generated memory seed -->\n'),+ },+ ];+ if (state.glbFile) {+ files.push({+ name: 'body.glb',+ data: new Uint8Array(await state.glbFile.arrayBuffer()),+ });+ }+ const zip = buildZip(files);+ const blob = new Blob([zip], { type: 'application/zip' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `${(state.name || 'agent').toLowerCase().replace(/\s+/g, '-')}-manifest.zip`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ setTimeout(() => URL.revokeObjectURL(url), 5000);+ } finally {+ btn.disabled = false;+ btn.textContent = 'ZIP';+ }+ }++ function buildInstructionsMd() {+ const lines = [+ '---',+ state.name ? `name: ${state.name}` : null,+ state.brainModel ? `model: ${state.brainModel}` : null,+ `temperature: ${state.temperature}`,+ '---',+ '',+ state.instructions || '',+ ].filter((l) => l !== null);+ return lines.join('\n');+ }++ // ── IPFS pinning ───────────────────────────────────────────────────────────++ async function pinIpfs() {+ const btn = $('#btn-ipfs');+ btn.disabled = true;+ btn.textContent = 'Pinning…';+ try {+ const pinner = window.__agent3dPinner;+ if (!pinner) throw new Error('No IPFS pinner (window.__agent3dPinner not configured)');++ const manifest = buildManifest(true);+ const jsonBlob = new Blob([JSON.stringify(manifest, null, 2)], {+ type: 'application/json',+ });+ const cid = await pinner.pin(jsonBlob, 'manifest.json');+ ipfsCid = cid;++ // Show result in preview area+ $('#prev-label').textContent = `ipfs://${cid.slice(0, 12)}…`;+ btn.textContent = 'Pinned ✓';+ btn.classList.add('success');++ // Copy-to-clipboard prompt below Raw JSON tab+ const rawScroll = shadow.querySelector('.raw-scroll');+ if (rawScroll) {+ let existing = rawScroll.querySelector('.ipfs-result');+ if (!existing) {+ existing = document.createElement('div');+ existing.className = 'ipfs-result';+ rawScroll.appendChild(existing);+ }+ existing.classList.add('show');+ existing.innerHTML = `ipfs://${esc(cid)} <button class="ipfs-copy" id="ipfs-copy-btn">copy</button>`;+ existing.querySelector('#ipfs-copy-btn').addEventListener('click', async () => {+ await navigator.clipboard.writeText(`ipfs://${cid}`).catch(() => {});+ existing.querySelector('#ipfs-copy-btn').textContent = 'copied';+ });+ }+ } catch (e) {+ alert('Pin failed: ' + e.message);+ btn.textContent = 'IPFS';+ } finally {+ btn.disabled = false;+ }+ }+}++// ─── Markdown renderer (no deps) ─────────────────────────────────────────────++function renderMarkdown(src) {+ if (!src) return '';+ // Strip frontmatter+ const fmStripped = src.replace(/^---[\s\S]*?---\n?/, '');+ const lines = fmStripped.split('\n');+ let html = '';+ let inPre = false;+ for (let i = 0; i < lines.length; i++) {+ let l = lines[i];+ if (l.startsWith('```')) {+ inPre = !inPre;+ html += inPre ? '<pre>' : '</pre>';+ continue;+ }+ if (inPre) {+ html += esc(l) + '\n';+ continue;+ }+ if (/^### /.test(l)) {+ html += `<h3>${inlineHtml(l.slice(4))}</h3>`;+ continue;+ }+ if (/^## /.test(l)) {+ html += `<h2>${inlineHtml(l.slice(3))}</h2>`;+ continue;+ }+ if (/^# /.test(l)) {+ html += `<h1>${inlineHtml(l.slice(2))}</h1>`;+ continue;+ }+ if (/^> /.test(l)) {+ html += `<blockquote>${inlineHtml(l.slice(2))}</blockquote>`;+ continue;+ }+ if (l.trim() === '') {+ html += '<br>';+ continue;+ }+ html += `<p>${inlineHtml(l)}</p>`;+ }+ return html;+}++function inlineHtml(s) {+ return esc(s)+ .replace(/`([^`]+)`/g, '<code>$1</code>')+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')+ .replace(/\*([^*]+)\*/g, '<em>$1</em>');+}++// ─── Minimal store-only ZIP encoder ──────────────────────────────────────────++function buildZip(files) {+ const tbl = makeCrcTable();+ const enc = new TextEncoder();++ const localParts = [];+ const centralParts = [];+ let offset = 0;++ for (const { name, data } of files) {+ const nameBytes = enc.encode(name);+ const crc = crc32(tbl, data);+ const local = localHeader(nameBytes, data.length, crc);+ localParts.push({ local, data, nameBytes, crc, offset });+ offset += local.length + data.length;+ }++ for (const f of localParts) {+ centralParts.push(centralHeader(f.nameBytes, f.data.length, f.crc, f.offset));+ }++ const centralSize = centralParts.reduce((s, p) => s + p.length, 0);+ const centralOffset = offset;+ const eocd = endRecord(localParts.length, centralSize, centralOffset);++ const chunks = [...localParts.flatMap((f) => [f.local, f.data]), ...centralParts, eocd];+ const total = chunks.reduce((s, c) => s + c.length, 0);+ const out = new Uint8Array(total);+ let pos = 0;+ for (const c of chunks) {+ out.set(c, pos);+ pos += c.length;+ }+ return out;+}++function localHeader(nameBytes, size, crc) {+ const h = new Uint8Array(30 + nameBytes.length);+ const v = new DataView(h.buffer);+ v.setUint32(0, 0x04034b50, true); // signature+ v.setUint16(4, 20, true); // version needed+ v.setUint16(6, 0, true); // flags+ v.setUint16(8, 0, true); // compression = stored+ v.setUint16(10, 0, true); // mod time+ v.setUint16(12, 0, true); // mod date+ v.setUint32(14, crc, true); // crc-32+ v.setUint32(18, size, true); // compressed size+ v.setUint32(22, size, true); // uncompressed size+ v.setUint16(26, nameBytes.length, true);+ v.setUint16(28, 0, true); // extra length+ h.set(nameBytes, 30);+ return h;+}++function centralHeader(nameBytes, size, crc, localOffset) {+ const h = new Uint8Array(46 + nameBytes.length);+ const v = new DataView(h.buffer);+ v.setUint32(0, 0x02014b50, true);+ v.setUint16(4, 0x031e, true); // version made by+ v.setUint16(6, 20, true); // version needed+ v.setUint16(8, 0, true); // flags+ v.setUint16(10, 0, true); // compression+ v.setUint16(12, 0, true); // mod time+ v.setUint16(14, 0, true); // mod date+ v.setUint32(16, crc, true);+ v.setUint32(20, size, true); // compressed+ v.setUint32(24, size, true); // uncompressed+ v.setUint16(28, nameBytes.length, true);+ v.setUint16(30, 0, true); // extra+ v.setUint16(32, 0, true); // comment+ v.setUint16(34, 0, true); // disk start+ v.setUint16(36, 0, true); // internal attr+ v.setUint32(38, 0, true); // external attr+ v.setUint32(42, localOffset, true); // local header offset+ h.set(nameBytes, 46);+ return h;+}++function endRecord(count, centralSize, centralOffset) {+ const h = new Uint8Array(22);+ const v = new DataView(h.buffer);+ v.setUint32(0, 0x06054b50, true);+ v.setUint16(4, 0, true); // disk number+ v.setUint16(6, 0, true); // disk with central dir+ v.setUint16(8, count, true);+ v.setUint16(10, count, true);+ v.setUint32(12, centralSize, true);+ v.setUint32(16, centralOffset, true);+ v.setUint16(20, 0, true); // comment length+ return h;+}++function makeCrcTable() {+ const t = new Uint32Array(256);+ for (let i = 0; i < 256; i++) {+ let c = i;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ t[i] = c;+ }+ return t;+}++function crc32(tbl, data) {+ let c = 0xffffffff;+ for (let i = 0; i < data.length; i++) c = tbl[(c ^ data[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++// ─── Escape helper ────────────────────────────────────────────────────────────++function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}diff --git a/publish/src/editor/material-editor.js b/publish/src/editor/material-editor.jsnew file mode 100644index 000000000..ec243b941--- /dev/null+++ b/publish/src/editor/material-editor.js@@ -0,0 +1,188 @@+/**+ * MaterialEditor — live PBR editing via dat.gui subfolders.+ *+ * Collects unique MeshStandardMaterial / MeshPhysicalMaterial instances from+ * the loaded content and builds one subfolder per material with controls that+ * mutate the Three.js material directly (for viewport preview) and record+ * the change on the EditorSession (for GLB export).+ */+import { FrontSide, BackSide, DoubleSide } from 'three';+import { traverseMaterials } from '../viewer/internal.js';++const SIDES = { Front: FrontSide, Back: BackSide, Double: DoubleSide };++export class MaterialEditor {+ constructor(viewer, session) {+ this.viewer = viewer;+ this.session = session;+ this.gui = viewer.gui;+ this.folder = null;+ this.subfolders = [];+ this.snapshots = new Map();+ }++ rebuild() {+ this._clear();+ if (!this.viewer.content || !this.gui) return;++ const mats = [];+ traverseMaterials(this.viewer.content, (mat) => {+ if (mat && (mat.isMeshStandardMaterial || mat.isMeshPhysicalMaterial)) {+ mats.push(mat);+ }+ });++ if (mats.length === 0) return;++ this.folder = this.gui.addFolder('Materials');++ mats.forEach((mat, i) => {+ const label = mat.name || `Material ${i + 1}`;+ const sub = this.folder.addFolder(label);+ this._addControls(sub, mat);+ this.subfolders.push(sub);+ });+ }++ _addControls(folder, mat) {+ const snap = {+ color: mat.color.getHex(),+ metalness: mat.metalness,+ roughness: mat.roughness,+ emissive: mat.emissive.getHex(),+ emissiveIntensity: mat.emissiveIntensity ?? 1,+ opacity: mat.opacity,+ transparent: mat.transparent,+ alphaTest: mat.alphaTest,+ wireframe: mat.wireframe,+ flatShading: mat.flatShading,+ envMapIntensity: mat.envMapIntensity ?? 1,+ side: mat.side,+ };+ this.snapshots.set(mat.uuid, snap);++ const proxy = {+ color: '#' + mat.color.getHexString(),+ emissive: '#' + mat.emissive.getHexString(),+ side: Object.keys(SIDES).find((k) => SIDES[k] === mat.side) || 'Front',+ };++ const record = () => {+ this.session.recordMaterialEdit(mat, {+ name: mat.name,+ baseColor: [mat.color.r, mat.color.g, mat.color.b],+ metalness: mat.metalness,+ roughness: mat.roughness,+ emissive: [mat.emissive.r, mat.emissive.g, mat.emissive.b],+ opacity: mat.opacity,+ alphaMode: mat.transparent ? 'BLEND' : mat.alphaTest > 0 ? 'MASK' : 'OPAQUE',+ alphaCutoff: mat.alphaTest,+ doubleSided: mat.side === DoubleSide,+ });+ mat.needsUpdate = true;+ this.viewer.invalidate();+ };++ folder+ .addColor(proxy, 'color')+ .name('base color')+ .onChange((v) => {+ mat.color.set(v);+ record();+ });+ folder.add(mat, 'metalness', 0, 1, 0.01).onChange(record);+ folder.add(mat, 'roughness', 0, 1, 0.01).onChange(record);+ folder.addColor(proxy, 'emissive').onChange((v) => {+ mat.emissive.set(v);+ record();+ });+ folder+ .add(mat, 'emissiveIntensity', 0, 4, 0.01)+ .name('emissive int')+ .onChange(() => {+ mat.needsUpdate = true;+ this.viewer.invalidate();+ });+ folder.add(mat, 'opacity', 0, 1, 0.01).onChange(() => {+ mat.transparent = mat.opacity < 1;+ record();+ });+ folder.add(mat, 'transparent').onChange(record);+ folder.add(mat, 'alphaTest', 0, 1, 0.01).name('alpha test').onChange(record);+ folder.add(mat, 'wireframe').onChange(() => {+ mat.needsUpdate = true;+ this.viewer.invalidate();+ });+ folder+ .add(mat, 'flatShading')+ .name('flat shading')+ .onChange(() => {+ mat.needsUpdate = true;+ this.viewer.invalidate();+ });+ if (mat.envMapIntensity !== undefined) {+ folder+ .add(mat, 'envMapIntensity', 0, 4, 0.01)+ .name('env map int')+ .onChange(() => {+ this.viewer.invalidate();+ });+ }+ folder.add(proxy, 'side', Object.keys(SIDES)).onChange((v) => {+ mat.side = SIDES[v];+ record();+ });++ folder+ .add(+ {+ reset: () => this._reset(folder, mat, proxy),+ },+ 'reset',+ )+ .name('↺ reset');+ }++ _reset(folder, mat, proxy) {+ const snap = this.snapshots.get(mat.uuid);+ if (!snap) return;+ mat.color.setHex(snap.color);+ mat.emissive.setHex(snap.emissive);+ mat.metalness = snap.metalness;+ mat.roughness = snap.roughness;+ mat.emissiveIntensity = snap.emissiveIntensity;+ mat.opacity = snap.opacity;+ mat.transparent = snap.transparent;+ mat.alphaTest = snap.alphaTest;+ mat.wireframe = snap.wireframe;+ mat.flatShading = snap.flatShading;+ if (mat.envMapIntensity !== undefined) mat.envMapIntensity = snap.envMapIntensity;+ mat.side = snap.side;+ proxy.color = '#' + mat.color.getHexString();+ proxy.emissive = '#' + mat.emissive.getHexString();+ proxy.side = Object.keys(SIDES).find((k) => SIDES[k] === mat.side) || 'Front';++ this.session.clearMaterialEdit(mat);+ mat.needsUpdate = true;+ this.viewer.invalidate();++ for (const ctrl of folder.__controllers) {+ if (ctrl.updateDisplay) ctrl.updateDisplay();+ }+ }++ _clear() {+ if (this.folder && this.gui) {+ try {+ this.gui.removeFolder(this.folder);+ } catch (e) {}+ }+ this.folder = null;+ this.subfolders = [];+ this.snapshots.clear();+ }++ dispose() {+ this._clear();+ }+}diff --git a/publish/src/editor/publish-modal.js b/publish/src/editor/publish-modal.jsnew file mode 100644index 000000000..2af28d240--- /dev/null+++ b/publish/src/editor/publish-modal.js@@ -0,0 +1,345 @@+/**+ * PublishModal — post-publish share UI.+ *+ * DOM mirrors AvatarCreator for visual consistency but uses its own+ * `.publish-*` CSS namespace to avoid collisions. The modal renders one of+ * three states into `.publish-body`: "working" (progress), "result"+ * (snippets), or "error" / "auth-required".+ */++import { stashSession } from './edit-persistence.js';++const STEPS = [+ { key: 'export', label: 'Export' },+ { key: 'upload', label: 'Upload' },+ { key: 'register', label: 'Register' },+ { key: 'widget', label: 'Widget' },+];++const STEP_ORDER = STEPS.map((s) => s.key);++export class PublishModal {+ constructor(containerEl, { session = null } = {}) {+ this.container = containerEl || document.body;+ this._session = session;++ this.overlay = null;+ this.modal = null;+ this.body = null;++ this._onKeyDown = null;+ this._onOverlayClick = null;+ this._onTrapFocus = null;+ this._previouslyFocused = null;++ this._stepState = {+ export: 'pending',+ upload: 'pending',+ register: 'pending',+ widget: 'pending',+ };+ }++ open() {+ if (this.overlay) return;+ this._previouslyFocused = document.activeElement;+ this._build();+ this._wireEvents();+ this._showWorking();+ }++ close() {+ if (!this.overlay) return;+ if (this._onKeyDown) document.removeEventListener('keydown', this._onKeyDown);+ this.overlay.remove();+ this.overlay = null;+ this.modal = null;+ this.body = null;+ this._onKeyDown = null;+ this._onOverlayClick = null;+ this._onTrapFocus = null;++ const prev = this._previouslyFocused;+ this._previouslyFocused = null;+ if (prev && typeof prev.focus === 'function' && document.contains(prev)) {+ try {+ prev.focus();+ } catch (_) {}+ }+ }++ onStep = ({ step, pct = 1 }) => {+ const mapped = step === 'presign' ? 'upload' : step;+ if (!STEP_ORDER.includes(mapped)) return;+ const idx = STEP_ORDER.indexOf(mapped);+ for (let i = 0; i < idx; i++) this._stepState[STEP_ORDER[i]] = 'done';+ this._stepState[mapped] = pct >= 1 ? 'done' : 'active';+ if (pct >= 1 && idx + 1 < STEP_ORDER.length) {+ const next = STEP_ORDER[idx + 1];+ if (this._stepState[next] === 'pending') this._stepState[next] = 'active';+ }+ this._renderSteps();+ };++ showResult(urls) {+ if (!this.body) return;+ this._setTitle('Published ✓');+ const rows = [+ { label: 'Share link', value: urls.page, open: true },+ { label: 'Iframe snippet', value: urls.iframe, open: false },+ { label: 'Web component snippet', value: urls.element, open: false },+ ];+ this.body.innerHTML = `+ <div class="publish-result">+ ${rows.map((r, i) => this._renderSnippetHTML(r, i)).join('')}+ <div class="publish-actions">+ <button type="button" class="publish-done-btn">Done</button>+ </div>+ </div>+ `;++ const values = rows.map((r) => r.value);+ this.body.querySelectorAll('.publish-copy-btn').forEach((btn) => {+ btn.addEventListener('click', () =>+ this._copyValue(btn, values[Number(btn.dataset.idx)]),+ );+ });+ this.body.querySelectorAll('.publish-open-btn').forEach((btn) => {+ btn.addEventListener('click', () => {+ const v = values[Number(btn.dataset.idx)];+ if (v) window.open(v, '_blank', 'noopener');+ });+ });+ const done = this.body.querySelector('.publish-done-btn');+ if (done) done.addEventListener('click', () => this.close());++ const firstCopy = this.body.querySelector('.publish-copy-btn');+ if (firstCopy) {+ try {+ firstCopy.focus();+ } catch (_) {}+ }+ }++ showAuthRequired() {+ if (!this.body) return;+ this._setTitle('Sign in to publish');+ this.body.innerHTML = `+ <div class="publish-auth">+ <p class="publish-auth-msg">+ Publishing saves your edited model to your account. Sign in to continue.+ </p>+ <div class="publish-actions">+ <button type="button" class="publish-cancel-btn">Cancel</button>+ <button type="button" class="publish-signin-btn">Sign in</button>+ </div>+ </div>+ `;+ this.body.querySelector('.publish-signin-btn').addEventListener('click', () => {+ this._signInAndReturn().catch((err) => {+ console.warn('[publish-modal] sign-in redirect failed', err);+ window.location.href = `/login?next=${encodeURIComponent(location.href)}`;+ });+ });+ this.body+ .querySelector('.publish-cancel-btn')+ .addEventListener('click', () => this.close());+ const signIn = this.body.querySelector('.publish-signin-btn');+ if (signIn) {+ try {+ signIn.focus();+ } catch (_) {}+ }+ }++ async _signInAndReturn() {+ const nextURL = new URL(location.href);+ if (this._session) {+ const token = await stashSession(this._session);+ nextURL.searchParams.set('resume', token);+ nextURL.searchParams.set('publish', '1');+ }+ window.location.href = `/login?next=${encodeURIComponent(nextURL.toString())}`;+ }++ showError(err) {+ if (!this.body) return;+ this._setTitle('Publish failed');+ const name = (err && err.name) || 'Error';+ const message = (err && err.message) || String(err);+ this.body.innerHTML = `+ <div class="publish-error" role="alert">+ <div class="publish-error-name">${escapeHtml(name)}</div>+ <div class="publish-error-message">${escapeHtml(message)}</div>+ <div class="publish-actions">+ <button type="button" class="publish-cancel-btn">Close</button>+ <button type="button" class="publish-retry-btn">Retry</button>+ </div>+ </div>+ `;+ this.body.querySelector('.publish-retry-btn').addEventListener('click', () => {+ const fn = this._onRetry;+ this.close();+ if (typeof fn === 'function') fn();+ });+ this.body+ .querySelector('.publish-cancel-btn')+ .addEventListener('click', () => this.close());+ const retry = this.body.querySelector('.publish-retry-btn');+ if (retry) {+ try {+ retry.focus();+ } catch (_) {}+ }+ }++ onRetry(fn) {+ this._onRetry = fn;+ }++ _build() {+ this.overlay = document.createElement('div');+ this.overlay.className = 'publish-overlay';+ this.overlay.setAttribute('role', 'dialog');+ this.overlay.setAttribute('aria-modal', 'true');+ this.overlay.setAttribute('aria-labelledby', 'publish-title');+ this.overlay.innerHTML = `+ <div class="publish-modal">+ <div class="publish-header">+ <span class="publish-title" id="publish-title">Publishing…</span>+ <button type="button" class="publish-close" aria-label="Close">×</button>+ </div>+ <div class="publish-body"></div>+ </div>+ `;+ this.container.appendChild(this.overlay);+ this.modal = this.overlay.querySelector('.publish-modal');+ this.body = this.overlay.querySelector('.publish-body');+ }++ _wireEvents() {+ this.overlay.querySelector('.publish-close').addEventListener('click', () => this.close());+ this._onOverlayClick = (e) => {+ if (e.target === this.overlay) this.close();+ };+ this.overlay.addEventListener('click', this._onOverlayClick);++ this._onKeyDown = (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ this.close();+ }+ };+ document.addEventListener('keydown', this._onKeyDown);++ this._onTrapFocus = (e) => {+ if (e.key !== 'Tab') return;+ const focusables = this._focusables();+ if (!focusables.length) return;+ const first = focusables[0];+ const last = focusables[focusables.length - 1];+ if (e.shiftKey && document.activeElement === first) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && document.activeElement === last) {+ e.preventDefault();+ first.focus();+ }+ };+ this.overlay.addEventListener('keydown', this._onTrapFocus);+ }++ _focusables() {+ if (!this.overlay) return [];+ return Array.from(+ this.overlay.querySelectorAll(+ 'button:not([disabled]), [tabindex]:not([tabindex="-1"])',+ ),+ );+ }++ _setTitle(text) {+ const t = this.overlay?.querySelector('.publish-title');+ if (t) t.textContent = text;+ }++ _showWorking() {+ this._setTitle('Publishing…');+ this.body.innerHTML = `+ <div class="publish-steps" aria-live="polite">+ ${STEPS.map(+ (s) => `+ <div class="publish-step publish-step--pending" data-step="${s.key}">+ <span class="publish-step-dot" aria-hidden="true"></span>+ <span class="publish-step-label">${s.label}</span>+ </div>+ `,+ ).join('')}+ </div>+ `;+ this._stepState = {+ export: 'active',+ upload: 'pending',+ register: 'pending',+ widget: 'pending',+ };+ this._renderSteps();+ }++ _renderSteps() {+ if (!this.body) return;+ for (const [key, state] of Object.entries(this._stepState)) {+ const row = this.body.querySelector(`.publish-step[data-step="${key}"]`);+ if (!row) continue;+ row.classList.remove(+ 'publish-step--pending',+ 'publish-step--active',+ 'publish-step--done',+ );+ row.classList.add(`publish-step--${state}`);+ const dot = row.querySelector('.publish-step-dot');+ if (dot) dot.textContent = state === 'done' ? '✓' : '';+ }+ }++ _renderSnippetHTML(row, i) {+ return `+ <div class="publish-snippet">+ <div class="publish-snippet-label">${escapeHtml(row.label)}</div>+ <div class="publish-snippet-row">+ <pre class="publish-snippet-value" tabindex="0">${escapeHtml(row.value)}</pre>+ <div class="publish-snippet-actions">+ <button type="button" class="publish-copy-btn" data-idx="${i}">Copy</button>+ ${row.open ? `<button type="button" class="publish-open-btn" data-idx="${i}">Open</button>` : ''}+ </div>+ </div>+ </div>+ `;+ }++ async _copyValue(btn, value) {+ const prev = btn.textContent;+ try {+ await navigator.clipboard.writeText(value);+ btn.textContent = 'Copied ✓';+ btn.disabled = true;+ } catch (err) {+ console.warn('[publish-modal] clipboard write failed', err);+ btn.textContent = 'Copy failed';+ }+ setTimeout(() => {+ if (!this.overlay || !document.contains(btn)) return;+ btn.textContent = prev;+ btn.disabled = false;+ }, 1200);+ }+}++function escapeHtml(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}diff --git a/publish/src/editor/publish.js b/publish/src/editor/publish.jsnew file mode 100644index 000000000..51594c78d--- /dev/null+++ b/publish/src/editor/publish.js@@ -0,0 +1,222 @@+/**+ * publishEditedGLB(session, opts)+ * -------------------------------+ * Turn an in-progress EditorSession into a live shareable widget:+ * 1. exportEditedGLB(session) → Uint8Array+ * 2. POST /api/avatars/presign → { storage_key, upload_url, headers }+ * 3. PUT upload_url with the bytes → R2+ * 4. POST /api/avatars → { avatar }+ * 5. POST /api/widgets → { widget }+ *+ * Transport-only: no UI, no auth redirects. On 401 any step throws+ * AuthRequiredError so the caller (task 04) can redirect to sign-in.+ */++import { exportEditedGLB } from './glb-export.js';++export const MAX_BYTES = 25 * 1024 * 1024;++// Mirrors public/studio/studio.js TYPE_DEFAULTS.turntable + BRAND_DEFAULTS.+// Kept local because public/studio/* is served verbatim (not bundled).+const TURNTABLE_DEFAULTS = Object.freeze({+ rotationSpeed: 0.5,+ autoRotate: true,+ showControls: true,+ background: '#0a0a0a',+ accent: '#8b5cf6',+});++export class AuthRequiredError extends Error {+ constructor() {+ super('auth required');+ this.name = 'AuthRequiredError';+ }+}++export class SizeTooLargeError extends Error {+ constructor(bytes, limit) {+ super(`${bytes} > ${limit}`);+ this.name = 'SizeTooLargeError';+ this.bytes = bytes;+ this.limit = limit;+ }+}++export class ExportFailedError extends Error {+ constructor(cause) {+ super(`export failed: ${cause?.message || cause}`);+ this.name = 'ExportFailedError';+ this.cause = cause;+ }+}++export class PublishError extends Error {+ constructor(step, status, body) {+ super(`${step} failed: ${status} ${body?.error_description || ''}`.trim());+ this.name = 'PublishError';+ this.step = step;+ this.status = status;+ this.body = body;+ }+}++export async function publishEditedGLB(+ session,+ {+ origin = location.origin,+ widgetType = 'turntable',+ widgetName,+ isPublic = true,+ config = {},+ onStep = () => {},+ } = {},+) {+ const displayName = widgetName || toDisplayName(session?.sourceName);++ // 1. Export+ onStep({ step: 'export', pct: 0 });+ let bytes;+ try {+ bytes = await exportEditedGLB(session);+ } catch (e) {+ throw new ExportFailedError(e);+ }+ if (!bytes || !bytes.byteLength) throw new ExportFailedError(new Error('empty buffer'));+ if (bytes.byteLength > MAX_BYTES) throw new SizeTooLargeError(bytes.byteLength, MAX_BYTES);+ onStep({ step: 'export', pct: 1 });++ // 2. Presign+ const presign = await postJson(+ `${origin}/api/avatars/presign`,+ {+ size_bytes: bytes.byteLength,+ content_type: 'model/gltf-binary',+ },+ 'presign',+ );+ onStep({ step: 'presign', pct: 1 });++ // 3. PUT upload (no credentials — presigned URL carries its own auth).+ await putWithProgress(presign.upload_url, bytes, presign.headers || {}, (pct) =>+ onStep({ step: 'upload', pct }),+ );++ // 4. Register avatar+ const avatarRes = await postJson(+ `${origin}/api/avatars`,+ {+ name: displayName,+ slug: toSlug(session?.sourceName),+ storage_key: presign.storage_key,+ content_type: 'model/gltf-binary',+ size_bytes: bytes.byteLength,+ visibility: isPublic ? 'public' : 'private',+ source: 'upload',+ source_meta: { origin: 'editor-publish' },+ },+ 'register',+ (status, body) => {+ if (status === 413) throw new SizeTooLargeError(bytes.byteLength, MAX_BYTES);+ },+ );+ const avatar = avatarRes.avatar;+ onStep({ step: 'register', pct: 1 });++ // 5. Create widget+ const widgetConfig = { ...TURNTABLE_DEFAULTS, ...config };+ const widgetRes = await postJson(+ `${origin}/api/widgets`,+ {+ type: widgetType,+ name: displayName,+ avatar_id: avatar.id,+ config: widgetConfig,+ is_public: isPublic,+ },+ 'widget',+ );+ const widget = widgetRes.widget;+ onStep({ step: 'widget', pct: 1 });++ const page = `${origin}/w/${widget.id}`;+ const iframe = `<iframe src="${page}" width="600" height="600" style="border:0"></iframe>`;+ const element =+ `<script type="module" src="${origin}/dist-lib/agent-3d.js"></script>\n` ++ `<agent-3d src="${origin}/api/avatars/${avatar.id}" style="width:600px;height:600px"></agent-3d>`;++ return { widget, avatar, urls: { page, iframe, element } };+}++async function postJson(url, body, step, onStatus) {+ let res;+ try {+ res = await fetch(url, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ } catch (e) {+ throw new PublishError(step, 0, { error_description: e?.message || String(e) });+ }+ if (res.status === 401) throw new AuthRequiredError();+ const parsed = await safeJson(res);+ if (onStatus) onStatus(res.status, parsed);+ if (!res.ok) throw new PublishError(step, res.status, parsed);+ return parsed;+}++function putWithProgress(url, bytes, headers, onProgress) {+ return new Promise((resolve, reject) => {+ onProgress(0);+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', url, true);+ for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable) onProgress(Math.max(0, Math.min(1, e.loaded / e.total)));+ };+ xhr.onerror = () =>+ reject(new PublishError('upload', 0, { error_description: 'network error' }));+ xhr.onabort = () => reject(new PublishError('upload', 0, { error_description: 'aborted' }));+ xhr.onload = () => {+ if (xhr.status === 401) return reject(new AuthRequiredError());+ if (xhr.status >= 200 && xhr.status < 300) {+ onProgress(1);+ return resolve();+ }+ reject(+ new PublishError('upload', xhr.status, {+ error_description: xhr.responseText || '',+ }),+ );+ };+ xhr.send(bytes);+ });+}++async function safeJson(res) {+ try {+ return await res.json();+ } catch {+ return null;+ }+}++function toDisplayName(raw) {+ const s = String(raw || 'Model')+ .replace(/\.(glb|gltf)$/i, '')+ .trim();+ return (s || 'Model').slice(0, 120);+}++function toSlug(raw) {+ let base = String(raw || 'model')+ .replace(/\.(glb|gltf)$/i, '')+ .toLowerCase()+ .replace(/[^a-z0-9_-]+/g, '-')+ .replace(/-+/g, '-')+ .replace(/^[-_]+|[-_]+$/g, '');+ if (!base || !/^[a-z0-9]/.test(base)) base = `model${base ? '-' + base : ''}`;+ const suffix = Math.random().toString(36).slice(2, 8);+ return `${base}-${suffix}`.slice(0, 64).replace(/[-_]+$/, '');+}diff --git a/publish/src/editor/regenerate-panel.js b/publish/src/editor/regenerate-panel.jsnew file mode 100644index 000000000..6bd0901ba--- /dev/null+++ b/publish/src/editor/regenerate-panel.js@@ -0,0 +1,284 @@+/**+ * RegeneratePanel — UI for avatar mesh/texture/rig regeneration.+ *+ * Usage:+ * import { mountRegeneratePanel } from './regenerate-panel.js';+ * const container = document.getElementById('regen-container');+ * mountRegeneratePanel(container, {+ * avatarId: 'uuid-...',+ * onResult: (newAvatarId) => { ... }+ * });+ *+ * Do NOT auto-mount. Caller controls where and when the panel appears.+ */++/**+ * Mount the regenerate panel into a DOM container.+ * @param {HTMLElement} container - Target container element+ * @param {Object} options+ * @param {string} options.avatarId - Avatar UUID to regenerate+ * @param {(resultId: string) => void} options.onResult - Callback on successful regen+ * @returns {Object} Control object with methods like .unmount()+ */+export function mountRegeneratePanel(container, { avatarId, onResult }) {+ const panel = new RegeneratePanel(container, { avatarId, onResult });+ panel.render();+ return panel;+}++class RegeneratePanel {+ constructor(container, { avatarId, onResult }) {+ this.container = container;+ this.avatarId = avatarId;+ this.onResult = onResult;+ this.state = {+ mode: 'remesh',+ params: '{}',+ inFlight: false,+ unconfigured: false,+ jobId: null,+ status: null,+ error: null,+ };+ this.pollTimer = null;+ }++ render() {+ this.container.innerHTML = '';+ this.container.style.padding = '16px';+ this.container.style.borderTop = '1px solid #ccc';+ this.container.style.marginTop = '16px';++ const wrapper = document.createElement('div');+ wrapper.innerHTML = `+ <h3 style="margin: 0 0 12px 0; font-size: 14px; font-weight: 600;">+ Regenerate Avatar+ </h3>+ `;+ this.container.appendChild(wrapper);++ // Render unconfigured banner if needed+ if (this.state.unconfigured) {+ this._renderUnconfiguredBanner();+ return;+ }++ // Mode select+ const modeLabel = document.createElement('label');+ modeLabel.style.display = 'block';+ modeLabel.style.marginBottom = '8px';+ modeLabel.style.fontSize = '12px';+ modeLabel.style.fontWeight = '500';+ modeLabel.textContent = 'Mode';+ this.container.appendChild(modeLabel);++ const modeSelect = document.createElement('select');+ modeSelect.value = this.state.mode;+ modeSelect.style.width = '100%';+ modeSelect.style.padding = '6px';+ modeSelect.style.marginBottom = '12px';+ modeSelect.style.borderRadius = '4px';+ modeSelect.style.border = '1px solid #ccc';+ modeSelect.innerHTML = `+ <option value="remesh">Re-mesh (regenerate topology)</option>+ <option value="retex">Re-texture (materials + textures)</option>+ <option value="rerig">Re-rig (skeleton binding)</option>+ <option value="restyle">Re-style (appearance from description)</option>+ `;+ modeSelect.addEventListener('change', (e) => {+ this.state.mode = e.target.value;+ });+ this.container.appendChild(modeSelect);++ // Params textarea+ const paramsLabel = document.createElement('label');+ paramsLabel.style.display = 'block';+ paramsLabel.style.marginBottom = '8px';+ paramsLabel.style.fontSize = '12px';+ paramsLabel.style.fontWeight = '500';+ paramsLabel.textContent = 'Parameters (JSON)';+ this.container.appendChild(paramsLabel);++ const paramsTextarea = document.createElement('textarea');+ paramsTextarea.value = this.state.params;+ paramsTextarea.style.width = '100%';+ paramsTextarea.style.height = '100px';+ paramsTextarea.style.padding = '6px';+ paramsTextarea.style.marginBottom = '12px';+ paramsTextarea.style.borderRadius = '4px';+ paramsTextarea.style.border = '1px solid #ccc';+ paramsTextarea.style.fontFamily = 'monospace';+ paramsTextarea.style.fontSize = '11px';+ paramsTextarea.addEventListener('change', (e) => {+ this.state.params = e.target.value;+ });+ this.container.appendChild(paramsTextarea);++ // Submit button+ const submitBtn = document.createElement('button');+ submitBtn.textContent = 'Start Regeneration';+ submitBtn.style.padding = '8px 16px';+ submitBtn.style.borderRadius = '4px';+ submitBtn.style.border = 'none';+ submitBtn.style.background = '#0066ff';+ submitBtn.style.color = 'white';+ submitBtn.style.cursor = this.state.inFlight ? 'not-allowed' : 'pointer';+ submitBtn.style.opacity = this.state.inFlight ? '0.6' : '1';+ submitBtn.disabled = this.state.inFlight;+ submitBtn.addEventListener('click', () => this._submit());+ this.container.appendChild(submitBtn);++ // Status / error display+ if (this.state.error) {+ const errorDiv = document.createElement('div');+ errorDiv.style.marginTop = '12px';+ errorDiv.style.padding = '8px';+ errorDiv.style.backgroundColor = '#fee';+ errorDiv.style.color = '#c00';+ errorDiv.style.borderRadius = '4px';+ errorDiv.style.fontSize = '12px';+ errorDiv.textContent = this.state.error;+ this.container.appendChild(errorDiv);+ }++ if (this.state.jobId) {+ const statusDiv = document.createElement('div');+ statusDiv.style.marginTop = '12px';+ statusDiv.style.padding = '8px';+ statusDiv.style.backgroundColor = '#eef';+ statusDiv.style.color = '#006';+ statusDiv.style.borderRadius = '4px';+ statusDiv.style.fontSize = '12px';+ statusDiv.innerHTML = `+ <strong>Job:</strong> ${this.state.jobId}<br/>+ <strong>Status:</strong> ${this.state.status || 'pending'}+ `;+ this.container.appendChild(statusDiv);+ }+ }++ _renderUnconfiguredBanner() {+ const banner = document.createElement('div');+ banner.style.padding = '12px';+ banner.style.backgroundColor = '#fef3cd';+ banner.style.border = '1px solid #ffeaa7';+ banner.style.borderRadius = '4px';+ banner.style.fontSize = '13px';+ banner.style.color = '#856404';+ banner.innerHTML = `+ <strong>Avatar regeneration is not yet live.</strong>+ Join the waitlist: <a href="mailto:[email protected]" style="color: #0066ff;">[email protected]</a><br/>+ <small style="display: block; margin-top: 6px;">+ ML backend integration is in progress. We'll notify you when it's ready.+ </small>+ `;+ this.container.appendChild(banner);+ }++ async _submit() {+ if (this.state.inFlight) return;++ // Validate JSON+ let params;+ try {+ params = JSON.parse(this.state.params);+ } catch (e) {+ this.state.error = `Invalid JSON in params: ${e.message}`;+ this.render();+ return;+ }++ this.state.inFlight = true;+ this.state.error = null;+ this.render();++ try {+ const resp = await fetch('/api/avatars/regenerate', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ sourceAvatarId: this.avatarId,+ mode: this.state.mode,+ params,+ }),+ });++ if (!resp.ok) {+ const body = await resp.json();++ // Handle 501 unconfigured case+ if (resp.status === 501 && body.error === 'regen_unconfigured') {+ this.state.unconfigured = true;+ this.state.inFlight = false;+ this.render();+ return;+ }++ throw new Error(body.error_description || `HTTP ${resp.status}`);+ }++ const body = await resp.json();+ this.state.jobId = body.jobId;+ this.state.status = body.status;+ this.state.inFlight = false;+ this.render();++ // Start polling for completion+ this._startPolling();+ } catch (err) {+ this.state.error = err.message;+ this.state.inFlight = false;+ this.render();+ }+ }++ _startPolling() {+ this.pollTimer = setInterval(async () => {+ try {+ const resp = await fetch(+ `/api/avatars/regenerate-status?jobId=${this.state.jobId}`,+ {+ credentials: 'include',+ },+ );++ if (!resp.ok) {+ throw new Error(`HTTP ${resp.status}`);+ }++ const body = await resp.json();+ this.state.status = body.status;++ if (body.error) {+ this.state.error = body.error;+ }++ this.render();++ // Terminal state — stop polling+ if (body.status === 'done' || body.status === 'failed') {+ clearInterval(this.pollTimer);+ this.pollTimer = null;++ if (body.status === 'done' && body.resultAvatarId && this.onResult) {+ this.onResult(body.resultAvatarId);+ }+ }+ } catch (err) {+ this.state.error = err.message;+ this.render();+ clearInterval(this.pollTimer);+ this.pollTimer = null;+ }+ }, 3000);+ }++ unmount() {+ if (this.pollTimer) {+ clearInterval(this.pollTimer);+ this.pollTimer = null;+ }+ this.container.innerHTML = '';+ }+}diff --git a/publish/src/editor/save-back.js b/publish/src/editor/save-back.jsnew file mode 100644index 000000000..87a60e0e7--- /dev/null+++ b/publish/src/editor/save-back.js@@ -0,0 +1,106 @@+import { exportEditedGLB } from './glb-export.js';++const MAX_BYTES = 25 * 1024 * 1024;++export class SaveError extends Error {+ constructor(code, message) {+ super(message);+ this.name = 'SaveError';+ this.code = code;+ }+}++/**+ * Export the current editor session and persist it back to the saved avatar.+ * @param {EditorSession} session+ * @param {{ avatarId: string, onStep?: (s: {step: string, pct: number}) => void }} opts+ * @returns {Promise<{ok: true, avatar: object}>}+ */+export async function saveEditedAvatar(session, { avatarId, onStep = () => {} } = {}) {+ // 1. Export+ onStep({ step: 'export', pct: 0 });+ let bytes;+ try {+ bytes = await exportEditedGLB(session);+ } catch (e) {+ throw new SaveError('server', 'GLB export failed: ' + (e?.message || e));+ }+ if (!bytes?.byteLength) throw new SaveError('server', 'Empty GLB buffer');+ if (bytes.byteLength > MAX_BYTES)+ throw new SaveError('oversize', `GLB too large (${bytes.byteLength} bytes)`);+ onStep({ step: 'export', pct: 1 });++ // 2. Presign+ onStep({ step: 'presign', pct: 0 });+ let presign;+ try {+ const res = await fetch('/api/avatars/presign', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ size_bytes: bytes.byteLength,+ content_type: 'model/gltf-binary',+ }),+ });+ if (res.status === 401) throw new SaveError('auth', 'Not signed in');+ if (!res.ok) {+ const b = await res.json().catch(() => ({}));+ throw new SaveError('server', b?.error_description || `Presign failed (${res.status})`);+ }+ presign = await res.json();+ } catch (e) {+ if (e instanceof SaveError) throw e;+ throw new SaveError('network', e?.message || 'Network error during presign');+ }+ onStep({ step: 'presign', pct: 1 });++ // 3. Upload+ await new Promise((resolve, reject) => {+ onStep({ step: 'upload', pct: 0 });+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', presign.upload_url, true);+ for (const [k, v] of Object.entries(presign.headers || {})) xhr.setRequestHeader(k, v);+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable)+ onStep({ step: 'upload', pct: Math.max(0, Math.min(1, e.loaded / e.total)) });+ };+ xhr.onerror = () => reject(new SaveError('network', 'Upload network error'));+ xhr.onabort = () => reject(new SaveError('network', 'Upload aborted'));+ xhr.onload = () => {+ if (xhr.status === 401) return reject(new SaveError('auth', 'Not signed in'));+ if (xhr.status >= 200 && xhr.status < 300) {+ onStep({ step: 'upload', pct: 1 });+ return resolve();+ }+ reject(new SaveError('server', `Upload failed (${xhr.status})`));+ };+ xhr.send(bytes);+ });++ // 4. PATCH avatar — derive non-signed URL by stripping presign query params+ onStep({ step: 'patch', pct: 0 });+ const parsed = new URL(presign.upload_url);+ const glbUrl = parsed.origin + parsed.pathname;+ let patchRes;+ try {+ const res = await fetch(`/api/avatars/${avatarId}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ glbUrl, storage_key: presign.storage_key }),+ });+ if (res.status === 401) throw new SaveError('auth', 'Not signed in');+ if (!res.ok) {+ const b = await res.json().catch(() => ({}));+ throw new SaveError('server', b?.error_description || `Patch failed (${res.status})`);+ }+ patchRes = await res.json();+ } catch (e) {+ if (e instanceof SaveError) throw e;+ throw new SaveError('network', e?.message || 'Network error during patch');+ }+ onStep({ step: 'patch', pct: 1 });++ return { ok: true, avatar: patchRes.avatar ?? patchRes };+}diff --git a/publish/src/editor/scene-explorer.js b/publish/src/editor/scene-explorer.jsnew file mode 100644index 000000000..73936c6d4--- /dev/null+++ b/publish/src/editor/scene-explorer.js@@ -0,0 +1,471 @@+/**+ * SceneExplorer — side panel with a collapsible scene tree, node inspector,+ * click-to-select raycasting, and a TransformControls gizmo.+ *+ * All structural changes (position/rotation/scale/visibility) are written+ * to the EditorSession so they can be re-applied at GLB export time.+ */+import { Box3, Raycaster, Vector3 } from 'three';+import { TransformControls } from 'three/addons/controls/TransformControls.js';++const ICONS = {+ Mesh: '📦',+ SkinnedMesh: '🧍',+ Group: '🎯',+ Object3D: '▫',+ Bone: '🦴',+ DirectionalLight: '💡',+ PointLight: '💡',+ SpotLight: '💡',+ AmbientLight: '💡',+ HemisphereLight: '💡',+ PerspectiveCamera: '📷',+ OrthographicCamera: '📷',+ Scene: '🌳',+};++function escapeHTML(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++function iconFor(node) {+ return ICONS[node.type] || (node.isMesh ? '📦' : '▫');+}++export class SceneExplorer {+ constructor(viewer, session) {+ this.viewer = viewer;+ this.session = session;+ this.panel = null;+ this.treeEl = null;+ this.inspectorEl = null;+ this.searchEl = null;+ this.selectedNode = null;+ this.transformControls = null;+ this.raycaster = new Raycaster();+ this._onKeyDown = this._onKeyDown.bind(this);+ this._onPointerDown = this._onPointerDown.bind(this);+ this._attached = false;+ }++ attach() {+ if (this._attached) return;+ this._attached = true;+ this._buildPanel();+ this._setupTransformControls();+ this.viewer.renderer.domElement.addEventListener('pointerdown', this._onPointerDown);+ window.addEventListener('keydown', this._onKeyDown);+ }++ detach() {+ if (!this._attached) return;+ this._attached = false;+ if (this.panel) {+ this.panel.remove();+ this.panel = null;+ }+ if (this.transformControls) {+ this.transformControls.detach();+ const helper = this.transformControls.getHelper+ ? this.transformControls.getHelper()+ : this.transformControls;+ this.viewer.scene.remove(helper);+ this.transformControls.dispose?.();+ this.transformControls = null;+ }+ if (this.viewer.renderer?.domElement) {+ this.viewer.renderer.domElement.removeEventListener('pointerdown', this._onPointerDown);+ }+ window.removeEventListener('keydown', this._onKeyDown);+ }++ toggle(show) {+ if (!this.panel) return;+ const willShow = show === undefined ? this.panel.classList.contains('hidden') : show;+ this.panel.classList.toggle('hidden', !willShow);+ }++ rebuild() {+ if (!this.treeEl) return;+ this.selectedNode = null;+ this.transformControls?.detach();+ this.treeEl.innerHTML = '';+ this.inspectorEl.innerHTML =+ '<div class="scene-explorer__empty">Select a node to inspect</div>';++ if (!this.viewer.content) {+ this.treeEl.innerHTML = '<div class="scene-explorer__empty">No model loaded</div>';+ return;+ }+ this.treeEl.appendChild(this._buildNodeElement(this.viewer.content, 0, true));+ }++ _buildPanel() {+ const panel = document.createElement('div');+ panel.className = 'scene-explorer hidden';+ panel.innerHTML = `+ <div class="scene-explorer__header">+ <span class="scene-explorer__title">Scene</span>+ <button class="scene-explorer__close" title="Close [T]">×</button>+ </div>+ <input type="text" class="scene-explorer__search" placeholder="Search nodes…">+ <div class="scene-explorer__hint">W translate · E rotate · R scale · Esc deselect</div>+ <div class="scene-explorer__tree"></div>+ <div class="scene-explorer__inspector"></div>+ `;+ this.viewer.el.appendChild(panel);+ this.panel = panel;+ this.treeEl = panel.querySelector('.scene-explorer__tree');+ this.inspectorEl = panel.querySelector('.scene-explorer__inspector');+ this.searchEl = panel.querySelector('.scene-explorer__search');++ panel.querySelector('.scene-explorer__close').addEventListener('click', () => {+ this.toggle(false);+ });+ this.searchEl.addEventListener('input', () => {+ this._filter(this.searchEl.value);+ });+ }++ _buildNodeElement(node, depth, autoExpand = false) {+ const div = document.createElement('div');+ div.className = 'scene-node';+ div.dataset.uuid = node.uuid;++ const hasChildren = node.children && node.children.length > 0;+ const name = node.name || node.type;+ const label = escapeHTML(name);++ const row = document.createElement('div');+ row.className = 'scene-node__row';+ row.style.paddingLeft = depth * 12 + 'px';+ row.innerHTML = `+ <span class="scene-node__expander">${hasChildren ? '▸' : '·'}</span>+ <span class="scene-node__icon">${iconFor(node)}</span>+ <span class="scene-node__label" title="${label}">${label}</span>+ <button class="scene-node__visibility" title="Toggle visibility">${node.visible ? '●' : '○'}</button>+ `;++ const childrenEl = document.createElement('div');+ childrenEl.className = 'scene-node__children';+ if (autoExpand) childrenEl.classList.add('open');++ const expander = row.querySelector('.scene-node__expander');+ const visBtn = row.querySelector('.scene-node__visibility');++ row.addEventListener('click', (e) => {+ if (e.target === visBtn || e.target === expander) return;+ this.selectNode(node);+ });+ row.addEventListener('dblclick', () => this._frameNode(node));++ if (hasChildren) {+ expander.addEventListener('click', (e) => {+ e.stopPropagation();+ const open = childrenEl.classList.toggle('open');+ expander.textContent = open ? '▾' : '▸';+ });+ if (autoExpand) expander.textContent = '▾';+ }++ visBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ node.visible = !node.visible;+ visBtn.textContent = node.visible ? '●' : '○';+ this.session.recordVisibilityEdit(node, node.visible);+ this.viewer.invalidate();+ });++ div.appendChild(row);+ div.appendChild(childrenEl);++ if (hasChildren) {+ node.children.forEach((child) => {+ childrenEl.appendChild(this._buildNodeElement(child, depth + 1));+ });+ }+ return div;+ }++ selectNode(node) {+ this.selectedNode = node;+ this.treeEl+ .querySelectorAll('.scene-node__row.selected')+ .forEach((r) => r.classList.remove('selected'));+ const target = this.treeEl.querySelector(+ `.scene-node[data-uuid="${node.uuid}"] > .scene-node__row`,+ );+ if (target) target.classList.add('selected');++ if (+ this.transformControls &&+ node !== this.viewer.content.parent &&+ !node.isScene &&+ node !== this.viewer.defaultCamera+ ) {+ try {+ this.transformControls.attach(node);+ } catch (e) {}+ }+ this._renderInspector(node);+ this.viewer.invalidate();+ }++ _renderInspector(node) {+ if (!this.inspectorEl) return;+ const rad2deg = 180 / Math.PI;+ const parts = [];+ parts.push(`<div class="inspector__title">${escapeHTML(node.name || node.type)}</div>`);+ parts.push(+ `<div class="inspector__sub">${node.type} · uuid: ${node.uuid.slice(0, 8)}</div>`,+ );++ parts.push('<div class="inspector__section">Transform</div>');+ parts.push(this._vec3Row('pos', [node.position.x, node.position.y, node.position.z]));+ parts.push(+ this._vec3Row('rot°', [+ node.rotation.x * rad2deg,+ node.rotation.y * rad2deg,+ node.rotation.z * rad2deg,+ ]),+ );+ parts.push(this._vec3Row('scl', [node.scale.x, node.scale.y, node.scale.z]));++ if (node.isMesh && node.geometry) {+ const g = node.geometry;+ const posAttr = g.getAttribute('position');+ const vertices = posAttr ? posAttr.count : 0;+ const index = g.getIndex();+ const triangles = Math.round(index ? index.count / 3 : vertices / 3);+ const attrs = Object.keys(g.attributes).join(', ');+ parts.push('<div class="inspector__section">Geometry</div>');+ parts.push(this._kv('vertices', vertices));+ parts.push(this._kv('triangles', triangles));+ parts.push(this._kv('indexed', index ? 'yes' : 'no'));+ parts.push(this._kv('attrs', attrs));+ if (posAttr) {+ try {+ const box = new Box3().setFromBufferAttribute(posAttr);+ const size = new Vector3();+ box.getSize(size);+ parts.push(+ this._kv(+ 'size',+ `${size.x.toFixed(2)} × ${size.y.toFixed(2)} × ${size.z.toFixed(2)}`,+ ),+ );+ } catch (e) {}+ }+ const mats = Array.isArray(node.material) ? node.material : [node.material];+ parts.push(+ this._kv(+ 'materials',+ mats+ .filter(Boolean)+ .map((m) => m.name || m.type)+ .join(', '),+ ),+ );+ }++ if (node.isLight) {+ parts.push('<div class="inspector__section">Light</div>');+ parts.push(this._kv('intensity', node.intensity?.toFixed(2)));+ if (node.color) parts.push(this._kv('color', '#' + node.color.getHexString()));+ if (node.distance !== undefined) parts.push(this._kv('distance', node.distance));+ }++ if (node.isCamera) {+ parts.push('<div class="inspector__section">Camera</div>');+ if (node.fov) parts.push(this._kv('fov', node.fov.toFixed(1) + '°'));+ parts.push(this._kv('near', node.near));+ parts.push(this._kv('far', node.far));+ }++ parts.push('<div class="inspector__section">Actions</div>');+ parts.push(+ `<div class="inspector__actions">+ <button data-act="frame">Frame</button>+ <button data-act="hide">${node.visible ? 'Hide' : 'Show'}</button>+ <button data-act="deselect">Deselect</button>+ </div>`,+ );++ this.inspectorEl.innerHTML = parts.join('');++ this.inspectorEl.querySelectorAll('.vec3-row input').forEach((inp) => {+ inp.addEventListener('change', () => this._onVec3Change(node));+ });++ this.inspectorEl+ .querySelector('[data-act="frame"]')+ ?.addEventListener('click', () => this._frameNode(node));+ this.inspectorEl.querySelector('[data-act="hide"]')?.addEventListener('click', () => {+ node.visible = !node.visible;+ this.session.recordVisibilityEdit(node, node.visible);+ const visBtn = this.treeEl.querySelector(+ `.scene-node[data-uuid="${node.uuid}"] .scene-node__visibility`,+ );+ if (visBtn) visBtn.textContent = node.visible ? '●' : '○';+ this._renderInspector(node);+ this.viewer.invalidate();+ });+ this.inspectorEl.querySelector('[data-act="deselect"]')?.addEventListener('click', () => {+ this.transformControls?.detach();+ this.selectedNode = null;+ this.treeEl+ .querySelectorAll('.scene-node__row.selected')+ .forEach((r) => r.classList.remove('selected'));+ this.inspectorEl.innerHTML =+ '<div class="scene-explorer__empty">Select a node to inspect</div>';+ this.viewer.invalidate();+ });+ }++ _onVec3Change(node) {+ const rows = this.inspectorEl.querySelectorAll('.vec3-row');+ if (rows.length < 3) return;+ const read = (row) => {+ const inputs = row.querySelectorAll('input');+ return [+ parseFloat(inputs[0].value) || 0,+ parseFloat(inputs[1].value) || 0,+ parseFloat(inputs[2].value) || 0,+ ];+ };+ const [px, py, pz] = read(rows[0]);+ const [rx, ry, rz] = read(rows[1]);+ const [sx, sy, sz] = read(rows[2]);+ const deg2rad = Math.PI / 180;+ node.position.set(px, py, pz);+ node.rotation.set(rx * deg2rad, ry * deg2rad, rz * deg2rad);+ node.scale.set(sx || 0.0001, sy || 0.0001, sz || 0.0001);+ this.session.recordTransformEdit(node);+ this.viewer.invalidate();+ }++ _vec3Row(label, values) {+ const [x, y, z] = values;+ return `<div class="inspector__row vec3-row">+ <span class="inspector__label">${label}</span>+ <span class="vec3">+ <input type="number" step="0.01" value="${x.toFixed(3)}">+ <input type="number" step="0.01" value="${y.toFixed(3)}">+ <input type="number" step="0.01" value="${z.toFixed(3)}">+ </span>+ </div>`;+ }++ _kv(k, v) {+ return `<div class="inspector__row">+ <span class="inspector__label">${k}</span>+ <span class="inspector__value">${escapeHTML(v ?? '')}</span>+ </div>`;+ }++ _frameNode(node) {+ const box = new Box3().setFromObject(node);+ if (box.isEmpty()) return;+ const center = new Vector3();+ const size = new Vector3();+ box.getCenter(center);+ box.getSize(size);+ const radius = Math.max(size.length(), 0.001);+ const cam = this.viewer.defaultCamera;+ const ctrl = this.viewer.controls;+ const dir = cam.position.clone().sub(ctrl.target).normalize();+ if (dir.lengthSq() < 1e-6) dir.set(0, 0, 1);+ ctrl.target.copy(center);+ cam.position.copy(center).add(dir.multiplyScalar(radius * 1.5));+ ctrl.update();+ this.viewer.invalidate();+ }++ _filter(query) {+ const q = query.trim().toLowerCase();+ const rows = this.treeEl.querySelectorAll('.scene-node');+ rows.forEach((row) => {+ const label = row.querySelector('.scene-node__label');+ if (!label) return;+ const match = !q || label.textContent.toLowerCase().includes(q);+ row.classList.toggle('filtered-out', !match);+ if (match && q) {+ let p = row.parentElement;+ while (p && p.classList.contains('scene-node__children')) {+ p.classList.add('open');+ const exp = p.previousElementSibling?.querySelector('.scene-node__expander');+ if (exp) exp.textContent = '▾';+ p = p.parentElement?.parentElement;+ }+ }+ });+ }++ _setupTransformControls() {+ const tc = new TransformControls(+ this.viewer.defaultCamera,+ this.viewer.renderer.domElement,+ );+ tc.addEventListener('dragging-changed', (e) => {+ this.viewer.controls.enabled = !e.value;+ });+ tc.addEventListener('objectChange', () => {+ if (this.selectedNode) {+ this.session.recordTransformEdit(this.selectedNode);+ if (this.inspectorEl && this.selectedNode === this.selectedNode) {+ this._renderInspector(this.selectedNode);+ }+ }+ this.viewer.invalidate();+ });+ tc.addEventListener('change', () => this.viewer.invalidate());+ this.viewer.scene.add(tc.getHelper ? tc.getHelper() : tc);+ this.transformControls = tc;+ }++ _onKeyDown(e) {+ if (this.viewer.isInputFocused()) return;+ if (!this.transformControls) return;++ if (e.key === 't' || e.key === 'T') {+ e.preventDefault();+ this.toggle();+ return;+ }+ if (this.panel?.classList.contains('hidden')) return;++ if (e.key === 'w' || e.key === 'W') this.transformControls.setMode('translate');+ else if (e.key === 'e' || e.key === 'E') this.transformControls.setMode('rotate');+ else if (e.key === 'r' || e.key === 'R') this.transformControls.setMode('scale');+ else if (e.key === 'Escape') {+ this.transformControls.detach();+ this.selectedNode = null;+ }+ }++ _onPointerDown(e) {+ if (e.button !== 0) return;+ if (this.panel?.classList.contains('hidden')) return;+ if (this.transformControls?.dragging) return;+ if (!this.viewer.content) return;+ if (this.panel && this.panel.contains(e.target)) return;++ const rect = this.viewer.renderer.domElement.getBoundingClientRect();+ const x = ((e.clientX - rect.left) / rect.width) * 2 - 1;+ const y = -((e.clientY - rect.top) / rect.height) * 2 + 1;++ this.raycaster.setFromCamera({ x, y }, this.viewer.defaultCamera);+ const hits = this.raycaster.intersectObject(this.viewer.content, true);+ if (hits.length > 0) {+ let target = hits[0].object;+ while (target.parent && !(target.isMesh || target.isLight || target.isCamera)) {+ target = target.parent;+ }+ this.selectNode(target);+ }+ }+}diff --git a/publish/src/editor/session.js b/publish/src/editor/session.jsnew file mode 100644index 000000000..28ac9e250--- /dev/null+++ b/publish/src/editor/session.js@@ -0,0 +1,187 @@+/**+ * EditorSession — central state for live-editable properties on a loaded model.+ *+ * Three kinds of edits are tracked and replayed at export time:+ * - materialEdits keyed by Three.js material.uuid+ * - transformEdits keyed by Three.js Object3D.uuid+ * - visibilityEdits keyed by Three.js Object3D.uuid+ *+ * We also keep the raw source bytes so we can re-serialize a modified GLB+ * via glTF-Transform without refetching. Bytes are captured lazily either+ * from a URL or from a File.+ */+export class EditorSession {+ constructor(viewer) {+ this.viewer = viewer;+ this.sourceURL = null;+ this.sourceFile = null;+ this.sourceBuffer = null;+ this.sourceName = 'model';+ this.materialEdits = {};+ this.transformEdits = {};+ this.visibilityEdits = {};+ this._listeners = new Set();+ }++ reset({ url = null, file = null, name = null } = {}) {+ this.sourceURL = url;+ this.sourceFile = file;+ this.sourceBuffer = null;+ this.sourceName =+ name || (file && file.name) || (url ? url.split('/').pop().split('?')[0] : 'model');+ this.materialEdits = {};+ this.transformEdits = {};+ this.visibilityEdits = {};+ if (!url && !file) {+ console.warn('[editor] no source — export disabled');+ }+ this._emit();+ }++ isExportReady() {+ return !!(this.sourceURL || this.sourceFile || this.sourceBuffer);+ }++ onChange(fn) {+ this._listeners.add(fn);+ return () => this._listeners.delete(fn);+ }++ _emit() {+ for (const fn of this._listeners) {+ try {+ fn(this);+ } catch (e) {+ console.warn('[editor.session] listener error', e);+ }+ }+ }++ recordMaterialEdit(material, patch) {+ const key = material.uuid;+ const existing = this.materialEdits[key] || { name: material.name, uuid: key };+ this.materialEdits[key] = { ...existing, ...patch };+ this._emit();+ }++ clearMaterialEdit(material) {+ delete this.materialEdits[material.uuid];+ this._emit();+ }++ recordTransformEdit(node) {+ this.transformEdits[node.uuid] = {+ name: node.name,+ uuid: node.uuid,+ position: node.position.toArray(),+ rotation: [node.rotation.x, node.rotation.y, node.rotation.z],+ scale: node.scale.toArray(),+ };+ this._emit();+ }++ recordVisibilityEdit(node, visible) {+ this.visibilityEdits[node.uuid] = { name: node.name, visible };+ this._emit();+ }++ isDirty() {+ return (+ Object.keys(this.materialEdits).length > 0 ||+ Object.keys(this.transformEdits).length > 0 ||+ Object.keys(this.visibilityEdits).length > 0+ );+ }++ /**+ * Replay previously-stashed edits onto the freshly loaded viewport.+ * UUIDs don't cross the reload boundary, so matching is by name — the+ * same strategy glb-export.js uses. After viewport mutation the three+ * maps are re-keyed by the new uuid so further edits update in place.+ *+ * @param {{materialEdits?: object, transformEdits?: object, visibilityEdits?: object}} edits+ */+ restoreEdits({ materialEdits, transformEdits, visibilityEdits } = {}) {+ this.materialEdits = { ...(materialEdits || {}) };+ this.transformEdits = { ...(transformEdits || {}) };+ this.visibilityEdits = { ...(visibilityEdits || {}) };+ this._applyRestoredToViewport();+ this._emit();+ }++ _applyRestoredToViewport() {+ const content = this.viewer && this.viewer.content;+ if (!content) return;++ const matByName = new Map();+ const nodeByName = new Map();+ content.traverse((node) => {+ if (node.name && !nodeByName.has(node.name)) nodeByName.set(node.name, node);+ if (!node.geometry) return;+ const mats = Array.isArray(node.material) ? node.material : [node.material];+ for (const mat of mats) {+ if (mat && mat.name && !matByName.has(mat.name)) matByName.set(mat.name, mat);+ }+ });++ const rekey = (map, lookup, apply) => {+ const rekeyed = {};+ for (const k in map) {+ const edit = map[k];+ const target = lookup.get(edit.name);+ if (!target) {+ rekeyed[k] = edit;+ continue;+ }+ apply(target, edit);+ rekeyed[target.uuid] = { ...edit, uuid: target.uuid };+ }+ return rekeyed;+ };++ this.materialEdits = rekey(this.materialEdits, matByName, (mat, edit) => {+ if (edit.baseColor && mat.color) mat.color.setRGB(...edit.baseColor);+ if (edit.emissive && mat.emissive) mat.emissive.setRGB(...edit.emissive);+ if (edit.metalness !== undefined) mat.metalness = edit.metalness;+ if (edit.roughness !== undefined) mat.roughness = edit.roughness;+ if (edit.opacity !== undefined) mat.opacity = edit.opacity;+ if (edit.alphaMode !== undefined) {+ mat.transparent = edit.alphaMode === 'BLEND';+ }+ if (edit.alphaCutoff !== undefined) mat.alphaTest = edit.alphaCutoff;+ mat.needsUpdate = true;+ });++ this.transformEdits = rekey(this.transformEdits, nodeByName, (node, edit) => {+ if (edit.position) node.position.fromArray(edit.position);+ if (edit.rotation) {+ node.rotation.set(edit.rotation[0], edit.rotation[1], edit.rotation[2]);+ }+ if (edit.scale) node.scale.fromArray(edit.scale);+ });++ this.visibilityEdits = rekey(this.visibilityEdits, nodeByName, (node, edit) => {+ node.visible = edit.visible !== false;+ });++ if (this.viewer && this.viewer.invalidate) this.viewer.invalidate();+ }++ async getSourceBuffer() {+ if (this.sourceBuffer) return this.sourceBuffer;++ if (this.sourceFile) {+ this.sourceBuffer = await this.sourceFile.arrayBuffer();+ return this.sourceBuffer;+ }++ if (this.sourceURL) {+ const res = await fetch(this.sourceURL);+ if (!res.ok) throw new Error(`Failed to fetch source: ${res.status}`);+ this.sourceBuffer = await res.arrayBuffer();+ return this.sourceBuffer;+ }++ throw new Error('No source URL or File set on EditorSession');+ }+}diff --git a/publish/src/editor/texture-inspector.js b/publish/src/editor/texture-inspector.jsnew file mode 100644index 000000000..6b43ce15c--- /dev/null+++ b/publish/src/editor/texture-inspector.js@@ -0,0 +1,481 @@+/**+ * TextureInspector — catalogs every texture referenced by the loaded model,+ * shows a grid of thumbnails with metadata, and opens a lightbox with+ * per-channel extraction (R/G/B/A grayscale), zoom/pan, and UV overlay+ * for any texture.+ */+import {+ RepeatWrapping,+ ClampToEdgeWrapping,+ MirroredRepeatWrapping,+ NearestFilter,+ LinearFilter,+ NearestMipmapNearestFilter,+ LinearMipmapNearestFilter,+ NearestMipmapLinearFilter,+ LinearMipmapLinearFilter,+} from 'three';+import { traverseMaterials } from '../viewer/internal.js';++const SLOT_LABELS = {+ map: 'Base Color',+ normalMap: 'Normal',+ metalnessMap: 'Metallic',+ roughnessMap: 'Roughness',+ aoMap: 'Occlusion',+ emissiveMap: 'Emissive',+ bumpMap: 'Bump',+ alphaMap: 'Alpha',+ displacementMap: 'Displacement',+ clearcoatMap: 'Clearcoat',+ clearcoatNormalMap: 'Clearcoat Normal',+ clearcoatRoughnessMap: 'Clearcoat Roughness',+ sheenColorMap: 'Sheen Color',+ sheenRoughnessMap: 'Sheen Roughness',+ specularColorMap: 'Specular Color',+ specularIntensityMap: 'Specular Intensity',+ transmissionMap: 'Transmission',+ thicknessMap: 'Thickness',+ lightMap: 'Light',+};++const WRAP_LABELS = {+ [RepeatWrapping]: 'repeat',+ [ClampToEdgeWrapping]: 'clamp',+ [MirroredRepeatWrapping]: 'mirror',+};++const FILTER_LABELS = {+ [NearestFilter]: 'nearest',+ [LinearFilter]: 'linear',+ [NearestMipmapNearestFilter]: 'nearest-mip-nearest',+ [LinearMipmapNearestFilter]: 'linear-mip-nearest',+ [NearestMipmapLinearFilter]: 'nearest-mip-linear',+ [LinearMipmapLinearFilter]: 'linear-mip-linear',+};++function detectFormat(tex) {+ if (tex.isCompressedTexture) return 'KTX2/Basis';+ const src = tex.image && tex.image.src;+ if (typeof src === 'string') {+ if (/\.ktx2(\?|$)/i.test(src)) return 'KTX2';+ if (/\.(jpe?g)(\?|$)/i.test(src)) return 'JPEG';+ if (/\.png(\?|$)/i.test(src)) return 'PNG';+ if (/\.webp(\?|$)/i.test(src)) return 'WebP';+ if (src.startsWith('data:image/png')) return 'PNG';+ if (src.startsWith('data:image/jpeg')) return 'JPEG';+ if (src.startsWith('data:image/webp')) return 'WebP';+ }+ if (tex.image && tex.image.tagName === 'VIDEO') return 'video';+ return 'image';+}++function estimateMemoryMB(w, h, mipmap) {+ const base = w * h * 4;+ const total = mipmap ? base * 1.333 : base;+ return (total / 1024 / 1024).toFixed(2);+}++function drawSourceToCanvas(canvas, src) {+ const ctx = canvas.getContext('2d');+ ctx.imageSmoothingEnabled = true;+ try {+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ ctx.drawImage(src, 0, 0, canvas.width, canvas.height);+ return true;+ } catch (e) {+ ctx.fillStyle = '#222';+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ ctx.fillStyle = '#888';+ ctx.font = '10px sans-serif';+ ctx.fillText('preview unavailable', 8, canvas.height / 2);+ return false;+ }+}++export class TextureInspector {+ constructor(viewer, session) {+ this.viewer = viewer;+ this.session = session;+ this.gui = viewer.gui;+ this.folder = null;+ this.panel = null;+ this._lastTextures = null;+ this._keyHandler = (e) => this._onKey(e);+ window.addEventListener('keydown', this._keyHandler);+ }++ rebuild() {+ this._clear();+ if (!this.viewer.content || !this.gui) return;+ const textures = this._collectTextures();+ this._lastTextures = textures;+ if (textures.length === 0) return;++ this.folder = this.gui.addFolder('Textures');+ this.folder+ .add(+ {+ open: () => this._openPanel(textures),+ },+ 'open',+ )+ .name(`inspect (${textures.length}) [X]`);+ }++ _onKey(e) {+ if (e.key !== 'x' && e.key !== 'X') return;+ const t = e.target;+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;+ if (this.panel) {+ this.panel.remove();+ this.panel = null;+ return;+ }+ if (this._lastTextures && this._lastTextures.length) {+ this._openPanel(this._lastTextures);+ }+ }++ _collectTextures() {+ const byUuid = new Map();+ traverseMaterials(this.viewer.content, (mat) => {+ for (const slot in SLOT_LABELS) {+ const tex = mat[slot];+ if (!tex || !tex.image) continue;+ const key = tex.uuid;+ if (!byUuid.has(key)) {+ byUuid.set(key, { tex, slots: new Set(), materials: new Set(), meshes: [] });+ }+ const entry = byUuid.get(key);+ entry.slots.add(SLOT_LABELS[slot]);+ entry.materials.add(mat.name || mat.type);+ }+ });++ // Second pass: gather meshes per texture for UV overlay+ this.viewer.content.traverse((node) => {+ if (!node.geometry || !node.material) return;+ const mats = Array.isArray(node.material) ? node.material : [node.material];+ mats.forEach((mat) => {+ for (const slot in SLOT_LABELS) {+ const tex = mat[slot];+ if (!tex || !byUuid.has(tex.uuid)) continue;+ const entry = byUuid.get(tex.uuid);+ if (!entry.meshes.includes(node)) entry.meshes.push(node);+ }+ });+ });++ return [...byUuid.values()];+ }++ _openPanel(textures) {+ if (this.panel) this.panel.remove();++ const panel = document.createElement('div');+ panel.className = 'texture-inspector';+ panel.innerHTML = `+ <div class="texture-inspector__header">+ <span class="texture-inspector__title">Texture Inspector · ${textures.length}</span>+ <button class="texture-inspector__close" title="Close [X]">×</button>+ </div>+ <div class="texture-inspector__grid"></div>+ `;+ document.body.appendChild(panel);+ this.panel = panel;++ panel.querySelector('.texture-inspector__close').addEventListener('click', () => {+ panel.remove();+ this.panel = null;+ });++ const grid = panel.querySelector('.texture-inspector__grid');+ textures.forEach((entry) => grid.appendChild(this._buildCard(entry)));+ }++ _buildCard(entry) {+ const { tex, slots, materials } = entry;+ const img = tex.image;+ const w = img.width || img.videoWidth || 0;+ const h = img.height || img.videoHeight || 0;+ const memMB = estimateMemoryMB(w, h, tex.generateMipmaps !== false);+ const format = detectFormat(tex);+ const wrap = `${WRAP_LABELS[tex.wrapS] || '?'}/${WRAP_LABELS[tex.wrapT] || '?'}`;+ const uvChannel = tex.channel ?? 0;++ const card = document.createElement('div');+ card.className = 'texture-card';+ const thumb = document.createElement('canvas');+ thumb.className = 'texture-card__thumb';+ thumb.width = 128;+ thumb.height = 128;+ drawSourceToCanvas(thumb, img);+ card.appendChild(thumb);++ const info = document.createElement('div');+ info.className = 'texture-card__info';+ info.innerHTML = `+ <div class="texture-card__name">${[...slots].join(' · ')}</div>+ <div class="texture-card__meta">${w}×${h} · ${format} · ~${memMB} MB</div>+ <div class="texture-card__meta">UV${uvChannel} · ${wrap}</div>+ <div class="texture-card__mats">${[...materials].slice(0, 3).join(', ')}${+ materials.size > 3 ? '…' : ''+ }</div>+ `;+ card.appendChild(info);++ const open = () => this._openLightbox(entry);+ thumb.addEventListener('click', open);+ card.addEventListener('click', (e) => {+ if (e.target === thumb) return;+ open();+ });+ return card;+ }++ _openLightbox(entry) {+ const { tex, slots, materials, meshes } = entry;+ const img = tex.image;+ const w = img.width || 256;+ const h = img.height || 256;+ const format = detectFormat(tex);+ const memMB = estimateMemoryMB(w, h, tex.generateMipmaps !== false);+ const wrap = `${WRAP_LABELS[tex.wrapS] || '?'}/${WRAP_LABELS[tex.wrapT] || '?'}`;+ const magFilter = FILTER_LABELS[tex.magFilter] || '?';+ const minFilter = FILTER_LABELS[tex.minFilter] || '?';+ const uvChannel = tex.channel ?? 0;++ const lb = document.createElement('div');+ lb.className = 'texture-lightbox';+ lb.innerHTML = `+ <div class="texture-lightbox__bar">+ <div class="texture-lightbox__meta">+ <span class="texture-lightbox__title">${[...slots].join(' · ')}</span>+ <span class="texture-lightbox__dim">${w}×${h} · ${format} · ~${memMB} MB · UV${uvChannel} · wrap ${wrap} · mag ${magFilter} · min ${minFilter}</span>+ </div>+ <div class="texture-lightbox__channels">+ <button data-ch="rgb" class="active">RGB</button>+ <button data-ch="r">R</button>+ <button data-ch="g">G</button>+ <button data-ch="b">B</button>+ <button data-ch="a">A</button>+ <button data-ch="checker" title="Alpha over checkerboard">⌗</button>+ <button data-act="uv" title="Toggle UV wireframe">UV</button>+ <button data-act="fit" title="Reset zoom">⤢</button>+ </div>+ <button class="texture-lightbox__close" title="Close">×</button>+ </div>+ <div class="texture-lightbox__stage">+ <div class="texture-lightbox__viewport">+ <canvas class="texture-lightbox__canvas" width="${w}" height="${h}"></canvas>+ <canvas class="texture-lightbox__uv" width="${w}" height="${h}"></canvas>+ </div>+ </div>+ <div class="texture-lightbox__footer">Used by: ${[...materials].join(', ')} · ${meshes.length} mesh${meshes.length === 1 ? '' : 'es'}</div>+ `;+ document.body.appendChild(lb);++ const canvas = lb.querySelector('.texture-lightbox__canvas');+ const uvCanvas = lb.querySelector('.texture-lightbox__uv');+ const viewport = lb.querySelector('.texture-lightbox__viewport');+ const ctx = canvas.getContext('2d');+ drawSourceToCanvas(canvas, img);++ let imgData = null;+ try {+ imgData = ctx.getImageData(0, 0, w, h);+ } catch (e) {+ imgData = null;+ }++ let currentChannel = 'rgb';+ let uvVisible = false;++ const drawChecker = () => {+ const tile = 16;+ ctx.fillStyle = '#ccc';+ ctx.fillRect(0, 0, w, h);+ ctx.fillStyle = '#777';+ for (let y = 0; y < h; y += tile) {+ for (let x = (y / tile) % 2 === 0 ? 0 : tile; x < w; x += tile * 2) {+ ctx.fillRect(x, y, tile, tile);+ }+ }+ };++ const drawChannel = (ch) => {+ currentChannel = ch;+ ctx.clearRect(0, 0, w, h);+ if (ch === 'rgb') {+ drawSourceToCanvas(canvas, img);+ return;+ }+ if (ch === 'checker') {+ drawChecker();+ try {+ ctx.drawImage(img, 0, 0, w, h);+ } catch (e) {}+ return;+ }+ if (!imgData) {+ ctx.fillStyle = '#222';+ ctx.fillRect(0, 0, w, h);+ ctx.fillStyle = '#aaa';+ ctx.font = '14px sans-serif';+ ctx.fillText('channel extraction blocked (CORS)', 16, h / 2);+ return;+ }+ const out = ctx.createImageData(w, h);+ const idx = { r: 0, g: 1, b: 2, a: 3 }[ch];+ for (let i = 0; i < imgData.data.length; i += 4) {+ const v = imgData.data[i + idx];+ out.data[i] = v;+ out.data[i + 1] = v;+ out.data[i + 2] = v;+ out.data[i + 3] = 255;+ }+ ctx.putImageData(out, 0, 0);+ };++ const drawUV = () => {+ const uctx = uvCanvas.getContext('2d');+ uctx.clearRect(0, 0, w, h);+ if (!uvVisible) return;+ uctx.strokeStyle = 'rgba(0, 255, 180, 0.75)';+ uctx.lineWidth = Math.max(1, w / 800);+ const attrName = uvChannel === 1 ? 'uv1' : 'uv';+ meshes.forEach((mesh) => {+ const geo = mesh.geometry;+ const uvAttr = geo.attributes[attrName] || geo.attributes.uv;+ if (!uvAttr) return;+ const index = geo.index;+ uctx.beginPath();+ const drawTri = (a, b, c) => {+ const ax = uvAttr.getX(a) * w;+ const ay = (1 - uvAttr.getY(a)) * h;+ const bx = uvAttr.getX(b) * w;+ const by = (1 - uvAttr.getY(b)) * h;+ const cx = uvAttr.getX(c) * w;+ const cy = (1 - uvAttr.getY(c)) * h;+ uctx.moveTo(ax, ay);+ uctx.lineTo(bx, by);+ uctx.moveTo(bx, by);+ uctx.lineTo(cx, cy);+ uctx.moveTo(cx, cy);+ uctx.lineTo(ax, ay);+ };+ if (index) {+ const arr = index.array;+ for (let i = 0; i < arr.length; i += 3) drawTri(arr[i], arr[i + 1], arr[i + 2]);+ } else {+ for (let i = 0; i < uvAttr.count; i += 3) drawTri(i, i + 1, i + 2);+ }+ uctx.stroke();+ });+ };++ // Zoom / pan+ let zoom = 1;+ let tx = 0;+ let ty = 0;+ let dragging = false;+ let lastX = 0;+ let lastY = 0;++ const applyTransform = () => {+ const t = `translate(${tx}px, ${ty}px) scale(${zoom})`;+ canvas.style.transform = t;+ uvCanvas.style.transform = t;+ };+ applyTransform();++ viewport.addEventListener(+ 'wheel',+ (e) => {+ e.preventDefault();+ const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;+ const next = Math.max(0.1, Math.min(12, zoom * factor));+ // zoom toward cursor+ const rect = viewport.getBoundingClientRect();+ const cx = e.clientX - rect.left - rect.width / 2;+ const cy = e.clientY - rect.top - rect.height / 2;+ tx = cx - (cx - tx) * (next / zoom);+ ty = cy - (cy - ty) * (next / zoom);+ zoom = next;+ applyTransform();+ },+ { passive: false },+ );++ viewport.addEventListener('mousedown', (e) => {+ dragging = true;+ lastX = e.clientX;+ lastY = e.clientY;+ viewport.style.cursor = 'grabbing';+ });+ window.addEventListener('mousemove', (e) => {+ if (!dragging) return;+ tx += e.clientX - lastX;+ ty += e.clientY - lastY;+ lastX = e.clientX;+ lastY = e.clientY;+ applyTransform();+ });+ window.addEventListener('mouseup', () => {+ dragging = false;+ viewport.style.cursor = '';+ });++ const fit = () => {+ zoom = 1;+ tx = 0;+ ty = 0;+ applyTransform();+ };++ lb.querySelectorAll('.texture-lightbox__channels button').forEach((btn) => {+ btn.addEventListener('click', () => {+ const act = btn.dataset.act;+ if (act === 'uv') {+ uvVisible = !uvVisible;+ btn.classList.toggle('active', uvVisible);+ drawUV();+ return;+ }+ if (act === 'fit') {+ fit();+ return;+ }+ lb.querySelectorAll('.texture-lightbox__channels button[data-ch]').forEach((b) =>+ b.classList.remove('active'),+ );+ btn.classList.add('active');+ drawChannel(btn.dataset.ch);+ });+ });++ lb.querySelector('.texture-lightbox__close').addEventListener('click', () => lb.remove());+ lb.addEventListener('click', (e) => {+ if (e.target === lb) lb.remove();+ });+ }++ _clear() {+ if (this.folder && this.gui) {+ try {+ this.gui.removeFolder(this.folder);+ } catch (e) {}+ }+ this.folder = null;+ if (this.panel) {+ this.panel.remove();+ this.panel = null;+ }+ }++ dispose() {+ this._clear();+ window.removeEventListener('keydown', this._keyHandler);+ }+}diff --git a/publish/src/element.js b/publish/src/element.jsnew file mode 100644index 000000000..09443e4f2--- /dev/null+++ b/publish/src/element.js@@ -0,0 +1,1513 @@+// <agent-3d> — the web component that ships the whole framework in one tag.+// See specs/EMBED_SPEC.md++import { Viewer } from './viewer.js';+import { Runtime } from './runtime/index.js';+import { SceneController } from './runtime/scene.js';+import { SkillRegistry } from './skills/index.js';+import { Memory } from './memory/index.js';+import { loadManifest, fetchRelative } from './manifest.js';+import { resolveURI } from './ipfs.js';+import { resolveAgentById, resolveByAgentId, AgentResolveError } from './agent-resolver.js';+import { parseAgentRef, resolveOnchainAgent, toManifest } from './erc8004/resolver.js';+// BEGIN:EMBED_BRIDGES_IMPORT+import { EmbedActionBridge } from './embed-action-bridge.js';+import { protocol, ACTION_TYPES } from './agent-protocol.js';+// END:EMBED_BRIDGES_IMPORT++const MODES = ['inline', 'floating', 'section', 'fullscreen'];++// 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 '';+ }+})();++function originAllowed(originUrl, policy, firstParty = []) {+ if (!originUrl) return false;+ let host;+ try {+ host = new URL(originUrl).hostname.toLowerCase();+ } catch {+ return false;+ }+ if (firstParty.some((fp) => host === fp || host.endsWith('.' + fp))) return true;+ const hosts = policy?.origins?.hosts ?? [];+ const mode = policy?.origins?.mode ?? 'allowlist';+ const matches = hosts.some((h) => {+ const lower = h.toLowerCase();+ if (lower.startsWith('*.')) return host.endsWith(lower.slice(1)) && host !== lower.slice(2);+ return host === lower;+ });+ return mode === 'allowlist' ? matches : !matches;+}++const BASE_STYLE = `+ :host {+ display: block;+ position: relative;+ width: 100%;+ height: 480px;+ --agent-bubble-radius: 16px;+ --agent-accent: #3b82f6;+ --agent-surface: rgba(17, 24, 39, 0.92);+ --agent-on-surface: #f9fafb;+ --agent-chat-font: system-ui, -apple-system, sans-serif;+ --agent-mic-glow: #22c55e;+ --agent-shadow: 0 20px 60px rgba(0,0,0,0.3);+ contain: layout style;+ }+ :host([mode="floating"]) {+ position: fixed;+ z-index: 2147483000;+ width: var(--agent-width, 320px);+ height: var(--agent-height, 420px);+ border-radius: var(--agent-bubble-radius);+ overflow: hidden;+ box-shadow: var(--agent-shadow);+ transition:+ width 0.3s cubic-bezier(0.4, 0, 0.2, 1),+ height 0.3s cubic-bezier(0.4, 0, 0.2, 1),+ border-radius 0.3s cubic-bezier(0.4, 0, 0.2, 1);+ }+ @media (prefers-reduced-motion: reduce) {+ :host([mode="floating"]) { transition: none; }+ }+ /* Inline responsive: height follows width at a 3:4 portrait ratio */+ :host([mode="inline"][data-responsive]) {+ height: auto;+ aspect-ratio: var(--agent-aspect, 3/4);+ }+ :host([mode="fullscreen"]) {+ position: fixed;+ inset: 0;+ width: 100vw;+ height: 100vh;+ z-index: 2147483000;+ }+ :host([hidden]) { display: none; }+ .stage {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ }+ .stage canvas { display: block; }+ /* Pill tap target — shown when collapsed to pill on narrow viewports */+ .pill-btn {+ display: none;+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ background: none;+ border: 0;+ cursor: pointer;+ border-radius: inherit;+ z-index: 10;+ }+ /* Swipe-down handle visible when bottom-sheet is expanded */+ .pill-drag {+ display: none;+ position: absolute;+ top: 8px;+ left: 50%;+ transform: translateX(-50%);+ width: 36px;+ height: 4px;+ border-radius: 2px;+ background: rgba(255,255,255,0.25);+ pointer-events: none;+ z-index: 20;+ }+ .chrome {+ position: absolute;+ left: 12px;+ right: 12px;+ bottom: 12px;+ display: flex;+ gap: 8px;+ align-items: flex-end;+ pointer-events: none;+ }+ .chrome > * { pointer-events: auto; }+ .chat {+ flex: 1;+ max-height: 40%;+ overflow-y: auto;+ background: var(--agent-surface);+ color: var(--agent-on-surface);+ font: 14px/1.4 var(--agent-chat-font);+ border-radius: 12px;+ padding: 10px 12px;+ backdrop-filter: blur(12px);+ }+ .chat:empty { display: none; }+ .msg { margin: 6px 0; padding: 8px 10px; border-radius: 10px; border-left: 3px solid transparent; transition: border-color .2s; }+ .msg.celebration { border-left-color: rgba(34,197,94,0.85); background: rgba(34,197,94,0.06); }+ .msg.concern { border-left-color: rgba(239,68,68,0.85); background: rgba(239,68,68,0.06); }+ .msg.curiosity { border-left-color: rgba(59,130,246,0.7); background: rgba(59,130,246,0.05); }+ .msg .role { opacity: 0.55; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }+ .msg .body { white-space: pre-wrap; }+ /* Suggestion chips when the conversation is empty */+ .suggest-row { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 0 0; }+ .suggest-chip { font: 600 11px/1 var(--agent-chat-font); color: var(--agent-on-surface); background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.1); padding: 6px 10px; border-radius: 999px; cursor: pointer; transition: all .12s; }+ .suggest-chip:hover { background: rgba(255,255,255,.12); border-color: rgba(255,255,255,.18); }+ /* Tool-call indicator near the bottom of the canvas */+ .tool-indicator { position: absolute; left: 50%; bottom: 96px; transform: translateX(-50%); display: none; align-items: center; gap: 8px; padding: 6px 12px; background: var(--agent-surface); color: var(--agent-on-surface); border-radius: 999px; font: 12px var(--agent-chat-font); backdrop-filter: blur(12px); pointer-events: none; opacity: 0; transition: opacity .15s; z-index: 3; }+ .tool-indicator[data-active="true"] { display: inline-flex; opacity: 1; }+ .tool-indicator .spin { width: 10px; height: 10px; border-radius: 50%; border: 2px solid rgba(255,255,255,.25); border-top-color: var(--agent-accent); animation: spin .9s linear infinite; }+ @keyframes spin { to { transform: rotate(360deg); } }+ /* Sticky alert banner (e.g. rug flag) */+ .alert-banner { position: absolute; top: 12px; left: 12px; right: 12px; padding: 8px 12px; border-radius: 10px; font: 600 12px/1.4 var(--agent-chat-font); display: none; align-items: center; gap: 8px; backdrop-filter: blur(12px); z-index: 3; }+ .alert-banner[data-active="true"] { display: flex; }+ .alert-banner.warn { background: rgba(234,179,8,.15); color: #fde68a; border: 1px solid rgba(234,179,8,.4); }+ .alert-banner.danger { background: rgba(239,68,68,.18); color: #fecaca; border: 1px solid rgba(239,68,68,.4); }+ .alert-banner button { background: none; border: 0; color: inherit; font: 600 14px var(--agent-chat-font); cursor: pointer; padding: 0 4px; opacity: .7; }+ .alert-banner button:hover { opacity: 1; }+ /* Rich token card unfurl rendered inline in chat */+ .token-card { margin: 6px 0; padding: 10px 12px; background: rgba(0,0,0,.25); border: 1px solid rgba(255,255,255,.08); border-radius: 10px; font: 12px var(--agent-chat-font); color: var(--agent-on-surface); }+ .token-card.solana { border-left: 3px solid #c084fc; }+ .token-card-header { display: flex; align-items: center; gap: 8px; }+ .token-card-symbol { font: 700 14px var(--agent-chat-font); }+ .token-card-name { opacity: .7; }+ .token-card-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 12px; margin-top: 8px; }+ .token-card-stat { display: flex; flex-direction: column; gap: 2px; }+ .token-card-stat .label { font: 600 9px/1 var(--agent-chat-font); letter-spacing: .06em; text-transform: uppercase; opacity: .5; }+ .token-card-stat .value { font: 600 13px var(--agent-chat-font); font-variant-numeric: tabular-nums; }+ .token-card-bar { margin-top: 8px; height: 6px; background: rgba(255,255,255,.08); border-radius: 999px; overflow: hidden; }+ .token-card-bar .fill { height: 100%; background: linear-gradient(90deg, #3b82f6, #c084fc); transition: width .4s; }+ .token-card-bar .fill.danger { background: linear-gradient(90deg, #f59e0b, #ef4444); }+ .token-card .flags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }+ .token-card .flag { font: 600 9px/1 var(--agent-chat-font); letter-spacing: .04em; text-transform: uppercase; padding: 3px 6px; border-radius: 4px; background: rgba(239,68,68,.18); color: #fecaca; border: 1px solid rgba(239,68,68,.32); }+ .input-row {+ display: flex;+ gap: 6px;+ background: var(--agent-surface);+ border-radius: 999px;+ padding: 4px 4px 4px 14px;+ backdrop-filter: blur(12px);+ flex: 1;+ }+ .input-row input {+ flex: 1;+ background: transparent;+ border: 0;+ color: var(--agent-on-surface);+ font: 14px var(--agent-chat-font);+ outline: none;+ }+ button.icon {+ width: 36px;+ height: 36px;+ border-radius: 50%;+ border: 0;+ background: var(--agent-accent);+ color: white;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ }+ button.icon.mic[data-listening="true"] { box-shadow: 0 0 0 4px var(--agent-mic-glow); }+ .poster {+ position: absolute;+ inset: 0;+ background-size: contain;+ background-position: center;+ background-repeat: no-repeat;+ transition: opacity 0.4s;+ pointer-events: none;+ }+ .loading {+ position: absolute;+ left: 50%;+ top: 50%;+ transform: translate(-50%, -50%);+ color: var(--agent-on-surface);+ font: 14px var(--agent-chat-font);+ background: var(--agent-surface);+ padding: 8px 14px;+ border-radius: 999px;+ }+ .error, .agent-3d-error {+ position: absolute;+ inset: 16px;+ display: grid;+ place-items: center;+ color: var(--agent-on-surface);+ background: var(--agent-surface);+ border-radius: 12px;+ padding: 16px;+ font: 14px var(--agent-chat-font);+ }+ /* Optional name plate overlay — toggled by the name-plate attribute. */+ .name-plate {+ position: absolute;+ left: 12px;+ bottom: 10px;+ z-index: 2;+ pointer-events: none;+ font: 11px/1 var(--agent-chat-font);+ letter-spacing: 0.04em;+ color: rgba(255, 255, 255, 0.6);+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);+ }+ .name-plate:empty,+ :host([name-plate="off"]) .name-plate { display: none; }+ /* Background variants — set on :host so the canvas composites over them. */+ :host([background="transparent"]) { background: transparent; }+ :host([background="dark"]) { background: #0b0d10; }+ :host([background="light"]) { background: #f5f5f5; }+ :host([background="light"]) .name-plate {+ color: rgba(0, 0, 0, 0.55);+ text-shadow: none;+ }+`;++class Agent3DElement extends HTMLElement {+ static get observedAttributes() {+ return [+ 'src',+ 'manifest',+ 'body',+ 'agent-id',+ 'mode',+ 'position',+ 'width',+ 'height',+ 'voice',+ 'api-key',+ 'key-proxy',+ 'responsive',+ 'background',+ 'name-plate',+ ];+ }++ constructor() {+ super();+ this.attachShadow({ mode: 'open' });+ this._viewer = null;+ this._scene = null;+ this._runtime = null;+ this._memory = null;+ this._skills = null;+ this._manifest = null;+ this._mounted = false;+ this._booting = false;+ this._listening = false;+ this._pillActive = false;+ this._mqNarrow = null;+ this._mqNarrowHandler = null;+ this._ro = null;+ this._outsideTapHandler = null;+ this._autoResolvedManifest = false;+ this._suppressAttrChange = false;+ }++ connectedCallback() {+ this._renderShell();+ this._applyLayout();+ this._setupResponsive();+ this._observeViewport();+ // Defer boot until visible unless `eager` attr is present.+ // Skip boot entirely if no source — wait for src/manifest/body/agent-id+ // to be set, which triggers reboot via attributeChangedCallback.+ if (this.hasAttribute('eager') && this._hasSource()) this._boot();+ }++ _hasSource() {+ return (+ this.hasAttribute('src') ||+ this.hasAttribute('manifest') ||+ this.hasAttribute('body') ||+ this.hasAttribute('agent-id')+ );+ }++ disconnectedCallback() {+ this._teardown();+ }++ 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 (+ !this._mounted &&+ !this._booting &&+ this.isConnected &&+ ['src', 'manifest', 'body', 'agent-id'].includes(name) &&+ newVal+ ) {+ this._boot();+ return;+ }+ if (!this._mounted) return;+ if (['mode', 'position', 'width', 'height', 'responsive'].includes(name))+ this._applyLayout();+ if (name === 'background') this._applyBackground();+ if (name === 'name-plate') this._applyNamePlate();+ if (['src', 'manifest', 'body', 'agent-id'].includes(name)) {+ // Source change — reboot+ this._teardown();+ this._boot();+ }+ }++ _renderShell() {+ const style = document.createElement('style');+ style.textContent = BASE_STYLE;+ this.shadowRoot.appendChild(style);++ const stage = document.createElement('div');+ stage.className = 'stage';+ stage.part = 'stage';+ this.shadowRoot.appendChild(stage);+ this._stageEl = stage;++ const poster = document.createElement('div');+ poster.className = 'poster';+ if (this.getAttribute('poster')) {+ poster.style.backgroundImage = `url(${this.getAttribute('poster')})`;+ }+ this.shadowRoot.appendChild(poster);+ this._posterEl = poster;++ const loading = document.createElement('div');+ loading.className = 'loading';+ loading.textContent = 'Loading...';+ loading.hidden = true;+ this.shadowRoot.appendChild(loading);+ this._loadingEl = loading;++ // Optional name-plate overlay. Hidden until a name is set on boot, and+ // toggled off entirely when the host carries `name-plate="off"`. The CSS+ // hides `.name-plate:empty`, so we don't have to manage `hidden` here.+ const namePlate = document.createElement('div');+ namePlate.className = 'name-plate';+ namePlate.part = 'name-plate';+ this.shadowRoot.appendChild(namePlate);+ this._nameplateEl = namePlate;++ // Pill button — tap/keyboard target when floating collapses to pill on narrow viewports+ const pillBtn = document.createElement('button');+ pillBtn.className = 'pill-btn';+ pillBtn.setAttribute('aria-label', 'Open agent');+ pillBtn.addEventListener('click', () => this._expandPill());+ pillBtn.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ this._expandPill();+ }+ });+ this.shadowRoot.appendChild(pillBtn);+ this._pillBtn = pillBtn;++ // Drag handle shown when bottom-sheet is expanded+ const pillDrag = document.createElement('div');+ pillDrag.className = 'pill-drag';+ this.shadowRoot.appendChild(pillDrag);+ this._pillDrag = pillDrag;++ // Chat + input chrome (omitted in kiosk mode)+ if (!this.hasAttribute('kiosk')) {+ const chrome = document.createElement('div');+ chrome.className = 'chrome';+ chrome.part = 'chrome';++ const chat = document.createElement('div');+ chat.className = 'chat';+ chat.part = 'chat';++ const row = document.createElement('div');+ row.className = 'input-row';+ const input = document.createElement('input');+ input.type = 'text';+ input.placeholder = 'Say something...';+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' && input.value.trim()) {+ const v = input.value.trim();+ input.value = '';+ this.say(v);+ }+ });+ const micBtn = document.createElement('button');+ micBtn.className = 'icon mic';+ micBtn.title = 'Push to talk';+ micBtn.innerHTML = '🎙';+ micBtn.addEventListener('click', () => this._toggleMic());+ row.appendChild(input);+ row.appendChild(micBtn);++ chrome.appendChild(chat);+ chrome.appendChild(row);+ this.shadowRoot.appendChild(chrome);+ this._chatEl = chat;+ this._inputEl = input;+ this._micEl = micBtn;++ // Tool-call indicator ("Checking the chain…").+ const toolInd = document.createElement('div');+ toolInd.className = 'tool-indicator';+ toolInd.part = 'tool-indicator';+ toolInd.innerHTML = '<span class="spin"></span><span class="label">Working…</span>';+ this.shadowRoot.appendChild(toolInd);+ this._toolIndicatorEl = toolInd;++ // Sticky alert banner (rug flags etc.).+ const banner = document.createElement('div');+ banner.className = 'alert-banner';+ banner.part = 'alert-banner';+ banner.innerHTML = '<span class="msg-text"></span><button aria-label="Dismiss">×</button>';+ banner.querySelector('button').addEventListener('click', () => {+ banner.dataset.active = 'false';+ });+ this.shadowRoot.appendChild(banner);+ this._alertBannerEl = banner;++ // Suggestion chips visible while the chat is empty.+ this._renderSuggestions();+ }+ }++ _renderSuggestions() {+ if (!this._chatEl) return;+ const existing = this._chatEl.querySelector('.suggest-row');+ if (existing) existing.remove();+ const row = document.createElement('div');+ row.className = 'suggest-row';+ const chips = this._suggestionChips();+ for (const c of chips) {+ const btn = document.createElement('button');+ btn.className = 'suggest-chip';+ btn.textContent = c.label;+ btn.addEventListener('click', () => {+ row.remove();+ this.say(c.prompt);+ });+ row.appendChild(btn);+ }+ this._chatEl.appendChild(row);+ }++ _suggestionChips() {+ // Tailor the chip set to which skills are installed; fall back to a+ // generic greeting set otherwise. Skill names come from the manifest,+ // not the registry, so this works even before runtime boot.+ const installed = new Set(+ (this._manifest?.skills || []).map((s) => {+ if (typeof s === 'string') return s.replace(/\/$/, '').split('/').pop();+ if (s?.id) return s.id;+ if (s?.uri) return String(s.uri).replace(/\/$/, '').split('/').pop();+ return '';+ }),+ );+ const chips = [];+ if (installed.has('pump-fun')) {+ chips.push(+ { label: '🔥 Trending now', prompt: 'What are the trending tokens on pump.fun right now?' },+ { label: '👑 King of the hill', prompt: "Who's the king of the hill on pump.fun?" },+ { label: '🆕 New launches', prompt: 'Show me the newest pump.fun launches.' },+ );+ }+ if (installed.has('dca')) {+ chips.push({ label: '💸 Set up DCA', prompt: 'Help me set up a weekly USDC → WETH DCA.' });+ }+ if (chips.length === 0) {+ chips.push(+ { label: '👋 Say hi', prompt: 'Hi! Who are you?' },+ { label: '🎬 Show your animations', prompt: 'What animations can you do?' },+ );+ }+ return chips.slice(0, 4);+ }++ _isResponsive() {+ // Default on; opt out with responsive="false"+ return this.getAttribute('responsive') !== 'false';+ }++ _clampWidth(val) {+ const px = _parsePx(val);+ if (!px) return val;+ const min = Math.round(Math.max(160, px * 0.65));+ const vwPct = Math.round((px / 1440) * 100);+ return `clamp(${min}px, ${vwPct}vw, ${px}px)`;+ }++ /**+ * Apply the `background` attribute. Mirrors the iframe embed semantics so+ * the snippet builder's options translate cleanly: 'transparent' → renderer+ * clears with alpha=0 and the scene background is unset; 'dark' / 'light' →+ * scene background is painted in the corresponding color so the agent+ * composites over it. The host element's CSS background is driven by the+ * `:host([background="..."])` rules in BASE_STYLE.+ *+ * Safe to call before the viewer exists — it no-ops in that case and is+ * re-run automatically once `_boot()` constructs the viewer.+ */+ _applyBackground() {+ const v = this._viewer;+ if (!v) return;+ const mode = this.getAttribute('background') || 'transparent';+ if (mode === 'transparent') {+ v.renderer?.setClearAlpha?.(0);+ if (v.scene) v.scene.background = null;+ } else if (mode === 'dark') {+ v.renderer?.setClearAlpha?.(1);+ if (v.scene?.background?.set) v.scene.background.set('#0b0d10');+ } else if (mode === 'light') {+ v.renderer?.setClearAlpha?.(1);+ if (v.scene?.background?.set) v.scene.background.set('#f5f5f5');+ }+ }++ /**+ * Apply the `name-plate` attribute. Visibility is purely CSS-driven via+ * `:host([name-plate="off"])`, so this method only needs to ensure the+ * element exists in the shadow DOM (it does, see `_renderShell`).+ *+ * Kept as a separate method so attributeChangedCallback has a clear hook,+ * and so future changes to plate position/style stay localised here.+ */+ _applyNamePlate() {+ // CSS handles visibility via the `name-plate="off"` host selector.+ // Method exists so the attribute observer has a hook + future-proofing.+ }++ /** Update the plate text. Empty string hides the plate (`.name-plate:empty`). */+ _setNamePlateText(name) {+ if (!this._nameplateEl) return;+ this._nameplateEl.textContent = name || '';+ }++ _clampHeight(val) {+ const px = _parsePx(val);+ if (!px) return val;+ const min = Math.round(Math.max(200, px * 0.65));+ const vhPct = Math.round((px / 900) * 100);+ return `clamp(${min}px, ${vhPct}vh, ${px}px)`;+ }++ _applyLayout() {+ const mode = this.getAttribute('mode') || 'inline';+ if (!MODES.includes(mode)) return;+ const responsive = this._isResponsive();++ if (mode === 'floating') {+ if (!this._pillActive) {+ const pos = this.getAttribute('position') || 'bottom-right';+ const offset = (this.getAttribute('offset') || '24px 24px').split(/\s+/);+ const [vOff, hOff] = [offset[0], offset[1] || offset[0]];+ this.style.top = this.style.bottom = this.style.left = this.style.right = '';+ if (pos.includes('top')) this.style.top = vOff;+ else this.style.bottom = vOff;+ if (pos.includes('left')) this.style.left = hOff;+ else if (pos.includes('right')) this.style.right = hOff;+ else if (pos.includes('center')) {+ this.style.left = '50%';+ this.style.transform = 'translateX(-50%)';+ }+ }++ const width = this.getAttribute('width') || '320px';+ const height = this.getAttribute('height') || '420px';+ this.style.setProperty('--agent-width', responsive ? this._clampWidth(width) : width);+ this.style.setProperty(+ '--agent-height',+ responsive ? this._clampHeight(height) : height,+ );+ } else {+ this.style.top =+ this.style.bottom =+ this.style.left =+ this.style.right =+ this.style.transform =+ '';++ const width = this.getAttribute('width');+ const height = this.getAttribute('height');++ if (mode === 'inline') {+ if (width) this.style.width = responsive ? this._clampWidth(width) : width;+ if (height) {+ this.style.height = height;+ this.removeAttribute('data-responsive');+ } else if (responsive && width) {+ // No explicit height: aspect-ratio preserves 3:4 portrait via CSS+ this.style.height = '';+ this.setAttribute('data-responsive', '');+ }+ }++ if (width)+ this.style.setProperty(+ '--agent-width',+ responsive ? this._clampWidth(width) : width,+ );+ if (height)+ this.style.setProperty(+ '--agent-height',+ responsive ? this._clampHeight(height) : height,+ );+ }+ }++ _setupResponsive() {+ const mode = this.getAttribute('mode') || 'inline';++ // ResizeObserver on this — reacts to container changes without a viewport listener+ if (mode === 'inline' && typeof ResizeObserver !== 'undefined') {+ this._ro = new ResizeObserver(() => this._applyLayout());+ this._ro.observe(this);+ }++ // matchMedia for floating pill collapse at narrow viewports+ if (mode === 'floating' && this._isResponsive() && typeof window !== 'undefined') {+ this._mqNarrow = window.matchMedia('(max-width: 479px)');+ this._mqNarrowHandler = (e) => this._updatePillState(e.matches);+ this._mqNarrow.addEventListener('change', this._mqNarrowHandler);+ this._updatePillState(this._mqNarrow.matches);+ }++ // Swipe-down to close the bottom-sheet (CSS transitions handle the animation)+ let touchStartY = 0;+ this.shadowRoot.addEventListener(+ 'touchstart',+ (e) => {+ touchStartY = e.touches[0].clientY;+ },+ { passive: true },+ );+ this.shadowRoot.addEventListener(+ 'touchend',+ (e) => {+ const dy = e.changedTouches[0].clientY - touchStartY;+ if (dy > 60 && this._pillActive && this.getAttribute('aria-expanded') === 'true') {+ this._collapsePill();+ }+ },+ { passive: true },+ );+ }++ _updatePillState(narrow) {+ if (narrow && !this._pillActive) {+ this._pillActive = true;+ this._collapsePill();+ } else if (!narrow && this._pillActive) {+ this._pillActive = false;+ this._restoreFromPill();+ }+ }++ _collapsePill() {+ this.style.width = '56px';+ this.style.height = '56px';+ this.style.borderRadius = '50%';+ this.setAttribute('aria-expanded', 'false');+ this._pillBtn.style.display = 'block';+ this._pillDrag.style.display = 'none';+ const chrome = this.shadowRoot.querySelector('.chrome');+ if (chrome) chrome.style.display = 'none';+ this._stageEl.style.display = 'none';+ if (this._outsideTapHandler) {+ document.removeEventListener('pointerdown', this._outsideTapHandler);+ this._outsideTapHandler = null;+ }+ }++ _expandPill() {+ if (!this._pillActive) return;+ this.style.width = '100vw';+ this.style.height = '70vh';+ this.style.borderRadius = '16px 16px 0 0';+ this.style.bottom = '0';+ this.style.top = 'auto';+ this.style.left = '0';+ this.style.right = '0';+ this.style.transform = 'none';+ this.setAttribute('aria-expanded', 'true');+ this._pillBtn.style.display = 'none';+ this._pillDrag.style.display = 'block';+ const chrome = this.shadowRoot.querySelector('.chrome');+ if (chrome) chrome.style.display = '';+ this._stageEl.style.display = '';++ // Close on outside tap+ this._outsideTapHandler = (e) => {+ if (!e.composedPath().includes(this)) this._collapsePill();+ };+ setTimeout(() => document.addEventListener('pointerdown', this._outsideTapHandler), 0);+ }++ _restoreFromPill() {+ this.removeAttribute('aria-expanded');+ this._pillBtn.style.display = 'none';+ this._pillDrag.style.display = 'none';+ const chrome = this.shadowRoot.querySelector('.chrome');+ if (chrome) chrome.style.display = '';+ this._stageEl.style.display = '';+ // Clear pill inline overrides, re-apply proper floating layout+ this.style.width = this.style.height = this.style.borderRadius = '';+ this.style.bottom =+ this.style.top =+ this.style.left =+ this.style.right =+ this.style.transform =+ '';+ this._applyLayout();+ if (this._outsideTapHandler) {+ document.removeEventListener('pointerdown', this._outsideTapHandler);+ this._outsideTapHandler = null;+ }+ }++ _observeViewport() {+ if (this.hasAttribute('eager')) return;+ if (typeof IntersectionObserver === 'undefined') {+ this._boot();+ return;+ }+ this._io = new IntersectionObserver((entries) => {+ if (entries.some((e) => e.isIntersecting)) {+ this._io.disconnect();+ this._boot();+ }+ });+ this._io.observe(this);+ }++ async _boot() {+ if (this._booting || this._mounted) return;+ this._booting = true;+ try {+ this._loadingEl.hidden = false;+ this.dispatchEvent(+ new CustomEvent('agent:load-progress', { detail: { phase: 'manifest', pct: 0.1 } }),+ );++ const manifest = await this._resolveManifest();+ this._manifest = manifest;+ this.dispatchEvent(+ new CustomEvent('agent:load-progress', { detail: { phase: 'manifest', pct: 0.3 } }),+ );++ // Hydrate instructions.md if referenced+ if (+ typeof manifest.brain?.instructions === 'string' &&+ manifest.brain.instructions.endsWith('.md')+ ) {+ const text = await fetchRelative(manifest, manifest.brain.instructions);+ if (text) manifest.instructions = stripFrontmatter(text);+ } else if (manifest.brain?.instructions) {+ manifest.instructions = manifest.brain.instructions;+ }++ // Embed-policy surface + origin gate (fail-open on infra errors)+ const _backendId = (() => {+ const a = this.getAttribute('agent-id') || manifest.id?.agentId || '';+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)+ ? a+ : null;+ })();+ if (_backendId) {+ try {+ const _policyBase = _scriptOrigin || window.location.origin;+ const _pr = await fetch(+ `${_policyBase}/api/agents/${_backendId}/embed-policy`,+ { credentials: 'omit' },+ );+ if (_pr.ok) {+ const { policy } = await _pr.json();+ if (policy) {+ if (policy.surfaces?.script === false) {+ this._fail(+ 'embed_denied_surface',+ 'This agent disallows the script-tag embed.',+ );+ return;+ }+ const _fp = ['three.ws', 'localhost'];+ const _host = window.location.origin;+ if (+ !_host.startsWith('http://localhost') &&+ !originAllowed(_host, policy, _fp)+ ) {+ this._fail(+ 'embed_denied_origin',+ `This agent isn't permitted on ${_host}.`,+ );+ return;+ }+ }+ }+ } catch (_e) {+ console.warn('[agent-3d] embed-policy fetch failed; continuing', _e);+ }+ }++ // Build Viewer+ this.dispatchEvent(+ new CustomEvent('agent:load-progress', { detail: { phase: 'body', pct: 0.45 } }),+ );+ const viewer = new Viewer(this._stageEl, { kiosk: this.hasAttribute('kiosk') });+ this._viewer = viewer;+ // Apply the embed surface attributes (`background`, `name-plate`) now+ // that the viewer exists. They are also re-applied on attribute change.+ this._applyBackground();+ this._setNamePlateText(manifest.name || '');+ this._applyNamePlate();+ const bodyURI = resolveURI(manifest.body?.uri);+ if (bodyURI) {+ await viewer.load(bodyURI, '', new Map());+ }+ this._scene = new SceneController(viewer);++ // Memory+ this.dispatchEvent(+ new CustomEvent('agent:load-progress', { detail: { phase: 'memory', pct: 0.6 } }),+ );+ 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',+ namespace: memoryNamespace,+ manifestURI: manifest._baseURI + 'manifest.json',+ fetchFn: fetch.bind(globalThis),+ });++ // Skills+ this.dispatchEvent(+ new CustomEvent('agent:load-progress', { detail: { phase: 'skills', pct: 0.75 } }),+ );+ this._skills = new SkillRegistry({+ trust: this.getAttribute('skill-trust') || 'owned-only',+ ownerAddress: manifest.id?.owner,+ });+ const skillList = manifest.skills || [];+ for (const spec of skillList) {+ try {+ const skill = await this._skills.install(spec, {+ bundleBase: manifest._baseURI,+ });+ this.dispatchEvent(+ new CustomEvent('skill:loaded', {+ detail: { name: skill.name, uri: skill.uri },+ }),+ );+ } catch (e) {+ console.warn('[agent-3d] skill load failed', spec, e);+ }+ }++ // Runtime+ this.dispatchEvent(+ new CustomEvent('agent:load-progress', { detail: { phase: 'brain', pct: 0.9 } }),+ );+ const providerConfig = {+ apiKey: this.getAttribute('api-key') || undefined,+ proxyURL: this.getAttribute('key-proxy') || undefined,+ agentId: _backendId || undefined,+ apiOrigin: _scriptOrigin || window.location.origin,+ };+ this._runtime = new Runtime({+ manifest,+ viewer: this._scene,+ memory: this._memory,+ skills: this._skills,+ providerConfig,+ });+ // Re-dispatch runtime events on the host+ for (const ev of [+ 'brain:thinking',+ 'brain:message',+ 'skill:tool-called',+ 'voice:speech-start',+ 'voice:speech-end',+ 'voice:transcript',+ 'voice:listen-start',+ 'memory:write',+ ]) {+ this._runtime.addEventListener(ev, (e) => {+ this.dispatchEvent(+ new CustomEvent(ev, { detail: e.detail, bubbles: true, composed: true }),+ );+ if (ev === 'brain:message' && this._chatEl) {+ // Transfer sentiment from the most recent tool call to+ // this assistant message so the bubble tints correctly.+ const detail = { ...e.detail };+ if (+ detail.role === 'assistant' &&+ detail.sentiment === undefined &&+ this._lastToolSentiment !== undefined+ ) {+ detail.sentiment = this._lastToolSentiment;+ this._lastToolSentiment = undefined;+ }+ this._renderMessage(detail);+ }+ if (ev === 'brain:thinking' && this._toolIndicatorEl) {+ if (e.detail?.thinking) this._setToolIndicator('thinking');+ else this._clearToolIndicator();+ }+ if (ev === 'skill:tool-called') {+ const { tool, result } = e.detail || {};+ this._setToolIndicator(tool);+ this._clearToolIndicator();+ if (typeof result?.sentiment === 'number') {+ this._lastToolSentiment = result.sentiment;+ }+ this._renderToolCallCard({ tool, result });+ }+ });+ }++ this._mounted = true;+ // BEGIN:EMBED_BRIDGES+ if (window !== window.parent) {+ this._embedBridge = new EmbedActionBridge({+ protocol,+ manifest: this._manifest,+ window,+ });+ this._embedBridge.start();+ }+ // END:EMBED_BRIDGES+ this._loadingEl.hidden = true;+ if (!this._pillActive) this._posterEl.style.opacity = '0';+ this.dispatchEvent(+ new CustomEvent('agent:ready', {+ detail: { agent: this, manifest },+ bubbles: true,+ composed: true,+ }),+ );+ } catch (err) {+ console.error('[agent-3d] boot failed', err);+ this._loadingEl.hidden = true;+ if (err instanceof AgentResolveError && err.code === 'not-found') {+ const el = document.createElement('div');+ el.className = 'agent-3d-error';+ el.textContent = 'Agent not found';+ this.shadowRoot.appendChild(el);+ } else {+ this._showError(err);+ }+ this.dispatchEvent(+ new CustomEvent('agent:error', {+ detail: { phase: 'boot', error: err },+ bubbles: true,+ composed: true,+ }),+ );+ } finally {+ this._booting = false;+ }+ }++ async _resolveManifest() {+ const src = this.getAttribute('src');+ const manifestAttr = this.getAttribute('manifest');+ const body = this.getAttribute('body');+ const agentIdAttr = this.getAttribute('agent-id');+ const chainIdAttr = this.getAttribute('chain-id');+ if (src) {+ if (agentIdAttr) console.warn('[agent-3d] both src and agent-id provided; using src');+ // Plain .glb / .gltf URLs are bare bodies, not manifests — treat+ // them as if `body=` had been set so users don't need to know the+ // distinction.+ if (/\.(glb|gltf)(\?|$)/i.test(src)) {+ return {+ spec: 'agent-manifest/0.1',+ _baseURI: '',+ name: this.getAttribute('name') || 'Agent',+ body: { uri: src, format: 'gltf-binary' },+ brain: { provider: 'none' },+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },+ skills: [],+ };+ }+ return loadManifest(src, {+ rpcURL: this.getAttribute('rpc-url'),+ registry: this.getAttribute('registry'),+ });+ }+ if (agentIdAttr) {+ // On-chain reference? Supported forms:+ // agent-id="eip155:8453:0xabc...:42" full CAIP-10 + token+ // agent-id="onchain:8453:42" shorthand, canonical registry+ // agent-id="42" chain-id="8453" numeric id + explicit chain+ // agent-id="agent://8453/42" agent URI+ const caipInput = chainIdAttr+ ? {+ chainId: Number(chainIdAttr),+ agentId: agentIdAttr,+ registry: this.getAttribute('registry') || undefined,+ }+ : agentIdAttr;+ const ref = parseAgentRef(caipInput);+ if (ref) {+ const resolved = await resolveOnchainAgent(ref);+ 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 resolveAgentById(agentIdAttr);+ }+ if (manifestAttr) return loadManifest(manifestAttr);+ if (body) {+ // Ad-hoc agent from a bare GLB+ const instructionsAttr = this.getAttribute('instructions');+ return {+ spec: 'agent-manifest/0.1',+ _baseURI: '',+ name: this.getAttribute('name') || 'Agent',+ body: { uri: body, format: 'gltf-binary' },+ brain: {+ provider: this.getAttribute('brain') ? 'anthropic' : 'none',+ model: this.getAttribute('brain') || undefined,+ instructions: instructionsAttr || 'You are an embodied three.ws.',+ },+ instructions: instructionsAttr || 'You are an embodied three.ws.',+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },+ skills: (this.getAttribute('skills') || '')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ .map((uri) => ({ uri })),+ memory: { mode: this.getAttribute('memory') || 'local' },+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],+ version: '0.1.0',+ };+ }+ throw new Error('<agent-3d> requires src=, manifest=, or body= attribute');+ }++ _renderMessage({ role, content, sentiment }) {+ if (!this._chatEl) return;+ if (!content) return;+ // Hide the suggestion chips once a real conversation starts.+ this._chatEl.querySelector('.suggest-row')?.remove();+ const msg = document.createElement('div');+ msg.className = 'msg';+ const tone = this._sentimentTone(sentiment);+ if (tone) msg.classList.add(tone);+ msg.innerHTML = `<div class="role"></div><div class="body"></div>`;+ msg.querySelector('.role').textContent = role;+ msg.querySelector('.body').textContent = content;+ this._chatEl.appendChild(msg);+ this._chatEl.scrollTop = this._chatEl.scrollHeight;+ }++ _sentimentTone(s) {+ if (typeof s !== 'number') return null;+ if (s > 0.3) return 'celebration';+ if (s < -0.2) return 'concern';+ if (s > 0.05) return 'curiosity';+ return null;+ }++ _setToolIndicator(toolName) {+ if (!this._toolIndicatorEl) return;+ clearTimeout(this._toolIndicatorHideTimer);+ const label = this._toolIndicatorLabel(toolName);+ this._toolIndicatorEl.querySelector('.label').textContent = label;+ this._toolIndicatorEl.dataset.active = 'true';+ }++ _clearToolIndicator() {+ if (!this._toolIndicatorEl) return;+ clearTimeout(this._toolIndicatorHideTimer);+ this._toolIndicatorHideTimer = setTimeout(() => {+ if (this._toolIndicatorEl) this._toolIndicatorEl.dataset.active = 'false';+ }, 350);+ }++ _toolIndicatorLabel(toolName) {+ const map = {+ searchTokens: 'Searching pump.fun…',+ getTokenDetails: 'Fetching token details…',+ getBondingCurve: 'Reading bonding curve…',+ getTokenTrades: 'Pulling recent trades…',+ getTrendingTokens: 'Loading trending tokens…',+ getNewTokens: 'Loading new launches…',+ getGraduatedTokens: 'Loading graduated tokens…',+ getKingOfTheHill: 'Crowning the king…',+ getCreatorProfile: 'Auditing the creator…',+ getTokenHolders: 'Inspecting holders…',+ wave: 'Waving…',+ remember: 'Saving to memory…',+ play_clip: 'Playing animation…',+ };+ return map[toolName] || `Running ${toolName}…`;+ }++ _showAlertBanner({ level = 'warn', text } = {}) {+ if (!this._alertBannerEl || !text) return;+ this._alertBannerEl.classList.remove('warn', 'danger');+ this._alertBannerEl.classList.add(level === 'danger' ? 'danger' : 'warn');+ this._alertBannerEl.querySelector('.msg-text').textContent = text;+ this._alertBannerEl.dataset.active = 'true';+ }++ _renderToolCallCard({ tool, result }) {+ if (!this._chatEl || !result || result.ok === false) return;+ const data = result.data ?? result;+ const card = this._buildTokenCard(tool, data);+ if (!card) return;+ this._chatEl.querySelector('.suggest-row')?.remove();+ this._chatEl.appendChild(card);+ this._chatEl.scrollTop = this._chatEl.scrollHeight;++ // Surface a sticky banner for clearly dangerous signals.+ if (tool === 'getCreatorProfile') {+ const flags = data?.rugFlags ?? data?.risk_flags ?? data?.flags ?? [];+ const rugged = data?.rugCount ?? data?.rug_count ?? 0;+ if (rugged > 0 || (Array.isArray(flags) && flags.length >= 2)) {+ this._showAlertBanner({+ level: 'danger',+ text: `⚠️ Creator has ${flags.length || rugged} rug indicator${(flags.length || rugged) > 1 ? 's' : ''} — be cautious.`,+ });+ } else if (Array.isArray(flags) && flags.length === 1) {+ this._showAlertBanner({+ level: 'warn',+ text: `One risk flag on this creator: ${flags[0]}`,+ });+ }+ }+ }++ _buildTokenCard(tool, data) {+ if (!data || typeof data !== 'object') return null;+ const fmt = (n, opts = {}) => {+ const v = Number(n);+ if (!Number.isFinite(v)) return '—';+ if (opts.usd) {+ if (v >= 1e6) return `$${(v / 1e6).toFixed(2)}M`;+ if (v >= 1e3) return `$${(v / 1e3).toFixed(1)}K`;+ return `$${v.toFixed(2)}`;+ }+ if (opts.pct) return `${v.toFixed(1)}%`;+ return v.toLocaleString();+ };++ const card = document.createElement('div');+ card.className = 'token-card solana';++ if (tool === 'getTokenDetails' || tool === 'getKingOfTheHill') {+ const t = data.token || data;+ const symbol = t.symbol || t.ticker || 'TOKEN';+ const name = t.name || '';+ const mcap = t.marketCapUsd ?? t.market_cap_usd ?? t.usd_market_cap;+ const price = t.priceUsd ?? t.price_usd ?? t.usd_price;+ const grad = t.graduationPercent ?? t.graduation_percent ?? t.progress;+ card.innerHTML = `+ <div class="token-card-header">+ <span class="token-card-symbol">$${this._esc(symbol)}</span>+ <span class="token-card-name">${this._esc(name)}</span>+ </div>+ <div class="token-card-grid">+ <div class="token-card-stat"><div class="label">Market cap</div><div class="value">${fmt(mcap, { usd: true })}</div></div>+ <div class="token-card-stat"><div class="label">Price</div><div class="value">${fmt(price, { usd: true })}</div></div>+ </div>+ ${+ Number.isFinite(Number(grad))+ ? `<div class="token-card-bar"><div class="fill" style="width:${Math.min(100, Math.max(0, Number(grad)))}%"></div></div>+ <div class="token-card-stat" style="margin-top:4px"><div class="label">Graduation</div><div class="value">${fmt(grad, { pct: true })}</div></div>`+ : ''+ }+ `;+ return card;+ }++ if (tool === 'getBondingCurve') {+ const grad = data.graduationPercent ?? data.graduation_percent ?? data.progress;+ const reserves = data.solReserves ?? data.sol_reserves;+ const tokenReserves = data.tokenReserves ?? data.token_reserves;+ const danger = Number(grad) < 5;+ card.innerHTML = `+ <div class="token-card-header">+ <span class="token-card-symbol">Bonding curve</span>+ </div>+ <div class="token-card-grid">+ ${reserves !== undefined ? `<div class="token-card-stat"><div class="label">SOL reserves</div><div class="value">${fmt(reserves)}</div></div>` : ''}+ ${tokenReserves !== undefined ? `<div class="token-card-stat"><div class="label">Token reserves</div><div class="value">${fmt(tokenReserves)}</div></div>` : ''}+ </div>+ ${+ Number.isFinite(Number(grad))+ ? `<div class="token-card-bar"><div class="fill ${danger ? 'danger' : ''}" style="width:${Math.min(100, Math.max(0, Number(grad)))}%"></div></div>+ <div class="token-card-stat" style="margin-top:4px"><div class="label">Graduation</div><div class="value">${fmt(grad, { pct: true })}</div></div>`+ : ''+ }+ `;+ return card;+ }++ if (tool === 'getCreatorProfile') {+ const flags = data.rugFlags ?? data.risk_flags ?? data.flags ?? [];+ const tokenCount = data.tokenCount ?? data.token_count ?? data.tokens?.length;+ const rugged = data.rugCount ?? data.rug_count ?? 0;+ card.innerHTML = `+ <div class="token-card-header">+ <span class="token-card-symbol">Creator audit</span>+ </div>+ <div class="token-card-grid">+ <div class="token-card-stat"><div class="label">Tokens launched</div><div class="value">${fmt(tokenCount)}</div></div>+ <div class="token-card-stat"><div class="label">Rugs</div><div class="value">${fmt(rugged)}</div></div>+ </div>+ ${+ Array.isArray(flags) && flags.length+ ? `<div class="flags">${flags.map((f) => `<span class="flag">${this._esc(String(f))}</span>`).join('')}</div>`+ : ''+ }+ `;+ return card;+ }++ if (tool === 'getTrendingTokens' || tool === 'getNewTokens' || tool === 'getGraduatedTokens') {+ const list = data.tokens || data.results || data.items || (Array.isArray(data) ? data : []);+ if (!list.length) return null;+ const top = list.slice(0, 5);+ card.innerHTML = `+ <div class="token-card-header">+ <span class="token-card-symbol">${tool === 'getTrendingTokens' ? '🔥 Trending' : tool === 'getNewTokens' ? '🆕 New' : '🎓 Graduated'}</span>+ </div>+ <div style="margin-top:8px;display:flex;flex-direction:column;gap:4px">+ ${top+ .map((t) => {+ const sym = t.symbol || t.ticker || '?';+ const mc = t.marketCapUsd ?? t.market_cap_usd ?? t.usd_market_cap;+ return `<div style="display:flex;justify-content:space-between"><span>$${this._esc(sym)}</span><span style="font-variant-numeric:tabular-nums;opacity:.8">${fmt(mc, { usd: true })}</span></div>`;+ })+ .join('')}+ </div>+ `;+ return card;+ }++ return null;+ }++ _esc(s) {+ return String(s ?? '').replace(/[&<>"]/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c],+ );+ }++ _showError(err) {+ const el = document.createElement('div');+ el.className = 'error';+ el.textContent = `Couldn't load agent: ${err.message || err}`;+ this.shadowRoot.appendChild(el);+ }++ _fail(code, message) {+ this._loadingEl.hidden = true;+ const el = document.createElement('div');+ el.className = 'error';+ el.textContent = message;+ this.shadowRoot.appendChild(el);+ this.dispatchEvent(+ new CustomEvent('agent:error', {+ detail: { phase: 'policy', error: { code, message } },+ bubbles: true,+ composed: true,+ }),+ );+ }++ async _toggleMic() {+ if (!this._runtime) return;+ if (this._listening) {+ this._runtime.stt?.stop();+ this._listening = false;+ this._micEl.dataset.listening = 'false';+ return;+ }+ this._listening = true;+ this._micEl.dataset.listening = 'true';+ try {+ const text = await this._runtime.listen();+ if (text) await this.say(text, { voice: true });+ } catch (e) {+ console.warn('[agent-3d] listen failed', e);+ } finally {+ this._listening = false;+ this._micEl.dataset.listening = 'false';+ }+ }++ _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;+ }+ try {+ this._io?.disconnect();+ } catch {}+ try {+ this._ro?.disconnect();+ } catch {}+ try {+ if (this._mqNarrow && this._mqNarrowHandler) {+ this._mqNarrow.removeEventListener('change', this._mqNarrowHandler);+ }+ } catch {}+ if (this._outsideTapHandler) {+ document.removeEventListener('pointerdown', this._outsideTapHandler);+ this._outsideTapHandler = null;+ }+ this._embedBridge?.stop();+ this._embedBridge = null;+ try {+ this._runtime?.destroy();+ } catch {}+ try {+ this._viewer?.dispose?.();+ } catch {}+ this._mounted = false;+ this._pillActive = false;+ this._runtime = this._viewer = this._scene = this._memory = this._skills = null;+ }++ // --- Public JS API ---++ async say(text, opts = {}) {+ if (!this._runtime) await this._waitForReady();+ return this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });+ }++ // Play speak animation — tries 'talk', falls back to 'yes', then 'wave'.+ speak(text, opts = {}) {+ const duration = Math.max(1.5, (text?.split(' ').length ?? 3) * 0.3);+ const sc = this._scene;+ if (!sc) return;+ sc.playAnimationByHint('talk', { duration }) ||+ sc.playAnimationByHint('yes', { duration }) ||+ sc.playAnimationByHint('wave', { duration });+ }++ async ask(text, opts = {}) {+ const reply = await this.say(text, opts);+ return reply?.text || '';+ }++ clearConversation() {+ this._runtime?.clearConversation();+ }++ async wave(opts) {+ return this._scene?.playAnimationByHint('wave', opts);+ }+ async lookAt(target) {+ return this._scene?.lookAt(target);+ }+ async play(name, opts) {+ return this._scene?.playClipByName(name, opts);+ }++ async installSkill(uri) {+ if (!this._skills) throw new Error('Agent not mounted');+ return this._skills.install({ uri });+ }+ uninstallSkill(name) {+ return this._skills?.uninstall(name);+ }+ get skills() {+ return this._skills?.all() || [];+ }+ get memory() {+ return this._memory;+ }+ get manifest() {+ return this._manifest;+ }+ get runtime() {+ return this._runtime;+ }++ setMode(mode) {+ this.setAttribute('mode', mode);+ }+ setPosition(pos, offset) {+ this.setAttribute('position', pos);+ if (offset) this.setAttribute('offset', offset);+ }+ setSize(w, h) {+ this.setAttribute('width', w);+ this.setAttribute('height', h);+ }++ pause() {+ this._runtime?.pause();+ }+ resume() {+ /* viewer resumes via IntersectionObserver */+ }+ destroy() {+ this._teardown();+ }++ /**+ * Trigger an emotion stimulus on the running avatar(s) via the protocol bus.+ * Trigger names match the avatar's emotion vocabulary:+ * 'celebration' | 'concern' | 'curiosity' | 'empathy' | 'patience'+ * Weight is clamped to [0, 1] by the avatar; defaults to 0.7.+ * No-op if the agent hasn't booted yet.+ */+ expressEmotion(trigger, weight = 0.7) {+ if (!trigger) return false;+ protocol.emit(ACTION_TYPES.EMOTE, {+ trigger,+ weight: Math.max(0, Math.min(1, Number(weight) || 0)),+ agentId: this._manifest?.id?.agentId,+ });+ return true;+ }++ _waitForReady() {+ if (this._mounted) return Promise.resolve();+ return new Promise((resolve) => {+ const on = () => {+ this.removeEventListener('agent:ready', on);+ resolve();+ };+ this.addEventListener('agent:ready', on);+ if (!this._booting) this._boot();+ });+ }+}++function stripFrontmatter(text) {+ const m = text.match(/^---\n[\s\S]*?\n---\n?([\s\S]*)$/);+ return m ? m[1] : text;+}++if (!customElements.get('agent-3d')) {+ customElements.define('agent-3d', Agent3DElement);+}++export { Agent3DElement };diff --git a/publish/src/embed-action-bridge.js b/publish/src/embed-action-bridge.jsnew file mode 100644index 000000000..0668d4d47--- /dev/null+++ b/publish/src/embed-action-bridge.js@@ -0,0 +1,194 @@+// Agent-side postMessage bridge — lives inside <agent-3d> when running inside an iframe.+// Translates host requests into AgentProtocol events and mirrors agent events back to the host.+// See specs/EMBED_SPEC.md §Bridge Protocol++const PROTOCOL_VERSION = 1;+const MAX_QUEUED_EVENTS = 256;++/** @returns {string} */+function genId() {+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')+ return crypto.randomUUID();+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {+ const r = (Math.random() * 16) | 0;+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);+ });+}++/** Maps bridge op names to AgentProtocol action types. */+const OP_TO_ACTION = {+ speak: 'speak',+ gesture: 'gesture',+ emote: 'emote',+ look: 'look-at',+};++/**+ * Agent-side bridge. Receives host requests via postMessage and emits them onto the+ * AgentProtocol bus. Optionally mirrors protocol events back to the host when the+ * host opts in with a `subscribe` request.+ *+ * Host must send `{ kind:'request', op:'subscribe' }` to receive action events —+ * events are NOT leaked by default.+ */+export class EmbedActionBridge {+ /**+ * @param {{ protocol: object, avatar?: object, manifest: object, window: Window }} opts+ */+ constructor({ protocol, avatar = null, manifest, window: win }) {+ this._protocol = protocol;+ this._avatar = avatar; // reserved for future direct avatar control+ this._manifest = manifest;+ this._win = win;+ this._subscribed = false; // host must explicitly subscribe to receive events+ this._evtQueue = []; // events queued before host subscribes+ this._running = false;+ this._onMessage = this._handleMessage.bind(this);+ this._onAction = this._handleAction.bind(this);+ }++ start() {+ if (this._running) return;+ this._running = true;+ this._win.addEventListener('message', this._onMessage);+ this._protocol.on('*', this._onAction);++ // Announce ready to the parent — triggers the ping/pong handshake+ const agentId = this._manifest?.id?.agentId || this._manifest?.agentId || '';+ const capabilities = [...Object.keys(OP_TO_ACTION), 'setAgent', 'ping', 'subscribe'];+ this._toParent({ kind: 'event', op: 'ready', payload: { agentId, capabilities } });+ }++ stop() {+ if (!this._running) return;+ this._running = false;+ this._win.removeEventListener('message', this._onMessage);+ this._protocol.off('*', this._onAction);+ this._evtQueue = [];+ }++ // ── Helpers ───────────────────────────────────────────────────────────────++ _allowedOrigins() {+ const policy = this._manifest?.policy;+ if (!policy) return [];+ const list = policy.origins || policy.allowlist || [];+ return Array.isArray(list) ? list : [list];+ }++ _originAllowed(origin) {+ const allowed = this._allowedOrigins();+ // If no policy restriction, accept any origin (fail-open matches embed-policy spec)+ if (allowed.length === 0) return true;+ return allowed.some((o) => {+ if (o === '*') return true;+ try {+ return new URL(o).origin === origin;+ } catch {+ return o === origin;+ }+ });+ }++ _toParent(msg) {+ // Use '*' as targetOrigin — we don't know the parent's origin at construction time.+ // Incoming messages are validated via _originAllowed before acting on them.+ this._win.parent.postMessage(+ { ...msg, v: PROTOCOL_VERSION, source: 'agent-3d', id: msg.id || genId() },+ '*',+ );+ }++ _reply(req, payload) {+ this._toParent({+ id: genId(),+ inReplyTo: req.id,+ kind: 'response',+ op: req.op === 'ping' ? 'pong' : req.op,+ payload,+ });+ }++ _replyError(req, code, message) {+ this._toParent({+ id: genId(),+ inReplyTo: req.id,+ kind: 'response',+ op: req.op,+ payload: { error: `${code}: ${message}` },+ });+ }++ // ── Incoming (host → agent) ───────────────────────────────────────────────++ _handleMessage(event) {+ if (event.source !== this._win.parent) return;+ if (!this._originAllowed(event.origin)) return;+ const msg = event.data;+ if (!msg || msg.v !== PROTOCOL_VERSION || msg.source !== 'agent-host') return;+ if (msg.kind !== 'request') return;++ const { op, payload = {} } = msg;++ if (op === 'ping') {+ this._reply(msg, { capabilities: [...Object.keys(OP_TO_ACTION), 'subscribe'] });+ return;+ }++ if (op === 'subscribe') {+ this._subscribed = true;+ this._reply(msg, { ok: true });+ // Flush any events queued before subscription+ for (const e of this._evtQueue) this._toParent(e);+ this._evtQueue = [];+ return;+ }++ if (op === 'setAgent') {+ // Runtime agent-switching requires a src attribute change on the host iframe.+ this._replyError(+ msg,+ 'not_supported',+ 'setAgent requires host to update the iframe src',+ );+ return;+ }++ const actionType = OP_TO_ACTION[op];+ if (!actionType) {+ this._replyError(msg, 'unknown_op', `Unknown op "${op}"`);+ return;+ }++ try {+ this._protocol.emit({ type: actionType, payload });+ this._reply(msg, { ok: true });+ } catch (err) {+ this._replyError(msg, 'emit_failed', err?.message || String(err));+ }+ }++ // ── Outgoing (agent → host) ───────────────────────────────────────────────++ _handleAction(action) {+ if (!this._running) return;+ const evt = {+ id: genId(),+ kind: 'event',+ op: 'action',+ payload: {+ type: action.type,+ payload: action.payload,+ agentId: action.agentId,+ },+ };++ if (!this._subscribed) {+ // Cap queue to prevent memory runaway; drop oldest+ if (this._evtQueue.length >= MAX_QUEUED_EVENTS) this._evtQueue.shift();+ this._evtQueue.push(evt);+ return;+ }+ this._toParent(evt);+ }+}diff --git a/publish/src/embed-host-bridge.js b/publish/src/embed-host-bridge.jsnew file mode 100644index 000000000..2a656bc4c--- /dev/null+++ b/publish/src/embed-host-bridge.js@@ -0,0 +1,193 @@+// Host-page bridge for talking to an embedded <agent-3d> iframe.+// Consumed by the parent page (or lobehub-plugin/src/bridge.ts etc.).+// See specs/EMBED_SPEC.md §Bridge Protocol++const PROTOCOL_VERSION = 1;+const REQUEST_TIMEOUT_MS = 10_000;+const MAX_BUFFERED_EVENTS = 256;++/** @returns {string} */+function genId() {+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')+ return crypto.randomUUID();+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {+ const r = (Math.random() * 16) | 0;+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);+ });+}++/**+ * Bidirectional postMessage bridge — host (parent-page) side.+ *+ * Wire format (all messages):+ * { v:1, source:'agent-host'|'agent-3d', id, inReplyTo?, kind, op, payload }+ *+ * @example+ * const bridge = new EmbedHostBridge({ iframe, agentId: 'abc', allowedOrigin: 'https://three.ws/' });+ * await bridge.ready;+ * await bridge.speak('Hello world');+ * const unsub = bridge.on('action', (a) => console.log(a));+ */+export class EmbedHostBridge {+ /**+ * @param {{ iframe: HTMLIFrameElement, agentId: string, allowedOrigin: string }} opts+ */+ constructor({ iframe, agentId, allowedOrigin }) {+ this._iframe = iframe;+ this._agentId = agentId;+ this._allowedOrigin = allowedOrigin;+ this._pending = new Map(); // id → { resolve, reject, timer }+ this._listeners = { action: new Set(), state: new Set(), error: new Set() };+ this._outQueue = []; // requests queued before handshake completes+ this._evtBuffer = []; // incoming events buffered before a listener is attached+ this._ready = false;+ this._destroyed = false;++ this._onMessage = this._handleMessage.bind(this);+ window.addEventListener('message', this._onMessage);++ /** @type {Promise<{ agentId: string, capabilities: string[] }>} resolves after handshake */+ this.ready = new Promise((resolve, reject) => {+ this._resolveReady = resolve;+ this._rejectReady = reject;+ });+ }++ _send(msg) {+ this._iframe.contentWindow?.postMessage(+ { ...msg, v: PROTOCOL_VERSION, source: 'agent-host' },+ this._allowedOrigin,+ );+ }++ _request(op, payload = {}) {+ return new Promise((resolve, reject) => {+ if (this._destroyed) {+ reject(new Error('EmbedHostBridge: destroyed'));+ return;+ }+ const id = genId();+ const timer = setTimeout(() => {+ this._pending.delete(id);+ reject(+ new Error(+ `TimeoutError: request "${op}" timed out after ${REQUEST_TIMEOUT_MS}ms`,+ ),+ );+ }, REQUEST_TIMEOUT_MS);+ this._pending.set(id, { resolve, reject, timer });+ if (this._ready) {+ this._send({ id, kind: 'request', op, payload });+ } else {+ this._outQueue.push({ id, kind: 'request', op, payload });+ }+ });+ }++ _handleMessage(event) {+ if (event.source !== this._iframe.contentWindow) return;+ if (this._allowedOrigin !== '*' && event.origin !== this._allowedOrigin) return;+ const msg = event.data;+ if (!msg || msg.v !== PROTOCOL_VERSION || msg.source !== 'agent-3d') return;++ if (msg.kind === 'event' && msg.op === 'ready') {+ // Handshake step 1 — child announced ready, send ping+ this._send({ id: genId(), kind: 'request', op: 'ping', payload: {} });+ return;+ }++ if (msg.kind === 'response' && msg.op === 'pong') {+ // Handshake complete — flush queued outgoing requests+ this._ready = true;+ this._resolveReady({+ agentId: this._agentId,+ capabilities: msg.payload?.capabilities || [],+ });+ for (const m of this._outQueue) this._send(m);+ this._outQueue = [];+ return;+ }++ if (msg.kind === 'response' && msg.inReplyTo) {+ const entry = this._pending.get(msg.inReplyTo);+ if (entry) {+ clearTimeout(entry.timer);+ this._pending.delete(msg.inReplyTo);+ if (msg.payload?.error) entry.reject(new Error(msg.payload.error));+ else entry.resolve(msg.payload);+ }+ return;+ }++ if (msg.kind === 'event') {+ const bucket = msg.op === 'error' ? 'error' : msg.op === 'state' ? 'state' : 'action';+ const set = this._listeners[bucket];+ if (set?.size) {+ for (const h of set) h(msg.payload);+ } else {+ // Buffer events until a listener attaches; cap to avoid runaway+ if (this._evtBuffer.length >= MAX_BUFFERED_EVENTS) this._evtBuffer.shift();+ this._evtBuffer.push({ bucket, payload: msg.payload });+ }+ }+ }++ /** @param {string} text @param {object} [opts] @returns {Promise<void>} */+ speak(text, opts = {}) {+ return this._request('speak', { text, ...opts });+ }++ /** @param {string} name @returns {Promise<void>} */+ gesture(name) {+ return this._request('gesture', { name });+ }++ /** @param {{ trigger: string, weight: number }} emote @returns {Promise<void>} */+ emote({ trigger, weight }) {+ return this._request('emote', { trigger, weight });+ }++ /** @param {{ target: string }} look @returns {Promise<void>} */+ look({ target }) {+ return this._request('look', { target });+ }++ /** @param {string} nextAgentId @returns {Promise<void>} */+ setAgent(nextAgentId) {+ return this._request('setAgent', { agentId: nextAgentId });+ }++ /**+ * Subscribe to events from the embedded agent.+ * @param {'action'|'state'|'error'} event+ * @param {Function} handler+ * @returns {Function} unsubscribe+ */+ on(event, handler) {+ const set = this._listeners[event];+ if (!set) throw new Error(`EmbedHostBridge: unknown event "${event}"`);+ set.add(handler);+ // Flush buffered events for this bucket+ const remaining = [];+ for (const item of this._evtBuffer) {+ if (item.bucket === event) handler(item.payload);+ else remaining.push(item);+ }+ this._evtBuffer = remaining;+ return () => set.delete(handler);+ }++ destroy() {+ if (this._destroyed) return;+ this._destroyed = true;+ window.removeEventListener('message', this._onMessage);+ for (const { timer, reject } of this._pending.values()) {+ clearTimeout(timer);+ reject(new Error('EmbedHostBridge: destroyed'));+ }+ this._pending.clear();+ this._outQueue = [];+ this._evtBuffer = [];+ this._rejectReady?.(new Error('EmbedHostBridge: destroyed'));+ }+}diff --git a/publish/src/environments.js b/publish/src/environments.jsnew file mode 100644index 000000000..18f97f3cd--- /dev/null+++ b/publish/src/environments.js@@ -0,0 +1,24 @@+export const environments = [+ {+ id: '',+ name: 'None',+ path: null,+ },+ {+ id: 'neutral', // THREE.RoomEnvironment+ name: 'Neutral',+ path: null,+ },+ {+ id: 'venice-sunset',+ name: 'Venice Sunset',+ path: 'https://storage.googleapis.com/donmccurdy-static/venice_sunset_1k.exr',+ format: '.exr',+ },+ {+ id: 'footprint-court',+ name: 'Footprint Court (HDR Labs)',+ path: 'https://storage.googleapis.com/donmccurdy-static/footprint_court_2k.exr',+ format: '.exr',+ },+];diff --git a/publish/src/erc7710/README.md b/publish/src/erc7710/README.mdnew file mode 100644index 000000000..aefe0ec92--- /dev/null+++ b/publish/src/erc7710/README.md@@ -0,0 +1,55 @@+# src/erc7710 — ERC-7710 DelegationManager constants & pure encoders++## What this module is++Constants and pure ABI-encoding helpers for the MetaMask DelegationManager contract+(ERC-7710). It is the single source of truth for contract addresses and ABI fragments+used across the permissions subsystem.++All addresses are sourced from `@metamask/delegation-deployments` v1.2.0 (DEPLOYMENTS_1_3_0),+verified 2026-04-18. All supported chains share the same CREATE2 addresses.++## Exports++| Export | Description |+| ----------------------------------------------- | ---------------------------------------------------------- |+| `DELEGATION_MANAGER_DEPLOYMENTS` | `{ chainId: address }` map for DelegationManager |+| `DELEGATION_MANAGER_ABI` | ethers v6 human-readable ABI strings |+| `CAVEAT_ENFORCERS` | `{ enforcerName: { chainId: address } }` map |+| `EIP712_DOMAIN({ chainId, verifyingContract })` | Returns EIP-712 domain separator fields |+| `DELEGATION_TYPES` | EIP-712 `types` object for `Delegation` + `Caveat` |+| `encodeCaveats(caveats)` | ABI-encodes `{ enforcer, terms, args }[]` for on-chain use |++## What is NOT in this module++- **No signing** — `signTypedData` and wallet interaction live in `src/permissions/toolkit.js`.+- **No RPC calls** — no `eth_call`, `eth_getCode`, or provider logic here.+- **No redemption logic** — `redeemDelegations` call construction is in `src/permissions/toolkit.js`.+- **No UI** — grant/manage modals are in `src/permissions/`.++## How `src/permissions/toolkit.js` consumes this module++```js+import {+ DELEGATION_MANAGER_DEPLOYMENTS,+ DELEGATION_MANAGER_ABI,+ EIP712_DOMAIN,+ DELEGATION_TYPES,+ encodeCaveats,+} from '../erc7710/abi.js';++// Get the DelegationManager address for the active chain+const managerAddress = DELEGATION_MANAGER_DEPLOYMENTS[chainId];++// Build an ethers Contract instance+const manager = new ethers.Contract(managerAddress, DELEGATION_MANAGER_ABI, signer);++// Sign a delegation+const domain = EIP712_DOMAIN({ chainId, verifyingContract: managerAddress });+const sig = await signer.signTypedData(domain, DELEGATION_TYPES, delegationObject);++// Encode caveats before constructing the delegation struct+const encodedCaveats = encodeCaveats([+ { enforcer: CAVEAT_ENFORCERS.TimestampEnforcer[chainId], terms: '0x...', args: '0x' },+]);+```diff --git a/publish/src/erc7710/abi.js b/publish/src/erc7710/abi.jsnew file mode 100644index 000000000..e9561267b--- /dev/null+++ b/publish/src/erc7710/abi.js@@ -0,0 +1,155 @@+/**+ * ERC-7710 DelegationManager ABIs and canonical deployments.+ *+ * Addresses sourced from @metamask/delegation-deployments v1.2.0 (DEPLOYMENTS_1_3_0).+ * ABI verified against @metamask/delegation-abis v1.0.0 DelegationManager.cjs.+ * No mainnet defaults per project policy.+ *+ * Only constants and pure encoders live here — no signing, no RPC calls.+ * See src/permissions/toolkit.js for signing + redemption logic.+ */++import { AbiCoder } from 'ethers';++// DelegationManager deployment addresses, keyed by numeric chainId.+// All supported chains use the same address (CREATE2 deterministic, DEPLOYMENTS_1_3_0).+// Source: @metamask/delegation-deployments v1.2.0, fetched 2026-04-18.+export const DELEGATION_MANAGER_DEPLOYMENTS = {+ // Mainnets+ 1: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Ethereum mainnet+ 8453: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Base mainnet+ // Testnets+ 84532: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Base Sepolia+ 11155111: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Sepolia+ 421614: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Arbitrum Sepolia+ 11155420: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Optimism Sepolia+};++// Human-readable ethers v6 ABI strings for DelegationManager.+// Verified against @metamask/delegation-abis v1.0.0.+export const DELEGATION_MANAGER_ABI = [+ // Redeem one or more delegations to execute calls+ 'function redeemDelegations(bytes[] _permissionContexts, bytes32[] _modes, bytes[] _executionCallDatas) external',++ // Disable (revoke) a delegation — caller must be the delegator+ 'function disableDelegation(tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) _delegation) external',++ // Public mapping: true if the delegation hash has been disabled on-chain+ // (on-chain name is disabledDelegations; isDelegationDisabled in task spec maps here)+ 'function disabledDelegations(bytes32 delegationHash) external view returns (bool isDisabled)',++ // Returns the keccak256 hash for a delegation (used for revoke checks and signing)+ 'function getDelegationHash(tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) _input) external pure returns (bytes32)',++ // --- Events ---+ 'event RedeemedDelegation(address indexed rootDelegator, address indexed redeemer, tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) delegation)',+ 'event DisabledDelegation(bytes32 indexed delegationHash, address indexed delegator, address indexed delegate, tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) delegation)',+ 'event EnabledDelegation(bytes32 indexed delegationHash, address indexed delegator, address indexed delegate, tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) delegation)',+];++// Caveat enforcer addresses per chain — enforcer name → { chainId: address }.+// Addresses are identical on all supported chains (CREATE2 deterministic, DEPLOYMENTS_1_3_0).+// Source: @metamask/delegation-deployments v1.2.0, fetched 2026-04-18.+const _CHAINS = [1, 8453, 11155111, 84532, 421614, 11155420];+const _addr = (a) => Object.fromEntries(_CHAINS.map((id) => [id, a]));+export const CAVEAT_ENFORCERS = {+ AllowedCalldataEnforcer: _addr('0xc2b0d624c1c4319760C96503BA27C347F3260f55'),+ AllowedMethodsEnforcer: _addr('0x2c21fD0Cb9DC8445CB3fb0DC5E7Bb0Aca01842B5'),+ AllowedTargetsEnforcer: _addr('0x7F20f61b1f09b08D970938F6fa563634d65c4EeB'),+ ERC20TransferAmountEnforcer: _addr('0xf100b0819427117EcF76Ed94B358B1A5b5C6D2Fc'),+ ERC20PeriodTransferEnforcer: _addr('0x474e3Ae7E169e940607cC624Da8A15Eb120139aB'),+ LimitedCallsEnforcer: _addr('0x04658B29F6b82ed55274221a06Fc97D318E25416'),+ NativeTokenTransferAmountEnforcer: _addr('0xF71af580b9c3078fbc2BBF16FbB8EEd82b330320'),+ NativeTokenPeriodTransferEnforcer: _addr('0x9BC0FAf4Aca5AE429F4c06aEEaC517520CB16BD9'),+ TimestampEnforcer: _addr('0x1046bb45C8d673d4ea75321280DB34899413c069'),+ NonceEnforcer: _addr('0xDE4f2FAC4B3D87A1d9953Ca5FC09FCa7F366254f'),+ ValueLteEnforcer: _addr('0x92Bf12322527cAA612fd31a0e810472BBB106A8F'),+};++// bytes32 sentinel used as `authority` for root (non-chained) delegations.+export const ROOT_AUTHORITY = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';++// EIP-712 type hashes (from @metamask/delegation-core v1.1.0).+export const DELEGATION_TYPEHASH =+ '0x88c1d2ecf185adf710588203a5f263f0ff61be0d33da39792cde19ba9aa4331e';+export const CAVEAT_TYPEHASH = '0x80ad7e1b04ee6d994a125f4714ca0720908bd80ed16063ec8aee4b88e9253e2d';++// EIP-712 domain builder for delegation signing.+// NAME = 'DelegationManager', DOMAIN_VERSION = '1' per on-chain constants.+export function EIP712_DOMAIN({ chainId, verifyingContract }) {+ return {+ name: 'DelegationManager',+ version: '1',+ chainId,+ verifyingContract,+ };+}++// EIP-712 type definitions for signing delegations.+// `signature` is excluded — it is what we are computing.+export const DELEGATION_TYPES = {+ Delegation: [+ { name: 'delegate', type: 'address' },+ { name: 'delegator', type: 'address' },+ { name: 'authority', type: 'bytes32' },+ { name: 'caveats', type: 'Caveat[]' },+ { name: 'salt', type: 'uint256' },+ ],+ Caveat: [+ { name: 'enforcer', type: 'address' },+ { name: 'terms', type: 'bytes' },+ { name: 'args', type: 'bytes' },+ ],+};++/**+ * ABI-encode an array of caveats into the on-chain format.+ * @param {{ enforcer: string, terms: string, args: string }[]} caveats+ * @returns {string} ABI-encoded bytes+ */+export function encodeCaveats(caveats) {+ const coder = AbiCoder.defaultAbiCoder();+ return coder.encode(+ ['tuple(address enforcer, bytes terms, bytes args)[]'],+ [caveats.map((c) => [c.enforcer, c.terms || '0x', c.args || '0x'])],+ );+}++/**+ * ABI-encode a delegation chain (array of signed delegations) into the bytes+ * format expected by DelegationManager.redeemDelegations permissionContexts[i].+ * For a direct root delegation, pass a single-element array.+ * @param {{ delegate: string, delegator: string, authority: string, caveats: object[], salt: string|bigint, signature: string }[]} delegations+ * @returns {string} ABI-encoded bytes+ */+export function encodePermissionContext(delegations) {+ const coder = AbiCoder.defaultAbiCoder();+ const tuples = delegations.map((d) => [+ d.delegate,+ d.delegator,+ d.authority || ROOT_AUTHORITY,+ (d.caveats || []).map((c) => [c.enforcer, c.terms || '0x', c.args || '0x']),+ BigInt(d.salt ?? 0),+ d.signature || '0x',+ ]);+ return coder.encode(+ [+ 'tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature)[]',+ ],+ [tuples],+ );+}++/**+ * ABI-encode a batch of calls into the Execution[] format expected by+ * DelegationManager.redeemDelegations executionCallDatas[i].+ * @param {{ to: string, value: string, data: string }[]} calls+ * @returns {{ to: string, value: bigint, data: string }[]} tuple array (passed directly, not encoded)+ */+export function buildExecutionTuples(calls) {+ return calls.map((c) => ({+ to: c.to,+ value: BigInt(c.value || '0'),+ data: c.data || '0x',+ }));+}diff --git a/publish/src/erc8004/abi.js b/publish/src/erc8004/abi.jsnew file mode 100644index 000000000..3f215670d--- /dev/null+++ b/publish/src/erc8004/abi.js@@ -0,0 +1,120 @@+/**+ * ERC-8004 Registry ABIs & canonical deployments.+ *+ * Contract addresses below are the canonical ERC-8004 reference deployments+ * shared across every EVM chain (deployed via CREATE2). Source:+ * https://github.com/nirholas/erc8004-agents+ *+ * Validation Registry is only on testnets today — mainnet entry is null.+ */++export const IDENTITY_REGISTRY_ABI = [+ // --- Registration ---+ 'function register() external returns (uint256 agentId)',+ 'function register(string agentURI) external returns (uint256 agentId)',+ 'function register(string agentURI, tuple(string metadataKey, bytes metadataValue)[] metadata) external returns (uint256 agentId)',++ // --- URI ---+ 'function setAgentURI(uint256 agentId, string newURI) external',+ 'function tokenURI(uint256 tokenId) external view returns (string)',++ // --- Metadata ---+ 'function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue) external',+ 'function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)',++ // --- Wallet ---+ 'function getAgentWallet(uint256 agentId) external view returns (address)',++ // --- ERC-721 basics ---+ 'function ownerOf(uint256 tokenId) external view returns (address)',+ 'function balanceOf(address owner) external view returns (uint256)',+ 'function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256)',+ 'function totalSupply() external view returns (uint256)',+ 'function name() external view returns (string)',+ 'function symbol() external view returns (string)',+ 'function getVersion() external pure returns (string)',++ // --- ERC-721 transfer ---+ 'function transferFrom(address from, address to, uint256 tokenId) external',+ 'function safeTransferFrom(address from, address to, uint256 tokenId) external',+ 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) external',+ 'function approve(address to, uint256 tokenId) external',+ 'function setApprovalForAll(address operator, bool approved) external',++ // --- Events ---+ 'event Registered(uint256 indexed agentId, string agentURI, address indexed owner)',+ 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)',+];++export const REPUTATION_REGISTRY_ABI = [+ 'function submitReputation(uint256 agentId, uint8 score, string comment) external',+ 'function getReputation(uint256 agentId) external view returns (uint256 totalScore, uint256 count)',+ 'event ReputationSubmitted(uint256 indexed agentId, address indexed submitter, uint8 score, string comment)',+];++/**+ * Validation Registry ABI — best-effort; may need updating once the canonical+ * interface is published. Mainnet has no Validation Registry deployed yet.+ */+export const VALIDATION_REGISTRY_ABI = [+ 'function recordValidation(uint256 agentId, bool passed, bytes32 proofHash, string proofURI, string kind) external',+ 'function getValidationCount(uint256 agentId) external view returns (uint256)',+ 'event ValidationRecorded(uint256 indexed agentId, address indexed validator, bool passed, bytes32 proofHash, string kind)',+];++// ---------------------------------------------------------------------------+// Canonical deployments (same address on every chain)+// ---------------------------------------------------------------------------++const TESTNET = {+ identityRegistry: '0x8004A818BFB912233c491871b3d84c89A494BD9e',+ reputationRegistry: '0x8004B663056A597Dffe9eCcC1965A193B7388713',+ validationRegistry: '0x8004Cb1BF31DAf7788923b405b754f57acEB4272',+};++const MAINNET = {+ identityRegistry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',+ reputationRegistry: '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63',+ validationRegistry: '', // not yet deployed on mainnet+};++/**+ * Known deployments keyed by chainId.+ */+export const REGISTRY_DEPLOYMENTS = {+ // Mainnets+ 1: MAINNET, // Ethereum+ 10: MAINNET, // Optimism+ 56: MAINNET, // BSC+ 100: MAINNET, // Gnosis+ 137: MAINNET, // Polygon+ 250: MAINNET, // Fantom+ 324: MAINNET, // zkSync Era+ 1284: MAINNET, // Moonbeam+ 5000: MAINNET, // Mantle+ 8453: MAINNET, // Base+ 42161: MAINNET, // Arbitrum One+ 42220: MAINNET, // Celo+ 43114: MAINNET, // Avalanche+ 59144: MAINNET, // Linea+ 534352: MAINNET, // Scroll++ // Testnets+ 97: TESTNET, // BSC Testnet+ 11155111: TESTNET, // Ethereum Sepolia+ 84532: TESTNET, // Base Sepolia+ 421614: TESTNET, // Arbitrum Sepolia+ 11155420: TESTNET, // Optimism Sepolia+ 80002: TESTNET, // Polygon Amoy+ 43113: TESTNET, // Avalanche Fuji+};++/**+ * Build the agentRegistry string per spec.+ * @param {number} chainId+ * @param {string} registryAddress+ * @returns {string} e.g. "eip155:8453:0x742..."+ */+export function agentRegistryId(chainId, registryAddress) {+ return `eip155:${chainId}:${registryAddress}`;+}diff --git a/publish/src/erc8004/agent-registry.js b/publish/src/erc8004/agent-registry.jsnew file mode 100644index 000000000..bea6a382d--- /dev/null+++ b/publish/src/erc8004/agent-registry.js@@ -0,0 +1,524 @@+/**+ * ERC-8004 Agent Registry — wallet + contract interaction layer.+ *+ * Handles:+ * 1. Wallet connection (injected provider — MetaMask, Brave, etc.)+ * 2. Uploading GLB + registration JSON to IPFS via web3.storage or Filebase+ * 3. Calling register() on the Identity Registry+ * 4. Building the ERC-8004 registration JSON+ */++import { BrowserProvider, Contract } from 'ethers';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './abi.js';+import { glbFileToThumbnail } from './thumbnail.js';++// ---------------------------------------------------------------------------+// Wallet+// ---------------------------------------------------------------------------++let _provider = null;+let _signer = null;+let _address = null;+let _chainId = null;+const _listeners = new Set();+let _walletEventsBound = false;++// localStorage hint — set after a successful explicit connect, cleared on+// `accountsChanged → []`. Lets us decide whether to *attempt* eager reconnect+// on a fresh page load (avoiding noisy `eth_accounts` polls for first-time+// visitors). Not authoritative — the wallet is still the source of truth.+const HINT_KEY = '3dagent:wallet-connected';++function setHint(on) {+ try {+ if (on) localStorage.setItem(HINT_KEY, '1');+ else localStorage.removeItem(HINT_KEY);+ } catch {+ /* private mode / storage disabled */+ }+}++function hasHint() {+ try {+ return localStorage.getItem(HINT_KEY) === '1';+ } catch {+ return false;+ }+}++function notify(reason) {+ const snapshot = {+ address: _address,+ chainId: _chainId,+ signer: _signer,+ reason,+ };+ for (const fn of _listeners) {+ try {+ fn(snapshot);+ } catch {+ /* listener errors must not break the bus */+ }+ }+}++function bindWalletEvents() {+ if (_walletEventsBound || !window.ethereum?.on) return;+ _walletEventsBound = true;++ window.ethereum.on('accountsChanged', async (accounts) => {+ if (!accounts || accounts.length === 0) {+ _provider = null;+ _signer = null;+ _address = null;+ _chainId = null;+ setHint(false);+ notify('disconnected');+ return;+ }+ // Re-derive signer for the new account (no popup).+ try {+ _provider = new BrowserProvider(window.ethereum);+ _signer = await _provider.getSigner();+ _address = await _signer.getAddress();+ const net = await _provider.getNetwork();+ _chainId = Number(net.chainId);+ notify('account-changed');+ } catch {+ /* swallow — next explicit connect will recover */+ }+ });++ window.ethereum.on('chainChanged', async (chainIdHex) => {+ _chainId = Number(chainIdHex);+ // Refresh provider/signer so they bind to the new network.+ if (_address) {+ try {+ _provider = new BrowserProvider(window.ethereum);+ _signer = await _provider.getSigner();+ } catch {+ /* signer may briefly be unavailable mid-switch */+ }+ }+ notify('chain-changed');+ });+}++/**+ * Subscribe to wallet state changes (connect, disconnect, account/chain switch).+ * Returns an unsubscribe function.+ *+ * @param {(state: { address: string|null, chainId: number|null, signer: import('ethers').Signer|null, reason: string }) => void} fn+ * @returns {() => void}+ */+export function onWalletChange(fn) {+ _listeners.add(fn);+ bindWalletEvents();+ return () => _listeners.delete(fn);+}++/**+ * Snapshot of the current wallet state without triggering a connection.+ * @returns {{ address: string|null, chainId: number|null, signer: import('ethers').Signer|null }}+ */+export function getWalletState() {+ return { address: _address, chainId: _chainId, signer: _signer };+}++/**+ * Attempt a *silent* reconnect using `eth_accounts` — no MetaMask popup.+ * Only succeeds if the wallet has previously authorized this origin and is+ * still unlocked. Safe to call on every page mount.+ *+ * @returns {Promise<{address: string, chainId: number, signer: import('ethers').Signer} | null>}+ * Resolves to null when no eager connection is possible (no wallet, no prior+ * authorization, locked, or wallet refused). Never throws.+ */+export async function eagerConnectWallet() {+ if (!window.ethereum) return null;+ // Skip the RPC roundtrip for users who've never connected — no hint, no try.+ // (Doesn't apply if the wallet was authorized in a previous session before+ // we shipped the hint; on first visit after deploy they get one extra+ // silent `eth_accounts` call which is free.)+ if (!hasHint() && _address === null) {+ // Still attempt once — `eth_accounts` is cheap and may surface an+ // already-authorized session that predates the hint mechanism.+ }+ try {+ const accounts = await window.ethereum.request({ method: 'eth_accounts' });+ if (!accounts || accounts.length === 0) {+ setHint(false);+ return null;+ }+ _provider = new BrowserProvider(window.ethereum);+ _signer = await _provider.getSigner();+ _address = await _signer.getAddress();+ const network = await _provider.getNetwork();+ _chainId = Number(network.chainId);+ setHint(true);+ bindWalletEvents();+ notify('eager-connected');+ return { address: _address, chainId: _chainId, signer: _signer };+ } catch {+ return null;+ }+}++/**+ * Connect a wallet via the injected EIP-1193 provider (MetaMask, Brave, etc.).+ *+ * @returns {Promise<{provider: BrowserProvider, signer: import('ethers').Signer, address: string, chainId: number}>}+ */+export async function connectWallet() {+ if (!window.ethereum) {+ throw new Error('No wallet detected. Install MetaMask or use a wallet-enabled browser.');+ }++ _provider = new BrowserProvider(window.ethereum);+ _signer = await _provider.getSigner();+ _address = await _signer.getAddress();+ const network = await _provider.getNetwork();+ _chainId = Number(network.chainId);++ setHint(true);+ bindWalletEvents();+ notify('connected');++ return { provider: _provider, signer: _signer, address: _address, chainId: _chainId };+}++/**+ * @returns {import('ethers').Signer | null}+ */+export function getSigner() {+ return _signer;+}++/**+ * Get a usable wallet for an action, preferring an existing connection.+ *+ * Resolution order:+ * 1. Already-connected signer (no popup)+ * 2. Eager `eth_accounts` reconnect (no popup)+ * 3. Explicit `connectWallet()` (popup if user hasn't authorized yet)+ *+ * Use this in any flow that needs `{ signer, address, chainId }` — instead of+ * calling `connectWallet()` directly, which always shows a popup if the+ * wallet's internal session has been forgotten.+ *+ * @returns {Promise<{signer: import('ethers').Signer, address: string, chainId: number}>}+ */+export async function ensureWallet() {+ if (_signer && _address && _chainId) {+ return { signer: _signer, address: _address, chainId: _chainId };+ }+ const eager = await eagerConnectWallet();+ if (eager) return eager;+ const fresh = await connectWallet();+ return { signer: fresh.signer, address: fresh.address, chainId: fresh.chainId };+}++/**+ * Tear down the in-memory wallet state and clear the eager-reconnect hint.+ * Does NOT revoke wallet-side permissions — there is no standard EIP-1193 RPC+ * for that; users must revoke from their wallet UI. After calling this, the+ * next `ensureWallet()` will prompt unless they re-authorize.+ */+export function disconnectWallet() {+ _provider = null;+ _signer = null;+ _address = null;+ _chainId = null;+ setHint(false);+ notify('disconnected');+}++// ---------------------------------------------------------------------------+// File upload — backend R2 (default) or Pinata (if token supplied)+// ---------------------------------------------------------------------------++/**+ * Upload a file blob. Returns the public URL.+ *+ * Without a token: POSTs to /api/erc8004/pin which stores to R2.+ * With a Pinata JWT token: POSTs to Pinata and returns an ipfs:// URL.+ *+ * @param {Blob|File} blob+ * @param {string} [apiToken] Pinata JWT (optional)+ * @returns {Promise<string>} Public URL for the uploaded file.+ */+export async function pinFile(blob, apiToken) {+ if (apiToken) {+ const form = new FormData();+ form.append('file', blob, blob.name || 'upload');+ const res = await fetch('https://api.pinata.cloud/pinning/pinFileToIPFS', {+ method: 'POST',+ headers: { Authorization: `Bearer ${apiToken}` },+ body: form,+ });+ if (!res.ok) throw new Error(`Pinata upload failed (${res.status})`);+ const data = await res.json();+ return `ipfs://${data.IpfsHash}`;+ }++ const res = await fetch('/api/erc8004/pin', {+ method: 'POST',+ headers: { 'content-type': blob.type || 'application/octet-stream' },+ body: blob,+ credentials: 'include',+ });+ if (!res.ok) {+ const text = await res.text().catch(() => res.status);+ throw new Error(`Upload failed (${res.status}): ${text}`);+ }+ const data = await res.json();+ return data.url;+}++// ---------------------------------------------------------------------------+// Registration JSON builder+// ---------------------------------------------------------------------------++/**+ * Build an ERC-8004 agent registration JSON.+ *+ * @param {object} opts+ * @param {string} opts.name Agent display name+ * @param {string} opts.description Natural-language description+ * @param {string} opts.imageUrl URL of the 3D GLB model (HTTPS or ipfs://)+ * @param {number} opts.agentId Token ID from the registry (filled after mint)+ * @param {number} opts.chainId Chain ID where registered+ * @param {string} opts.registryAddr Identity Registry contract address+ * @param {string[]} [opts.services] Additional service objects+ * @returns {object}+ */+/**+ * Build a spec-compliant ERC-8004 registration JSON.+ *+ * `imageUrl` is the 2D thumbnail (per NFT convention). `glbUrl` is optional —+ * when present, the GLB is surfaced as a dedicated `avatar` service entry and+ * a companion `3D` renderer service pointing at 3dagent so other apps can load+ * the body in-browser without coupling to our domain.+ *+ * @param {object} opts+ * @param {string} opts.name+ * @param {string} opts.description+ * @param {string} [opts.imageUrl] 2D thumbnail URL (PNG/JPG) — used for `image`+ * @param {string} [opts.glbUrl] Optional GLB URL — emitted as an `avatar` service+ * @param {number} opts.agentId+ * @param {number} opts.chainId+ * @param {string} opts.registryAddr+ * @param {Array} [opts.services] Extra service entries+ * @param {boolean}[opts.x402Support]+ * @param {Array<{name:string,url:string,loop?:boolean,clipName?:string,source?:string}>} [opts.animations]+ * Optional animation clip list — emitted as a top-level `animations` extension+ * field (ERC-8004 permits extensions). Viewers that understand the field can+ * attach extra clips; others ignore it harmlessly.+ */+export function buildRegistrationJSON({+ name,+ description,+ imageUrl,+ glbUrl,+ agentId,+ chainId,+ registryAddr,+ services = [],+ x402Support = false,+ animations,+}) {+ const baseServices = [];+ if (glbUrl) {+ baseServices.push({+ name: 'avatar',+ endpoint: glbUrl,+ version: 'gltf-2.0',+ });+ baseServices.push({+ name: '3D',+ endpoint: `https://three.ws/#model=${encodeURIComponent(glbUrl)}`,+ version: '1.0',+ });+ }++ const json = {+ type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',+ name,+ description,+ image: imageUrl || '',+ active: true,+ x402Support,+ services: [...baseServices, ...services],+ registrations: [+ {+ agentId,+ agentRegistry: agentRegistryId(chainId, registryAddr),+ },+ ],+ supportedTrust: ['reputation'],+ };++ // Top-level `body` field follows specs/AGENT_MANIFEST.md convention and is+ // read directly by src/manifest.js → normalize(). Spec-permitted (extension+ // fields MAY be added). Redundant with the `avatar` service entry above but+ // keeps this repo's manifest resolver happy without forcing it to grep services.+ if (glbUrl) {+ json.body = { uri: glbUrl, format: 'gltf-binary' };+ }++ if (Array.isArray(animations) && animations.length > 0) {+ json.animations = animations;+ }++ return json;+}++// ---------------------------------------------------------------------------+// On-chain registration+// ---------------------------------------------------------------------------++/**+ * Get the Identity Registry contract for the connected chain.+ * @param {number} chainId+ * @param {import('ethers').Signer} signer+ * @returns {Contract}+ */+export function getIdentityRegistry(chainId, signer) {+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment || !deployment.identityRegistry) {+ throw new Error(`No Identity Registry deployment configured for chain ${chainId}.`);+ }+ return new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, signer);+}++/**+ * Full ERC-8004 registration flow.+ *+ * Resolution order for each asset:+ * - GLB: `glbUrl` (already-stable URL, skips re-pinning) → `glbFile` (pinned) → none+ * - 2D image: `imageUrl` → `imageFile` (pinned) → auto-render from `glbFile`+ * (unless `autoThumbnail: false`) → empty string+ *+ * On-chain sequence:+ * 1. Pin any files that aren't already URLs+ * 2. (Optional) auto-render a 2D thumbnail from the GLB for ERC-721 marketplace compat+ * 3. Connect wallet + get Identity Registry contract+ * 4. `register(seedURI)` — seeds the mint with whichever URL resolves first+ * 5. Build full registration JSON with the minted agentId+ * 6. Pin the JSON+ * 7. `setAgentURI(agentId, registrationUrl)` — point on-chain pointer at final JSON+ *+ * @param {object} opts+ * @param {string} opts.name+ * @param {string} opts.description+ * @param {File} [opts.glbFile] GLB to pin (skipped if `glbUrl` provided)+ * @param {string} [opts.glbUrl] Pre-resolved GLB URL — pass instead of `glbFile` to skip re-pin+ * @param {string} [opts.imageUrl] Pre-resolved 2D image URL (PNG/JPG)+ * @param {File|Blob} [opts.imageFile] 2D image to pin when `imageUrl` absent+ * @param {boolean} [opts.autoThumbnail=true] Auto-render thumbnail from GLB if no image provided+ * @param {string} [opts.apiToken] Optional Pinata JWT — omit to use built-in R2 backend+ * @param {Array<{name?:string,type?:string,endpoint:string,version?:string}>} [opts.services]+ * @param {boolean} [opts.x402Support=false]+ * @param {(msg: string) => void} [opts.onStatus] Progress callback+ * @returns {Promise<{agentId: number, registrationUrl: string, txHash: string, chainId: number}>}+ */+export async function registerAgent({+ name,+ description,+ glbFile,+ glbUrl,+ imageUrl,+ imageFile,+ autoThumbnail = true,+ apiToken,+ services = [],+ x402Support = false,+ onStatus,+}) {+ const log = onStatus || (() => {});++ // ── 1. Resolve GLB: pin file if we don't already have a URL.+ if (glbFile && !glbUrl) {+ log('Uploading 3D model...');+ glbUrl = await pinFile(glbFile, apiToken);+ log(`Model uploaded: ${glbUrl}`);+ }++ // ── 2. Resolve 2D image. Priority: URL → File → auto-thumbnail from GLB.+ if (!imageUrl && imageFile) {+ log('Uploading 2D image...');+ imageUrl = await pinFile(imageFile, apiToken);+ log(`Image uploaded: ${imageUrl}`);+ } else if (!imageUrl && autoThumbnail && glbFile) {+ try {+ log('Rendering 2D thumbnail from GLB...');+ const thumb = await glbFileToThumbnail(glbFile);+ imageUrl = await pinFile(thumb, apiToken);+ log(`Thumbnail uploaded: ${imageUrl}`);+ } catch (err) {+ log(`Thumbnail render failed (${err.message}) — continuing without 2D image.`);+ }+ }+ imageUrl = imageUrl || '';++ // ── 3. Wallet + contract. ensureWallet() reuses any prior connection+ // (no popup) and only prompts for a brand-new authorization.+ log('Connecting wallet...');+ const { signer, chainId } = await ensureWallet();+ const registry = getIdentityRegistry(chainId, signer);++ // ── 4. Mint with seed URI (useful metadata in the Registered event even if+ // setAgentURI fails before step 7 completes).+ log('Registering agent on-chain...');+ const seedURI = glbUrl || imageUrl || '';+ const tx = seedURI+ ? await registry['register(string)'](seedURI)+ : await registry['register()']();+ log(`Transaction submitted: ${tx.hash}`);+ const receipt = await tx.wait();++ const registeredEvent = receipt.logs+ .map((l) => {+ try {+ return registry.interface.parseLog(l);+ } catch {+ return null;+ }+ })+ .find((e) => e && e.name === 'Registered');++ if (!registeredEvent) {+ throw new Error('Registration transaction succeeded but Registered event not found.');+ }++ const agentId = Number(registeredEvent.args.agentId);+ log(`Agent minted! agentId = ${agentId}`);++ // ── 5 + 6. Build + pin the full registration JSON.+ const registrationJSON = buildRegistrationJSON({+ name,+ description,+ imageUrl,+ glbUrl,+ agentId,+ chainId,+ registryAddr: REGISTRY_DEPLOYMENTS[chainId].identityRegistry,+ services,+ x402Support,+ });++ log('Uploading registration metadata...');+ const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], {+ type: 'application/json',+ });+ const registrationUrl = await pinFile(jsonBlob, apiToken);+ log(`Registration metadata uploaded: ${registrationUrl}`);++ // ── 7. Point agentURI at the final JSON.+ log('Updating agentURI on-chain...');+ const updateTx = await registry.setAgentURI(agentId, registrationUrl);+ await updateTx.wait();+ log('Agent URI updated on-chain.');++ return { agentId, registrationUrl, txHash: tx.hash, chainId };+}diff --git a/publish/src/erc8004/badge.js b/publish/src/erc8004/badge.jsnew file mode 100644index 000000000..476b99920--- /dev/null+++ b/publish/src/erc8004/badge.js@@ -0,0 +1,156 @@+/**+ * <three-d-agent-badge> — embeddable trust badge for an ERC-8004 / three.ws Card v1 agent.+ *+ * Usage:+ * <script type="module" src="https://three.ws/erc8004/badge.js"></script>+ * <three-d-agent-badge agent="eip155:8453:0x8004A818BFB912233c491871b3d84c89A494BD9e/1"></three-d-agent-badge>+ *+ * Attributes:+ * - agent CAIP-style ref: "eip155:<chainId>:<registry>/<tokenId>"+ * - card-url Direct URL to a three.ws Card v1 JSON (alternative to `agent`)+ * - resolver Resolver base URL (default: https://three.ws/)+ *+ * Verification performed (client-side):+ * 1. Card JSON fetched and parsed.+ * 2. sha256(model bytes) === card.model.sha256.+ * 3. Validation report present and reportType matches (if card has `validation`).+ *+ * Renders a pill: verified / partial / unverified / error.+ */++const DEFAULT_RESOLVER = 'https://three.ws/';++const STYLES = `+:host { display: inline-block; font: 500 12px/1.4 system-ui, sans-serif; }+.pill {+ display: inline-flex; align-items: center; gap: 6px;+ padding: 4px 10px; border-radius: 999px;+ border: 1px solid currentColor;+ cursor: pointer; user-select: none;+ transition: opacity .15s;+}+.pill:hover { opacity: .8; }+.dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }+.verified { color: #0a7d2c; background: #e6f5ec; }+.partial { color: #8a5a00; background: #fff3d6; }+.unverified{ color: #8a1f1f; background: #fdebeb; }+.loading { color: #555; background: #eee; }+.error { color: #8a1f1f; background: #fdebeb; }+`;++async function sha256Hex(bytes) {+ const buf = await crypto.subtle.digest('SHA-256', bytes);+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');+}++function ipfsToHttp(uri) {+ if (uri.startsWith('ipfs://')) return `https://w3s.link/ipfs/${uri.slice(7)}`;+ return uri;+}++async function fetchCard({ agent, cardUrl, resolver }) {+ if (cardUrl) {+ const r = await fetch(cardUrl, { mode: 'cors' });+ if (!r.ok) throw new Error(`card HTTP ${r.status}`);+ return await r.json();+ }+ if (!agent) throw new Error('no agent ref or card-url provided');+ const url = `${resolver.replace(/\/$/, '')}/api/v1/agents/${encodeURIComponent(agent)}`;+ const r = await fetch(url, { mode: 'cors' });+ if (!r.ok) throw new Error(`resolver HTTP ${r.status}`);+ const body = await r.json();+ return body.card || body;+}++async function verify(card) {+ const checks = { model: null, validation: null };+ if (card?.model?.uri && card?.model?.sha256) {+ try {+ const r = await fetch(ipfsToHttp(card.model.uri), { mode: 'cors' });+ if (!r.ok) throw new Error(`model HTTP ${r.status}`);+ const bytes = new Uint8Array(await r.arrayBuffer());+ const hash = await sha256Hex(bytes);+ checks.model = hash.toLowerCase() === card.model.sha256.toLowerCase();+ } catch {+ checks.model = false;+ }+ }+ if (card?.validation?.reportUri) {+ try {+ const r = await fetch(ipfsToHttp(card.validation.reportUri), { mode: 'cors' });+ checks.validation = r.ok;+ } catch {+ checks.validation = false;+ }+ }+ return checks;+}++function statusFor(checks) {+ if (checks.model === false || checks.validation === false) return 'unverified';+ if (checks.model === true && (checks.validation === true || checks.validation === null)) {+ return checks.validation === true ? 'verified' : 'partial';+ }+ return 'partial';+}++const LABELS = {+ loading: 'Verifying…',+ verified: 'three.ws · Verified',+ partial: 'three.ws · Partial',+ unverified: 'three.ws · Unverified',+ error: 'three.ws · Error',+};++class ThreeDAgentBadge extends HTMLElement {+ static get observedAttributes() {+ return ['agent', 'card-url', 'resolver'];+ }+ constructor() {+ super();+ this.attachShadow({ mode: 'open' });+ }+ connectedCallback() {+ this.render('loading');+ this.refresh();+ }+ attributeChangedCallback() {+ if (this.isConnected) this.refresh();+ }+ render(status, detail) {+ this.shadowRoot.innerHTML = `<style>${STYLES}</style>+ <a class="pill ${status}" part="pill" title="${detail || ''}"+ href="${this.detailUrl()}" target="_blank" rel="noopener">+ <span class="dot"></span>${LABELS[status]}+ </a>`;+ }+ detailUrl() {+ const agent = this.getAttribute('agent');+ const resolver = this.getAttribute('resolver') || DEFAULT_RESOLVER;+ return agent ? `${resolver.replace(/\/$/, '')}/agent/${encodeURIComponent(agent)}` : '#';+ }+ async refresh() {+ try {+ const card = await fetchCard({+ agent: this.getAttribute('agent'),+ cardUrl: this.getAttribute('card-url'),+ resolver: this.getAttribute('resolver') || DEFAULT_RESOLVER,+ });+ const checks = await verify(card);+ const status = statusFor(checks);+ const detail = `model=${checks.model} validation=${checks.validation}`;+ this.render(status, detail);+ this.dispatchEvent(+ new CustomEvent('verified', { detail: { status, checks, card }, bubbles: true }),+ );+ } catch (err) {+ this.render('error', String(err.message || err));+ }+ }+}++if (!customElements.get('three-d-agent-badge')) {+ customElements.define('three-d-agent-badge', ThreeDAgentBadge);+}++export { ThreeDAgentBadge };diff --git a/publish/src/erc8004/batch-tab.js b/publish/src/erc8004/batch-tab.jsnew file mode 100644index 000000000..3e7963a81--- /dev/null+++ b/publish/src/erc8004/batch-tab.js@@ -0,0 +1,255 @@+/**+ * Batch registration tab for ERC-8004 agents.+ *+ * Drop a CSV (`name,description,serviceType,endpoint`) or a JSON array of+ * agent configs, preview the queue, then run the same pipeline as step-4 of+ * the single-agent wizard (register(string) with a data-URI registration JSON)+ * for each row.+ *+ * Port of reference logic from erc8004.agency (`handleBatchFile`,+ * `renderBatchPreview`, `executeBatch`). Lightly adapted to our DOM + the+ * helpers already exported by agent-registry.js.+ */++import { ensureWallet, getIdentityRegistry } from './agent-registry.js';+import { REGISTRY_DEPLOYMENTS } from './abi.js';+import { CHAIN_META, switchChain, txExplorerUrl } from './chain-meta.js';++const esc = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );++/**+ * Render the Batch tab into `body`, wired to the surrounding RegisterUI.+ *+ * @param {HTMLElement} body Container element — cleared and repopulated.+ * @param {object} ctx+ * @param {() => (null | { address: string, chainId: number })} ctx.getWallet+ * @param {() => number} ctx.getChainId+ * @param {(msg: string, isError?: boolean) => void} ctx.toast+ */+export function renderBatchTab(body, ctx) {+ body.innerHTML = `+ <h3 class="erc8004-h3">Batch Registration</h3>+ <p class="erc8004-p">Register multiple agents at once via CSV or JSON import.</p>++ <div class="erc8004-file-drop erc8004-batch-drop" data-role="drop">+ <input type="file" accept=".csv,.json" class="erc8004-file-input" />+ <div class="erc8004-batch-drop-inner">+ <div class="erc8004-batch-drop-icon">📁</div>+ <div class="erc8004-batch-drop-title">Drop CSV or JSON file here</div>+ <div class="erc8004-batch-drop-sub">or click to browse</div>+ </div>+ </div>++ <div class="erc8004-batch-preview" data-role="preview" style="display:none">+ <div class="erc8004-h4">Preview (<span data-role="count">0</span> agents)</div>+ <div class="erc8004-batch-list" data-role="list"></div>+ <div class="erc8004-row" style="margin-top:12px">+ <button class="erc8004-btn erc8004-btn--primary" data-role="run">🚀 Register All</button>+ <button class="erc8004-btn" data-role="clear">Clear</button>+ </div>+ <div class="erc8004-batch-progress" data-role="progress" style="display:none">+ <div class="erc8004-progress-bar"><div class="erc8004-progress-fill" data-role="bar"></div></div>+ <div class="erc8004-muted erc8004-small" data-role="status">Processing…</div>+ </div>+ </div>++ <details class="erc8004-accordion" data-role="format-guide">+ <summary class="erc8004-accordion-head">📝 Format Guide</summary>+ <div class="erc8004-accordion-body">+ <p class="erc8004-p"><strong>JSON format:</strong></p>+<pre class="erc8004-pre">[+ {+ "name": "Agent 1",+ "description": "Description here",+ "services": [{"name": "A2A", "endpoint": "https://..."}]+ }+]</pre>+ <p class="erc8004-p"><strong>CSV format:</strong></p>+<pre class="erc8004-pre">name,description,serviceType,endpoint+Agent 1,Does things,A2A,https://agent1.com+Agent 2,Does more,MCP,https://agent2.com</pre>+ </div>+ </details>+ `;++ const drop = body.querySelector('[data-role="drop"]');+ const input = drop.querySelector('.erc8004-file-input');+ const preview = body.querySelector('[data-role="preview"]');+ const countEl = body.querySelector('[data-role="count"]');+ const listEl = body.querySelector('[data-role="list"]');+ const progress = body.querySelector('[data-role="progress"]');+ const bar = body.querySelector('[data-role="bar"]');+ const status = body.querySelector('[data-role="status"]');++ let queue = [];++ const renderPreview = () => {+ if (!queue.length) {+ preview.style.display = 'none';+ return;+ }+ preview.style.display = '';+ countEl.textContent = String(queue.length);+ listEl.innerHTML = queue+ .map(+ (a, i) => `+ <div class="erc8004-batch-row" data-i="${i}">+ <div class="erc8004-batch-row-num">${i + 1}</div>+ <div class="erc8004-batch-row-body">+ <div class="erc8004-batch-row-title">${esc(a.name || 'Agent ' + (i + 1))}</div>+ <div class="erc8004-muted erc8004-small">${esc((a.description || '').slice(0, 80))}</div>+ </div>+ <div class="erc8004-batch-row-status erc8004-muted" data-role="row-status">pending</div>+ </div>+ `,+ )+ .join('');+ };++ const handleFile = (file) => {+ if (!file) return;+ const reader = new FileReader();+ reader.onload = (ev) => {+ const text = ev.target.result;+ try {+ if (/\.json$/i.test(file.name)) {+ let parsed = JSON.parse(text);+ if (!Array.isArray(parsed)) parsed = [parsed];+ queue = parsed;+ } else {+ // CSV+ const lines = String(text).trim().split(/\r?\n/);+ const headers = lines[0].split(',').map((h) => h.trim());+ queue = lines+ .slice(1)+ .map((line) => {+ const values = line.split(',').map((v) => v.trim());+ const obj = {};+ headers.forEach((h, i) => (obj[h] = values[i] || ''));+ return {+ name: obj.name || obj.Name || '',+ description: obj.description || obj.Description || '',+ services: [+ {+ name: obj.serviceType || obj.type || 'web',+ endpoint: obj.endpoint || obj.url || '',+ },+ ],+ };+ })+ .filter((a) => a.name && a.services[0].endpoint);+ }+ renderPreview();+ } catch (err) {+ ctx.toast('Invalid file format: ' + err.message, true);+ }+ };+ reader.readAsText(file);+ };++ input.addEventListener('change', (e) => handleFile(e.target.files[0]));+ drop.addEventListener('dragover', (e) => {+ e.preventDefault();+ drop.classList.add('erc8004-file-drop--active');+ });+ drop.addEventListener('dragleave', () => drop.classList.remove('erc8004-file-drop--active'));+ drop.addEventListener('drop', (e) => {+ e.preventDefault();+ drop.classList.remove('erc8004-file-drop--active');+ handleFile(e.dataTransfer.files[0]);+ });++ body.querySelector('[data-role="clear"]').addEventListener('click', () => {+ queue = [];+ input.value = '';+ renderPreview();+ });++ body.querySelector('[data-role="run"]').addEventListener('click', async () => {+ const wallet = ctx.getWallet();+ if (!wallet) {+ ctx.toast('Connect a wallet first.', true);+ return;+ }+ if (!queue.length) return;++ const chainId = ctx.getChainId();+ const chain = CHAIN_META[chainId];+ if (!chain.testnet) {+ const proceed = window.confirm(+ `Batch register ${queue.length} agents on ${chain.name}? This uses real ${chain.currency.symbol}.`,+ );+ if (!proceed) return;+ }++ // Ensure we're on the target chain+ if (wallet.chainId !== chainId) {+ try {+ await switchChain(chainId);+ wallet.chainId = chainId;+ } catch (err) {+ ctx.toast('Chain switch rejected: ' + err.message, true);+ return;+ }+ }++ const { signer } = await ensureWallet();+ const registry = getIdentityRegistry(chainId, signer);+ const identityAddr = REGISTRY_DEPLOYMENTS[chainId].identityRegistry;++ progress.style.display = '';+ let success = 0;+ let failed = 0;+ const rows = listEl.querySelectorAll('.erc8004-batch-row');++ for (let i = 0; i < queue.length; i++) {+ const a = queue[i];+ const pct = ((i + 1) / queue.length) * 100;+ bar.style.width = pct.toFixed(0) + '%';+ status.textContent = `Processing ${i + 1}/${queue.length}: ${a.name || 'Agent'}`;+ const rowStatus = rows[i]?.querySelector('[data-role="row-status"]');+ if (rowStatus) rowStatus.textContent = 'signing…';++ try {+ const json = {+ type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',+ name: a.name,+ description: a.description || '',+ services: a.services || [],+ active: true,+ registrations: [+ {+ agentId: 'PENDING',+ agentRegistry: `eip155:${chainId}:${identityAddr}`,+ },+ ],+ };+ const uri =+ 'data:application/json;base64,' ++ btoa(unescape(encodeURIComponent(JSON.stringify(json))));+ const tx = await registry['register(string)'](uri);+ if (rowStatus) rowStatus.textContent = 'confirming…';+ await tx.wait();+ success++;+ if (rowStatus) {+ rowStatus.innerHTML = `<a class="erc8004-link" href="${esc(+ txExplorerUrl(chainId, tx.hash),+ )}" target="_blank" rel="noopener">confirmed ↗</a>`;+ }+ } catch (err) {+ failed++;+ if (rowStatus) rowStatus.textContent = 'failed';+ if (err && (err.code === 'ACTION_REJECTED' || err.code === 4001)) {+ status.textContent = 'Batch cancelled by user.';+ break;+ }+ }+ }+ status.textContent = `Done! ${success} registered, ${failed} failed.`;+ ctx.toast(`Batch complete: ${success} registered.`, success === 0);+ });+}diff --git a/publish/src/erc8004/chain-edit.js b/publish/src/erc8004/chain-edit.jsnew file mode 100644index 000000000..bc1dc9cb5--- /dev/null+++ b/publish/src/erc8004/chain-edit.js@@ -0,0 +1,264 @@+/**+ * On-chain agent edit flow — /a/:chainId/:agentId/edit+ *+ * Loads the current manifest from tokenURI, verifies wallet ownership,+ * lets the user edit name/description/avatar, then re-pins the manifest+ * and calls setAgentURI on-chain.+ */++import { BrowserProvider, Contract } from 'ethers';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './abi.js';+import { CHAIN_META } from './chain-meta.js';+import { fetchAgentMetadata, findAvatar3D } from './queries.js';+import { buildRegistrationJSON, pinFile } from './agent-registry.js';+import { resolveURI } from '../ipfs.js';++const esc = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );++/**+ * Mount the chain-edit UI into `rootEl`.+ * @param {HTMLElement} rootEl+ * @param {number} chainId+ * @param {string|bigint} agentId+ */+export async function mountChainEdit(rootEl, chainId, agentId) {+ const chainMeta = CHAIN_META[chainId];+ if (!chainMeta) {+ rootEl.innerHTML = `<div class="ce-error">Chain ${chainId} is not supported.</div>`;+ return;+ }++ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment?.identityRegistry) {+ rootEl.innerHTML = `<div class="ce-error">No registry on chain ${chainId}.</div>`;+ return;+ }++ rootEl.innerHTML = renderShell(chainId, agentId, chainMeta);++ const statusEl = rootEl.querySelector('#ce-status');+ const formEl = rootEl.querySelector('#ce-form');+ const connectBtn = rootEl.querySelector('#ce-connect');+ const saveBtn = rootEl.querySelector('#ce-save');+ const viewerEl = rootEl.querySelector('#ce-viewer');++ setStatus(statusEl, 'Loading agent…');++ // ── 1. Load current manifest ───────────────────────────────────────────+ let currentManifest = null;+ let currentTokenURI = null;+ let currentGlbUrl = null;++ try {+ const { JsonRpcProvider } = await import('ethers');+ const provider = new JsonRpcProvider(chainMeta.rpcUrl, chainId);+ const registry = new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);+ currentTokenURI = await registry.tokenURI(agentId).catch(() => null);++ if (currentTokenURI) {+ const { ok, data } = await fetchAgentMetadata(currentTokenURI);+ if (ok && data) {+ currentManifest = data;+ const rawGlb = findAvatar3D(data);+ if (rawGlb) currentGlbUrl = await resolveURI(rawGlb).catch(() => rawGlb);+ }+ }+ } catch (err) {+ setStatus(statusEl, `Could not load agent: ${err.message}`, 'error');+ return;+ }++ // Pre-fill form+ const nameInput = rootEl.querySelector('#ce-name');+ const descInput = rootEl.querySelector('#ce-desc');+ nameInput.value = currentManifest?.name || '';+ descInput.value = currentManifest?.description || '';++ if (currentGlbUrl) {+ viewerEl.src = currentGlbUrl;+ viewerEl.removeAttribute('hidden');+ }++ setStatus(statusEl, 'Connect your wallet to edit.');+ formEl.removeAttribute('hidden');++ // ── 2. Wallet connect + ownership check ───────────────────────────────+ let signer = null;+ let connectedAddress = null;++ connectBtn.addEventListener('click', async () => {+ connectBtn.disabled = true;+ connectBtn.textContent = 'Connecting…';+ setStatus(statusEl, '');++ try {+ if (!window.ethereum) throw new Error('No wallet detected — install MetaMask.');+ const browserProvider = new BrowserProvider(window.ethereum);+ signer = await browserProvider.getSigner();+ connectedAddress = await signer.getAddress();++ // Verify chain+ const network = await browserProvider.getNetwork();+ const walletChainId = Number(network.chainId);+ if (walletChainId !== chainId) {+ try {+ await window.ethereum.request({+ method: 'wallet_switchEthereumChain',+ params: [{ chainId: '0x' + chainId.toString(16) }],+ });+ // Re-get signer after switch+ const switched = new BrowserProvider(window.ethereum);+ signer = await switched.getSigner();+ } catch {+ throw new Error(+ `Switch your wallet to ${chainMeta.name} (chainId ${chainId}) to edit this agent.`,+ );+ }+ }++ // Verify ownership+ const provider2 = signer.provider;+ const registry = new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider2);+ const owner = await registry.ownerOf(agentId).catch(() => null);++ if (!owner || owner.toLowerCase() !== connectedAddress.toLowerCase()) {+ throw new Error(`This wallet (${connectedAddress.slice(0, 6)}…) does not own agent #${agentId}.`);+ }++ connectBtn.textContent = `${connectedAddress.slice(0, 6)}…${connectedAddress.slice(-4)} ✓`;+ connectBtn.classList.add('ce-btn--connected');+ saveBtn.disabled = false;+ setStatus(statusEl, 'Ownership verified. Make your edits and save.');+ } catch (err) {+ connectBtn.disabled = false;+ connectBtn.textContent = 'Connect Wallet';+ setStatus(statusEl, err.message, 'error');+ }+ });++ // ── 3. GLB file picker preview ────────────────────────────────────────+ const glbInput = rootEl.querySelector('#ce-glb');+ let pendingGlbFile = null;++ glbInput.addEventListener('change', () => {+ const file = glbInput.files?.[0];+ if (!file) return;+ pendingGlbFile = file;+ const url = URL.createObjectURL(file);+ viewerEl.src = url;+ viewerEl.removeAttribute('hidden');+ });++ // ── 4. Save ───────────────────────────────────────────────────────────+ saveBtn.addEventListener('click', async () => {+ if (!signer) return;+ saveBtn.disabled = true;+ saveBtn.textContent = 'Saving…';+ setStatus(statusEl, '');++ try {+ const name = nameInput.value.trim() || currentManifest?.name || `Agent #${agentId}`;+ const description = descInput.value.trim();++ // Pin new GLB if provided+ let glbUrl = currentGlbUrl;+ if (pendingGlbFile) {+ setStatus(statusEl, 'Uploading new avatar…');+ glbUrl = await pinFile(pendingGlbFile);+ }++ // Rebuild manifest preserving existing services + fields+ const updatedManifest = {+ ...(currentManifest || {}),+ name,+ description,+ };++ if (glbUrl) {+ // Update avatar service in-place if present, else use buildRegistrationJSON logic+ const services = Array.isArray(updatedManifest.services) ? [...updatedManifest.services] : [];+ const avatarIdx = services.findIndex((s) => s.name === 'avatar' || s.name === 'avatar-3d');+ const avatarEntry = { name: 'avatar', endpoint: glbUrl, version: 'gltf-2.0' };+ if (avatarIdx >= 0) services[avatarIdx] = avatarEntry;+ else services.unshift(avatarEntry);+ updatedManifest.services = services;+ updatedManifest.body = { uri: glbUrl, format: 'gltf-binary' };+ }++ // Pin the updated manifest+ setStatus(statusEl, 'Pinning updated manifest…');+ const jsonBlob = new Blob([JSON.stringify(updatedManifest, null, 2)], {+ type: 'application/json',+ });+ const newManifestUrl = await pinFile(jsonBlob);++ // Call setAgentURI on-chain+ setStatus(statusEl, 'Submitting transaction…');+ const registry = new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, signer);+ const tx = await registry.setAgentURI(agentId, newManifestUrl);+ setStatus(statusEl, `Transaction submitted: ${tx.hash.slice(0, 10)}… — waiting for confirmation.`);+ await tx.wait();++ setStatus(statusEl, 'Saved! Agent updated on-chain.', 'success');+ saveBtn.textContent = 'Saved ✓';++ // Link to the agent page+ const agentPageUrl = `/a/${chainId}/${agentId}`;+ setStatus(+ statusEl,+ `Agent updated. <a href="${agentPageUrl}" class="ce-link">View agent →</a>`,+ 'success',+ );+ } catch (err) {+ setStatus(statusEl, err.message, 'error');+ saveBtn.disabled = false;+ saveBtn.textContent = 'Save Changes';+ }+ });+}++function setStatus(el, html, type = '') {+ el.innerHTML = html;+ el.className = `ce-status${type ? ` ce-status--${type}` : ''}`;+}++function renderShell(chainId, agentId, chainMeta) {+ return `+ <h1 class="ce-title">Edit Agent <span class="ce-chain-label">${esc(chainMeta.shortName)} #${agentId}</span></h1>++ <model-viewer+ id="ce-viewer"+ camera-controls+ auto-rotate+ rotation-per-second="15deg"+ exposure="0.9"+ shadow-intensity="0.4"+ interaction-prompt="none"+ class="ce-viewer"+ hidden+ alt="Agent avatar preview"+ ></model-viewer>++ <div id="ce-status" class="ce-status">Loading…</div>++ <form id="ce-form" hidden>+ <label class="ce-label" for="ce-name">Name</label>+ <input id="ce-name" class="ce-input" type="text" maxlength="80" placeholder="Agent name" />++ <label class="ce-label" for="ce-desc">Description</label>+ <textarea id="ce-desc" class="ce-input ce-textarea" rows="3" maxlength="500" placeholder="What does this agent do?"></textarea>++ <label class="ce-label" for="ce-glb">Avatar GLB <span class="ce-optional">(optional — replaces current)</span></label>+ <input id="ce-glb" class="ce-input ce-file" type="file" accept=".glb,.gltf" />++ <div class="ce-actions">+ <button type="button" id="ce-connect" class="ce-btn ce-btn--ghost">Connect Wallet</button>+ <button type="button" id="ce-save" class="ce-btn ce-btn--primary" disabled>Save Changes</button>+ </div>+ </form>+ `;+}diff --git a/publish/src/erc8004/chain-meta.js b/publish/src/erc8004/chain-meta.jsnew file mode 100644index 000000000..750008e2a--- /dev/null+++ b/publish/src/erc8004/chain-meta.js@@ -0,0 +1,285 @@+/**+ * Human-readable metadata for every chain in REGISTRY_DEPLOYMENTS.+ *+ * Used by:+ * - Chain switcher (wallet_switchEthereumChain + wallet_addEthereumChain fallback)+ * - Agent card "View on explorer" links+ * - Chain dropdown labels+ *+ * Public RPCs below are safe defaults. They work out-of-the-box for+ * wallet_addEthereumChain but may rate-limit on heavy reads — use user-supplied+ * wallet provider for production reads.+ */++import { REGISTRY_DEPLOYMENTS } from './abi.js';++/** @type {Record<number, { name: string, shortName: string, currency: { name: string, symbol: string, decimals: number }, rpcUrl: string, explorer: string, testnet: boolean }>} */+export const CHAIN_META = {+ // ── Mainnets ──────────────────────────────────────────────────────────+ 1: {+ name: 'Ethereum',+ shortName: 'ETH',+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://ethereum-rpc.publicnode.com',+ explorer: 'https://etherscan.io',+ testnet: false,+ },+ 10: {+ name: 'Optimism',+ shortName: 'OP',+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://mainnet.optimism.io',+ explorer: 'https://optimistic.etherscan.io',+ testnet: false,+ },+ 56: {+ name: 'BNB Chain',+ shortName: 'BSC',+ currency: { name: 'BNB', symbol: 'BNB', decimals: 18 },+ rpcUrl: 'https://bsc-dataseed.bnbchain.org',+ explorer: 'https://bscscan.com',+ testnet: false,+ },+ 100: {+ name: 'Gnosis',+ shortName: 'GNO',+ currency: { name: 'xDAI', symbol: 'xDAI', decimals: 18 },+ rpcUrl: 'https://rpc.gnosischain.com',+ explorer: 'https://gnosisscan.io',+ testnet: false,+ },+ 137: {+ name: 'Polygon',+ shortName: 'POL',+ currency: { name: 'POL', symbol: 'POL', decimals: 18 },+ rpcUrl: 'https://polygon-rpc.com',+ explorer: 'https://polygonscan.com',+ testnet: false,+ },+ 250: {+ name: 'Fantom',+ shortName: 'FTM',+ currency: { name: 'Fantom', symbol: 'FTM', decimals: 18 },+ rpcUrl: 'https://rpc.ftm.tools',+ explorer: 'https://ftmscan.com',+ testnet: false,+ },+ 324: {+ name: 'zkSync Era',+ shortName: 'zkSync',+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://mainnet.era.zksync.io',+ explorer: 'https://explorer.zksync.io',+ testnet: false,+ },+ 1284: {+ name: 'Moonbeam',+ shortName: 'GLMR',+ currency: { name: 'Glimmer', symbol: 'GLMR', decimals: 18 },+ rpcUrl: 'https://rpc.api.moonbeam.network',+ explorer: 'https://moonbeam.moonscan.io',+ testnet: false,+ },+ 5000: {+ name: 'Mantle',+ shortName: 'MNT',+ currency: { name: 'Mantle', symbol: 'MNT', decimals: 18 },+ rpcUrl: 'https://rpc.mantle.xyz',+ explorer: 'https://explorer.mantle.xyz',+ testnet: false,+ },+ 8453: {+ name: 'Base',+ shortName: 'Base',+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://mainnet.base.org',+ explorer: 'https://basescan.org',+ testnet: false,+ },+ 42161: {+ name: 'Arbitrum One',+ shortName: 'ARB',+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://arb1.arbitrum.io/rpc',+ explorer: 'https://arbiscan.io',+ testnet: false,+ },+ 42220: {+ name: 'Celo',+ shortName: 'CELO',+ currency: { name: 'Celo', symbol: 'CELO', decimals: 18 },+ rpcUrl: 'https://forno.celo.org',+ explorer: 'https://celoscan.io',+ testnet: false,+ },+ 43114: {+ name: 'Avalanche',+ shortName: 'AVAX',+ currency: { name: 'Avax', symbol: 'AVAX', decimals: 18 },+ rpcUrl: 'https://api.avax.network/ext/bc/C/rpc',+ explorer: 'https://snowtrace.io',+ testnet: false,+ },+ 59144: {+ name: 'Linea',+ shortName: 'Linea',+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://rpc.linea.build',+ explorer: 'https://lineascan.build',+ testnet: false,+ },+ 534352: {+ name: 'Scroll',+ shortName: 'Scroll',+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://rpc.scroll.io',+ explorer: 'https://scrollscan.com',+ testnet: false,+ },++ // ── Testnets ──────────────────────────────────────────────────────────+ 97: {+ name: 'BSC Testnet',+ shortName: 'BSCt',+ currency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 },+ rpcUrl: 'https://bsc-testnet-rpc.publicnode.com',+ explorer: 'https://testnet.bscscan.com',+ testnet: true,+ },+ 11155111: {+ name: 'Ethereum Sepolia',+ shortName: 'Sep',+ currency: { name: 'SepETH', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://ethereum-sepolia-rpc.publicnode.com',+ explorer: 'https://sepolia.etherscan.io',+ testnet: true,+ },+ 84532: {+ name: 'Base Sepolia',+ shortName: 'BaseSep',+ currency: { name: 'SepETH', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://sepolia.base.org',+ explorer: 'https://sepolia.basescan.org',+ testnet: true,+ },+ 421614: {+ name: 'Arbitrum Sepolia',+ shortName: 'ArbSep',+ currency: { name: 'SepETH', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://sepolia-rollup.arbitrum.io/rpc',+ explorer: 'https://sepolia.arbiscan.io',+ testnet: true,+ },+ 11155420: {+ name: 'Optimism Sepolia',+ shortName: 'OpSep',+ currency: { name: 'SepETH', symbol: 'ETH', decimals: 18 },+ rpcUrl: 'https://sepolia.optimism.io',+ explorer: 'https://sepolia-optimism.etherscan.io',+ testnet: true,+ },+ 80002: {+ name: 'Polygon Amoy',+ shortName: 'Amoy',+ currency: { name: 'POL', symbol: 'POL', decimals: 18 },+ rpcUrl: 'https://rpc-amoy.polygon.technology',+ explorer: 'https://amoy.polygonscan.com',+ testnet: true,+ },+ 43113: {+ name: 'Avalanche Fuji',+ shortName: 'Fuji',+ currency: { name: 'Avax', symbol: 'AVAX', decimals: 18 },+ rpcUrl: 'https://api.avax-test.network/ext/bc/C/rpc',+ explorer: 'https://testnet.snowtrace.io',+ testnet: true,+ },+};++export const DEFAULT_CHAIN_ID = 8453; // Base mainnet++/** @returns {number[]} All chain IDs where both CHAIN_META and REGISTRY_DEPLOYMENTS exist. */+export function supportedChainIds() {+ return Object.keys(CHAIN_META)+ .map(Number)+ .filter((id) => REGISTRY_DEPLOYMENTS[id]);+}++/**+ * Same set as supportedChainIds() but split into mainnets and testnets.+ * @returns {{ mainnets: number[], testnets: number[] }}+ */+export function supportedChainIdsGrouped() {+ const mainnets = [];+ const testnets = [];+ for (const id of supportedChainIds()) {+ (CHAIN_META[id]?.testnet ? testnets : mainnets).push(id);+ }+ return { mainnets, testnets };+}++/** @param {number} chainId */+export function chainIdHex(chainId) {+ return '0x' + chainId.toString(16);+}++/**+ * Switch the injected wallet to `chainId`. If the chain isn't known to the+ * wallet (error 4902), add it via wallet_addEthereumChain then retry switch.+ *+ * @param {number} chainId+ * @param {any} [provider] Optional EIP-1193 provider (defaults to window.ethereum)+ */+export async function switchChain(chainId, provider) {+ const eth = provider || window.ethereum;+ if (!eth) throw new Error('No wallet provider available');++ const meta = CHAIN_META[chainId];+ if (!meta) throw new Error(`Unknown chainId ${chainId}`);+ const hex = chainIdHex(chainId);++ try {+ await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: hex }] });+ } catch (err) {+ if (+ err &&+ (err.code === 4902 ||+ /Unrecognized chain|not added|add.*chain/i.test(err.message || ''))+ ) {+ await eth.request({+ method: 'wallet_addEthereumChain',+ params: [+ {+ chainId: hex,+ chainName: meta.name,+ nativeCurrency: meta.currency,+ rpcUrls: [meta.rpcUrl],+ blockExplorerUrls: [meta.explorer],+ },+ ],+ });+ // wallet_addEthereumChain usually auto-switches, but force it to be safe.+ await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: hex }] });+ } else {+ throw err;+ }+ }+}++/** @param {number} chainId @param {string} txHash */+export function txExplorerUrl(chainId, txHash) {+ const m = CHAIN_META[chainId];+ return m ? `${m.explorer}/tx/${txHash}` : '';+}++/** @param {number} chainId @param {string} address */+export function addressExplorerUrl(chainId, address) {+ const m = CHAIN_META[chainId];+ return m ? `${m.explorer}/address/${address}` : '';+}++/** @param {number} chainId @param {string} contract @param {string|number} tokenId */+export function tokenExplorerUrl(chainId, contract, tokenId) {+ const m = CHAIN_META[chainId];+ return m ? `${m.explorer}/token/${contract}?a=${tokenId}` : '';+}diff --git a/publish/src/erc8004/chains.js b/publish/src/erc8004/chains.jsnew file mode 100644index 000000000..af6384079--- /dev/null+++ b/publish/src/erc8004/chains.js@@ -0,0 +1,326 @@+/**+ * Chain metadata for the ERC-8004 creator UI.+ *+ * Only chains that appear in REGISTRY_DEPLOYMENTS should be listed here.+ * Default: BSC Testnet (chainId 97) — cheapest to experiment on.+ */++import { REGISTRY_DEPLOYMENTS } from './abi.js';++/**+ * @typedef {Object} ChainInfo+ * @property {number} chainId+ * @property {string} name Display name shown in the selector.+ * @property {string} short Short label (e.g. "BSC", "Base").+ * @property {string} symbol Native token symbol.+ * @property {string} explorer Block explorer base URL (no trailing slash).+ * @property {string} rpc Public RPC URL (used for read-only calls).+ * @property {'mainnet'|'testnet'} kind+ */++/** @type {Record<number, ChainInfo>} */+export const CHAIN_INFO = {+ // ── Mainnets ──────────────────────────────────────────────────────────+ 1: {+ chainId: 1,+ name: 'Ethereum',+ short: 'ETH',+ symbol: 'ETH',+ explorer: 'https://etherscan.io',+ rpc: 'https://eth.llamarpc.com',+ kind: 'mainnet',+ },+ 10: {+ chainId: 10,+ name: 'Optimism',+ short: 'OP',+ symbol: 'ETH',+ explorer: 'https://optimistic.etherscan.io',+ rpc: 'https://mainnet.optimism.io',+ kind: 'mainnet',+ },+ 56: {+ chainId: 56,+ name: 'BNB Chain',+ short: 'BSC',+ symbol: 'BNB',+ explorer: 'https://bscscan.com',+ rpc: 'https://bsc-dataseed.bnbchain.org',+ kind: 'mainnet',+ },+ 100: {+ chainId: 100,+ name: 'Gnosis',+ short: 'GNO',+ symbol: 'xDAI',+ explorer: 'https://gnosisscan.io',+ rpc: 'https://rpc.gnosischain.com',+ kind: 'mainnet',+ },+ 137: {+ chainId: 137,+ name: 'Polygon',+ short: 'MATIC',+ symbol: 'POL',+ explorer: 'https://polygonscan.com',+ rpc: 'https://polygon-rpc.com',+ kind: 'mainnet',+ },+ 250: {+ chainId: 250,+ name: 'Fantom',+ short: 'FTM',+ symbol: 'FTM',+ explorer: 'https://ftmscan.com',+ rpc: 'https://rpc.ftm.tools',+ kind: 'mainnet',+ },+ 324: {+ chainId: 324,+ name: 'zkSync Era',+ short: 'zkSync',+ symbol: 'ETH',+ explorer: 'https://explorer.zksync.io',+ rpc: 'https://mainnet.era.zksync.io',+ kind: 'mainnet',+ },+ 1284: {+ chainId: 1284,+ name: 'Moonbeam',+ short: 'GLMR',+ symbol: 'GLMR',+ explorer: 'https://moonscan.io',+ rpc: 'https://rpc.api.moonbeam.network',+ kind: 'mainnet',+ },+ 5000: {+ chainId: 5000,+ name: 'Mantle',+ short: 'MNT',+ symbol: 'MNT',+ explorer: 'https://explorer.mantle.xyz',+ rpc: 'https://rpc.mantle.xyz',+ kind: 'mainnet',+ },+ 8453: {+ chainId: 8453,+ name: 'Base',+ short: 'BASE',+ symbol: 'ETH',+ explorer: 'https://basescan.org',+ rpc: 'https://mainnet.base.org',+ kind: 'mainnet',+ },+ 42161: {+ chainId: 42161,+ name: 'Arbitrum One',+ short: 'ARB',+ symbol: 'ETH',+ explorer: 'https://arbiscan.io',+ rpc: 'https://arb1.arbitrum.io/rpc',+ kind: 'mainnet',+ },+ 42220: {+ chainId: 42220,+ name: 'Celo',+ short: 'CELO',+ symbol: 'CELO',+ explorer: 'https://celoscan.io',+ rpc: 'https://forno.celo.org',+ kind: 'mainnet',+ },+ 43114: {+ chainId: 43114,+ name: 'Avalanche',+ short: 'AVAX',+ symbol: 'AVAX',+ explorer: 'https://snowtrace.io',+ rpc: 'https://api.avax.network/ext/bc/C/rpc',+ kind: 'mainnet',+ },+ 59144: {+ chainId: 59144,+ name: 'Linea',+ short: 'LINEA',+ symbol: 'ETH',+ explorer: 'https://lineascan.build',+ rpc: 'https://rpc.linea.build',+ kind: 'mainnet',+ },+ 534352: {+ chainId: 534352,+ name: 'Scroll',+ short: 'SCR',+ symbol: 'ETH',+ explorer: 'https://scrollscan.com',+ rpc: 'https://rpc.scroll.io',+ kind: 'mainnet',+ },++ // ── Testnets ──────────────────────────────────────────────────────────+ 97: {+ chainId: 97,+ name: 'BSC Testnet',+ short: 'tBSC',+ symbol: 'tBNB',+ explorer: 'https://testnet.bscscan.com',+ rpc: 'https://data-seed-prebsc-1-s1.bnbchain.org:8545',+ kind: 'testnet',+ },+ 11155111: {+ chainId: 11155111,+ name: 'Ethereum Sepolia',+ short: 'SEP',+ symbol: 'ETH',+ explorer: 'https://sepolia.etherscan.io',+ rpc: 'https://rpc.sepolia.org',+ kind: 'testnet',+ },+ 84532: {+ chainId: 84532,+ name: 'Base Sepolia',+ short: 'baseSep',+ symbol: 'ETH',+ explorer: 'https://sepolia.basescan.org',+ rpc: 'https://sepolia.base.org',+ kind: 'testnet',+ },+ 421614: {+ chainId: 421614,+ name: 'Arbitrum Sepolia',+ short: 'arbSep',+ symbol: 'ETH',+ explorer: 'https://sepolia.arbiscan.io',+ rpc: 'https://sepolia-rollup.arbitrum.io/rpc',+ kind: 'testnet',+ },+ 11155420: {+ chainId: 11155420,+ name: 'Optimism Sepolia',+ short: 'opSep',+ symbol: 'ETH',+ explorer: 'https://sepolia-optimism.etherscan.io',+ rpc: 'https://sepolia.optimism.io',+ kind: 'testnet',+ },+ 80002: {+ chainId: 80002,+ name: 'Polygon Amoy',+ short: 'Amoy',+ symbol: 'POL',+ explorer: 'https://amoy.polygonscan.com',+ rpc: 'https://rpc-amoy.polygon.technology',+ kind: 'testnet',+ },+ 43113: {+ chainId: 43113,+ name: 'Avalanche Fuji',+ short: 'Fuji',+ symbol: 'AVAX',+ explorer: 'https://testnet.snowtrace.io',+ rpc: 'https://api.avax-test.network/ext/bc/C/rpc',+ kind: 'testnet',+ },+};++/** Default chain presented to new users. */+export const DEFAULT_CHAIN_ID = 97; // BSC Testnet++/**+ * @param {number} chainId+ * @returns {ChainInfo|null}+ */+export function getChainInfo(chainId) {+ return CHAIN_INFO[chainId] || null;+}++/**+ * Chains grouped as [mainnets, testnets], in the order users see them in the+ * selector. Only chains with an ERC-8004 deployment are returned.+ * @returns {{mainnets: ChainInfo[], testnets: ChainInfo[]}}+ */+export function supportedChainsGrouped() {+ const mainnets = [];+ const testnets = [];+ for (const [id, info] of Object.entries(CHAIN_INFO)) {+ const chainId = Number(id);+ if (!REGISTRY_DEPLOYMENTS[chainId]?.identityRegistry) continue;+ (info.kind === 'mainnet' ? mainnets : testnets).push(info);+ }+ mainnets.sort((a, b) => a.name.localeCompare(b.name));+ testnets.sort((a, b) => a.name.localeCompare(b.name));+ return { mainnets, testnets };+}++/**+ * Convert a chainId to the 0x-prefixed hex form required by+ * wallet_switchEthereumChain / wallet_addEthereumChain.+ * @param {number} chainId+ * @returns {string}+ */+export function toHexChainId(chainId) {+ return '0x' + Number(chainId).toString(16);+}++/**+ * Ask the connected wallet to switch chains, adding the chain definition if+ * the wallet hasn't seen it before.+ *+ * Throws if the user rejects or no wallet is present.+ * @param {number} chainId+ */+export async function requestSwitchChain(chainId) {+ if (!window.ethereum?.request) {+ throw new Error('No wallet available to switch chains.');+ }+ const info = getChainInfo(chainId);+ if (!info) throw new Error(`Unknown chain: ${chainId}`);++ const hex = toHexChainId(chainId);+ try {+ await window.ethereum.request({+ method: 'wallet_switchEthereumChain',+ params: [{ chainId: hex }],+ });+ } catch (err) {+ // 4902 = chain not added to the wallet yet.+ if (err?.code === 4902 || /unrecognized chain/i.test(err?.message || '')) {+ await window.ethereum.request({+ method: 'wallet_addEthereumChain',+ params: [+ {+ chainId: hex,+ chainName: info.name,+ nativeCurrency: { name: info.symbol, symbol: info.symbol, decimals: 18 },+ rpcUrls: [info.rpc],+ blockExplorerUrls: [info.explorer],+ },+ ],+ });+ } else {+ throw err;+ }+ }+}++/**+ * Build an explorer URL for a tx / address / token given a chainId.+ * @param {number} chainId+ * @param {'tx'|'address'|'token'} kind+ * @param {string|number} value+ * @returns {string}+ */+export function explorerUrl(chainId, kind, value) {+ const info = getChainInfo(chainId);+ if (!info) return '';+ switch (kind) {+ case 'tx':+ return `${info.explorer}/tx/${value}`;+ case 'address':+ return `${info.explorer}/address/${value}`;+ case 'token':+ return `${info.explorer}/token/${value}`;+ default:+ return info.explorer;+ }+}diff --git a/publish/src/erc8004/default-avatars.js b/publish/src/erc8004/default-avatars.jsnew file mode 100644index 000000000..af17897f8--- /dev/null+++ b/publish/src/erc8004/default-avatars.js@@ -0,0 +1,37 @@+/**+ * Pre-pinned default avatars for ERC-8004 deploy flow.+ *+ * Populated entries here become selectable in the "Default avatar" option of+ * the register-ui Step 3 wizard. Each entry:+ * - id stable key (used for radio selection + analytics)+ * - name display label+ * - description short hint under the card+ * - url stable GLB URL (ipfs:// preferred — CID-addressable + free)+ * - thumbnailUrl 2D poster URL used both as the card preview AND the+ * ERC-721 `image` field, skipping client-side re-render+ *+ * Leave the array empty until we've pinned real assets — the wizard gracefully+ * hides the option when `DEFAULT_AVATARS.length === 0`.+ *+ * To add one:+ * 1. Pin the GLB + a 512x512 PNG thumbnail to IPFS (Pinata / R2 / nft.storage).+ * 2. Append an entry below with both `ipfs://<cid>` URLs.+ * 3. Verify the CIDs resolve via https://ipfs.io/ipfs/<cid>.+ * 4. Prettier + `npm run build` — done.+ */++/**+ * @typedef {object} DefaultAvatar+ * @property {string} id+ * @property {string} name+ * @property {string} description+ * @property {string} url GLB URL (ipfs:// or https://)+ * @property {string} thumbnailUrl PNG URL (ipfs:// or https://)+ */++/** @type {DefaultAvatar[]} */+export const DEFAULT_AVATARS = [];++export function getDefaultAvatar(id) {+ return DEFAULT_AVATARS.find((a) => a.id === id) || null;+}diff --git a/publish/src/erc8004/deploy-button.css b/publish/src/erc8004/deploy-button.cssnew file mode 100644index 000000000..5a3a899b7--- /dev/null+++ b/publish/src/erc8004/deploy-button.css@@ -0,0 +1,278 @@+/* deploy-button.css — scoped under .deploy-button-root */++.visually-hidden {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++.deploy-button-root {+ display: inline-flex;+ align-items: center;+ font-family: inherit;+}++/* ── Chain select + deploy row ───────────────────────────────────────────── */++.deploy-chain-row {+ display: inline-flex;+ align-items: center;+ gap: 0.5em;+ flex-wrap: wrap;+}++.deploy-chain-select {+ padding: 0.4em 0.65em;+ border: 1.5px solid #6c63ff;+ border-radius: 6px;+ background: transparent;+ color: #a89fff;+ font-family: inherit;+ font-size: 0.82rem;+ font-weight: 500;+ cursor: pointer;+ transition:+ background 0.15s,+ border-color 0.15s,+ color 0.15s;+ max-width: 12em;+}++.deploy-chain-select:hover:not(:disabled) {+ background: #6c63ff15;+ color: #fff;+ border-color: #a89fff;+}++.deploy-chain-select:focus-visible {+ outline: 2px solid #a89fff;+ outline-offset: 2px;+}++.deploy-chain-select:disabled {+ opacity: 0.6;+ cursor: progress;+}++.deploy-chain-select optgroup {+ color: #888;+ font-style: italic;+}++.deploy-chain-select option {+ background: #14141c;+ color: #e6e6e6;+ font-style: normal;+}++/* ── Deploy button ───────────────────────────────────────────────────────── */++.deploy-btn {+ display: inline-flex;+ align-items: center;+ gap: 0.4em;+ padding: 0.45em 1em;+ border: 1.5px solid #6c63ff;+ border-radius: 6px;+ background: transparent;+ color: #a89fff;+ font-size: 0.875rem;+ font-weight: 600;+ cursor: pointer;+ transition:+ background 0.15s,+ color 0.15s,+ border-color 0.15s;+ white-space: nowrap;+}++.deploy-btn:hover:not(:disabled) {+ background: #6c63ff22;+ border-color: #a89fff;+ color: #fff;+}++.deploy-btn--disabled,+.deploy-btn:disabled {+ opacity: 0.45;+ cursor: not-allowed;+ border-color: #555;+ color: #888;+}++/* ── Success chip ────────────────────────────────────────────────────────── */++.deploy-chip {+ display: inline-flex;+ align-items: center;+ gap: 0.4em;+ padding: 0.35em 0.85em;+ border-radius: 999px;+ font-size: 0.8rem;+ font-weight: 600;+ text-decoration: none;+ white-space: nowrap;+ transition: opacity 0.15s;+}++.deploy-chip--success {+ background: #0f2e1a;+ border: 1.5px solid #2a7a4a;+ color: #4ade80;+}++.deploy-chip--success:hover {+ opacity: 0.82;+}++/* ── Progress bar ────────────────────────────────────────────────────────── */++.deploy-progress {+ display: inline-flex;+ align-items: center;+ gap: 0.3em;+ font-size: 0.78rem;+ color: #aaa;+}++.progress-step {+ padding: 0.2em 0.5em;+ border-radius: 4px;+ transition:+ color 0.2s,+ background 0.2s;+}++.progress-step--pending {+ color: #555;+}++.progress-step--active {+ color: #fff;+ background: #6c63ff33;+ border: 1px solid #6c63ff88;+}++.progress-step--done {+ color: #4ade80;+}++.progress-sep {+ color: #444;+ font-size: 0.7em;+}++/* ── Error state ─────────────────────────────────────────────────────────── */++.deploy-error {+ display: inline-flex;+ align-items: center;+ gap: 0.6em;+ padding: 0.4em 0.75em;+ border: 1.5px solid #7a2a2a;+ border-radius: 6px;+ background: #2e0f0f;+ font-size: 0.8rem;+ color: #f87171;+ max-width: 400px;+}++.deploy-error-msg {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.deploy-action-btn {+ flex-shrink: 0;+ padding: 0.25em 0.7em;+ border: 1px solid #f87171;+ border-radius: 4px;+ background: transparent;+ color: #f87171;+ font-size: 0.8rem;+ cursor: pointer;+ transition: background 0.15s;+}++.deploy-action-btn:hover {+ background: #f8717122;+}++/* ── Tooltip ─────────────────────────────────────────────────────────────── */++.deploy-tooltip {+ margin-left: 0.5em;+ font-size: 0.75rem;+ color: #888;+ font-style: italic;+}++/* ── Light-mode overrides ────────────────────────────────────────────────── */++@media (prefers-color-scheme: light) {+ .deploy-chain-select {+ border-color: #4f46e5;+ color: #4f46e5;+ }++ .deploy-chain-select:hover:not(:disabled) {+ background: #4f46e511;+ color: #312e81;+ border-color: #4f46e5;+ }++ .deploy-chain-select option {+ background: #fff;+ color: #1e1b4b;+ }++ .deploy-btn {+ border-color: #4f46e5;+ color: #4f46e5;+ }++ .deploy-btn:hover:not(:disabled) {+ background: #4f46e511;+ border-color: #4f46e5;+ color: #312e81;+ }++ .deploy-chip--success {+ background: #ecfdf5;+ border-color: #22c55e;+ color: #15803d;+ }++ .deploy-progress {+ color: #555;+ }++ .progress-step--active {+ color: #312e81;+ background: #eef2ff;+ border-color: #818cf8;+ }++ .progress-step--done {+ color: #15803d;+ }++ .deploy-error {+ background: #fff1f2;+ border-color: #fca5a5;+ color: #b91c1c;+ }++ .deploy-action-btn {+ border-color: #b91c1c;+ color: #b91c1c;+ }+}diff --git a/publish/src/erc8004/deploy-button.js b/publish/src/erc8004/deploy-button.jsnew file mode 100644index 000000000..a3088feeb--- /dev/null+++ b/publish/src/erc8004/deploy-button.js@@ -0,0 +1,688 @@+/**+ * DeployButton — minimal "Deploy on-chain" UI for an agent's home page.+ *+ * Flow (matches the canonical 3-step pipeline used by /deploy):+ * 1. POST /api/agents/register-prep — server pins a manifest to IPFS,+ * returns { cid, metadataURI, prepId }.+ * The prepId is cached in localStorage so retries reuse the same prep+ * record (idempotency: never pin twice on a flaky network).+ * 2. registry.register(metadataURI) — user signs the on-chain mint.+ * 3. POST /api/agents/register-confirm — server verifies the receipt against+ * the prep record and upserts+ * agent_identities.{chain_id,+ * erc8004_agent_id, erc8004_registry,+ * registration_cid}.+ *+ * Distinct from register-ui.js (the full multi-tab wizard) — this is the+ * one-click chip surfaced on the agent's profile page for the owner.+ */++import { ensureWallet, getIdentityRegistry } from './agent-registry.js';+import { REGISTRY_DEPLOYMENTS } from './abi.js';+import {+ CHAIN_META,+ DEFAULT_CHAIN_ID,+ supportedChainIdsGrouped,+ switchChain,+ addressExplorerUrl,+} from './chain-meta.js';+import { runSolanaDeploy, solanaTxExplorerUrl, detectSolanaWallet } from './solana-deploy.js';+import { openVanityModal } from './vanity-modal.js';++const VANITY_LS_KEY = (agentId) => `3dagent:vanity-prefix:${agentId}`;+const VANITY_TTL_MS = 30 * 60 * 1000;++function _loadVanity(agentId) {+ try {+ const raw = localStorage.getItem(VANITY_LS_KEY(agentId));+ if (!raw) return '';+ const { prefix, ts } = JSON.parse(raw);+ if (Date.now() - ts > VANITY_TTL_MS) return '';+ return prefix || '';+ } catch { return ''; }+}+function _saveVanity(agentId, prefix) {+ try {+ if (prefix) localStorage.setItem(VANITY_LS_KEY(agentId), JSON.stringify({ prefix, ts: Date.now() }));+ else localStorage.removeItem(VANITY_LS_KEY(agentId));+ } catch {}+}++// Sentinel chain selections for non-EVM targets. The chain dropdown stores+// these as option values; _chainId may be a number (EVM chainId) or one of+// these strings.+const SOLANA_MAINNET = 'solana-mainnet';+const SOLANA_DEVNET = 'solana-devnet';+const SOLANA_LABELS = {+ [SOLANA_MAINNET]: 'Solana',+ [SOLANA_DEVNET]: 'Solana Devnet',+};+function _isSolana(id) {+ return id === SOLANA_MAINNET || id === SOLANA_DEVNET;+}+function _solanaNetwork(id) {+ return id === SOLANA_DEVNET ? 'devnet' : 'mainnet';+}++// Faucet links for testnets where users commonly run out of gas.+const FAUCETS = {+ 84532: 'https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet',+ 11155111: 'https://sepoliafaucet.com/',+ 421614: 'https://www.alchemy.com/faucets/arbitrum-sepolia',+ 11155420: 'https://app.optimism.io/faucet',+ 80002: 'https://faucet.polygon.technology/',+ 43113: 'https://faucet.avax.network/',+ 97: 'https://testnet.bnbchain.org/faucet-smart',+};++const WALLET_INSTALL_URL = 'https://metamask.io/download/';++function _hasWallet() {+ return typeof window !== 'undefined' && !!window.ethereum;+}++// localStorage key for caching the active prep record across retries.+function _prepCacheKey(agentId) {+ return `3dagent:deploy-prep:${agentId}`;+}++export class DeployButton {+ /**+ * @param {object} opts+ * @param {object} opts.agent Agent record. Required: id, name.+ * Optional but recommended for a+ * richer manifest: avatarId,+ * description, skills.+ * @param {HTMLElement} opts.container Where to mount.+ * @param {number} [opts.preferredChainId] Defaults to DEFAULT_CHAIN_ID.+ */+ constructor({ agent, container, preferredChainId = DEFAULT_CHAIN_ID }) {+ this._agent = agent;+ this._container = container;+ this._chainId = preferredChainId;+ this._root = null;+ }++ mount() {+ this._root = document.createElement('div');+ this._root.className = 'deploy-button-root';+ this._container.appendChild(this._root);+ this._render();+ }++ unmount() {+ if (this._root) {+ this._root.remove();+ this._root = null;+ }+ }++ _render() {+ if (!this._root) return;+ const agent = this._agent;++ if (agent.chainId && agent.txHash) {+ this._renderSuccessChip(agent.chainId, agent.txHash, agent.contractAddress);+ } else if (!_isSolana(this._chainId) && !REGISTRY_DEPLOYMENTS[this._chainId]) {+ this._renderDisabled('No registry on this chain');+ } else {+ this._renderDeployButton();+ }+ }++ _renderDeployButton() {+ const { mainnets, testnets } = supportedChainIdsGrouped();+ const evmOptionsFor = (ids) =>+ ids+ .map(+ (id) =>+ `<option value="${id}"${id === this._chainId ? ' selected' : ''}>${_esc(+ CHAIN_META[id]?.name || `Chain ${id}`,+ )}</option>`,+ )+ .join('');+ const solanaOptionFor = (id) =>+ `<option value="${id}"${id === this._chainId ? ' selected' : ''}>${_esc(SOLANA_LABELS[id])}</option>`;++ const showVanity = _isSolana(this._chainId);+ // Hydrate from localStorage on first render.+ if (this._vanityPrefix == null) this._vanityPrefix = _loadVanity(this._agent?.id) || '';++ this._root.innerHTML = `+ <div class="deploy-chain-row">+ <select class="deploy-chain-select" title="Choose chain to deploy to" aria-label="Target chain">+ <optgroup label="Mainnets">${evmOptionsFor(mainnets)}</optgroup>+ <optgroup label="Testnets">${evmOptionsFor(testnets)}</optgroup>+ <optgroup label="Solana (beta)">${solanaOptionFor(SOLANA_MAINNET)}${solanaOptionFor(SOLANA_DEVNET)}</optgroup>+ </select>+ <button class="deploy-btn" title="Deploy this agent as an ERC-8004 token on-chain">+ ⬢ Deploy on-chain+ </button>+ </div>+ <div class="deploy-vanity-link-row" style="${showVanity ? '' : 'display:none'};margin-top:4px;font-size:12px;">+ <button type="button" class="deploy-vanity-link"+ style="background:none;border:none;color:#0066cc;cursor:pointer;padding:0;font-size:12px;text-decoration:underline">+ ${this._vanityPrefix+ ? `✨ Vanity: <span style="font-family:monospace;font-weight:600">${_esc(this._vanityPrefix)}</span> · change`+ : '✨ Customize address (optional)'}+ </button>+ </div>+ `;++ const select = this._root.querySelector('.deploy-chain-select');+ const vanityLinkRow = this._root.querySelector('.deploy-vanity-link-row');+ const vanityLink = this._root.querySelector('.deploy-vanity-link');++ vanityLink.addEventListener('click', async () => {+ const chosen = await openVanityModal({+ agentName: this._agent?.name || '',+ initial: this._vanityPrefix || '',+ });+ if (chosen === null) return; // dismissed++ // Modal returns either a string (prefix to grind in browser) or+ // { prefix, secretKey } when the user pasted a CLI-ground keypair.+ if (chosen && typeof chosen === 'object') {+ this._vanityPrefix = chosen.prefix || '';+ this._preGroundSecretKey = chosen.secretKey;+ } else {+ this._vanityPrefix = chosen;+ this._preGroundSecretKey = null;+ }+ _saveVanity(this._agent?.id, this._vanityPrefix);+ this._renderDeployButton(); // re-render to update label+ });++ select.addEventListener('change', async (ev) => {+ const raw = ev.target.value;+ const newChainId = _isSolana(raw) ? raw : Number(raw);+ this._chainId = newChainId;+ vanityLinkRow.style.display = _isSolana(newChainId) ? '' : 'none';+ if (!_isSolana(newChainId) && _hasWallet()) {+ select.disabled = true;+ try {+ await switchChain(newChainId);+ } catch (err) {+ if (!_isUserRejection(err)) {+ console.warn('[deploy-button] switchChain failed:', err?.message);+ }+ } finally {+ select.disabled = false;+ }+ }+ });++ this._root+ .querySelector('.deploy-btn')+ .addEventListener('click', () => this._startDeploy());+ }++ _renderDisabled(reason) {+ this._root.innerHTML = `+ <button class="deploy-btn deploy-btn--disabled" disabled title="${_esc(reason)}">+ ⬢ Deploy on-chain+ </button>+ <span class="deploy-tooltip">${_esc(reason)}</span>+ `;+ }++ _renderSuccessChip(chainId, txHash, contractAddress, vanityPrefix) {+ let chainName, explorerUrl;+ if (_isSolana(chainId)) {+ const network = _solanaNetwork(chainId);+ chainName = SOLANA_LABELS[chainId];+ explorerUrl = solanaTxExplorerUrl(network, txHash);+ } else {+ const meta = CHAIN_META[chainId];+ chainName = meta ? meta.name : `Chain ${chainId}`;+ // Use the registry contract URL on the explorer — it's the most+ // universally available link, since some chains' explorers don't+ // surface tx hashes for arbitrary contracts.+ explorerUrl = contractAddress ? addressExplorerUrl(chainId, contractAddress) : '#';+ }+ const vanityNote = vanityPrefix+ ? ` · <span style="background:linear-gradient(90deg,#ffd54f,#ff8a65);color:#1a1a1a;padding:0 6px;border-radius:999px;font-weight:600">✨ ${_esc(vanityPrefix)}</span>`+ : '';+ this._root.innerHTML = `+ <a class="deploy-chip deploy-chip--success" href="${_esc(explorerUrl)}" target="_blank" rel="noopener noreferrer"+ aria-label="View this agent's registry on the ${_esc(chainName)} block explorer">+ ⬢ On-chain on ${_esc(chainName)}${vanityNote} · view on explorer+ </a>+ `;+ }++ _renderProgress(steps, activeIdx, extra) {+ const labels = steps.map((s, i) => {+ const cls = i < activeIdx ? 'done' : i === activeIdx ? 'active' : 'pending';+ return `<span class="progress-step progress-step--${cls}">${_esc(s)}</span>`;+ });+ const liveText = activeIdx < steps.length ? `${steps[activeIdx]}…` : 'Done';+ this._root.innerHTML = `+ <div class="deploy-progress" role="status" aria-live="polite" aria-label="Deployment progress">+ ${labels.join('<span class="progress-sep" aria-hidden="true">→</span>')}+ <span class="visually-hidden">${_esc(liveText)}</span>+ </div>+ <div class="deploy-progress-detail" aria-live="polite"+ style="margin-top:6px;font-size:12px;color:#555;font-family:ui-monospace,monospace;min-height:1.2em">+ ${extra?.text ? _esc(extra.text) : ''}+ </div>+ ${extra?.cancelable ? `<button class="deploy-cancel-btn" type="button"+ style="margin-top:4px;font-size:11px;background:none;border:1px solid #ccc;border-radius:4px;padding:2px 8px;cursor:pointer">cancel</button>` : ''}+ `;+ if (extra?.onCancel) {+ const cb = this._root.querySelector('.deploy-cancel-btn');+ if (cb) cb.addEventListener('click', extra.onCancel);+ }+ }++ _renderError(msg, action) {+ const actionHtml = action+ ? `<button class="deploy-action-btn">${_esc(action.label)}</button>`+ : '<button class="deploy-action-btn deploy-action-btn--reset">Try again</button>';+ this._root.innerHTML = `+ <div class="deploy-error" role="alert">+ <span class="deploy-error-msg">${_esc(msg)}</span>+ ${actionHtml}+ </div>+ `;+ const btn = this._root.querySelector('.deploy-action-btn');+ if (action) {+ btn.addEventListener('click', action.handler);+ } else {+ btn.addEventListener('click', () => this._renderDeployButton());+ }+ }++ // ─── Deploy state machine ──────────────────────────────────────────────++ async _startSolanaDeploy() {+ if (!detectSolanaWallet()) {+ this._renderError('No Solana wallet detected. Install Phantom to continue.', {+ label: 'Install Phantom',+ handler: () => window.open('https://phantom.app', '_blank', 'noopener'),+ });+ return;+ }++ const agent = this._agent;+ if (!agent?.id) {+ this._renderError('This agent is missing an ID — cannot deploy.');+ return;+ }++ const network = _solanaNetwork(this._chainId);+ const vanityPrefix = (this._vanityPrefix || '').trim();+ const preGround = this._preGroundSecretKey || null;+ const willGrind = vanityPrefix && !preGround;+ const steps = preGround+ ? ['Loading pre-ground keypair', 'Sign tx', 'Confirming on-chain', 'Saving']+ : willGrind+ ? ['Grinding vanity address', 'Sign tx', 'Confirming on-chain', 'Saving']+ : ['Connecting wallet', 'Sign tx', 'Confirming on-chain', 'Saving'];+ const abort = new AbortController();+ this._renderProgress(steps, 0, willGrind ? {+ text: `searching for "${vanityPrefix}…"`,+ cancelable: true,+ onCancel: () => abort.abort(),+ } : preGround ? {+ text: `using CLI-ground keypair${vanityPrefix ? ` for "${vanityPrefix}…"` : ''}`,+ } : undefined);++ let result;+ try {+ result = await runSolanaDeploy({+ agent,+ network,+ vanity: (vanityPrefix || preGround) ? {+ prefix: vanityPrefix || undefined,+ preGroundSecretKey: preGround || undefined,+ signal: abort.signal,+ onProgress: willGrind ? ({ attempts, rate, eta }) => {+ const detail = this._root.querySelector('.deploy-progress-detail');+ if (detail) {+ detail.textContent =+ `🔍 "${vanityPrefix}…" ${attempts.toLocaleString()} tries · ${Math.round(rate).toLocaleString()}/s · eta ${eta}`;+ }+ } : undefined,+ } : undefined,+ });+ this._renderProgress(steps, 1);+ this._renderProgress(steps, 3);+ } catch (err) {+ if (_isUserRejection(err) || err?.name === 'AbortError') return this._renderDeployButton();+ if (err.code === 'forbidden') {+ this._renderError(+ 'Your Solana wallet is not linked to this account. Sign in with your Solana wallet first.',+ {+ label: 'Open wallet sign-in',+ handler: () => (window.location.href = '/login.html'),+ },+ );+ return;+ }+ if (err.code === 'payment_required') {+ this._renderError(+ `${err.message || 'Paid plan required'} — upgrade to use 5+ character vanity prefixes.`,+ {+ label: 'View plans',+ handler: () => (window.location.href = '/billing.html'),+ },+ );+ return;+ }+ this._renderError(`Solana deploy failed: ${_humanError(err)}`);+ return;+ }++ this._agent.chainId = this._chainId;+ this._agent.txHash = result.txSignature;+ this._agent.contractAddress = result.assetPubkey;+ _saveVanity(this._agent?.id, ''); // clear after successful deploy+ this._preGroundSecretKey = null;+ this._renderSuccessChip(this._chainId, result.txSignature, result.assetPubkey, result.vanityPrefix);+ }++ async _startDeploy() {+ if (_isSolana(this._chainId)) return this._startSolanaDeploy();++ if (!_hasWallet()) {+ this._renderError('No wallet detected. Install one to deploy on-chain.', {+ label: 'Install MetaMask',+ handler: () => window.open(WALLET_INSTALL_URL, '_blank', 'noopener'),+ });+ return;+ }++ const agent = this._agent;+ if (!agent?.id) {+ this._renderError('This agent is missing an ID — cannot deploy.');+ return;+ }+ if (!agent.avatarId && !agent.avatar_id) {+ this._renderError('This agent has no avatar attached. Add a body before deploying.', {+ label: 'Open editor',+ handler: () =>+ (window.location.href = `/app?agent=${encodeURIComponent(agent.id)}`),+ });+ return;+ }++ const steps = ['Preparing manifest', 'Sign tx', 'Confirming on-chain', 'Saving'];+ this._renderProgress(steps, 0);++ // ── Step 0: prep + IPFS pin ────────────────────────────────────────+ // Reuse a recent prep record so retries don't re-pin and don't waste+ // time. Server expires prep records after 1h.+ let prep;+ try {+ prep = await this._getOrCreatePrep();+ } catch (err) {+ this._renderError(`Could not prepare manifest: ${err.message}`);+ return;+ }++ // ── Connect wallet on the selected chain ───────────────────────────+ let signer, walletChainId;+ try {+ ({ signer, chainId: walletChainId } = await ensureWallet());+ } catch (err) {+ if (_isUserRejection(err)) return this._renderDeployButton();+ this._renderError(`Wallet connection failed: ${_humanError(err)}`);+ return;+ }++ if (walletChainId !== this._chainId) {+ const targetName = CHAIN_META[this._chainId]?.name || `chain ${this._chainId}`;+ this._renderError(`Wallet is on a different network. Switch to ${targetName}.`, {+ label: `Switch to ${targetName}`,+ handler: async () => {+ try {+ await switchChain(this._chainId);+ this._renderDeployButton();+ } catch (e) {+ if (_isUserRejection(e)) return this._renderDeployButton();+ this._renderError(`Network switch failed: ${_humanError(e)}`);+ }+ },+ });+ return;+ }++ const deployment = REGISTRY_DEPLOYMENTS[walletChainId];+ if (!deployment?.identityRegistry) {+ this._renderDisabled('No ERC-8004 registry deployed on this chain');+ return;+ }++ // ── Step 1: sign tx ────────────────────────────────────────────────+ this._renderProgress(steps, 1);+ const registry = getIdentityRegistry(walletChainId, signer);+ let tx;+ try {+ tx = await registry['register(string)'](prep.metadataURI);+ } catch (err) {+ this._handleSignError(err, walletChainId);+ return;+ }++ // ── Step 2: wait for confirmation ──────────────────────────────────+ this._renderProgress(steps, 2);+ let receipt;+ try {+ receipt = await tx.wait();+ } catch (err) {+ this._renderError(`Transaction reverted: ${_humanError(err)}`);+ return;+ }+ if (receipt?.status !== 1) {+ this._renderError('Transaction failed on-chain.');+ return;+ }++ // Pull the agentId out of the Registered event so the confirm call+ // can cross-check it against the on-chain receipt server-side.+ const onchainAgentId = _parseRegisteredAgentId(receipt, registry);+ if (onchainAgentId == null) {+ this._renderError(+ 'Could not parse Registered event from the receipt. The tx is on-chain — please retry "Save".',+ {+ label: 'Retry save',+ handler: () =>+ this._confirmAndFinish(prep, walletChainId, tx, null, deployment),+ },+ );+ return;+ }++ // ── Step 3: server-side confirm (verify + upsert) ──────────────────+ this._renderProgress(steps, 3);+ await this._confirmAndFinish(prep, walletChainId, tx, onchainAgentId, deployment);+ }++ /**+ * Cache layer for register-prep so retries reuse the same IPFS pin+ * (idempotent across reloads / network blips).+ */+ async _getOrCreatePrep() {+ const agent = this._agent;+ const cacheKey = _prepCacheKey(agent.id);++ try {+ const raw = localStorage.getItem(cacheKey);+ if (raw) {+ const cached = JSON.parse(raw);+ if (cached?.prepId && cached?.metadataURI && cached?.expiresAt > Date.now()) {+ return cached;+ }+ }+ } catch {+ /* fall through to a fresh prep */+ }++ const body = {+ name: agent.name || 'Agent',+ description: agent.description || '',+ avatarId: agent.avatarId || agent.avatar_id,+ ...(Array.isArray(agent.skills) && agent.skills.length > 0+ ? { skills: agent.skills }+ : {}),+ };++ const resp = await fetch('/api/agents/register-prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ if (!resp.ok) {+ const data = await resp.json().catch(() => ({}));+ throw new Error(data.error_description || `register-prep returned ${resp.status}`);+ }+ const prep = await resp.json();+ const cached = {+ prepId: prep.prepId,+ cid: prep.cid,+ metadataURI: prep.metadataURI,+ expiresAt: Date.now() + 50 * 60 * 1000, // server keeps prep 1h, expire ours at 50m+ };+ try {+ localStorage.setItem(cacheKey, JSON.stringify(cached));+ } catch {+ /* quota or disabled storage — fine, we just lose retry caching */+ }+ return cached;+ }++ async _confirmAndFinish(prep, chainId, tx, onchainAgentId, deployment) {+ try {+ const resp = await fetch('/api/agents/register-confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ prepId: prep.prepId,+ chainId,+ agentId: String(onchainAgentId ?? 0),+ txHash: tx.hash,+ }),+ });+ if (!resp.ok) {+ const data = await resp.json().catch(() => ({}));+ throw new Error(+ data.error_description || `register-confirm returned ${resp.status}`,+ );+ }+ } catch (err) {+ this._renderError(+ `Mint succeeded on-chain but server save failed: ${err.message}. Reload the page to retry — your tx is at ${tx.hash.slice(0, 10)}…`,+ );+ return;+ }++ // Clear the prep cache — it's been consumed server-side.+ try {+ localStorage.removeItem(_prepCacheKey(this._agent.id));+ } catch {+ /* ignore */+ }++ // Reflect in local agent state and flip to the success chip.+ this._agent.chainId = chainId;+ this._agent.txHash = tx.hash;+ this._agent.contractAddress = deployment.identityRegistry;+ this._agent.erc8004AgentId = onchainAgentId;+ this._renderSuccessChip(chainId, tx.hash, deployment.identityRegistry);+ }++ // ─── Error classification ──────────────────────────────────────────────++ _handleSignError(err, chainId) {+ if (_isUserRejection(err)) {+ this._renderDeployButton();+ return;+ }+ if (_isInsufficientFunds(err)) {+ const faucetUrl = FAUCETS[chainId];+ this._renderError('Insufficient funds in this wallet.', {+ label: faucetUrl ? 'Get testnet funds' : 'Try again',+ handler: () => {+ if (faucetUrl) window.open(faucetUrl, '_blank');+ else this._renderDeployButton();+ },+ });+ return;+ }+ if (_isReplacementUnderpriced(err)) {+ this._renderError(+ 'A pending transaction from this wallet is blocking the new one. Cancel it in your wallet and try again.',+ );+ return;+ }+ this._renderError(`Transaction failed: ${_humanError(err)}`);+ }+}++// ─── Helpers ──────────────────────────────────────────────────────────────++/**+ * EIP-1193 user-rejection detection.+ * Spec: error code 4001 = user rejected request.+ * ethers also wraps errors with `code: 'ACTION_REJECTED'`.+ */+function _isUserRejection(err) {+ if (!err) return false;+ if (err.code === 4001) return true;+ if (err.code === 'ACTION_REJECTED') return true;+ if (err?.info?.error?.code === 4001) return true;+ return /user rejected|user denied|rejected by user|user cancel/i.test(err.message || '');+}++function _isInsufficientFunds(err) {+ if (!err) return false;+ if (err.code === 'INSUFFICIENT_FUNDS') return true;+ if (err?.info?.error?.code === -32000) {+ // Some RPCs surface insufficient funds via -32000 + body text.+ return /insufficient funds/i.test(err?.info?.error?.message || '');+ }+ return /insufficient funds|insufficient balance|not enough.*funds/i.test(err.message || '');+}++function _isReplacementUnderpriced(err) {+ if (!err) return false;+ if (err.code === 'REPLACEMENT_UNDERPRICED') return true;+ return /replacement.*underpriced|already known|nonce too low/i.test(err.message || '');+}++/** Pull a human-readable string from a ProviderError / ethers error. */+function _humanError(err) {+ if (!err) return 'unknown error';+ const inner = err?.info?.error?.message || err?.shortMessage || err?.message;+ return String(inner || 'unknown error')+ .replace(/\s+/g, ' ')+ .slice(0, 240);+}++/** Decode the Registered event's agentId from a confirmed receipt. */+function _parseRegisteredAgentId(receipt, registry) {+ if (!receipt?.logs) return null;+ for (const log of receipt.logs) {+ try {+ const parsed = registry.interface.parseLog(log);+ if (parsed?.name === 'Registered') {+ return Number(parsed.args.agentId);+ }+ } catch {+ /* not our event */+ }+ }+ return null;+}++/** Escape HTML attribute/text content to prevent XSS. */+function _esc(str) {+ return String(str ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}diff --git a/publish/src/erc8004/enumeration.js b/publish/src/erc8004/enumeration.jsnew file mode 100644index 000000000..f03d066f8--- /dev/null+++ b/publish/src/erc8004/enumeration.js@@ -0,0 +1,179 @@+/**+ * Agent enumeration & metadata fetching.+ *+ * Strategy, in priority order:+ * 1. ERC-721 Enumerable: balanceOf + tokenOfOwnerByIndex (fast, one call per id)+ * 2. Event scan: query Transfer(to = owner) filter on the registry (slow on+ * chains with many blocks; keep a bounded `fromBlock` when provided)+ *+ * Metadata resolution fetches `tokenURI(id)` and follows ipfs://, ar://, https://.+ */++import { getIdentityRegistry } from './agent-registry.js';++const IPFS_GATEWAYS = [+ (cid) => `https://ipfs.io/ipfs/${cid}`,+ (cid) => `https://cloudflare-ipfs.com/ipfs/${cid}`,+ (cid) => `https://dweb.link/ipfs/${cid}`,+];++/**+ * Resolve an ipfs://, ar://, or https:// URI to an HTTP URL.+ * Returns the first gateway for ipfs — caller may retry others via `ipfsFallbackUrls`.+ * @param {string} uri+ * @returns {string}+ */+export function uriToHttp(uri) {+ if (!uri) return '';+ if (uri.startsWith('ipfs://')) return IPFS_GATEWAYS[0](uri.slice(7));+ if (uri.startsWith('ar://')) return `https://arweave.net/${uri.slice(5)}`;+ return uri;+}++/**+ * Full list of fallback HTTP URLs for an IPFS URI (for retries).+ * @param {string} uri+ * @returns {string[]}+ */+export function ipfsFallbackUrls(uri) {+ if (!uri?.startsWith('ipfs://')) return [uri];+ const cid = uri.slice(7);+ return IPFS_GATEWAYS.map((fn) => fn(cid));+}++/**+ * Enumerate token IDs owned by `address` on the given registry.+ *+ * @param {import('ethers').Contract} registry+ * @param {string} address+ * @param {{ fromBlock?: number, onStatus?: (msg: string) => void }} [opts]+ * @returns {Promise<{tokenIds: number[], balance: number, strategy: 'enumerable'|'event-scan'|'empty'}>}+ */+export async function getAgentsByOwner(registry, address, opts = {}) {+ const log = opts.onStatus || (() => {});++ log('Reading balance…');+ const balance = Number(await registry.balanceOf(address));+ if (balance === 0) return { tokenIds: [], balance: 0, strategy: 'empty' };++ // Try ERC-721 Enumerable first.+ try {+ const tokenIds = [];+ for (let i = 0; i < balance; i++) {+ tokenIds.push(Number(await registry.tokenOfOwnerByIndex(address, i)));+ }+ return { tokenIds, balance, strategy: 'enumerable' };+ } catch {+ // Fall through to event scan.+ }++ log('Scanning Transfer events…');+ const filter = registry.filters.Transfer(null, address);+ const events = opts.fromBlock+ ? await registry.queryFilter(filter, opts.fromBlock)+ : await registry.queryFilter(filter);++ const seen = new Set();+ const tokenIds = [];+ for (const e of events) {+ const id = Number(e.args.tokenId);+ if (seen.has(id)) continue;+ seen.add(id);+ try {+ const currentOwner = await registry.ownerOf(id);+ if (currentOwner.toLowerCase() === address.toLowerCase()) tokenIds.push(id);+ } catch {+ /* burned — skip */+ }+ }+ return { tokenIds, balance, strategy: 'event-scan' };+}++/**+ * Fetch `tokenURI(id)` and its resolved JSON (if reachable).+ *+ * @param {import('ethers').Contract} registry+ * @param {number} tokenId+ * @returns {Promise<{id: number, uri: string, meta: object|null, owner: string|null}>}+ */+export async function fetchTokenMeta(registry, tokenId) {+ let uri = '';+ let meta = null;+ let owner = null;++ try {+ uri = await registry.tokenURI(tokenId);+ } catch {+ /* no URI set */+ }+ try {+ owner = await registry.ownerOf(tokenId);+ } catch {+ /* burned */+ }++ if (uri) {+ const urls = ipfsFallbackUrls(uri);+ for (const u of urls) {+ try {+ const r = await fetch(u, { signal: AbortSignal.timeout(6000) });+ const ct = r.headers.get('content-type') || '';+ if (r.ok && ct.includes('json')) {+ meta = await r.json();+ break;+ }+ } catch {+ /* try next gateway */+ }+ }+ }+ return { id: tokenId, uri, meta, owner };+}++/**+ * Scan past `Registered` events for a given owner — powers the History tab.+ *+ * @param {import('ethers').Contract} registry+ * @param {string} ownerAddress+ * @param {{ fromBlock?: number, limit?: number }} [opts]+ * @returns {Promise<Array<{agentId: number, agentURI: string, txHash: string, blockNumber: number, blockHash: string}>>}+ */+export async function getRegistrationHistory(registry, ownerAddress, opts = {}) {+ const limit = opts.limit ?? 50;+ const filter = registry.filters.Registered(null, null, ownerAddress);+ const events = opts.fromBlock+ ? await registry.queryFilter(filter, opts.fromBlock)+ : await registry.queryFilter(filter);++ return events+ .map((e) => ({+ agentId: Number(e.args.agentId),+ agentURI: String(e.args.agentURI || ''),+ txHash: e.transactionHash,+ blockNumber: Number(e.blockNumber),+ blockHash: e.blockHash,+ }))+ .sort((a, b) => b.blockNumber - a.blockNumber)+ .slice(0, limit);+}++/**+ * Read-only registry connect — uses a public RPC when no signer is available.+ * Used by the Search tab when a user hasn't connected a wallet yet.+ *+ * @param {number} chainId+ * @param {string} rpcUrl+ * @returns {Promise<import('ethers').Contract>}+ */+export async function getReadOnlyRegistry(chainId, rpcUrl) {+ const { JsonRpcProvider, Contract } = await import('ethers');+ const { REGISTRY_DEPLOYMENTS, IDENTITY_REGISTRY_ABI } = await import('./abi.js');+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment?.identityRegistry) {+ throw new Error(`No registry for chain ${chainId}`);+ }+ const provider = new JsonRpcProvider(rpcUrl);+ return new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);+}++export { getIdentityRegistry };diff --git a/publish/src/erc8004/gltf-extras.js b/publish/src/erc8004/gltf-extras.jsnew file mode 100644index 000000000..390be9cd0--- /dev/null+++ b/publish/src/erc8004/gltf-extras.js@@ -0,0 +1,56 @@+/**+ * Embed and extract agent manifests from glTF/GLB extras.+ *+ * The manifest lives at document.extras.agent so that standard glTF tools+ * ignore it gracefully while any ERC-8004-aware renderer can find it.+ *+ * Usage:+ * const glb = await embedAgentExtras(originalGlb, manifest);+ * const manifest = await readAgentExtras(glb);+ */++import { WebIO } from '@gltf-transform/core';++const io = new WebIO();++/**+ * Embed an agent manifest into a GLB's extras field.+ *+ * @param {ArrayBuffer|Uint8Array} glb Source GLB bytes+ * @param {object} manifest Agent manifest (agent-manifest/0.1 shape)+ * @returns {Promise<Uint8Array>} Modified GLB bytes+ */+export async function embedAgentExtras(glb, manifest) {+ const buffer = glb instanceof ArrayBuffer ? new Uint8Array(glb) : glb;+ const doc = await io.readBinary(buffer);+ const root = doc.getRoot();++ const existing = root.getExtras() || {};+ root.setExtras({ ...existing, agent: manifest });++ return io.writeBinary(doc);+}++/**+ * Read the agent manifest embedded in a GLB's extras field.+ *+ * @param {ArrayBuffer|Uint8Array} glb+ * @returns {Promise<object|null>} The manifest, or null if not present+ */+export async function readAgentExtras(glb) {+ const buffer = glb instanceof ArrayBuffer ? new Uint8Array(glb) : glb;+ const doc = await io.readBinary(buffer);+ const extras = doc.getRoot().getExtras() || {};+ return extras.agent ?? null;+}++/**+ * Check whether a GLB has an embedded agent manifest.+ *+ * @param {ArrayBuffer|Uint8Array} glb+ * @returns {Promise<boolean>}+ */+export async function hasAgentExtras(glb) {+ const manifest = await readAgentExtras(glb);+ return manifest !== null;+}diff --git a/publish/src/erc8004/hydrate.js b/publish/src/erc8004/hydrate.jsnew file mode 100644index 000000000..af3ba5424--- /dev/null+++ b/publish/src/erc8004/hydrate.js@@ -0,0 +1,45 @@+/**+ * Client-side agent hydrator.+ * Fetches agents from /api/erc8004/hydrate and /api/erc8004/import.+ */++/**+ * Fetch discovered agents owned by the user's linked wallets.+ * @returns {Promise<Array<{ chainId, agentId, name, description, image, glbUrl, owner, alreadyImported }>>}+ */+export async function fetchDiscoveredAgents() {+ const res = await fetch('/api/erc8004/hydrate', {+ method: 'GET',+ credentials: 'include',+ });++ if (!res.ok) {+ const error = await res.json().catch(() => ({}));+ throw new Error(error.error_description || `HTTP ${res.status}`);+ }++ const data = await res.json();+ return data.agents || [];+}++/**+ * Import an on-chain agent.+ * @param {{ chainId: number, agentId: string }} agent+ * @returns {Promise<{ id, erc8004_agent_id, erc8004_agent_id_chain_id, name, avatar_url }>}+ */+export async function importAgent({ chainId, agentId }) {+ const res = await fetch('/api/erc8004/import', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ chainId, agentId }),+ });++ if (!res.ok) {+ const error = await res.json().catch(() => ({}));+ throw new Error(error.error_description || `HTTP ${res.status}`);+ }++ const data = await res.json();+ return data.agent;+}diff --git a/publish/src/erc8004/index.js b/publish/src/erc8004/index.jsnew file mode 100644index 000000000..df06929d1--- /dev/null+++ b/publish/src/erc8004/index.js@@ -0,0 +1,27 @@+export {+ IDENTITY_REGISTRY_ABI,+ REPUTATION_REGISTRY_ABI,+ VALIDATION_REGISTRY_ABI,+ REGISTRY_DEPLOYMENTS,+ agentRegistryId,+} from './abi.js';+export {+ connectWallet,+ eagerConnectWallet,+ ensureWallet,+ disconnectWallet,+ getWalletState,+ getSigner,+ onWalletChange,+ registerAgent,+ buildRegistrationJSON,+ pinFile,+} from './agent-registry.js';+export { RegisterUI } from './register-ui.js';+export { submitReputation, submitFeedback, getReputation, getRecentReviews } from './reputation.js';+export {+ recordValidation,+ getLatestValidation,+ reportPassed,+ hashReport,+} from './validation-recorder.js';diff --git a/publish/src/erc8004/qr.js b/publish/src/erc8004/qr.jsnew file mode 100644index 000000000..c4764ce6d--- /dev/null+++ b/publish/src/erc8004/qr.js@@ -0,0 +1,423 @@+/**+ * Minimal QR-code generator (zero-dep, ESM).+ *+ * Implements QR Model 2, byte mode, error-correction level L, versions 1–10.+ * That's enough to encode URLs up to ~174 UTF-8 bytes at ECL=L — which covers+ * every explorer URL we'd embed in an ERC-8004 agent QR.+ *+ * Derived from Project Nayuki's public-domain QR code generator+ * (https://www.nayuki.io/page/qr-code-generator-library) reduced to the+ * minimum path this app needs. Pure JS, no external deps.+ */++// ───────────────────────────────────────────────────────────────────────────+// Generator+// ───────────────────────────────────────────────────────────────────────────++const ECL = 0; // L (1 = M, 2 = Q, 3 = H). We only need L.++const EC_CODEWORDS_PER_BLOCK = [+ // ECL_L+ [7, 10, 15, 20, 26, 18, 20, 24, 30, 18],+];+const NUM_EC_BLOCKS = [[1, 1, 1, 1, 1, 2, 2, 2, 2, 4]];++/** Returns the bitmask size (modules per side) for a given version (1..10). */+function sizeForVersion(ver) {+ return ver * 4 + 17;+}++/** Total number of data codewords for a given version + ECL. */+function numDataCodewords(ver) {+ const total = numRawDataModules(ver) >>> 3;+ const ecBlocks = NUM_EC_BLOCKS[ECL][ver - 1];+ const ecPerBlock = EC_CODEWORDS_PER_BLOCK[ECL][ver - 1];+ return total - ecPerBlock * ecBlocks;+}++function numRawDataModules(ver) {+ let result = (16 * ver + 128) * ver + 64;+ if (ver >= 2) {+ const numAlign = Math.floor(ver / 7) + 2;+ result -= (25 * numAlign - 10) * numAlign - 55;+ if (ver >= 7) result -= 36;+ }+ return result;+}++// Reed–Solomon in GF(256)+function rsGenerator(degree) {+ const result = new Uint8Array(degree);+ result[degree - 1] = 1;+ let root = 1;+ for (let i = 0; i < degree; i++) {+ for (let j = 0; j < degree; j++) {+ result[j] = rsMul(result[j], root);+ if (j + 1 < degree) result[j] ^= result[j + 1];+ }+ root = rsMul(root, 0x02);+ }+ return result;+}+function rsMul(x, y) {+ let z = 0;+ for (let i = 7; i >= 0; i--) {+ z = (z << 1) ^ ((z >>> 7) * 0x11d);+ z ^= ((y >>> i) & 1) * x;+ }+ return z & 0xff;+}+function rsRemainder(data, gen) {+ const result = new Uint8Array(gen.length);+ for (const b of data) {+ const factor = b ^ result[0];+ result.copyWithin(0, 1);+ result[result.length - 1] = 0;+ for (let i = 0; i < result.length; i++) result[i] ^= rsMul(gen[i], factor);+ }+ return result;+}++// Pick the smallest version (1..10) that fits `dataLen` bytes in byte mode at ECL=L.+function pickVersion(dataLen) {+ for (let v = 1; v <= 10; v++) {+ const bitsAvailable = numDataCodewords(v) * 8;+ // byte mode: 4 (mode) + (v<10 ? 8 : 16) char-count + 8*len+ const charCountBits = v < 10 ? 8 : 16;+ const needed = 4 + charCountBits + dataLen * 8;+ if (needed <= bitsAvailable) return v;+ }+ throw new Error('QR payload too large (>10 versions)');+}++/**+ * Generate a QR code matrix for the given string.+ *+ * @param {string} text+ * @returns {{ size: number, modules: boolean[][] }}+ */+export function generateQR(text) {+ const bytes = new TextEncoder().encode(text);+ const ver = pickVersion(bytes.length);+ const size = sizeForVersion(ver);+ const charCountBits = ver < 10 ? 8 : 16;++ // --- 1. Build bitstream ------------------------------------------------+ const bits = [];+ const pushBits = (val, n) => {+ for (let i = n - 1; i >= 0; i--) bits.push((val >>> i) & 1);+ };+ pushBits(0b0100, 4); // byte mode+ pushBits(bytes.length, charCountBits);+ for (const b of bytes) pushBits(b, 8);++ const dataCodewords = numDataCodewords(ver);+ const capacityBits = dataCodewords * 8;+ // terminator+ for (let i = 0; i < 4 && bits.length < capacityBits; i++) bits.push(0);+ // byte-align+ while (bits.length % 8 !== 0) bits.push(0);+ // pad+ const pads = [0xec, 0x11];+ let padIdx = 0;+ while (bits.length < capacityBits) {+ pushBits(pads[padIdx % 2], 8);+ padIdx++;+ }+ const data = new Uint8Array(dataCodewords);+ for (let i = 0; i < dataCodewords; i++) {+ let v = 0;+ for (let j = 0; j < 8; j++) v = (v << 1) | bits[i * 8 + j];+ data[i] = v;+ }++ // --- 2. Reed–Solomon EC ------------------------------------------------+ const numBlocks = NUM_EC_BLOCKS[ECL][ver - 1];+ const ecLen = EC_CODEWORDS_PER_BLOCK[ECL][ver - 1];+ const rawCodewords = numRawDataModules(ver) >>> 3;+ const shortBlockLen = Math.floor(rawCodewords / numBlocks);+ const numShort = numBlocks - (rawCodewords % numBlocks);++ const blocks = [];+ const gen = rsGenerator(ecLen);+ let offset = 0;+ for (let i = 0; i < numBlocks; i++) {+ const dataLen = shortBlockLen - ecLen + (i < numShort ? 0 : 1);+ const dat = data.slice(offset, offset + dataLen);+ offset += dataLen;+ const ec = rsRemainder(dat, gen);+ blocks.push({ dat, ec });+ }+ // Interleave+ const out = [];+ for (let i = 0; i < shortBlockLen - ecLen + 1; i++) {+ for (const b of blocks) {+ if (i < b.dat.length) out.push(b.dat[i]);+ }+ }+ for (let i = 0; i < ecLen; i++) {+ for (const b of blocks) out.push(b.ec[i]);+ }++ // --- 3. Matrix ---------------------------------------------------------+ const modules = Array.from({ length: size }, () => new Array(size).fill(false));+ const isFn = Array.from({ length: size }, () => new Array(size).fill(false));++ const setFn = (x, y, dark) => {+ modules[y][x] = dark;+ isFn[y][x] = true;+ };++ // Finder + separators+ const drawFinder = (cx, cy) => {+ for (let dy = -4; dy <= 4; dy++) {+ for (let dx = -4; dx <= 4; dx++) {+ const x = cx + dx;+ const y = cy + dy;+ if (x < 0 || x >= size || y < 0 || y >= size) continue;+ const d = Math.max(Math.abs(dx), Math.abs(dy));+ setFn(x, y, d !== 2 && d !== 4);+ }+ }+ };+ drawFinder(3, 3);+ drawFinder(size - 4, 3);+ drawFinder(3, size - 4);++ // Timing+ for (let i = 0; i < size; i++) {+ if (!isFn[6][i]) setFn(i, 6, i % 2 === 0);+ if (!isFn[i][6]) setFn(6, i, i % 2 === 0);+ }++ // Alignment patterns+ const alignPositions = (ver) => {+ if (ver === 1) return [];+ const num = Math.floor(ver / 7) + 2;+ const step = ver === 32 ? 26 : Math.ceil((ver * 4 + 4) / (num * 2 - 2)) * 2;+ const result = [6];+ for (let pos = size - 7; result.length < num; pos -= step) result.splice(1, 0, pos);+ return result;+ };+ const aps = alignPositions(ver);+ for (const x of aps) {+ for (const y of aps) {+ if ((x === 6 && y === 6) || (x === 6 && y === size - 7) || (x === size - 7 && y === 6))+ continue;+ for (let dy = -2; dy <= 2; dy++) {+ for (let dx = -2; dx <= 2; dx++) {+ const d = Math.max(Math.abs(dx), Math.abs(dy));+ setFn(x + dx, y + dy, d !== 1);+ }+ }+ }+ }++ // Reserve format info area+ for (let i = 0; i < 9; i++) setFn(8, i, false);+ for (let i = 0; i < 8; i++) setFn(i, 8, false);+ for (let i = 0; i < 8; i++) setFn(size - 1 - i, 8, false);+ for (let i = 0; i < 7; i++) setFn(8, size - 1 - i, false);+ setFn(8, size - 8, true); // dark module++ // Version info (ver >= 7)+ if (ver >= 7) {+ let rem = ver;+ for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);+ const bits = ((ver << 12) | rem) >>> 0;+ for (let i = 0; i < 18; i++) {+ const bit = ((bits >>> i) & 1) === 1;+ const a = size - 11 + (i % 3);+ const b = Math.floor(i / 3);+ setFn(a, b, bit);+ setFn(b, a, bit);+ }+ }++ // --- 4. Place data by zig-zag -----------------------------------------+ let bitIdx = 0;+ const bitAt = (i) => ((out[i >>> 3] >>> (7 - (i & 7))) & 1) === 1;+ for (let right = size - 1; right >= 1; right -= 2) {+ if (right === 6) right = 5;+ for (let vert = 0; vert < size; vert++) {+ for (let j = 0; j < 2; j++) {+ const x = right - j;+ const upward = ((right + 1) & 2) === 0;+ const y = upward ? size - 1 - vert : vert;+ if (!isFn[y][x] && bitIdx < out.length * 8) {+ modules[y][x] = bitAt(bitIdx);+ bitIdx++;+ }+ }+ }+ }++ // --- 5. Try all 8 masks; pick lowest penalty --------------------------+ let bestMask = 0;+ let bestPenalty = Infinity;+ let bestModules = null;+ for (let mask = 0; mask < 8; mask++) {+ const m = modules.map((row) => row.slice());+ applyMask(m, isFn, mask);+ applyFormatInfo(m, mask);+ const p = penalty(m);+ if (p < bestPenalty) {+ bestPenalty = p;+ bestMask = mask;+ bestModules = m;+ }+ }+ return { size, modules: bestModules };+}++function maskFn(mask, x, y) {+ switch (mask) {+ case 0:+ return (x + y) % 2 === 0;+ case 1:+ return y % 2 === 0;+ case 2:+ return x % 3 === 0;+ case 3:+ return (x + y) % 3 === 0;+ case 4:+ return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;+ case 5:+ return ((x * y) % 2) + ((x * y) % 3) === 0;+ case 6:+ return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;+ case 7:+ return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;+ }+ return false;+}++function applyMask(modules, isFn, mask) {+ const size = modules.length;+ for (let y = 0; y < size; y++) {+ for (let x = 0; x < size; x++) {+ if (!isFn[y][x] && maskFn(mask, x, y)) modules[y][x] = !modules[y][x];+ }+ }+}++function applyFormatInfo(modules, mask) {+ const size = modules.length;+ const data = (ECL_BITS[ECL] << 3) | mask;+ let rem = data;+ for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);+ const bits = (((data << 10) | rem) ^ 0x5412) >>> 0;+ const setBit = (x, y, b) => {+ modules[y][x] = b;+ };+ for (let i = 0; i <= 5; i++) setBit(8, i, ((bits >>> i) & 1) === 1);+ setBit(8, 7, ((bits >>> 6) & 1) === 1);+ setBit(8, 8, ((bits >>> 7) & 1) === 1);+ setBit(7, 8, ((bits >>> 8) & 1) === 1);+ for (let i = 9; i < 15; i++) setBit(14 - i, 8, ((bits >>> i) & 1) === 1);+ for (let i = 0; i < 8; i++) setBit(size - 1 - i, 8, ((bits >>> i) & 1) === 1);+ for (let i = 8; i < 15; i++) setBit(8, size - 15 + i, ((bits >>> i) & 1) === 1);+ setBit(8, size - 8, true);+}++const ECL_BITS = [1, 0, 3, 2]; // index by ECL 0..3 → {L,M,Q,H}++function penalty(modules) {+ const size = modules.length;+ let p = 0;+ // N1: runs of 5++ for (let y = 0; y < size; y++) {+ let run = 1;+ for (let x = 1; x < size; x++) {+ if (modules[y][x] === modules[y][x - 1]) {+ run++;+ if (run === 5) p += 3;+ else if (run > 5) p++;+ } else run = 1;+ }+ }+ for (let x = 0; x < size; x++) {+ let run = 1;+ for (let y = 1; y < size; y++) {+ if (modules[y][x] === modules[y - 1][x]) {+ run++;+ if (run === 5) p += 3;+ else if (run > 5) p++;+ } else run = 1;+ }+ }+ // N2: 2×2 blocks+ for (let y = 0; y < size - 1; y++) {+ for (let x = 0; x < size - 1; x++) {+ const c = modules[y][x];+ if (modules[y][x + 1] === c && modules[y + 1][x] === c && modules[y + 1][x + 1] === c)+ p += 3;+ }+ }+ // N3: finder-like patterns — skipped for brevity; penalty approximation is fine for URLs.+ // N4: light/dark imbalance+ let dark = 0;+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) if (modules[y][x]) dark++;+ const total = size * size;+ const k = Math.floor(Math.abs(dark * 20 - total * 10) / total);+ p += k * 10;+ return p;+}++// ───────────────────────────────────────────────────────────────────────────+// Renderers+// ───────────────────────────────────────────────────────────────────────────++/**+ * Render a QR code as an SVG string. Works in any environment that can hold a+ * string — no canvas required. Useful as a fallback when 2D canvas is+ * unavailable or as a directly embeddable inline SVG.+ *+ * @param {string} text+ * @param {{ scale?: number, margin?: number, dark?: string, light?: string }} [opts]+ * @returns {string} SVG markup+ */+export function renderQRToSVG(text, opts = {}) {+ const scale = opts.scale ?? 8;+ const margin = opts.margin ?? 2;+ const dark = opts.dark ?? '#000';+ const light = opts.light ?? '#fff';+ const { size, modules } = generateQR(text);+ const px = (size + margin * 2) * scale;+ let rects = '';+ for (let y = 0; y < size; y++) {+ for (let x = 0; x < size; x++) {+ if (modules[y][x]) {+ rects += `<rect x="${(x + margin) * scale}" y="${(y + margin) * scale}" width="${scale}" height="${scale}"/>`;+ }+ }+ }+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${px} ${px}" shape-rendering="crispEdges"><rect width="${px}" height="${px}" fill="${light}"/><g fill="${dark}">${rects}</g></svg>`;+}++/**+ * Render a QR code into a canvas. Returns the canvas.+ * @param {string} text+ * @param {{ scale?: number, margin?: number }} [opts]+ */+export function renderQRToCanvas(text, opts = {}) {+ const scale = opts.scale ?? 8;+ const margin = opts.margin ?? 2;+ const { size, modules } = generateQR(text);+ const pixels = (size + margin * 2) * scale;+ const canvas = document.createElement('canvas');+ canvas.width = pixels;+ canvas.height = pixels;+ const ctx = canvas.getContext('2d');+ ctx.fillStyle = '#fff';+ ctx.fillRect(0, 0, pixels, pixels);+ ctx.fillStyle = '#000';+ for (let y = 0; y < size; y++) {+ for (let x = 0; x < size; x++) {+ if (modules[y][x]) {+ ctx.fillRect((x + margin) * scale, (y + margin) * scale, scale, scale);+ }+ }+ }+ return canvas;+}diff --git a/publish/src/erc8004/queries.js b/publish/src/erc8004/queries.jsnew file mode 100644index 000000000..5387e14c7--- /dev/null+++ b/publish/src/erc8004/queries.js@@ -0,0 +1,255 @@+/**+ * Read-only queries against the Identity Registry.+ *+ * Used by the tabbed registration UI (My Agents / Search / History).+ *+ * All queries use a read-only provider (wallet provider preferred; public RPC+ * fallback from CHAIN_META). We deliberately avoid backend state for these —+ * the chain is the source of truth.+ */++import { BrowserProvider, Contract, JsonRpcProvider } from 'ethers';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './abi.js';+import { CHAIN_META } from './chain-meta.js';++/**+ * Return a read-only ethers provider. Uses the connected wallet provider if+ * `ethProvider` is given, else falls back to the public RPC from CHAIN_META.+ *+ * @param {number} chainId+ * @param {any} [ethProvider] EIP-1193 provider (window.ethereum / Privy)+ */+export function getReadProvider(chainId, ethProvider) {+ if (ethProvider) return new BrowserProvider(ethProvider);+ const meta = CHAIN_META[chainId];+ if (!meta) throw new Error(`No RPC configured for chainId ${chainId}`);+ return new JsonRpcProvider(meta.rpcUrl, chainId);+}++/** @param {number} chainId @param {any} [ethProvider] */+export function getReadRegistry(chainId, ethProvider) {+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment || !deployment.identityRegistry) {+ throw new Error(`No Identity Registry for chainId ${chainId}`);+ }+ const provider = getReadProvider(chainId, ethProvider);+ return new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);+}++/**+ * Verify the registry's on-chain version. Non-throwing — returns null on error.+ * @param {number} chainId @param {any} [ethProvider]+ * @returns {Promise<string|null>}+ */+export async function getRegistryVersion(chainId, ethProvider) {+ try {+ const registry = getReadRegistry(chainId, ethProvider);+ return await registry.getVersion();+ } catch {+ return null;+ }+}++/**+ * @param {number} chainId @param {any} [ethProvider]+ * @returns {Promise<bigint>}+ */+export async function getTotalSupply(chainId, ethProvider) {+ const registry = getReadRegistry(chainId, ethProvider);+ return await registry.totalSupply();+}++/**+ * List agent IDs owned by `address`. Strategy:+ *+ * 1. Try ERC-721 Enumerable: balanceOf → tokenOfOwnerByIndex.+ * 2. If that reverts, fall back to a Registered-event scan over the last+ * `eventScanBlocks` blocks (default 500k ~= 1 week on 12s chains, cheap+ * on most public RPCs), filtered by owner topic.+ * 3. If neither path yields full detail, return `{ ids: [...], partial: true }`+ * so the UI can render the count + a "check explorer" fallback.+ *+ * @param {object} opts+ * @param {number} opts.chainId+ * @param {string} opts.owner+ * @param {any} [opts.ethProvider]+ * @param {number} [opts.eventScanBlocks]+ * @returns {Promise<{ ids: bigint[], count: number, partial: boolean, mode: 'enumerable'|'events'|'count-only' }>}+ */+export async function listAgentsByOwner({ chainId, owner, ethProvider, eventScanBlocks = 500000 }) {+ const registry = getReadRegistry(chainId, ethProvider);+ const balance = await registry.balanceOf(owner);+ const count = Number(balance);+ if (count === 0) return { ids: [], count: 0, partial: false, mode: 'enumerable' };++ // 1. Enumerable path+ try {+ const ids = [];+ for (let i = 0; i < count; i++) {+ const id = await registry.tokenOfOwnerByIndex(owner, i);+ ids.push(id);+ }+ return { ids, count, partial: false, mode: 'enumerable' };+ } catch {+ /* fall through */+ }++ // 2. Event-scan fallback+ try {+ const provider = registry.runner.provider || registry.runner;+ const latest = await provider.getBlockNumber();+ const fromBlock = Math.max(0, latest - eventScanBlocks);+ const filter = registry.filters.Registered(null, null, owner);+ const events = await registry.queryFilter(filter, fromBlock, latest);+ const idsFromEvents = [];+ for (const ev of events) {+ const id = ev.args?.agentId;+ if (id === undefined) continue;+ // Confirm still owned (transfers could have moved it)+ try {+ const currentOwner = await registry.ownerOf(id);+ if (currentOwner.toLowerCase() === owner.toLowerCase()) idsFromEvents.push(id);+ } catch {+ /* ignore burned/missing */+ }+ }+ return {+ ids: idsFromEvents,+ count,+ partial: idsFromEvents.length < count,+ mode: 'events',+ };+ } catch {+ /* fall through */+ }++ // 3. Count-only+ return { ids: [], count, partial: true, mode: 'count-only' };+}++/**+ * Fetch recent Registered events for display in the History tab.+ * Optionally filter to a specific owner.+ *+ * @param {object} opts+ * @param {number} opts.chainId+ * @param {string} [opts.owner]+ * @param {any} [opts.ethProvider]+ * @param {number} [opts.blocks] Scan depth (default 500k)+ * @param {number} [opts.limit] Max events returned (newest first)+ * @returns {Promise<Array<{ agentId: bigint, agentURI: string, owner: string, blockNumber: number, txHash: string }>>}+ */+export async function listRegisteredEvents({+ chainId,+ owner,+ ethProvider,+ blocks = 500000,+ limit = 100,+}) {+ const registry = getReadRegistry(chainId, ethProvider);+ const provider = registry.runner.provider || registry.runner;+ const latest = await provider.getBlockNumber();+ const fromBlock = Math.max(0, latest - blocks);+ const filter = owner+ ? registry.filters.Registered(null, null, owner)+ : registry.filters.Registered();+ const events = await registry.queryFilter(filter, fromBlock, latest);++ const out = events+ .slice()+ .reverse()+ .slice(0, limit)+ .map((ev) => ({+ agentId: ev.args.agentId,+ agentURI: ev.args.agentURI,+ owner: ev.args.owner,+ blockNumber: ev.blockNumber,+ txHash: ev.transactionHash,+ }));+ return out;+}++/**+ * Fetch on-chain detail for a single agent: owner + tokenURI.+ * Does NOT fetch the off-chain metadata JSON — callers do that via fetchAgentMetadata.+ *+ * @param {object} opts+ * @param {number} opts.chainId+ * @param {bigint|number|string} opts.agentId+ * @param {any} [opts.ethProvider]+ */+export async function getAgentOnchain({ chainId, agentId, ethProvider }) {+ const registry = getReadRegistry(chainId, ethProvider);+ const [owner, uri] = await Promise.all([+ registry.ownerOf(agentId).catch(() => null),+ registry.tokenURI(agentId).catch(() => null),+ ]);+ return { agentId: BigInt(agentId), owner, uri };+}++/**+ * Extract a 3D avatar URL (GLB/GLTF) from an ERC-8004 registration payload.+ *+ * Canonical location is a service entry named `avatar` / `avatar-3d` with a+ * `version` that starts with `gltf`. Falls back to the top-level `image` field+ * when it ends in `.glb` or `.gltf` — older files we wrote before the service+ * convention pollute `image` with the GLB URL.+ *+ * @param {any} metadata Parsed registration JSON+ * @returns {string|null} GLB/GLTF URL (still in raw ipfs://, ar://, https:// form)+ */+export function findAvatar3D(metadata) {+ if (!metadata || typeof metadata !== 'object') return null;++ const services = Array.isArray(metadata.services) ? metadata.services : [];+ for (const svc of services) {+ if (!svc || typeof svc !== 'object') continue;+ const endpoint = String(svc.endpoint || '').trim();+ if (!endpoint) continue;+ const name = String(svc.name || '').toLowerCase();+ const version = String(svc.version || '').toLowerCase();+ if (name === 'avatar' || name === 'avatar-3d') return endpoint;+ if (version.startsWith('gltf')) return endpoint;+ if (/\.(glb|gltf)(\?|#|$)/i.test(endpoint)) return endpoint;+ }++ const img = String(metadata.image || '').trim();+ if (/\.(glb|gltf)(\?|#|$)/i.test(img)) return img;++ return null;+}++/**+ * Resolve any IPFS/Arweave/data/https URI to a fetchable URL and parse JSON.+ *+ * @param {string} uri+ * @returns {Promise<{ ok: boolean, data?: any, error?: string, resolvedUrl?: string }>}+ */+export async function fetchAgentMetadata(uri) {+ if (!uri) return { ok: false, error: 'empty uri' };++ // data:application/json;base64,... (inline)+ if (uri.startsWith('data:')) {+ try {+ const match = uri.match(/^data:application\/json(?:;base64)?,(.*)$/);+ if (!match) return { ok: false, error: 'unsupported data URI' };+ const payload = /;base64,/.test(uri) ? atob(match[1]) : decodeURIComponent(match[1]);+ return { ok: true, data: JSON.parse(payload), resolvedUrl: uri };+ } catch (err) {+ return { ok: false, error: 'data URI parse failed: ' + err.message };+ }+ }++ let url = uri;+ if (uri.startsWith('ipfs://')) url = 'https://ipfs.io/ipfs/' + uri.slice(7);+ else if (uri.startsWith('ar://')) url = 'https://arweave.net/' + uri.slice(5);++ try {+ const res = await fetch(url);+ if (!res.ok) return { ok: false, error: `HTTP ${res.status}`, resolvedUrl: url };+ const data = await res.json();+ return { ok: true, data, resolvedUrl: url };+ } catch (err) {+ return { ok: false, error: err.message, resolvedUrl: url };+ }+}diff --git a/publish/src/erc8004/register-ui.js b/publish/src/erc8004/register-ui.jsnew file mode 100644index 000000000..560bef71f--- /dev/null+++ b/publish/src/erc8004/register-ui.js@@ -0,0 +1,2379 @@+/**+ * ERC-8004 registration UI.+ *+ * Tabbed interface for creating, listing, searching, and auditing ERC-8004+ * agents. Inspired by erc8004.agency but extended with GLB uploads and 3D+ * viewer links specific to 3D-Agent.+ *+ * Tabs:+ * - Create Agent (4-step wizard: Identity → Services → Configuration → Deploy)+ * - My Agents (owned-by-wallet, current chain)+ * - Search (by Agent ID)+ * - Templates (pre-fills Create Agent)+ * - History (Registered events for the connected wallet)+ *+ * Uses plain DOM — consistent with the rest of the project.+ */++import {+ registerAgent,+ connectWallet,+ eagerConnectWallet,+ onWalletChange,+ pinFile,+ getIdentityRegistry,+ buildRegistrationJSON,+} from './agent-registry.js';+import { glbFileToThumbnail } from './thumbnail.js';+import { DEFAULT_AVATARS, getDefaultAvatar } from './default-avatars.js';+import { REGISTRY_DEPLOYMENTS } from './abi.js';+import { renderBatchTab } from './batch-tab.js';+import { renderQRToCanvas } from './qr.js';+import {+ CHAIN_META,+ DEFAULT_CHAIN_ID,+ switchChain,+ addressExplorerUrl,+ tokenExplorerUrl,+ txExplorerUrl,+ supportedChainIds,+} from './chain-meta.js';+import {+ getReadRegistry,+ listAgentsByOwner,+ listRegisteredEvents,+ getAgentOnchain,+ fetchAgentMetadata,+ findAvatar3D,+ getRegistryVersion,+ getTotalSupply,+} from './queries.js';+import {+ detectInputType,+ resolveByAddress,+ resolveByTxHash,+ resolveENSAddress,+ INPUT_TYPES,+} from './resolve-avatar.js';++// ───────────────────────────────────────────────────────────────────────────+// Templates (for the Templates tab → prefills Create)+// ───────────────────────────────────────────────────────────────────────────++// Service presets per template. Types match SERVICE_TYPES; endpoints are blank+// so the wizard shows empty rows the user fills in with their own URLs.+const S = {+ a2a: { type: 'A2A', name: 'A2A', endpoint: '' },+ mcp: { type: 'MCP', name: 'MCP', endpoint: '' },+ web: { type: 'web', name: 'Website', endpoint: '' },+ x402: { type: 'x402', name: 'x402', endpoint: '' },+};++const TEMPLATES = [+ {+ id: 'companion',+ emoji: '🤝',+ name: 'Virtual Companion',+ description:+ 'Always-on digital friend with persistent memory and empathy for daily check-ins and emotional support.',+ services: [S.a2a],+ },+ {+ id: 'influencer',+ emoji: '🎭',+ name: 'Virtual Influencer',+ description:+ 'On-brand 3D persona for social posts, livestreams, and AMAs with a consistent face and voice.',+ services: [S.a2a, S.web],+ },+ {+ id: 'vtuber',+ emoji: '📺',+ name: 'VTuber Co-Host',+ description:+ 'Livestream co-host with reactive expressions, chat moderation, superchat shoutouts, and lore memory.',+ services: [S.a2a],+ },+ {+ id: 'tutor',+ emoji: '🎓',+ name: 'Language Tutor',+ description:+ 'One-on-one conversation practice with pronunciation feedback, spaced repetition, and adaptive lessons.',+ services: [S.a2a, S.mcp],+ },+ {+ id: 'gallery',+ emoji: '🖼️',+ name: 'Gallery Guide',+ description:+ 'Embodied docent for 3D galleries, NFT exhibitions, and metaverse rooms with scripted tours and Q&A.',+ services: [S.a2a, S.web],+ },+ {+ id: 'npc',+ emoji: '🎮',+ name: 'Game NPC',+ description:+ 'Questgiver and dialog partner for game worlds with persistent lore, per-player memory, and branching scripts.',+ services: [S.a2a],+ },+ {+ id: 'wellness',+ emoji: '🧘',+ name: 'Wellness Coach',+ description:+ 'Breathwork, meditation, and daily mood check-ins with a calm, empathetic embodied presence.',+ services: [S.a2a],+ },+ {+ id: 'concierge',+ emoji: '🪪',+ name: 'NFT Concierge',+ description:+ 'Token-gated holder assistant — perks, drops, private channel access, and holder-specific analytics.',+ services: [S.a2a, S.mcp],+ },+ {+ id: 'dao',+ emoji: '🏛️',+ name: 'DAO Delegate',+ description:+ 'Reads governance proposals, summarizes sentiment, and votes on behalf of delegators within a mandate.',+ services: [S.a2a, S.mcp],+ },+ {+ id: 'portfolio',+ emoji: '💼',+ name: 'Portfolio Manager',+ description:+ 'Tracks wallet positions across chains, alerts on drawdown and risk, and rebalances on schedule.',+ services: [S.a2a, S.mcp],+ },+ {+ id: 'defi',+ emoji: '📈',+ name: 'DeFi Trading Agent',+ description:+ 'Automated DeFi yield optimization, liquidity management, and token swaps across protocols.',+ services: [S.a2a, S.mcp, S.x402],+ x402Support: true,+ },+ {+ id: 'support',+ emoji: '🎧',+ name: 'Avatar Support Agent',+ description:+ 'Face-of-the-brand support — tickets, FAQ, and multi-language help with a consistent embodied persona.',+ services: [S.a2a, S.web],+ },+ {+ id: 'code',+ emoji: '🔍',+ name: 'Code Review Agent',+ description:+ 'Automated code analysis, security auditing, gas optimization, and best-practice enforcement.',+ services: [S.a2a, S.mcp, S.x402],+ x402Support: true,+ },+ {+ id: 'data',+ emoji: '📊',+ name: 'Data Analysis Agent',+ description:+ 'On-chain and off-chain data analysis, reporting, visualization, and pattern recognition.',+ services: [S.a2a, S.mcp],+ },+ {+ id: 'content',+ emoji: '✍️',+ name: 'Content Creator',+ description:+ 'AI content generation for social posts, documentation, technical writing, and marketing copy.',+ services: [S.a2a, S.x402],+ x402Support: true,+ },+ {+ id: 'research',+ emoji: '🔬',+ name: 'Research Assistant',+ description: 'Deep research on protocols, tokens, governance proposals, and market trends.',+ services: [S.a2a, S.mcp],+ },+];++const SERVICE_TYPES = ['A2A', 'MCP', 'OASF', 'x402', 'web', 'custom'];++// ───────────────────────────────────────────────────────────────────────────+// Helpers+// ───────────────────────────────────────────────────────────────────────────++const esc = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+const shortAddr = (a) => (a ? a.slice(0, 6) + '…' + a.slice(-4) : '');++/**+ * True if `url` is already a content-addressed or durable public URL that+ * doesn't need to be fetched and re-pinned before referencing in a+ * registration JSON. Avoids wasted uploads for avatars users created+ * earlier (or default avatars shipped on the same domain).+ */+const _isStableUrl = (url) => {+ if (!url || typeof url !== 'string') return false;+ const u = url.trim();+ return (+ u.startsWith('ipfs://') ||+ u.startsWith('ar://') ||+ u.startsWith('https://') ||+ u.startsWith('http://') ||+ u.startsWith('/') // same-origin public asset (e.g. /avatars/cz.glb)+ );+};++// ───────────────────────────────────────────────────────────────────────────+// RegisterUI+// ───────────────────────────────────────────────────────────────────────────++export class RegisterUI {+ /**+ * @param {HTMLElement} containerEl+ * @param {(result: { agentId: number, txHash: string, chainId: number }) => void} [onRegistered]+ * @param {{ initial?: { name?: string, description?: string, imageUrl?: string, glbUrl?: string } }} [opts]+ */+ constructor(containerEl, onRegistered, opts = {}) {+ this.container = containerEl;+ this.onRegistered = onRegistered || (() => {});+ this.mode = opts.mode === 'page' ? 'page' : 'modal';++ // Wallet state+ this.wallet = null; // { address, chainId }++ // Selected chain for reads + writes. Initialized to BSC Testnet; if the+ // wallet is already on a different supported chain, we'll adopt that.+ this.selectedChainId = DEFAULT_CHAIN_ID;++ // Tab state+ this.activeTab = opts.initialTab || 'create';++ const initial = opts.initial || {};++ // Wizard state — pre-populate from the user's current avatar/session so+ // the on-chain JSON points to the GLB they just uploaded/created.+ // `avatarSource` drives Step 3 behaviour:+ // 'current' → use `glbUrl` pre-filled from the live SPA viewer+ // 'saved' → pick one from the signed-in user's saved avatars+ // 'upload' → user drops a new .glb in the wizard+ // 'skip' → deploy as a metadata-only agent (no 3D body)+ this.wizardStep = 1;+ this.form = {+ name: initial.name || '',+ description: initial.description || '',+ imageUrl: initial.imageUrl || '',+ glbUrl: initial.glbUrl || '',+ glbFile: null,+ savedAvatar: null, // { id, name, url, thumbnailUrl }+ defaultAvatarId: null, // id of a pre-pinned DEFAULT_AVATARS entry+ avatarSource: initial.glbUrl ? 'current' : 'upload',+ services: [], // [{ name, type, endpoint }]+ x402Support: false,+ apiToken: '', // optional Pinata JWT+ };++ // Cache of signed-in user's backend agent id (if any) — linked after deploy+ this._backendAgentId = null;+ this._signedIn = false;+ this._savedAvatars = null; // loaded lazily when user switches source to 'saved'++ this._build();+ this._bind();+ this._fetchBackendAgent(); // fire & forget+ this._eagerConnectWallet(); // silent reconnect if wallet already authorized++ // Keep the UI in sync when the user switches account/chain in the wallet,+ // or when another tab/page on this origin connects/disconnects.+ this._unsubscribeWallet = onWalletChange(({ address, chainId }) => {+ if (!address) {+ this.wallet = null;+ } else {+ this.wallet = { address, chainId: Number(chainId) };+ if (REGISTRY_DEPLOYMENTS[this.wallet.chainId]) {+ this.selectedChainId = this.wallet.chainId;+ const sel = this.el.querySelector('.erc8004-chain-select');+ if (sel) sel.value = String(this.selectedChainId);+ }+ }+ this._refreshWalletButton();+ this._renderActiveTab();+ this._refreshMainnetBanner();+ });+ }++ // -----------------------------------------------------------------------+ // Top-level DOM+ // -----------------------------------------------------------------------++ _build() {+ const pageMode = this.mode === 'page';+ this.el = document.createElement('div');+ this.el.className = 'erc8004-register' + (pageMode ? ' erc8004-register--page' : '');+ const closeBtn = pageMode+ ? ''+ : `<button class="erc8004-btn erc8004-btn--close" type="button" title="Close">✕</button>`;+ this.el.innerHTML = `+ <div class="erc8004-card erc8004-card--wide">+ <div class="erc8004-header">+ <div class="erc8004-controls">+ <select class="erc8004-chain-select" title="Target chain"></select>+ <button class="erc8004-btn erc8004-btn--wallet" type="button">+ Connect MetaMask+ </button>+ ${closeBtn}+ </div>+ </div>++ <div class="erc8004-mainnet-banner" data-role="mainnet-banner" style="display:none"></div>++ <nav class="erc8004-tabs" role="tablist">+ <button class="erc8004-tab erc8004-tab--active" data-tab="create">Create Agent</button>+ <button class="erc8004-tab" data-tab="my">My Agents</button>+ <button class="erc8004-tab" data-tab="search">Search</button>+ <button class="erc8004-tab" data-tab="templates">Templates</button>+ <button class="erc8004-tab" data-tab="batch">Batch</button>+ <button class="erc8004-tab" data-tab="history">History</button>+ </nav>++ <div class="erc8004-tab-body" data-role="tab-body"></div>+ </div>+ `;+ this.container.appendChild(this.el);++ this._populateChainSelect();+ this._renderActiveTab();+ this._refreshMainnetBanner();+ }++ _refreshMainnetBanner() {+ const banner = this.el.querySelector('[data-role="mainnet-banner"]');+ if (!banner) return;+ const meta = CHAIN_META[this.selectedChainId];+ if (meta && !meta.testnet) {+ banner.style.display = '';+ banner.innerHTML = `⚠️ <strong>Mainnet Mode</strong> — Transactions use real ${esc(+ meta.currency.symbol,+ )}. Test on a testnet first.`;+ } else {+ banner.style.display = 'none';+ banner.innerHTML = '';+ }+ }++ _bind() {+ this.el+ .querySelector('.erc8004-btn--wallet')+ .addEventListener('click', () => this._connectWallet());+ const closeBtn = this.el.querySelector('.erc8004-btn--close');+ if (closeBtn) closeBtn.addEventListener('click', () => this.destroy());++ this.el.querySelector('.erc8004-chain-select').addEventListener('change', async (e) => {+ const newChain = Number(e.target.value);+ this.selectedChainId = newChain;+ // If wallet connected and on the wrong chain, try to switch+ if (this.wallet && this.wallet.chainId !== newChain && window.ethereum) {+ try {+ await switchChain(newChain);+ this.wallet.chainId = newChain;+ this._refreshWalletButton();+ } catch (err) {+ this._toast('Chain switch rejected: ' + err.message, true);+ }+ }+ this._renderActiveTab();+ this._refreshMainnetBanner();+ });++ this.el.querySelectorAll('.erc8004-tab').forEach((btn) => {+ btn.addEventListener('click', () => this._setTab(btn.dataset.tab));+ });+ }++ destroy() {+ if (this._unsubscribeWallet) this._unsubscribeWallet();+ this.el.remove();+ }++ // -----------------------------------------------------------------------+ // Wallet & chain+ // -----------------------------------------------------------------------++ async _connectWallet() {+ try {+ const { address, chainId } = await connectWallet();+ this.wallet = { address, chainId: Number(chainId) };++ // Adopt wallet's chain if supported; otherwise keep selected and offer switch+ if (REGISTRY_DEPLOYMENTS[this.wallet.chainId]) {+ this.selectedChainId = this.wallet.chainId;+ const sel = this.el.querySelector('.erc8004-chain-select');+ if (sel) sel.value = String(this.selectedChainId);+ }++ this._refreshWalletButton();+ this._renderActiveTab();+ this._refreshMainnetBanner();+ } catch (err) {+ this._toast('Wallet: ' + err.message, true);+ }+ }++ // Silent reconnect on mount — uses `eth_accounts` (no popup). If the wallet+ // has previously authorized this origin and is unlocked, we restore the+ // connection transparently so the user doesn't see "Connect MetaMask" twice.+ async _eagerConnectWallet() {+ const result = await eagerConnectWallet();+ if (!result) return;+ this.wallet = { address: result.address, chainId: Number(result.chainId) };+ if (REGISTRY_DEPLOYMENTS[this.wallet.chainId]) {+ this.selectedChainId = this.wallet.chainId;+ const sel = this.el.querySelector('.erc8004-chain-select');+ if (sel) sel.value = String(this.selectedChainId);+ }+ this._refreshWalletButton();+ this._renderActiveTab();+ this._refreshMainnetBanner();+ }++ _refreshWalletButton() {+ const btn = this.el.querySelector('.erc8004-btn--wallet');+ if (!this.wallet) {+ btn.textContent = 'Connect MetaMask';+ btn.classList.remove('erc8004-btn--connected');+ return;+ }+ btn.textContent = shortAddr(this.wallet.address);+ btn.classList.add('erc8004-btn--connected');+ }++ _populateChainSelect() {+ const sel = this.el.querySelector('.erc8004-chain-select');+ const ids = supportedChainIds();+ // Mainnets first (production-default), then testnets+ const mainnets = ids.filter((id) => !CHAIN_META[id].testnet);+ const testnets = ids.filter((id) => CHAIN_META[id].testnet);+ const groupM = document.createElement('optgroup');+ groupM.label = 'Mainnets';+ const groupT = document.createElement('optgroup');+ groupT.label = 'Testnets';+ for (const id of mainnets) {+ const opt = document.createElement('option');+ opt.value = String(id);+ opt.textContent = CHAIN_META[id].name;+ groupM.appendChild(opt);+ }+ for (const id of testnets) {+ const opt = document.createElement('option');+ opt.value = String(id);+ opt.textContent = CHAIN_META[id].name;+ groupT.appendChild(opt);+ }+ sel.appendChild(groupM);+ sel.appendChild(groupT);+ sel.value = String(this.selectedChainId);+ }++ async _refreshStats() {+ const el = (k) => this.el.querySelector(`[data-stat="${k}"]`);+ try {+ const [total, version] = await Promise.all([+ getTotalSupply(this.selectedChainId).catch(() => null),+ getRegistryVersion(this.selectedChainId).catch(() => null),+ ]);+ const totalEl = el('total');+ const versionEl = el('version');+ if (total !== null && totalEl) totalEl.textContent = String(total);+ if (version && versionEl) versionEl.textContent = version;+ } catch {+ /* swallow; stats are cosmetic */+ }+ }++ // -----------------------------------------------------------------------+ // Backend agent link (optional)+ // -----------------------------------------------------------------------++ async _fetchBackendAgent() {+ try {+ const res = await fetch('/api/agents/me', { credentials: 'include' });+ if (!res.ok) return;+ this._signedIn = true;+ const { agent } = await res.json();+ if (agent && agent.id) this._backendAgentId = agent.id;+ // If Step 3 is already rendered (signed-in detection raced with UI),+ // re-render so the "Use a saved avatar" option appears.+ if (this.wizardStep === 3 && this.activeTab === 'create') this._renderActiveTab();+ } catch {+ /* anon user or endpoint unavailable — fine */+ }+ }++ /**+ * Lazily fetch the signed-in user's saved avatars for the Step 3 picker.+ * Returns [] on any failure (anonymous, endpoint down, etc) so the UI can+ * silently fall back to the upload/skip options.+ */+ async _loadSavedAvatars() {+ if (this._savedAvatars) return this._savedAvatars;+ try {+ const res = await fetch('/api/avatars?limit=50', { credentials: 'include' });+ if (!res.ok) {+ this._savedAvatars = [];+ return this._savedAvatars;+ }+ const payload = await res.json();+ const rows = payload.avatars || payload.data || [];+ this._savedAvatars = rows.map((r) => ({+ id: r.id,+ name: r.name || 'Untitled',+ modelUrl: r.model_url || null, // null for private — resolved on select+ thumbnailUrl: r.thumbnail_url || null,+ visibility: r.visibility,+ }));+ } catch {+ this._savedAvatars = [];+ }+ return this._savedAvatars;+ }++ /**+ * Resolve a saved avatar's download URL. Public/unlisted expose `model_url`+ * directly; private avatars require a per-object signed-URL fetch.+ */+ async _resolveSavedAvatarUrl(avatar) {+ if (avatar.modelUrl) return avatar.modelUrl;+ const res = await fetch(`/api/avatars/${encodeURIComponent(avatar.id)}`, {+ credentials: 'include',+ });+ if (!res.ok) throw new Error(`avatar fetch failed (${res.status})`);+ const { avatar: detail } = await res.json();+ return detail?.url || null;+ }++ async _linkAgentToAccount({ agentId, chainId, txHash, throwOnError = false }) {+ if (!this._backendAgentId || !this.wallet) {+ if (throwOnError) throw new Error('Sign in and connect a wallet first');+ return;+ }+ try {+ const res = await fetch(+ `/api/agents/${encodeURIComponent(this._backendAgentId)}/wallet`,+ {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ wallet_address: this.wallet.address,+ chain_id: chainId,+ erc8004_agent_id: agentId,+ tx_hash: txHash,+ }),+ },+ );+ if (!res.ok) {+ const text = await res.text().catch(() => res.status);+ throw new Error(`link failed (${res.status}): ${text}`);+ }+ } catch (err) {+ console.warn('[erc8004] Failed to link on-chain agentId to account:', err.message);+ if (throwOnError) throw err;+ }+ }++ // -----------------------------------------------------------------------+ // Tabs+ // -----------------------------------------------------------------------++ _setTab(tab) {+ this.activeTab = tab;+ this.el.querySelectorAll('.erc8004-tab').forEach((btn) => {+ btn.classList.toggle('erc8004-tab--active', btn.dataset.tab === tab);+ });+ this._renderActiveTab();+ }++ _renderActiveTab() {+ const body = this.el.querySelector('[data-role="tab-body"]');+ body.innerHTML = '';+ switch (this.activeTab) {+ case 'create':+ this._renderCreate(body);+ break;+ case 'my':+ this._renderMyAgents(body);+ break;+ case 'search':+ this._renderSearch(body);+ break;+ case 'templates':+ this._renderTemplates(body);+ break;+ case 'batch':+ this._renderBatch(body);+ break;+ case 'history':+ this._renderHistory(body);+ break;+ }+ }++ _renderBatch(body) {+ renderBatchTab(body, {+ getWallet: () => this.wallet,+ getChainId: () => this.selectedChainId,+ toast: (msg, err) => this._toast(msg, err),+ });+ }++ // -----------------------------------------------------------------------+ // Tab: Create Agent (4-step wizard)+ // -----------------------------------------------------------------------++ _renderCreate(body) {+ const step = this.wizardStep;+ body.innerHTML = `+ <div class="erc8004-wizard">+ <div class="erc8004-quickstart" data-role="quickstart">+ <div class="erc8004-quickstart-title">How would you like to start?</div>+ <div class="erc8004-quickstart-grid">+ <button class="erc8004-quickstart-btn" data-role="qs-saved" ${this._signedIn ? '' : 'disabled'}>+ <div class="erc8004-quickstart-btn-title">🧑 My saved agent</div>+ <div class="erc8004-quickstart-btn-hint">Prefill from the agent linked to your account.</div>+ </button>+ <button class="erc8004-quickstart-btn" data-role="qs-current">+ <div class="erc8004-quickstart-btn-title">🪄 Current session</div>+ <div class="erc8004-quickstart-btn-hint">Use the avatar loaded in the viewer right now.</div>+ </button>+ <button class="erc8004-quickstart-btn" data-role="qs-scratch">+ <div class="erc8004-quickstart-btn-title">📝 From scratch</div>+ <div class="erc8004-quickstart-btn-hint">Metadata-only agent — add a GLB later if you want.</div>+ </button>+ <button class="erc8004-quickstart-btn" data-role="qs-update">+ <div class="erc8004-quickstart-btn-title">✏️ Update on-chain</div>+ <div class="erc8004-quickstart-btn-hint">Edit an agent you've already registered.</div>+ </button>+ </div>+ </div>+ <ol class="erc8004-steps">+ ${[1, 2, 3, 4]+ .map(+ (n) => `+ <li class="erc8004-step ${n === step ? 'erc8004-step--active' : ''} ${n < step ? 'erc8004-step--done' : ''}">+ <span class="erc8004-step-num">${n}</span>+ <span class="erc8004-step-lbl">${['Identity', 'Services', 'Configuration', 'Deploy'][n - 1]}</span>+ </li>+ `,+ )+ .join('')}+ </ol>+ <div class="erc8004-wizard-body" data-role="wizard-body"></div>+ </div>+ `;+ body.querySelector('[data-role="qs-saved"]').addEventListener('click', () =>+ this._applyQuickStart('saved'),+ );+ body.querySelector('[data-role="qs-current"]').addEventListener('click', () =>+ this._applyQuickStart('current'),+ );+ body.querySelector('[data-role="qs-scratch"]').addEventListener('click', () =>+ this._applyQuickStart('scratch'),+ );+ body.querySelector('[data-role="qs-update"]').addEventListener('click', () =>+ this._applyQuickStart('update'),+ );+ const wbody = body.querySelector('[data-role="wizard-body"]');+ if (step === 1) this._renderStepIdentity(wbody);+ else if (step === 2) this._renderStepServices(wbody);+ else if (step === 3) this._renderStepConfig(wbody);+ else this._renderStepDeploy(wbody);+ }++ /**+ * Apply one of the Step-0 quick-start modes. Resets wizard state appropriately+ * and returns to Step 1. Signed-in-only modes bail with a toast if no session.+ */+ async _applyQuickStart(mode) {+ if (mode === 'update') {+ this._setTab('my');+ this._toast('Pick an agent and click "Edit on-chain ✏️".');+ return;+ }+ if (mode === 'scratch') {+ this.form = {+ name: '',+ description: '',+ imageUrl: '',+ glbUrl: '',+ glbFile: null,+ savedAvatar: null,+ avatarSource: 'skip',+ services: [],+ x402Support: false,+ apiToken: this.form.apiToken || '',+ };+ this.wizardStep = 1;+ this._renderActiveTab();+ return;+ }+ if (mode === 'current') {+ this.form.avatarSource = this.form.glbUrl ? 'current' : 'upload';+ this.wizardStep = 1;+ this._renderActiveTab();+ return;+ }+ if (mode === 'saved') {+ if (!this._signedIn) {+ this._toast('Sign in to use a saved agent.', true);+ return;+ }+ try {+ const res = await fetch('/api/agents/me', { credentials: 'include' });+ const body = await res.json().catch(() => ({}));+ const agent = body?.agent;+ if (!agent) {+ this._toast('No saved agent on this account yet.', true);+ return;+ }+ this.form.name = agent.name || this.form.name;+ this.form.description = agent.description || this.form.description;+ this.form.avatarSource = 'saved';+ this.wizardStep = 1;+ this._renderActiveTab();+ this._loadSavedAvatars?.();+ } catch (err) {+ this._toast('Could not load saved agent: ' + err.message, true);+ }+ }+ }++ _renderStepIdentity(body) {+ body.innerHTML = `+ <h3 class="erc8004-h3">Agent Identity</h3>+ <p class="erc8004-p">Define your agent's core identity — name, description, and image.</p>++ <label class="erc8004-label">Agent Name <span class="erc8004-req">*</span>+ <input class="erc8004-input" name="name" maxlength="100" placeholder="e.g., DeFi Yield Optimizer" value="${esc(this.form.name)}" />+ </label>+ <p class="erc8004-hint">A short, memorable name (max 100 chars)</p>++ <label class="erc8004-label">Description <span class="erc8004-req">*</span>+ <textarea class="erc8004-input erc8004-textarea" name="description" maxlength="1000" rows="4" placeholder="Describe what your agent does, capabilities, pricing…">${esc(this.form.description)}</textarea>+ </label>+ <p class="erc8004-hint">Clear description (max 1000 chars)</p>++ <label class="erc8004-label">Image URL+ <input class="erc8004-input" name="imageUrl" placeholder="https://example.com/avatar.png or ipfs://…" value="${esc(this.form.imageUrl)}" />+ </label>+ <p class="erc8004-hint">Avatar or logo for your agent NFT</p>++ <div class="erc8004-wizard-nav">+ <span></span>+ <button class="erc8004-btn erc8004-btn--primary" data-role="next">Next: Services →</button>+ </div>+ `;+ body.querySelector('[name="name"]').addEventListener(+ 'input',+ (e) => (this.form.name = e.target.value),+ );+ body.querySelector('[name="description"]').addEventListener(+ 'input',+ (e) => (this.form.description = e.target.value),+ );+ body.querySelector('[name="imageUrl"]').addEventListener(+ 'input',+ (e) => (this.form.imageUrl = e.target.value),+ );+ body.querySelector('[data-role="next"]').addEventListener('click', () => {+ if (!this.form.name.trim() || !this.form.description.trim()) {+ this._toast('Name and description are required.', true);+ return;+ }+ this.wizardStep = 2;+ this._renderActiveTab();+ });+ }++ _renderStepServices(body) {+ body.innerHTML = `+ <h3 class="erc8004-h3">Service Endpoints</h3>+ <p class="erc8004-p">Add one or more endpoints so other agents can discover and talk to yours. Optional but recommended.</p>++ <div class="erc8004-services" data-role="list"></div>++ <button class="erc8004-btn erc8004-btn--ghost" data-role="add">+ Add endpoint</button>++ <label class="erc8004-checkbox" style="margin-top:12px">+ <input type="checkbox" data-role="x402" ${this.form.x402Support ? 'checked' : ''} />+ Accept x402 payments (HTTP-native micropayments)+ </label>++ <div class="erc8004-wizard-nav">+ <button class="erc8004-btn" data-role="back">← Back</button>+ <button class="erc8004-btn erc8004-btn--primary" data-role="next">Next: Configuration →</button>+ </div>+ `;+ const list = body.querySelector('[data-role="list"]');+ const renderList = () => {+ list.innerHTML = this.form.services+ .map(+ (svc, i) => `+ <div class="erc8004-svc-row" data-i="${i}">+ <select class="erc8004-input erc8004-input--tight" data-field="type">+ ${SERVICE_TYPES.map((t) => `<option value="${t}" ${svc.type === t ? 'selected' : ''}>${t}</option>`).join('')}+ </select>+ <input class="erc8004-input" data-field="name" placeholder="Name" value="${esc(svc.name)}" />+ <input class="erc8004-input" data-field="endpoint" placeholder="https://… or ipfs://…" value="${esc(svc.endpoint)}" />+ <button class="erc8004-btn erc8004-btn--ghost erc8004-btn--x" data-role="rm" title="Remove">✕</button>+ </div>+ `,+ )+ .join('');++ list.querySelectorAll('.erc8004-svc-row').forEach((row) => {+ const i = Number(row.dataset.i);+ row.querySelectorAll('[data-field]').forEach((input) => {+ input.addEventListener('input', (e) => {+ this.form.services[i][e.target.dataset.field] = e.target.value;+ });+ });+ row.querySelector('[data-role="rm"]').addEventListener('click', () => {+ this.form.services.splice(i, 1);+ renderList();+ });+ });+ };+ renderList();++ body.querySelector('[data-role="add"]').addEventListener('click', () => {+ this.form.services.push({ type: 'A2A', name: '', endpoint: '' });+ renderList();+ });+ body.querySelector('[data-role="x402"]').addEventListener('change', (e) => {+ this.form.x402Support = e.target.checked;+ });+ body.querySelector('[data-role="back"]').addEventListener('click', () => {+ this.wizardStep = 1;+ this._renderActiveTab();+ });+ body.querySelector('[data-role="next"]').addEventListener('click', () => {+ this.wizardStep = 3;+ this._renderActiveTab();+ });+ }++ _renderStepConfig(body) {+ const hasCurrent = !!this.form.glbUrl;+ const canPickSaved = this._signedIn;+ const src = this.form.avatarSource;+ const radio = (value, label, hint, disabled = false) => `+ <label class="erc8004-avatar-source ${src === value ? 'erc8004-avatar-source--active' : ''} ${disabled ? 'erc8004-avatar-source--disabled' : ''}">+ <input type="radio" name="avatarSource" value="${value}" ${src === value ? 'checked' : ''} ${disabled ? 'disabled' : ''} />+ <div>+ <div class="erc8004-avatar-source-title">${label}</div>+ <div class="erc8004-avatar-source-hint">${hint}</div>+ </div>+ </label>+ `;++ body.innerHTML = `+ <h3 class="erc8004-h3">3D Avatar</h3>+ <p class="erc8004-p">Attach a GLB so any 3D-aware client can render your agent's body, or deploy as metadata-only. ERC-8004 doesn't require a 3D avatar — a 2D <code>image</code> works too.</p>++ <div class="erc8004-avatar-sources" data-role="sources">+ ${hasCurrent ? radio('current', 'Use current avatar', `From your active session — <code>${esc(this.form.glbUrl)}</code>`) : ''}+ ${radio('saved', 'Use a saved avatar', canPickSaved ? 'Pick one from your account library.' : 'Sign in to pick from your saved avatars.', !canPickSaved)}+ ${DEFAULT_AVATARS.length ? radio('default', 'Use a default avatar', 'Pick a pre-pinned starter avatar — no upload needed.') : ''}+ ${radio('upload', 'Upload a new GLB', 'Drop or browse a .glb / .gltf file from your machine.')}+ ${radio('skip', 'Skip — no 3D body', 'Deploy as a metadata-only agent. You can attach an avatar later via setAgentURI.')}+ </div>++ <div class="erc8004-avatar-panel" data-role="panel"></div>++ <label class="erc8004-label">IPFS Pinning Token (optional)+ <input class="erc8004-input" type="password" name="apiToken" placeholder="Pinata JWT — leave blank to use built-in R2 storage" value="${esc(this.form.apiToken)}" />+ </label>+ <p class="erc8004-hint">Without a token, uploads go through our backend (R2). Paste a Pinata JWT to pin directly to IPFS.</p>++ <div class="erc8004-wizard-nav">+ <button class="erc8004-btn" data-role="back">← Back</button>+ <button class="erc8004-btn erc8004-btn--primary" data-role="next">Next: Deploy →</button>+ </div>+ `;++ const panel = body.querySelector('[data-role="panel"]');++ const renderPanel = () => {+ const s = this.form.avatarSource;+ if (s === 'current') {+ panel.innerHTML = `+ <div class="erc8004-avatar-summary">+ <span class="erc8004-avatar-summary-badge">✓</span>+ <div>+ <div>Using your current avatar.</div>+ <div class="erc8004-hint"><code>${esc(this.form.glbUrl)}</code></div>+ </div>+ </div>+ `;+ } else if (s === 'saved') {+ panel.innerHTML = `<div class="erc8004-saved-grid" data-role="grid"><div class="erc8004-muted">Loading your avatars…</div></div>`;+ this._loadSavedAvatars().then((list) => {+ const grid = panel.querySelector('[data-role="grid"]');+ if (!grid) return;+ if (!list.length) {+ grid.innerHTML = `<div class="erc8004-muted">No saved avatars yet. <a href="/create" class="erc8004-link">Create one</a> or choose another option above.</div>`;+ return;+ }+ grid.innerHTML = list+ .map(+ (a) => `+ <button type="button" class="erc8004-saved-card ${this.form.savedAvatar?.id === a.id ? 'erc8004-saved-card--active' : ''}" data-id="${esc(a.id)}">+ ${a.thumbnailUrl ? `<img src="${esc(a.thumbnailUrl)}" alt="" loading="lazy" />` : `<div class="erc8004-saved-card-ph">GLB</div>`}+ <div class="erc8004-saved-card-name">${esc(a.name)}</div>+ </button>+ `,+ )+ .join('');+ grid.querySelectorAll('.erc8004-saved-card').forEach((btn) => {+ btn.addEventListener('click', () => {+ const id = btn.dataset.id;+ const picked = list.find((x) => x.id === id);+ this.form.savedAvatar = picked || null;+ renderPanel();+ });+ });+ });+ } else if (s === 'upload') {+ panel.innerHTML = `+ <div class="erc8004-file-drop" data-role="drop">+ <input type="file" accept=".glb,.gltf" class="erc8004-file-input" />+ <span class="erc8004-file-text">${this.form.glbFile ? esc(this.form.glbFile.name) : 'Drop .glb file or click to browse'}</span>+ </div>+ `;+ const drop = panel.querySelector('[data-role="drop"]');+ const input = drop.querySelector('.erc8004-file-input');+ const label = drop.querySelector('.erc8004-file-text');+ const setFile = (f) => {+ if (!f) return;+ if (!/\.(glb|gltf)$/i.test(f.name)) {+ this._toast('Must be a .glb or .gltf file', true);+ return;+ }+ this.form.glbFile = f;+ label.textContent = f.name;+ };+ input.addEventListener('change', (e) => setFile(e.target.files[0]));+ drop.addEventListener('dragover', (e) => {+ e.preventDefault();+ drop.classList.add('erc8004-file-drop--active');+ });+ drop.addEventListener('dragleave', () =>+ drop.classList.remove('erc8004-file-drop--active'),+ );+ drop.addEventListener('drop', (e) => {+ e.preventDefault();+ drop.classList.remove('erc8004-file-drop--active');+ setFile(e.dataTransfer.files[0]);+ });+ } else if (s === 'default') {+ panel.innerHTML = `<div class="erc8004-saved-grid" data-role="grid"></div>`;+ const grid = panel.querySelector('[data-role="grid"]');+ if (!DEFAULT_AVATARS.length) {+ grid.innerHTML = `<div class="erc8004-muted">No default avatars available yet.</div>`;+ } else {+ grid.innerHTML = DEFAULT_AVATARS.map(+ (a) => `+ <button type="button" class="erc8004-saved-card ${this.form.defaultAvatarId === a.id ? 'erc8004-saved-card--active' : ''}" data-id="${esc(a.id)}">+ ${a.thumbnailUrl ? `<img src="${esc(a.thumbnailUrl)}" alt="" loading="lazy" />` : `<div class="erc8004-saved-card-ph">GLB</div>`}+ <div class="erc8004-saved-card-name">${esc(a.name)}</div>+ </button>+ `,+ ).join('');+ grid.querySelectorAll('.erc8004-saved-card').forEach((btn) => {+ btn.addEventListener('click', () => {+ this.form.defaultAvatarId = btn.dataset.id;+ renderPanel();+ });+ });+ }+ } else if (s === 'skip') {+ panel.innerHTML = `+ <div class="erc8004-avatar-summary">+ <span class="erc8004-avatar-summary-badge erc8004-avatar-summary-badge--muted">∅</span>+ <div>+ <div>Deploying as a metadata-only agent.</div>+ <div class="erc8004-hint">Your registration JSON will include <code>image</code> (from Step 1) and services but no GLB. You can attach an avatar later from My Agents → Edit.</div>+ </div>+ </div>+ `;+ }+ };++ renderPanel();++ body.querySelectorAll('input[name="avatarSource"]').forEach((r) => {+ r.addEventListener('change', (e) => {+ this.form.avatarSource = e.target.value;+ this._renderActiveTab(); // re-render to update active-class + panel+ });+ });++ body.querySelector('[name="apiToken"]').addEventListener(+ 'input',+ (e) => (this.form.apiToken = e.target.value),+ );+ body.querySelector('[data-role="back"]').addEventListener('click', () => {+ this.wizardStep = 2;+ this._renderActiveTab();+ });+ body.querySelector('[data-role="next"]').addEventListener('click', () => {+ // Validate the selected source before advancing.+ const s = this.form.avatarSource;+ if (s === 'saved' && !this.form.savedAvatar) {+ this._toast('Pick one of your saved avatars, or choose another option.', true);+ return;+ }+ if (s === 'upload' && !this.form.glbFile) {+ this._toast('Drop a .glb file, or choose another option.', true);+ return;+ }+ if (s === 'default' && !this.form.defaultAvatarId) {+ this._toast('Pick a default avatar, or choose another option.', true);+ return;+ }+ this.wizardStep = 4;+ this._renderActiveTab();+ });+ }++ _renderStepDeploy(body) {+ const meta = CHAIN_META[this.selectedChainId];+ const walletOk = !!this.wallet;+ const chainOk = walletOk && this.wallet.chainId === this.selectedChainId;+ body.innerHTML = `+ <h3 class="erc8004-h3">Review & Deploy</h3>+ <p class="erc8004-p">Your agent will be minted as an ERC-721 NFT on <b>${esc(meta.name)}</b>. This is the only step that costs gas.</p>++ <dl class="erc8004-summary">+ <dt>Name</dt> <dd>${esc(this.form.name)}</dd>+ <dt>Description</dt> <dd>${esc(this.form.description)}</dd>+ ${this.form.imageUrl ? `<dt>Image</dt> <dd>${esc(this.form.imageUrl)}</dd>` : ''}+ <dt>Avatar</dt> <dd>${this._avatarSummary()}</dd>+ <dt>Services</dt> <dd>${this.form.services.length ? this.form.services.map((s) => `${esc(s.type)}: ${esc(s.endpoint || '—')}`).join('<br>') : '<span class="erc8004-muted">none</span>'}</dd>+ <dt>Chain</dt> <dd>${esc(meta.name)} (chainId ${this.selectedChainId})</dd>+ <dt>Registry</dt> <dd><code>${esc(REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry)}</code></dd>+ </dl>++ ${!walletOk ? `<div class="erc8004-alert">Connect a wallet before deploying.</div>` : ''}+ ${walletOk && !chainOk ? `<div class="erc8004-alert">Your wallet is on chain ${this.wallet.chainId}. <button class="erc8004-link" data-role="switch">Switch to ${esc(meta.name)}</button></div>` : ''}++ <details class="erc8004-accordion">+ <summary class="erc8004-accordion-head">📦 Export Options</summary>+ <div class="erc8004-accordion-body">+ <div class="erc8004-export-grid">+ <button type="button" class="erc8004-export-opt" data-role="exp-json">+ <div class="erc8004-export-emoji">📄</div>+ <div class="erc8004-export-title">Export JSON</div>+ <div class="erc8004-export-sub">Raw registration config</div>+ </button>+ <button type="button" class="erc8004-export-opt" data-role="exp-cast">+ <div class="erc8004-export-emoji">⌨️</div>+ <div class="erc8004-export-title">cast / forge</div>+ <div class="erc8004-export-sub">Copy shell command</div>+ </button>+ <button type="button" class="erc8004-export-opt" data-role="exp-viem">+ <div class="erc8004-export-emoji">🧩</div>+ <div class="erc8004-export-title">viem snippet</div>+ <div class="erc8004-export-sub">Copy TS snippet</div>+ </button>+ <button type="button" class="erc8004-export-opt" data-role="exp-curl">+ <div class="erc8004-export-emoji">🌐</div>+ <div class="erc8004-export-title">curl</div>+ <div class="erc8004-export-sub">Graph query stub</div>+ </button>+ </div>+ </div>+ </details>++ <div class="erc8004-log" data-role="log"></div>++ <div class="erc8004-result" data-role="result" style="display:none">+ <h4 class="erc8004-h4">✓ Agent registered</h4>+ <dl class="erc8004-result-dl">+ <dt>Agent ID</dt> <dd data-role="res-id"></dd>+ <dt>Metadata</dt> <dd data-role="res-uri"></dd>+ <dt>Tx Hash</dt> <dd data-role="res-tx"></dd>+ </dl>+ <div class="erc8004-row">+ <button class="erc8004-btn" data-role="view-3d">View in 3D</button>+ <a class="erc8004-btn" data-role="view-explorer" target="_blank" rel="noopener">View on explorer ↗</a>+ </div>+ </div>++ <div class="erc8004-wizard-nav">+ <button class="erc8004-btn" data-role="back">← Back</button>+ <button class="erc8004-btn erc8004-btn--primary" data-role="deploy" ${walletOk ? '' : 'disabled'}>🚀 Register Agent On-Chain</button>+ </div>+ `;+ body.querySelector('[data-role="back"]').addEventListener('click', () => {+ this.wizardStep = 3;+ this._renderActiveTab();+ });++ const switchBtn = body.querySelector('[data-role="switch"]');+ if (switchBtn) {+ switchBtn.addEventListener('click', async () => {+ try {+ await switchChain(this.selectedChainId);+ if (this.wallet) this.wallet.chainId = this.selectedChainId;+ this._renderActiveTab();+ } catch (err) {+ this._toast('Switch failed: ' + err.message, true);+ }+ });+ }++ body.querySelector('[data-role="deploy"]').addEventListener('click', () =>+ this._doDeploy(body),+ );++ this._wireExportOptions(body);+ }++ /**+ * One-line summary of the user's Step 3 avatar choice, shown on the Deploy+ * review screen.+ */+ _avatarSummary() {+ const s = this.form.avatarSource;+ if (s === 'current' && this.form.glbUrl) {+ return `Current session avatar — <code>${esc(this.form.glbUrl)}</code>`;+ }+ if (s === 'saved' && this.form.savedAvatar) {+ return `Saved: ${esc(this.form.savedAvatar.name)}`;+ }+ if (s === 'upload' && this.form.glbFile) {+ return `Uploaded: ${esc(this.form.glbFile.name)} (${(this.form.glbFile.size / 1024).toFixed(1)} KB)`;+ }+ if (s === 'default' && this.form.defaultAvatarId) {+ const def = getDefaultAvatar(this.form.defaultAvatarId);+ return def ? `Default: ${esc(def.name)}` : `Default avatar`;+ }+ if (s === 'skip') return `<span class="erc8004-muted">None — metadata-only</span>`;+ return `<span class="erc8004-muted">Not selected</span>`;+ }++ _wireExportOptions(body) {+ const buildJSON = () => {+ const identityAddr = REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry;+ // Preview JSON should match the shape `_doRegister` actually mints so+ // users export what they're about to deploy.+ const extra = (this.form.services || [])+ .filter((s) => s.endpoint?.trim())+ .map((s) => ({+ name: s.name || s.type,+ type: s.type,+ endpoint: s.endpoint,+ version: '1.0',+ }));+ // Best-effort glbUrl preview: 'current' uses pre-fill; 'saved' uses the+ // picked avatar's known URL; 'default' uses the picked default's known+ // URL; 'upload' is unknown until pin; 'skip' is omitted entirely.+ let glbUrl = null;+ if (this.form.avatarSource === 'current') glbUrl = this.form.glbUrl || null;+ else if (this.form.avatarSource === 'saved')+ glbUrl = this.form.savedAvatar?.modelUrl || null;+ else if (this.form.avatarSource === 'default' && this.form.defaultAvatarId)+ glbUrl = getDefaultAvatar(this.form.defaultAvatarId)?.url || null;+ else if (this.form.avatarSource === 'upload' && this.form.glbFile)+ glbUrl = `<pending-upload:${this.form.glbFile.name}>`;++ return buildRegistrationJSON({+ name: this.form.name,+ description: this.form.description,+ imageUrl: this.form.imageUrl || glbUrl || '',+ glbUrl: glbUrl || undefined,+ agentId: 'PENDING',+ chainId: this.selectedChainId,+ registryAddr: identityAddr,+ services: extra,+ });+ };+ const download = (text, filename, mime = 'application/json') => {+ const blob = new Blob([text], { type: mime });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ setTimeout(() => URL.revokeObjectURL(url), 2000);+ };+ const copy = async (text) => {+ try {+ await navigator.clipboard.writeText(text);+ this._toast('Copied to clipboard');+ } catch {+ this._toast('Copy failed', true);+ }+ };++ const jsonBtn = body.querySelector('[data-role="exp-json"]');+ const castBtn = body.querySelector('[data-role="exp-cast"]');+ const viemBtn = body.querySelector('[data-role="exp-viem"]');+ const curlBtn = body.querySelector('[data-role="exp-curl"]');+ if (!jsonBtn) return;++ jsonBtn.addEventListener('click', () => {+ download(JSON.stringify(buildJSON(), null, 2), 'agent-registration.json');+ this._toast('JSON downloaded');+ });+ castBtn.addEventListener('click', () => {+ const identityAddr = REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry;+ const b64 = btoa(unescape(encodeURIComponent(JSON.stringify(buildJSON()))));+ const uri = `data:application/json;base64,${b64}`;+ const cmd = `cast send ${identityAddr} "register(string)" '${uri}' \\\n --rpc-url ${CHAIN_META[this.selectedChainId].rpcUrl} \\\n --private-key $PRIVATE_KEY`;+ copy(cmd);+ });+ viemBtn.addEventListener('click', () => {+ const identityAddr = REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry;+ const b64 = btoa(unescape(encodeURIComponent(JSON.stringify(buildJSON()))));+ const uri = `data:application/json;base64,${b64}`;+ const snippet = `import { createWalletClient, http, parseAbi } from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\n\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY);\nconst client = createWalletClient({ account, transport: http('${CHAIN_META[this.selectedChainId].rpcUrl}') });\n\nawait client.writeContract({\n address: '${identityAddr}',\n abi: parseAbi(['function register(string) external returns (uint256)']),\n functionName: 'register',\n args: ['${uri}'],\n});`;+ copy(snippet);+ });+ curlBtn.addEventListener('click', () => {+ const identityAddr = REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry;+ const query = `query { agents(where: { registry: "${identityAddr.toLowerCase()}" }, first: 5) { id agentId agentURI owner } }`;+ const cmd = `curl -X POST https://api.thegraph.com/subgraphs/name/erc-8004/registry \\\n -H 'content-type: application/json' \\\n -d '${JSON.stringify({ query })}'`;+ copy(cmd);+ });+ }++ async _doDeploy(body) {+ const log = body.querySelector('[data-role="log"]');+ const say = (msg, err = false) => {+ const line = document.createElement('div');+ line.className = 'erc8004-log-line' + (err ? ' erc8004-log-error' : '');+ line.textContent = msg;+ log.appendChild(line);+ log.scrollTop = log.scrollHeight;+ };+ const deployBtn = body.querySelector('[data-role="deploy"]');+ deployBtn.disabled = true;++ try {+ // Ensure we're on the target chain+ if (this.wallet && this.wallet.chainId !== this.selectedChainId) {+ say(`Switching to ${CHAIN_META[this.selectedChainId].name}…`);+ await switchChain(this.selectedChainId);+ this.wallet.chainId = this.selectedChainId;+ }++ const result = await this._doRegister(say);++ body.querySelector('[data-role="result"]').style.display = '';+ body.querySelector('[data-role="res-id"]').textContent = String(result.agentId);+ body.querySelector('[data-role="res-uri"]').textContent = result.registrationUrl;+ body.querySelector('[data-role="res-tx"]').textContent = result.txHash;++ const view3D = body.querySelector('[data-role="view-3d"]');+ view3D.addEventListener('click', () => {+ window.location.href = `/a/${this.selectedChainId}/${result.agentId}`;+ });+ body.querySelector('[data-role="view-explorer"]').href = txExplorerUrl(+ this.selectedChainId,+ result.txHash,+ );++ this.onRegistered({ ...result, chainId: this.selectedChainId });+ await this._linkAgentToAccount({+ agentId: result.agentId,+ chainId: this.selectedChainId,+ txHash: result.txHash,+ });+ this._refreshStats();+ } catch (err) {+ say('Registration failed: ' + (err.shortMessage || err.message || String(err)), true);+ deployBtn.disabled = false;+ }+ }++ /**+ * Unified deploy flow covering all avatar scenarios:+ * - 'upload' → pin the dropped File+ * - 'current' → reference existing stable URL (ipfs/https) without re-pinning,+ * or fetch+pin if it's a blob:/data: URL+ * - 'saved' → same bypass logic for stable saved-avatar URLs+ * - 'skip' → no GLB, metadata-only agent+ *+ * If a GLB is present but no 2D `imageUrl` was supplied, auto-render a+ * 512×512 PNG thumbnail from the GLB and pin it so ERC-721 marketplaces+ * have a valid value for the `image` field.+ */+ async _doRegister(say) {+ const {+ name,+ description,+ imageUrl: userImageUrl,+ services,+ apiToken,+ avatarSource,+ } = this.form;+ const extraServices = services+ .filter((s) => s.endpoint.trim())+ .map((s) => ({+ name: s.name || s.type,+ type: s.type,+ endpoint: s.endpoint,+ version: '1.0',+ }));++ // Resolve avatarSource → { glbFile?, glbUrl?, imageUrl? }. Stable URLs skip+ // re-pinning; everything else is fetched into a File so `registerAgent` can+ // pin it (and render a 2D thumbnail) uniformly. Defaults ship their own+ // thumbnail, so we pre-seed `imageUrl` to skip client-side re-rendering.+ let glbFile = null;+ let glbUrl = null;+ let imageUrl = userImageUrl;++ if (avatarSource === 'upload') {+ glbFile = this.form.glbFile;+ } else if (avatarSource === 'default' && this.form.defaultAvatarId) {+ const def = getDefaultAvatar(this.form.defaultAvatarId);+ if (def) {+ glbUrl = def.url;+ if (!imageUrl && def.thumbnailUrl) imageUrl = def.thumbnailUrl;+ say(`Using default avatar: ${def.name}`);+ }+ } else if (avatarSource === 'current' && this.form.glbUrl) {+ if (_isStableUrl(this.form.glbUrl)) {+ glbUrl = this.form.glbUrl;+ say(`Reusing existing avatar URL (no re-upload): ${glbUrl}`);+ } else {+ glbFile = await this._fetchUrlAsFile(this.form.glbUrl, say, 'current avatar');+ }+ } else if (avatarSource === 'saved' && this.form.savedAvatar) {+ try {+ say(`Resolving saved avatar: ${this.form.savedAvatar.name}…`);+ const url = await this._resolveSavedAvatarUrl(this.form.savedAvatar);+ if (!url) throw new Error('no download URL');+ if (_isStableUrl(url)) {+ glbUrl = url;+ say(`Reusing saved avatar URL (no re-upload): ${url}`);+ } else {+ glbFile = await this._fetchUrlAsFile(url, say, this.form.savedAvatar.name);+ }+ } catch (err) {+ say(+ `Could not load saved avatar (${err.message}) — deploying metadata-only.`,+ true,+ );+ }+ }++ return await registerAgent({+ name,+ description,+ glbFile: glbFile || undefined,+ glbUrl: glbUrl || undefined,+ imageUrl: imageUrl || undefined,+ apiToken: apiToken || undefined,+ services: extraServices,+ x402Support: !!this.form.x402Support,+ onStatus: say,+ });+ }++ /**+ * Fetch a URL and wrap the response as a File for the pinning pipeline.+ * Returns null on failure (after logging via `say`).+ */+ async _fetchUrlAsFile(url, say, label = 'avatar') {+ try {+ say(`Fetching ${label}…`);+ const res = await fetch(url, { credentials: 'include' });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const blob = await res.blob();+ const fileName = url.split('/').pop()?.split('?')[0] || 'avatar.glb';+ return new File([blob], fileName, { type: blob.type || 'model/gltf-binary' });+ } catch (err) {+ say(`Could not fetch ${label} (${err.message}) — continuing without GLB.`, true);+ return null;+ }+ }++ // -----------------------------------------------------------------------+ // Tab: My Agents+ // -----------------------------------------------------------------------++ _renderMyAgents(body) {+ body.innerHTML = `+ <h3 class="erc8004-h3">Your Registered Agents</h3>+ ${+ this.wallet+ ? `<p class="erc8004-p">Connected as <code>${esc(this.wallet.address)}</code> on <b>${esc(CHAIN_META[this.selectedChainId]?.name || '?')}</b>.</p>`+ : `<p class="erc8004-p erc8004-muted">Connect a wallet to see agents you own.</p>`+ }+ <div data-role="list"></div>+ `;+ if (!this.wallet) return;++ const list = body.querySelector('[data-role="list"]');+ list.innerHTML = `<div class="erc8004-muted">Scanning…</div>`;++ listAgentsByOwner({+ chainId: this.selectedChainId,+ owner: this.wallet.address,+ ethProvider: window.ethereum,+ })+ .then(async (res) => {+ if (res.count === 0) {+ list.innerHTML = `<div class="erc8004-muted">No agents registered on this chain yet. <a class="erc8004-link" data-role="goto-create">Create one →</a> or <a class="erc8004-link" href="/discover" target="_blank" rel="noopener">browse other on-chain agents ↗</a>.</div>`;+ list.querySelector('[data-role="goto-create"]').addEventListener(+ 'click',+ (e) => {+ e.preventDefault();+ this._setTab('create');+ },+ );+ return;+ }+ if (res.ids.length === 0 && res.partial) {+ const explorer = addressExplorerUrl(this.selectedChainId, this.wallet.address);+ list.innerHTML = `+ <div class="erc8004-muted">+ You own ${res.count} agent(s) but details could not be loaded from recent blocks.+ <a href="${esc(explorer)}" target="_blank" rel="noopener" class="erc8004-link">Check explorer ↗</a>+ </div>`;+ return;+ }+ list.innerHTML = '';+ for (const id of res.ids) {+ const card = document.createElement('div');+ card.className = 'erc8004-agent-card';+ card.innerHTML = `<div class="erc8004-muted">Loading #${id}…</div>`;+ list.appendChild(card);+ this._fillAgentCard(card, id, { withQR: true, withEdit: true });+ }+ if (res.partial) {+ const note = document.createElement('div');+ note.className = 'erc8004-muted';+ note.textContent = `Showing ${res.ids.length} of ${res.count} agents — older mints may be outside the scanned block window.`;+ list.appendChild(note);+ }+ })+ .catch((err) => {+ list.innerHTML = `<div class="erc8004-log-error">Query failed: ${esc(err.message)}</div>`;+ });+ }++ async _fillAgentCard(card, agentId, opts = {}) {+ try {+ const { uri, owner } = await getAgentOnchain({+ chainId: this.selectedChainId,+ agentId,+ ethProvider: window.ethereum,+ });+ const meta = uri ? await fetchAgentMetadata(uri) : { ok: false, error: 'no uri' };+ const registryAddr = REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry;+ const tokenUrl = tokenExplorerUrl(this.selectedChainId, registryAddr, agentId);++ const name = meta.ok ? meta.data.name || `Agent #${agentId}` : `Agent #${agentId}`;+ const description = meta.ok ? meta.data.description : '';+ const image = meta.ok ? meta.data.image : '';+ const glbUrl = meta.ok ? findAvatar3D(meta.data) : null;+ const hasX402 = meta.ok && (meta.data.x402Support || meta.data.x402);+ card._meta = meta.ok ? meta.data : null;+ card._owner = owner;+ const publicUrl = `/a/${this.selectedChainId}/${agentId}`;++ const isOwner =+ this.wallet && owner && this.wallet.address.toLowerCase() === owner.toLowerCase();+ const showLink = isOwner && this._signedIn && this._backendAgentId;++ card.innerHTML = `+ <div class="erc8004-agent-card-inner">+ <div class="erc8004-agent-card-img">+ ${image ? `<img src="${esc(resolveGateway(image))}" alt="" loading="lazy" />` : `<div class="erc8004-agent-card-ph">🤖</div>`}+ </div>+ <div class="erc8004-agent-card-body">+ <div class="erc8004-agent-card-head">+ <strong>${esc(name)}</strong>+ <span class="erc8004-tag">#${agentId}</span>+ ${hasX402 ? `<span class="erc8004-tag erc8004-tag--x402">x402 💳</span>` : ''}+ ${isOwner ? `<span class="erc8004-tag erc8004-tag--owner">You own this</span>` : ''}+ ${glbUrl ? `<span class="erc8004-tag" title="Resolvable 3D avatar">3D</span>` : ''}+ </div>+ ${description ? `<p class="erc8004-p erc8004-clip">${esc(description)}</p>` : ''}+ <div class="erc8004-agent-card-actions">+ ${tokenUrl ? `<a class="erc8004-link" href="${esc(tokenUrl)}" target="_blank" rel="noopener">Details ↗</a>` : ''}+ ${glbUrl ? `<a class="erc8004-link" href="${esc(publicUrl)}">Open in 3D ↗</a>` : `<a class="erc8004-link" href="#agent=${agentId}">Open in viewer</a>`}+ <button type="button" class="erc8004-link" data-role="embed">Embed </></button>+ ${opts.withQR && tokenUrl ? `<button type="button" class="erc8004-link" data-role="qr">QR</button>` : ''}+ ${opts.withEdit ? `<button type="button" class="erc8004-link" data-role="edit">Edit on-chain ✏️</button>` : ''}+ ${isOwner ? `<button type="button" class="erc8004-link" data-role="redeploy">Deploy on another chain 🌐</button>` : ''}+ ${isOwner ? `<button type="button" class="erc8004-link" data-role="transfer">Transfer 🔁</button>` : ''}+ ${showLink ? `<button type="button" class="erc8004-link" data-role="link">Link to my account 🔗</button>` : ''}+ </div>+ </div>+ </div>+ `;++ const embedBtn = card.querySelector('[data-role="embed"]');+ if (embedBtn)+ embedBtn.addEventListener('click', () =>+ this._openEmbedModal({ agentId, name, glbUrl }),+ );+ if (opts.withQR && tokenUrl) {+ const qrBtn = card.querySelector('[data-role="qr"]');+ if (qrBtn)+ qrBtn.addEventListener('click', () =>+ this._openQRModal({ agentId, url: tokenUrl }),+ );+ }+ if (opts.withEdit) {+ const editBtn = card.querySelector('[data-role="edit"]');+ if (editBtn)+ editBtn.addEventListener('click', () =>+ this._openEditModal({ agentId, currentMeta: card._meta, card }),+ );+ }+ const redeployBtn = card.querySelector('[data-role="redeploy"]');+ if (redeployBtn)+ redeployBtn.addEventListener('click', () =>+ this._openRedeployModal({ agentId, currentMeta: card._meta }),+ );+ const transferBtn = card.querySelector('[data-role="transfer"]');+ if (transferBtn)+ transferBtn.addEventListener('click', () =>+ this._openTransferModal({ agentId, card }),+ );+ const linkBtn = card.querySelector('[data-role="link"]');+ if (linkBtn)+ linkBtn.addEventListener('click', async () => {+ linkBtn.disabled = true;+ linkBtn.textContent = 'Linking…';+ try {+ await this._linkAgentToAccount({+ agentId: Number(agentId),+ chainId: this.selectedChainId,+ throwOnError: true,+ });+ linkBtn.textContent = 'Linked ✓';+ this._toast('Agent linked to your account');+ } catch (err) {+ linkBtn.disabled = false;+ linkBtn.textContent = 'Link to my account 🔗';+ this._toast(`Link failed: ${err.message}`, true);+ }+ });+ } catch (err) {+ card.innerHTML = `<div class="erc8004-log-error">Agent #${agentId}: ${esc(err.message)}</div>`;+ }+ }++ _openQRModal({ agentId, url }) {+ const chainName = CHAIN_META[this.selectedChainId]?.name || '?';+ const modal = document.createElement('div');+ modal.className = 'erc8004-modal';+ modal.innerHTML = `+ <div class="erc8004-modal-card">+ <div class="erc8004-modal-head">+ <div class="erc8004-h4" style="margin:0">Agent QR Code</div>+ <button class="erc8004-btn erc8004-btn--x" data-role="close" title="Close">✕</button>+ </div>+ <p class="erc8004-muted erc8004-small">Agent #${String(agentId)} on ${esc(chainName)}</p>+ <div class="erc8004-qr-canvas-wrap" data-role="canvas"></div>+ <p class="erc8004-muted erc8004-small erc8004-qr-url">${esc(url)}</p>+ <div class="erc8004-row" style="justify-content:center">+ <button class="erc8004-btn erc8004-btn--primary" data-role="download">Download PNG</button>+ <button class="erc8004-btn" data-role="copy">Copy Link</button>+ </div>+ </div>+ `;+ this.el.appendChild(modal);++ let canvas;+ try {+ canvas = renderQRToCanvas(url, { scale: 6, margin: 2 });+ modal.querySelector('[data-role="canvas"]').appendChild(canvas);+ } catch (err) {+ modal.querySelector('[data-role="canvas"]').innerHTML =+ `<div class="erc8004-log-error">QR error: ${esc(err.message)}</div>`;+ }++ const close = () => modal.remove();+ modal.addEventListener('click', (e) => {+ if (e.target === modal) close();+ });+ modal.querySelector('[data-role="close"]').addEventListener('click', close);+ modal.querySelector('[data-role="download"]').addEventListener('click', () => {+ if (!canvas) return;+ const a = document.createElement('a');+ a.href = canvas.toDataURL('image/png');+ a.download = `agent-${String(agentId)}-qr.png`;+ a.click();+ });+ modal.querySelector('[data-role="copy"]').addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(url);+ this._toast('Link copied!');+ } catch {+ this._toast('Copy failed', true);+ }+ });+ }++ /**+ * Embed-snippet modal. Gives the owner four ready-to-paste surfaces for+ * their on-chain agent: a web-component tag, a plain iframe, a share URL,+ * and the oEmbed discovery URL. Any page that discovers this agent can+ * render it the same way — chain is the source of truth.+ */+ _openEmbedModal({ agentId, name, glbUrl }) {+ const chainId = this.selectedChainId;+ const origin = location.origin;+ const pageUrl = `${origin}/a/${chainId}/${agentId}`;+ const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;+ const oembedUrl = `${origin}/api/oembed?url=${encodeURIComponent(pageUrl)}`;+ const cdnBase = `${origin}/agent-3d/latest/agent-3d.js`;++ const snippetWC =+ `<script type="module" src="${cdnBase}"></script>\n` ++ `<agent-3d chain-id="${chainId}" agent-id="${agentId}" style="width:420px;height:520px"></agent-3d>`;+ const snippetIframe =+ `<iframe src="${embedUrl}" width="420" height="520" ` ++ `style="border:0;border-radius:12px" ` ++ `allow="autoplay; xr-spatial-tracking" ` ++ `sandbox="allow-scripts allow-same-origin allow-popups"></iframe>`;++ const modal = document.createElement('div');+ modal.className = 'erc8004-modal';+ modal.innerHTML = `+ <div class="erc8004-modal-card" style="max-width:640px">+ <div class="erc8004-modal-head">+ <div class="erc8004-h4" style="margin:0">Embed ${esc(name || 'agent')}</div>+ <button class="erc8004-btn erc8004-btn--x" data-role="close" title="Close">✕</button>+ </div>+ <p class="erc8004-muted erc8004-small">+ Any surface can render this agent from chain data alone — no backend account needed.+ ${glbUrl ? '' : '<br><b>Note:</b> this agent has no 3D body registered yet. Add one via Edit on-chain.'}+ </p>+ <div class="erc8004-embed-tabs" role="tablist">+ <button type="button" data-tab="wc" class="erc8004-tab is-active">Web component</button>+ <button type="button" data-tab="if" class="erc8004-tab">iframe</button>+ <button type="button" data-tab="sh" class="erc8004-tab">Share URL</button>+ <button type="button" data-tab="oe" class="erc8004-tab">oEmbed</button>+ </div>+ <div class="erc8004-embed-panels">+ <div data-panel="wc" class="is-active">+ <p class="erc8004-muted erc8004-small">Drop into any HTML page. Self-contained, no build step.</p>+ <textarea class="erc8004-code" data-role="code-wc" readonly rows="4">${esc(snippetWC)}</textarea>+ <button class="erc8004-btn erc8004-btn--primary" data-copy="wc">Copy</button>+ </div>+ <div data-panel="if" hidden>+ <p class="erc8004-muted erc8004-small">Works everywhere iframes do — Notion, Ghost, WordPress, Substack.</p>+ <textarea class="erc8004-code" data-role="code-if" readonly rows="4">${esc(snippetIframe)}</textarea>+ <button class="erc8004-btn erc8004-btn--primary" data-copy="if">Copy</button>+ </div>+ <div data-panel="sh" hidden>+ <p class="erc8004-muted erc8004-small">Paste anywhere (Discord, Slack, X, Farcaster) — OG preview + Twitter Player Card auto-render.</p>+ <textarea class="erc8004-code" data-role="code-sh" readonly rows="2">${esc(pageUrl)}</textarea>+ <button class="erc8004-btn erc8004-btn--primary" data-copy="sh">Copy</button>+ </div>+ <div data-panel="oe" hidden>+ <p class="erc8004-muted erc8004-small">For apps that consume <a href="https://oembed.com" target="_blank" rel="noopener">oEmbed</a> directly (Notion, some CMSes).</p>+ <textarea class="erc8004-code" data-role="code-oe" readonly rows="2">${esc(oembedUrl)}</textarea>+ <button class="erc8004-btn erc8004-btn--primary" data-copy="oe">Copy</button>+ </div>+ </div>+ <details class="erc8004-embed-policy">+ <summary>Restrict where this agent can be embedded</summary>+ <p class="erc8004-muted erc8004-small">+ Add <code>embedPolicy</code> to your registration JSON (via Edit on-chain):+ </p>+ <pre class="erc8004-code" style="user-select:text">{+ "embedPolicy": {+ "mode": "allowlist",+ "hosts": ["example.com", "*.mysite.xyz"]+ }+}</pre>+ <p class="erc8004-muted erc8004-small">+ Chain is the source of truth — policy is enforced by every embed surface.+ </p>+ </details>+ </div>+ `;+ this.el.appendChild(modal);++ const close = () => modal.remove();+ modal.addEventListener('click', (e) => {+ if (e.target === modal) close();+ });+ modal.querySelector('[data-role="close"]').addEventListener('click', close);++ modal.querySelectorAll('.erc8004-tab').forEach((tab) => {+ tab.addEventListener('click', () => {+ const id = tab.getAttribute('data-tab');+ modal+ .querySelectorAll('.erc8004-tab')+ .forEach((t) => t.classList.toggle('is-active', t === tab));+ modal.querySelectorAll('[data-panel]').forEach((p) => {+ const match = p.getAttribute('data-panel') === id;+ p.hidden = !match;+ p.classList.toggle('is-active', match);+ });+ });+ });++ modal.querySelectorAll('[data-copy]').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const which = btn.getAttribute('data-copy');+ const ta = modal.querySelector(`[data-role="code-${which}"]`);+ if (!ta) return;+ try {+ await navigator.clipboard.writeText(ta.value);+ const prev = btn.textContent;+ btn.textContent = 'Copied ✓';+ setTimeout(() => (btn.textContent = prev), 1400);+ } catch {+ ta.select();+ document.execCommand('copy');+ this._toast('Copied');+ }+ });+ });+ }++ /**+ * Edit modal for an existing on-chain agent. Lets the owner update+ * name / description / 2D image / 3D body, then pins a new registration+ * JSON and calls setAgentURI(agentId, newURI). Preserves unrelated+ * fields from the current metadata (services, registrations, trust, etc.).+ */+ _openEditModal({ agentId, currentMeta, card }) {+ const meta = currentMeta || {};+ const modal = document.createElement('div');+ modal.className = 'erc8004-modal';+ modal.innerHTML = `+ <div class="erc8004-modal-card">+ <div class="erc8004-modal-head">+ <div class="erc8004-h4" style="margin:0">Edit Agent #${String(agentId)}</div>+ <button class="erc8004-btn erc8004-btn--x" data-role="close" title="Close">✕</button>+ </div>+ <p class="erc8004-muted erc8004-small">Updates are written on-chain via <code>setAgentURI()</code>. Re-pins the registration JSON and points <code>agentURI</code> at the new CID.</p>++ <label class="erc8004-label">Name+ <input class="erc8004-input" name="name" value="${esc(meta.name || '')}" />+ </label>+ <label class="erc8004-label">Description+ <textarea class="erc8004-input" name="description" rows="3">${esc(meta.description || '')}</textarea>+ </label>+ <label class="erc8004-label">Image URL (2D — for marketplaces)+ <input class="erc8004-input" name="imageUrl" value="${esc(meta.image || '')}" placeholder="https://… or ipfs://…" />+ </label>+ <label class="erc8004-label">3D Avatar (GLB) — optional, replaces existing body+ <input type="file" accept=".glb,.gltf" class="erc8004-file-input" name="glb" />+ </label>+ ${+ currentMeta?.body?.uri ||+ (currentMeta?.services || []).some((s) => s?.name === 'avatar')+ ? `<label class="erc8004-checkbox">+ <input type="checkbox" name="removeAvatar" />+ Remove 3D avatar from this agent (clears body + avatar service)+ </label>`+ : ''+ }+ <label class="erc8004-checkbox">+ <input type="checkbox" name="x402Support" ${currentMeta?.x402Support || currentMeta?.x402 ? 'checked' : ''} />+ Accept x402 payments (HTTP-native micropayments)+ </label>+ <label class="erc8004-label">Pinata JWT (optional)+ <input class="erc8004-input" name="apiToken" placeholder="leave blank for R2 backend" />+ </label>++ <div class="erc8004-log" data-role="log"></div>++ <div class="erc8004-row" style="justify-content:flex-end">+ <button class="erc8004-btn" data-role="cancel">Cancel</button>+ <button class="erc8004-btn erc8004-btn--primary" data-role="save">Save on-chain</button>+ </div>+ </div>+ `;+ this.el.appendChild(modal);++ const close = () => modal.remove();+ modal.addEventListener('click', (e) => {+ if (e.target === modal) close();+ });+ modal.querySelector('[data-role="close"]').addEventListener('click', close);+ modal.querySelector('[data-role="cancel"]').addEventListener('click', close);++ modal.querySelector('[data-role="save"]').addEventListener('click', async () => {+ const saveBtn = modal.querySelector('[data-role="save"]');+ const log = modal.querySelector('[data-role="log"]');+ const say = (msg, err = false) => {+ const line = document.createElement('div');+ line.className = 'erc8004-log-line' + (err ? ' erc8004-log-error' : '');+ line.textContent = msg;+ log.appendChild(line);+ log.scrollTop = log.scrollHeight;+ };+ saveBtn.disabled = true;+ try {+ const name = modal.querySelector('[name="name"]').value.trim();+ const description = modal.querySelector('[name="description"]').value.trim();+ const imageUrlInput = modal.querySelector('[name="imageUrl"]').value.trim();+ const apiToken = modal.querySelector('[name="apiToken"]').value.trim() || undefined;+ const fileInput = modal.querySelector('[name="glb"]');+ const glbFile = fileInput.files?.[0] || null;+ const removeAvatar = !!modal.querySelector('[name="removeAvatar"]')?.checked;+ const x402Support = !!modal.querySelector('[name="x402Support"]')?.checked;++ await this._doUpdateAgent({+ agentId,+ name,+ description,+ imageUrl: imageUrlInput,+ glbFile,+ removeAvatar,+ x402Support,+ apiToken,+ currentMeta: meta,+ say,+ });++ this._toast('Agent updated on-chain');+ close();+ if (card) this._fillAgentCard(card, agentId, { withQR: true, withEdit: true });+ } catch (err) {+ say('Update failed: ' + (err.shortMessage || err.message || String(err)), true);+ saveBtn.disabled = false;+ }+ });+ }++ /**+ * Build + pin a new registration JSON and call setAgentURI on-chain.+ * Preserves `services`, `registrations`, `supportedTrust`, `x402Support`+ * from the existing metadata; only touches the fields the user edited.+ */+ async _doUpdateAgent({+ agentId,+ name,+ description,+ imageUrl,+ glbFile,+ removeAvatar = false,+ x402Support,+ apiToken,+ currentMeta,+ say,+ }) {+ // Find the current GLB URL from the metadata (it lives in services[name=avatar]+ // or the top-level body field — check both).+ const existingGlbUrl =+ currentMeta?.body?.uri ||+ (currentMeta?.services || []).find((s) => s?.name === 'avatar' && s?.endpoint)+ ?.endpoint;++ let glbUrl = removeAvatar ? undefined : existingGlbUrl || undefined;+ let newImageUrl = imageUrl;++ if (removeAvatar) {+ say('Avatar will be removed from this agent.');+ }++ // If user uploaded a new GLB, pin it and re-render thumbnail when image is empty.+ // Uploading a new GLB overrides a `removeAvatar` checkbox — user likely meant to+ // replace rather than delete.+ if (glbFile) {+ say('Uploading new 3D model…');+ glbUrl = await pinFile(glbFile, apiToken);+ say(`Model uploaded: ${glbUrl}`);+ if (!newImageUrl) {+ try {+ say('Rendering 2D thumbnail from new GLB…');+ const thumb = await glbFileToThumbnail(glbFile);+ newImageUrl = await pinFile(thumb, apiToken);+ say(`Thumbnail uploaded: ${newImageUrl}`);+ } catch (err) {+ say(`Thumbnail render failed (${err.message}) — keeping existing image.`);+ newImageUrl = currentMeta?.image || '';+ }+ }+ }++ // Preserve non-avatar services (user-added A2A/MCP/etc.) and other fields.+ const preservedServices = (currentMeta?.services || []).filter(+ (s) => s?.name !== 'avatar' && s?.name !== '3D',+ );++ say('Connecting wallet…');+ const { signer, chainId } = await connectWallet();+ if (chainId !== this.selectedChainId) {+ throw new Error(+ `Wallet is on chain ${chainId} but this agent lives on ${this.selectedChainId} (${CHAIN_META[this.selectedChainId]?.name || 'unknown'}). Switch chains in your wallet and try again.`,+ );+ }+ const registry = getIdentityRegistry(chainId, signer);+ const registryAddr = REGISTRY_DEPLOYMENTS[chainId].identityRegistry;++ const registrationJSON = buildRegistrationJSON({+ name,+ description,+ imageUrl: newImageUrl || '',+ glbUrl,+ agentId,+ chainId,+ registryAddr,+ services: preservedServices,+ x402Support:+ typeof x402Support === 'boolean'+ ? x402Support+ : !!(currentMeta?.x402Support || currentMeta?.x402),+ });++ say('Uploading new registration metadata…');+ const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], {+ type: 'application/json',+ });+ const newUri = await pinFile(jsonBlob, apiToken);+ say(`New metadata: ${newUri}`);++ say('Calling setAgentURI on-chain…');+ const tx = await registry.setAgentURI(agentId, newUri);+ say(`Transaction submitted: ${tx.hash}`);+ await tx.wait();+ say('Agent URI updated ✓');+ }++ // -----------------------------------------------------------------------+ // Transfer ownership — ERC-721 safeTransferFrom+ // -----------------------------------------------------------------------++ _openTransferModal({ agentId, card }) {+ const modal = document.createElement('div');+ modal.className = 'erc8004-modal';+ modal.innerHTML = `+ <div class="erc8004-modal-card">+ <div class="erc8004-modal-head">+ <div class="erc8004-h4" style="margin:0">Transfer Agent #${String(agentId)}</div>+ <button class="erc8004-btn erc8004-btn--x" data-role="close" title="Close">✕</button>+ </div>+ <p class="erc8004-muted erc8004-small">Transfers the agent NFT to a new owner on <b>${esc(CHAIN_META[this.selectedChainId]?.name || '?')}</b>. The new owner gains full control — they can update the URI, transfer it again, or burn it.</p>+ <label class="erc8004-label">Recipient address+ <input class="erc8004-input" name="to" placeholder="0x…" />+ </label>+ <div class="erc8004-log" data-role="log"></div>+ <div class="erc8004-row" style="justify-content:flex-end">+ <button class="erc8004-btn" data-role="cancel">Cancel</button>+ <button class="erc8004-btn erc8004-btn--primary" data-role="go">Transfer</button>+ </div>+ </div>+ `;+ this.el.appendChild(modal);+ const close = () => modal.remove();+ modal.addEventListener('click', (e) => {+ if (e.target === modal) close();+ });+ modal.querySelector('[data-role="close"]').addEventListener('click', close);+ modal.querySelector('[data-role="cancel"]').addEventListener('click', close);++ modal.querySelector('[data-role="go"]').addEventListener('click', async () => {+ const btn = modal.querySelector('[data-role="go"]');+ const log = modal.querySelector('[data-role="log"]');+ const say = (msg, err = false) => {+ const line = document.createElement('div');+ line.className = 'erc8004-log-line' + (err ? ' erc8004-log-error' : '');+ line.textContent = msg;+ log.appendChild(line);+ };+ const to = modal.querySelector('[name="to"]').value.trim();+ if (!/^0x[0-9a-fA-F]{40}$/.test(to)) {+ say('Invalid recipient address.', true);+ return;+ }+ btn.disabled = true;+ try {+ say('Connecting wallet…');+ const { signer, address } = await connectWallet();+ const registry = getIdentityRegistry(this.selectedChainId, signer);+ say('Submitting safeTransferFrom…');+ const tx = await registry['safeTransferFrom(address,address,uint256)'](+ address,+ to,+ agentId,+ );+ say(`Transaction: ${tx.hash}`);+ await tx.wait();+ say('Transfer complete ✓');+ this._toast('Agent transferred');+ close();+ if (card) this._fillAgentCard(card, agentId, { withQR: true, withEdit: true });+ } catch (err) {+ say('Transfer failed: ' + (err.shortMessage || err.message || String(err)), true);+ btn.disabled = false;+ }+ });+ }++ // -----------------------------------------------------------------------+ // Deploy on another chain — re-mint using the current agent's metadata+ // -----------------------------------------------------------------------++ _openRedeployModal({ agentId, currentMeta }) {+ const meta = currentMeta || {};+ const chainOptions = supportedChainIds()+ .filter((id) => id !== this.selectedChainId)+ .map(+ (id) =>+ `<option value="${id}">${esc(CHAIN_META[id]?.name || id)} ${CHAIN_META[id]?.testnet ? '(testnet)' : ''}</option>`,+ )+ .join('');++ const modal = document.createElement('div');+ modal.className = 'erc8004-modal';+ modal.innerHTML = `+ <div class="erc8004-modal-card">+ <div class="erc8004-modal-head">+ <div class="erc8004-h4" style="margin:0">Deploy #${String(agentId)} on another chain</div>+ <button class="erc8004-btn erc8004-btn--x" data-role="close" title="Close">✕</button>+ </div>+ <p class="erc8004-muted erc8004-small">Mints a new agent on the selected chain reusing this agent's name, description, image, and 3D body. The new agent gets its own on-chain ID — nothing about the original changes.</p>+ <label class="erc8004-label">Target chain+ <select class="erc8004-input" name="chain">${chainOptions}</select>+ </label>+ <label class="erc8004-label">Pinata JWT (optional)+ <input class="erc8004-input" name="apiToken" placeholder="leave blank for R2 backend" />+ </label>+ <div class="erc8004-log" data-role="log"></div>+ <div class="erc8004-row" style="justify-content:flex-end">+ <button class="erc8004-btn" data-role="cancel">Cancel</button>+ <button class="erc8004-btn erc8004-btn--primary" data-role="go">Deploy</button>+ </div>+ </div>+ `;+ this.el.appendChild(modal);+ const close = () => modal.remove();+ modal.addEventListener('click', (e) => {+ if (e.target === modal) close();+ });+ modal.querySelector('[data-role="close"]').addEventListener('click', close);+ modal.querySelector('[data-role="cancel"]').addEventListener('click', close);++ modal.querySelector('[data-role="go"]').addEventListener('click', async () => {+ const btn = modal.querySelector('[data-role="go"]');+ const log = modal.querySelector('[data-role="log"]');+ const say = (msg, err = false) => {+ const line = document.createElement('div');+ line.className = 'erc8004-log-line' + (err ? ' erc8004-log-error' : '');+ line.textContent = msg;+ log.appendChild(line);+ };+ const targetChainId = Number(modal.querySelector('[name="chain"]').value);+ const apiToken = modal.querySelector('[name="apiToken"]').value.trim() || undefined;+ btn.disabled = true;+ try {+ say(`Switching wallet to ${CHAIN_META[targetChainId]?.name || targetChainId}…`);+ await switchChain(targetChainId);+ const existingGlb = (meta.services || []).find(+ (s) => s?.name === 'avatar' && s?.endpoint,+ )?.endpoint;+ let glbFile = null;+ if (existingGlb) {+ glbFile = await this._fetchUrlAsFile(+ existingGlb.startsWith('ipfs://')+ ? 'https://ipfs.io/ipfs/' + existingGlb.slice(7)+ : existingGlb,+ say,+ '3D body',+ );+ }+ const preservedServices = (meta.services || []).filter(+ (s) => s?.name !== 'avatar' && s?.name !== '3D',+ );+ say('Registering on new chain…');+ const result = await registerAgent({+ glbFile,+ name: meta.name || `Agent #${agentId}`,+ description: meta.description || '',+ imageUrl: meta.image || '',+ apiToken,+ services: preservedServices,+ x402Support: !!(meta.x402Support || meta.x402),+ onStatus: (m) => say(m),+ });+ say(`Deployed! New agentId = ${result.agentId} on chain ${targetChainId}`);+ this._toast(`Deployed as #${result.agentId} on ${CHAIN_META[targetChainId]?.name}`);+ close();+ } catch (err) {+ say('Deploy failed: ' + (err.shortMessage || err.message || String(err)), true);+ btn.disabled = false;+ }+ });+ }++ // -----------------------------------------------------------------------+ // Tab: Search+ // -----------------------------------------------------------------------++ _renderSearch(body) {+ if (!this._searchFilter) this._searchFilter = 'all';+ const chainName = esc(CHAIN_META[this.selectedChainId]?.name);+ body.innerHTML = `+ <h3 class="erc8004-h3">Agent Search</h3>+ <p class="erc8004-p">+ Look up agents on <b>${chainName}</b> by ID, wallet address, ENS name, tx hash, or <code>agent://</code> URI.+ Need cross-chain? <a class="erc8004-link" href="/discover" target="_blank" rel="noopener">Open /discover ↗</a>.+ </p>+ <div class="erc8004-row">+ <input class="erc8004-input" name="q" placeholder="Agent ID · 0x address · ENS · tx hash · agent://chain/id" />+ <button class="erc8004-btn erc8004-btn--primary" data-role="go">Search</button>+ </div>+ <div class="erc8004-filter-chips" data-role="chips">+ <button class="erc8004-chip ${this._searchFilter === 'all' ? 'erc8004-chip--active' : ''}" data-filter="all">All</button>+ <button class="erc8004-chip ${this._searchFilter === 'A2A' ? 'erc8004-chip--active' : ''}" data-filter="A2A">A2A</button>+ <button class="erc8004-chip ${this._searchFilter === 'MCP' ? 'erc8004-chip--active' : ''}" data-filter="MCP">MCP</button>+ <button class="erc8004-chip ${this._searchFilter === 'OASF' ? 'erc8004-chip--active' : ''}" data-filter="OASF">OASF</button>+ <button class="erc8004-chip ${this._searchFilter === 'x402' ? 'erc8004-chip--active' : ''}" data-filter="x402">x402 💳</button>+ </div>+ <div data-role="result" style="margin-top:14px"></div>+ `;+ const q = body.querySelector('[name="q"]');+ const out = body.querySelector('[data-role="result"]');++ body.querySelectorAll('[data-role="chips"] .erc8004-chip').forEach((chip) => {+ chip.addEventListener('click', () => {+ this._searchFilter = chip.dataset.filter;+ body.querySelectorAll('[data-role="chips"] .erc8004-chip').forEach((c) => {+ c.classList.toggle(+ 'erc8004-chip--active',+ c.dataset.filter === this._searchFilter,+ );+ });+ this._applySearchFilter(out);+ });+ });++ const go = async () => {+ const raw = q.value.trim();+ if (!raw) return;+ const type = detectInputType(raw);+ out.innerHTML = `<div class="erc8004-muted">Resolving…</div>`;++ try {+ let agentIds = [];+ if (type === INPUT_TYPES.AGENT_ID) {+ agentIds = [BigInt(raw)];+ } else if (type === INPUT_TYPES.AGENT_URI) {+ const match = raw.match(/^agent:\/\/([^/]+)\/(\d+)$/i);+ if (!match) throw new Error('Malformed agent:// URI');+ const aliases = {+ base: 8453,+ 'base-sepolia': 84532,+ ethereum: 1,+ mainnet: 1,+ optimism: 10,+ arbitrum: 42161,+ polygon: 137,+ bsc: 56,+ };+ const uriChain = aliases[match[1].toLowerCase()] || Number(match[1]);+ if (uriChain !== this.selectedChainId) {+ out.innerHTML = `<div class="erc8004-log-error">+ This agent is on <b>${esc(CHAIN_META[uriChain]?.name || `Chain ${uriChain}`)}</b>, not the selected chain.+ <a class="erc8004-link" href="/discover?q=${encodeURIComponent(raw)}" target="_blank" rel="noopener">Open in /discover ↗</a>+ </div>`;+ return;+ }+ agentIds = [BigInt(match[2])];+ } else if (type === INPUT_TYPES.ADDRESS) {+ const results = await resolveByAddress({+ address: raw,+ chainIds: [this.selectedChainId],+ ethProvider: window.ethereum,+ });+ agentIds = results.map((r) => BigInt(r.agentId));+ } else if (type === INPUT_TYPES.ENS) {+ const addr = await resolveENSAddress(raw);+ const results = await resolveByAddress({+ address: addr,+ chainIds: [this.selectedChainId],+ ethProvider: window.ethereum,+ });+ agentIds = results.map((r) => BigInt(r.agentId));+ } else if (type === INPUT_TYPES.TX_HASH) {+ const results = await resolveByTxHash({+ txHash: raw,+ chainId: this.selectedChainId,+ ethProvider: window.ethereum,+ });+ agentIds = results.map((r) => BigInt(r.agentId));+ } else {+ out.innerHTML = `<div class="erc8004-log-error">Unrecognized input. Try an agent ID, 0x address, ENS name, tx hash, or agent:// URI.</div>`;+ return;+ }++ if (!agentIds.length) {+ out.innerHTML = `+ <div class="erc8004-muted">+ No agents resolved on ${chainName} for <code>${esc(raw)}</code>.+ <a class="erc8004-link" href="/discover?q=${encodeURIComponent(raw)}" target="_blank" rel="noopener">Try across all chains ↗</a>+ </div>+ `;+ return;+ }++ out.innerHTML = '';+ for (const id of agentIds) {+ const card = document.createElement('div');+ card.className = 'erc8004-agent-card';+ card.innerHTML = `<div class="erc8004-muted">Loading #${id}…</div>`;+ out.appendChild(card);+ this._fillAgentCard(card, id, { withQR: true, withEdit: true });+ }+ this._applySearchFilter(out);+ } catch (err) {+ out.innerHTML = `<div class="erc8004-log-error">${esc(err.message)}</div>`;+ }+ };+ body.querySelector('[data-role="go"]').addEventListener('click', go);+ q.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') go();+ });+ }++ _applySearchFilter(out) {+ const filter = this._searchFilter || 'all';+ out.querySelectorAll('.erc8004-agent-card').forEach((card) => {+ if (filter === 'all') {+ card.style.display = '';+ return;+ }+ const meta = card._meta;+ if (!meta) {+ card.style.display = '';+ return;+ }+ const services = Array.isArray(meta.services) ? meta.services : [];+ const types = services.map((s) => String(s.type || s.name || '').toUpperCase());+ const hasX402 = !!meta.x402Support || !!meta.x402;+ let match = false;+ if (filter === 'x402') match = hasX402;+ else match = types.includes(filter.toUpperCase());+ card.style.display = match ? '' : 'none';+ });+ }++ // -----------------------------------------------------------------------+ // Tab: Templates+ // -----------------------------------------------------------------------++ _renderTemplates(body) {+ body.innerHTML = `+ <h3 class="erc8004-h3">Agent Templates</h3>+ <p class="erc8004-p">Pre-built configurations — one click to prefill the Create Agent wizard.</p>+ <div class="erc8004-template-grid">+ ${TEMPLATES.map(+ (t) => `+ <button class="erc8004-template" data-id="${t.id}">+ <div class="erc8004-template-emoji">${t.emoji}</div>+ <div class="erc8004-template-name">${esc(t.name)}</div>+ <div class="erc8004-template-desc">${esc(t.description)}</div>+ </button>+ `,+ ).join('')}+ </div>+ `;+ body.querySelectorAll('.erc8004-template').forEach((btn) => {+ btn.addEventListener('click', () => {+ const t = TEMPLATES.find((x) => x.id === btn.dataset.id);+ if (!t) return;+ this.form.name = t.name;+ this.form.description = t.description;+ if (Array.isArray(t.services)) {+ this.form.services = t.services.map((s) => ({ ...s }));+ }+ this.form.x402Support = !!t.x402Support;+ this.wizardStep = 1;+ this._setTab('create');+ });+ });+ }++ // -----------------------------------------------------------------------+ // Tab: History+ // -----------------------------------------------------------------------++ _renderHistory(body) {+ body.innerHTML = `+ <h3 class="erc8004-h3">Transaction History</h3>+ <p class="erc8004-p">Recent <code>Registered</code> events on <b>${esc(CHAIN_META[this.selectedChainId]?.name)}</b>${this.wallet ? ` for <code>${esc(this.wallet.address)}</code>` : ''}.</p>+ <div data-role="list"></div>+ `;+ const list = body.querySelector('[data-role="list"]');+ list.innerHTML = `<div class="erc8004-muted">Loading…</div>`;++ listRegisteredEvents({+ chainId: this.selectedChainId,+ owner: this.wallet?.address,+ ethProvider: window.ethereum,+ limit: 50,+ })+ .then((events) => {+ if (events.length === 0) {+ list.innerHTML = `<div class="erc8004-muted">No events in the scanned window.</div>`;+ return;+ }+ list.innerHTML = events+ .map(+ (ev) => `+ <div class="erc8004-history-row">+ <div class="erc8004-history-main">+ <div><strong>Agent #${ev.agentId}</strong> <span class="erc8004-muted">by ${esc(shortAddr(ev.owner))}</span></div>+ <div class="erc8004-muted erc8004-small">Block ${ev.blockNumber} · <code>${esc(ev.agentURI).slice(0, 60)}${ev.agentURI.length > 60 ? '…' : ''}</code></div>+ </div>+ <a class="erc8004-link" href="${esc(txExplorerUrl(this.selectedChainId, ev.txHash))}" target="_blank" rel="noopener">tx ↗</a>+ </div>+ `,+ )+ .join('');+ })+ .catch((err) => {+ list.innerHTML = `<div class="erc8004-log-error">Failed to load: ${esc(err.message)}</div>`;+ });+ }++ // -----------------------------------------------------------------------+ // Toast+ // -----------------------------------------------------------------------++ _toast(msg, isError = false) {+ const t = document.createElement('div');+ t.className = 'erc8004-toast' + (isError ? ' erc8004-toast--error' : '');+ t.textContent = msg;+ this.el.appendChild(t);+ setTimeout(() => t.remove(), 4000);+ }+}++// ───────────────────────────────────────────────────────────────────────────+// Helpers+// ───────────────────────────────────────────────────────────────────────────++function resolveGateway(uri) {+ if (!uri) return '';+ if (uri.startsWith('ipfs://')) return 'https://ipfs.io/ipfs/' + uri.slice(7);+ if (uri.startsWith('ar://')) return 'https://arweave.net/' + uri.slice(5);+ return uri;+}diff --git a/publish/src/erc8004/reputation-panel.js b/publish/src/erc8004/reputation-panel.jsnew file mode 100644index 000000000..0f0574b5e--- /dev/null+++ b/publish/src/erc8004/reputation-panel.js@@ -0,0 +1,313 @@+/**+ * Reputation panel — surfaces ERC-8004 ReputationRegistry state on an+ * agent's public profile.+ *+ * Reads:+ * • getReputation(agentId) → { total, count, average }+ * • Recent ReputationSubmitted events (best-effort; some RPCs cap log+ * queries so we ask for the last ~50k blocks and degrade gracefully)+ *+ * Writes (only when signed-in visitor has a wallet):+ * • submitReputation(agentId, score, comment) — the "vouch" CTA+ *+ * Mounted from agent-home.html when the agent has chain_id and+ * erc8004_agent_id, so visitors see real on-chain reputation rather+ * than a generic identity card.+ */++import { JsonRpcProvider, BrowserProvider } from 'ethers';+import { CHAIN_META, switchChain, txExplorerUrl } from './chain-meta.js';+import { REGISTRY_DEPLOYMENTS } from './abi.js';+import { submitReputation, getReputation, getRecentReviews } from './reputation.js';++// Look back ~50k blocks (~7 days on most L2s, ~7 days on Ethereum mainnet).+// Some RPCs reject huge ranges; this is a conservative default that still+// captures recent activity without a 429.+const REVIEWS_LOOKBACK_BLOCKS = 50_000;++export class ReputationPanel {+ /**+ * @param {object} opts+ * @param {HTMLElement} opts.container+ * @param {{ id: string, chainId: number, erc8004AgentId: number|string,+ * registryAddress?: string, ownerUserId?: string|null }} opts.agent+ * @param {{ id: string }|null} [opts.viewer] Current signed-in user, or null.+ */+ constructor({ container, agent, viewer = null }) {+ this._container = container;+ this._agent = agent;+ this._viewer = viewer;+ this._root = null;+ this._stats = null;+ this._reviews = [];+ }++ async mount() {+ this._root = document.createElement('section');+ this._root.className = 'agent-reputation';+ this._root.setAttribute('aria-labelledby', 'agent-reputation-heading');+ this._root.innerHTML = `+ <h2 class="agent-reputation__heading" id="agent-reputation-heading">Reputation</h2>+ <div class="agent-reputation__loading" role="status">Loading reputation…</div>+ `;+ this._container.appendChild(this._root);+ await this._refresh();+ }++ async _refresh() {+ const meta = CHAIN_META[this._agent.chainId];+ if (!meta?.rpcUrl) {+ this._renderEmpty(`No public RPC configured for chain ${this._agent.chainId}.`);+ return;+ }++ const deployment = REGISTRY_DEPLOYMENTS[this._agent.chainId];+ if (!deployment?.reputationRegistry) {+ this._renderEmpty(`No Reputation Registry deployed on ${meta.name}.`);+ return;+ }++ const provider = new JsonRpcProvider(meta.rpcUrl, this._agent.chainId, {+ staticNetwork: true,+ });++ try {+ this._stats = await getReputation({+ agentId: this._agent.erc8004AgentId,+ runner: provider,+ chainId: this._agent.chainId,+ });+ } catch (err) {+ console.warn('[reputation-panel] getReputation failed:', err?.message);+ this._renderEmpty('Could not read reputation from the chain.');+ return;+ }++ // Recent reviews are best-effort. Some RPCs (free tiers) reject open-+ // ended log queries — fall back to "no reviews shown" without breaking+ // the rest of the panel.+ try {+ const head = await provider.getBlockNumber();+ const fromBlock = Math.max(0, head - REVIEWS_LOOKBACK_BLOCKS);+ this._reviews = await getRecentReviews({+ agentId: this._agent.erc8004AgentId,+ runner: provider,+ chainId: this._agent.chainId,+ fromBlock,+ });+ } catch {+ this._reviews = [];+ }++ this._render();+ }++ _render() {+ const stats = this._stats || { count: 0, average: 0, total: 0 };+ const meta = CHAIN_META[this._agent.chainId];+ const chainName = meta?.name || `Chain ${this._agent.chainId}`;++ const summary =+ stats.count > 0+ ? `<span class="agent-reputation__avg">${_fmtAvg(stats.average)}</span>+ <span class="agent-reputation__sep">·</span>+ <span class="agent-reputation__count">${stats.count} ${+ stats.count === 1 ? 'vouch' : 'vouches'+ }</span>`+ : `<span class="agent-reputation__empty">No reputation submitted yet.</span>`;++ const canVouch = this._canVouch();+ const vouchHtml = canVouch+ ? `<button class="agent-reputation__vouch" type="button">+ Vouch for this agent+ </button>`+ : this._viewer+ ? `<span class="agent-reputation__hint">Owners can't vouch for their own agent.</span>`+ : `<span class="agent-reputation__hint">+ <a href="/login?next=${encodeURIComponent(`/agent/${this._agent.id}`)}">Sign in</a>+ to vouch for this agent.+ </span>`;++ const reviewsHtml = this._reviews.length+ ? `<ul class="agent-reputation__list">${this._reviews+ .slice(-8)+ .reverse()+ .map(+ (r) => `+ <li class="agent-reputation__row">+ <span class="agent-reputation__row-score">${_score(r.score)}</span>+ <span class="agent-reputation__row-from" title="${_esc(r.from)}">${_shortAddr(r.from)}</span>+ ${r.comment ? `<span class="agent-reputation__row-comment">${_esc(r.comment)}</span>` : ''}+ <a class="agent-reputation__row-tx"+ href="${_esc(txExplorerUrl(this._agent.chainId, r.txHash))}"+ target="_blank" rel="noopener noreferrer"+ aria-label="Open transaction in block explorer">↗</a>+ </li>`,+ )+ .join('')}</ul>`+ : stats.count > 0+ ? `<p class="agent-reputation__no-recent">+ Vouches exist on-chain but couldn't be enumerated by this RPC. Open+ ${chainName}'s explorer to see them.+ </p>`+ : '';++ this._root.innerHTML = `+ <h2 class="agent-reputation__heading" id="agent-reputation-heading">Reputation</h2>+ <div class="agent-reputation__summary">${summary}</div>+ <div class="agent-reputation__action">${vouchHtml}</div>+ ${reviewsHtml}+ `;++ const vouchBtn = this._root.querySelector('.agent-reputation__vouch');+ if (vouchBtn) vouchBtn.addEventListener('click', () => this._openVouchDialog());+ }++ _renderEmpty(reason) {+ this._root.innerHTML = `+ <h2 class="agent-reputation__heading" id="agent-reputation-heading">Reputation</h2>+ <p class="agent-reputation__hint">${_esc(reason)}</p>+ `;+ }++ _canVouch() {+ if (!this._viewer) return false;+ // Owners can't review their own agent — that would be self-promotion+ // noise and the contract may reject it anyway.+ if (this._agent.ownerUserId && this._viewer.id === this._agent.ownerUserId) {+ return false;+ }+ if (typeof window === 'undefined' || !window.ethereum) return false;+ return true;+ }++ async _openVouchDialog() {+ // Inline modal — keeps dependency surface small. Prompts for a 1-5+ // star score and an optional comment.+ const dialog = document.createElement('div');+ dialog.className = 'agent-vouch-modal';+ dialog.setAttribute('role', 'dialog');+ dialog.setAttribute('aria-modal', 'true');+ dialog.setAttribute('aria-labelledby', 'agent-vouch-title');+ dialog.innerHTML = `+ <div class="agent-vouch-modal__inner">+ <button class="agent-vouch-modal__close" type="button" aria-label="Cancel">×</button>+ <h3 id="agent-vouch-title" class="agent-vouch-modal__title">Vouch on-chain</h3>+ <p class="agent-vouch-modal__desc">+ Submits a signed reputation entry to ERC-8004 on+ ${_esc(CHAIN_META[this._agent.chainId]?.name || 'chain')}. Costs gas.+ </p>+ <fieldset class="agent-vouch-modal__rating">+ <legend>Score</legend>+ ${[1, 2, 3, 4, 5]+ .map(+ (n) => `+ <label>+ <input type="radio" name="score" value="${n}" ${n === 5 ? 'checked' : ''} />+ ${'★'.repeat(n)}+ </label>`,+ )+ .join('')}+ </fieldset>+ <label class="agent-vouch-modal__comment">+ <span>Comment (optional, public, on-chain)</span>+ <input type="text" maxlength="280" placeholder="e.g. Great agent for X" />+ </label>+ <div class="agent-vouch-modal__actions">+ <button type="button" class="agent-vouch-modal__cancel">Cancel</button>+ <button type="button" class="agent-vouch-modal__submit">Sign & submit</button>+ </div>+ <p class="agent-vouch-modal__status" role="status" aria-live="polite"></p>+ </div>+ `;+ document.body.appendChild(dialog);++ const close = () => dialog.remove();+ dialog.querySelector('.agent-vouch-modal__close').addEventListener('click', close);+ dialog.querySelector('.agent-vouch-modal__cancel').addEventListener('click', close);+ dialog.addEventListener('click', (e) => {+ if (e.target === dialog) close();+ });++ const submitBtn = dialog.querySelector('.agent-vouch-modal__submit');+ const statusEl = dialog.querySelector('.agent-vouch-modal__status');++ submitBtn.addEventListener('click', async () => {+ const score = Number(dialog.querySelector('input[name="score"]:checked')?.value || 0);+ const comment = dialog.querySelector('.agent-vouch-modal__comment input').value.trim();++ submitBtn.disabled = true;+ statusEl.textContent = 'Connecting wallet…';++ try {+ const provider = new BrowserProvider(window.ethereum);+ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });+ if (!accounts || !accounts.length) throw new Error('Wallet returned no account');++ const network = await provider.getNetwork();+ if (Number(network.chainId) !== this._agent.chainId) {+ statusEl.textContent = `Switching network to ${+ CHAIN_META[this._agent.chainId]?.name || 'target chain'+ }…`;+ await switchChain(this._agent.chainId);+ }++ const signer = await provider.getSigner();+ statusEl.textContent = 'Sign transaction in your wallet…';+ const txHash = await submitReputation({+ agentId: this._agent.erc8004AgentId,+ score,+ comment,+ signer,+ chainId: this._agent.chainId,+ });++ statusEl.innerHTML = `Submitted ✓ <a href="${_esc(+ txExplorerUrl(this._agent.chainId, txHash),+ )}" target="_blank" rel="noopener noreferrer">view tx</a>`;++ // Refresh stats in the background — the chain reflects new state on the next block.+ setTimeout(() => this._refresh().catch(() => {}), 4000);+ setTimeout(close, 2400);+ } catch (err) {+ if (_isUserRejection(err)) {+ statusEl.textContent = 'Cancelled.';+ } else {+ statusEl.textContent = `Failed: ${err?.shortMessage || err?.message || 'unknown error'}`;+ }+ submitBtn.disabled = false;+ }+ });+ }+}++function _isUserRejection(err) {+ if (!err) return false;+ if (err.code === 4001 || err.code === 'ACTION_REJECTED') return true;+ return /user rejected|user denied|rejected by user/i.test(err.message || '');+}++function _fmtAvg(avg) {+ if (!avg) return '0.0';+ if (avg <= 5) return avg.toFixed(1) + ' / 5';+ if (avg <= 100) return Math.round(avg) + ' / 100';+ return String(Math.round(avg));+}++function _score(n) {+ const x = Math.max(0, Math.min(5, Math.round(Number(n))));+ return '★'.repeat(x) + '☆'.repeat(5 - x);+}++function _shortAddr(addr) {+ if (!addr || typeof addr !== 'string' || addr.length < 10) return addr || '';+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}++function _esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}diff --git a/publish/src/erc8004/reputation.js b/publish/src/erc8004/reputation.jsnew file mode 100644index 000000000..635752cbb--- /dev/null+++ b/publish/src/erc8004/reputation.js@@ -0,0 +1,77 @@+/**+ * ReputationRegistry helpers — submit and query agent feedback.+ *+ * Matches the canonical ERC-8004 reputation contract:+ * submitReputation(uint256 agentId, uint8 score, string comment)+ * getReputation(uint256 agentId) → (uint256 totalScore, uint256 count)+ */++import { Contract } from 'ethers';+import { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } from './abi.js';++function getContract(chainId, runner) {+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment || !deployment.reputationRegistry) {+ throw new Error(`No Reputation Registry deployed on chain ${chainId}.`);+ }+ return new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, runner);+}++/**+ * Submit a reputation score about an agent.+ * @param {object} opts+ * @param {number|bigint} opts.agentId+ * @param {number} opts.score Integer 0-255 (typically 1-5 or 1-100)+ * @param {string} [opts.comment=''] Free-form comment+ * @param {import('ethers').Signer} opts.signer+ * @param {number} [opts.chainId]+ * @returns {Promise<string>} tx hash+ */+export async function submitReputation({ agentId, score, comment = '', signer, chainId }) {+ if (!Number.isInteger(score) || score < 0 || score > 255) {+ throw new Error('score must be a uint8 (0-255)');+ }+ const resolvedChainId = chainId ?? Number((await signer.provider.getNetwork()).chainId);+ const contract = getContract(resolvedChainId, signer);+ const tx = await contract.submitReputation(agentId, score, comment);+ await tx.wait();+ return tx.hash;+}++// Back-compat alias — the canonical contract calls it submitReputation.+export const submitFeedback = submitReputation;++/**+ * Read aggregated reputation.+ * @returns {Promise<{total: number, count: number, average: number}>}+ * average is 0 when no reviews have been submitted.+ */+export async function getReputation({ agentId, runner, chainId }) {+ const contract = getContract(chainId, runner);+ const [totalScore, count] = await contract.getReputation(agentId);+ const n = Number(count);+ const t = Number(totalScore);+ return {+ total: t,+ count: n,+ average: n === 0 ? 0 : t / n,+ };+}++/**+ * Enumerate past reviews by querying the ReputationSubmitted event log.+ * Optional — only useful if an indexer/provider supports filtered log queries.+ */+export async function getRecentReviews({ agentId, runner, chainId, fromBlock = 0 }) {+ const contract = getContract(chainId, runner);+ const filter = contract.filters.ReputationSubmitted(agentId);+ const events = await contract.queryFilter(filter, fromBlock);+ return events.map((ev) => ({+ agentId: Number(ev.args.agentId),+ from: ev.args.submitter,+ score: Number(ev.args.score),+ comment: ev.args.comment,+ blockNumber: ev.blockNumber,+ txHash: ev.transactionHash,+ }));+}diff --git a/publish/src/erc8004/resolve-avatar.js b/publish/src/erc8004/resolve-avatar.jsnew file mode 100644index 000000000..a65f5117a--- /dev/null+++ b/publish/src/erc8004/resolve-avatar.js@@ -0,0 +1,467 @@+/**+ * Avatar resolver — the "paste anything, see their 3D avatar" primitive.+ *+ * Given free-form input (address, ENS name, tx hash, agent ID, agent:// URI)+ * this module fans out across configured chains, discovers matching ERC-8004+ * agent registrations, hydrates their metadata, and returns a flat list of+ * results ready to render as a gallery.+ *+ * Used by:+ * - src/erc8004/register-ui.js ("Find Avatar" tab for creators)+ *+ * Chain reads happen through public RPCs (CHAIN_META) so no wallet required.+ */++import { JsonRpcProvider, Contract, Interface, isAddress, getAddress } from 'ethers';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './abi.js';+import { CHAIN_META, supportedChainIds } from './chain-meta.js';+import {+ getReadProvider,+ getReadRegistry,+ getAgentOnchain,+ fetchAgentMetadata,+ findAvatar3D,+ listAgentsByOwner,+} from './queries.js';++// ───────────────────────────────────────────────────────────────────────────+// Input detection+// ───────────────────────────────────────────────────────────────────────────++export const INPUT_TYPES = {+ AGENT_ID: 'agentId',+ ADDRESS: 'address',+ TX_HASH: 'txHash',+ ENS: 'ens',+ AGENT_URI: 'agentURI',+ UNKNOWN: 'unknown',+};++/** @param {string} input */+export function detectInputType(input) {+ const v = String(input ?? '').trim();+ if (!v) return INPUT_TYPES.UNKNOWN;+ if (/^agent:\/\/[^/]+\/\d+$/i.test(v)) return INPUT_TYPES.AGENT_URI;+ if (/^0x[a-fA-F0-9]{64}$/.test(v)) return INPUT_TYPES.TX_HASH;+ if (/^0x[a-fA-F0-9]{40}$/.test(v)) return INPUT_TYPES.ADDRESS;+ if (/^\d{1,10}$/.test(v)) return INPUT_TYPES.AGENT_ID;+ // ENS-style: any string with at least one dot and an alpha TLD-ish tail+ if (/^[a-z0-9][a-z0-9-]*(\.[a-z0-9-]+)+$/i.test(v)) return INPUT_TYPES.ENS;+ return INPUT_TYPES.UNKNOWN;+}++/** Default fan-out set — active ERC-8004 chains. Small enough that 9 parallel reads is cheap. */+export const DEFAULT_FAN_OUT_CHAINS = [+ 8453, // Base+ 1, // Ethereum+ 10, // Optimism+ 42161, // Arbitrum One+ 137, // Polygon+ 56, // BNB Chain+ 84532, // Base Sepolia+ 11155111, // Ethereum Sepolia+ 97, // BSC Testnet+];++// ───────────────────────────────────────────────────────────────────────────+// Shared result shape+// ───────────────────────────────────────────────────────────────────────────++/**+ * A single resolved on-chain agent.+ *+ * @typedef {object} AvatarResult+ * @property {number} chainId+ * @property {string} chainName+ * @property {boolean} testnet+ * @property {string} agentId Stringified (bigint-safe)+ * @property {string} owner Checksummed+ * @property {string} [uri] Raw tokenURI (ipfs://, ar://, data:, https://)+ * @property {any} [meta] Parsed registration JSON (when available)+ * @property {string|null} avatarUri Raw GLB/GLTF URI (ipfs://, ar://, https://) or null+ * @property {string} [image] Poster image URL+ * @property {string} [name]+ * @property {string} [description]+ * @property {boolean} [x402]+ * @property {string[]} [serviceTypes] Uppercased service.type/name list for filtering+ * @property {string} viewerUrl Canonical `/a/<chainId>/<agentId>` link+ * @property {string} tokenExplorerUrl+ * @property {string} ownerExplorerUrl+ * @property {string} registry+ * @property {string} [error] Per-agent non-fatal error message+ */++// ───────────────────────────────────────────────────────────────────────────+// Single-agent resolution helpers+// ───────────────────────────────────────────────────────────────────────────++function _extractX402(meta) {+ if (!meta || typeof meta !== 'object') return false;+ if (meta.x402Support || meta.x402) return true;+ const services = Array.isArray(meta.services) ? meta.services : [];+ return services.some((s) => {+ const t = String(s?.type || s?.name || '').toUpperCase();+ return t === 'X402' || t.includes('X402');+ });+}++function _extractServiceTypes(meta) {+ if (!meta || typeof meta !== 'object') return [];+ const services = Array.isArray(meta.services) ? meta.services : [];+ return services.map((s) => String(s?.type || s?.name || '').toUpperCase()).filter(Boolean);+}++function _chainName(chainId) {+ return CHAIN_META[chainId]?.name || `Chain ${chainId}`;+}++/**+ * Hydrate a single (chainId, agentId) pair into a full AvatarResult.+ * Uses the read-only public RPC — no wallet required.+ *+ * @param {object} opts+ * @param {number} opts.chainId+ * @param {bigint|string|number} opts.agentId+ * @param {any} [opts.ethProvider]+ * @returns {Promise<AvatarResult>}+ */+export async function hydrateAgent({ chainId, agentId, ethProvider }) {+ const meta = CHAIN_META[chainId];+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ const registry = deployment?.identityRegistry || '';++ const base = {+ chainId,+ chainName: meta?.name || `Chain ${chainId}`,+ testnet: !!meta?.testnet,+ agentId: String(agentId),+ owner: '',+ uri: '',+ meta: null,+ avatarUri: null,+ image: '',+ name: '',+ description: '',+ x402: false,+ serviceTypes: [],+ viewerUrl: `/a/${chainId}/${String(agentId)}`,+ tokenExplorerUrl:+ registry && meta ? `${meta.explorer}/token/${registry}?a=${String(agentId)}` : '',+ ownerExplorerUrl: '',+ registry,+ };++ try {+ const { owner, uri } = await getAgentOnchain({ chainId, agentId, ethProvider });+ base.owner = owner ? getAddress(owner) : '';+ base.uri = uri || '';+ base.ownerExplorerUrl = base.owner && meta ? `${meta.explorer}/address/${base.owner}` : '';++ if (!uri) {+ base.error = 'no agentURI';+ return base;+ }++ const fetched = await fetchAgentMetadata(uri);+ if (!fetched.ok) {+ base.error = fetched.error || 'metadata fetch failed';+ return base;+ }+ const data = fetched.data || {};+ base.meta = data;+ base.name = String(data.name || '').trim();+ base.description = String(data.description || '').trim();+ base.image = String(data.image || '').trim();+ base.avatarUri = findAvatar3D(data);+ base.x402 = _extractX402(data);+ base.serviceTypes = _extractServiceTypes(data);+ } catch (err) {+ base.error = err?.message || String(err);+ }+ return base;+}++// ───────────────────────────────────────────────────────────────────────────+// Resolvers — each takes shape-preserving opts and returns AvatarResult[]+// ───────────────────────────────────────────────────────────────────────────++/**+ * @param {{ chainId: number, agentId: string|number|bigint, ethProvider?: any }} opts+ * @returns {Promise<AvatarResult[]>}+ */+export async function resolveByAgentId(opts) {+ const result = await hydrateAgent(opts);+ return [result];+}++/**+ * Fan-out: given (chainIds, agentId) try the same id on every chain and return+ * every hit. Useful when the user pastes "6443" and we don't know the chain.+ *+ * @param {object} opts+ * @param {string|number|bigint} opts.agentId+ * @param {number[]} [opts.chainIds]+ * @param {any} [opts.ethProvider]+ * @param {(chainId: number, stage: 'start'|'done'|'error', payload?: any) => void} [opts.onProgress]+ * @returns {Promise<AvatarResult[]>}+ */+export async function resolveByAgentIdFanOut({+ agentId,+ chainIds = DEFAULT_FAN_OUT_CHAINS,+ ethProvider,+ onProgress = () => {},+}) {+ const jobs = chainIds.map(async (chainId) => {+ onProgress(chainId, 'start');+ try {+ const r = await hydrateAgent({ chainId, agentId, ethProvider });+ // Filter out "doesn't exist" (no owner AND no uri). Those are empty slots, not agents.+ if (!r.owner && !r.uri) {+ onProgress(chainId, 'done', 0);+ return null;+ }+ onProgress(chainId, 'done', 1);+ return r;+ } catch (err) {+ onProgress(chainId, 'error', err);+ return null;+ }+ });+ const out = (await Promise.all(jobs)).filter(Boolean);+ return out;+}++/**+ * Resolve every agent owned by `address` across `chainIds`.+ *+ * @param {object} opts+ * @param {string} opts.address+ * @param {number[]} [opts.chainIds]+ * @param {any} [opts.ethProvider]+ * @param {(chainId: number, stage: 'start'|'done'|'error', payload?: any) => void} [opts.onProgress]+ * @returns {Promise<AvatarResult[]>}+ */+export async function resolveByAddress({+ address,+ chainIds = DEFAULT_FAN_OUT_CHAINS,+ ethProvider,+ onProgress = () => {},+}) {+ if (!isAddress(address)) throw new Error('Not a valid EVM address');+ const checksummed = getAddress(address);++ const chainJobs = chainIds.map(async (chainId) => {+ onProgress(chainId, 'start');+ try {+ const { ids } = await listAgentsByOwner({+ chainId,+ owner: checksummed,+ ethProvider,+ });+ if (!ids || ids.length === 0) {+ onProgress(chainId, 'done', 0);+ return [];+ }+ // Hydrate each in parallel, but cap concurrency on chains with big balances.+ const hydrated = await Promise.all(+ ids.map((id) => hydrateAgent({ chainId, agentId: id, ethProvider })),+ );+ onProgress(chainId, 'done', hydrated.length);+ return hydrated;+ } catch (err) {+ onProgress(chainId, 'error', err);+ return [];+ }+ });++ const nested = await Promise.all(chainJobs);+ return nested.flat();+}++/**+ * Resolve every `Registered` event in a given tx hash — yields one result per+ * agent minted in that transaction.+ *+ * @param {object} opts+ * @param {string} opts.txHash+ * @param {number} [opts.chainId] If omitted, we fan-out across chainIds.+ * @param {number[]} [opts.chainIds]+ * @param {any} [opts.ethProvider]+ * @param {(chainId: number, stage: 'start'|'done'|'error', payload?: any) => void} [opts.onProgress]+ * @returns {Promise<AvatarResult[]>}+ */+export async function resolveByTxHash({+ txHash,+ chainId,+ chainIds = DEFAULT_FAN_OUT_CHAINS,+ ethProvider,+ onProgress = () => {},+}) {+ if (!/^0x[a-fA-F0-9]{64}$/.test(txHash)) throw new Error('Not a valid tx hash');+ const candidates = chainId ? [chainId] : chainIds;++ const iface = new Interface(IDENTITY_REGISTRY_ABI);+ const registeredTopic = iface.getEvent('Registered').topicHash;++ const chainJobs = candidates.map(async (cid) => {+ onProgress(cid, 'start');+ try {+ const deployment = REGISTRY_DEPLOYMENTS[cid];+ if (!deployment?.identityRegistry) {+ onProgress(cid, 'done', 0);+ return [];+ }+ const provider = getReadProvider(cid, ethProvider);+ const receipt = await provider.getTransactionReceipt(txHash);+ if (!receipt) {+ onProgress(cid, 'done', 0);+ return [];+ }+ const registryAddr = deployment.identityRegistry.toLowerCase();+ const hits = [];+ for (const log of receipt.logs) {+ if (!log.address || log.address.toLowerCase() !== registryAddr) continue;+ if (!log.topics || log.topics[0] !== registeredTopic) continue;+ try {+ const parsed = iface.parseLog(log);+ const agentId = parsed.args.agentId;+ hits.push(await hydrateAgent({ chainId: cid, agentId, ethProvider }));+ } catch {+ // malformed log — skip+ }+ }+ onProgress(cid, 'done', hits.length);+ return hits;+ } catch (err) {+ onProgress(cid, 'error', err);+ return [];+ }+ });++ const nested = await Promise.all(chainJobs);+ return nested.flat();+}++/**+ * Resolve an agent://<chain>/<id> URI.+ *+ * @param {string} uri+ * @param {any} [ethProvider]+ * @returns {Promise<AvatarResult[]>}+ */+export async function resolveByAgentURI(uri, ethProvider) {+ const m = String(uri).match(/^agent:\/\/([^/]+)\/(\d+)$/i);+ if (!m) throw new Error('Malformed agent URI');+ const [, chainToken, idStr] = m;+ const CHAIN_ALIASES = {+ base: 8453,+ 'base-mainnet': 8453,+ 'base-sepolia': 84532,+ ethereum: 1,+ mainnet: 1,+ optimism: 10,+ arbitrum: 42161,+ polygon: 137,+ bsc: 56,+ };+ const chainId = CHAIN_ALIASES[chainToken.toLowerCase()] || Number(chainToken);+ if (!chainId || !REGISTRY_DEPLOYMENTS[chainId]) {+ throw new Error(`Unknown chain in URI: ${chainToken}`);+ }+ const r = await hydrateAgent({ chainId, agentId: idStr, ethProvider });+ return [r];+}++/**+ * Resolve an ENS name to an address using Ethereum mainnet public RPC, then+ * delegate to resolveByAddress. Names that don't resolve throw.+ *+ * @param {string} name+ */+export async function resolveENSAddress(name) {+ const provider = new JsonRpcProvider(CHAIN_META[1].rpcUrl, 1);+ const addr = await provider.resolveName(name);+ if (!addr) throw new Error(`ENS name does not resolve: ${name}`);+ return getAddress(addr);+}++// ───────────────────────────────────────────────────────────────────────────+// Auto-resolve — single entry point+// ───────────────────────────────────────────────────────────────────────────++/**+ * @param {object} opts+ * @param {string} opts.input+ * @param {number[]} [opts.chainIds] Fan-out set+ * @param {any} [opts.ethProvider]+ * @param {(chainId: number, stage: 'start'|'done'|'error', payload?: any) => void} [opts.onProgress]+ * @returns {Promise<{ type: string, resolvedAddress?: string, results: AvatarResult[] }>}+ */+export async function autoResolve({+ input,+ chainIds = DEFAULT_FAN_OUT_CHAINS,+ ethProvider,+ onProgress = () => {},+}) {+ const type = detectInputType(input);+ const trimmed = String(input).trim();++ switch (type) {+ case INPUT_TYPES.AGENT_URI: {+ const results = await resolveByAgentURI(trimmed, ethProvider);+ return { type, results };+ }+ case INPUT_TYPES.TX_HASH: {+ const results = await resolveByTxHash({+ txHash: trimmed,+ chainIds,+ ethProvider,+ onProgress,+ });+ return { type, results };+ }+ case INPUT_TYPES.ADDRESS: {+ const results = await resolveByAddress({+ address: trimmed,+ chainIds,+ ethProvider,+ onProgress,+ });+ return { type, resolvedAddress: getAddress(trimmed), results };+ }+ case INPUT_TYPES.AGENT_ID: {+ const results = await resolveByAgentIdFanOut({+ agentId: trimmed,+ chainIds,+ ethProvider,+ onProgress,+ });+ return { type, results };+ }+ case INPUT_TYPES.ENS: {+ const address = await resolveENSAddress(trimmed);+ const results = await resolveByAddress({ address, chainIds, ethProvider, onProgress });+ return { type, resolvedAddress: address, results };+ }+ default:+ throw new Error(+ `Unrecognized input: "${trimmed}". Paste an address, ENS name, tx hash, or agent ID.`,+ );+ }+}++// ───────────────────────────────────────────────────────────────────────────+// Convenience: all chains with a deployed registry (for UI toggle row)+// ───────────────────────────────────────────────────────────────────────────++export function allSupportedChains() {+ return supportedChainIds();+}++/** Split supported chains into mainnets vs testnets for UI grouping. */+export function splitChainsByNet() {+ const all = allSupportedChains();+ const mainnet = all.filter((id) => !CHAIN_META[id]?.testnet);+ const testnet = all.filter((id) => CHAIN_META[id]?.testnet);+ return { mainnet, testnet };+}diff --git a/publish/src/erc8004/resolver.js b/publish/src/erc8004/resolver.jsnew file mode 100644index 000000000..9216ad6aa--- /dev/null+++ b/publish/src/erc8004/resolver.js@@ -0,0 +1,323 @@+/**+ * Universal on-chain agent resolver.+ *+ * One import point for every surface that needs to turn "an on-chain agent"+ * into something renderable: the web component, oEmbed, OG image, explore+ * page, Claude.ai artifact, LobeHub plugin, SDK.+ *+ * Inputs it understands:+ *+ * parseAgentRef('eip155:8453:0xabc...:42') — full CAIP-10 + tokenId+ * parseAgentRef('onchain:8453:42') — shorthand (canonical registry)+ * parseAgentRef('agent://8453/42') — agent URI+ * parseAgentRef({ chainId: 8453, agentId: 42 }) — already parsed+ * parseAgentRef('/a/8453/42') — URL path+ *+ * Output of resolveOnchainAgent: a normalized record with on-chain facts+ * (owner, URI) + off-chain metadata + a resolved GLB URL.+ */++import { getAgentOnchain, fetchAgentMetadata, findAvatar3D } from './queries.js';+import { REGISTRY_DEPLOYMENTS, agentRegistryId } from './abi.js';+import { CHAIN_META } from './chain-meta.js';++// ---------------------------------------------------------------------------+// Parsing+// ---------------------------------------------------------------------------++/**+ * Parse any supported agent reference into `{ chainId, agentId, registry? }`.+ * Returns `null` if the input doesn't look like an on-chain reference.+ *+ * @param {string|object} input+ * @returns {{ chainId: number, agentId: string, registry?: string }|null}+ */+export function parseAgentRef(input) {+ if (!input) return null;++ if (typeof input === 'object') {+ if (input.chainId && input.agentId !== undefined) {+ return {+ chainId: Number(input.chainId),+ agentId: String(input.agentId),+ registry: input.registry || undefined,+ };+ }+ return null;+ }++ const s = String(input).trim();+ if (!s) return null;++ // Full CAIP-10 + token: "eip155:<chainId>:<registry>:<agentId>"+ let m = s.match(/^eip155:(\d+):(0x[0-9a-fA-F]{40}):(\d+)$/);+ if (m) return { chainId: Number(m[1]), registry: m[2], agentId: m[3] };++ // CAIP-10 assetType form: "eip155:<chainId>/erc721:<registry>/<agentId>"+ m = s.match(/^eip155:(\d+)\/erc721:(0x[0-9a-fA-F]{40})\/(\d+)$/);+ if (m) return { chainId: Number(m[1]), registry: m[2], agentId: m[3] };++ // Shorthand: "onchain:<chainId>:<agentId>"+ m = s.match(/^onchain:(\d+):(\d+)$/);+ if (m) return { chainId: Number(m[1]), agentId: m[2] };++ // agent:// scheme+ m = s.match(/^agent:\/\/(\d+)\/(\d+)$/);+ if (m) return { chainId: Number(m[1]), agentId: m[2] };++ // URL path: "/a/<chainId>/<agentId>" or with explicit registry+ m = s.match(/^\/?a\/(\d+)\/(\d+)(?:\/(embed))?\/?$/);+ if (m) return { chainId: Number(m[1]), agentId: m[2] };+ m = s.match(/^\/?a\/(\d+)\/(0x[0-9a-fA-F]{40})\/(\d+)\/?$/);+ if (m) return { chainId: Number(m[1]), registry: m[2], agentId: m[3] };++ return null;+}++/**+ * Return the canonical CAIP-10 identifier string for an agent.+ * @param {{ chainId: number, agentId: string|number, registry?: string }} ref+ */+export function toCAIP10(ref) {+ const registry = ref.registry || REGISTRY_DEPLOYMENTS[ref.chainId]?.identityRegistry;+ if (!registry) return `onchain:${ref.chainId}:${ref.agentId}`;+ return `eip155:${ref.chainId}:${registry}:${ref.agentId}`;+}++/**+ * Return the public `/a/<chainId>/<agentId>` URL for an agent.+ * @param {{ chainId: number, agentId: string|number }} ref+ * @param {object} [opts]+ * @param {boolean} [opts.embed] Append `/embed` for chromeless iframe mode+ * @param {string} [opts.origin] Override origin (defaults to location.origin)+ */+export function toPublicUrl(ref, { embed = false, origin } = {}) {+ const o = origin || (typeof location !== 'undefined' ? location.origin : '');+ return `${o}/a/${ref.chainId}/${ref.agentId}${embed ? '/embed' : ''}`;+}++// ---------------------------------------------------------------------------+// URL fallback — tries direct, then rotates IPFS gateways, then Arweave+// ---------------------------------------------------------------------------++const IPFS_GATEWAYS = [+ 'https://ipfs.io/ipfs/',+ 'https://dweb.link/ipfs/',+ 'https://cloudflare-ipfs.com/ipfs/',+ 'https://gateway.pinata.cloud/ipfs/',+];+const AR_GATEWAY = 'https://arweave.net/';++/**+ * Convert any of `https://…`, `ipfs://<cid>[/path]`, `ar://<tx>` into a plain+ * HTTPS URL. For ipfs, returns the first gateway — use `resolveUrlCandidates`+ * when you need fallbacks.+ *+ * @param {string} uri+ * @returns {string}+ */+export function resolveUrl(uri) {+ if (!uri) return '';+ if (uri.startsWith('ipfs://')) return IPFS_GATEWAYS[0] + uri.slice(7);+ if (uri.startsWith('ar://')) return AR_GATEWAY + uri.slice(5);+ return uri;+}++/**+ * All HTTPS forms of an off-chain URI, in preference order. Use when you+ * want to try each in sequence — e.g. the `<img>` fallback chain or a+ * `fetch` retry loop.+ *+ * @param {string} uri+ * @returns {string[]}+ */+export function resolveUrlCandidates(uri) {+ if (!uri) return [];+ if (uri.startsWith('ipfs://')) {+ const rest = uri.slice(7);+ return IPFS_GATEWAYS.map((gw) => gw + rest);+ }+ if (uri.startsWith('ar://')) return [AR_GATEWAY + uri.slice(5)];+ return [uri];+}++// ---------------------------------------------------------------------------+// Resolution+// ---------------------------------------------------------------------------++// Lightweight in-memory cache keyed by canonical ref string. The resolver is+// a hot path on /discover and in consumer embeds; don't hit the chain twice+// for the same agent within a page session.+const _cache = new Map();+function cacheKey(ref) {+ return `${ref.chainId}:${ref.agentId}`;+}++/**+ * Full resolution of an on-chain ERC-8004 agent.+ *+ * @param {string|object} input Anything `parseAgentRef` accepts+ * @param {object} [opts]+ * @param {any} [opts.ethProvider] EIP-1193 provider for chain reads+ * @param {boolean} [opts.fresh] Bypass the session cache+ * @returns {Promise<{+ * ref: { chainId: number, agentId: string, registry: string },+ * caip: string,+ * publicUrl: string,+ * chain: { name: string, testnet: boolean, explorer: string }|null,+ * onchain: { owner: string|null, uri: string|null },+ * metadata: any|null,+ * metadataUrl: string|null,+ * image: string|null,+ * glbUrl: string|null,+ * name: string,+ * description: string,+ * services: any[],+ * error?: string,+ * }>}+ */+export async function resolveOnchainAgent(input, { ethProvider, fresh = false } = {}) {+ const parsed = parseAgentRef(input);+ if (!parsed) throw new Error(`Unrecognised agent reference: ${input}`);++ const ref = {+ chainId: parsed.chainId,+ agentId: String(parsed.agentId),+ registry: parsed.registry || REGISTRY_DEPLOYMENTS[parsed.chainId]?.identityRegistry || null,+ };+ if (!ref.registry) throw new Error(`No registry deployed on chain ${ref.chainId}`);++ const key = cacheKey(ref);+ if (!fresh && _cache.has(key)) return _cache.get(key);++ const chainMeta = CHAIN_META[ref.chainId] || null;+ const base = {+ ref,+ caip: toCAIP10(ref),+ publicUrl:+ typeof location !== 'undefined' ? toPublicUrl(ref) : `/a/${ref.chainId}/${ref.agentId}`,+ chain: chainMeta+ ? { name: chainMeta.name, testnet: !!chainMeta.testnet, explorer: chainMeta.explorer }+ : null,+ onchain: { owner: null, uri: null },+ metadata: null,+ metadataUrl: null,+ image: null,+ glbUrl: null,+ name: `Agent #${ref.agentId}`,+ description: '',+ services: [],+ };++ try {+ const { owner, uri } = await getAgentOnchain({+ chainId: ref.chainId,+ agentId: ref.agentId,+ ethProvider,+ });+ base.onchain = { owner, uri };++ if (!uri) {+ base.error = 'agentURI not set';+ _cache.set(key, base);+ return base;+ }++ const metaRes = await fetchAgentMetadata(uri);+ if (!metaRes.ok) {+ base.error = metaRes.error;+ base.metadataUrl = metaRes.resolvedUrl || null;+ _cache.set(key, base);+ return base;+ }+ const md = metaRes.data;+ base.metadata = md;+ base.metadataUrl = metaRes.resolvedUrl || null;+ base.name = (md?.name && String(md.name)) || base.name;+ base.description = (md?.description && String(md.description)) || '';+ base.image = md?.image ? String(md.image) : null;+ base.services = Array.isArray(md?.services) ? md.services : [];+ base.glbUrl = findAvatar3D(md);+ } catch (err) {+ base.error = err.message || String(err);+ }++ _cache.set(key, base);+ return base;+}++/**+ * Build a full agent-manifest/0.1 object from a resolved on-chain agent.+ * Mirrors the shape `resolveAgentById` returns so the rest of the boot path+ * (memory, skills, runtime) works unchanged.+ *+ * @param {Awaited<ReturnType<typeof resolveOnchainAgent>>} resolved+ * @returns {object}+ */+export function toManifest(resolved) {+ const services = Array.isArray(resolved.services) ? resolved.services : [];+ const brainSvc = services.find((s) => /brain|llm|chat/i.test(s?.name || s?.type || ''));+ const skillSvcs = services.filter((s) => /skill/i.test(s?.name || s?.type || ''));++ const glb = resolved.glbUrl ? resolveUrl(resolved.glbUrl) : '';+ const img = resolved.image ? resolveUrl(resolved.image) : '';++ return {+ spec: 'agent-manifest/0.1',+ _baseURI: resolved.metadataUrl ? trimToDir(resolved.metadataUrl) : '',+ _source: 'erc8004-resolver',+ id: {+ agentId: resolved.ref.agentId,+ chainId: resolved.ref.chainId,+ registry: resolved.ref.registry,+ owner: resolved.onchain.owner || undefined,+ walletAddress: resolved.onchain.owner || undefined,+ caip: resolved.caip,+ agentRegistry: agentRegistryId(resolved.ref.chainId, resolved.ref.registry),+ },+ name: resolved.name,+ description: resolved.description,+ image: img,+ body: { uri: glb || img, format: 'gltf-binary' },+ brain: brainSvc+ ? { provider: 'remote', endpoint: brainSvc.endpoint }+ : { provider: 'none' },+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },+ skills: skillSvcs.map((s) => ({ name: s.name, uri: s.endpoint })),+ memory: { mode: 'local', namespace: resolved.caip },+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression'],+ version: '0.1.0',+ services,+ x402Support: !!(resolved.metadata?.x402Support || resolved.metadata?.x402),+ embedPolicy: resolved.metadata?.embedPolicy || null,+ };+}++function trimToDir(url) {+ const i = url.lastIndexOf('/');+ return i >= 0 ? url.slice(0, i + 1) : url;+}++/**+ * Should a given parent origin be allowed to embed this agent?+ * Respects an `embedPolicy` field in the registration JSON:+ *+ * { mode: 'allowlist'|'denylist', hosts: ['example.com', '*.foo.com'] }+ *+ * No policy = public. Rules match hostname suffix; `*.` wildcards supported.+ *+ * @param {object|null} policy+ * @param {string} host+ * @returns {boolean}+ */+export function isEmbedAllowed(policy, host) {+ if (!policy || !policy.mode || !Array.isArray(policy.hosts)) return true;+ const match = policy.hosts.some((rule) => {+ if (!rule) return false;+ const r = String(rule).toLowerCase();+ const h = String(host || '').toLowerCase();+ if (r.startsWith('*.')) return h === r.slice(2) || h.endsWith('.' + r.slice(2));+ return h === r;+ });+ return policy.mode === 'allowlist' ? match : !match;+}diff --git a/publish/src/erc8004/showcase.js b/publish/src/erc8004/showcase.jsnew file mode 100644index 000000000..4323388e0--- /dev/null+++ b/publish/src/erc8004/showcase.js@@ -0,0 +1,544 @@+/**+ * /showcase — browsable directory of every ERC-8004 agent with a 3D avatar.+ *+ * Reads from GET /api/showcase (backed by erc8004_agents_index, populated by+ * api/cron/erc8004-crawl.js). Unlike /discover (search-by-input via /api/explore),+ * this page is pure browse: pick a net + chains, scroll a grid of newest-minted+ * agents, click a card to open its 3D viewer at /a/<chainId>/<agentId>.+ *+ * Lazy-loaded by src/app.js `_showShowcasePage`.+ */++import { CHAIN_META, supportedChainIds } from './chain-meta.js';+import { resolveURI } from '../ipfs.js';++const PAGE_SIZE = 24;+const NET_KEY = '3dagent.showcase.net';+const CHAINS_KEY = '3dagent.showcase.chains';+const SORT_KEY = '3dagent.showcase.sort';++const esc = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );++const shortAddr = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : '');++function loadNet() {+ try {+ const v = localStorage.getItem(NET_KEY);+ if (v === 'mainnet' || v === 'testnet' || v === 'all') return v;+ } catch {}+ return 'mainnet';+}+function saveNet(v) {+ try {+ localStorage.setItem(NET_KEY, v);+ } catch {}+}++function loadSort() {+ try {+ const v = localStorage.getItem(SORT_KEY);+ if (v === 'newest' || v === 'oldest') return v;+ } catch {}+ return 'newest';+}+function saveSort(v) {+ try {+ localStorage.setItem(SORT_KEY, v);+ } catch {}+}++function loadChains() {+ try {+ const raw = localStorage.getItem(CHAINS_KEY);+ if (!raw) return [];+ const parsed = JSON.parse(raw);+ if (!Array.isArray(parsed)) return [];+ return parsed.filter((n) => Number.isInteger(n));+ } catch {+ return [];+ }+}+function saveChains(ids) {+ try {+ localStorage.setItem(CHAINS_KEY, JSON.stringify(ids));+ } catch {}+}++function splitChains() {+ const ids = supportedChainIds();+ const mainnet = [];+ const testnet = [];+ for (const id of ids) {+ const m = CHAIN_META[id];+ if (!m) continue;+ (m.testnet ? testnet : mainnet).push(id);+ }+ return { mainnet, testnet };+}++/**+ * Entry point called by app.js `_showShowcasePage`.+ * @param {HTMLElement} container+ */+export function renderShowcasePage(container) {+ const page = new ShowcasePage(container);+ page.mount();+ return page;+}++class ShowcasePage {+ /** @param {HTMLElement} container */+ constructor(container) {+ this.container = container;+ this._net = loadNet();+ this._sort = loadSort();+ this._chains = loadChains(); // empty = all of `_net`+ this._items = [];+ this._nextCursor = null;+ this._total = 0;+ this._loading = false;+ this._reqSeq = 0;+ this._onHashChange = () => this._readURL({ replace: true });+ this._onScroll = () => this._maybeAutoLoad();+ }++ mount() {+ this.container.innerHTML = `+ <div class="showcase-shell">+ <header class="showcase-hero">+ <div class="showcase-hero-inner">+ <div class="showcase-eyebrow">ERC-8004 · Directory</div>+ <h1 class="showcase-title">Every three.ws on-chain.</h1>+ <p class="showcase-subtitle">+ Browse every ERC-8004 agent with a <code>gltf</code> body — discovered across+ ${supportedChainIds().length} chains and indexed from canonical registries. Click any+ card to open it in the 3D viewer.+ </p>+ <div class="showcase-stats" data-role="stats">+ <div class="showcase-stat">+ <span class="showcase-stat-value" data-role="statTotal">—</span>+ <span class="showcase-stat-label">three.wss</span>+ </div>+ <div class="showcase-stat">+ <span class="showcase-stat-value">${splitChains().mainnet.length}+${splitChains().testnet.length}</span>+ <span class="showcase-stat-label">chains</span>+ </div>+ <div class="showcase-stat">+ <span class="showcase-stat-value">v2.0</span>+ <span class="showcase-stat-label">registry</span>+ </div>+ </div>+ </div>+ </header>++ <section class="showcase-controls">+ <div class="showcase-controls-row">+ <div class="showcase-segmented" role="tablist" data-role="netGroup">+ <button type="button" role="tab" class="showcase-seg" data-net="mainnet">Mainnet</button>+ <button type="button" role="tab" class="showcase-seg" data-net="testnet">Testnet</button>+ <button type="button" role="tab" class="showcase-seg" data-net="all">All</button>+ </div>+ <div class="showcase-controls-spacer"></div>+ <div class="showcase-sort">+ <label class="showcase-sort-lbl" for="showcase-sort-sel">Sort</label>+ <select id="showcase-sort-sel" class="showcase-sort-sel" data-role="sortSel">+ <option value="newest">Newest</option>+ <option value="oldest">Oldest</option>+ </select>+ </div>+ </div>+ <div class="showcase-controls-row showcase-controls-row--chains">+ <strong class="showcase-controls-lbl">Chains</strong>+ <div class="showcase-chain-chips" data-role="chainChips"></div>+ <button type="button" class="showcase-chip-reset" data-role="chainReset" hidden>Clear</button>+ </div>+ </section>++ <section class="showcase-results" data-role="results" aria-live="polite"></section>++ <div class="showcase-loadmore" data-role="loadMore" hidden>+ <button type="button" class="showcase-btn" data-role="loadMoreBtn">Load more</button>+ </div>+ </div>+ `;++ this._bindControls();+ this._renderNetSegmented();+ this._renderSortSelect();+ this._renderChainChips();++ window.addEventListener('hashchange', this._onHashChange);+ window.addEventListener('popstate', this._onHashChange);+ window.addEventListener('scroll', this._onScroll, { passive: true });++ this._readURL({ replace: true });+ }++ destroy() {+ window.removeEventListener('hashchange', this._onHashChange);+ window.removeEventListener('popstate', this._onHashChange);+ window.removeEventListener('scroll', this._onScroll);+ }++ // ── URL ↔ state ───────────────────────────────────────────────────────++ _readURL({ replace }) {+ const url = new URL(location.href);+ const net = url.searchParams.get('net');+ const sort = url.searchParams.get('sort');+ const chains = url.searchParams.get('chain');+ if (net && ['mainnet', 'testnet', 'all'].includes(net)) {+ this._net = net;+ saveNet(net);+ }+ if (sort && ['newest', 'oldest'].includes(sort)) {+ this._sort = sort;+ saveSort(sort);+ }+ if (chains !== null) {+ const parsed = chains+ .split(',')+ .map((s) => Number(s.trim()))+ .filter((n) => Number.isInteger(n) && CHAIN_META[n]);+ this._chains = parsed;+ saveChains(parsed);+ }++ this._renderNetSegmented();+ this._renderSortSelect();+ this._renderChainChips();+ this._resetAndLoad();+ }++ _pushURL() {+ const url = new URL(location.href);+ if (this._net !== 'mainnet') url.searchParams.set('net', this._net);+ else url.searchParams.delete('net');+ if (this._sort !== 'newest') url.searchParams.set('sort', this._sort);+ else url.searchParams.delete('sort');+ if (this._chains.length) url.searchParams.set('chain', this._chains.join(','));+ else url.searchParams.delete('chain');+ history.replaceState({}, '', url.toString());+ }++ // ── Controls ──────────────────────────────────────────────────────────++ _bindControls() {+ this.container.querySelector('[data-role="netGroup"]').addEventListener('click', (e) => {+ const btn = e.target.closest('button[data-net]');+ if (!btn) return;+ const next = btn.dataset.net;+ if (next === this._net) return;+ this._net = next;+ saveNet(next);+ // Clearing chain filter makes sense when flipping net (chips re-render anyway).+ this._chains = [];+ saveChains([]);+ this._renderNetSegmented();+ this._renderChainChips();+ this._pushURL();+ this._resetAndLoad();+ });++ this.container.querySelector('[data-role="sortSel"]').addEventListener('change', (e) => {+ const v = e.target.value;+ if (v !== 'newest' && v !== 'oldest') return;+ this._sort = v;+ saveSort(v);+ this._pushURL();+ this._resetAndLoad();+ });++ this.container.querySelector('[data-role="chainReset"]').addEventListener('click', () => {+ this._chains = [];+ saveChains([]);+ this._renderChainChips();+ this._pushURL();+ this._resetAndLoad();+ });++ this.container.querySelector('[data-role="loadMoreBtn"]').addEventListener('click', () => {+ this._loadMore();+ });+ }++ _renderNetSegmented() {+ const group = this.container.querySelector('[data-role="netGroup"]');+ group.querySelectorAll('button[data-net]').forEach((btn) => {+ const active = btn.dataset.net === this._net;+ btn.classList.toggle('showcase-seg--active', active);+ btn.setAttribute('aria-selected', active ? 'true' : 'false');+ });+ }++ _renderSortSelect() {+ const sel = this.container.querySelector('[data-role="sortSel"]');+ sel.value = this._sort;+ }++ _renderChainChips() {+ const root = this.container.querySelector('[data-role="chainChips"]');+ const { mainnet, testnet } = splitChains();+ const pool =+ this._net === 'mainnet'+ ? mainnet+ : this._net === 'testnet'+ ? testnet+ : [...mainnet, ...testnet];++ const chip = (id) => {+ const m = CHAIN_META[id];+ if (!m) return '';+ const active = this._chains.includes(id);+ return `+ <button type="button"+ class="showcase-chip ${active ? 'showcase-chip--active' : ''} ${m.testnet ? 'showcase-chip--testnet' : ''}"+ data-chain="${id}"+ title="${esc(m.name)}"+ aria-pressed="${active ? 'true' : 'false'}"+ >+ <span class="showcase-chip-dot"></span>+ ${esc(m.shortName || m.name)}+ </button>+ `;+ };++ root.innerHTML = pool.map(chip).join('');+ root.querySelectorAll('.showcase-chip').forEach((btn) => {+ btn.addEventListener('click', () => {+ const id = Number(btn.dataset.chain);+ const idx = this._chains.indexOf(id);+ if (idx >= 0) this._chains.splice(idx, 1);+ else this._chains.push(id);+ saveChains(this._chains);+ this._renderChainChips();+ this._pushURL();+ this._resetAndLoad();+ });+ });++ const reset = this.container.querySelector('[data-role="chainReset"]');+ reset.hidden = this._chains.length === 0;+ }++ // ── Data ──────────────────────────────────────────────────────────────++ _resetAndLoad() {+ this._items = [];+ this._nextCursor = null;+ this._reqSeq++;+ this._renderResults({ skeleton: true });+ this._loadMore({ first: true });+ }++ async _loadMore({ first = false } = {}) {+ if (this._loading) return;+ if (!first && !this._nextCursor) return;+ this._loading = true;+ const seq = this._reqSeq;+ this._setLoadMoreState();++ const params = new URLSearchParams();+ params.set('net', this._net);+ params.set('sort', this._sort);+ params.set('limit', String(PAGE_SIZE));+ if (this._chains.length) params.set('chain', this._chains.join(','));+ if (this._nextCursor) params.set('cursor', this._nextCursor);++ try {+ const res = await fetch('/api/showcase?' + params.toString(), {+ headers: { accept: 'application/json' },+ });+ if (!res.ok) {+ const text = await res.text().catch(() => '');+ throw new Error(`HTTP ${res.status}${text ? ': ' + text.slice(0, 200) : ''}`);+ }+ const data = await res.json();+ if (seq !== this._reqSeq) return; // superseded+ const agents = Array.isArray(data.agents) ? data.agents : [];+ this._items = this._items.concat(agents);+ this._nextCursor = data.next_cursor || null;+ this._total = Number(data.total) || this._total;+ this._renderStats();+ this._renderResults();+ } catch (err) {+ if (seq !== this._reqSeq) return;+ this._renderError(err.message || String(err));+ } finally {+ if (seq === this._reqSeq) this._loading = false;+ this._setLoadMoreState();+ }+ }++ _maybeAutoLoad() {+ if (this._loading || !this._nextCursor) return;+ const more = this.container.querySelector('[data-role="loadMore"]');+ if (!more || more.hidden) return;+ const rect = more.getBoundingClientRect();+ if (rect.top < window.innerHeight + 400) this._loadMore();+ }++ // ── Render ────────────────────────────────────────────────────────────++ _renderStats() {+ const el = this.container.querySelector('[data-role="statTotal"]');+ if (el) el.textContent = formatCount(this._total);+ }++ _setLoadMoreState() {+ const wrap = this.container.querySelector('[data-role="loadMore"]');+ const btn = this.container.querySelector('[data-role="loadMoreBtn"]');+ if (!wrap || !btn) return;+ wrap.hidden = !this._nextCursor;+ btn.disabled = !!this._loading;+ btn.textContent = this._loading ? 'Loading…' : 'Load more';+ }++ _renderResults({ skeleton = false } = {}) {+ const out = this.container.querySelector('[data-role="results"]');+ if (skeleton) {+ out.innerHTML = `+ <div class="showcase-grid" aria-busy="true">+ ${Array.from(+ { length: 8 },+ () => `+ <div class="showcase-card showcase-card--skel">+ <div class="showcase-skel-img"></div>+ <div class="showcase-skel-line"></div>+ <div class="showcase-skel-line showcase-skel-line--short"></div>+ </div>+ `,+ ).join('')}+ </div>+ `;+ return;+ }++ if (!this._items.length) {+ out.innerHTML = `+ <div class="showcase-empty">+ <div class="showcase-empty-art">✨</div>+ <h3>No three.wss found.</h3>+ <p class="showcase-muted">+ Try a different chain filter, flip to ${this._net === 'mainnet' ? 'Testnet' : 'Mainnet'}, or+ <a href="/deploy">deploy your own</a>.+ </p>+ </div>+ `;+ return;+ }++ out.innerHTML = `+ <div class="showcase-grid">+ ${this._items.map((a) => renderCard(a)).join('')}+ </div>+ `;+ this._wireCardShare(out);+ }++ _renderError(message) {+ const out = this.container.querySelector('[data-role="results"]');+ out.innerHTML = `+ <div class="showcase-empty showcase-empty--error">+ <div class="showcase-empty-art">⚠️</div>+ <h3>Couldn't load the directory.</h3>+ <p class="showcase-muted">${esc(message)}</p>+ <button type="button" class="showcase-btn" data-role="retry">Retry</button>+ </div>+ `;+ out.querySelector('[data-role="retry"]').addEventListener('click', () =>+ this._resetAndLoad(),+ );+ }++ _wireCardShare(root) {+ root.querySelectorAll('[data-role="card-share"]').forEach((btn) => {+ btn.addEventListener('click', async (e) => {+ e.preventDefault();+ const href = btn.dataset.share;+ if (!href) return;+ const url = new URL(href, location.origin).toString();+ try {+ await navigator.clipboard.writeText(url);+ btn.textContent = 'Copied ✓';+ setTimeout(() => (btn.textContent = 'Share'), 1400);+ } catch {+ window.prompt('Copy link:', url);+ }+ });+ });+ }+}++// ─── Card ──────────────────────────────────────────────────────────────────++/**+ * @param {object} a Shaped agent from /api/showcase+ */+function renderCard(a) {+ const chainMeta = CHAIN_META[a.chainId];+ const chainShort = chainMeta?.shortName || a.chainName || `#${a.chainId}`;+ const img = a.image ? resolveURI(a.image) : '';+ const title = esc(a.name || `Agent #${a.agentId}`);+ const descLine = a.description+ ? `<p class="showcase-card-desc">${esc(truncate(a.description, 140))}</p>`+ : '';+ const ownerLine = a.owner+ ? `<a class="showcase-card-owner" href="${esc(a.ownerExplorerUrl || '#')}" target="_blank" rel="noopener" title="${esc(a.owner)}">Owner ${esc(shortAddr(a.owner))} ↗</a>`+ : '';++ const tags = [];+ tags.push(`<span class="showcase-tag showcase-tag--3d">3D</span>`);+ if (a.x402Support) tags.push(`<span class="showcase-tag showcase-tag--x402">x402 💳</span>`);+ const serviceTypes = new Set();+ for (const s of a.services || []) {+ const name = String(s?.name || '').toLowerCase();+ if (name === 'a2a' || name.startsWith('a2a')) serviceTypes.add('A2A');+ else if (name === 'mcp' || name.startsWith('mcp')) serviceTypes.add('MCP');+ else if (name === 'oasf') serviceTypes.add('OASF');+ }+ for (const t of serviceTypes) tags.push(`<span class="showcase-tag">${t}</span>`);++ return `+ <article class="showcase-card">+ <a class="showcase-card-thumb" href="${esc(a.viewerUrl)}" aria-label="Open Agent #${esc(a.agentId)} in 3D viewer">+ ${img ? `<img src="${esc(img)}" alt="" loading="lazy" />` : `<div class="showcase-card-ph">🤖</div>`}+ <span class="showcase-chain-badge ${chainMeta?.testnet ? 'showcase-chain-badge--testnet' : ''}" title="${esc(chainMeta?.name || '')}">+ ${esc(chainShort)}+ </span>+ <span class="showcase-card-3dpill">▶ 3D</span>+ </a>+ <div class="showcase-card-body">+ <div class="showcase-card-head">+ <a class="showcase-card-title" href="${esc(a.viewerUrl)}">${title}</a>+ <span class="showcase-card-id">#${esc(a.agentId)}</span>+ </div>+ ${descLine}+ <div class="showcase-card-tags">${tags.join('')}</div>+ ${ownerLine}+ <div class="showcase-card-actions">+ <a class="showcase-btn showcase-btn--sm showcase-btn--primary" href="${esc(a.viewerUrl)}">Open 3D ↗</a>+ ${a.tokenExplorerUrl ? `<a class="showcase-btn showcase-btn--sm" href="${esc(a.tokenExplorerUrl)}" target="_blank" rel="noopener">Explorer ↗</a>` : ''}+ <button type="button" class="showcase-btn showcase-btn--sm showcase-btn--ghost"+ data-role="card-share" data-share="${esc(a.viewerUrl)}" title="Copy shareable link">Share</button>+ </div>+ </div>+ </article>+ `;+}++function truncate(s, n) {+ s = String(s || '');+ return s.length > n ? s.slice(0, n - 1) + '…' : s;+}++function formatCount(n) {+ if (!Number.isFinite(n)) return '—';+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';+ if (n >= 1_000) return (n / 1_000).toFixed(1).replace(/\.0$/, '') + 'K';+ return String(n);+}diff --git a/publish/src/erc8004/solana-deploy.js b/publish/src/erc8004/solana-deploy.jsnew file mode 100644index 000000000..579226a2f--- /dev/null+++ b/publish/src/erc8004/solana-deploy.js@@ -0,0 +1,185 @@+/**+ * Solana deploy flow — Metaplex Core NFT minted via the user's wallet.+ *+ * Mirrors the EVM register flow in deploy-button.js but for Solana:+ * 1. POST /api/agents/solana-register-prep — server builds an unsigned+ * Metaplex Core createV1 transaction (base64) for `wallet_address`.+ * 2. Phantom (or any compatible Solana wallet) signs and submits the tx.+ * 3. POST /api/agents/solana-register-confirm — server verifies the tx and+ * upserts the agent_identity row with chain_type='solana'.+ *+ * Wallet must be linked to the user account via SIWS first; the prep endpoint+ * returns 403 otherwise.+ */++import { Connection, Keypair, Transaction, VersionedTransaction } from '@solana/web3.js';+import { grindVanity } from '../solana/vanity/grinder.js';++/** Detect an injected Solana wallet (Phantom / Backpack / Solflare). */+export function detectSolanaWallet() {+ if (typeof window === 'undefined') return null;+ if (window.phantom?.solana?.isPhantom) return window.phantom.solana;+ if (window.solana?.isPhantom) return window.solana;+ if (window.backpack?.solana) return window.backpack.solana;+ if (window.solflare?.isSolflare) return window.solflare;+ return null;+}++export const SOLANA_RPC = {+ mainnet: 'https://api.mainnet-beta.solana.com',+ devnet: 'https://api.devnet.solana.com',+};+const RPC = SOLANA_RPC;++export function solanaTxExplorerUrl(network, sig) {+ return network === 'devnet'+ ? `https://explorer.solana.com/tx/${sig}?cluster=devnet`+ : `https://solscan.io/tx/${sig}`;+}++/** @param {string} b64 */+function decodeBase64Tx(b64) {+ const bin = atob(b64);+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ // Server uses Umi's buildAndSign which produces a versioned tx.+ try {+ return VersionedTransaction.deserialize(bytes);+ } catch {+ return Transaction.from(bytes);+ }+}++/**+ * Run the Solana deploy flow end-to-end.+ *+ * @param {object} opts+ * @param {object} opts.agent Agent record. Required: id, name. Optional: avatarId, description.+ * @param {'mainnet'|'devnet'} opts.network+ * @param {object} [opts.vanity] Optional vanity prefix config.+ * @param {string} [opts.vanity.prefix] Base58 prefix to grind.+ * @param {(p: { attempts: number, rate: number, eta: string }) => void} [opts.vanity.onProgress]+ * @param {AbortSignal} [opts.vanity.signal]+ * @param {Uint8Array} [opts.vanity.preGroundSecretKey] 64-byte Ed25519 secret key from a CLI grinder+ * (e.g. nirholas/solana-wallet-toolkit). When present, the in-browser grinder+ * is skipped and this keypair is used directly. The caller is responsible for+ * verifying the public key matches `vanity.prefix`.+ * @returns {Promise<{ assetPubkey: string, txSignature: string, network: string, agent: object, vanityPrefix?: string }>}+ */+export async function runSolanaDeploy({ agent, network, vanity }) {+ const wallet = detectSolanaWallet();+ if (!wallet) {+ const err = new Error('No Solana wallet detected. Install Phantom to continue.');+ err.code = 'NO_WALLET';+ throw err;+ }++ const conn = await wallet.connect();+ const walletAddress = (conn?.publicKey || wallet.publicKey)?.toString();+ if (!walletAddress) throw new Error('Could not read Solana wallet address.');++ // Optional: grind a vanity asset keypair before asking the server to build the tx.+ // Or accept a pre-ground keypair from a CLI grinder (faster for prefixes >=5 chars).+ let vanityKeypair = null;+ if (vanity?.preGroundSecretKey) {+ vanityKeypair = Keypair.fromSecretKey(vanity.preGroundSecretKey);+ if (vanity.prefix && !vanityKeypair.publicKey.toBase58().startsWith(vanity.prefix)) {+ throw new Error(`Pre-ground keypair does not start with prefix "${vanity.prefix}".`);+ }+ } else if (vanity?.prefix) {+ const result = await grindVanity({+ prefix: vanity.prefix,+ onProgress: vanity.onProgress,+ signal: vanity.signal,+ });+ vanityKeypair = Keypair.fromSecretKey(result.secretKey);+ }++ const prepResp = await fetch('/api/agents/solana-register-prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: agent.name || 'Agent',+ description: agent.description || '',+ avatar_id: agent.avatarId || agent.avatar_id,+ wallet_address: walletAddress,+ network,+ ...(vanityKeypair ? {+ asset_pubkey: vanityKeypair.publicKey.toBase58(),+ vanity_prefix: vanity.prefix,+ } : {}),+ }),+ });+ if (!prepResp.ok) {+ const data = await prepResp.json().catch(() => ({}));+ const err = new Error(+ data.error_description || `solana-register-prep returned ${prepResp.status}`,+ );+ err.status = prepResp.status;+ err.code = data.error;+ throw err;+ }+ const prep = await prepResp.json();+ const tx = decodeBase64Tx(prep.tx_base64);++ // If we used a vanity keypair, the server built the tx with a noop signer+ // for the asset slot — we must fill it in here before the wallet signs.+ // VersionedTransaction.sign() only modifies signatures whose pubkey matches+ // a provided signer, so the wallet sig slot is preserved as zero for Phantom.+ if (vanityKeypair && tx instanceof VersionedTransaction) {+ tx.sign([vanityKeypair]);+ } else if (vanityKeypair && tx instanceof Transaction) {+ tx.partialSign(vanityKeypair);+ }++ // Phantom + Backpack expose signAndSendTransaction; Solflare does too.+ const endpoint = RPC[network] || RPC.mainnet;+ let signature;+ if (typeof wallet.signAndSendTransaction === 'function') {+ const res = await wallet.signAndSendTransaction(tx);+ signature = res?.signature || res;+ } else {+ const signed = await wallet.signTransaction(tx);+ const conn2 = new Connection(endpoint, 'confirmed');+ const raw = signed.serialize();+ signature = await conn2.sendRawTransaction(raw);+ }++ // Wait for confirmation before calling the server.+ const conn3 = new Connection(endpoint, 'confirmed');+ await conn3.confirmTransaction(signature, 'confirmed');++ const confirmResp = await fetch('/api/agents/solana-register-confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ tx_signature: signature,+ asset_pubkey: prep.asset_pubkey,+ wallet_address: walletAddress,+ network,+ name: agent.name,+ description: agent.description || '',+ avatar_id: agent.avatarId || agent.avatar_id,+ }),+ });+ if (!confirmResp.ok) {+ const data = await confirmResp.json().catch(() => ({}));+ const err = new Error(+ data.error_description || `solana-register-confirm returned ${confirmResp.status}`,+ );+ err.status = confirmResp.status;+ err.code = data.error;+ err.txSignature = signature;+ throw err;+ }+ const confirmed = await confirmResp.json();+ return {+ assetPubkey: prep.asset_pubkey,+ txSignature: signature,+ network,+ agent: confirmed.agent,+ ...(vanity?.prefix ? { vanityPrefix: vanity.prefix } : {}),+ };+}diff --git a/publish/src/erc8004/thumbnail.js b/publish/src/erc8004/thumbnail.jsnew file mode 100644index 000000000..0ccdd9ab1--- /dev/null+++ b/publish/src/erc8004/thumbnail.js@@ -0,0 +1,96 @@+/**+ * Client-side GLB → PNG thumbnail renderer.+ *+ * ERC-8004's `image` field is for 2D ERC-721 marketplace compatibility+ * (OpenSea, wallets) which can't render GLB. When a user deploys a three.ws+ * without supplying a 2D poster, we render one from the GLB in an offscreen+ * canvas and pin it alongside the body.+ */++import {+ Scene,+ PerspectiveCamera,+ WebGLRenderer,+ HemisphereLight,+ DirectionalLight,+ Color,+ Box3,+ Vector3,+ SRGBColorSpace,+ ACESFilmicToneMapping,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';++/**+ * Render a GLB/GLTF file to a PNG blob.+ *+ * @param {File|Blob} file GLB/GLTF file+ * @param {object} [opts]+ * @param {number} [opts.size=512]+ * @param {string} [opts.background='#1a1a1a']+ * @returns {Promise<Blob>} PNG blob (has `.name = 'thumbnail.png'`)+ */+export async function glbFileToThumbnail(file, { size = 512, background = '#1a1a1a' } = {}) {+ const buffer = await file.arrayBuffer();+ const loader = new GLTFLoader();+ const gltf = await new Promise((resolve, reject) => {+ loader.parse(buffer, '', resolve, reject);+ });++ const scene = new Scene();+ scene.background = new Color(background);+ scene.add(gltf.scene);++ const box = new Box3().setFromObject(gltf.scene);+ const center = box.getCenter(new Vector3());+ const boxSize = box.getSize(new Vector3());+ const maxDim = Math.max(boxSize.x, boxSize.y, boxSize.z) || 1;++ const fov = 35;+ const camera = new PerspectiveCamera(fov, 1, 0.01, 1000);+ const dist = maxDim / (2 * Math.tan((Math.PI * fov) / 360));+ // Mixamo-style framing: eye-level, slightly above center, pulled back.+ camera.position.set(center.x, center.y + boxSize.y * 0.05, center.z + dist * 1.8);+ camera.lookAt(center.x, center.y, center.z);++ scene.add(new HemisphereLight(0xffffff, 0x444444, 2.0));+ const dir = new DirectionalLight(0xffffff, 2.5);+ dir.position.set(3, 10, 7);+ scene.add(dir);++ const canvas = document.createElement('canvas');+ canvas.width = size;+ canvas.height = size;+ const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: false });+ renderer.setPixelRatio(1);+ renderer.setSize(size, size, false);+ renderer.outputColorSpace = SRGBColorSpace;+ renderer.toneMapping = ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.0;++ try {+ renderer.render(scene, camera);+ const blob = await new Promise((resolve, reject) => {+ canvas.toBlob(+ (b) => (b ? resolve(b) : reject(new Error('toBlob returned null'))),+ 'image/png',+ );+ });+ // File-like name so pinFile can label the upload.+ try {+ Object.defineProperty(blob, 'name', { value: 'thumbnail.png' });+ } catch {+ /* Blob is usually writable; ignore if not */+ }+ return blob;+ } finally {+ renderer.dispose();+ scene.traverse((obj) => {+ if (obj.geometry) obj.geometry.dispose?.();+ if (obj.material) {+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];+ for (const m of mats) m.dispose?.();+ }+ });+ }+}diff --git a/publish/src/erc8004/user-profile.js b/publish/src/erc8004/user-profile.jsnew file mode 100644index 000000000..53c38023e--- /dev/null+++ b/publish/src/erc8004/user-profile.js@@ -0,0 +1,223 @@+/**+ * Public user profile page — /u/:address+ *+ * Shows all ERC-8004 agents registered by a given Ethereum address across+ * all supported chains. Uses existing query layer (listAgentsByOwner,+ * fetchAgentMetadata, findAvatar3D) — no new backend needed.+ */++import { JsonRpcProvider, Contract } from 'ethers';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './abi.js';+import { listAgentsByOwner, fetchAgentMetadata, findAvatar3D } from './queries.js';+import { CHAIN_META, supportedChainIds } from './chain-meta.js';+import { resolveURI } from '../ipfs.js';++const esc = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );++const shortAddr = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : '');++/**+ * Mount the user profile into `rootEl`.+ * @param {HTMLElement} rootEl+ * @param {string} address Ethereum address (0x…)+ */+export async function mountUserProfile(rootEl, address) {+ rootEl.innerHTML = renderShell(address);++ const grid = rootEl.querySelector('.up-grid');+ const header = rootEl.querySelector('.up-header-count');+ const chainBar = rootEl.querySelector('.up-chain-bar');++ // Scan all mainnet chains in parallel+ const mainnetChains = supportedChainIds().filter((id) => !CHAIN_META[id]?.testnet);++ let totalAgents = 0;+ let chainsWithAgents = [];++ // Per-chain results accumulate into the grid as they resolve+ const chainResults = await Promise.allSettled(+ mainnetChains.map(async (chainId) => {+ const { ids, count, partial } = await listAgentsByOwner({+ chainId,+ owner: address,+ }).catch(() => ({ ids: [], count: 0, partial: false }));++ if (count === 0) return { chainId, count: 0, cards: [] };++ // Fetch metadata for each agent (cap at 50 per chain to avoid rate limits)+ const toFetch = ids.slice(0, 50);+ const cards = await Promise.all(+ toFetch.map((agentId) => resolveAgentCard({ chainId, agentId, address })),+ );++ return { chainId, count, partial, cards };+ }),+ );++ const allCards = [];+ for (const result of chainResults) {+ if (result.status !== 'fulfilled') continue;+ const { chainId, count, cards } = result.value;+ if (count === 0) continue;+ totalAgents += count;+ chainsWithAgents.push(chainId);+ allCards.push(...cards);+ }++ // Update header count+ if (header) {+ header.textContent =+ totalAgents === 0+ ? 'No agents registered yet'+ : `${totalAgents} agent${totalAgents === 1 ? '' : 's'} across ${chainsWithAgents.length} chain${chainsWithAgents.length === 1 ? '' : 's'}`;+ }++ // Render chain filter pills+ if (chainBar && chainsWithAgents.length > 1) {+ chainBar.innerHTML =+ `<button class="up-chain-pill up-chain-pill--active" data-chain="all">All</button>` ++ chainsWithAgents+ .map((id) => {+ const meta = CHAIN_META[id];+ return `<button class="up-chain-pill" data-chain="${id}">${esc(meta?.shortName || id)}</button>`;+ })+ .join('');++ chainBar.addEventListener('click', (e) => {+ const btn = e.target.closest('.up-chain-pill');+ if (!btn) return;+ chainBar.querySelectorAll('.up-chain-pill').forEach((b) => b.classList.remove('up-chain-pill--active'));+ btn.classList.add('up-chain-pill--active');+ const chain = btn.dataset.chain;+ grid.querySelectorAll('.up-card').forEach((card) => {+ card.hidden = chain !== 'all' && card.dataset.chain !== chain;+ });+ });+ } else if (chainBar) {+ chainBar.hidden = true;+ }++ // Render cards+ if (allCards.length === 0) {+ grid.innerHTML = `<p class="up-empty">No agents registered on-chain yet. <a href="/create">Create one →</a></p>`;+ return;+ }++ // Sort: newest agent ID first (higher ID = more recent mint on same chain)+ allCards.sort((a, b) => Number(b.agentId) - Number(a.agentId));++ grid.innerHTML = allCards.map(renderCard).join('');++ // Lazy-load thumbnails via model-viewer after card DOM is present+ grid.querySelectorAll('.up-card[data-glb]').forEach((card) => {+ const glb = card.dataset.glb;+ if (!glb) return;+ const thumb = card.querySelector('.up-card-thumb');+ if (!thumb) return;+ thumb.innerHTML = `<model-viewer+ src="${esc(glb)}"+ camera-controls+ auto-rotate+ rotation-per-second="15deg"+ exposure="0.9"+ shadow-intensity="0"+ interaction-prompt="none"+ style="width:100%;height:100%;background:transparent"+ loading="lazy"+ ></model-viewer>`;+ });+}++async function resolveAgentCard({ chainId, agentId, address }) {+ const base = {+ chainId,+ agentId,+ owner: address,+ name: `Agent #${agentId}`,+ description: '',+ image: '',+ glb: '',+ };++ try {+ const meta = CHAIN_META[chainId];+ if (!meta) return base;++ const provider = new JsonRpcProvider(meta.rpcUrl, chainId);+ const addr = REGISTRY_DEPLOYMENTS[chainId]?.identityRegistry;+ if (!addr) return base;++ const registry = new Contract(addr, IDENTITY_REGISTRY_ABI, provider);+ const tokenURI = await registry.tokenURI(agentId).catch(() => null);+ if (!tokenURI) return base;++ const { ok, data } = await fetchAgentMetadata(tokenURI);+ if (!ok || !data) return base;++ const rawGlb = findAvatar3D(data);+ const glb = rawGlb ? await resolveURI(rawGlb).catch(() => rawGlb) : '';++ return {+ ...base,+ name: data.name || base.name,+ description: data.description || '',+ image: data.image || '',+ glb,+ };+ } catch {+ return base;+ }+}++function renderCard({ chainId, agentId, name, description, image, glb }) {+ const meta = CHAIN_META[chainId];+ const agentUrl = `/a/${chainId}/${agentId}`;+ const hasThumb = !!glb || !!image;+ const thumbContent = glb+ ? '' // filled lazily+ : image+ ? `<img src="${esc(image)}" alt="${esc(name)} thumbnail" style="width:100%;height:100%;object-fit:cover">`+ : `<div class="up-card-thumb-placeholder">◎</div>`;++ const editUrl = `/a/${chainId}/${agentId}/edit`;++ return `<article+ class="up-card"+ data-chain="${chainId}"+ ${glb ? `data-glb="${esc(glb)}"` : ''}+ >+ <a href="${esc(agentUrl)}" class="up-card-thumb-link" tabindex="-1" aria-hidden="true">+ <div class="up-card-thumb">${thumbContent}</div>+ </a>+ <div class="up-card-body">+ <div class="up-card-chain">${esc(meta?.shortName || chainId)}</div>+ <a href="${esc(agentUrl)}" class="up-card-name">${esc(name)}</a>+ ${description ? `<p class="up-card-desc">${esc(description)}</p>` : ''}+ <div class="up-card-footer">+ <span class="up-card-id">#${agentId}</span>+ <a href="${esc(editUrl)}" class="up-card-edit">Edit →</a>+ </div>+ </div>+ </article>`;+}++function renderShell(address) {+ return `+ <div class="up-hero">+ <div class="up-avatar-ring">+ <span class="up-avatar-glyph">◎</span>+ </div>+ <div class="up-hero-info">+ <h1 class="up-address">${esc(shortAddr(address))}</h1>+ <p class="up-header-count up-muted">Loading agents…</p>+ <p class="up-full-address up-muted">${esc(address)}</p>+ </div>+ </div>+ <div class="up-chain-bar"></div>+ <div class="up-grid"></div>+ `;+}diff --git a/publish/src/erc8004/validation-recorder.js b/publish/src/erc8004/validation-recorder.jsnew file mode 100644index 000000000..c39d1009e--- /dev/null+++ b/publish/src/erc8004/validation-recorder.js@@ -0,0 +1,99 @@+/**+ * ValidationRegistry bridge — turn a glTF-Validator report into an on-chain+ * validation record.+ *+ * Usage:+ * import { recordValidation } from './erc8004/validation-recorder.js';+ * await recordValidation({ agentId, report, signer, pinToIPFS, apiToken });+ */++import { Contract, keccak256, toUtf8Bytes } from 'ethers';+import { REGISTRY_DEPLOYMENTS, VALIDATION_REGISTRY_ABI } from './abi.js';+import { pinFile } from './agent-registry.js';++const KIND_GLB_SCHEMA = 'glb-schema';++/**+ * Derive a deterministic pass/fail flag from a glTF-Validator report.+ * Pass = zero errors (warnings/infos/hints are allowed).+ */+export function reportPassed(report) {+ const errs = (report && report.issues && report.issues.numErrors) || 0;+ return errs === 0;+}++/**+ * keccak256 hash of the canonicalized JSON report, suitable for on-chain proof.+ * @param {object} report+ * @returns {string} 0x-prefixed 32-byte hex.+ */+export function hashReport(report) {+ const json = JSON.stringify(report);+ return keccak256(toUtf8Bytes(json));+}++/**+ * Record a validation result on-chain. Optionally pin the full report to IPFS+ * first so verifiers can fetch the details behind the hash.+ *+ * @param {object} opts+ * @param {number|bigint} opts.agentId+ * @param {object} opts.report glTF-Validator report+ * @param {import('ethers').Signer} opts.signer Must be an allow-listed validator+ * @param {number} [opts.chainId] Defaults to signer's network+ * @param {string} [opts.apiToken] IPFS pinning token (optional)+ * @param {boolean} [opts.pin=true] Pin report to IPFS before recording+ * @param {string} [opts.kind='glb-schema']+ * @returns {Promise<{txHash: string, proofHash: string, proofURI: string, passed: boolean}>}+ */+export async function recordValidation({+ agentId,+ report,+ signer,+ chainId,+ apiToken,+ pin = true,+ kind = KIND_GLB_SCHEMA,+}) {+ if (!signer) throw new Error('signer is required');+ if (!report) throw new Error('report is required');++ const resolvedChainId = chainId ?? Number((await signer.provider.getNetwork()).chainId);+ const deployment = REGISTRY_DEPLOYMENTS[resolvedChainId];+ if (!deployment || !deployment.validationRegistry) {+ throw new Error(`No Validation Registry deployed on chain ${resolvedChainId}.`);+ }++ const proofHash = hashReport(report);+ const passed = reportPassed(report);++ let proofURI = '';+ if (pin && apiToken) {+ const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });+ const cid = await pinFile(blob, apiToken);+ proofURI = `ipfs://${cid}`;+ }++ const contract = new Contract(deployment.validationRegistry, VALIDATION_REGISTRY_ABI, signer);+ const tx = await contract.recordValidation(agentId, passed, proofHash, proofURI, kind);+ await tx.wait();++ return { txHash: tx.hash, proofHash, proofURI, passed };+}++/**+ * Read the most recent validation of a given kind.+ * @param {object} opts+ * @param {number|bigint} opts.agentId+ * @param {import('ethers').Provider | import('ethers').Signer} opts.runner+ * @param {number} opts.chainId+ * @param {string} [opts.kind='glb-schema']+ */+export async function getLatestValidation({ agentId, runner, chainId, kind = KIND_GLB_SCHEMA }) {+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment || !deployment.validationRegistry) {+ throw new Error(`No Validation Registry deployed on chain ${chainId}.`);+ }+ const contract = new Contract(deployment.validationRegistry, VALIDATION_REGISTRY_ABI, runner);+ return contract.getLatestByKind(agentId, kind);+}diff --git a/publish/src/erc8004/vanity-modal.js b/publish/src/erc8004/vanity-modal.jsnew file mode 100644index 000000000..6de325a39--- /dev/null+++ b/publish/src/erc8004/vanity-modal.js@@ -0,0 +1,350 @@+/**+ * VanityModal — focused mini-modal for picking a Solana vanity prefix.+ *+ * Surfaces:+ * - Live address preview ("AGNT9k4mPq3X…fT2H") that updates as the user types+ * - Suggestion chips seeded from the agent name + curated short prefixes+ * - Difficulty meter with per-tier (Free/Pro) callouts+ * - Estimated grind time + paid-plan badge for >=5 chars+ * - Mobile warning when hardwareConcurrency <= 2+ *+ * Returns the chosen prefix via `await openVanityModal({ agentName })`,+ * or `null` if the user dismisses.+ *+ * Persistence is the caller's job (see deploy-button.js).+ */++const FREE_THRESHOLD = 5;+const MAX_LENGTH = 6;+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+const RATE_PER_CORE = 5000; // empirical lower bound for JS Keypair.generate()+const CURATED_CHIPS = ['AGNT', 'BOT', 'NPC', 'AI', 'GOOD', 'WISE'];++function _esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ })[c]);+}++function _coreCount() {+ if (typeof navigator === 'undefined') return 4;+ return Math.max(1, Math.min(navigator.hardwareConcurrency || 4, 8));+}++function _estimateSeconds(prefixLen) {+ if (prefixLen <= 0) return 0;+ const attempts = Math.pow(58, prefixLen);+ return attempts / (RATE_PER_CORE * _coreCount());+}++function _formatTime(seconds) {+ if (seconds < 1) return '<1s';+ if (seconds < 60) return `~${Math.round(seconds)}s`;+ if (seconds < 3600) return `~${Math.round(seconds / 60)}m`;+ if (seconds < 86400) return `~${Math.round(seconds / 3600)}h`;+ return '>1d';+}++/** Sample base58 string (deterministic-ish — not crypto). For preview only. */+function _sampleAddress(prefix = '') {+ const len = 44 - prefix.length;+ let out = prefix;+ for (let i = 0; i < len; i++) {+ out += BASE58_ALPHABET[Math.floor(Math.random() * BASE58_ALPHABET.length)];+ }+ return out;+}++function _suggestionsFor(agentName) {+ const seeded = [];+ if (agentName) {+ // First 3-4 base58-valid chars of the name, capitalized.+ const cleaned = agentName.replace(/[^1-9A-HJ-NP-Za-km-z]/g, '');+ if (cleaned.length >= 3) seeded.push(cleaned.slice(0, 4));+ }+ const all = [...new Set([...seeded, ...CURATED_CHIPS])].slice(0, 6);+ return all;+}++const STYLE = `+.vm-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.5); z-index: 9999; display: flex; align-items: center; justify-content: center; padding: 1rem; }+.vm-modal { background: #fff; border-radius: 12px; max-width: 460px; width: 100%; padding: 1.25rem 1.4rem; box-shadow: 0 20px 60px rgba(0,0,0,.3); font: 14px/1.4 system-ui, sans-serif; color: #111; }+.vm-title { font-size: 1.1rem; font-weight: 600; margin: 0 0 .25rem; }+.vm-sub { color: #666; font-size: .8rem; margin: 0 0 1rem; }+.vm-input { font: inherit; font-family: ui-monospace, monospace; padding: .5rem .65rem; width: 100%; border: 1px solid #ccc; border-radius: 6px; box-sizing: border-box; text-transform: none; }+.vm-input.invalid { border-color: #c33; background: #fff8f8; }+.vm-preview { font-family: ui-monospace, monospace; font-size: .85rem; padding: .55rem .65rem; background: #f7f7f8; border-radius: 6px; margin-top: .55rem; word-break: break-all; }+.vm-preview .pfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 2px; border-radius: 2px; font-weight: 600; }+.vm-preview .rest { color: #888; }+.vm-meter { display: flex; gap: 3px; margin-top: .6rem; }+.vm-meter .seg { flex: 1; height: 6px; border-radius: 3px; background: #eee; }+.vm-meter .seg.lit-1, .vm-meter .seg.lit-2, .vm-meter .seg.lit-3, .vm-meter .seg.lit-4 { background: #4caf50; }+.vm-meter .seg.lit-5 { background: #fb8c00; }+.vm-meter .seg.lit-6 { background: #d32f2f; }+.vm-row { display: flex; justify-content: space-between; align-items: center; margin-top: .5rem; font-size: .78rem; color: #666; }+.vm-paid { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; font-weight: 600; padding: .1rem .5rem; border-radius: 999px; font-size: .7rem; }+.vm-chips { display: flex; flex-wrap: wrap; gap: .35rem; margin-top: .85rem; }+.vm-chip { background: #f0f0f2; border: 1px solid #ddd; border-radius: 999px; padding: .25rem .65rem; cursor: pointer; font-family: ui-monospace, monospace; font-size: .75rem; color: #333; }+.vm-chip:hover { background: #e6e6e8; }+.vm-chip-est { color: #888; margin-left: .35rem; font-family: system-ui, sans-serif; }+.vm-warn { background: #fff3cd; color: #855008; padding: .5rem .65rem; border-radius: 6px; margin-top: .85rem; font-size: .75rem; }+.vm-actions { display: flex; gap: .5rem; justify-content: flex-end; margin-top: 1.1rem; }+.vm-btn { font: inherit; padding: .45rem .9rem; border-radius: 6px; border: 1px solid #ccc; background: #fff; cursor: pointer; }+.vm-btn.primary { background: #111; color: #fff; border-color: #111; }+.vm-btn:disabled { opacity: .4; cursor: not-allowed; }+.vm-skip { background: none; border: none; color: #666; font-size: .75rem; cursor: pointer; margin-top: .5rem; padding: 0; }+.vm-cli { margin-top: .85rem; padding: .55rem .65rem; background: #f7f7f8; border: 1px solid #eee; border-radius: 6px; font-size: .72rem; color: #555; }+.vm-cli code { background: #fff; padding: .1rem .3rem; border-radius: 3px; border: 1px solid #e0e0e0; font-family: ui-monospace, monospace; }+.vm-cli a { color: #0d47a1; }+.vm-cli .vm-paste-toggle { background: none; border: none; color: #0d47a1; cursor: pointer; padding: 0; font-size: .72rem; text-decoration: underline; }+.vm-paste { margin-top: .55rem; }+.vm-paste textarea { font: inherit; font-family: ui-monospace, monospace; font-size: .7rem; width: 100%; min-height: 70px; box-sizing: border-box; padding: .4rem .5rem; border: 1px solid #ccc; border-radius: 6px; resize: vertical; }+.vm-paste-status { margin-top: .35rem; font-size: .72rem; min-height: 1em; }+.vm-paste-status.ok { color: #1b5e20; }+.vm-paste-status.bad { color: #b71c1c; }+`;++let _styleInjected = false;+function _injectStyle() {+ if (_styleInjected || typeof document === 'undefined') return;+ const tag = document.createElement('style');+ tag.id = 'vanity-modal-style';+ tag.textContent = STYLE;+ document.head.appendChild(tag);+ _styleInjected = true;+}++/**+ * Open the vanity prefix picker.+ *+ * @param {object} opts+ * @param {string} [opts.agentName] Used to seed suggestion chips.+ * @param {string} [opts.initial] Pre-fill (e.g. from localStorage).+ * @returns {Promise<string | { prefix: string, secretKey: Uint8Array } | null>}+ * - `null` → user dismissed+ * - `''` → user chose "skip"+ * - `string` → prefix to grind in the browser+ * - `{ prefix, secretKey }` → pre-ground keypair from a CLI tool+ * (e.g. nirholas/solana-wallet-toolkit); skip the in-browser grinder.+ */+export function openVanityModal({ agentName = '', initial = '' } = {}) {+ _injectStyle();++ return new Promise((resolve) => {+ const overlay = document.createElement('div');+ overlay.className = 'vm-overlay';+ overlay.setAttribute('role', 'dialog');+ overlay.setAttribute('aria-modal', 'true');+ overlay.setAttribute('aria-labelledby', 'vm-title');++ const suggestions = _suggestionsFor(agentName);+ const isMobile = _coreCount() <= 2;+ overlay.innerHTML = `+ <div class="vm-modal">+ <h2 class="vm-title" id="vm-title">Customize your agent's address</h2>+ <p class="vm-sub">Pick characters your agent's Solana address should start with.</p>++ <label for="vm-input" style="font-size:.8rem;color:#444;">Prefix (Base58, max ${MAX_LENGTH})</label>+ <input id="vm-input" class="vm-input" type="text" maxlength="${MAX_LENGTH}"+ placeholder="e.g. AGNT" autocomplete="off" spellcheck="false"+ value="${_esc(initial)}" />++ <div class="vm-preview" aria-live="polite" id="vm-preview"></div>++ <div class="vm-meter" aria-hidden="true">+ ${[1, 2, 3, 4, 5, 6].map((i) => `<div class="seg" data-seg="${i}"></div>`).join('')}+ </div>++ <div class="vm-row">+ <span id="vm-est">enter a prefix above</span>+ <span id="vm-tier"></span>+ </div>++ <div class="vm-chips" aria-label="Suggested prefixes">+ ${suggestions.map((s) => `+ <button class="vm-chip" data-prefix="${_esc(s)}" type="button">+ ${_esc(s)}<span class="vm-chip-est">${_formatTime(_estimateSeconds(s.length))}</span>+ </button>`).join('')}+ </div>++ ${isMobile ? `<div class="vm-warn">⚠️ Vanity addresses work best on desktop — your device has limited CPU cores.</div>` : ''}++ <div class="vm-cli">+ Got a long prefix? Grind offline with+ <a href="https://github.com/nirholas/solana-wallet-toolkit" target="_blank" rel="noopener">solana-wallet-toolkit</a>+ (50–100k keys/s/core), then+ <button class="vm-paste-toggle" id="vm-paste-toggle" type="button">paste the keypair JSON</button>.+ <div class="vm-paste" id="vm-paste" hidden>+ <textarea id="vm-paste-input" placeholder="[12, 34, 56, ... ] — solana-keygen JSON, 64 bytes"></textarea>+ <div class="vm-paste-status" id="vm-paste-status"></div>+ </div>+ </div>++ <div class="vm-actions">+ <button class="vm-btn" id="vm-cancel" type="button">Cancel</button>+ <button class="vm-btn primary" id="vm-ok" type="button" disabled>Use prefix</button>+ </div>+ <button class="vm-skip" id="vm-skip" type="button">Skip — use a random address</button>+ </div>+ `;+ document.body.appendChild(overlay);++ const input = overlay.querySelector('#vm-input');+ const preview = overlay.querySelector('#vm-preview');+ const meter = overlay.querySelectorAll('.vm-meter .seg');+ const estEl = overlay.querySelector('#vm-est');+ const tierEl = overlay.querySelector('#vm-tier');+ const okBtn = overlay.querySelector('#vm-ok');+ const pasteToggle = overlay.querySelector('#vm-paste-toggle');+ const pastePanel = overlay.querySelector('#vm-paste');+ const pasteInput = overlay.querySelector('#vm-paste-input');+ const pasteStatus = overlay.querySelector('#vm-paste-status');++ /** @type {{ secretKey: Uint8Array, publicKey: string } | null} */+ let pasteResult = null;++ pasteToggle.addEventListener('click', () => {+ const open = pastePanel.hasAttribute('hidden');+ pastePanel.toggleAttribute('hidden', !open);+ if (open) pasteInput.focus();+ });++ pasteInput.addEventListener('input', async () => {+ pasteResult = null;+ const raw = pasteInput.value.trim();+ if (!raw) {+ pasteStatus.textContent = '';+ pasteStatus.className = 'vm-paste-status';+ update();+ return;+ }+ let bytes;+ try {+ const arr = JSON.parse(raw);+ if (!Array.isArray(arr) || arr.length !== 64) throw new Error('expected a 64-element JSON array');+ if (!arr.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) throw new Error('values must be 0–255');+ bytes = new Uint8Array(arr);+ } catch (e) {+ pasteStatus.textContent = `invalid: ${e.message}`;+ pasteStatus.className = 'vm-paste-status bad';+ update();+ return;+ }+ try {+ const { Keypair } = await import('@solana/web3.js');+ const kp = Keypair.fromSecretKey(bytes);+ const pubkey = kp.publicKey.toBase58();+ const wantedPrefix = input.value.trim();+ if (wantedPrefix && !pubkey.startsWith(wantedPrefix)) {+ pasteStatus.textContent = `address ${pubkey.slice(0, 8)}… does not start with "${wantedPrefix}"`;+ pasteStatus.className = 'vm-paste-status bad';+ update();+ return;+ }+ pasteResult = { secretKey: bytes, publicKey: pubkey };+ pasteStatus.textContent = `✓ ${pubkey.slice(0, 12)}… ready`;+ pasteStatus.className = 'vm-paste-status ok';+ } catch (e) {+ pasteStatus.textContent = `invalid keypair: ${e.message || e}`;+ pasteStatus.className = 'vm-paste-status bad';+ }+ update();+ });++ let previewTimer = null;+ function update() {+ const raw = input.value;+ const valid = !raw || BASE58_RE.test(raw);+ input.classList.toggle('invalid', !valid);++ meter.forEach((seg, idx) => {+ seg.className = 'seg' + (raw.length > idx ? ` lit-${raw.length}` : '');+ });++ if (pasteResult) {+ preview.innerHTML = `<span class="pfx">${_esc(pasteResult.publicKey.slice(0, raw.length || 0))}</span><span class="rest">${_esc(pasteResult.publicKey.slice(raw.length || 0))}</span>`;+ estEl.textContent = `pre-ground (no browser grind)`;+ tierEl.innerHTML = `<span style="color:#1b5e20;font-weight:600">CLI</span>`;+ okBtn.disabled = false;+ okBtn.textContent = 'Use pre-ground keypair';+ return;+ }+ okBtn.textContent = 'Use prefix';++ if (!raw) {+ preview.innerHTML = '<span class="rest">' + _esc(_sampleAddress()) + '</span>';+ estEl.textContent = 'enter a prefix above';+ tierEl.innerHTML = '';+ okBtn.disabled = true;+ return;+ }+ if (!valid) {+ preview.textContent = 'invalid Base58 — avoid 0, O, I, l';+ estEl.textContent = '';+ tierEl.innerHTML = '';+ okBtn.disabled = true;+ return;+ }+ const sample = _sampleAddress(raw);+ preview.innerHTML = `<span class="pfx">${_esc(raw)}</span><span class="rest">${_esc(sample.slice(raw.length))}</span>`;+ estEl.textContent = `est. ${_formatTime(_estimateSeconds(raw.length))} on ${_coreCount()} cores`;+ tierEl.innerHTML = raw.length >= FREE_THRESHOLD+ ? `<span class="vm-paid">✦ Paid plan</span>`+ : `<span style="color:#1b5e20;font-weight:600">Free</span>`;+ okBtn.disabled = false;+ }++ // Animate the preview's tail every 600ms so it feels alive — only when prefix is set.+ function startPreviewLoop() {+ stopPreviewLoop();+ previewTimer = setInterval(() => {+ const raw = input.value;+ if (raw && BASE58_RE.test(raw)) {+ const sample = _sampleAddress(raw);+ const pfxNode = preview.querySelector('.pfx');+ const restNode = preview.querySelector('.rest');+ if (pfxNode && restNode) restNode.textContent = sample.slice(raw.length);+ }+ }, 600);+ }+ function stopPreviewLoop() {+ if (previewTimer) clearInterval(previewTimer);+ previewTimer = null;+ }++ input.addEventListener('input', update);+ overlay.querySelectorAll('.vm-chip').forEach((c) => {+ c.addEventListener('click', () => {+ input.value = c.dataset.prefix;+ update();+ input.focus();+ });+ });++ function close(value) {+ stopPreviewLoop();+ overlay.remove();+ document.removeEventListener('keydown', onKey);+ resolve(value);+ }+ function resolveValue() {+ const prefix = input.value.trim();+ if (pasteResult) return { prefix, secretKey: pasteResult.secretKey };+ return prefix;+ }+ function onKey(e) {+ if (e.key === 'Escape') close(null);+ if (e.key === 'Enter' && !okBtn.disabled && document.activeElement !== pasteInput) close(resolveValue());+ }+ overlay.querySelector('#vm-cancel').addEventListener('click', () => close(null));+ overlay.querySelector('#vm-skip').addEventListener('click', () => close(''));+ overlay.querySelector('#vm-ok').addEventListener('click', () => close(resolveValue()));+ overlay.addEventListener('click', (e) => { if (e.target === overlay) close(null); });+ document.addEventListener('keydown', onKey);++ update();+ startPreviewLoop();+ setTimeout(() => input.focus(), 50);+ });+}diff --git a/publish/src/features/hero-dragon.js b/publish/src/features/hero-dragon.jsnew file mode 100644index 000000000..626ea0b8c--- /dev/null+++ b/publish/src/features/hero-dragon.js@@ -0,0 +1,265 @@+// Dragon mode — the hero avatar chases the cursor while the subtitle reflows+// around its silhouette every frame. Inspired by the chenglou/pretext dragon+// demo. Opt-in via ?pretext=4 only; gimmick risk is real.+//+// Layering:+// - Avatar is translated via transform (.hero-avatar). .hero--dragon absolutely+// positions it within .hero; a home transform returns it to grid baseline.+// - Text reflows via PretextHero.paintCircle(cx, cy, r), called once per frame.+// - One rAF drives both the spring integrator and the reflow.+//+// Auto-downgrade: if mean reflow cost over a 30-frame window exceeds+// COST_BUDGET_MS, disable per-frame relayout and keep the chase running.++const STIFFNESS = 120;+const DAMPING = 20;+const MASS = 1;+const RETURN_EPS_POS = 0.5; // px+const RETURN_EPS_VEL = 5; // px/s+const COST_BUDGET_MS = 8;+const COST_WINDOW = 30;+const HERO_INSET = 16; // px — keep avatar fully inside hero++function prefersReducedMotion() {+ return (+ typeof window !== 'undefined' &&+ window.matchMedia &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches+ );+}++function hasHover() {+ return (+ typeof window !== 'undefined' &&+ window.matchMedia &&+ window.matchMedia('(hover: hover)').matches+ );+}++export class HeroDragon {+ constructor(hero) {+ this.hero = hero;+ this.root = hero.root;+ this.avatar = hero.avatar;+ this.modelViewer = hero.modelViewer;++ this._targetX = 0;+ this._targetY = 0;+ this._x = 0;+ this._y = 0;+ this._vx = 0;+ this._vy = 0;++ this._homeRect = null;+ this._heroRect = null;+ this._lastTs = 0;+ this._rafId = null;+ this._attached = false;+ this._returning = false;++ this._costSamples = [];+ this._downgraded = false;++ this._onPointerMove = this._onPointerMove.bind(this);+ this._onPointerLeave = this._onPointerLeave.bind(this);+ this._onResize = this._onResize.bind(this);+ this._onVisibility = this._onVisibility.bind(this);+ this._tick = this._tick.bind(this);+ }++ attach() {+ if (this._attached) return;+ if (!this.avatar || !this.root || !this.hero?.pretext) return;+ if (prefersReducedMotion()) return;+ if (!hasHover()) return;++ this._attached = true;++ this.root.classList.add('hero--dragon');+ this._setAutoRotate(false);++ // Wait a frame for the CSS to resettle (grid column changes), then+ // measure rects and recompute pretext layout context.+ requestAnimationFrame(() => {+ if (!this._attached) return;+ this._measureRects();+ this.hero.recomputeContext?.();+ this._paint();++ this.root.addEventListener('pointermove', this._onPointerMove, { passive: true });+ this.root.addEventListener('pointerleave', this._onPointerLeave);+ window.addEventListener('resize', this._onResize, { passive: true });+ window.addEventListener('scroll', this._onResize, { passive: true });+ document.addEventListener('visibilitychange', this._onVisibility);++ this._lastTs = performance.now();+ this._rafId = requestAnimationFrame(this._tick);+ });+ }++ detach() {+ if (!this._attached) return;+ this._attached = false;++ this.root.removeEventListener('pointermove', this._onPointerMove);+ this.root.removeEventListener('pointerleave', this._onPointerLeave);+ window.removeEventListener('resize', this._onResize);+ window.removeEventListener('scroll', this._onResize);+ document.removeEventListener('visibilitychange', this._onVisibility);++ if (this._rafId != null) cancelAnimationFrame(this._rafId);+ this._rafId = null;++ this.root.classList.remove('hero--dragon');+ if (this.avatar) {+ this.avatar.style.transform = '';+ this.avatar.style.willChange = '';+ }+ this._setAutoRotate(true);++ // Static wrap resumes once the class is gone — bounce through pretext's+ // own repaint path so the overlay matches the non-dragon layout.+ this.hero.recomputeContext?.();+ const c = this._homeCircle();+ if (c) this.hero.paintCircle?.(c.x, c.y, c.r);+ }++ _measureRects() {+ this._heroRect = this.root.getBoundingClientRect();+ this._homeRect = this.avatar.getBoundingClientRect();+ this.avatar.style.willChange = 'transform';+ }++ _homeCircle() {+ const ctx = this.hero._ctx;+ if (!ctx) return null;+ // Home center in overlay-local coords, mirroring _avatarCircle()+ // but using the avatar's home rect.+ const r = this._homeRect ?? ctx.avatarRect;+ return {+ x: r.left + r.width / 2 - ctx.subtitleLeftPage,+ y: r.top + r.height / 2 - ctx.subtitleTopPage,+ r: ctx.circleBaseR,+ };+ }++ _onResize() {+ if (this._resizePending) return;+ this._resizePending = true;+ requestAnimationFrame(() => {+ this._resizePending = false;+ this._measureRects();+ this.hero.recomputeContext?.();+ });+ }++ _onVisibility() {+ if (document.hidden) {+ if (this._rafId != null) cancelAnimationFrame(this._rafId);+ this._rafId = null;+ } else if (this._attached && this._rafId == null) {+ this._lastTs = performance.now();+ this._rafId = requestAnimationFrame(this._tick);+ }+ }++ _onPointerMove(e) {+ const home = this._homeRect;+ const hero = this._heroRect;+ if (!home || !hero) return;++ const homeCx = home.left + home.width / 2;+ const homeCy = home.top + home.height / 2;++ // Clamp so the avatar rect stays within the hero rect (minus inset).+ const halfW = home.width / 2;+ const halfH = home.height / 2;+ const minCx = hero.left + halfW + HERO_INSET;+ const maxCx = hero.right - halfW - HERO_INSET;+ const minCy = hero.top + halfH + HERO_INSET;+ const maxCy = hero.bottom - halfH - HERO_INSET;++ const cx = Math.min(maxCx, Math.max(minCx, e.clientX));+ const cy = Math.min(maxCy, Math.max(minCy, e.clientY));++ this._targetX = cx - homeCx;+ this._targetY = cy - homeCy;+ this._returning = false;+ }++ _onPointerLeave() {+ this._targetX = 0;+ this._targetY = 0;+ this._returning = true;+ }++ _tick(ts) {+ if (!this._attached) return;++ const dtRaw = (ts - this._lastTs) / 1000;+ this._lastTs = ts;+ // Cap dt to avoid spring explosions after a tab-switch pause.+ const dt = Math.min(dtRaw, 1 / 30);++ // Semi-implicit Euler spring integrator.+ const ax = (STIFFNESS * (this._targetX - this._x) - DAMPING * this._vx) / MASS;+ const ay = (STIFFNESS * (this._targetY - this._y) - DAMPING * this._vy) / MASS;+ this._vx += ax * dt;+ this._vy += ay * dt;+ this._x += this._vx * dt;+ this._y += this._vy * dt;++ this.avatar.style.transform = `translate3d(${this._x.toFixed(2)}px, ${this._y.toFixed(2)}px, 0)`;++ this._paint();++ // Once fully settled at home after a pointerleave, detach cleanly so+ // the static wrap and auto-rotate resume.+ if (this._returning) {+ const settled =+ Math.abs(this._x) < RETURN_EPS_POS &&+ Math.abs(this._y) < RETURN_EPS_POS &&+ Math.abs(this._vx) < RETURN_EPS_VEL &&+ Math.abs(this._vy) < RETURN_EPS_VEL;+ if (settled) {+ this.detach();+ return;+ }+ }++ this._rafId = requestAnimationFrame(this._tick);+ }++ _paint() {+ if (this._downgraded) return;+ const ctx = this.hero._ctx;+ if (!ctx) return;++ const home = this._homeRect;+ if (!home) return;++ const homeCxPage = home.left + home.width / 2;+ const homeCyPage = home.top + home.height / 2;+ const cx = homeCxPage + this._x - ctx.subtitleLeftPage;+ const cy = homeCyPage + this._y - ctx.subtitleTopPage;++ const cost = this.hero.paintCircle?.(cx, cy, ctx.circleBaseR) ?? 0;++ this._costSamples.push(cost);+ if (this._costSamples.length > COST_WINDOW) this._costSamples.shift();+ if (this._costSamples.length === COST_WINDOW) {+ let sum = 0;+ for (const c of this._costSamples) sum += c;+ if (sum / COST_WINDOW > COST_BUDGET_MS) {+ this._downgraded = true;+ console.warn('[pretext-hero] dragon downgraded — reflow cost exceeded budget');+ }+ }+ }++ _setAutoRotate(on) {+ if (!this.modelViewer) return;+ if (on) this.modelViewer.setAttribute('auto-rotate', '');+ else this.modelViewer.removeAttribute('auto-rotate');+ }+}diff --git a/publish/src/features/hero-gaze.js b/publish/src/features/hero-gaze.jsnew file mode 100644index 000000000..5e8b54988--- /dev/null+++ b/publish/src/features/hero-gaze.js@@ -0,0 +1,196 @@+// Gaze follow — the hero avatar's camera-orbit tracks the user's cursor.+//+// Uses <model-viewer>'s camera-orbit attribute rather than reaching into the+// Three.js scene, so this stays compatible with the CDN-loaded custom element+// and never touches the main app viewer.+//+// When the cursor moves over the hero, auto-rotate turns off and the avatar+// tracks the cursor (normalized relative to the avatar's bounding rect). On+// pointerleave or after an idle window, the avatar eases back to its default+// orbit and auto-rotate resumes.++// Defaults must match features.html's camera-orbit attribute.+const BASE_THETA_DEG = 20;+const BASE_PHI_DEG = 68;+const BASE_RADIUS = '3.4m';+const THETA_RANGE_DEG = 15; // ±15° azimuth — subtle but legible+const PHI_RANGE_DEG = 8; // ±8° polar+const IDLE_MS = 1200; // Resume auto-rotate after this quiet+const SMOOTH = 0.12; // Lerp alpha toward target per frame (~60fps)+const SETTLE_EPSILON = 0.05; // Degrees — below this we consider the return complete++function prefersReducedMotion() {+ return (+ typeof window !== 'undefined' &&+ window.matchMedia &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches+ );+}++function hasHover() {+ return (+ typeof window !== 'undefined' &&+ window.matchMedia &&+ window.matchMedia('(hover: hover)').matches+ );+}++export class HeroGaze {+ constructor(hero) {+ this.hero = hero;+ this.root = hero.root;+ this.avatar = hero.avatar;+ this.modelViewer = hero.modelViewer;++ this._targetTheta = BASE_THETA_DEG;+ this._targetPhi = BASE_PHI_DEG;+ this._currentTheta = BASE_THETA_DEG;+ this._currentPhi = BASE_PHI_DEG;++ this._avatarRect = null;+ this._lastMoveAt = 0;+ this._rafId = null;+ this._tracking = false;+ this._attached = false;++ this._onPointerMove = this._onPointerMove.bind(this);+ this._onPointerLeave = this._onPointerLeave.bind(this);+ this._onResize = this._onResize.bind(this);+ this._tick = this._tick.bind(this);+ }++ attach() {+ if (this._attached) return;+ if (!this.modelViewer || !this.root || !this.avatar) return;++ // Skip entirely on reduced-motion and on no-hover (touch) devices.+ if (prefersReducedMotion()) return;+ if (!hasHover()) return;++ this._attached = true;+ this._refreshRect();++ this.root.addEventListener('pointermove', this._onPointerMove, { passive: true });+ this.root.addEventListener('pointerleave', this._onPointerLeave);+ window.addEventListener('resize', this._onResize, { passive: true });+ window.addEventListener('scroll', this._onResize, { passive: true });++ this._rafId = requestAnimationFrame(this._tick);+ }++ detach() {+ if (!this._attached) return;+ this._attached = false;++ this.root.removeEventListener('pointermove', this._onPointerMove);+ this.root.removeEventListener('pointerleave', this._onPointerLeave);+ window.removeEventListener('resize', this._onResize);+ window.removeEventListener('scroll', this._onResize);++ if (this._rafId != null) cancelAnimationFrame(this._rafId);+ this._rafId = null;++ // Hand control back to model-viewer so the hero doesn't freeze mid-turn.+ this._setAutoRotate(true);+ }++ _refreshRect() {+ this._avatarRect = this.avatar.getBoundingClientRect();+ }++ _onResize() {+ // rAF-coalesce rect reads; scroll/resize fire often.+ if (this._rectPending) return;+ this._rectPending = true;+ requestAnimationFrame(() => {+ this._rectPending = false;+ this._refreshRect();+ });+ }++ _onPointerMove(e) {+ // The rAF tick consumes these target values; the event handler itself+ // does no DOM writes and no orbit math beyond the normalization.+ const rect = this._avatarRect;+ if (!rect || rect.width === 0 || rect.height === 0) return;++ const cx = rect.left + rect.width / 2;+ const cy = rect.top + rect.height / 2;++ // Normalize to [-1, 1] relative to avatar's own half-extents so the+ // signal is strongest as the cursor approaches the avatar and clamps+ // at the edges of the hero.+ let nx = (e.clientX - cx) / (rect.width / 2);+ let ny = (e.clientY - cy) / (rect.height / 2);+ if (nx < -1) nx = -1;+ else if (nx > 1) nx = 1;+ if (ny < -1) ny = -1;+ else if (ny > 1) ny = 1;++ this._targetTheta = BASE_THETA_DEG + nx * THETA_RANGE_DEG;+ // Cursor moving down (ny > 0) should tilt the avatar's gaze down too,+ // which in model-viewer's polar convention means increasing phi.+ this._targetPhi = BASE_PHI_DEG + ny * PHI_RANGE_DEG;++ this._lastMoveAt = performance.now();++ if (!this._tracking) {+ this._tracking = true;+ this._setAutoRotate(false);+ }+ }++ _onPointerLeave() {+ // Ease back to base; the tick loop will flip auto-rotate back on once+ // we've settled near the default orbit.+ this._targetTheta = BASE_THETA_DEG;+ this._targetPhi = BASE_PHI_DEG;+ this._lastMoveAt = 0;+ }++ _tick() {+ if (!this._attached) return;++ this._currentTheta += (this._targetTheta - this._currentTheta) * SMOOTH;+ this._currentPhi += (this._targetPhi - this._currentPhi) * SMOOTH;++ if (this._tracking) {+ const orbit = `${this._currentTheta.toFixed(2)}deg ${this._currentPhi.toFixed(2)}deg ${BASE_RADIUS}`;+ this.modelViewer.setAttribute('camera-orbit', orbit);+ }++ const now = performance.now();+ const idleFor = this._lastMoveAt > 0 ? now - this._lastMoveAt : 0;+ const settled =+ Math.abs(this._currentTheta - BASE_THETA_DEG) < SETTLE_EPSILON &&+ Math.abs(this._currentPhi - BASE_PHI_DEG) < SETTLE_EPSILON;++ // Resume auto-rotate either after a quiet window (cursor still over the+ // hero but idle) or after pointerleave once the avatar has eased home.+ const shouldResume =+ this._lastMoveAt === 0+ ? settled // pointerleave: wait for ease-back to complete+ : idleFor > IDLE_MS; // idle: cursor still in hero but stopped+ if (this._tracking && shouldResume) {+ this._tracking = false;+ if (this._lastMoveAt === 0 && settled) {+ // Snap to the canonical orbit so auto-rotate picks up cleanly.+ this.modelViewer.setAttribute(+ 'camera-orbit',+ `${BASE_THETA_DEG}deg ${BASE_PHI_DEG}deg ${BASE_RADIUS}`,+ );+ this._currentTheta = BASE_THETA_DEG;+ this._currentPhi = BASE_PHI_DEG;+ }+ this._setAutoRotate(true);+ }++ this._rafId = requestAnimationFrame(this._tick);+ }++ _setAutoRotate(on) {+ if (!this.modelViewer) return;+ if (on) this.modelViewer.setAttribute('auto-rotate', '');+ else this.modelViewer.removeAttribute('auto-rotate');+ }+}diff --git a/publish/src/features/hero-pretext.js b/publish/src/features/hero-pretext.jsnew file mode 100644index 000000000..6f587ccd5--- /dev/null+++ b/publish/src/features/hero-pretext.js@@ -0,0 +1,297 @@+// Hero controller for /features — scaffolds submodules behind ?pretext=N flags.+//+// Respecting prefers-reduced-motion is the responsibility of any submodule that+// animates (gaze, dragon reflow). The scaffold itself is inert. The static wrap+// (flag >= 2) is a one-shot paint per resize, so it has nothing to gate.++const MOBILE_MQ = '(max-width: 768px)';+const RESIZE_DEBOUNCE_MS = 120;++export default class PretextHero {+ constructor(root, options = {}) {+ this.root = root;+ this.content = root?.querySelector('.hero-content') || null;+ this.title = root?.querySelector('.hero-title') || null;+ this.subtitle = root?.querySelector('.hero-subtitle') || null;+ this.avatar = root?.querySelector('.hero-avatar') || null;+ this.modelViewer = this.avatar?.querySelector('model-viewer') || null;++ this.flag = String(options.flag ?? '1');+ this.pretext = null;++ this._gaze = null;+ this._dragon = null;+ this._overlay = null;+ this._onResize = null;+ this._resizeT = null;+ this._rafToken = 0;+ this._ctx = null;+ }++ async init() {+ const mod = await import('@chenglou/pretext');+ this.pretext = mod;++ const flagNum = Number.parseInt(this.flag, 10);++ if (flagNum >= 2) {+ try {+ this.enableStaticWrap();+ } catch (err) {+ console.warn('[pretext-hero] static wrap failed:', err);+ }+ }++ // Gaze follows the cursor with subtle head rotation. Dragon mode moves+ // the avatar itself, so the two don't compose — flag 4 opts out of gaze.+ if (this.flag === '3') {+ try {+ const { HeroGaze } = await import('./hero-gaze.js');+ this._gaze = new HeroGaze(this);+ this._gaze.attach();+ } catch (err) {+ console.warn('[pretext-hero] gaze unavailable:', err);+ }+ }++ if (this.flag === '4') {+ try {+ const { HeroDragon } = await import('./hero-dragon.js');+ this._dragon = new HeroDragon(this);+ this._dragon.attach();+ } catch (err) {+ console.warn('[pretext-hero] dragon unavailable:', err);+ }+ }++ return this;+ }++ enableStaticWrap() {+ if (!this.content || !this.subtitle || !this.avatar || !this.pretext) return;++ // Keep the original subtitle accessible to screen readers even when+ // visually hidden via .pretext-active; the overlay is aria-hidden.+ this.subtitle.setAttribute('aria-hidden', 'false');++ this._overlay = document.createElement('div');+ this._overlay.className = 'hero-subtitle-pretext';+ this._overlay.setAttribute('aria-hidden', 'true');+ this.content.appendChild(this._overlay);++ const paint = () => {+ try {+ this._paintStaticWrap();+ } catch (err) {+ console.warn('[pretext-hero] paint failed:', err);+ this.root.classList.remove('pretext-active');+ }+ };++ const ready = document.fonts?.ready ?? Promise.resolve();+ ready.then(paint);++ this._onResize = () => {+ if (this._resizeT) clearTimeout(this._resizeT);+ this._resizeT = setTimeout(paint, RESIZE_DEBOUNCE_MS);+ };+ window.addEventListener('resize', this._onResize);+ }++ // One-shot layout pass. Reads geometry, then paints once via rAF — no mid-frame+ // writes, so resize doesn't thrash.+ _paintStaticWrap() {+ if (!this._overlay) return;++ if (window.matchMedia(MOBILE_MQ).matches) {+ this.root.classList.remove('pretext-active');+ this._overlay.replaceChildren();+ this._overlay.style.display = 'none';+ this._ctx = null;+ return;+ }+ this._overlay.style.display = '';++ const ctx = this._computeLayoutContext();+ if (!ctx) return;+ this._ctx = ctx;++ const { circleX, circleY, circleR } = this._avatarCircle(ctx);+ const { lines, contentHeight } = this._layoutLinesAroundCircle(+ ctx,+ circleX,+ circleY,+ circleR,+ );++ const token = ++this._rafToken;+ requestAnimationFrame(() => {+ if (token !== this._rafToken || !this._overlay) return;+ this._paintLines(ctx, lines, contentHeight);+ this.root.classList.add('pretext-active');+ });+ }++ // Reads rects + style once. Returned context is the input to+ // _layoutLinesAroundCircle, which is pure math and reusable per-frame+ // by dragon mode.+ _computeLayoutContext() {+ if (!this.content || !this.subtitle || !this.avatar || !this.pretext) return null;++ const contentRect = this.content.getBoundingClientRect();+ const subtitleRect = this.subtitle.getBoundingClientRect();+ const avatarRect = this.avatar.getBoundingClientRect();++ const style = getComputedStyle(this.subtitle);+ const font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;+ const fontSize = Number.parseFloat(style.fontSize);+ const lhRaw = style.lineHeight;+ const lineHeight = lhRaw === 'normal' ? fontSize * 1.5 : Number.parseFloat(lhRaw);++ const overlayLeft = subtitleRect.left - contentRect.left;+ const overlayTop = subtitleRect.top - contentRect.top;++ // Dragon mode stretches .hero-content to full hero width, so use the+ // content box as the outer bound and let the subtitle flow wider.+ const heroRect = this.root.getBoundingClientRect();+ const rightmostPage = this.root.classList.contains('hero--dragon')+ ? heroRect.right - 32+ : Math.max(avatarRect.right - 24, subtitleRect.right);+ const overlayWidth = Math.max(subtitleRect.width, rightmostPage - subtitleRect.left);++ const text = this.subtitle.textContent ?? '';+ const prepared = this.pretext.prepareWithSegments(text, font);++ const circleBaseR = (Math.min(avatarRect.width, avatarRect.height) / 2) * 0.92;++ return {+ font,+ lineHeight,+ prepared,+ text,+ overlayLeft,+ overlayTop,+ overlayWidth,+ subtitleRect,+ avatarRect,+ subtitleLeftPage: subtitleRect.left,+ subtitleTopPage: subtitleRect.top,+ circleBaseR,+ hPad: 14,+ maxLines: 32,+ };+ }++ _avatarCircle(ctx) {+ const r = ctx.avatarRect;+ return {+ circleX: r.left + r.width / 2 - ctx.subtitleLeftPage,+ circleY: r.top + r.height / 2 - ctx.subtitleTopPage,+ circleR: ctx.circleBaseR,+ };+ }++ _layoutLinesAroundCircle(ctx, circleX, circleY, circleR) {+ const { overlayWidth, lineHeight, hPad, prepared, maxLines } = ctx;+ const lines = [];+ let cursor = { segmentIndex: 0, graphemeIndex: 0 };+ let lineTop = 0;++ while (lines.length < maxLines) {+ const bandMid = lineTop + lineHeight / 2;+ const dy = bandMid - circleY;+ const effR = circleR + hPad;++ let slotWidth = overlayWidth;+ if (Math.abs(dy) < effR) {+ const dx = Math.sqrt(effR * effR - dy * dy);+ const blockedLeft = circleX - dx;+ if (blockedLeft < overlayWidth) {+ if (blockedLeft > 24) {+ slotWidth = blockedLeft;+ } else {+ lineTop += lineHeight;+ continue;+ }+ }+ }++ const line = this.pretext.layoutNextLine(prepared, cursor, slotWidth);+ if (line === null) break;++ lines.push({ y: lineTop, text: line.text });+ cursor = line.end;+ lineTop += lineHeight;+ }++ return { lines, contentHeight: lineTop };+ }++ _paintLines(ctx, lines, contentHeight) {+ if (!this._overlay) return;+ const overlay = this._overlay;+ overlay.style.left = `${ctx.overlayLeft}px`;+ overlay.style.top = `${ctx.overlayTop}px`;+ overlay.style.width = `${ctx.overlayWidth}px`;+ overlay.style.height = `${Math.max(contentHeight, ctx.subtitleRect.height)}px`;++ const frag = document.createDocumentFragment();+ for (const { y, text } of lines) {+ const span = document.createElement('span');+ span.className = 'hero-subtitle-pretext-line';+ span.style.top = `${y}px`;+ span.textContent = text;+ frag.appendChild(span);+ }+ overlay.replaceChildren(frag);+ }++ // Public for dragon mode — recompute rects after toggling .hero--dragon.+ recomputeContext() {+ this._ctx = this._computeLayoutContext();+ return this._ctx;+ }++ // Public for dragon mode — reflow using the current cached context and+ // the caller-supplied avatar circle (in overlay-local coordinates).+ // Returns the measured layout cost in ms for the auto-downgrade budget.+ paintCircle(circleX, circleY, circleR) {+ if (!this._ctx || !this._overlay) return 0;+ const t0 = performance.now();+ const { lines, contentHeight } = this._layoutLinesAroundCircle(+ this._ctx,+ circleX,+ circleY,+ circleR,+ );+ this._paintLines(this._ctx, lines, contentHeight);+ return performance.now() - t0;+ }++ dispose() {+ if (this._onResize) {+ window.removeEventListener('resize', this._onResize);+ this._onResize = null;+ }+ if (this._resizeT) {+ clearTimeout(this._resizeT);+ this._resizeT = null;+ }+ if (this._overlay) {+ this._overlay.remove();+ this._overlay = null;+ }+ this.subtitle?.removeAttribute('aria-hidden');+ this.root?.classList.remove('pretext-active');++ if (this._gaze) {+ this._gaze.detach();+ this._gaze = null;+ }+ if (this._dragon) {+ this._dragon.detach();+ this._dragon = null;+ }+ this._ctx = null;+ }+}diff --git a/publish/src/first-meet.css b/publish/src/first-meet.cssnew file mode 100644index 000000000..849622d70--- /dev/null+++ b/publish/src/first-meet.css@@ -0,0 +1,141 @@+/* first-meet.css — scoped under .first-meet-root */++.first-meet-root {+ position: fixed;+ inset: 0;+ z-index: 9900;+ pointer-events: none;+ font-family: system-ui, sans-serif;+}++/* ── Fade overlay ─────────────────────────────────────────────────────────── */++.fm-fade-overlay {+ position: absolute;+ inset: 0;+ background: #000;+ opacity: 1;+ transition: opacity 0.4s ease;+}++.fm-fade-overlay.fm-faded {+ opacity: 0;+}++/* ── Subtitle ─────────────────────────────────────────────────────────────── */++.fm-subtitle {+ position: absolute;+ bottom: 30%;+ left: 50%;+ transform: translateX(-50%);+ background: rgba(0, 0, 0, 0.55);+ color: #fff;+ font-size: clamp(18px, 3vw, 26px);+ font-weight: 500;+ letter-spacing: 0.01em;+ padding: 10px 24px;+ border-radius: 8px;+ white-space: nowrap;+ opacity: 0;+ transition: opacity 0.5s ease;+ backdrop-filter: blur(4px);+}++.fm-subtitle.fm-visible {+ opacity: 1;+}++/* ── Buttons ──────────────────────────────────────────────────────────────── */++.fm-actions {+ position: absolute;+ bottom: 18%;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ gap: 12px;+ opacity: 0;+ transition: opacity 0.45s ease;+ pointer-events: none;+}++.fm-actions.fm-visible {+ opacity: 1;+ pointer-events: auto;+}++.fm-btn {+ padding: 11px 28px;+ border-radius: 8px;+ font-size: 15px;+ font-weight: 600;+ cursor: pointer;+ border: none;+ transition:+ background 0.15s,+ transform 0.1s;+}++.fm-btn:active {+ transform: scale(0.96);+}++.fm-btn-share {+ background: #fff;+ color: #111;+}++.fm-btn-share:hover {+ background: #e8e8e8;+}++.fm-btn-continue {+ background: #3d7eff;+ color: #fff;+}++.fm-btn-continue:hover {+ background: #2d6fee;+}++/* ── Confetti ─────────────────────────────────────────────────────────────── */++.fm-confetti-piece {+ position: absolute;+ top: -20px;+ border-radius: 2px;+ pointer-events: none;+ animation: fm-fall linear forwards;+}++@keyframes fm-fall {+ 0% {+ transform: translateY(0) rotate(0deg);+ opacity: 1;+ }+ 70% {+ opacity: 1;+ }+ 100% {+ transform: translateY(110vh) rotate(720deg);+ opacity: 0;+ }+}++/* ── Reduced motion overrides ─────────────────────────────────────────────── */++@media (prefers-reduced-motion: reduce) {+ .fm-fade-overlay {+ transition: none;+ }+ .fm-subtitle {+ transition: none;+ }+ .fm-actions {+ transition: none;+ }+ .fm-confetti-piece {+ display: none;+ }+}diff --git a/publish/src/first-meet.js b/publish/src/first-meet.jsnew file mode 100644index 000000000..d0e5dc8c1--- /dev/null+++ b/publish/src/first-meet.js@@ -0,0 +1,195 @@+/**+ * playFirstMeet — first-encounter celebration sequence for a newly generated avatar.+ *+ * @param {object} opts+ * @param {object} opts.viewer — SceneController / AgentAvatar (duck-typed: .playClip(name) OR .mixer + .animations)+ * @param {{ id: string, name: string, slug: string }} opts.agent+ * @param {() => void} opts.onShare — called when user clicks "Share"+ * @param {() => void} opts.onContinue — called when user clicks "Continue"+ * @returns {Promise<void>} resolves when user clicks either button+ */+export async function playFirstMeet({ viewer, agent, onShare, onContinue }) {+ const reducedMotion =+ typeof window !== 'undefined' &&+ window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;++ // Inject stylesheet once+ if (!document.querySelector('link[data-fm-css]')) {+ const link = document.createElement('link');+ link.rel = 'stylesheet';+ link.href = new URL('./first-meet.css', import.meta.url).href;+ link.dataset.fmCss = '1';+ document.head.appendChild(link);+ }++ // Build root overlay+ const root = document.createElement('div');+ root.className = 'first-meet-root';++ // Fade overlay (black → transparent)+ const overlay = document.createElement('div');+ overlay.className = 'fm-fade-overlay';++ // Subtitle+ const subtitle = document.createElement('div');+ subtitle.className = 'fm-subtitle';+ subtitle.textContent = `Hello, I'm ${agent?.name ?? 'your agent'}.`;++ // Action buttons+ const actions = document.createElement('div');+ actions.className = 'fm-actions';++ const btnShare = document.createElement('button');+ btnShare.className = 'fm-btn fm-btn-share';+ btnShare.textContent = 'Share';++ const btnContinue = document.createElement('button');+ btnContinue.className = 'fm-btn fm-btn-continue';+ btnContinue.textContent = 'Continue';++ actions.appendChild(btnShare);+ actions.appendChild(btnContinue);+ root.appendChild(overlay);+ root.appendChild(subtitle);+ root.appendChild(actions);+ document.body.appendChild(root);++ // ── Helpers ───────────────────────────────────────────────────────────────++ function delay(ms) {+ return new Promise((res) => setTimeout(res, ms));+ }++ // Try to play a wave gesture on the viewer (duck-typed).+ // Order probed:+ // 1. viewer.playClip('Wave') — exact name+ // 2. viewer.playClip('wave') — lowercase+ // 3. viewer.playAnimationByHint?.('wave') — partial name search (SceneController)+ // 4. Scripted bone tilt via viewer.mixer + content skeleton+ // — bones probed: 'mixamorigRightHand', 'RightHand', 'mixamorigRightArm', 'RightArm'+ function tryWave() {+ if (reducedMotion) return;++ // Method 1 & 2: direct clip by name+ if (typeof viewer?.playClip === 'function') {+ if (viewer.playClip('Wave')) return;+ if (viewer.playClip('wave')) return;+ }++ // Method 3: SceneController hint search+ if (typeof viewer?.playAnimationByHint === 'function') {+ if (viewer.playAnimationByHint('wave')) return;+ if (viewer.playAnimationByHint('Wave')) return;+ }++ // Method 4: scripted bone animation if mixer exists+ const mixer = viewer?.mixer;+ const root3d = viewer?.content ?? viewer?.scene;+ if (!mixer || !root3d) return;++ const BONE_NAMES = ['mixamorigRightHand', 'RightHand', 'mixamorigRightArm', 'RightArm'];+ let targetBone = null;+ root3d.traverse?.((obj) => {+ if (targetBone) return;+ if (obj.isBone && BONE_NAMES.includes(obj.name)) targetBone = obj;+ });+ if (!targetBone) return;++ // Simple scripted tilt: raise then return over 1.2s using rAF+ const origZ = targetBone.rotation.z;+ const origX = targetBone.rotation.x;+ const RAISE_Z = 1.2; // radians+ const RAISE_X = -0.5;+ const DURATION = 1200; // ms+ let start = null;++ function animateBone(ts) {+ if (!start) start = ts;+ const t = Math.min((ts - start) / DURATION, 1);+ // Ease in-out cubic+ const ease = t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;+ const wave = Math.sin(t * Math.PI); // arc: 0 → 1 → 0+ targetBone.rotation.z = origZ + RAISE_Z * wave * ease;+ targetBone.rotation.x = origX + RAISE_X * wave * ease;+ if (t < 1) requestAnimationFrame(animateBone);+ else {+ targetBone.rotation.z = origZ;+ targetBone.rotation.x = origX;+ }+ }+ requestAnimationFrame(animateBone);+ }++ // Spawn CSS confetti: 40–60 spans, random hue/size/rotation/position/duration+ function spawnConfetti() {+ if (reducedMotion) return;+ const count = 40 + Math.floor(Math.random() * 21);+ const pieces = [];+ for (let i = 0; i < count; i++) {+ const span = document.createElement('span');+ span.className = 'fm-confetti-piece';+ const hue = Math.floor(Math.random() * 360);+ const w = 6 + Math.random() * 8;+ const h = 10 + Math.random() * 10;+ const left = Math.random() * 100;+ const duration = 1.4 + Math.random() * 0.8;+ const delay_ = Math.random() * 0.4;+ const rot = Math.floor(Math.random() * 360);+ span.style.cssText = `+ left: ${left}%;+ width: ${w}px;+ height: ${h}px;+ background: hsl(${hue},80%,60%);+ transform: rotate(${rot}deg);+ animation-duration: ${duration}s;+ animation-delay: ${delay_}s;+ `.replace(/\s+/g, ' ');+ root.appendChild(span);+ pieces.push(span);+ }+ // Clean up after 2s+ setTimeout(() => pieces.forEach((p) => p.remove()), 2000);+ }++ // ── Sequence ──────────────────────────────────────────────────────────────++ // t=0.0 — fade overlay out (scene reveal)+ await delay(0);+ requestAnimationFrame(() => overlay.classList.add('fm-faded'));++ // t=0.2 — wave+ await delay(200);+ tryWave();++ // t=0.6 — subtitle fades in+ await delay(400);+ subtitle.classList.add('fm-visible');++ // t=1.4 — confetti burst+ await delay(800);+ spawnConfetti();++ // t=2.2 — buttons fade in+ await delay(800);+ actions.classList.add('fm-visible');++ // ── Wait for user ─────────────────────────────────────────────────────────++ await new Promise((resolve) => {+ function cleanup() {+ root.remove();+ }++ btnShare.addEventListener('click', () => {+ cleanup();+ onShare?.();+ resolve();+ });++ btnContinue.addEventListener('click', () => {+ cleanup();+ onContinue?.();+ resolve();+ });+ });+}diff --git a/publish/src/home-act2-viewer.js b/publish/src/home-act2-viewer.jsnew file mode 100644index 000000000..a781d83cc--- /dev/null+++ b/publish/src/home-act2-viewer.js@@ -0,0 +1,319 @@+/**+ * Three.js viewer for the homepage Act 2 — same trick as /app:+ * loads any GLB, fetches the project's animation manifest+ * (/animations/manifest.json), lazy-loads clips on first play, and+ * retargets them onto whatever skeleton is loaded.+ *+ * Public API (mounted on window):+ * const v = new Act2Viewer(canvas);+ * v.onClipsReady = (defs) => { /* build chips */ /* };+ * await v.loadModel('/avatars/cz.glb');+ * v.playClip('dance');+ */+import {+ WebGLRenderer,+ Scene,+ PerspectiveCamera,+ AnimationMixer,+ AnimationClip,+ Box3,+ Vector3,+ Clock,+ HemisphereLight,+ DirectionalLight,+ ACESFilmicToneMapping,+ SRGBColorSpace,+ PMREMGenerator,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++const CROSSFADE = 0.35;++export class Act2Viewer {+ constructor(canvas, { fov = 14 } = {}) {+ this.canvas = canvas;+ this.renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });+ this.renderer.toneMapping = ACESFilmicToneMapping;+ this.renderer.toneMappingExposure = 1.0;+ this.renderer.outputColorSpace = SRGBColorSpace;++ this.scene = new Scene();+ this.camera = new PerspectiveCamera(fov, 1, 0.1, 100);+ this.camera.position.set(0, 1.0, 22);++ /* neutral environment (matches model-viewer's environment-image="neutral") */+ const pmrem = new PMREMGenerator(this.renderer);+ this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++ this.scene.add(new HemisphereLight(0xffffff, 0x444466, 0.8));+ const sun = new DirectionalLight(0xffffff, 1.2);+ sun.position.set(4, 8, 6);+ this.scene.add(sun);++ /** @type {Map<string, AnimationClip>} */+ this.clips = new Map();+ /** @type {THREE.AnimationAction|null} */+ this.currentAction = null;+ this.mixer = null;+ this.model = null;++ /** @type {Array<{name:string,url:string,label:string,icon:string,loop?:boolean}>} */+ this._manifest = [];+ this._manifestPromise = null;++ this._loader = new GLTFLoader();+ this._clock = new Clock();+ this._modelYaw = 0;+ this._modelFocusY = 1.0;+ this._focusX = 0;+ this._externalOrbit = false;++ /** Optional callback when the chip list changes (manifest + GLB-baked combined). */+ this.onClipsReady = null;++ this._resize();+ const ro = new ResizeObserver(() => this._resize());+ ro.observe(canvas);++ this._tick = this._tick.bind(this);+ requestAnimationFrame(this._tick);+ }++ _resize() {+ const dpr = Math.min(devicePixelRatio || 1, 2);+ const w = this.canvas.clientWidth;+ const h = this.canvas.clientHeight;+ if (!w || !h) return;+ this.renderer.setPixelRatio(dpr);+ this.renderer.setSize(w, h, false);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ }++ _tick() {+ const dt = this._clock.getDelta();+ if (this.mixer) this.mixer.update(dt);+ if (this.model && !this._externalOrbit) {+ this._modelYaw += dt * 0.18;+ this.model.rotation.y = this._modelYaw;+ }+ this.renderer.render(this.scene, this.camera);+ requestAnimationFrame(this._tick);+ }++ async _loadManifest() {+ if (this._manifest.length) return this._manifest;+ if (this._manifestPromise) return this._manifestPromise;+ this._manifestPromise = fetch('/animations/manifest.json')+ .then((r) => r.json())+ .then((data) => {+ const arr = Array.isArray(data) ? data : data.animations || [];+ this._manifest = arr;+ return arr;+ })+ .catch(() => {+ this._manifest = [];+ return [];+ });+ return this._manifestPromise;+ }++ /** Returns combined: GLB-baked clips + project animation manifest, deduped by name.+ * When the model ships its own rich animation set (robot, etc.) those are shown+ * exclusively — manifest clips are Mixamo-retargeted and won't work on a different skeleton.+ */+ listAvailableClips() {+ const IDLE_RE = /idle/i;+ const glbGoodNames = [...this.clips.keys()].filter((n) => !IDLE_RE.test(n));++ /* Model has its own animations — skip manifest entirely */+ if (glbGoodNames.length >= 3) {+ return [...this.clips.keys()].map((name) => ({+ name,+ label: name,+ icon: '✨',+ loop: true,+ source: 'glb',+ }));+ }++ const out = [];+ const seen = new Set();+ /* manifest first (humanoid / Mixamo models like CZ) */+ for (const def of this._manifest) {+ if (!seen.has(def.name)) {+ out.push({ ...def, source: 'manifest' });+ seen.add(def.name);+ }+ }+ /* then any extra GLB clips not already in manifest */+ for (const name of this.clips.keys()) {+ if (seen.has(name)) continue;+ seen.add(name);+ out.push({ name, label: name, icon: '✨', loop: true, source: 'glb' });+ }+ return out;+ }++ async _fetchClip(url) {+ const r = await fetch(url);+ if (!r.ok) throw new Error('clip ' + url + ' ' + r.status);+ const json = await r.json();+ return AnimationClip.parse(json);+ }++ async loadModel(url, { autoPlay = true } = {}) {+ /* swap out previous model */+ if (this.model) {+ if (this.mixer) this.mixer.stopAllAction();+ this.scene.remove(this.model);+ this.model = null;+ this.mixer = null;+ this.currentAction = null;+ this.clips.clear();+ }++ const gltf = await this._loader.loadAsync(url);+ this.model = gltf.scene;+ this.scene.add(this.model);++ /* center horizontally + plant feet on ground */+ const box = new Box3().setFromObject(this.model);+ const size = box.getSize(new Vector3());+ const center = box.getCenter(new Vector3());+ this.model.position.x -= center.x;+ this.model.position.z -= center.z;+ this.model.position.y -= box.min.y;++ /* fit camera to model height with a comfortable framing */+ const targetHeight = size.y;+ const dist = (targetHeight / 2) / Math.tan((this.camera.fov / 2) * (Math.PI / 180));+ this._modelFocusY = targetHeight * 0.55;+ this._externalOrbit = false;+ this.camera.position.set(0, this._modelFocusY, dist * 1.2);+ this.camera.lookAt(0, this._modelFocusY, 0);++ this.mixer = new AnimationMixer(this.model);++ /* collect node names available on this skeleton so we can drop+ * tracks that target bones the current model doesn't have — otherwise+ * three.js floods the console with "No target node found" warnings+ * for every mismatched bone, every frame the clip plays. */+ const knownNodes = new Set();+ this.model.traverse((n) => {+ if (n.name) knownNodes.add(n.name);+ });++ /* register baked-in clips, filtering tracks to those that bind */+ for (const clip of gltf.animations || []) {+ const tracks = clip.tracks.filter((t) => {+ const nodeName = t.name.split('.')[0];+ return knownNodes.has(nodeName);+ });+ if (tracks.length === 0) continue;+ this.clips.set(clip.name, new AnimationClip(clip.name, clip.duration, tracks));+ }++ /* ensure manifest is fetched */+ await this._loadManifest();++ /* fire chip rebuild */+ if (typeof this.onClipsReady === 'function') {+ this.onClipsReady(this.listAvailableClips());+ }++ /* auto-play first clip unless caller wants to handle it */+ if (autoPlay) {+ const startName = this._pickStartName();+ if (startName) await this.playClip(startName);+ }++ return this.model;+ }++ _pickStartName() {+ const SKIP_RE = /idle|silly/i;+ const all = this.listAvailableClips();+ /* When model uses its own GLB clips, pick a lively one from those */+ if (all.length && all[0].source === 'glb') {+ const PREFERRED = ['Dance', 'Wave', 'Jump', 'Punch', 'Running', 'ThumbsUp'];+ for (const p of PREFERRED) {+ const match = all.find((c) => c.name === p);+ if (match) return match.name;+ }+ return all.find((c) => !SKIP_RE.test(c.name))?.name || all[0]?.name || null;+ }+ /* Humanoid / manifest models */+ for (const preferred of ['dance', 'rumba', 'capoeira', 'wave', 'thriller']) {+ const match = all.find((c) => c.name === preferred);+ if (match) return match.name;+ }+ return all.find((c) => !SKIP_RE.test(c.name))?.name || all[0]?.name || null;+ }++ async playClip(name) {+ if (!this.mixer) return;+ let clip = this.clips.get(name);++ if (!clip) {+ /* lazy-load from manifest */+ const def = this._manifest.find((d) => d.name === name);+ if (!def) return;+ clip = await this._fetchClip(def.url);+ const knownNodes = new Set();+ this.model?.traverse((n) => {+ if (n.name) knownNodes.add(n.name);+ });+ const tracks = clip.tracks.filter((t) =>+ knownNodes.has(t.name.split('.')[0]),+ );+ clip = new AnimationClip(clip.name, clip.duration, tracks);+ this.clips.set(name, clip);+ }++ const action = this.mixer.clipAction(clip);+ action.enabled = true;+ action.setLoop(undefined, Infinity); /* default loop */+ if (this.currentAction && this.currentAction !== action) {+ action.reset().fadeIn(CROSSFADE).play();+ this.currentAction.fadeOut(CROSSFADE);+ } else {+ action.reset().play();+ }+ this.currentAction = action;+ }++ /**+ * Orbit the camera around the model using polar coordinates matching model-viewer's+ * camera-orbit convention: theta = azimuth (deg), phi = elevation from top (deg),+ * radius = distance (m). Calling this disables internal auto-rotate.+ */+ setOrbit(thetaDeg, phiDeg, radius) {+ this._externalOrbit = true;+ const theta = thetaDeg * (Math.PI / 180);+ const phi = phiDeg * (Math.PI / 180);+ const sinPhi = Math.sin(phi);+ const cosPhi = Math.cos(phi);+ const fx = this._focusX;+ this.camera.position.set(+ fx + radius * sinPhi * Math.sin(theta),+ this._modelFocusY + radius * cosPhi,+ radius * sinPhi * Math.cos(theta),+ );+ this.camera.lookAt(fx, this._modelFocusY, 0);+ }++ setExposure(v) {+ this.renderer.toneMappingExposure = v;+ }++ zoom(distance) {+ const cur = this.camera.position.length();+ this.camera.position.normalize().multiplyScalar(distance);+ this.camera.lookAt(0, this.camera.position.y * 0.6, 0);+ }+}++/* expose on window so the inline home.html script can use it */+window.Act2Viewer = Act2Viewer;diff --git a/publish/src/idle-animation.js b/publish/src/idle-animation.jsnew file mode 100644index 000000000..24f22eff2--- /dev/null+++ b/publish/src/idle-animation.js@@ -0,0 +1,369 @@+/**+ * Idle Animation Loop+ * -------------------+ * Four additive ambient motion channels for a static avatar:+ * 1. Breathing — spine bone X micro-rotation (~4s period); morph fallback if no bones.+ * 2. Saccades — small eye/head yaw+pitch offsets, critically damped spring.+ * 3. Blink — eyelid morph close/hold/open on a random [2.5–6s] interval.+ * 4. Weight shift — hip bone yaw drift (~8s period), per-avatar seeded phase.+ *+ * All channels are additive — empathy layer wins. Pure dt-driven; no setTimeout/setInterval.+ * No allocations in update() — all scratch buffers are pre-allocated instance fields.+ */++import { ACTION_TYPES } from './agent-protocol.js';++const DEG2RAD = Math.PI / 180;+const TWO_PI = Math.PI * 2;++/** mulberry32 PRNG — deterministic, seeded. Returns a function yielding [0, 1). */+function mulberry32(seed) {+ return () => {+ seed |= 0;+ seed = (seed + 0x6d2b79f5) | 0;+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 0x100000000;+ };+}++/** djb2-style string → uint32, used for PRNG seeding. */+function hashStr(str) {+ let h = 0x811c9dc5;+ for (let i = 0; i < str.length; i++) {+ h ^= str.charCodeAt(i);+ h = Math.imul(h, 0x01000193) >>> 0;+ }+ return h;+}++export class IdleAnimation {+ /**+ * @param {object} opts+ * @param {() => import('three').Object3D | null} opts.getRoot+ * Getter for the live avatar root — called each frame, handles late-loaded content.+ * @param {import('./agent-protocol.js').AgentProtocol} opts.protocol+ * @param {string} [opts.seed] Stable per-avatar seed (agent id); prevents multi-avatar sync.+ * @param {() => Record<string,number>} [opts.getMorphCurrent]+ * Returns the empathy layer's live morph weight map (avatar._morphCurrent).+ * @param {Partial<{breathing:boolean,saccade:boolean,blink:boolean,weightShift:boolean}>} [opts.channels]+ */+ constructor(opts) {+ this._getRoot = opts.getRoot;+ this._protocol = opts.protocol;+ this._getMorphCurrent = opts.getMorphCurrent ?? null;++ this._channels = {+ breathing: true,+ saccade: true,+ blink: true,+ weightShift: true,+ ...opts.channels,+ };++ const seed = opts.seed ?? 'default';+ this._rand = mulberry32(hashStr(seed));++ // Per-avatar phase offsets — desync multiple instances on the same page.+ this._breathPhase = this._rand() * TWO_PI;+ this._weightPhase = this._rand() * TWO_PI;++ // ── Lazy bone / morph discovery ───────────────────────────────────────────+ this._scannedRoot = null;+ this._headBone = null;+ this._spineBone = null;+ this._hipBone = null;+ this._spineRestX = 0;+ this._hipRestY = 0;++ /**+ * Pre-built morph index cache per mesh — eliminates dict lookup in hot path.+ * @type {Array<{mesh:import('three').Mesh,blinkL:number,blinkR:number,browInner:number,mouthOpen:number}>}+ */+ this._morphMeshes = [];++ // ── Spring scratch buffer — Float32Array avoids GC pressure ─────────────+ this._springBuf = new Float32Array(2);++ // ── Micro-saccade state ───────────────────────────────────────────────────+ this._saccYaw = 0;+ this._saccYawVel = 0;+ this._saccPitch = 0;+ this._saccPitchVel = 0;+ this._saccTargetYaw = 0;+ this._saccTargetPitch = 0;+ this._saccDwell = this._randRange(0.8, 2.4);+ this._saccTimer = 0;+ this._saccPauseTimer = 0; // counts down after look-at; saccade pauses while > 0++ // ── Blink state ───────────────────────────────────────────────────────────+ this._blinkCountdown = this._randRange(2.5, 6.0);+ this._blinkPhase = 'idle'; // 'idle' | 'close' | 'hold' | 'open'+ this._blinkPhaseT = 0;+ this._blinkWeight = 0;+ this._blinkPauseTimer = 0; // counts down after speak; blink start paused while > 0++ // ── Protocol listeners ────────────────────────────────────────────────────+ this._onSpeak = () => {+ this._blinkPauseTimer = 1.0;+ };+ this._onLookAt = () => {+ this._saccPauseTimer = 0.5;+ };+ this._protocol.on(ACTION_TYPES.SPEAK, this._onSpeak);+ this._protocol.on(ACTION_TYPES.LOOK_AT, this._onLookAt);+ }++ // ── Public API ───────────────────────────────────────────────────────────────++ /**+ * Call every frame with elapsed seconds since the last tick.+ * @param {number} dt+ */+ update(dt) {+ this._ensureInit();+ if (this._channels.breathing) this._tickBreathing(dt);+ if (this._channels.saccade) this._tickSaccade(dt);+ if (this._channels.blink) this._tickBlink(dt);+ if (this._channels.weightShift) this._tickWeightShift(dt);+ }++ /**+ * Toggle channels at runtime. Partial — unmentioned channels unchanged.+ * @param {Partial<{breathing:boolean,saccade:boolean,blink:boolean,weightShift:boolean}>} partial+ */+ setChannels(partial) {+ Object.assign(this._channels, partial);+ }++ /** Remove protocol listeners. */+ dispose() {+ this._protocol.off(ACTION_TYPES.SPEAK, this._onSpeak);+ this._protocol.off(ACTION_TYPES.LOOK_AT, this._onLookAt);+ }++ // ── Lazy init ────────────────────────────────────────────────────────────────++ _ensureInit() {+ const root = this._getRoot?.();+ if (!root || root === this._scannedRoot) return;+ this._scannedRoot = root;+ this._headBone = null;+ this._spineBone = null;+ this._hipBone = null;+ this._morphMeshes = [];++ let headCandidate = null, neckCandidate = null;+ root.traverse((node) => {+ if (node.isBone) {+ // Strip mixamorig prefix and any leading namespace so 'mixamorig:Head' → 'head'+ const canon = node.name+ .replace(/^mixamorig:?/i, '')+ .replace(/^[A-Za-z0-9]+[_:]/, '')+ .toLowerCase();++ if (!headCandidate && canon === 'head') headCandidate = node;+ else if (!neckCandidate && canon === 'neck') neckCandidate = node;++ if (+ !this._spineBone &&+ (canon === 'spine' ||+ canon === 'spine1' ||+ canon === 'spine2' ||+ canon === 'chest' ||+ canon === 'upperchest')+ ) {+ this._spineBone = node;+ this._spineRestX = node.rotation.x;+ }++ if (+ !this._hipBone &&+ (canon === 'hips' || canon === 'hip' || canon === 'pelvis' || canon === 'root')+ ) {+ this._hipBone = node;+ this._hipRestY = node.rotation.y;+ }+ }++ if (node.isMesh && node.morphTargetDictionary && node.morphTargetInfluences) {+ const d = node.morphTargetDictionary;+ this._morphMeshes.push({+ mesh: node,+ blinkL: d.eyeBlinkLeft ?? -1,+ blinkR: d.eyeBlinkRight ?? -1,+ browInner: d.browInnerUp ?? -1,+ mouthOpen: d.mouthOpen ?? -1,+ });+ }+ });++ // Prefer head over neck — neck is visited first in DFS but adding rotation+ // at neck level cascades into head, fighting the empathy layer's head-only control.+ this._headBone = headCandidate || neckCandidate;++ if (+ !this._headBone &&+ !this._spineBone &&+ !this._hipBone &&+ this._morphMeshes.length === 0+ ) {+ console.log(+ '[IdleAnimation] No bones or morph targets found on avatar root — channels will be no-ops.',+ );+ }+ }++ // ── Channel 1: Breathing ─────────────────────────────────────────────────────++ _tickBreathing(dt) {+ this._breathPhase = (this._breathPhase + (dt * TWO_PI) / 4.0) % TWO_PI;+ const signal = Math.sin(this._breathPhase);++ if (this._spineBone) {+ // Preferred path: subtle chest expansion via spine X rotation (±0.3°).+ this._spineBone.rotation.x = this._spineRestX + signal * 0.3 * DEG2RAD;+ return;+ }++ // Morph fallback when no spine bone — micro-modulate brow + mouthOpen.+ const mc = this._getMorphCurrent?.();+ const empMouthOpen = mc?.mouthOpen ?? 0;+ const amp = 0.005; // 0.5% amplitude — imperceptible except as "aliveness"++ for (let i = 0; i < this._morphMeshes.length; i++) {+ const m = this._morphMeshes[i];+ if (m.browInner >= 0) {+ m.mesh.morphTargetInfluences[m.browInner] = Math.max(+ 0,+ Math.min(1, m.mesh.morphTargetInfluences[m.browInner] + signal * amp),+ );+ }+ // Defer to empathy layer when it is actively using mouthOpen.+ if (m.mouthOpen >= 0 && empMouthOpen <= 0.2) {+ m.mesh.morphTargetInfluences[m.mouthOpen] = Math.max(+ 0,+ Math.min(1, m.mesh.morphTargetInfluences[m.mouthOpen] + signal * amp),+ );+ }+ }+ }++ // ── Channel 2: Micro-saccades ────────────────────────────────────────────────++ _tickSaccade(dt) {+ if (!this._headBone) return;++ if (this._saccPauseTimer > 0) {+ this._saccPauseTimer -= dt;+ return;+ }++ // Dwell timer — pick a new random target when the dwell expires.+ this._saccTimer += dt;+ if (this._saccTimer >= this._saccDwell) {+ this._saccTimer = 0;+ this._saccDwell = this._randRange(0.8, 2.4);+ this._saccTargetYaw = (this._rand() * 2 - 1) * 1.5 * DEG2RAD;+ this._saccTargetPitch = (this._rand() * 2 - 1) * 1.5 * DEG2RAD;+ }++ // Critically damped spring (omega=5) — smooth approach, no overshoot.+ this._springStep(this._saccYaw, this._saccYawVel, this._saccTargetYaw, 5, dt);+ this._saccYaw = this._springBuf[0];+ this._saccYawVel = this._springBuf[1];++ this._springStep(this._saccPitch, this._saccPitchVel, this._saccTargetPitch, 5, dt);+ this._saccPitch = this._springBuf[0];+ this._saccPitchVel = this._springBuf[1];++ // Additive — applied after the empathy layer sets head rotation this frame.+ this._headBone.rotation.y += this._saccYaw;+ this._headBone.rotation.x += this._saccPitch;+ }++ // ── Channel 3: Blink ─────────────────────────────────────────────────────────++ _tickBlink(dt) {+ if (this._blinkPauseTimer > 0) this._blinkPauseTimer -= dt;+ const paused = this._blinkPauseTimer > 0;++ switch (this._blinkPhase) {+ case 'idle':+ if (!paused) {+ this._blinkCountdown -= dt;+ if (this._blinkCountdown <= 0) {+ this._blinkPhase = 'close';+ this._blinkPhaseT = 0;+ this._blinkCountdown = this._randRange(2.5, 6.0);+ }+ }+ return; // nothing to write while idle++ case 'close':+ this._blinkPhaseT += dt;+ this._blinkWeight = Math.min(1, this._blinkPhaseT / 0.08); // 80ms close+ if (this._blinkPhaseT >= 0.08) {+ this._blinkPhase = 'hold';+ this._blinkPhaseT = 0;+ this._blinkWeight = 1;+ }+ break;++ case 'hold':+ this._blinkPhaseT += dt;+ if (this._blinkPhaseT >= 0.04) {+ // 40ms hold+ this._blinkPhase = 'open';+ this._blinkPhaseT = 0;+ }+ break;++ case 'open':+ this._blinkPhaseT += dt;+ this._blinkWeight = Math.max(0, 1 - this._blinkPhaseT / 0.12); // 120ms open+ if (this._blinkPhaseT >= 0.12) {+ this._blinkPhase = 'idle';+ this._blinkWeight = 0;+ }+ break;+ }++ for (let i = 0; i < this._morphMeshes.length; i++) {+ const m = this._morphMeshes[i];+ if (m.blinkL >= 0) m.mesh.morphTargetInfluences[m.blinkL] = this._blinkWeight;+ if (m.blinkR >= 0) m.mesh.morphTargetInfluences[m.blinkR] = this._blinkWeight;+ }+ }++ // ── Channel 4: Weight shift ──────────────────────────────────────────────────++ _tickWeightShift(dt) {+ if (!this._hipBone) return;+ this._weightPhase = (this._weightPhase + (dt * TWO_PI) / 8.0) % TWO_PI;+ this._hipBone.rotation.y = this._hipRestY + Math.sin(this._weightPhase) * 0.5 * DEG2RAD;+ }++ // ── Utility ──────────────────────────────────────────────────────────────────++ /**+ * Critically damped spring step — closed-form, no Euler drift.+ * Writes [newPos, newVel] into this._springBuf (zero allocation).+ * @param {number} pos Current position+ * @param {number} vel Current velocity+ * @param {number} target Rest position+ * @param {number} omega Natural frequency (stiffness^0.5)+ * @param {number} dt+ */+ _springStep(pos, vel, target, omega, dt) {+ const x0 = pos - target;+ const b = vel + omega * x0;+ const decay = Math.exp(-omega * dt);+ this._springBuf[0] = target + (x0 + b * dt) * decay;+ this._springBuf[1] = (b - omega * (x0 + b * dt)) * decay;+ }++ _randRange(min, max) {+ return min + this._rand() * (max - min);+ }+}diff --git a/publish/src/ipfs.js b/publish/src/ipfs.jsnew file mode 100644index 000000000..42187a228--- /dev/null+++ b/publish/src/ipfs.js@@ -0,0 +1,74 @@+/**+ * IPFS / Arweave URI resolver.+ *+ * Translates decentralised storage URIs into HTTPS gateway URLs+ * so the Three.js loader can fetch them normally.+ *+ * ipfs://QmXyz... → https://dweb.link/ipfs/QmXyz...+ * ipfs://bafkreiXyz... → https://dweb.link/ipfs/bafkreiXyz...+ * ar://txId → https://arweave.net/txId+ */++const IPFS_GATEWAYS = [+ 'https://dweb.link/ipfs/',+ 'https://cloudflare-ipfs.com/ipfs/',+ 'https://ipfs.io/ipfs/',+];++const AR_GATEWAY = 'https://arweave.net/';++/**+ * Returns true when the URL uses a decentralised storage scheme.+ * @param {string} url+ * @returns {boolean}+ */+export function isDecentralizedURI(url) {+ return /^(ipfs|ar):\/\//i.test(url);+}++/**+ * Resolve an ipfs:// or ar:// URI to an HTTPS gateway URL.+ * For regular URLs the input is returned unchanged.+ *+ * @param {string} uri+ * @param {number} [gatewayIndex=0] Which IPFS gateway to use (for fallback).+ * @returns {string}+ */+export function resolveURI(uri, gatewayIndex = 0) {+ if (!uri) return uri;++ // ipfs://CID or ipfs://CID/path+ const ipfsMatch = uri.match(/^ipfs:\/\/(.+)$/i);+ if (ipfsMatch) {+ const gw = IPFS_GATEWAYS[gatewayIndex % IPFS_GATEWAYS.length];+ return gw + ipfsMatch[1];+ }++ // ar://txId+ const arMatch = uri.match(/^ar:\/\/(.+)$/i);+ if (arMatch) {+ return AR_GATEWAY + arMatch[1];+ }++ return uri;+}++/**+ * Try to fetch from the primary gateway; on failure, cycle through fallbacks.+ *+ * @param {string} ipfsURI An ipfs:// URI.+ * @returns {Promise<Response>}+ */+export async function fetchWithFallback(ipfsURI) {+ let lastError;+ for (let i = 0; i < IPFS_GATEWAYS.length; i++) {+ const url = resolveURI(ipfsURI, i);+ try {+ const res = await fetch(url);+ if (res.ok) return res;+ } catch (err) {+ lastError = err;+ }+ }+ throw lastError || new Error('All IPFS gateways failed for ' + ipfsURI);+}diff --git a/publish/src/lib.js b/publish/src/lib.jsnew file mode 100644index 000000000..35837a55c--- /dev/null+++ b/publish/src/lib.js@@ -0,0 +1,22 @@+// Library entry — imported by the CDN bundle <script type="module" src="agent-3d.js">.+// Registers the custom element and exposes public API classes for programmatic use.++import { Agent3DElement } from './element.js';+import { AgentStageElement } from './stage-element.js';++export { Agent3DElement, AgentStageElement };+export { Viewer } from './viewer.js';+export { Runtime } from './runtime/index.js';+export { SceneController } from './runtime/scene.js';+export { SkillRegistry, Skill } from './skills/index.js';+export { Memory } from './memory/index.js';+export { loadManifest, normalize, fetchRelative } from './manifest.js';+export { resolveURI, fetchWithFallback } from './ipfs.js';++// Re-export the side-effectful element import for users who import the whole bundle.+export const defineElement = (tag = 'agent-3d') => {+ if (!customElements.get(tag)) customElements.define(tag, Agent3DElement);+};++// The element also self-registers on import, but calling defineElement() with a+// custom tag lets consumers ship under their own brand.diff --git a/publish/src/manifest.js b/publish/src/manifest.jsnew file mode 100644index 000000000..b3d4081e3--- /dev/null+++ b/publish/src/manifest.js@@ -0,0 +1,163 @@+// Manifest loader — resolves agent://, ipfs://, https:// into a normalized manifest.+// See specs/AGENT_MANIFEST.md++import { JsonRpcProvider, Contract } from 'ethers';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';+import { findAvatar3D } from './erc8004/queries.js';+import { resolveURI, fetchWithFallback } from './ipfs.js';++const CHAIN_ALIASES = {+ base: 8453,+ 'base-mainnet': 8453,+ 'base-sepolia': 84532,+ ethereum: 1,+ mainnet: 1,+};++const DEFAULT_RPCS = {+ 8453: 'https://mainnet.base.org',+ 84532: 'https://sepolia.base.org',+ 1: 'https://eth.llamarpc.com',+};++export async function loadManifest(source, { rpcURL, registry: registryOverride } = {}) {+ if (!source) throw new Error('loadManifest: source required');++ if (source.startsWith('agent://')) {+ return loadFromAgentURI(source, { rpcURL, registryOverride });+ }+ if (source.startsWith('ipfs://') || source.startsWith('ar://')) {+ const url = resolveURI(source);+ const json = await fetchManifestJSON(url);+ return normalize(json, { baseURI: trimToDir(url) });+ }+ if (source.startsWith('http')) {+ const json = await fetchManifestJSON(source);+ return normalize(json, { baseURI: trimToDir(source) });+ }+ throw new Error(`Unsupported manifest source: ${source}`);+}++async function loadFromAgentURI(uri, { rpcURL, registryOverride }) {+ // agent://{chain}/{agentId}+ const m = uri.match(/^agent:\/\/([^/]+)\/(\d+)$/);+ if (!m) throw new Error(`Malformed agent URI: ${uri}`);+ const [, chainName, agentIdStr] = m;+ const chainId = CHAIN_ALIASES[chainName.toLowerCase()] || Number(chainName);+ if (!chainId) throw new Error(`Unknown chain: ${chainName}`);++ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ const registryAddr = registryOverride || deployment?.identityRegistry;+ if (!registryAddr) {+ throw new Error(`No registry deployed on chain ${chainId}. Pass registry= override.`);+ }++ const provider = new JsonRpcProvider(rpcURL || DEFAULT_RPCS[chainId]);+ const registry = new Contract(registryAddr, IDENTITY_REGISTRY_ABI, provider);+ const agentId = BigInt(agentIdStr);++ const tokenURI = await registry.tokenURI(agentId);+ if (!tokenURI) throw new Error(`Agent ${agentIdStr} on chain ${chainId} has no URI`);++ const resolved = resolveURI(tokenURI);+ const json = await fetchManifestJSON(resolved);+ const manifest = normalize(json, { baseURI: trimToDir(resolved) });++ // Ensure id is stamped on the manifest+ manifest.id = {+ ...manifest.id,+ chain: chainName,+ chainId,+ registry: registryAddr,+ agentId: agentIdStr,+ };+ return manifest;+}++async function fetchManifestJSON(url) {+ // Prefer fetchWithFallback if this is an IPFS URI we can detect.+ let res;+ try {+ res = await fetch(url);+ } catch {+ res = await fetchWithFallback(url);+ }+ if (!res.ok) throw new Error(`Manifest fetch failed: ${url} (${res.status})`);+ return res.json();+}++// Convert either a full AGENT_MANIFEST or a bare ERC-8004 registration JSON+// into a uniform manifest object the runtime consumes.+export function normalize(json, { baseURI = '' } = {}) {+ // Full manifest — spec: "agent-manifest/0.1"+ if (json.spec && json.spec.startsWith('agent-manifest/')) {+ const m = { ...json, _baseURI: baseURI };+ m.body = m.body || {};+ if (!m.body.uri && m.image) m.body.uri = m.image;+ return m;+ }++ // ERC-8004 registration JSON — adapt to manifest shape+ if (json.type && json.type.includes('eip-8004')) {+ const registration = json.registrations?.[0] || {};+ // The GLB lives in services[{name:'avatar'}] per our convention. The+ // top-level `image` field is a 2D thumbnail (NFT-marketplace compat) —+ // only fall back to it when no 3D body was declared.+ const glbUri = findAvatar3D(json);+ return {+ spec: 'agent-manifest/0.1',+ _baseURI: baseURI,+ _source: 'erc8004-registration',+ id: { agentId: registration.agentId?.toString() },+ name: json.name,+ description: json.description,+ image: json.image,+ body: { uri: resolveURI(glbUri || json.image || ''), format: 'gltf-binary' },+ brain: { provider: 'none' },+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },+ skills: [],+ memory: { mode: 'local' },+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression'],+ version: '0.1.0',+ services: Array.isArray(json.services) ? json.services : [],+ x402Support: !!json.x402Support,+ embedPolicy: json.embedPolicy || null,+ };+ }++ // Unknown / partial — best effort+ return {+ spec: 'agent-manifest/0.1',+ _baseURI: baseURI,+ name: json.name || 'Unnamed agent',+ description: json.description || '',+ body: {+ uri: json.body?.uri || json.image || json.model || '',+ format: json.body?.format || 'gltf-binary',+ },+ brain: json.brain || { provider: 'none' },+ voice: json.voice || { tts: { provider: 'browser' }, stt: { provider: 'browser' } },+ skills: json.skills || [],+ memory: json.memory || { mode: 'local' },+ tools: json.tools || ['wave', 'lookAt', 'play_clip', 'setExpression'],+ version: json.version || '0.1.0',+ };+}++function trimToDir(url) {+ const i = url.lastIndexOf('/');+ return i >= 0 ? url.slice(0, i + 1) : url;+}++// Load instructions.md, SKILL.md and other relative files referenced by the manifest+export async function fetchRelative(manifest, relPath) {+ if (!manifest._baseURI) return null;+ try {+ const url = new URL(relPath, manifest._baseURI).href;+ const res = await fetch(url);+ if (!res.ok) return null;+ return res.text();+ } catch {+ return null;+ }+}diff --git a/publish/src/memory/crypto.js b/publish/src/memory/crypto.jsnew file mode 100644index 000000000..0e8afefc7--- /dev/null+++ b/publish/src/memory/crypto.js@@ -0,0 +1,79 @@+// Deterministic key derivation + AES-GCM-256 authenticated encryption for memory bundles.+// Uses only crypto.subtle — no polyfills, no bundle weight.++function hexToBytes(hex) {+ const clean = hex.startsWith('0x') ? hex.slice(2) : hex;+ const out = new Uint8Array(clean.length / 2);+ for (let i = 0; i < out.length; i++) out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);+ return out;+}++export function bytesToBase64(bytes) {+ return btoa(String.fromCharCode(...bytes));+}++export function base64ToBytes(b64) {+ return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));+}++/**+ * Derive a non-extractable AES-GCM-256 CryptoKey from a wallet signer.+ * Deterministic for the same (wallet, agentId) pair — memory follows the owner across devices.+ *+ * Canonical message: `agent-3d:memory:v1:{agentId}`+ * Bump the version prefix on any breaking crypto change.+ *+ * @param {import('ethers').Signer} signer+ * @param {string} agentId+ * @returns {Promise<CryptoKey>}+ */+export async function deriveEncryptionKey(signer, agentId) {+ const message = `agent-3d:memory:v1:${agentId}`;+ const signature = await signer.signMessage(message);+ const sigBytes = hexToBytes(signature);+ const hashBuf = await crypto.subtle.digest('SHA-256', sigBytes);+ const baseKey = await crypto.subtle.importKey('raw', hashBuf, 'HKDF', false, ['deriveKey']);+ return crypto.subtle.deriveKey(+ {+ name: 'HKDF',+ hash: 'SHA-256',+ salt: new Uint8Array(32),+ info: new TextEncoder().encode('agent-3d-memory-aes-gcm'),+ },+ baseKey,+ { name: 'AES-GCM', length: 256 },+ false,+ ['encrypt', 'decrypt'],+ );+}++/**+ * Encrypt plaintext bytes with AES-GCM-256.+ * A fresh 12-byte nonce is generated per call; the GCM auth tag is appended to ciphertext.+ *+ * @param {Uint8Array} plaintext+ * @param {CryptoKey} key+ * @returns {Promise<{ nonce: Uint8Array, ciphertext: Uint8Array }>}+ */+export async function encryptBlob(plaintext, key) {+ const nonce = crypto.getRandomValues(new Uint8Array(12));+ const buf = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, key, plaintext);+ return { nonce, ciphertext: new Uint8Array(buf) };+}++/**+ * Decrypt an AES-GCM-256 blob.+ * Throws clearly on tampered ciphertext or wrong key — no silent corruption.+ *+ * @param {{ nonce: Uint8Array, ciphertext: Uint8Array }} blob+ * @param {CryptoKey} key+ * @returns {Promise<Uint8Array>}+ */+export async function decryptBlob({ nonce, ciphertext }, key) {+ try {+ const buf = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, key, ciphertext);+ return new Uint8Array(buf);+ } catch {+ throw new Error('[memory/crypto] Decryption failed — wrong key or tampered ciphertext');+ }+}diff --git a/publish/src/memory/index.js b/publish/src/memory/index.jsnew file mode 100644index 000000000..c1d7f969d--- /dev/null+++ b/publish/src/memory/index.js@@ -0,0 +1,205 @@+// 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/publish/src/mint/index.js b/publish/src/mint/index.jsnew file mode 100644index 000000000..80c22b22c--- /dev/null+++ b/publish/src/mint/index.js@@ -0,0 +1,111 @@+/**+ * Mint flow — the full pipeline for creating a permanent onchain agent.+ *+ * Steps:+ * 1. Embed agent manifest into GLB extras (the file becomes self-describing)+ * 2. Pin the GLB to IPFS (hot, fast access)+ * 3. Upload the GLB to Arweave (permanent backup)+ * 4. Build ERC-8004 registration JSON referencing both URIs+ * 5. Register onchain via Identity Registry+ *+ * None of this is wired to any UI or nav yet — call mintAgent() directly.+ *+ * Usage:+ * import { mintAgent } from '../mint/index.js';+ * const result = await mintAgent({ glbBlob, manifest, signer, chainId, onLog });+ */++import { embedAgentExtras } from '../erc8004/gltf-extras.js';+import { uploadToArweave } from '../arweave/upload.js';+import { getPinner } from '../pinning/index.js';+import { buildRegistrationJSON, registerAgent } from '../erc8004/agent-registry.js';++/**+ * @typedef {object} MintOptions+ * @property {Blob} glbBlob Original GLB file+ * @property {object} manifest agent-manifest/0.1 shaped object+ * @property {import('ethers').Signer} signer Connected ethers signer+ * @property {number} chainId+ * @property {string} [registryAddr] Override default registry address+ * @property {function(string): void} [onLog] Progress callback+ * @property {boolean} [skipArweave] Skip Arweave upload (dev/test)+ */++/**+ * @typedef {object} MintResult+ * @property {string} agentId+ * @property {string} ipfsUri ipfs:// URI of the GLB+ * @property {string|null} arUri ar:// URI of the GLB (null if skipArweave)+ * @property {string} registrationUrl+ * @property {string} txHash+ * @property {number} chainId+ */++/**+ * Run the full mint pipeline.+ *+ * @param {MintOptions} opts+ * @returns {Promise<MintResult>}+ */+export async function mintAgent(opts) {+ const { glbBlob, manifest, signer, chainId, registryAddr, onLog, skipArweave = false } = opts;+ const log = onLog ?? (() => {});++ // 1. Embed manifest into GLB extras+ log('Embedding agent manifest into GLB...');+ const originalBytes = new Uint8Array(await glbBlob.arrayBuffer());+ const enrichedBytes = await embedAgentExtras(originalBytes, manifest);+ const enrichedBlob = new Blob([enrichedBytes], { type: 'model/gltf-binary' });++ // 2. Pin to IPFS+ log('Pinning GLB to IPFS...');+ const pinner = getPinner();+ const { cid } = await pinner.pinBlob(enrichedBlob, { name: `${manifest.name ?? 'agent'}.glb` });+ const ipfsUri = `ipfs://${cid}`;+ log(`IPFS: ${ipfsUri}`);++ // 3. Upload to Arweave (permanent backup)+ let arUri = null;+ if (!skipArweave) {+ log('Uploading GLB to Arweave (permanent)...');+ try {+ arUri = await uploadToArweave(enrichedBytes, signer, {+ name: `${manifest.name ?? 'agent'}.glb`,+ contentType: 'model/gltf-binary',+ });+ log(`Arweave: ${arUri}`);+ } catch (err) {+ // Arweave failure is non-fatal — IPFS still works+ log(`Arweave upload failed (non-fatal): ${err.message}`);+ }+ }++ // 4 + 5. Build registration JSON and register onchain+ // glbUrl points to IPFS; arUri stored as an additional service entry+ const services = arUri+ ? [{ name: 'avatar-arweave', endpoint: arUri, version: 'gltf-2.0' }]+ : [];++ log('Registering agent onchain...');+ const result = await registerAgent({+ name: manifest.name,+ description: manifest.description,+ glbUrl: ipfsUri,+ imageUrl: manifest.image ?? '',+ signer,+ chainId,+ registryAddr,+ services,+ animations: manifest.animations,+ onLog: log,+ });++ return {+ agentId: result.agentId,+ ipfsUri,+ arUri,+ registrationUrl: result.registrationUrl,+ txHash: result.txHash,+ chainId: result.chainId,+ };+}diff --git a/publish/src/model-info.js b/publish/src/model-info.jsnew file mode 100644index 000000000..fd6b78f40--- /dev/null+++ b/publish/src/model-info.js@@ -0,0 +1,339 @@+import {+ prepare,+ layout,+ prepareWithSegments,+ layoutWithLines,+ measureLineStats,+} from '@chenglou/pretext';+import {+ prepareRichInline,+ walkRichInlineLineRanges,+ materializeRichInlineLineRange,+} from '@chenglou/pretext/rich-inline';++// Fonts+const FONT_TITLE = '500 14px Inter, sans-serif';+const FONT_LABEL = '600 10px Inter, sans-serif';+const FONT_VALUE = '300 13px Inter, sans-serif';+const FONT_CHIP = '600 10px Inter, sans-serif';+const FONT_DESC = '300 12px Inter, sans-serif';++// Layout+const LINE_HEIGHT = 18;+const CHIP_HEIGHT = 16;+const PADDING = 16;+const ROW_GAP = 6;+const CHIP_PAD_X = 12; // horizontal padding inside chip+const DPR = Math.min(window.devicePixelRatio || 1, 2);++// Colors+const COL_BG = 'rgba(0, 0, 0, 0.75)';+const COL_BORDER = 'rgba(255, 255, 255, 0.08)';+const COL_TITLE = 'rgba(255, 255, 255, 0.9)';+const COL_LABEL = 'rgba(255, 255, 255, 0.30)';+const COL_VALUE = 'rgba(255, 255, 255, 0.85)';+const COL_SEP = 'rgba(255, 255, 255, 0.08)';+const COL_DESC = 'rgba(255, 255, 255, 0.45)';+const COL_CHIP_BG = 'rgba(255, 255, 255, 0.08)';+const COL_CHIP_TEXT = 'rgba(255, 255, 255, 0.7)';++function countStats(object) {+ let vertices = 0;+ let triangles = 0;+ let meshes = 0;+ const materialSet = new Set();+ const textureSet = new Set();+ const materialTypes = new Set();+ let hasSkinning = false;+ let hasMorphs = false;++ object.traverse((node) => {+ if (node.isMesh || node.isPoints || node.isLine) {+ meshes++;+ const geo = node.geometry;+ if (geo) {+ if (geo.index) {+ triangles += geo.index.count / 3;+ } else if (geo.attributes.position) {+ triangles += geo.attributes.position.count / 3;+ }+ if (geo.attributes.position) {+ vertices += geo.attributes.position.count;+ }+ }+ if (node.skeleton) hasSkinning = true;+ if (node.morphTargetInfluences && node.morphTargetInfluences.length > 0)+ hasMorphs = true;++ const mats = Array.isArray(node.material) ? node.material : [node.material];+ mats.forEach((mat) => {+ if (mat) {+ materialSet.add(mat.uuid);+ materialTypes.add(mat.type.replace('Material', ''));+ for (const key in mat) {+ if (mat[key] && mat[key].isTexture) {+ textureSet.add(mat[key].uuid);+ }+ }+ }+ });+ }+ });++ return {+ vertices,+ triangles: Math.floor(triangles),+ meshes,+ materials: materialSet.size,+ textures: textureSet.size,+ materialTypes: Array.from(materialTypes),+ hasSkinning,+ hasMorphs,+ };+}++function formatNum(n) {+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M';+ if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';+ return n.toString();+}++function buildDescription(stats, clips) {+ const parts = [];+ if (stats.hasSkinning) parts.push('skinned');+ if (stats.hasMorphs) parts.push('morph targets');+ if (clips && clips.length > 0)+ parts.push(`${clips.length} animation${clips.length > 1 ? 's' : ''}`);+ if (stats.materialTypes.length > 0) parts.push(stats.materialTypes.join(', '));+ return parts.length > 0 ? parts.join(' · ') : '';+}++/**+ * Creates the model info overlay using pretext rich-inline for mixed-style rendering.+ */+export function createModelInfo(container, object, clips) {+ const stats = countStats(object);+ const desc = buildDescription(stats, clips);++ // Build stat rows+ const rows = [+ { label: 'MESHES', value: formatNum(stats.meshes) },+ { label: 'VERTICES', value: formatNum(stats.vertices) },+ { label: 'TRIANGLES', value: formatNum(stats.triangles) },+ { label: 'MATERIALS', value: formatNum(stats.materials) },+ { label: 'TEXTURES', value: formatNum(stats.textures) },+ ];+ if (clips && clips.length > 0) {+ rows.push({ label: 'ANIMATIONS', value: clips.length.toString() });+ }++ // Build chips from material types & features+ const chips = [];+ stats.materialTypes.forEach((t) => chips.push(t));+ if (stats.hasSkinning) chips.push('Skinned');+ if (stats.hasMorphs) chips.push('Morph');+ if (clips && clips.length > 0) chips.push('Animated');++ // -- Measure everything with pretext --+ const maxWidth = 200;++ // Title+ const titlePrepared = prepare('Model Info', FONT_TITLE);+ const titleMeasure = layout(titlePrepared, maxWidth, LINE_HEIGHT + 2);++ // Stat rows: use rich-inline for each row (label + value in one flow)+ const rowMeasurements = rows.map((row) => {+ const items = [+ { text: row.label + ' ', font: FONT_LABEL },+ { text: row.value, font: FONT_VALUE },+ ];+ const prepared = prepareRichInline(items);+ // Get the natural width by measuring with a very wide max+ const labelPrepared = prepare(row.label, FONT_LABEL);+ const labelStats = measureLineStats(labelPrepared, maxWidth);+ const valuePrepared = prepare(row.value, FONT_VALUE);+ const valueStats = measureLineStats(valuePrepared, maxWidth);+ return {+ ...row,+ labelWidth: labelStats.maxLineWidth,+ valueWidth: valueStats.maxLineWidth,+ richPrepared: prepared,+ };+ });++ // Chips: measure each chip with pretext+ const chipMeasurements = chips.map((text) => {+ const prepared = prepare(text, FONT_CHIP);+ const stats = measureLineStats(prepared, 300);+ return { text, width: stats.maxLineWidth + CHIP_PAD_X };+ });++ // Description: multi-line wrapping — this is where pretext really shines+ let descLines = [];+ let descHeight = 0;+ if (desc) {+ const descPrepared = prepareWithSegments(desc, FONT_DESC);+ const descLayout = layoutWithLines(descPrepared, maxWidth - PADDING, LINE_HEIGHT);+ descLines = descLayout.lines;+ descHeight = descLayout.height;+ }++ // -- Calculate canvas size from measurements --+ const contentWidth = Math.max(+ titleMeasure.width + PADDING * 2,+ ...rowMeasurements.map((r) => r.labelWidth + r.valueWidth + PADDING * 3),+ );+ const canvasWidth = Math.max(contentWidth, 180);++ // Chip row height+ let chipRowHeight = 0;+ if (chipMeasurements.length > 0) {+ // Wrap chips into rows+ let chipX = 0;+ let chipRows = 1;+ chipMeasurements.forEach((chip) => {+ if (chipX > 0 && chipX + chip.width > canvasWidth - PADDING * 2) {+ chipRows++;+ chipX = 0;+ }+ chipX += chip.width + 6;+ });+ chipRowHeight = chipRows * (CHIP_HEIGHT + 6) + ROW_GAP;+ }++ const canvasHeight =+ PADDING ++ titleMeasure.height ++ ROW_GAP + // title+ ROW_GAP + // separator+ rowMeasurements.length * (LINE_HEIGHT + ROW_GAP) + // stat rows+ chipRowHeight + // chips+ (descHeight > 0 ? ROW_GAP + descHeight : 0) + // description+ PADDING;++ // -- Render to canvas --+ const canvas = document.createElement('canvas');+ canvas.width = canvasWidth * DPR;+ canvas.height = canvasHeight * DPR;+ canvas.style.width = canvasWidth + 'px';+ canvas.style.height = canvasHeight + 'px';++ const ctx = canvas.getContext('2d');+ ctx.scale(DPR, DPR);++ // Background+ ctx.fillStyle = COL_BG;+ roundRect(ctx, 0, 0, canvasWidth, canvasHeight, 10);+ ctx.fill();++ // Border+ ctx.strokeStyle = COL_BORDER;+ ctx.lineWidth = 1;+ roundRect(ctx, 0.5, 0.5, canvasWidth - 1, canvasHeight - 1, 10);+ ctx.stroke();++ // Title+ let y = PADDING;+ ctx.font = FONT_TITLE;+ ctx.fillStyle = COL_TITLE;+ ctx.textBaseline = 'top';+ ctx.fillText('Model Info', PADDING, y);+ y += titleMeasure.height + ROW_GAP;++ // Separator+ ctx.strokeStyle = COL_SEP;+ ctx.beginPath();+ ctx.moveTo(PADDING, y);+ ctx.lineTo(canvasWidth - PADDING, y);+ ctx.stroke();+ y += ROW_GAP;++ // Stat rows+ rowMeasurements.forEach((row) => {+ ctx.font = FONT_LABEL;+ ctx.fillStyle = COL_LABEL;+ ctx.textAlign = 'left';+ ctx.fillText(row.label, PADDING, y);++ ctx.font = FONT_VALUE;+ ctx.fillStyle = COL_VALUE;+ ctx.textAlign = 'right';+ ctx.fillText(row.value, canvasWidth - PADDING, y);+ ctx.textAlign = 'left';++ y += LINE_HEIGHT + ROW_GAP;+ });++ // Chips+ if (chipMeasurements.length > 0) {+ let chipX = PADDING;++ chipMeasurements.forEach((chip) => {+ if (chipX > PADDING && chipX + chip.width > canvasWidth - PADDING) {+ chipX = PADDING;+ y += CHIP_HEIGHT + 6;+ }++ // Chip background+ ctx.fillStyle = COL_CHIP_BG;+ roundRect(ctx, chipX, y, chip.width, CHIP_HEIGHT, 4);+ ctx.fill();++ // Chip text (centered in chip)+ ctx.font = FONT_CHIP;+ ctx.fillStyle = COL_CHIP_TEXT;+ ctx.textBaseline = 'top';+ ctx.fillText(chip.text, chipX + CHIP_PAD_X / 2, y + 3);++ chipX += chip.width + 6;+ });++ y += CHIP_HEIGHT + ROW_GAP + 4;+ }++ // Description (multi-line, pretext-wrapped)+ if (descLines.length > 0) {+ ctx.strokeStyle = COL_SEP;+ ctx.beginPath();+ ctx.moveTo(PADDING, y);+ ctx.lineTo(canvasWidth - PADDING, y);+ ctx.stroke();+ y += ROW_GAP;++ ctx.font = FONT_DESC;+ ctx.fillStyle = COL_DESC;+ ctx.textBaseline = 'top';+ descLines.forEach((line) => {+ ctx.fillText(line.text, PADDING, y);+ y += LINE_HEIGHT;+ });+ }++ // Mount+ const el = document.createElement('div');+ el.classList.add('model-info');+ el.appendChild(canvas);+ container.appendChild(el);++ return {+ el,+ canvas,+ remove() {+ el.remove();+ },+ };+}++function roundRect(ctx, x, y, w, h, r) {+ ctx.beginPath();+ ctx.moveTo(x + r, y);+ ctx.lineTo(x + w - r, y);+ ctx.quadraticCurveTo(x + w, y, x + w, y + r);+ ctx.lineTo(x + w, y + h - r);+ ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);+ ctx.lineTo(x + r, y + h);+ ctx.quadraticCurveTo(x, y + h, x, y + h - r);+ ctx.lineTo(x, y + r);+ ctx.quadraticCurveTo(x, y, x + r, y);+ ctx.closePath();+}diff --git a/publish/src/nich-agent.js b/publish/src/nich-agent.jsnew file mode 100644index 000000000..4c2b73ca3--- /dev/null+++ b/publish/src/nich-agent.js@@ -0,0 +1,694 @@+/**+ * NichAgent — Voice + Chat Interface+ * ------------------------------------+ * The conversational surface of the three.ws.+ * Now protocol-aware: responses go through the AgentProtocol bus,+ * which drives the avatar's Empathy Layer and action timeline.+ *+ * Skills-aware: routes recognised intents to AgentSkills.perform()+ * so the avatar performs them visibly, not just textually.+ */++import { ACTION_TYPES } from './agent-protocol.js';++const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;++/**+ * @typedef {Object} NichAgentOptions+ * @property {'floating'|'embedded'} [layout] 'floating' (default) = legacy fixed-position toggle button + panel.+ * 'embedded' = panel mounts directly inside containerEl, no toggle button.+ * @property {'right'|'bottom'|'overlay'} [position] Layout hint applied as a CSS class. Embedded only.+ * @property {string} [greeting] First agent message shown on open / mount.+ * @property {string} [title] Override identity.name in the panel header.+ * @property {{accent?:string, background?:string, caption?:string}} [theme]+ * CSS custom-property overrides (--nich-accent, --nich-bg, --nich-fg).+ * @property {boolean} [showPoweredBy] Show "powered by three.ws" footer link.+ * @property {boolean} [voiceInput] Enable mic button (default true).+ * @property {boolean} [voiceOutput] Speak replies via speechSynthesis (default true).+ * @property {(text:string)=>Promise<{reply?:string,actions?:any[]}>} [onSend]+ * Override the default chat dispatch. Used by the talking-agent widget+ * to route through /api/widgets/:id/chat instead of /api/chat.+ * @property {boolean} [skipDefaultListeners] Skip wiring SPEAK / LOAD_START / PERFORM_SKILL bus handlers.+ * Widgets manage their own greeting + history.+ */++export class NichAgent {+ /**+ * @param {HTMLElement} containerEl+ * @param {import('./agent-protocol.js').AgentProtocol} [protocol]+ * @param {import('./agent-skills.js').AgentSkills} [skills]+ * @param {import('./agent-identity.js').AgentIdentity} [identity]+ * @param {import('./runtime/index.js').Runtime} [runtime]+ * @param {NichAgentOptions} [options]+ */+ constructor(+ containerEl,+ protocol = null,+ skills = null,+ identity = null,+ runtime = null,+ options = {},+ ) {+ this.container = containerEl;+ this.protocol = protocol;+ this.skills = skills;+ this.identity = identity;+ this.runtime = runtime;+ this.options = options || {};+ this.layout = this.options.layout || 'floating';+ this.position = this.options.position || 'right';+ this.voiceInput = this.options.voiceInput !== false;+ this.voiceOutput = this.options.voiceOutput !== false;+ this.isSpeaking = false;+ this.isListening = false;+ this.recognition = null;+ this.synth = window.speechSynthesis;+ this.messages = [];+ this.onFirstOpen = null;+ this._hasOpened = false;+ this._apiDisabled = false;+ this._storageKey = `nich-agent:history:${this.identity?.id || 'default'}`;+ this._loadHistory();++ this._buildUI();+ if (this.voiceInput) this._initSpeechRecognition();++ // Listen for SPEAK actions to render them in the chat+ if (this.protocol && !this.options.skipDefaultListeners) {+ this.protocol.on(ACTION_TYPES.SPEAK, (action) => {+ const text = action.payload?.text;+ if (text) {+ this._addMessage('agent', text);+ this._speak(text);+ }+ });++ // Show skill status in chat+ this.protocol.on(ACTION_TYPES.PERFORM_SKILL, (action) => {+ const skill = action.payload?.skill;+ if (skill && skill !== 'greet') {+ this._addMessage('agent', `[performing: ${skill}]`, 'status');+ }+ });++ // Clear chat history on model change so context stays relevant+ this.protocol.on(ACTION_TYPES.LOAD_START, () => this._resetHistory());+ }+ }++ // ── Speech Recognition ────────────────────────────────────────────────────++ _initSpeechRecognition() {+ if (!SpeechRecognition) return;++ this.recognition = new SpeechRecognition();+ this.recognition.continuous = false;+ this.recognition.interimResults = false;+ this.recognition.lang = 'en-US';++ this.recognition.onresult = (event) => {+ const text = event.results[0][0].transcript;+ this._addMessage('user', text);+ this._handleInput(text);+ };++ this.recognition.onend = () => {+ this.isListening = false;+ this.panel.querySelector('.nich-mic').classList.remove('active');+ };++ this.recognition.onerror = () => {+ this.isListening = false;+ this.panel.querySelector('.nich-mic').classList.remove('active');+ };+ }++ // ── UI ────────────────────────────────────────────────────────────────────++ _buildUI() {+ const titleText = this.options.title || this.identity?.name || 'Agent';+ const greeting =+ this.options.greeting ||+ (this.layout === 'embedded'+ ? 'Hi! Ask me anything.'+ : `I'm here. Drop a model, ask me anything, or say "help".`);++ this.panel = document.createElement('div');+ this.panel.className =+ 'nich-panel' ++ (this.layout === 'embedded'+ ? ' nich-panel--embedded nich-position--' + this.position+ : '');+ this.panel.innerHTML = `+ <div class="nich-header">+ <span class="nich-title">${_escapeHTML(titleText)}</span>+ <div class="nich-header-right">+ <span class="nich-emotion-dot" id="nich-emotion-dot" title="Agent emotional state"></span>+ ${this.layout === 'embedded' ? '' : '<button class="nich-close" aria-label="Close">×</button>'}+ </div>+ </div>+ <div class="nich-messages" id="agent-messages">+ <div class="nich-message agent">${_escapeHTML(greeting)}</div>+ </div>+ <div class="nich-controls">+ <input type="text" class="nich-input" placeholder="Ask the agent…" autocomplete="off" maxlength="4000" />+ <button class="nich-send" aria-label="Send">+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>+ </button>+ </div>+ ${+ this.voiceInput+ ? `+ <div class="nich-mic-row">+ <button class="nich-mic" aria-label="Toggle microphone">+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1-9c0-.55.45-1 1-1s1 .45 1 1v6c0 .55-.45 1-1 1s-1-.45-1-1V5zm6 6c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>+ </button>+ <span class="nich-mic-hint">${SpeechRecognition ? 'or press mic to speak' : 'voice unavailable in this browser'}</span>+ </div>+ `+ : ''+ }+ ${this.options.showPoweredBy ? '<a class="nich-powered-by" href="https://three.ws/" target="_blank" rel="noopener noreferrer">powered by 3dagent</a>' : ''}+ `;++ // Apply theme overrides via CSS custom properties scoped to the panel.+ if (this.options.theme) {+ const t = this.options.theme;+ if (t.accent) this.panel.style.setProperty('--nich-accent', t.accent);+ if (t.background) this.panel.style.setProperty('--nich-bg', t.background);+ if (t.caption) this.panel.style.setProperty('--nich-fg', t.caption);+ }++ if (this.layout === 'embedded') {+ // Embedded: panel is always open inside its container, no toggle.+ this.container.appendChild(this.panel);+ } else {+ // Floating: original behaviour — fixed-position panel + toggle button on body.+ this.panel.style.display = 'none';+ this.container.appendChild(this.panel);+ this.toggleBtn = document.createElement('button');+ this.toggleBtn.className = 'nich-toggle';+ this.toggleBtn.setAttribute('aria-label', 'Talk to three.ws');+ this.toggleBtn.title = 'Talk to Agent';+ this.toggleBtn.innerHTML = `+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">+ <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>+ <path d="M7 9h2v2H7zm4 0h2v2h-2zm4 0h2v2h-2z"/>+ </svg>+ <span class="nich-toggle-label">Agent</span>+ `;+ this.container.appendChild(this.toggleBtn);+ this.toggleBtn.addEventListener('click', () => this._togglePanel());+ this.panel+ .querySelector('.nich-close')+ ?.addEventListener('click', () => this._togglePanel());+ }++ this.panel.querySelector('.nich-send').addEventListener('click', () => this._send());+ this.panel.querySelector('.nich-input').addEventListener('keydown', (e) => {+ if (e.key === 'Enter') this._send();+ });+ this.panel.querySelector('.nich-mic')?.addEventListener('click', () => this._toggleMic());+ }++ // ── Panel Toggle ──────────────────────────────────────────────────────────++ _togglePanel() {+ const visible = this.panel.style.display !== 'none';+ this.panel.style.display = visible ? 'none' : 'flex';+ this.toggleBtn.classList.toggle('active', !visible);+ if (!visible) {+ this.panel.querySelector('.nich-input').focus();+ // First open triggers a greeting skill+ if (!this._hasOpened) {+ this._hasOpened = true;+ if (this.onFirstOpen) this.onFirstOpen();+ else if (this.skills) {+ this.skills.perform('greet', {}, { identity: this.identity });+ }+ }+ }+ }++ // ── Input Handling ────────────────────────────────────────────────────────++ _send() {+ const input = this.panel.querySelector('.nich-input');+ const text = input.value.trim();+ if (!text) return;+ input.value = '';+ this._addMessage('user', text);+ this._handleInput(text);+ }++ async _handleInput(text) {+ // Custom dispatch (talking-agent widget routes through /api/widgets/:id/chat)+ if (typeof this.options.onSend === 'function') {+ const typing = this._startTyping();+ try {+ const result = await this.options.onSend(text);+ if (result?.reply) {+ this._addMessage('agent', result.reply);+ this._speak(result.reply);+ this._pushHistory('user', text);+ this._pushHistory('assistant', result.reply);+ if (this.protocol) {+ this.protocol.emit({+ type: ACTION_TYPES.SPEAK,+ payload: { text: result.reply, sentiment: 0 },+ agentId: this.identity?.id || 'default',+ });+ }+ } else if (result?.error) {+ this._addMessage('agent', result.error, 'status');+ }+ } finally {+ typing();+ }+ return;+ }++ const lower = text.toLowerCase();++ // Route to skills first (high-precision pattern matching)+ if (this.skills) {+ const skillName = this._matchSkill(lower);+ if (skillName) {+ await this.skills.perform(skillName, { query: text }, { identity: this.identity });+ return;+ }+ }++ // Preferred path: call the /api/chat LLM endpoint with viewer context.+ if (!this._apiDisabled) {+ const apiResult = await this._callChatAPI(text);+ if (apiResult.ok) {+ await this._applyApiReply(apiResult);+ return;+ }+ if (apiResult.disable) this._apiDisabled = true;+ }++ // Secondary: the client-side Runtime (only meaningful if a provider+ // was configured via #brain=anthropic&proxyURL=... — NullProvider returns '').+ if (this.runtime) {+ try {+ const { text: reply } = await this.runtime.send(text);+ if (reply) {+ this._addMessage('agent', reply);+ this._speak(reply);+ this._pushHistory('user', text);+ this._pushHistory('assistant', reply);+ return;+ }+ } catch (err) {+ console.warn('[NichAgent] Runtime error, falling back:', err.message);+ }+ }++ // Final fallback: offline pattern match so the agent still responds.+ const response = this._generateResponse(text);+ this._addMessage('agent', response);+ this._speak(response);++ if (this.protocol) {+ this.protocol.emit({+ type: ACTION_TYPES.SPEAK,+ payload: { text: response, sentiment: 0 },+ agentId: this.identity?.id || 'default',+ });+ }+ }++ // ── Chat API ─────────────────────────────────────────────────────────────++ async _callChatAPI(message) {+ const typing = this._startTyping();+ try {+ const res = await fetch('/api/chat', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ message,+ context: this._buildContext(),+ history: this._history.slice(-10),+ }),+ });++ if (res.status === 401) return { ok: false, disable: true, reason: 'unauthorized' };+ if (res.status === 503) return { ok: false, disable: true, reason: 'unconfigured' };+ if (res.status === 429) {+ const data = await res.json().catch(() => ({}));+ return { ok: false, rateLimited: true, retryAfter: data.retry_after };+ }+ if (!res.ok) return { ok: false, reason: `http_${res.status}` };++ const data = await res.json();+ return {+ ok: true,+ message,+ reply: (data.reply || '').trim(),+ actions: data.actions || [],+ };+ } catch (err) {+ console.warn('[NichAgent] /api/chat failed:', err.message);+ return { ok: false, reason: 'network' };+ } finally {+ typing();+ }+ }++ async _applyApiReply({ message, reply, actions }) {+ this._pushHistory('user', message);++ if (reply) {+ this._addMessage('agent', reply);+ this._speak(reply);+ this._pushHistory('assistant', reply);+ if (this.protocol) {+ this.protocol.emit({+ type: ACTION_TYPES.SPEAK,+ payload: { text: reply, sentiment: 0 },+ agentId: this.identity?.id || 'default',+ });+ }+ }++ for (const action of actions || []) {+ try {+ await this._executeAction(action);+ } catch (err) {+ console.warn('[NichAgent] action failed:', action?.type, err.message);+ }+ }+ }++ _buildContext() {+ const viewer = window.VIEWER?.app?.viewer;+ const validator = window.VIEWER?.app?.validator;+ const state = viewer?.state || {};+ const ctx = {+ wireframe: !!state.wireframe,+ skeleton: !!state.skeleton,+ grid: !!state.grid,+ autoRotate: !!state.autoRotate,+ transparentBg: !!state.transparentBg,+ bgColor: state.bgColor,+ currentEnvironment: state.environment,+ };+ if (viewer?.content) {+ if (viewer.content.name) ctx.modelName = viewer.content.name;+ const stats = this._countStats(viewer.content);+ ctx.vertices = stats.vertices;+ ctx.triangles = stats.triangles;+ ctx.materials = stats.materials;+ ctx.animations = viewer.clips?.length || 0;+ }+ if (validator?.report) {+ ctx.validationErrors = validator.report.errors?.length || 0;+ ctx.validationWarnings = validator.report.warnings?.length || 0;+ }+ return ctx;+ }++ _countStats(root) {+ let vertices = 0,+ triangles = 0;+ const materials = new Set();+ root.traverse((node) => {+ if (node.isMesh || node.isPoints || node.isLine) {+ const geo = node.geometry;+ if (geo) {+ if (geo.index) triangles += geo.index.count / 3;+ else if (geo.attributes.position)+ triangles += geo.attributes.position.count / 3;+ if (geo.attributes.position) vertices += geo.attributes.position.count;+ }+ const mats = Array.isArray(node.material) ? node.material : [node.material];+ for (const m of mats) if (m) materials.add(m.uuid);+ }+ });+ return { vertices, triangles: Math.round(triangles), materials: materials.size };+ }++ async _executeAction(action) {+ const viewer = window.VIEWER?.app?.viewer;+ const app = window.VIEWER?.app;+ if (!action || typeof action.type !== 'string') return;++ switch (action.type) {+ case 'setWireframe':+ if (viewer) {+ viewer.state.wireframe = !!action.value;+ viewer.updateDisplay();+ }+ break;+ case 'setSkeleton':+ if (viewer) {+ viewer.state.skeleton = !!action.value;+ viewer.updateDisplay();+ }+ break;+ case 'setGrid':+ if (viewer) {+ viewer.state.grid = !!action.value;+ viewer.updateDisplay();+ }+ break;+ case 'setAutoRotate':+ if (viewer) {+ viewer.state.autoRotate = !!action.value;+ viewer.updateDisplay();+ }+ break;+ case 'setBgColor':+ if (viewer && typeof action.value === 'string') {+ viewer.state.bgColor = action.value;+ viewer.updateBackground();+ }+ break;+ case 'setTransparentBg':+ if (viewer) {+ viewer.state.transparentBg = !!action.value;+ viewer.updateBackground();+ }+ break;+ case 'setEnvironment':+ if (viewer && typeof action.value === 'string') {+ viewer.state.environment = action.value;+ viewer.updateEnvironment();+ }+ break;+ case 'takeScreenshot':+ viewer?.takeScreenshot?.();+ break;+ case 'loadModel':+ if (typeof action.url === 'string' && app?.view) {+ app.view(action.url, '', new Map());+ }+ break;+ case 'runValidation':+ // Open/focus the validation report panel so the user sees current results.+ document.querySelector('.validator-toggle')?.click?.();+ break;+ case 'showMaterialEditor':+ app?.editor?.sceneExplorer?.toggle?.();+ break;+ default:+ console.warn('[NichAgent] unknown action:', action.type);+ }+ }++ // ── Typing indicator ─────────────────────────────────────────────────────++ _startTyping() {+ const messagesEl = this.panel.querySelector('#agent-messages');+ const el = document.createElement('div');+ el.className = 'nich-message agent typing';+ el.textContent = '…';+ messagesEl.appendChild(el);+ messagesEl.scrollTop = messagesEl.scrollHeight;+ return () => el.remove();+ }++ // ── Conversation history (sessionStorage) ────────────────────────────────++ _loadHistory() {+ this._history = [];+ try {+ const raw = sessionStorage.getItem(this._storageKey);+ if (raw) this._history = JSON.parse(raw).slice(-20);+ } catch {+ this._history = [];+ }+ }++ _pushHistory(role, content) {+ this._history.push({ role, content });+ if (this._history.length > 20) this._history = this._history.slice(-20);+ try {+ sessionStorage.setItem(this._storageKey, JSON.stringify(this._history));+ } catch {}+ }++ _resetHistory() {+ this._history = [];+ try {+ sessionStorage.removeItem(this._storageKey);+ } catch {}+ }++ /**+ * Map user input to a skill name.+ * Returns null if no skill matches.+ */+ _matchSkill(lower) {+ if (lower.match(/\b(present|describe|tell me about|what.*model|show me)\b/))+ return 'present-model';+ if (lower.match(/\b(validate|check|errors|warnings|valid)\b/)) return 'validate-model';+ if (lower.match(/\b(remember|save|store|note|don't forget)\b/)) return 'remember';+ if (lower.match(/\b(sign|signature|wallet|verify|prove)\b/)) return 'sign-action';+ if (lower.match(/\b(think|recall|what do you know|context)\b/)) return 'think';+ if (lower.match(/\b(help|what can you|commands|skills|abilities)\b/)) return 'help';+ return null;+ }++ // ── Response Generation (fallback) ────────────────────────────────────────++ _generateResponse(input) {+ const lower = input.toLowerCase();+ const viewer = window.VIEWER?.app?.viewer;++ if (lower.match(/\b(hello|hi|hey|sup|yo)\b/)) {+ return 'Hey! Drop a 3D model in or ask me about the controls.';+ }+ if (lower.match(/\b(how|what).*(upload|load|open|import)\b/)) {+ return 'Drag and drop any glTF or GLB file onto the viewer, or click the upload button. The model loads instantly in your browser.';+ }+ if (lower.match(/\b(rotate|spin|orbit)\b/)) {+ return 'Click and drag to orbit. Enable auto-rotate in the Display controls panel on the right.';+ }+ if (lower.match(/\b(zoom)\b/)) {+ return 'Scroll wheel to zoom. On mobile, pinch.';+ }+ if (lower.match(/\b(pan|move)\b/)) {+ return 'Right-click and drag to pan. Two fingers on mobile.';+ }+ if (lower.match(/\b(wireframe)\b/)) {+ return 'Toggle wireframe in the Display controls panel — shows mesh topology.';+ }+ if (lower.match(/\b(light|lighting|dark|bright|exposure)\b/)) {+ return 'Open the Lighting folder in the controls panel. Change the environment map, adjust exposure, toggle punctual lights.';+ }+ if (lower.match(/\b(animation|animate|play|clip)\b/)) {+ return viewer?.clips?.length+ ? `This model has ${viewer.clips.length} animation clip${viewer.clips.length !== 1 ? 's' : ''}. Find them in the Animation folder.`+ : 'No animations on this model, or load a model first.';+ }+ if (lower.match(/\b(background|bg|color)\b/)) {+ return 'Change the background colour in the Display controls using the bgColor picker.';+ }+ if (lower.match(/\b(format|gltf|glb|supported|file)\b/)) {+ return 'Supports glTF 2.0 (.gltf) and GLB (.glb). Convert other formats with Blender.';+ }+ if (lower.match(/\b(skeleton|bones|rig)\b/)) {+ return 'Enable skeleton helper in the Display panel to visualise bone structure.';+ }+ if (lower.match(/\b(screenshot|capture|photo)\b/)) {+ return 'Press P to take a screenshot. It downloads as a PNG automatically.';+ }+ if (lower.match(/\b(performance|fps|stats)\b/)) {+ return 'Open the Performance folder in the controls panel for live FPS/MS/MB stats.';+ }+ if (lower.match(/\b(who|what).*(you|this|agent)\b/)) {+ return `I'm ${this.identity?.name || 'three.ws'} — present, embodied, and here to help with your 3D work.`;+ }+ if (lower.match(/\b(memory|remember|memories)\b/)) {+ const stats = this.identity?.memory?.stats;+ if (stats?.total) {+ return `I have ${stats.total} memories: ${stats.user || 0} about you, ${stats.project || 0} project notes, ${stats.feedback || 0} feedback entries.`;+ }+ return 'No memories yet. Tell me something worth remembering.';+ }++ return 'Try asking me to present or validate the loaded model, or drop a glTF/GLB file to get started.';+ }++ // ── Speech Synthesis ─────────────────────────────────────────────────────++ _speak(text) {+ if (!this.voiceOutput) return;+ if (!this.synth) return;+ this.synth.cancel();++ const utterance = new SpeechSynthesisUtterance(text);+ utterance.rate = 1.0;+ utterance.pitch = 1.0;+ utterance.volume = 0.8;+ utterance.onstart = () => {+ this.isSpeaking = true;+ };+ utterance.onend = () => {+ this.isSpeaking = false;+ };++ this.synth.speak(utterance);+ }++ // ── Mic Toggle ────────────────────────────────────────────────────────────++ _toggleMic() {+ if (!this.recognition) {+ this._addMessage('agent', 'Speech recognition not supported here. Try Chrome or Edge.');+ return;+ }+ if (this.isListening) {+ this.recognition.stop();+ this.isListening = false;+ this.panel.querySelector('.nich-mic').classList.remove('active');+ } else {+ this.recognition.start();+ this.isListening = true;+ this.panel.querySelector('.nich-mic').classList.add('active');+ }+ }++ // ── Message Rendering ────────────────────────────────────────────────────++ _addMessage(role, text, type = '') {+ if (role !== 'status') {+ this.messages.push({ role, text });+ }+ const messagesEl = this.panel.querySelector('#agent-messages');+ const msgEl = document.createElement('div');+ msgEl.className = `nich-message ${role}${type ? ' ' + type : ''}`;+ msgEl.textContent = text;+ messagesEl.appendChild(msgEl);+ messagesEl.scrollTop = messagesEl.scrollHeight;+ }++ // ── Dispose ───────────────────────────────────────────────────────────────++ dispose() {+ if (this.recognition) {+ try {+ this.recognition.stop();+ } catch {}+ }+ try {+ this.synth?.cancel();+ } catch {}+ this.panel?.remove();+ this.toggleBtn?.remove();+ }+}++function _escapeHTML(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}diff --git a/publish/src/onchain/README.md b/publish/src/onchain/README.mdnew file mode 100644index 000000000..4cc870d7b--- /dev/null+++ b/publish/src/onchain/README.md@@ -0,0 +1,339 @@+# src/onchain++Unified, family-agnostic on-chain deploy stack. Parallel to (and intended to+eventually supersede) `src/erc8004/deploy-button.js` + `src/erc8004/solana-deploy.js`.++## Why this exists++The legacy stack branches on chain family (`if isSolana ...`) at every layer:+deploy button, register-prep payload, agent_identities `meta` shape. Every new+chain family doubles the branching surface. This module collapses all of that+behind two abstractions:++- **`ChainRef`** — a CAIP-2-shaped value: `{ family, chainId | cluster }`. Every+ helper takes a `ChainRef`. Family-specific knowledge does not leak into the+ UI.+- **`WalletAdapter`** — `{ connect, switchTo, signAndSend }`. EVM and Solana+ adapters implement the same interface; the deploy orchestrator never sees+ `window.ethereum` or `window.phantom` directly.++## Layout++```+src/onchain/+├── chain-ref.js ChainRef + CAIP-2 + chain registry (pure)+├── adapters/+│ ├── base.js WalletAdapter abstract class + isUserRejection()+│ ├── evm.js ethers + window.ethereum+│ ├── solana.js @solana/web3.js + Phantom/Backpack/Solflare + inline SIWS+│ └── index.js getAdapter(family) factory with cache+├── deploy.js Unified prep → sign → confirm orchestrator+└── deploy-button.js Mountable UI component (drop-in for legacy)+```++## API surface (frontend)++```js+import { OnchainDeployButton } from 'src/onchain/deploy-button.js';++const btn = new OnchainDeployButton({+ agent, // { id, name, description?, avatarId?, onchain? }+ container: document.querySelector('#deploy'),+ preferredChain: 'eip155:8453', // CAIP-2; default Base mainnet+});+btn.mount();+```++Or, headless:++```js+import { deployAgent } from 'src/onchain/deploy.js';+import { evm, solana } from 'src/onchain/chain-ref.js';++const result = await deployAgent({+ agent,+ ref: solana('devnet'),+ onProgress: (step) => console.log(step), // 'connect'|'prep'|'sign'|'confirm'|'save'+});+// → { ref, txHash, onchainId, contractOrMint, agent }+```++## API surface (server)++Two endpoints — replace the four legacy ones:++| Endpoint | Purpose |+| --------------------------------- | ------------------------------------------------------- |+| `POST /api/agents/onchain/prep` | Pin manifest, build family-specific tx prep, return prepId |+| `POST /api/agents/onchain/confirm`| Verify tx on-chain, link wallet, write `meta.onchain` |++Request shape (prep):++```json+{+ "agent_id": "uuid",+ "chain": "eip155:8453",+ "wallet_address": "0x...",+ "name": "...",+ "description": "...",+ "avatar_id": "uuid|null",+ "skills": ["..."]+}+```++Response (prep): `{ prepId, chain, metadataUri, cid, contractAddress | { assetPubkey, txBase64, cluster } }`++Request shape (confirm):++```json+{+ "prep_id": "...",+ "tx_hash": "0x... | <base58 sig>",+ "onchain_id": "<EVM agentId> | null",+ "wallet_address": "..."+}+```++Confirm writes a single canonical block to `agent_identities.meta.onchain`:++```json+{+ "onchain": {+ "chain": "eip155:8453",+ "family": "evm",+ "tx_hash": "0x...",+ "onchain_id": "42",+ "contract_or_mint": "0x8004...",+ "wallet": "0x...",+ "metadata_uri": "ipfs://...",+ "confirmed_at": "2026-..."+ }+}+```++Frontend reads `agent.onchain` only — no family-specific fields.++## Migration++`api/_lib/migrations/2026-04-29-onchain-unified.sql` backfills legacy rows+(both EVM and Solana shapes) into `meta.onchain`. Idempotent. Apply via:++```bash+psql $DATABASE_URL -f api/_lib/migrations/2026-04-29-onchain-unified.sql+```++The legacy endpoints (`register-prep`, `register-confirm`,+`solana-register-prep`, `solana-register-confirm`) are left intact. Deprecate+once all callers move to `/api/agents/onchain/*`.++## Adding a new chain family++1. Add a `ChainRef` constructor + CAIP-2 namespace handling in `chain-ref.js`.+2. Add an entry helper to `buildRegistry()` so it appears in the dropdown.+3. Implement `WalletAdapter` for the family in `adapters/<name>.js`.+4. Wire the adapter into `getAdapter()` in `adapters/index.js`.+5. Add a `prep<Family>()` branch in `api/agents/onchain/prep.js` and a+ `verify<Family>()` branch in `api/agents/onchain/confirm.js`.++No UI changes required.++## Tests++`tests/src/onchain.test.js` — pure-logic coverage of `chain-ref` + adapter+factory dispatch. Wallet I/O is integration-tested via Playwright (not yet+written for this module — TODO).++## Token launches (Pump.fun, …)++Layered on top of the deploy stack. Same pattern: a `TokenAdapter` interface+under `src/onchain/tokens/` with one impl today (`PumpfunTokenAdapter`) and+two endpoints (`/api/agents/tokens/launch-prep` + `launch-confirm`) writing a+canonical `meta.token` block on the agent record:++```json+{+ "token": {+ "provider": "pumpfun",+ "mint": "<base58>",+ "symbol": "AGT",+ "name": "Agent",+ "metadata_uri": "ipfs://...",+ "cluster": "mainnet" | "devnet",+ "creator": "<base58>",+ "tx_signature": "<base58>",+ "launched_at": "2026-...",+ "pumpfun_url": "https://pump.fun/<mint>"+ }+}+```++Mounting:++```js+import { LaunchTokenButton } from 'src/onchain/launch-token-button.js';+new LaunchTokenButton({ agent, container }).mount();+```++The button auto-hides itself unless the agent is deployed on Solana. After a+launch, it rehydrates as a chip linking to the Pump.fun page (mainnet) or+Solana Explorer (devnet).++Schema migration: `api/_lib/migrations/2026-04-29-token-launches.sql`.++Pump.fun specifics:+- The mint Keypair is generated server-side and partial-signs the launch tx.+ Its secret key never touches the client and is dropped after partial-signing.+- Optional `initial_buy_sol` (0–50) buys the first slot on the bonding curve+ in the same transaction as the create.+- Compute budget is bumped to 350k units — coin creation routinely overflows+ the 200k default and reverts otherwise.+- Mainnet only after deploy. Devnet works for QA via Pump.fun's devnet-tagged+ SDK builds (`@pump-fun/pump-sdk@*-devnet.*`).++### Cost preview++`GET /api/agents/tokens/launch-quote?initial_buy_sol=0.5&cluster=mainnet` →+`{ fixed_total_sol, initial_buy: { tokens_out, protocol_fee_sol }, total_sol }`.+Returns conservative upper-bound rent costs + a live curve quote when an+initial buy is requested. Surface in any UI that asks the user to launch.++### Migrations++Apply migrations with the bundled runner:++```bash+DATABASE_URL=postgres://… node scripts/apply-migrations.mjs # dry-run+DATABASE_URL=postgres://… node scripts/apply-migrations.mjs --apply # execute+```++Tracks state in `schema_migrations` (filename + sha256). Refuses to proceed+if a previously-applied file has been edited after the fact (drift) — roll+forward with a new migration instead.++## Agent payments (Pump.fun agent-payments-sdk)++Layered on top of token launches. Same prep/sign/submit/confirm pattern.++Two flows:++- **Owner enables payments** — once the agent has a launched token, the owner+ signs a one-time `create` tx that registers the agent's TokenAgentPayments+ PDA. Persists `meta.payments` on the agent record.+- **Anyone pays the agent** — signed-in user picks a currency mint + amount,+ signs an `agent_accept_payment` tx, server verifies via the SDK's+ `validateInvoicePayment` and writes `agent_payment_intents.status='paid'`.++```js+import {+ EnablePaymentsButton,+ PayAgentButton,+} from 'src/onchain/payments-buttons.js';++new EnablePaymentsButton({ agent, container }).mount(); // owner-only+new PayAgentButton({ agent, container }).mount(); // any signed-in user+```++Endpoints: `/api/agents/payments/{create-prep,create-confirm,pay-prep,pay-confirm}`.+Schema: `payment_configs_pending` + `agent_payment_intents` (see migration+`2026-04-29-agent-payments.sql`).++`meta.payments` shape (returned at top level on `/api/agents/:id` as+`agent.payments` when configured):++```json+{+ "payments": {+ "configured": true,+ "provider": "pumpfun",+ "mint": "<token mint base58>",+ "token_agent_pda": "<TokenAgentPayments PDA base58>",+ "receiver": "<owner wallet base58>",+ "cluster": "mainnet" | "devnet",+ "tx_signature": "<base58>",+ "configured_at": "2026-...",+ "accepted_tokens": []+ }+}+```++## Vanity wallets (custodial agent identities)++Agents can be provisioned with a custodial Solana wallet whose address starts+with a chosen base58 prefix. The secret key is encrypted server-side+(AES-GCM, HKDF-derived from `JWT_SECRET`) and never leaves the server after+provisioning.++```js+import { VanityWalletButton } from 'src/onchain/vanity-wallet-button.js';+new VanityWalletButton({ agent, container }).mount();+```++Headless usage:++```js+import { provisionVanityForAgent } from 'src/onchain/vanity/index.js';+await provisionVanityForAgent({+ agentId,+ prefix: 'AGNT',+ ignoreCase: false,+ onProgress: ({ rate, eta }) => console.log(rate, eta),+});+```++Grinding happens client-side via Web Workers (one per logical core, capped+at 8). Long prefixes take time — pass an `AbortSignal` to support a Cancel+UX. Server-side grinding for 5+ char prefixes already exists in+`api/_lib/pump-vanity.js` and is wired into the legacy `pumpfun/launch`+flow.++The provisioning endpoint (`POST /api/agents/:id/solana`) verifies that the+submitted secret derives the claimed pubkey and that the prefix matches+before storing the encrypted secret.++## x402 (HTTP 402 Payment Required for paid skills)++Wires the agent payments layer to per-call paywalls. Any agent endpoint can+return `402 Payment Required` with a canonical manifest; clients pay via the+Pump.fun agent-payments flow and retry with `x-payment-intent`.++Server middleware:++```js+import { emit402, verifyPaid, consumeIntent } from 'api/_lib/x402.js';++const paid = await verifyPaid(req, {+ agentId, skill: 'summarize',+ expectedAmount: '10000',+ expectedCurrency: USDC_MINT,+});+if (!paid) return emit402(res, { agent, skill, amount, currency });+await consumeIntent(paid.intentId); // single-shot+return doTheThing();+```++Reference impl: `api/agents/x402/invoke.js` (paid-skill router with `echo`+demo skill). Manifest discovery at `GET /api/agents/x402/manifest`.++Client wrapper that follows 402 automatically:++```js+import { x402Fetch } from 'src/onchain/x402/client.js';+const res = await x402Fetch('/api/agents/x402/invoke', {+ method: 'POST',+ body: JSON.stringify({ agent_id, skill: 'echo', args: {} }),+ onPaymentRequired: () => 'auto',+});+```++Full spec at [docs/x402.md](../../docs/x402.md).++Note: the agent-payments-sdk is published as a restricted npm package. If+`npm install` fails with 403, contact Pump.fun for access. The pump-sdk used+for token launches is public and unaffected.++Adding another launchpad:+1. Implement `TokenAdapter` in `src/onchain/tokens/<provider>.js`.+2. Add to `getTokenAdapter()` in `src/onchain/tokens/index.js`.+3. Branch on `provider` in `api/agents/tokens/launch-prep.js`.+4. UI auto-extends if you make the dropdown provider-aware (single provider+ today, no dropdown).diff --git a/publish/src/onchain/adapters/base.js b/publish/src/onchain/adapters/base.jsnew file mode 100644index 000000000..c0d0ab900--- /dev/null+++ b/publish/src/onchain/adapters/base.js@@ -0,0 +1,90 @@+/**+ * WalletAdapter — the contract every chain family implements.+ *+ * The deploy orchestrator only ever sees this interface. New chains plug in by+ * adding a new adapter; the UI stays family-agnostic.+ */++/**+ * @typedef {object} ConnectResult+ * @property {string} address User's wallet address (hex for EVM, base58 for Solana).+ * @property {import('../chain-ref.js').ChainRef} ref Chain the wallet is currently on.+ */++/**+ * @typedef {object} PrepResponse+ * @property {string} prepId+ * @property {string} metadataUri // ipfs:// or https:// pointing at the manifest+ * @property {string} [contractAddress] // EVM: identity-registry address+ * @property {string} [txBase64] // Solana: serialized unsigned tx+ * @property {string} [assetPubkey] // Solana: mint pubkey+ * @property {string} [chainCaip2]+ */++/**+ * @typedef {object} SignResult+ * @property {string} txHash // EVM tx hash or Solana signature+ * @property {string} [onchainId] // Optional family-specific ID (EVM agentId, Solana asset)+ */++/**+ * @abstract+ */+export class WalletAdapter {+ /** @returns {string} 'evm' | 'solana' */+ get family() {+ throw new Error('not implemented');+ }++ /** @returns {boolean} Whether an injected provider is detectable. */+ isAvailable() {+ throw new Error('not implemented');+ }++ /** @returns {string} URL to install a typical wallet for this family. */+ installUrl() {+ throw new Error('not implemented');+ }++ /**+ * Connect (and on-Solana, optionally SIWS-link) the user's wallet.+ * Implementations must throw on user rejection with `err.code === 'USER_REJECTED'`.+ * @param {{ ensureLinked?: boolean, csrfToken?: string }} [opts]+ * @returns {Promise<ConnectResult>}+ */+ async connect(_opts) {+ throw new Error('not implemented');+ }++ /**+ * Switch the wallet to the given ChainRef. EVM wallets prompt the user;+ * Solana wallets typically have no concept of switching — adapters return+ * silently if already on the right cluster, or throw if mismatched.+ * @param {import('../chain-ref.js').ChainRef} ref+ */+ async switchTo(_ref) {+ throw new Error('not implemented');+ }++ /**+ * Sign and submit the prep transaction returned by the server.+ * @param {PrepResponse} prep+ * @param {import('../chain-ref.js').ChainRef} ref+ * @returns {Promise<SignResult>}+ */+ async signAndSend(_prep, _ref) {+ throw new Error('not implemented');+ }+}++/** Helper: classify a thrown error as a user rejection across providers. */+export function isUserRejection(err) {+ if (!err) return false;+ if (err.code === 'USER_REJECTED') return true;+ if (err.code === 4001) return true;+ if (err.code === 'ACTION_REJECTED') return true;+ const msg = String(err.message || err).toLowerCase();+ return /user rejected|user denied|rejected by user|user cancel|signature cancel|connection cancel/.test(+ msg,+ );+}diff --git a/publish/src/onchain/adapters/evm.js b/publish/src/onchain/adapters/evm.jsnew file mode 100644index 000000000..3bfcd4694--- /dev/null+++ b/publish/src/onchain/adapters/evm.js@@ -0,0 +1,73 @@+/**+ * EvmAdapter — wraps an injected EIP-1193 provider (MetaMask, Brave, Rabby…).+ *+ * Reuses the existing ethers integration in src/erc8004/agent-registry.js so we+ * don't fork wallet state. The adapter is a thin facade over those helpers.+ */++import { WalletAdapter } from './base.js';+import { ensureWallet, getIdentityRegistry } from '../../erc8004/agent-registry.js';+import { switchChain, CHAIN_META } from '../../erc8004/chain-meta.js';+import { evm } from '../chain-ref.js';++export class EvmAdapter extends WalletAdapter {+ get family() {+ return 'evm';+ }++ isAvailable() {+ return typeof window !== 'undefined' && !!window.ethereum;+ }++ installUrl() {+ return 'https://metamask.io/download/';+ }++ async connect() {+ const { signer, chainId } = await ensureWallet();+ const address = await signer.getAddress();+ return { address, ref: evm(chainId) };+ }++ async switchTo(ref) {+ if (ref.family !== 'evm') {+ throw new Error('EvmAdapter cannot switch to non-EVM chain');+ }+ await switchChain(ref.chainId);+ }++ async signAndSend(prep, ref) {+ if (ref.family !== 'evm') throw new Error('EvmAdapter expects an EVM ChainRef');+ const { signer } = await ensureWallet();+ const registry = getIdentityRegistry(ref.chainId, signer);++ const tx = await registry['register(string)'](prep.metadataUri);+ const receipt = await tx.wait();+ if (receipt?.status !== 1) {+ const e = new Error('EVM transaction reverted');+ e.code = 'TX_REVERTED';+ throw e;+ }++ // Pull the agentId out of the Registered event for cross-checking server-side.+ let onchainId = null;+ for (const log of receipt.logs || []) {+ try {+ const parsed = registry.interface.parseLog(log);+ if (parsed?.name === 'Registered') {+ onchainId = String(parsed.args.agentId);+ break;+ }+ } catch {+ /* not our event */+ }+ }++ return { txHash: tx.hash, onchainId };+ }++ /** @param {number} chainId */+ chainName(chainId) {+ return CHAIN_META[chainId]?.name || `Chain ${chainId}`;+ }+}diff --git a/publish/src/onchain/adapters/index.js b/publish/src/onchain/adapters/index.jsnew file mode 100644index 000000000..b63235fc1--- /dev/null+++ b/publish/src/onchain/adapters/index.js@@ -0,0 +1,32 @@+/**+ * Adapter factory — pick the right WalletAdapter for a ChainRef family.+ *+ * Adapters are stateful (they hold the wallet provider handle), so callers+ * generally hold one instance per family for the lifetime of the page.+ */++import { EvmAdapter } from './evm.js';+import { SolanaAdapter } from './solana.js';++const cache = new Map();++/**+ * @param {'evm'|'solana'} family+ * @returns {import('./base.js').WalletAdapter}+ */+export function getAdapter(family) {+ if (cache.has(family)) return cache.get(family);+ let inst;+ if (family === 'evm') inst = new EvmAdapter();+ else if (family === 'solana') inst = new SolanaAdapter();+ else throw new Error(`No adapter for chain family: ${family}`);+ cache.set(family, inst);+ return inst;+}++/** Test hook — forget cached adapters. */+export function _resetAdapters() {+ cache.clear();+}++export { isUserRejection } from './base.js';diff --git a/publish/src/onchain/adapters/solana.js b/publish/src/onchain/adapters/solana.jsnew file mode 100644index 000000000..b51ef9c6c--- /dev/null+++ b/publish/src/onchain/adapters/solana.js@@ -0,0 +1,245 @@+/**+ * SolanaAdapter — Phantom / Backpack / Solflare via window injection.+ *+ * Two responsibilities the EVM adapter doesn't have:+ * 1. Inline SIWS linking. If the wallet isn't yet linked to the user's+ * account, this adapter runs the SIWS challenge as part of `connect()` so+ * the deploy flow stays single-click. Implementation mirrors+ * public/wallet/connect-button-solana.js but is callable headlessly.+ * 2. Cluster control. We always submit the signed tx through a Connection we+ * construct on the chosen cluster, never via the wallet's+ * signAndSendTransaction default — the wallet's RPC may be on a different+ * cluster than the one the user picked in the UI.+ */++import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';+import { WalletAdapter } from './base.js';+import { solana } from '../chain-ref.js';++const RPC = {+ mainnet: 'https://api.mainnet-beta.solana.com',+ devnet: 'https://api.devnet.solana.com',+};++function detect(preferred) {+ if (typeof window === 'undefined') return null;+ if (preferred === 'phantom') return window.phantom?.solana || window.solana || null;+ if (preferred === 'backpack') return window.backpack?.solana || null;+ if (preferred === 'solflare') return window.solflare || null;+ if (window.phantom?.solana?.isPhantom) return window.phantom.solana;+ if (window.solana?.isPhantom) return window.solana;+ if (window.backpack?.solana) return window.backpack.solana;+ if (window.solflare?.isSolflare) return window.solflare;+ return null;+}++function toBase64(bytes) {+ let s = '';+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);+ return btoa(s);+}++function decodeTx(b64) {+ const bin = atob(b64);+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ try {+ return VersionedTransaction.deserialize(bytes);+ } catch {+ return Transaction.from(bytes);+ }+}++export class SolanaAdapter extends WalletAdapter {+ #provider = null;+ #address = null;+ #preferred;++ constructor({ preferredWallet = null } = {}) {+ super();+ this.#preferred = preferredWallet;+ }++ get family() {+ return 'solana';+ }++ isAvailable() {+ return !!detect(this.#preferred);+ }++ installUrl() {+ if (this.#preferred === 'backpack') return 'https://www.backpack.app';+ if (this.#preferred === 'solflare') return 'https://solflare.com';+ return 'https://phantom.app';+ }++ /**+ * Connect, and if the wallet isn't linked to the current session, run SIWS+ * inline so the caller doesn't have to redirect the user.+ * @param {{ ensureLinked?: boolean, cluster?: 'mainnet'|'devnet' }} [opts]+ */+ async connect({ ensureLinked = true, cluster = 'mainnet' } = {}) {+ const provider = detect(this.#preferred);+ if (!provider) {+ const err = new Error('No Solana wallet detected.');+ err.code = 'NO_PROVIDER';+ throw err;+ }+ this.#provider = provider;++ let resp;+ try {+ resp = await provider.connect();+ } catch (e) {+ if (e?.code === 4001 || /reject/i.test(e?.message || '')) {+ const err = new Error('Connection cancelled.');+ err.code = 'USER_REJECTED';+ throw err;+ }+ throw e;+ }+ this.#address = (resp?.publicKey || provider.publicKey)?.toString();+ if (!this.#address) throw new Error('Could not read Solana wallet address.');++ if (ensureLinked) {+ await this.#ensureLinkedViaSiws(cluster);+ }++ return { address: this.#address, ref: solana(cluster) };+ }++ async switchTo(ref) {+ // Solana wallets don't expose a switchCluster RPC. We respect the user's+ // selection by sending the tx to our own Connection on the chosen+ // cluster (see signAndSend). Nothing to do here.+ if (ref.family !== 'solana') throw new Error('SolanaAdapter cannot switch to non-Solana');+ }++ async signAndSend(prep, ref) {+ if (ref.family !== 'solana') throw new Error('SolanaAdapter expects a Solana ChainRef');+ if (!this.#provider) throw new Error('Wallet not connected');+ if (!prep.txBase64) throw new Error('Solana prep missing txBase64');++ const tx = decodeTx(prep.txBase64);+ const conn = new Connection(RPC[ref.cluster], 'confirmed');++ // Always go through signTransaction + our own Connection so we control+ // which cluster the tx lands on. Avoids the silent mismatch where+ // Phantom is set to mainnet but the user picked devnet (or vice versa).+ let signed;+ try {+ signed = await this.#provider.signTransaction(tx);+ } catch (e) {+ if (e?.code === 4001 || /reject/i.test(e?.message || '')) {+ const err = new Error('Signature cancelled.');+ err.code = 'USER_REJECTED';+ throw err;+ }+ throw e;+ }++ const raw = signed.serialize();+ const signature = await conn.sendRawTransaction(raw, {+ skipPreflight: false,+ preflightCommitment: 'confirmed',+ });++ // Poll signature status with a real deadline. confirmTransaction is+ // deprecated and unreliable on devnet.+ await this.#waitForConfirmation(conn, signature, 60_000);++ return { txHash: signature, onchainId: prep.assetPubkey || null };+ }++ async #waitForConfirmation(conn, signature, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const { value } = await conn.getSignatureStatuses([signature]);+ const status = value?.[0];+ if (status) {+ if (status.err) {+ const e = new Error(`Tx failed: ${JSON.stringify(status.err)}`);+ e.code = 'TX_FAILED';+ throw e;+ }+ if (+ status.confirmationStatus === 'confirmed' ||+ status.confirmationStatus === 'finalized'+ ) {+ return;+ }+ }+ await new Promise((r) => setTimeout(r, 1_000));+ }+ const e = new Error('Confirmation timed out after 60s. Tx may still land — check explorer.');+ e.code = 'TX_TIMEOUT';+ throw e;+ }++ async #ensureLinkedViaSiws(cluster) {+ // Cheap pre-check: if already linked for this user+address, skip the+ // signature prompt. Uses an existing endpoint that returns 200 if the+ // session has any linked Solana wallet, 404 otherwise. We tolerate any+ // non-200 here and fall through to the SIWS path.+ try {+ const r = await fetch(+ `/api/auth/wallets/check?chain_type=solana&address=${encodeURIComponent(this.#address)}`,+ { credentials: 'include' },+ );+ if (r.ok) {+ const data = await r.json().catch(() => ({}));+ if (data?.linked) return;+ }+ } catch {+ /* non-fatal — proceed with SIWS */+ }++ const nonceRes = await fetch('/api/auth/siws/nonce', { credentials: 'include' });+ if (!nonceRes.ok) throw new Error('Could not start wallet linking: nonce request failed.');+ const { nonce, csrf } = await nonceRes.json();++ const domain = location.host;+ const uri = location.origin;+ const issuedAt = new Date().toISOString();+ const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();+ const message = [+ `${domain} wants you to sign in with your Solana account:`,+ this.#address,+ '',+ 'Link this wallet to deploy your agent on Solana. No fees, no transaction.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${cluster}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ `Expiration Time: ${expirationTime}`,+ ].join('\n');++ const msgBytes = new TextEncoder().encode(message);+ let sig;+ try {+ const out = await this.#provider.signMessage(msgBytes, 'utf8');+ sig = out.signature;+ } catch (e) {+ if (e?.code === 4001 || /reject/i.test(e?.message || '')) {+ const err = new Error('Wallet linking cancelled.');+ err.code = 'USER_REJECTED';+ throw err;+ }+ throw e;+ }++ const verifyRes = await fetch('/api/auth/siws/verify', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },+ body: JSON.stringify({ message, signature: toBase64(sig) }),+ });+ if (!verifyRes.ok) {+ const data = await verifyRes.json().catch(() => ({}));+ throw new Error(data.error_description || 'Wallet linking failed.');+ }+ }+}diff --git a/publish/src/onchain/chain-ref.js b/publish/src/onchain/chain-ref.jsnew file mode 100644index 000000000..381d00fee--- /dev/null+++ b/publish/src/onchain/chain-ref.js@@ -0,0 +1,153 @@+/**+ * ChainRef — a single, comparable, serializable reference to "what chain."+ *+ * Replaces the dual world of (number EVM chainId) vs (sentinel strings like+ * 'solana-devnet'). Every onchain helper takes a ChainRef; family-specific+ * branching happens in adapters, not in the UI.+ *+ * Wire format is CAIP-2-shaped. CAIP-2 references for Solana are the+ * genesis-hash prefix; we use the well-known short prefixes published in the+ * spec so that the same string round-trips through DBs, URLs, and registries.+ *+ * Examples:+ * 'eip155:1' Ethereum mainnet+ * 'eip155:8453' Base mainnet+ * 'eip155:84532' Base Sepolia+ * 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' Solana mainnet-beta+ * 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1' Solana devnet+ */++/** @typedef {{ namespace: 'eip155', chainId: number, family: 'evm' }} EvmChainRef */+/** @typedef {{ namespace: 'solana', cluster: 'mainnet'|'devnet', family: 'solana' }} SolanaChainRef */+/** @typedef {EvmChainRef|SolanaChainRef} ChainRef */++// CAIP-2 references for Solana per https://chainagnostic.org/CAIPs/caip-2.+const SOLANA_REFS = {+ mainnet: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ devnet: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1',+};+const SOLANA_REF_TO_CLUSTER = Object.fromEntries(+ Object.entries(SOLANA_REFS).map(([k, v]) => [v, k]),+);++/** @param {number} chainId @returns {EvmChainRef} */+export function evm(chainId) {+ if (!Number.isInteger(chainId) || chainId <= 0) {+ throw new TypeError(`evm(): chainId must be a positive integer, got ${chainId}`);+ }+ return { namespace: 'eip155', chainId, family: 'evm' };+}++/** @param {'mainnet'|'devnet'} cluster @returns {SolanaChainRef} */+export function solana(cluster) {+ if (cluster !== 'mainnet' && cluster !== 'devnet') {+ throw new TypeError(`solana(): cluster must be 'mainnet' or 'devnet', got ${cluster}`);+ }+ return { namespace: 'solana', cluster, family: 'solana' };+}++/** @param {ChainRef} ref @returns {string} CAIP-2 string */+export function toCaip2(ref) {+ if (ref.family === 'evm') return `eip155:${ref.chainId}`;+ if (ref.family === 'solana') return `solana:${SOLANA_REFS[ref.cluster]}`;+ throw new TypeError(`Unknown ChainRef family: ${ref?.family}`);+}++/** @param {string} caip2 @returns {ChainRef} */+export function fromCaip2(caip2) {+ if (typeof caip2 !== 'string') throw new TypeError('fromCaip2 expects a string');+ const [ns, ref] = caip2.split(':');+ if (ns === 'eip155') return evm(Number(ref));+ if (ns === 'solana') {+ const cluster = SOLANA_REF_TO_CLUSTER[ref];+ if (!cluster) throw new Error(`Unknown solana ref: ${ref}`);+ return solana(cluster);+ }+ throw new Error(`Unsupported namespace: ${ns}`);+}++/** @param {ChainRef} a @param {ChainRef} b */+export function eqRef(a, b) {+ if (!a || !b) return false;+ return toCaip2(a) === toCaip2(b);+}++/** @param {ChainRef} ref */+export function familyOf(ref) {+ return ref.family;+}++// ── Registry of supported chains for the deploy UI ──────────────────────────+//+// This is the source-of-truth list the dropdown reads from. EVM entries point+// at the legacy CHAIN_META + REGISTRY_DEPLOYMENTS tables for backwards compat;+// new chains added here automatically appear in the picker.++/**+ * @typedef {{+ * ref: ChainRef,+ * name: string,+ * shortName: string,+ * testnet: boolean,+ * explorerTx: (sigOrHash: string) => string,+ * explorerAddress: (addr: string) => string,+ * }} ChainEntry+ */++const SOLANA_ENTRIES = {+ mainnet: {+ ref: solana('mainnet'),+ name: 'Solana',+ shortName: 'SOL',+ testnet: false,+ explorerTx: (sig) => `https://solscan.io/tx/${sig}`,+ explorerAddress: (addr) => `https://solscan.io/account/${addr}`,+ },+ devnet: {+ ref: solana('devnet'),+ name: 'Solana Devnet',+ shortName: 'SOLdev',+ testnet: true,+ explorerTx: (sig) => `https://explorer.solana.com/tx/${sig}?cluster=devnet`,+ explorerAddress: (addr) => `https://explorer.solana.com/address/${addr}?cluster=devnet`,+ },+};++/**+ * Build the registry by combining EVM chains from the legacy meta table with+ * the Solana entries above. Pure function — no I/O.+ *+ * @param {Record<number, { name: string, shortName: string, explorer: string, testnet: boolean }>} evmMeta+ * @param {Record<number, unknown>} evmDeployments Used as the gate for EVM inclusion+ * @returns {ChainEntry[]}+ */+export function buildRegistry(evmMeta, evmDeployments) {+ const entries = [];+ for (const [idStr, meta] of Object.entries(evmMeta || {})) {+ const id = Number(idStr);+ if (!evmDeployments?.[id]) continue;+ entries.push({+ ref: evm(id),+ name: meta.name,+ shortName: meta.shortName,+ testnet: !!meta.testnet,+ explorerTx: (h) => `${meta.explorer}/tx/${h}`,+ explorerAddress: (a) => `${meta.explorer}/address/${a}`,+ });+ }+ entries.push(SOLANA_ENTRIES.mainnet, SOLANA_ENTRIES.devnet);+ return entries;+}++/** @param {ChainEntry[]} reg @returns {{ mainnets: ChainEntry[], testnets: ChainEntry[] }} */+export function groupRegistry(reg) {+ const mainnets = [];+ const testnets = [];+ for (const e of reg) (e.testnet ? testnets : mainnets).push(e);+ return { mainnets, testnets };+}++/** @param {ChainEntry[]} reg @param {string} caip2 */+export function entryByCaip2(reg, caip2) {+ return reg.find((e) => toCaip2(e.ref) === caip2) || null;+}diff --git a/publish/src/onchain/deploy-button.js b/publish/src/onchain/deploy-button.jsnew file mode 100644index 000000000..40914f9f8--- /dev/null+++ b/publish/src/onchain/deploy-button.js@@ -0,0 +1,213 @@+/**+ * OnchainDeployButton — drop-in replacement for src/erc8004/deploy-button.js.+ *+ * Differences:+ * • Reads chain entries from chain-ref.js registry (CAIP-2 keyed) — Solana,+ * EVM, and any future family share one dropdown without sentinel strings.+ * • Delegates everything wallet-shaped to the adapter layer.+ * • Rehydrates the success chip from `agent.onchain` (the unified shape+ * returned by /api/agents/:id and persisted by the new confirm endpoint),+ * so a page reload shows the deployed state regardless of family.+ *+ * Mounting:+ * const btn = new OnchainDeployButton({ agent, container });+ * btn.mount();+ */++import { CHAIN_META } from '../erc8004/chain-meta.js';+import { REGISTRY_DEPLOYMENTS } from '../erc8004/abi.js';+import {+ buildRegistry,+ groupRegistry,+ entryByCaip2,+ toCaip2,+ fromCaip2,+ evm,+} from './chain-ref.js';+import { deployAgent } from './deploy.js';+import { isUserRejection } from './adapters/index.js';++const DEFAULT_REF_CAIP2 = 'eip155:8453'; // Base mainnet++const STEP_LABELS = {+ connect: 'Connecting wallet',+ prep: 'Preparing manifest',+ sign: 'Sign tx',+ confirm: 'Confirming on-chain',+ save: 'Saving',+};+const STEP_ORDER = ['connect', 'prep', 'sign', 'confirm', 'save'];++function _esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++export class OnchainDeployButton {+ /**+ * @param {object} opts+ * @param {object} opts.agent+ * @param {HTMLElement} opts.container+ * @param {string} [opts.preferredChain] CAIP-2 string. Defaults to Base mainnet.+ */+ constructor({ agent, container, preferredChain = DEFAULT_REF_CAIP2 }) {+ this._agent = agent;+ this._container = container;+ this._registry = buildRegistry(CHAIN_META, REGISTRY_DEPLOYMENTS);+ this._refCaip2 = preferredChain;+ this._root = null;+ }++ mount() {+ this._root = document.createElement('div');+ this._root.className = 'deploy-button-root';+ this._container.appendChild(this._root);+ this._render();+ }++ unmount() {+ this._root?.remove();+ this._root = null;+ }++ // ── Render ─────────────────────────────────────────────────────────────++ _render() {+ if (!this._root) return;+ const onchain = this._agent.onchain;+ if (onchain?.txHash && onchain?.chain) {+ const entry = entryByCaip2(this._registry, onchain.chain);+ if (entry) {+ this._renderSuccessChip(entry, onchain.txHash, onchain.contractOrMint);+ return;+ }+ }+ const entry = entryByCaip2(this._registry, this._refCaip2);+ if (!entry) {+ this._renderDisabled('Selected chain is not configured');+ return;+ }+ this._renderDeployButton();+ }++ _renderDeployButton() {+ const { mainnets, testnets } = groupRegistry(this._registry);+ const optsHtml = (entries) =>+ entries+ .map((e) => {+ const c = toCaip2(e.ref);+ return `<option value="${_esc(c)}"${c === this._refCaip2 ? ' selected' : ''}>${_esc(e.name)}</option>`;+ })+ .join('');++ this._root.innerHTML = `+ <div class="deploy-chain-row">+ <select class="deploy-chain-select" aria-label="Target chain">+ <optgroup label="Mainnets">${optsHtml(mainnets)}</optgroup>+ <optgroup label="Testnets">${optsHtml(testnets)}</optgroup>+ </select>+ <button class="deploy-btn" title="Deploy this agent on-chain">+ ⬢ Deploy on-chain+ </button>+ </div>+ `;+ const sel = this._root.querySelector('.deploy-chain-select');+ sel.addEventListener('change', (ev) => {+ this._refCaip2 = ev.target.value;+ });+ this._root.querySelector('.deploy-btn').addEventListener('click', () => this._start());+ }++ _renderDisabled(msg) {+ this._root.innerHTML = `+ <button class="deploy-btn deploy-btn--disabled" disabled title="${_esc(msg)}">+ ⬢ Deploy on-chain+ </button>+ <span class="deploy-tooltip">${_esc(msg)}</span>+ `;+ }++ _renderProgress(activeStep) {+ const idx = STEP_ORDER.indexOf(activeStep);+ const html = STEP_ORDER.map((s, i) => {+ const cls = i < idx ? 'done' : i === idx ? 'active' : 'pending';+ return `<span class="progress-step progress-step--${cls}">${_esc(STEP_LABELS[s])}</span>`;+ }).join('<span class="progress-sep" aria-hidden="true">→</span>');+ this._root.innerHTML = `+ <div class="deploy-progress" role="status" aria-live="polite">+ ${html}+ </div>+ `;+ }++ _renderError(msg, action) {+ const actionHtml = action+ ? `<button class="deploy-action-btn">${_esc(action.label)}</button>`+ : '<button class="deploy-action-btn deploy-action-btn--reset">Try again</button>';+ this._root.innerHTML = `+ <div class="deploy-error" role="alert">+ <span class="deploy-error-msg">${_esc(msg)}</span>+ ${actionHtml}+ </div>+ `;+ const btn = this._root.querySelector('.deploy-action-btn');+ btn.addEventListener('click', action ? action.handler : () => this._renderDeployButton());+ }++ _renderSuccessChip(entry, txHash, contractOrMint) {+ // Prefer the tx explorer link — it survives across chains and works for+ // both EVM (tx hash) and Solana (signature).+ const url = entry.explorerTx(txHash);+ this._root.innerHTML = `+ <a class="deploy-chip deploy-chip--success" href="${_esc(url)}" target="_blank" rel="noopener noreferrer"+ aria-label="View on ${_esc(entry.name)} explorer">+ ⬢ On-chain on ${_esc(entry.name)} · view on explorer+ </a>+ `;+ }++ // ── Drive ──────────────────────────────────────────────────────────────++ async _start() {+ let ref;+ try {+ ref = fromCaip2(this._refCaip2);+ } catch (e) {+ this._renderError(`Invalid chain: ${e.message}`);+ return;+ }++ try {+ const result = await deployAgent({+ agent: this._agent,+ ref,+ onProgress: (step) => this._renderProgress(step),+ });+ this._agent.onchain = {+ chain: toCaip2(result.ref),+ txHash: result.txHash,+ onchainId: result.onchainId,+ contractOrMint: result.contractOrMint,+ };+ const entry = entryByCaip2(this._registry, this._refCaip2);+ this._renderSuccessChip(entry, result.txHash, result.contractOrMint);+ } catch (err) {+ if (isUserRejection(err)) return this._renderDeployButton();+ if (err.code === 'NO_PROVIDER') {+ this._renderError(err.message, {+ label: 'Install wallet',+ handler: () => window.open(err.installUrl, '_blank', 'noopener'),+ });+ return;+ }+ this._renderError(err.message || 'Deploy failed.');+ }+ }+}++// Re-export building blocks for callers that want to compose differently.+export { evm, fromCaip2, toCaip2 } from './chain-ref.js';+export { deployAgent } from './deploy.js';diff --git a/publish/src/onchain/deploy.js b/publish/src/onchain/deploy.jsnew file mode 100644index 000000000..2aa4ffa83--- /dev/null+++ b/publish/src/onchain/deploy.js@@ -0,0 +1,142 @@+/**+ * Unified deploy orchestrator.+ *+ * Drives the prep → sign → confirm pipeline against the new unified API+ * (`/api/agents/onchain/prep` + `/api/agents/onchain/confirm`). Family-specific+ * details (EVM ABI calls, Solana tx submission, SIWS linking) live in the+ * WalletAdapter. This module owns:+ *+ * • Prep idempotency (caches `prepId` per agent + chain so retries don't+ * re-pin metadata or rebuild a fresh Solana mint keypair).+ * • Progress callbacks for UI to render step state.+ * • Error normalization (USER_REJECTED short-circuits cleanly).+ */++import { getAdapter } from './adapters/index.js';+import { toCaip2 } from './chain-ref.js';++const PREP_CACHE_TTL_MS = 50 * 60 * 1000; // server keeps prep 60m++function prepCacheKey(agentId, ref) {+ return `3dagent:onchain-prep:${agentId}:${toCaip2(ref)}`;+}++async function getOrCreatePrep(agent, ref, walletAddress) {+ const key = prepCacheKey(agent.id, ref);+ try {+ const raw = localStorage.getItem(key);+ if (raw) {+ const cached = JSON.parse(raw);+ if (cached?.prepId && cached?.expiresAt > Date.now()) return cached;+ }+ } catch {+ /* fall through */+ }++ const body = {+ agent_id: agent.id,+ chain: toCaip2(ref),+ wallet_address: walletAddress,+ name: agent.name || 'Agent',+ description: agent.description || '',+ avatar_id: agent.avatarId || agent.avatar_id || null,+ skills: Array.isArray(agent.skills) && agent.skills.length ? agent.skills : undefined,+ };+ const resp = await fetch('/api/agents/onchain/prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ if (!resp.ok) {+ const data = await resp.json().catch(() => ({}));+ const err = new Error(data.error_description || `prep returned ${resp.status}`);+ err.status = resp.status;+ err.code = data.error;+ throw err;+ }+ const prep = await resp.json();+ const cached = { ...prep, expiresAt: Date.now() + PREP_CACHE_TTL_MS };+ try {+ localStorage.setItem(key, JSON.stringify(cached));+ } catch {+ /* quota — fine */+ }+ return cached;+}++function clearPrepCache(agentId, ref) {+ try {+ localStorage.removeItem(prepCacheKey(agentId, ref));+ } catch {+ /* ignore */+ }+}++/**+ * @param {object} opts+ * @param {{ id: string, name: string, [k: string]: any }} opts.agent+ * @param {import('./chain-ref.js').ChainRef} opts.ref+ * @param {(step: 'connect'|'prep'|'sign'|'confirm'|'save', detail?: object) => void} [opts.onProgress]+ * @returns {Promise<{ ref: import('./chain-ref.js').ChainRef, txHash: string, onchainId: string|null, contractOrMint: string|null, agent: object }>}+ */+export async function deployAgent({ agent, ref, onProgress = () => {} }) {+ if (!agent?.id) throw new Error('agent.id is required');++ const adapter = getAdapter(ref.family);+ if (!adapter.isAvailable()) {+ const err = new Error(`No ${ref.family.toUpperCase()} wallet detected.`);+ err.code = 'NO_PROVIDER';+ err.installUrl = adapter.installUrl();+ throw err;+ }++ onProgress('connect');+ const { address, ref: walletRef } = await adapter.connect({+ ensureLinked: true,+ cluster: ref.family === 'solana' ? ref.cluster : undefined,+ });++ if (ref.family === 'evm' && walletRef.family === 'evm' && walletRef.chainId !== ref.chainId) {+ await adapter.switchTo(ref);+ }++ onProgress('prep');+ const prep = await getOrCreatePrep(agent, ref, address);++ onProgress('sign');+ const sig = await adapter.signAndSend(prep, ref);++ onProgress('confirm');+ const confirmResp = await fetch('/api/agents/onchain/confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ prep_id: prep.prepId,+ tx_hash: sig.txHash,+ onchain_id: sig.onchainId || null,+ wallet_address: address,+ }),+ });+ if (!confirmResp.ok) {+ const data = await confirmResp.json().catch(() => ({}));+ const err = new Error(data.error_description || `confirm returned ${confirmResp.status}`);+ err.status = confirmResp.status;+ err.code = data.error;+ err.txHash = sig.txHash;+ throw err;+ }+ const result = await confirmResp.json();++ onProgress('save');+ clearPrepCache(agent.id, ref);++ return {+ ref,+ txHash: sig.txHash,+ onchainId: sig.onchainId,+ contractOrMint: prep.contractAddress || prep.assetPubkey || null,+ agent: result.agent,+ };+}diff --git a/publish/src/onchain/launch-token-button.js b/publish/src/onchain/launch-token-button.jsnew file mode 100644index 000000000..d4cedd67c--- /dev/null+++ b/publish/src/onchain/launch-token-button.js@@ -0,0 +1,223 @@+/**+ * LaunchTokenButton — UI for launching an agent's Pump.fun token.+ *+ * Mounting contract:+ * const btn = new LaunchTokenButton({ agent, container });+ * btn.mount();+ *+ * Visibility:+ * • If agent already has a launched token → renders a chip linking to it.+ * • If agent isn't deployed on Solana → renders disabled with tooltip.+ * • Otherwise → renders the launch button.+ */++import { getTokenAdapter } from './tokens/index.js';+import { isUserRejection } from './adapters/index.js';++function _esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++export class LaunchTokenButton {+ /**+ * @param {object} opts+ * @param {object} opts.agent+ * @param {HTMLElement} opts.container+ * @param {string} [opts.provider] Defaults to 'pumpfun'.+ */+ constructor({ agent, container, provider = 'pumpfun' }) {+ this._agent = agent;+ this._container = container;+ this._provider = provider;+ this._adapter = getTokenAdapter(provider);+ this._root = null;+ }++ mount() {+ this._root = document.createElement('div');+ this._root.className = 'launch-token-root';+ this._container.appendChild(this._root);+ this._render();+ }++ unmount() {+ this._root?.remove();+ this._root = null;+ }++ _render() {+ if (!this._root) return;+ const token = this._agent.token || this._agent.meta?.token;+ if (token?.mint) return this._renderChip(token);++ const pre = this._adapter.validatePreconditions({ agent: this._agent });+ if (!pre.ok) return this._renderDisabled(pre.reason);++ this._renderLaunchButton();+ }++ _renderLaunchButton() {+ this._root.innerHTML = `+ <button class="launch-token-btn" title="Launch this agent's token on Pump.fun">+ 🚀 Launch token+ </button>+ `;+ this._root.querySelector('.launch-token-btn').addEventListener('click', () => this._openModal());+ }++ _renderDisabled(reason) {+ this._root.innerHTML = `+ <button class="launch-token-btn launch-token-btn--disabled" disabled title="${_esc(reason)}">+ 🚀 Launch token+ </button>+ <span class="launch-token-tooltip">${_esc(reason)}</span>+ `;+ }++ _renderChip(token) {+ const url = token.pumpfun_url || token.explorer_url || '#';+ this._root.innerHTML = `+ <a class="launch-token-chip" href="${_esc(url)}" target="_blank" rel="noopener noreferrer"+ aria-label="View ${_esc(token.symbol)} on Pump.fun">+ 🚀 $${_esc(token.symbol)} · view on ${_esc(token.cluster === 'devnet' ? 'explorer' : 'pump.fun')}+ </a>+ `;+ }++ _renderProgress(step) {+ const labels = {+ connect: 'Connecting wallet…',+ prep: 'Preparing launch…',+ sign: 'Sign in your wallet…',+ submit: 'Submitting on-chain…',+ confirm: 'Saving…',+ };+ this._root.innerHTML = `+ <div class="launch-token-progress" role="status" aria-live="polite">+ ${_esc(labels[step] || step)}+ </div>+ `;+ }++ _renderError(msg) {+ this._root.innerHTML = `+ <div class="launch-token-error" role="alert">+ <span>${_esc(msg)}</span>+ <button class="launch-token-retry">Try again</button>+ </div>+ `;+ this._root.querySelector('.launch-token-retry').addEventListener('click', () => this._render());+ }++ _openModal() {+ // Inline lightweight modal — keeps this component self-contained.+ const overlay = document.createElement('div');+ overlay.className = 'launch-token-modal-overlay';+ overlay.innerHTML = `+ <div class="launch-token-modal" role="dialog" aria-label="Launch agent token">+ <h3>Launch \$${_esc(this._agent.name || 'AGENT')}</h3>+ <p>Mint a token tied to this agent on Pump.fun's bonding curve. The token's metadata will point to your agent.</p>+ <form class="launch-token-form">+ <label>Name <input name="name" maxlength="32" required value="${_esc(this._agent.name || '')}"></label>+ <label>Symbol (ticker) <input name="symbol" maxlength="10" required pattern="[A-Za-z0-9]{2,10}" value="${_esc((this._agent.name || 'AGT').slice(0, 6).toUpperCase())}"></label>+ <label>Description <textarea name="description" maxlength="280">${_esc(this._agent.description || '')}</textarea></label>+ <label>Initial buy (SOL, optional)+ <input name="initial_buy" type="number" min="0" max="50" step="0.01" value="0">+ </label>+ <div class="launch-token-quote" aria-live="polite">Loading cost estimate…</div>+ <div class="launch-token-modal-actions">+ <button type="button" class="launch-token-cancel">Cancel</button>+ <button type="submit" class="launch-token-submit">Launch</button>+ </div>+ </form>+ </div>+ `;+ document.body.appendChild(overlay);++ const close = () => overlay.remove();+ overlay.querySelector('.launch-token-cancel').addEventListener('click', close);+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) close();+ });++ const cluster = this._agent.onchain?.cluster || 'mainnet';+ const quoteEl = overlay.querySelector('.launch-token-quote');+ const buyInput = overlay.querySelector('input[name="initial_buy"]');+ const refreshQuote = this._debounce(async () => {+ const sol = Number(buyInput.value) || 0;+ quoteEl.textContent = 'Estimating cost…';+ try {+ const res = await fetch(+ `/api/agents/tokens/launch-quote?initial_buy_sol=${sol}&cluster=${cluster}`,+ { credentials: 'include' },+ );+ if (!res.ok) throw new Error(`quote ${res.status}`);+ const q = await res.json();+ const fixed = q.fixed_total_sol.toFixed(5);+ const total = q.total_sol.toFixed(5);+ const tokensOut = q.initial_buy?.tokens_out+ ? ` · ~${Number(q.initial_buy.tokens_out).toLocaleString()} tokens`+ : '';+ quoteEl.innerHTML = `Estimated cost: <strong>${total} SOL</strong> (launch fees ${fixed} + buy ${sol})${tokensOut}`;+ } catch {+ quoteEl.textContent = 'Cost estimate unavailable.';+ }+ }, 300);+ buyInput.addEventListener('input', refreshQuote);+ refreshQuote();++ overlay.querySelector('.launch-token-form').addEventListener('submit', async (ev) => {+ ev.preventDefault();+ const fd = new FormData(ev.target);+ const params = {+ name: String(fd.get('name') || '').trim(),+ symbol: String(fd.get('symbol') || '')+ .trim()+ .toUpperCase(),+ description: String(fd.get('description') || '').trim(),+ image: this._agent.thumbnailUrl || this._agent.avatar?.thumbnailUrl || '',+ initialBuySol: Number(fd.get('initial_buy') || 0),+ };+ close();+ await this._launch(params);+ });+ }++ _debounce(fn, ms) {+ let t = null;+ return (...args) => {+ clearTimeout(t);+ t = setTimeout(() => fn(...args), ms);+ };+ }++ async _launch(params) {+ try {+ const result = await this._adapter.launch({+ agent: this._agent,+ params,+ onProgress: (step) => this._renderProgress(step),+ });+ this._agent.token = {+ provider: result.provider,+ mint: result.mint,+ symbol: params.symbol,+ name: params.name,+ cluster: result.cluster,+ pumpfun_url: result.pumpfunUrl,+ };+ this._renderChip(this._agent.token);+ } catch (err) {+ if (isUserRejection(err)) return this._render();+ if (err.code === 'NO_PROVIDER') {+ this._renderError(`${err.message} Install at ${err.installUrl}`);+ return;+ }+ this._renderError(err.message || 'Token launch failed.');+ }+ }+}diff --git a/publish/src/onchain/payments-buttons.js b/publish/src/onchain/payments-buttons.jsnew file mode 100644index 000000000..22cb55793--- /dev/null+++ b/publish/src/onchain/payments-buttons.js@@ -0,0 +1,256 @@+/**+ * Payments UI components.+ *+ * • EnablePaymentsButton — owner-only. Becomes enabled once the agent has a+ * launched token. One click registers the agent for payments. Then+ * rehydrates as a "Payments enabled" chip on subsequent renders.+ *+ * • PayAgentButton — anyone signed in. Visible only when the agent has+ * payments configured. Opens an inline modal for amount + currency mint,+ * then walks the user through their wallet to pay.+ */++import { getPaymentsAdapter } from './payments/index.js';+import { isUserRejection } from './adapters/index.js';++const USDC_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const USDC_DEVNET = '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU';++function _esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++// ── Owner-side: enable payments ─────────────────────────────────────────────++export class EnablePaymentsButton {+ constructor({ agent, container }) {+ this._agent = agent;+ this._container = container;+ this._adapter = getPaymentsAdapter('pumpfun');+ this._root = null;+ }++ mount() {+ this._root = document.createElement('div');+ this._root.className = 'enable-payments-root';+ this._container.appendChild(this._root);+ this._render();+ }++ unmount() {+ this._root?.remove();+ this._root = null;+ }++ _render() {+ if (!this._root) return;+ const payments = this._agent.payments || this._agent.meta?.payments;+ if (payments?.configured) return this._renderChip(payments);++ if (!(this._agent.token?.mint || this._agent.meta?.token?.mint)) {+ return this._renderDisabled('Launch the agent token before enabling payments.');+ }++ this._renderEnableButton();+ }++ _renderEnableButton() {+ this._root.innerHTML = `+ <button class="enable-payments-btn" title="Register this agent to accept payments">+ 💳 Enable payments+ </button>+ `;+ this._root.querySelector('.enable-payments-btn').addEventListener('click', () => this._enable());+ }++ _renderDisabled(reason) {+ this._root.innerHTML = `+ <button class="enable-payments-btn enable-payments-btn--disabled" disabled title="${_esc(reason)}">+ 💳 Enable payments+ </button>+ <span class="enable-payments-tooltip">${_esc(reason)}</span>+ `;+ }++ _renderChip(_payments) {+ this._root.innerHTML = `+ <span class="enable-payments-chip">+ ✅ Payments enabled+ </span>+ `;+ }++ _renderProgress(step) {+ const labels = {+ connect: 'Connecting wallet…',+ prep: 'Preparing…',+ sign: 'Sign in your wallet…',+ submit: 'Submitting…',+ confirm: 'Saving…',+ };+ this._root.innerHTML = `+ <div class="enable-payments-progress" role="status" aria-live="polite">+ ${_esc(labels[step] || step)}+ </div>+ `;+ }++ _renderError(msg) {+ this._root.innerHTML = `+ <div class="enable-payments-error" role="alert">+ <span>${_esc(msg)}</span>+ <button class="enable-payments-retry">Try again</button>+ </div>+ `;+ this._root.querySelector('.enable-payments-retry').addEventListener('click', () => this._render());+ }++ async _enable() {+ try {+ const result = await this._adapter.enableForAgent({+ agent: this._agent,+ onProgress: (step) => this._renderProgress(step),+ });+ this._agent.payments = result.payments;+ this._renderChip(result.payments);+ } catch (err) {+ if (isUserRejection(err)) return this._render();+ this._renderError(err.message || 'Could not enable payments.');+ }+ }+}++// ── Payer-side: pay an agent ────────────────────────────────────────────────++export class PayAgentButton {+ constructor({ agent, container }) {+ this._agent = agent;+ this._container = container;+ this._adapter = getPaymentsAdapter('pumpfun');+ this._root = null;+ }++ mount() {+ this._root = document.createElement('div');+ this._root.className = 'pay-agent-root';+ this._container.appendChild(this._root);+ this._render();+ }++ unmount() {+ this._root?.remove();+ this._root = null;+ }++ _render() {+ if (!this._root) return;+ const payments = this._agent.payments || this._agent.meta?.payments;+ if (!payments?.configured) {+ this._root.innerHTML = '';+ return;+ }+ this._root.innerHTML = `+ <button class="pay-agent-btn" title="Pay this agent">+ 💰 Pay agent+ </button>+ `;+ this._root.querySelector('.pay-agent-btn').addEventListener('click', () => this._openModal());+ }++ _renderProgress(step) {+ const labels = {+ connect: 'Connecting wallet…',+ prep: 'Building payment…',+ sign: 'Sign in your wallet…',+ submit: 'Submitting payment…',+ confirm: 'Verifying…',+ };+ this._root.innerHTML = `+ <div class="pay-agent-progress" role="status" aria-live="polite">+ ${_esc(labels[step] || step)}+ </div>+ `;+ }++ _renderSuccess(intent) {+ this._root.innerHTML = `+ <span class="pay-agent-success">✅ Paid · <a href="https://solscan.io/tx/${_esc(intent.txSignature)}" target="_blank" rel="noopener noreferrer">view tx</a></span>+ `;+ }++ _renderError(msg) {+ this._root.innerHTML = `+ <div class="pay-agent-error" role="alert">+ <span>${_esc(msg)}</span>+ <button class="pay-agent-retry">Try again</button>+ </div>+ `;+ this._root.querySelector('.pay-agent-retry').addEventListener('click', () => this._render());+ }++ _openModal() {+ const cluster =+ this._agent.payments?.cluster || this._agent.meta?.payments?.cluster || 'mainnet';+ const defaultUsdc = cluster === 'devnet' ? USDC_DEVNET : USDC_MAINNET;++ const overlay = document.createElement('div');+ overlay.className = 'pay-agent-modal-overlay';+ overlay.innerHTML = `+ <div class="pay-agent-modal" role="dialog" aria-label="Pay agent">+ <h3>Pay ${_esc(this._agent.name || 'agent')}</h3>+ <p>Send a payment to this agent's Pump.fun payment account. The agent will be able to acknowledge and use the funds.</p>+ <form class="pay-agent-form">+ <label>Currency mint+ <input name="currency_mint" required value="${_esc(defaultUsdc)}" />+ <small>Default: USDC ${_esc(cluster)}</small>+ </label>+ <label>Amount (raw token units)+ <input name="amount" type="text" required pattern="[0-9]+" value="1000000" />+ <small>1 USDC = 1000000 (6 decimals)</small>+ </label>+ <div class="pay-agent-modal-actions">+ <button type="button" class="pay-agent-cancel">Cancel</button>+ <button type="submit" class="pay-agent-submit">Pay</button>+ </div>+ </form>+ </div>+ `;+ document.body.appendChild(overlay);++ const close = () => overlay.remove();+ overlay.querySelector('.pay-agent-cancel').addEventListener('click', close);+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) close();+ });++ overlay.querySelector('.pay-agent-form').addEventListener('submit', async (ev) => {+ ev.preventDefault();+ const fd = new FormData(ev.target);+ const params = {+ currencyMint: String(fd.get('currency_mint') || '').trim(),+ amount: String(fd.get('amount') || '').trim(),+ };+ close();+ await this._pay(params);+ });+ }++ async _pay({ currencyMint, amount }) {+ try {+ const result = await this._adapter.payAgent({+ agent: this._agent,+ currencyMint,+ amount,+ onProgress: (step) => this._renderProgress(step),+ });+ this._renderSuccess(result);+ } catch (err) {+ if (isUserRejection(err)) return this._render();+ this._renderError(err.message || 'Payment failed.');+ }+ }+}diff --git a/publish/src/onchain/payments/index.js b/publish/src/onchain/payments/index.jsnew file mode 100644index 000000000..1411f9bbf--- /dev/null+++ b/publish/src/onchain/payments/index.js@@ -0,0 +1,16 @@+import { PumpfunPaymentsAdapter } from './pumpfun-payments.js';++const cache = new Map();++export function getPaymentsAdapter(provider = 'pumpfun') {+ if (cache.has(provider)) return cache.get(provider);+ let inst;+ if (provider === 'pumpfun') inst = new PumpfunPaymentsAdapter();+ else throw new Error(`No payments adapter for provider: ${provider}`);+ cache.set(provider, inst);+ return inst;+}++export function _resetPaymentsAdapters() {+ cache.clear();+}diff --git a/publish/src/onchain/payments/pumpfun-payments.js b/publish/src/onchain/payments/pumpfun-payments.jsnew file mode 100644index 000000000..fa896fc3f--- /dev/null+++ b/publish/src/onchain/payments/pumpfun-payments.js@@ -0,0 +1,187 @@+/**+ * PumpfunPaymentsAdapter — frontend facade for the Pump.fun agent-payments-sdk.+ *+ * Two responsibilities:+ * • Owner side: enableForAgent() — one-time, registers the agent's token to+ * accept payments. Backend builds the create tx; user signs in Phantom.+ * • Payer side: payAgent() — creates an invoice intent, builds the+ * accept-payment tx, user signs and submits.+ *+ * Same prep/sign/submit/confirm shape as the deploy and launch flows. We+ * never trust the wallet's RPC for cluster correctness — Connection is built+ * from the cluster recorded on the agent's payments config.+ */++import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';+import { getAdapter as getWalletAdapter } from '../adapters/index.js';++const SOLANA_RPC = {+ mainnet: 'https://api.mainnet-beta.solana.com',+ devnet: 'https://api.devnet.solana.com',+};++function decodeTx(b64) {+ const bin = atob(b64);+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ try {+ return VersionedTransaction.deserialize(bytes);+ } catch {+ return Transaction.from(bytes);+ }+}++async function waitForConfirmation(conn, sig, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const { value } = await conn.getSignatureStatuses([sig]);+ const s = value?.[0];+ if (s) {+ if (s.err) throw new Error(`Tx failed: ${JSON.stringify(s.err)}`);+ if (s.confirmationStatus === 'confirmed' || s.confirmationStatus === 'finalized') return;+ }+ await new Promise((r) => setTimeout(r, 1500));+ }+ throw new Error('Confirmation timed out.');+}++export class PumpfunPaymentsAdapter {+ get provider() {+ return 'pumpfun';+ }++ /**+ * Owner-side: register the agent's token to accept payments.+ * Pre: agent.token.mint must exist; caller must own the agent.+ */+ async enableForAgent({ agent, onProgress = () => {} }) {+ if (!agent?.token?.mint && !agent?.meta?.token?.mint) {+ const e = new Error('Launch the agent token first.');+ e.code = 'PRECONDITION_FAILED';+ throw e;+ }+ const cluster = agent.token?.cluster || agent.meta?.token?.cluster || 'mainnet';+ const wallet = getWalletAdapter('solana');+ if (!wallet.isAvailable()) {+ const e = new Error('No Solana wallet detected.');+ e.code = 'NO_PROVIDER';+ e.installUrl = wallet.installUrl();+ throw e;+ }++ onProgress('connect');+ const { address } = await wallet.connect({ ensureLinked: true, cluster });++ onProgress('prep');+ const prepResp = await fetch('/api/agents/payments/create-prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agent_id: agent.id, wallet_address: address, cluster }),+ });+ if (!prepResp.ok) throw await asError(prepResp, 'create-prep');+ const prep = await prepResp.json();++ onProgress('sign');+ const provider =+ window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare;+ const signed = await provider.signTransaction(decodeTx(prep.tx_base64));++ onProgress('submit');+ const conn = new Connection(SOLANA_RPC[cluster], 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), {+ preflightCommitment: 'confirmed',+ });+ await waitForConfirmation(conn, sig, 60_000);++ onProgress('confirm');+ const confirmResp = await fetch('/api/agents/payments/create-confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ prep_id: prep.prep_id,+ tx_signature: sig,+ wallet_address: address,+ }),+ });+ if (!confirmResp.ok) throw await asError(confirmResp, 'create-confirm');+ return await confirmResp.json();+ }++ /**+ * Payer-side: pay an agent. Caller need not own the agent.+ * @param {{ agent: object, currencyMint: string, amount: string, memo?: string, onProgress?: Function }} opts+ */+ async payAgent({ agent, currencyMint, amount, memo, onProgress = () => {} }) {+ if (!agent?.payments?.configured && !agent?.meta?.payments?.configured) {+ const e = new Error('This agent has not enabled payments.');+ e.code = 'PRECONDITION_FAILED';+ throw e;+ }+ const cluster =+ agent.payments?.cluster || agent.meta?.payments?.cluster || 'mainnet';++ const wallet = getWalletAdapter('solana');+ if (!wallet.isAvailable()) {+ const e = new Error('No Solana wallet detected.');+ e.code = 'NO_PROVIDER';+ e.installUrl = wallet.installUrl();+ throw e;+ }++ onProgress('connect');+ const { address } = await wallet.connect({ ensureLinked: true, cluster });++ onProgress('prep');+ const prepResp = await fetch('/api/agents/payments/pay-prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ agent_id: agent.id,+ currency_mint: currencyMint,+ amount: String(amount),+ memo,+ wallet_address: address,+ cluster,+ }),+ });+ if (!prepResp.ok) throw await asError(prepResp, 'pay-prep');+ const prep = await prepResp.json();++ onProgress('sign');+ const provider =+ window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare;+ const signed = await provider.signTransaction(decodeTx(prep.tx_base64));++ onProgress('submit');+ const conn = new Connection(SOLANA_RPC[cluster], 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), {+ preflightCommitment: 'confirmed',+ });+ await waitForConfirmation(conn, sig, 60_000);++ onProgress('confirm');+ const confirmResp = await fetch('/api/agents/payments/pay-confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ intent_id: prep.intent_id,+ tx_signature: sig,+ wallet_address: address,+ }),+ });+ if (!confirmResp.ok) throw await asError(confirmResp, 'pay-confirm');+ return { ...(await confirmResp.json()), txSignature: sig, intentId: prep.intent_id };+ }+}++async function asError(resp, where) {+ const data = await resp.json().catch(() => ({}));+ const err = new Error(data.error_description || `${where} returned ${resp.status}`);+ err.status = resp.status;+ err.code = data.error;+ return err;+}diff --git a/publish/src/onchain/tokens/base.js b/publish/src/onchain/tokens/base.jsnew file mode 100644index 000000000..fc77c7472--- /dev/null+++ b/publish/src/onchain/tokens/base.js@@ -0,0 +1,57 @@+/**+ * TokenAdapter — the contract every token-launch backend implements.+ *+ * Parallel to WalletAdapter. The deploy orchestrator and UI talk only to this+ * interface; new launchpads (Zora, Bonfida, Streamflow…) plug in as new+ * adapters without forking the calling code.+ *+ * A "token" here is a fungible asset bound to an agent identity (memecoin on a+ * bonding curve, social token, etc.). Distinct from the agent's *identity* NFT+ * minted via the deploy flow.+ */++/**+ * @typedef {object} LaunchPrep+ * @property {string} prepId+ * @property {string} mint Mint pubkey (Solana base58, EVM addr, etc.)+ * @property {string} txBase64 Partially-signed unsigned-by-user tx+ * @property {string} metadataUri Token metadata pointer (ipfs://...)+ * @property {string} family 'solana' | 'evm' | ...+ * @property {string} provider 'pumpfun' | 'zora' | ...+ * @property {string} [cluster] For Solana+ */++/**+ * @typedef {object} LaunchResult+ * @property {string} mint+ * @property {string} txHash Tx hash / signature+ * @property {string} provider+ * @property {string} [curve] Provider-specific curve / pool ID+ */++/**+ * @abstract+ */+export class TokenAdapter {+ /** @returns {string} 'pumpfun' | etc. */+ get provider() {+ throw new Error('not implemented');+ }++ /** @returns {string} 'solana' | 'evm' */+ get family() {+ throw new Error('not implemented');+ }++ /**+ * Validate that a launch is permitted for the given agent state. Adapters+ * use this to enforce constraints (Pump.fun is Solana-only, requires the+ * agent to already have a Solana identity, etc.).+ *+ * @param {{ agent: object }} ctx+ * @returns {{ ok: boolean, reason?: string }}+ */+ validatePreconditions(_ctx) {+ throw new Error('not implemented');+ }+}diff --git a/publish/src/onchain/tokens/index.js b/publish/src/onchain/tokens/index.jsnew file mode 100644index 000000000..9f51b9abc--- /dev/null+++ b/publish/src/onchain/tokens/index.js@@ -0,0 +1,30 @@+/**+ * Token-adapter factory. Mirrors src/onchain/adapters/index.js for the wallet+ * layer.+ */++import { PumpfunTokenAdapter } from './pumpfun.js';++const cache = new Map();++/**+ * @param {'pumpfun'} provider+ * @returns {import('./base.js').TokenAdapter}+ */+export function getTokenAdapter(provider) {+ if (cache.has(provider)) return cache.get(provider);+ let inst;+ if (provider === 'pumpfun') inst = new PumpfunTokenAdapter();+ else throw new Error(`No token adapter for provider: ${provider}`);+ cache.set(provider, inst);+ return inst;+}++export function _resetTokenAdapters() {+ cache.clear();+}++/** @returns {string[]} */+export function listProviders() {+ return ['pumpfun'];+}diff --git a/publish/src/onchain/tokens/pumpfun.js b/publish/src/onchain/tokens/pumpfun.jsnew file mode 100644index 000000000..b1f9dd38f--- /dev/null+++ b/publish/src/onchain/tokens/pumpfun.js@@ -0,0 +1,204 @@+/**+ * PumpfunTokenAdapter — front-end facade for launching an agent's token on+ * Pump.fun's bonding curve.+ *+ * Most of the heavy lifting (mint keypair generation, fetching `global`,+ * building the `createV2Instruction` tx) happens server-side in+ * api/agents/tokens/launch-prep.js — this module only:+ *+ * 1. Validates that the agent has a Solana identity (Pump.fun is Solana-only).+ * 2. Calls the prep endpoint, gets back a base64 partially-signed tx.+ * 3. Hands the tx to the user's Solana wallet for the user-signature.+ * 4. Submits the fully-signed tx through our own Connection on the chosen+ * cluster (mirroring the SolanaAdapter discipline of not trusting the+ * wallet's RPC).+ * 5. Calls the confirm endpoint to verify + persist `meta.token`.+ */++import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';+import { TokenAdapter } from './base.js';+import { getAdapter as getWalletAdapter } from '../adapters/index.js';++const SOLANA_RPC = {+ mainnet: 'https://api.mainnet-beta.solana.com',+ devnet: 'https://api.devnet.solana.com',+};++function decodeTx(b64) {+ const bin = atob(b64);+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ try {+ return VersionedTransaction.deserialize(bytes);+ } catch {+ return Transaction.from(bytes);+ }+}++export class PumpfunTokenAdapter extends TokenAdapter {+ get provider() {+ return 'pumpfun';+ }++ get family() {+ return 'solana';+ }++ /** @param {{ agent: object }} ctx */+ validatePreconditions({ agent }) {+ const onchain = agent?.onchain;+ if (!onchain) {+ return {+ ok: false,+ reason: 'Agent must be deployed on-chain before launching a token.',+ };+ }+ if (onchain.family !== 'solana') {+ return {+ ok: false,+ reason: 'Pump.fun launches require a Solana-deployed agent.',+ };+ }+ if (agent?.token?.mint) {+ return { ok: false, reason: 'This agent already has a launched token.' };+ }+ return { ok: true };+ }++ /**+ * @param {object} opts+ * @param {object} opts.agent+ * @param {{ name: string, symbol: string, description?: string, image?: string, initialBuySol?: number }} opts.params+ * @param {(step: 'connect'|'prep'|'sign'|'submit'|'confirm') => void} [opts.onProgress]+ * @returns {Promise<{ mint: string, txHash: string, provider: 'pumpfun', cluster: 'mainnet'|'devnet' }>}+ */+ async launch({ agent, params, onProgress = () => {} }) {+ const pre = this.validatePreconditions({ agent });+ if (!pre.ok) {+ const err = new Error(pre.reason);+ err.code = 'PRECONDITION_FAILED';+ throw err;+ }++ const cluster = agent.onchain.cluster || 'mainnet';+ const wallet = getWalletAdapter('solana');+ if (!wallet.isAvailable()) {+ const err = new Error('No Solana wallet detected.');+ err.code = 'NO_PROVIDER';+ err.installUrl = wallet.installUrl();+ throw err;+ }++ onProgress('connect');+ const { address } = await wallet.connect({ ensureLinked: true, cluster });+ if (address !== agent.onchain.wallet) {+ const err = new Error(+ 'Connected wallet does not match the agent owner. Switch wallets and retry.',+ );+ err.code = 'WALLET_MISMATCH';+ throw err;+ }++ onProgress('prep');+ const prepResp = await fetch('/api/agents/tokens/launch-prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ agent_id: agent.id,+ provider: 'pumpfun',+ cluster,+ wallet_address: address,+ name: params.name,+ symbol: params.symbol,+ description: params.description || '',+ image: params.image || agent.thumbnailUrl || '',+ initial_buy_sol: Number.isFinite(params.initialBuySol) ? params.initialBuySol : 0,+ }),+ });+ if (!prepResp.ok) {+ const data = await prepResp.json().catch(() => ({}));+ const err = new Error(+ data.error_description || `launch-prep returned ${prepResp.status}`,+ );+ err.status = prepResp.status;+ err.code = data.error;+ throw err;+ }+ const prep = await prepResp.json();++ onProgress('sign');+ const provider =+ window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare;+ if (!provider) throw new Error('Solana wallet vanished mid-flow.');++ const tx = decodeTx(prep.tx_base64);+ const signed = await provider.signTransaction(tx);++ onProgress('submit');+ const conn = new Connection(SOLANA_RPC[cluster], 'confirmed');+ const signature = await conn.sendRawTransaction(signed.serialize(), {+ skipPreflight: false,+ preflightCommitment: 'confirmed',+ });++ // Bounded poll (Pump.fun launches occasionally take 10–20s on devnet).+ await this.#waitForConfirmation(conn, signature, 90_000);++ onProgress('confirm');+ const confirmResp = await fetch('/api/agents/tokens/launch-confirm', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ prep_id: prep.prep_id,+ tx_signature: signature,+ wallet_address: address,+ }),+ });+ if (!confirmResp.ok) {+ const data = await confirmResp.json().catch(() => ({}));+ const err = new Error(+ data.error_description || `launch-confirm returned ${confirmResp.status}`,+ );+ err.status = confirmResp.status;+ err.code = data.error;+ err.txSignature = signature;+ throw err;+ }+ const confirmed = await confirmResp.json();+ return {+ mint: prep.mint,+ txHash: signature,+ provider: 'pumpfun',+ cluster,+ agent: confirmed.agent,+ pumpfunUrl:+ cluster === 'mainnet'+ ? `https://pump.fun/${prep.mint}`+ : `https://explorer.solana.com/address/${prep.mint}?cluster=devnet`,+ };+ }++ async #waitForConfirmation(conn, signature, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const { value } = await conn.getSignatureStatuses([signature]);+ const s = value?.[0];+ if (s) {+ if (s.err) {+ const e = new Error(`Token launch failed: ${JSON.stringify(s.err)}`);+ e.code = 'TX_FAILED';+ throw e;+ }+ if (s.confirmationStatus === 'confirmed' || s.confirmationStatus === 'finalized') {+ return;+ }+ }+ await new Promise((r) => setTimeout(r, 1500));+ }+ const e = new Error('Launch confirmation timed out. Tx may still land — check explorer.');+ e.code = 'TX_TIMEOUT';+ throw e;+ }+}diff --git a/publish/src/onchain/vanity-wallet-button.js b/publish/src/onchain/vanity-wallet-button.jsnew file mode 100644index 000000000..20c1035a3--- /dev/null+++ b/publish/src/onchain/vanity-wallet-button.js@@ -0,0 +1,209 @@+/**+ * VanityWalletButton — provisions a custodial Solana wallet for the agent+ * with a user-chosen vanity prefix. Owner-only.+ *+ * • If the agent already has a custodial wallet → renders an address chip.+ * • Otherwise renders "Create vanity wallet". Click opens a modal with a+ * prefix input, live difficulty estimate, and grind progress.+ * • Reads agent.meta.solana_address (and the existing legacy field paths)+ * to detect whether a wallet is already provisioned.+ */++import {+ provisionVanityForAgent,+ validatePattern,+ estimateAttempts,+ formatTimeEstimate,+} from './vanity/index.js';++const RATE_PER_CORE = 5000;++function _esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ })[c]);+}++function _coreCount() {+ if (typeof navigator === 'undefined') return 4;+ return Math.max(1, Math.min(navigator.hardwareConcurrency || 4, 8));+}++export class VanityWalletButton {+ constructor({ agent, container }) {+ this._agent = agent;+ this._container = container;+ this._root = null;+ this._abort = null;+ }++ mount() {+ this._root = document.createElement('div');+ this._root.className = 'vanity-wallet-root';+ this._container.appendChild(this._root);+ this._render();+ }++ unmount() {+ try {+ this._abort?.abort();+ } catch {+ /* ignore */+ }+ this._root?.remove();+ this._root = null;+ }++ _currentAddress() {+ // Prefer the new top-level field; fall back to legacy meta paths.+ return (+ this._agent.solana_address ||+ this._agent.meta?.solana_address ||+ this._agent.meta?.solana?.address ||+ null+ );+ }++ _render() {+ if (!this._root) return;+ const addr = this._currentAddress();+ if (addr) return this._renderChip(addr);+ this._renderCreateButton();+ }++ _renderCreateButton() {+ this._root.innerHTML = `+ <button class="vanity-wallet-btn" title="Create a custodial Solana wallet for this agent with a chosen prefix">+ ✨ Create vanity wallet+ </button>+ `;+ this._root.querySelector('.vanity-wallet-btn').addEventListener('click', () => this._openModal());+ }++ _renderChip(addr) {+ const short = `${addr.slice(0, 6)}…${addr.slice(-4)}`;+ this._root.innerHTML = `+ <a class="vanity-wallet-chip" href="https://solscan.io/account/${_esc(addr)}" target="_blank" rel="noopener noreferrer"+ aria-label="View agent wallet on Solscan">+ 💼 ${_esc(short)} · agent wallet+ </a>+ `;+ }++ _renderProgress({ attempts, rate, eta }) {+ this._root.innerHTML = `+ <div class="vanity-wallet-progress" role="status" aria-live="polite">+ <span>Grinding… ${attempts.toLocaleString()} attempts</span>+ <span>${rate.toLocaleString()} k/s</span>+ <span>~${_esc(eta)} remaining</span>+ <button class="vanity-wallet-cancel">Cancel</button>+ </div>+ `;+ this._root.querySelector('.vanity-wallet-cancel').addEventListener('click', () => {+ try {+ this._abort?.abort();+ } catch {+ /* ignore */+ }+ });+ }++ _renderError(msg) {+ this._root.innerHTML = `+ <div class="vanity-wallet-error" role="alert">+ <span>${_esc(msg)}</span>+ <button class="vanity-wallet-retry">Try again</button>+ </div>+ `;+ this._root.querySelector('.vanity-wallet-retry').addEventListener('click', () => this._render());+ }++ _openModal() {+ const overlay = document.createElement('div');+ overlay.className = 'vanity-wallet-modal-overlay';+ overlay.innerHTML = `+ <div class="vanity-wallet-modal" role="dialog" aria-label="Create vanity wallet">+ <h3>Create vanity wallet for ${_esc(this._agent.name || 'agent')}</h3>+ <p>Generate a Solana keypair whose address starts with a chosen prefix. The secret key is encrypted server-side and never leaves the server after provisioning.</p>+ <form class="vanity-wallet-form">+ <label>Prefix (1–6 base58 chars)+ <input name="prefix" maxlength="6" required value="AGNT" pattern="[1-9A-HJ-NP-Za-km-z]+" />+ </label>+ <label>+ <input type="checkbox" name="ignore_case" />+ Ignore case (faster)+ </label>+ <div class="vanity-wallet-estimate" aria-live="polite"></div>+ <div class="vanity-wallet-modal-actions">+ <button type="button" class="vanity-wallet-cancel-btn">Cancel</button>+ <button type="submit" class="vanity-wallet-grind-btn">Grind & provision</button>+ </div>+ </form>+ </div>+ `;+ document.body.appendChild(overlay);++ const close = () => overlay.remove();+ overlay.querySelector('.vanity-wallet-cancel-btn').addEventListener('click', close);+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) close();+ });++ const prefixInput = overlay.querySelector('input[name="prefix"]');+ const ignoreCaseInput = overlay.querySelector('input[name="ignore_case"]');+ const estEl = overlay.querySelector('.vanity-wallet-estimate');+ const submitBtn = overlay.querySelector('.vanity-wallet-grind-btn');++ const refreshEstimate = () => {+ const prefix = prefixInput.value.trim();+ if (!prefix) {+ estEl.textContent = '';+ submitBtn.disabled = true;+ return;+ }+ const v = validatePattern(prefix);+ if (!v.valid) {+ estEl.textContent = v.errors.join('; ');+ submitBtn.disabled = true;+ return;+ }+ const ignoreCase = ignoreCaseInput.checked;+ const effective = ignoreCase ? prefix.length * 0.85 : prefix.length;+ const expected = estimateAttempts(effective);+ const seconds = expected / (RATE_PER_CORE * _coreCount());+ estEl.innerHTML = `~${expected.toLocaleString()} attempts · <strong>${_esc(formatTimeEstimate(seconds))}</strong> on ${_coreCount()} cores`;+ submitBtn.disabled = false;+ };+ prefixInput.addEventListener('input', refreshEstimate);+ ignoreCaseInput.addEventListener('change', refreshEstimate);+ refreshEstimate();++ overlay.querySelector('.vanity-wallet-form').addEventListener('submit', async (ev) => {+ ev.preventDefault();+ const prefix = prefixInput.value.trim();+ const ignoreCase = ignoreCaseInput.checked;+ close();+ await this._provision({ prefix, ignoreCase });+ });+ }++ async _provision({ prefix, ignoreCase }) {+ this._abort = new AbortController();+ try {+ const result = await provisionVanityForAgent({+ agentId: this._agent.id,+ prefix,+ ignoreCase,+ signal: this._abort.signal,+ onProgress: (p) => this._renderProgress(p),+ });+ this._agent.solana_address = result.address;+ this._renderChip(result.address);+ } catch (err) {+ if (err?.name === 'AbortError') return this._render();+ this._renderError(err.message || 'Provisioning failed.');+ } finally {+ this._abort = null;+ }+ }+}diff --git a/publish/src/onchain/vanity/index.js b/publish/src/onchain/vanity/index.jsnew file mode 100644index 000000000..2fed82468--- /dev/null+++ b/publish/src/onchain/vanity/index.js@@ -0,0 +1,85 @@+/**+ * Vanity wallet provisioning for agents.+ *+ * Wraps the existing client-side grinder (src/solana/vanity/grinder.js) and+ * the provisioning endpoint (POST /api/agents/:id/solana with secret_key ++ * vanity_prefix). Lets a caller grind a Solana keypair whose pubkey starts+ * with a chosen base58 prefix, then hand it to the server, which encrypts it+ * with AES-GCM (HKDF-derived from JWT_SECRET) and stores it on the agent.+ *+ * The agent thereafter has a custodial Solana wallet — the same model used+ * by the legacy /api/agents/:id/pumpfun/* endpoints. The plaintext secret+ * key only exists for the moment between grinding and the POST.+ *+ * Why client-side: keeps secret material out of server logs/RPC traces, and+ * avoids burning Vercel function time on CPU-bound grinding. Long prefixes+ * (5+) can take minutes — caller is responsible for surfacing a Cancel UX+ * via AbortSignal.+ */++import { grindVanity } from '../../solana/vanity/grinder.js';+import { Keypair } from '@solana/web3.js';+import bs58 from 'bs58';++/**+ * @param {object} opts+ * @param {string} opts.agentId+ * @param {string} [opts.prefix]+ * @param {string} [opts.suffix]+ * @param {boolean} [opts.ignoreCase]+ * @param {AbortSignal} [opts.signal]+ * @param {(p: { attempts: number, rate: number, eta: string }) => void} [opts.onProgress]+ * @returns {Promise<{ address: string, attempts: number, durationMs: number }>}+ */+export async function provisionVanityForAgent(opts) {+ if (!opts?.agentId) throw new Error('agentId required');+ if (!opts.prefix && !opts.suffix) throw new Error('prefix or suffix required');++ // 1. Grind locally — secret material stays in this tab.+ const ground = await grindVanity({+ prefix: opts.prefix,+ suffix: opts.suffix,+ ignoreCase: !!opts.ignoreCase,+ signal: opts.signal,+ onProgress: opts.onProgress,+ });++ // 2. Sanity-check: derive the pubkey from the secret and confirm it matches.+ // The server does this check too; doing it here surfaces local memory+ // corruption (rare) before paying for a network round-trip.+ const kp = Keypair.fromSecretKey(ground.secretKey);+ if (kp.publicKey.toBase58() !== ground.publicKey) {+ throw new Error('Locally-derived pubkey does not match grinder output.');+ }++ // 3. POST to the provisioning endpoint. The legacy endpoint accepts a+ // base58-encoded secret_key and (optional) vanity_prefix — see+ // api/agents/solana-wallet.js for the contract.+ const secretBase58 = bs58.encode(ground.secretKey);+ const resp = await fetch(`/api/agents/${encodeURIComponent(opts.agentId)}/solana`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ secret_key: secretBase58,+ vanity_prefix: opts.prefix || undefined,+ vanity_suffix: opts.suffix || undefined,+ }),+ });+ if (!resp.ok) {+ const data = await resp.json().catch(() => ({}));+ const err = new Error(data.error_description || `provision returned ${resp.status}`);+ err.status = resp.status;+ err.code = data.error;+ throw err;+ }+ const result = await resp.json();+ return {+ address: result.solana_address || ground.publicKey,+ attempts: ground.attempts,+ durationMs: ground.durationMs,+ };+}++export { grindVanity };+export { validatePattern, estimateAttempts, formatTimeEstimate } from '../../solana/vanity/validation.js';diff --git a/publish/src/onchain/x402/client.js b/publish/src/onchain/x402/client.jsnew file mode 100644index 000000000..b9fb3fdff--- /dev/null+++ b/publish/src/onchain/x402/client.js@@ -0,0 +1,113 @@+/**+ * x402 client — fetch wrapper that follows 402 Payment Required automatically.+ *+ * Usage:+ * import { x402Fetch } from 'src/onchain/x402/client.js';+ *+ * const res = await x402Fetch('/api/agents/x402/invoke', {+ * method: 'POST',+ * headers: { 'content-type': 'application/json' },+ * body: JSON.stringify({ agent_id, skill: 'echo', args: { hi: 1 } }),+ * onPaymentRequired: async (manifest) => 'auto', // or 'reject'+ * onProgress: (step) => console.log(step),+ * });+ *+ * Flow:+ * 1. Make the request.+ * 2. If 402: parse manifest, hand it to onPaymentRequired (caller can+ * reject — useful for showing a confirmation modal). On 'auto', use the+ * Pump.fun payments adapter to pay, then retry once with+ * `x-payment-intent`.+ * 3. Return the final response (whatever it is — 200, 4xx, etc.).+ */++import { getPaymentsAdapter } from '../payments/index.js';++/** @typedef {{ version: string, kind: string, agent_id: string, skill: string, amount: string, currency: string, recipient: string, valid_until: number, intent_url: string, verify_url: string, retry_with_header: string }} X402Manifest */++const MAX_RETRIES = 1;++/**+ * @param {string|URL} url+ * @param {RequestInit & {+ * onPaymentRequired?: (manifest: X402Manifest) => Promise<'auto'|'reject'> | 'auto' | 'reject',+ * onProgress?: (step: string) => void,+ * provider?: 'pumpfun',+ * }} [opts]+ * @returns {Promise<Response>}+ */+export async function x402Fetch(url, opts = {}) {+ const {+ onPaymentRequired = () => 'auto',+ onProgress = () => {},+ provider = 'pumpfun',+ ...fetchOpts+ } = opts;++ let attempt = 0;+ let intentId = null;++ while (true) {+ const headers = new Headers(fetchOpts.headers || {});+ if (intentId) headers.set('x-payment-intent', intentId);+ const response = await fetch(url, {+ ...fetchOpts,+ credentials: fetchOpts.credentials || 'include',+ headers,+ });++ if (response.status !== 402) return response;+ if (attempt >= MAX_RETRIES) return response; // gave up after one paid retry++ // Parse 402 manifest. Spec says it's JSON; refuse anything else.+ const ct = response.headers.get('content-type') || '';+ if (!ct.includes('json')) return response;+ const manifest = await response.json();+ if (manifest?.version !== 'x402/0.1' || manifest?.kind !== 'agent-skill') {+ return response;+ }++ const decision = await onPaymentRequired(manifest);+ if (decision !== 'auto') return response;++ // Pay via the configured adapter. Skill is bound into the intent+ // payload so the server can verify the intent matches the call.+ onProgress('paying');+ const adapter = getPaymentsAdapter(provider);+ const paid = await adapter.payAgent({+ agent: {+ id: manifest.agent_id,+ // payAgent() reads agent.payments to discover cluster + mint.+ // In x402, the manifest carries the cluster implicitly via the+ // currency mint; we can read it server-side, but the adapter+ // also needs the mint+cluster from the agent. We fetch a+ // minimal agent record to satisfy that.+ ...(await fetchAgentSnippet(manifest.agent_id)),+ },+ currencyMint: manifest.currency,+ amount: manifest.amount,+ memo: manifest.memo,+ onProgress: (s) => onProgress(`paying:${s}`),+ });++ intentId = paid.intentId;+ attempt += 1;+ onProgress('retrying');+ }+}++async function fetchAgentSnippet(agentId) {+ try {+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, {+ credentials: 'include',+ });+ if (!r.ok) return {};+ const data = await r.json();+ return {+ payments: data?.agent?.payments || data?.payments,+ meta: { payments: data?.agent?.payments || data?.payments },+ };+ } catch {+ return {};+ }+}diff --git a/publish/src/permissions/grant-modal.js b/publish/src/permissions/grant-modal.jsnew file mode 100644index 000000000..7b740b0a7--- /dev/null+++ b/publish/src/permissions/grant-modal.js@@ -0,0 +1,1098 @@+/**+ * Grant Permissions Modal — 3-step scope builder, plain-English review, and+ * MetaMask EIP-712 sign flow for ERC-7710 delegations.+ *+ * Public API:+ * new GrantPermissionsModal({ agentId, chainId, delegatorAddress,+ * delegateAddress, presets? }).open()+ * → Promise<{ ok: true, id, delegationHash } | { ok: false, reason }>+ */++import { AbiCoder, getAddress } from 'ethers';+import { ensureWallet } from '../erc8004/agent-registry.js';+import { encodeScopedDelegation, signDelegation } from './toolkit.js';+import { CAVEAT_ENFORCERS } from '../erc7710/abi.js';++// ── Token tables ──────────────────────────────────────────────────────────────++const TOKENS = {+ 84532: [+ { symbol: 'ETH', address: 'native', decimals: 18 },+ { symbol: 'USDC', address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', decimals: 6 },+ { symbol: 'WETH', address: '0x4200000000000000000000000000000000000006', decimals: 18 },+ ],+ 11155111: [+ { symbol: 'ETH', address: 'native', decimals: 18 },+ { symbol: 'USDC', address: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', decimals: 6 },+ { symbol: 'WETH', address: '0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9', decimals: 18 },+ ],+ 1: [+ { symbol: 'ETH', address: 'native', decimals: 18 },+ { symbol: 'USDC', address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', decimals: 6 },+ { symbol: 'WETH', address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', decimals: 18 },+ ],+};++const SUPPORTED_CHAINS = [+ { id: 84532, name: 'Base Sepolia', testnet: true },+ { id: 11155111, name: 'Sepolia', testnet: true },+ { id: 1, name: 'Ethereum Mainnet', testnet: false },+];++const KNOWN_CONTRACTS = {+ 84532: [{ name: 'Uniswap V3 Router', address: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4' }],+ 11155111: [{ name: 'Uniswap V3 Router', address: '0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48' }],+ 1: [+ { name: 'Uniswap V3 Router', address: '0xE592427A0AEce92De3Edee1F18E0157C05861564' },+ { name: 'Uniswap V2 Router', address: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' },+ ],+};++const EXPIRY_OFFSETS = { '24h': 86400, '7d': 604800, '30d': 2592000 };+const ZERO_ADDR = '0x' + '0'.repeat(40);++// ── Pure helpers ──────────────────────────────────────────────────────────────++function escapeHtml(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++function formatAddress(addr) {+ if (!addr || addr === 'native') return addr;+ return addr.slice(0, 6) + '…' + addr.slice(-4);+}++function formatAmount(raw, decimals) {+ if (!raw) return '0';+ const n = Number(raw) / 10 ** decimals;+ return n % 1 === 0 ? String(n) : n.toFixed(6).replace(/\.?0+$/, '');+}++function toBaseUnits(display, decimals) {+ const n = parseFloat(display) || 0;+ return BigInt(Math.round(n * 10 ** decimals)).toString();+}++function tokensForChain(chainId) {+ return TOKENS[chainId] ?? [{ symbol: 'ETH', address: 'native', decimals: 18 }];+}++function knownContractsForChain(chainId) {+ return KNOWN_CONTRACTS[chainId] ?? [];+}++function resolveExpiry(preset, custom) {+ if (preset === 'custom') {+ const ts = custom ? Math.floor(new Date(custom).getTime() / 1000) : 0;+ return ts;+ }+ return Math.floor(Date.now() / 1000) + (EXPIRY_OFFSETS[preset] ?? EXPIRY_OFFSETS['24h']);+}++function resolveTokenMeta(token, chainId) {+ const list = tokensForChain(chainId);+ return list.find((t) => t.address.toLowerCase() === token.toLowerCase()) ?? null;+}++function isKnownTarget(addr, chainId) {+ const list = knownContractsForChain(chainId);+ return list.some((c) => c.address.toLowerCase() === addr.toLowerCase());+}++function buildReviewLines(form, chainId) {+ const meta = resolveTokenMeta(form.token, chainId);+ const symbol = meta ? meta.symbol : formatAddress(form.token);+ const decimals = meta ? meta.decimals : 18;+ const amount = form.amount ? formatAmount(toBaseUnits(form.amount, decimals), decimals) : '?';++ const periodLabel =+ { once: 'in total', daily: 'per day', weekly: 'per week' }[form.period] ?? '';++ const expiryTs = resolveExpiry(form.expiry, form.customExpiry);+ const expiryDate = expiryTs+ ? new Date(expiryTs * 1000).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ })+ : 'an unknown date';++ const lines = [];++ const targetNames = form.targets.map((addr) => {+ const known = knownContractsForChain(chainId).find(+ (c) => c.address.toLowerCase() === addr.toLowerCase(),+ );+ return known ? `${known.name} (${formatAddress(addr)})` : formatAddress(addr);+ });++ const targetDesc = form.targets.length === 0 ? 'any contract' : targetNames.join(', ');++ lines.push(+ `This agent can spend up to <strong>${escapeHtml(amount)} ${escapeHtml(symbol)}</strong>` ++ ` ${escapeHtml(periodLabel)} on <strong>${escapeHtml(targetDesc)}</strong>` ++ ` until <strong>${escapeHtml(expiryDate)}</strong>.`,+ );++ return lines;+}++function buildScopeCaveats(scope, chainId) {+ const coder = AbiCoder.defaultAbiCoder();+ const e = (key) => CAVEAT_ENFORCERS[key]?.[chainId] ?? ZERO_ADDR;++ const tokenAddr = scope.token === 'native' ? ZERO_ADDR : getAddress(scope.token);++ const caveats = [+ {+ enforcer: e('ERC20LimitEnforcer'),+ terms: coder.encode(['address', 'uint256'], [tokenAddr, BigInt(scope.maxAmount)]),+ args: '0x',+ },+ {+ enforcer: e('TimestampEnforcer'),+ terms: coder.encode(['uint128', 'uint128'], [0n, BigInt(scope.expiry)]),+ args: '0x',+ },+ ];++ if (scope.targets && scope.targets.length > 0) {+ caveats.push({+ enforcer: e('AllowedTargetsEnforcer'),+ terms: coder.encode(['address[]'], [scope.targets.map((a) => getAddress(a))]),+ args: '0x',+ });+ }++ return caveats;+}++// ── CSS injection (once per page) ─────────────────────────────────────────────++const STYLE_ID = 'gm-styles';++function injectStyles() {+ if (document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = `+.gm-overlay{position:fixed;inset:0;z-index:130;display:flex;align-items:center;+ justify-content:center;background:rgba(0,0,0,.85);backdrop-filter:blur(18px);+ -webkit-backdrop-filter:blur(18px);animation:gm-fadein .2s ease}+@keyframes gm-fadein{from{opacity:0}to{opacity:1}}+.gm-modal{width:92vw;max-width:520px;max-height:88vh;display:flex;+ flex-direction:column;background:rgba(10,10,10,.97);+ border:1px solid rgba(255,255,255,.08);border-radius:var(--radius-lg);+ overflow:hidden;box-shadow:0 16px 64px rgba(0,0,0,.7);color:#e0e0e0}+.gm-header{display:flex;align-items:center;justify-content:space-between;+ padding:var(--space-sm) var(--space-lg);border-bottom:1px solid rgba(255,255,255,.06);+ flex-shrink:0}+.gm-title{font-size:var(--text-lg);font-weight:500;color:#fff;letter-spacing:.03em}+.gm-close{background:none;border:none;color:rgba(255,255,255,.4);+ font-size:var(--text-2xl);cursor:pointer;padding:0;line-height:1;transition:color .2s}+.gm-close:hover{color:#fff}+.gm-breadcrumb{display:flex;align-items:center;gap:var(--space-xs);+ padding:var(--space-xs) var(--space-lg);background:rgba(255,255,255,.02);+ border-bottom:1px solid rgba(255,255,255,.04);flex-shrink:0}+.gm-bc-step{font-size:var(--text-sm);color:rgba(255,255,255,.35);white-space:nowrap}+.gm-bc-step--active{color:#fff;font-weight:500}+.gm-bc-sep{color:rgba(255,255,255,.2);font-size:var(--text-xs)}+.gm-body{padding:var(--space-lg);overflow-y:auto;flex:1;min-height:0}+.gm-field{margin-bottom:var(--space-lg)}+.gm-label{display:block;font-size:var(--text-sm);color:rgba(255,255,255,.6);+ margin-bottom:var(--space-xs)}+.gm-input{width:100%;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);+ border-radius:var(--radius-md);color:#e0e0e0;padding:var(--space-xs) var(--space-sm);+ font-size:var(--text-sm);font-family:var(--font-body);outline:none;transition:border .2s}+.gm-input:focus{border-color:var(--accent)}+.gm-input[type=number]{-moz-appearance:textfield}+.gm-fieldset{border:none;padding:0;margin:0 0 var(--space-lg)}+.gm-legend{font-size:var(--text-sm);color:rgba(255,255,255,.6);margin-bottom:var(--space-xs)}+.gm-radio-group{display:flex;flex-wrap:wrap;gap:var(--space-xs)}+.gm-radio-label{display:flex;align-items:center;gap:var(--space-xs);cursor:pointer;+ font-size:var(--text-sm);color:#e0e0e0}+.gm-radio-label input[type=radio]{accent-color:var(--accent)}+.gm-amount-row{display:flex;align-items:center;gap:var(--space-xs)}+.gm-amount-row .gm-input{flex:1}+.gm-token-unit{font-size:var(--text-sm);color:rgba(255,255,255,.5);white-space:nowrap;+ min-width:3rem;text-align:right}+.gm-pills{display:flex;gap:var(--space-xs);flex-wrap:wrap;margin-bottom:var(--space-xs)}+.gm-pill{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.12);+ border-radius:20px;color:rgba(255,255,255,.7);font-size:var(--text-sm);+ padding:var(--space-2xs) var(--space-sm);cursor:pointer;transition:all .15s}+.gm-pill:hover{border-color:var(--accent);color:#fff}+.gm-pill--active{background:var(--accent-soft);border-color:var(--accent);color:#fff}+.gm-targets-list{display:flex;flex-direction:column;gap:var(--space-xs);+ margin-bottom:var(--space-xs)}+.gm-target-row{display:flex;align-items:center;gap:var(--space-xs);+ background:rgba(255,255,255,.04);border-radius:var(--radius-md);+ padding:var(--space-2xs) var(--space-sm)}+.gm-target-addr{font-size:var(--text-sm);font-family:var(--font-mono);flex:1;+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.gm-target-name{font-size:var(--text-xs);color:rgba(255,255,255,.45)}+.gm-target-remove{background:none;border:none;color:rgba(255,255,255,.35);cursor:pointer;+ font-size:var(--text-base);line-height:1;padding:0;transition:color .15s}+.gm-target-remove:hover{color:#e06c75}+.gm-targets-add{display:flex;gap:var(--space-xs);flex-wrap:wrap;align-items:center}+.gm-select{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);+ border-radius:var(--radius-md);color:#e0e0e0;padding:var(--space-2xs) var(--space-sm);+ font-size:var(--text-sm);cursor:pointer;outline:none}+.gm-actions{display:flex;justify-content:flex-end;gap:var(--space-sm);+ padding-top:var(--space-lg);border-top:1px solid rgba(255,255,255,.06)}+.gm-btn{padding:var(--space-xs) var(--space-lg);border-radius:var(--radius-md);+ font-size:var(--text-sm);font-family:var(--font-body);cursor:pointer;+ border:1px solid transparent;transition:all .15s;line-height:1.5}+.gm-btn--primary{background:var(--accent);border-color:var(--accent);color:#fff}+.gm-btn--primary:hover{filter:brightness(1.15)}+.gm-btn--primary:disabled{opacity:.5;cursor:not-allowed;filter:none}+.gm-btn--ghost{background:transparent;border-color:rgba(255,255,255,.2);+ color:rgba(255,255,255,.7)}+.gm-btn--ghost:hover{border-color:rgba(255,255,255,.5);color:#fff}+.gm-btn--sm{padding:var(--space-2xs) var(--space-sm);font-size:var(--text-xs)}+.gm-review-list{list-style:none;padding:0;margin:0 0 var(--space-lg);+ display:flex;flex-direction:column;gap:var(--space-sm)}+.gm-review-item{font-size:var(--text-sm);line-height:var(--leading-loose);+ padding:var(--space-sm) var(--space-md);background:rgba(255,255,255,.04);+ border-radius:var(--radius-md);border-left:3px solid var(--accent)}+.gm-warning{font-size:var(--text-sm);color:#e06c75;padding:var(--space-xs) var(--space-sm);+ background:rgba(224,108,117,.08);border:1px solid rgba(224,108,117,.3);+ border-radius:var(--radius-md);margin-bottom:var(--space-md)}+.gm-status{display:flex;flex-direction:column;align-items:center;gap:var(--space-md);+ padding:var(--space-xl) 0;text-align:center}+.gm-status-icon{font-size:2.5rem;line-height:1}+.gm-status-text{font-size:var(--text-sm);color:rgba(255,255,255,.75)}+.gm-status--success .gm-status-text{color:#98c379}+.gm-status--error .gm-status-text{color:#e06c75}+.gm-error-detail{font-size:var(--text-xs);color:rgba(255,255,255,.4);+ font-family:var(--font-mono);word-break:break-all;text-align:left;+ background:rgba(0,0,0,.3);padding:var(--space-xs);border-radius:var(--radius-md);+ max-width:100%}+.gm-custom-token-row{margin-top:var(--space-xs)}+.gm-chain-group{flex-direction:column;gap:var(--space-xs)}+.gm-chain-row{padding:var(--space-xs) var(--space-sm);background:rgba(255,255,255,.04);+ border-radius:var(--radius-md);border:1px solid rgba(255,255,255,.08);width:100%}+.gm-chain-row:hover{border-color:var(--accent)}+.gm-chain-name{flex:1}+.gm-chain-testnet{font-size:var(--text-xs);color:rgba(255,255,255,.45);+ background:rgba(255,255,255,.06);padding:1px 6px;border-radius:8px;margin-left:auto}+`;+ document.head.appendChild(style);+}++// ── Main class ────────────────────────────────────────────────────────────────++export class GrantPermissionsModal {+ /**+ * @param {{ agentId: string, chainId: number, delegatorAddress: string,+ * delegateAddress: string, presets?: object }} opts+ */+ constructor({ agentId, chainId, delegatorAddress, delegateAddress, presets = {} }) {+ this._agentId = agentId;+ this._chainId = chainId ?? null;+ this._delegatorAddress = delegatorAddress ?? null;+ this._delegateAddress = delegateAddress ?? null;++ // If chainId is missing, start with network picker (step 0).+ this._step = this._chainId ? 1 : 0;+ this._form = {+ token: presets.token ?? 'native',+ customToken: '',+ amount: presets.amount ?? '',+ period: presets.period ?? 'once',+ expiry: presets.expiry ?? '24h',+ customExpiry: '',+ targets: Array.isArray(presets.targets) ? [...presets.targets] : [],+ };++ this._signedDelegation = null;+ this._lastScope = null;++ this.overlay = null;+ this._modal = null;+ this._body = null;+ this._resolve = null;+ this._previouslyFocused = null;+ this._onKeyDown = null;+ this._onOverlayClick = null;+ this._onTrapFocus = null;+ }++ /**+ * Open the modal and return a promise that resolves when the user completes+ * or cancels the flow.+ * @returns {Promise<{ ok: true, id: string, delegationHash: string } | { ok: false, reason: string }>}+ */+ open() {+ if (this.overlay) return Promise.resolve({ ok: false, reason: 'already_open' });+ return new Promise((resolve) => {+ this._resolve = resolve;+ this._previouslyFocused = document.activeElement;+ injectStyles();+ this._build();+ this._wireGlobal();+ this._renderStep(this._chainId ? 1 : 0);+ this._focusFirst();+ });+ }++ close() {+ this._settle({ ok: false, reason: 'closed' });+ this._cleanup();+ }++ // ── Build / teardown ───────────────────────────────────────────────────────++ _build() {+ this.overlay = document.createElement('div');+ this.overlay.className = 'gm-overlay';+ this.overlay.setAttribute('role', 'dialog');+ this.overlay.setAttribute('aria-modal', 'true');+ this.overlay.setAttribute('aria-labelledby', 'gm-title');+ this.overlay.innerHTML = `+ <div class="gm-modal">+ <div class="gm-header">+ <span class="gm-title" id="gm-title">Grant Permissions</span>+ <button type="button" class="gm-close" aria-label="Close">×</button>+ </div>+ <nav class="gm-breadcrumb" aria-label="Steps">+ <span class="gm-bc-step" data-step="0" hidden>0. Network</span>+ <span class="gm-bc-sep gm-bc-sep--0" aria-hidden="true" hidden>›</span>+ <span class="gm-bc-step" data-step="1">1. Scope</span>+ <span class="gm-bc-sep" aria-hidden="true">›</span>+ <span class="gm-bc-step" data-step="2">2. Review</span>+ <span class="gm-bc-sep" aria-hidden="true">›</span>+ <span class="gm-bc-step" data-step="3">3. Sign</span>+ </nav>+ <div class="gm-body"></div>+ </div>+ `;+ document.body.appendChild(this.overlay);+ this._modal = this.overlay.querySelector('.gm-modal');+ this._body = this.overlay.querySelector('.gm-body');+ this.overlay.querySelector('.gm-close').addEventListener('click', () => this.close());+ }++ _wireGlobal() {+ this._onOverlayClick = (e) => {+ if (e.target === this.overlay) this.close();+ };+ this.overlay.addEventListener('click', this._onOverlayClick);++ this._onKeyDown = (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ this.close();+ }+ };+ document.addEventListener('keydown', this._onKeyDown);++ this._onTrapFocus = (e) => {+ if (e.key !== 'Tab') return;+ const items = this._focusables();+ if (!items.length) return;+ const first = items[0];+ const last = items[items.length - 1];+ if (e.shiftKey && document.activeElement === first) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && document.activeElement === last) {+ e.preventDefault();+ first.focus();+ }+ };+ this.overlay.addEventListener('keydown', this._onTrapFocus);+ }++ _cleanup() {+ if (!this.overlay) return;+ if (this._onKeyDown) document.removeEventListener('keydown', this._onKeyDown);+ this.overlay.remove();+ this.overlay = null;+ this._modal = null;+ this._body = null;+ this._onKeyDown = null;+ this._onOverlayClick = null;+ this._onTrapFocus = null;+ const prev = this._previouslyFocused;+ this._previouslyFocused = null;+ if (prev && typeof prev.focus === 'function' && document.contains(prev)) {+ try {+ prev.focus();+ } catch (_) {}+ }+ }++ _settle(result) {+ if (!this._resolve) return;+ const fn = this._resolve;+ this._resolve = null;+ fn(result);+ }++ // ── Step routing ───────────────────────────────────────────────────────────++ _renderStep(n) {+ this._step = n;+ this._body.innerHTML = '';+ this._updateBreadcrumb(n);+ if (n === 0) this._renderStep0();+ else if (n === 1) this._renderStep1();+ else if (n === 2) this._renderStep2();+ else this._renderStep3();+ }++ _updateBreadcrumb(active) {+ // Reveal step 0 in breadcrumb only if it's part of this flow.+ const showStep0 = !this._chainId || active === 0;+ const step0El = this.overlay.querySelector('.gm-bc-step[data-step="0"]');+ const step0Sep = this.overlay.querySelector('.gm-bc-sep--0');+ if (step0El) step0El.hidden = !showStep0;+ if (step0Sep) step0Sep.hidden = !showStep0;++ this.overlay.querySelectorAll('.gm-bc-step').forEach((el) => {+ el.classList.toggle('gm-bc-step--active', Number(el.dataset.step) === active);+ });+ }++ // ── Step 0: Network picker ────────────────────────────────────────────────++ _renderStep0() {+ const chainOptions = SUPPORTED_CHAINS.map(+ (c) => `+ <label class="gm-radio-label gm-chain-row">+ <input type="radio" name="gm-chain" value="${c.id}">+ <span class="gm-chain-name">${escapeHtml(c.name)}</span>+ ${c.testnet ? '<span class="gm-chain-testnet">testnet</span>' : ''}+ </label>`,+ ).join('');++ this._body.innerHTML = `+ <form id="gm-chain-form" novalidate>+ <fieldset class="gm-fieldset">+ <legend class="gm-legend">Choose a network</legend>+ <div class="gm-radio-group gm-chain-group">${chainOptions}</div>+ </fieldset>+ <div class="gm-actions">+ <button type="button" class="gm-btn gm-btn--ghost" id="gm-cancel-btn-0">+ Cancel+ </button>+ <button type="submit" class="gm-btn gm-btn--primary" id="gm-chain-next" disabled>+ Continue →+ </button>+ </div>+ </form>+ `;++ const form = this._body.querySelector('#gm-chain-form');+ const nextBtn = form.querySelector('#gm-chain-next');++ form.querySelectorAll('input[name="gm-chain"]').forEach((radio) => {+ radio.addEventListener('change', () => {+ nextBtn.disabled = false;+ });+ });++ form.querySelector('#gm-cancel-btn-0').addEventListener('click', () => this.close());++ form.addEventListener('submit', (e) => {+ e.preventDefault();+ const checked = form.querySelector('input[name="gm-chain"]:checked');+ if (!checked) return;+ this._chainId = parseInt(checked.value, 10);+ // Reset token to native since per-chain token list changes.+ this._form.token = 'native';+ this._renderStep(1);+ });+ }++ // ── Step 1: Scope builder ─────────────────────────────────────────────────++ _renderStep1() {+ const tokens = tokensForChain(this._chainId);+ const contracts = knownContractsForChain(this._chainId);+ const currentToken = this._form.token;+ const isCustomToken = !tokens.find((t) => t.address === currentToken);+ const currentMeta = tokens.find((t) => t.address === currentToken);+ const unitLabel = currentMeta ? currentMeta.symbol : 'tokens';++ const tokenRadios = tokens+ .map(+ (t) => `+ <label class="gm-radio-label">+ <input type="radio" name="gm-token" value="${escapeHtml(t.address)}"+ ${currentToken === t.address ? 'checked' : ''}>+ ${escapeHtml(t.symbol)}+ </label>`,+ )+ .join('');++ const periodRadios = ['once', 'daily', 'weekly']+ .map(+ (p) => `+ <label class="gm-radio-label">+ <input type="radio" name="gm-period" value="${p}"+ ${this._form.period === p ? 'checked' : ''}>+ ${p.charAt(0).toUpperCase() + p.slice(1)}+ </label>`,+ )+ .join('');++ const expiryPills = ['24h', '7d', '30d', 'custom']+ .map(+ (k) => `+ <button type="button" class="gm-pill ${this._form.expiry === k ? 'gm-pill--active' : ''}"+ data-expiry="${k}">${k === '24h' ? '24 h' : k === '7d' ? '7 d' : k === '30d' ? '30 d' : 'Custom'}+ </button>`,+ )+ .join('');++ const targetRows = this._form.targets+ .map((addr) => {+ const known = contracts.find((c) => c.address.toLowerCase() === addr.toLowerCase());+ return `+ <div class="gm-target-row" data-addr="${escapeHtml(addr)}">+ <span class="gm-target-addr" title="${escapeHtml(addr)}">${escapeHtml(addr)}</span>+ ${known ? `<span class="gm-target-name">${escapeHtml(known.name)}</span>` : ''}+ <button type="button" class="gm-target-remove" aria-label="Remove target"+ data-addr="${escapeHtml(addr)}">×</button>+ </div>`;+ })+ .join('');++ const knownOptions = contracts+ .map((c) => `<option value="${escapeHtml(c.address)}">${escapeHtml(c.name)}</option>`)+ .join('');++ this._body.innerHTML = `+ <form id="gm-scope-form" novalidate>+ <fieldset class="gm-fieldset">+ <legend class="gm-legend">Token</legend>+ <div class="gm-radio-group">+ ${tokenRadios}+ <label class="gm-radio-label">+ <input type="radio" name="gm-token" value="custom"+ ${isCustomToken || currentToken === 'custom' ? 'checked' : ''}>+ Custom+ </label>+ </div>+ <div class="gm-custom-token-row" id="gm-custom-token-row"+ ${!isCustomToken && currentToken !== 'custom' ? 'hidden' : ''}>+ <input type="text" class="gm-input" id="gm-custom-token-input"+ placeholder="0x… ERC-20 address"+ value="${escapeHtml(isCustomToken ? currentToken : '')}">+ </div>+ </fieldset>++ <div class="gm-field">+ <label class="gm-label" for="gm-amount">Max amount</label>+ <div class="gm-amount-row">+ <input type="number" class="gm-input" id="gm-amount" min="0" step="any"+ placeholder="0.00" value="${escapeHtml(this._form.amount)}">+ <span class="gm-token-unit" id="gm-token-unit">${escapeHtml(unitLabel)}</span>+ </div>+ </div>++ <fieldset class="gm-fieldset">+ <legend class="gm-legend">Period</legend>+ <div class="gm-radio-group">${periodRadios}</div>+ </fieldset>++ <div class="gm-field">+ <label class="gm-label">Expiry</label>+ <div class="gm-pills">${expiryPills}</div>+ <input type="datetime-local" class="gm-input" id="gm-expiry-custom"+ value="${escapeHtml(this._form.customExpiry)}"+ ${this._form.expiry !== 'custom' ? 'hidden' : ''}>+ </div>++ <div class="gm-field">+ <label class="gm-label">Allowed targets</label>+ <div class="gm-targets-list" id="gm-targets-list">${targetRows}</div>+ <div class="gm-targets-add">+ ${+ contracts.length+ ? `<select class="gm-select" id="gm-known-select">+ <option value="">Add known contract…</option>+ ${knownOptions}+ </select>`+ : ''+ }+ <button type="button" class="gm-btn gm-btn--ghost gm-btn--sm"+ id="gm-add-custom-btn">+ Custom address</button>+ </div>+ <input type="text" class="gm-input" id="gm-custom-target-input"+ placeholder="0x… target address" style="margin-top:var(--space-xs)" hidden>+ </div>++ <div class="gm-actions">+ <button type="button" class="gm-btn gm-btn--ghost" id="gm-cancel-btn">+ Cancel+ </button>+ <button type="submit" class="gm-btn gm-btn--primary">+ Review →+ </button>+ </div>+ </form>+ `;++ this._bindStep1();+ }++ _bindStep1() {+ const form = this._body.querySelector('#gm-scope-form');+ const customTokenRow = form.querySelector('#gm-custom-token-row');+ const customTokenInput = form.querySelector('#gm-custom-token-input');+ const unitLabel = form.querySelector('#gm-token-unit');+ const expiryCustom = form.querySelector('#gm-expiry-custom');+ const targetsList = form.querySelector('#gm-targets-list');+ const knownSelect = form.querySelector('#gm-known-select');+ const addCustomBtn = form.querySelector('#gm-add-custom-btn');+ const customTargetInput = form.querySelector('#gm-custom-target-input');++ form.querySelectorAll('input[name="gm-token"]').forEach((radio) => {+ radio.addEventListener('change', () => {+ const isCustom = radio.value === 'custom';+ customTokenRow.hidden = !isCustom;+ if (!isCustom) {+ const meta = tokensForChain(this._chainId).find(+ (t) => t.address === radio.value,+ );+ unitLabel.textContent = meta ? meta.symbol : 'tokens';+ } else {+ unitLabel.textContent = 'tokens';+ }+ });+ });++ form.querySelectorAll('.gm-pill[data-expiry]').forEach((btn) => {+ btn.addEventListener('click', () => {+ form.querySelectorAll('.gm-pill[data-expiry]').forEach((b) =>+ b.classList.remove('gm-pill--active'),+ );+ btn.classList.add('gm-pill--active');+ expiryCustom.hidden = btn.dataset.expiry !== 'custom';+ });+ });++ if (knownSelect) {+ knownSelect.addEventListener('change', () => {+ const addr = knownSelect.value;+ if (!addr) return;+ knownSelect.value = '';+ this._addTarget(addr, targetsList);+ });+ }++ addCustomBtn.addEventListener('click', () => {+ customTargetInput.hidden = !customTargetInput.hidden;+ if (!customTargetInput.hidden) {+ customTargetInput.focus();+ }+ });++ customTargetInput.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ const val = customTargetInput.value.trim();+ if (val) {+ try {+ const addr = getAddress(val);+ this._addTarget(addr, targetsList);+ customTargetInput.value = '';+ customTargetInput.hidden = true;+ } catch (_) {+ customTargetInput.style.borderColor = '#e06c75';+ setTimeout(() => (customTargetInput.style.borderColor = ''), 1500);+ }+ }+ }+ });++ targetsList.addEventListener('click', (e) => {+ const btn = e.target.closest('.gm-target-remove');+ if (!btn) return;+ const addr = btn.dataset.addr;+ this._form.targets = this._form.targets.filter(+ (t) => t.toLowerCase() !== addr.toLowerCase(),+ );+ btn.closest('.gm-target-row').remove();+ });++ form.querySelector('#gm-cancel-btn').addEventListener('click', () => this.close());++ form.addEventListener('submit', (e) => {+ e.preventDefault();+ this._collectStep1(form);+ this._renderStep(2);+ });+ }++ _addTarget(addr, listEl) {+ if (this._form.targets.some((t) => t.toLowerCase() === addr.toLowerCase())) return;+ this._form.targets.push(addr);+ const known = knownContractsForChain(this._chainId).find(+ (c) => c.address.toLowerCase() === addr.toLowerCase(),+ );+ const row = document.createElement('div');+ row.className = 'gm-target-row';+ row.dataset.addr = addr;+ row.innerHTML = `+ <span class="gm-target-addr" title="${escapeHtml(addr)}">${escapeHtml(addr)}</span>+ ${known ? `<span class="gm-target-name">${escapeHtml(known.name)}</span>` : ''}+ <button type="button" class="gm-target-remove" aria-label="Remove target"+ data-addr="${escapeHtml(addr)}">×</button>+ `;+ listEl.appendChild(row);+ }++ _collectStep1(form) {+ const checkedToken = form.querySelector('input[name="gm-token"]:checked');+ const tokenVal = checkedToken ? checkedToken.value : 'native';+ if (tokenVal === 'custom') {+ const raw = form.querySelector('#gm-custom-token-input').value.trim();+ this._form.token = raw || 'native';+ } else {+ this._form.token = tokenVal;+ }+ this._form.amount = form.querySelector('#gm-amount').value.trim();+ const checkedPeriod = form.querySelector('input[name="gm-period"]:checked');+ this._form.period = checkedPeriod ? checkedPeriod.value : 'once';+ const activePill = form.querySelector('.gm-pill--active[data-expiry]');+ this._form.expiry = activePill ? activePill.dataset.expiry : '24h';+ this._form.customExpiry = form.querySelector('#gm-expiry-custom').value;+ }++ // ── Step 2: Plain-English review ──────────────────────────────────────────++ _renderStep2() {+ const lines = buildReviewLines(this._form, this._chainId);+ const hasUnknown = this._form.targets.some((addr) => !isKnownTarget(addr, this._chainId));++ const lineItems = lines.map((l) => `<li class="gm-review-item">${l}</li>`).join('');++ this._body.innerHTML = `+ <ul class="gm-review-list" role="list">${lineItems}</ul>+ ${+ hasUnknown+ ? `<div class="gm-warning" role="alert">+ ⚠ One or more target addresses are not on the known-contracts list.+ Verify them before continuing.+ </div>`+ : ''+ }+ <div class="gm-actions">+ <button type="button" class="gm-btn gm-btn--ghost" id="gm-back-btn">+ ← Back+ </button>+ <button type="button" class="gm-btn gm-btn--primary" id="gm-continue-btn">+ Continue to MetaMask →+ </button>+ </div>+ `;++ this._body+ .querySelector('#gm-back-btn')+ .addEventListener('click', () => this._renderStep(1));+ this._body+ .querySelector('#gm-continue-btn')+ .addEventListener('click', () => this._renderStep(3));+ }++ // ── Step 3: Sign + submit ─────────────────────────────────────────────────++ _renderStep3() {+ this._body.innerHTML = `+ <div class="gm-status" id="gm-status" role="status" aria-live="polite">+ <div class="gm-status-icon" id="gm-status-icon">⏳</div>+ <div class="gm-status-text" id="gm-status-text">Preparing…</div>+ </div>+ <div class="gm-actions" id="gm-sign-actions"></div>+ `;+ this._signAndSubmit();+ }++ _setStatus(icon, text, className = '') {+ const status = this._body?.querySelector('#gm-status');+ if (!status) return;+ status.className = 'gm-status' + (className ? ` ${className}` : '');+ const iconEl = status.querySelector('#gm-status-icon');+ const textEl = status.querySelector('#gm-status-text');+ if (iconEl) iconEl.textContent = icon;+ if (textEl) textEl.textContent = text;+ }++ _setActions(html) {+ const el = this._body?.querySelector('#gm-sign-actions');+ if (el) el.innerHTML = html;+ }++ async _signAndSubmit() {+ this._setStatus('⏳', 'Connecting wallet…');++ let signer;+ try {+ const wallet = await ensureWallet();+ signer = wallet.signer;+ // If we don't have a delegator yet, this connection provides it.+ if (!this._delegatorAddress) {+ this._delegatorAddress = wallet.address;+ }+ } catch (err) {+ this._setStatus('✗', `Wallet connection failed: ${err.message}`, 'gm-status--error');+ this._setActions(+ `<button class="gm-btn gm-btn--ghost" id="gm-retry-conn">Retry</button>`,+ );+ this._body+ .querySelector('#gm-retry-conn')+ ?.addEventListener('click', () => this._signAndSubmit());+ return;+ }++ if (!this._delegateAddress) {+ this._setStatus(+ '✗',+ 'Agent has no on-chain address yet. Register the agent first, then grant permissions.',+ 'gm-status--error',+ );+ this._setActions(+ `<button class="gm-btn gm-btn--ghost" id="gm-close-no-delegate">Close</button>`,+ );+ this._body+ .querySelector('#gm-close-no-delegate')+ ?.addEventListener('click', () => this.close());+ return;+ }++ const meta = tokensForChain(this._chainId).find((t) => t.address === this._form.token);+ const decimals = meta ? meta.decimals : 18;+ const maxAmount = toBaseUnits(this._form.amount || '0', decimals);+ const expiry = resolveExpiry(this._form.expiry, this._form.customExpiry);++ const scope = {+ token: this._form.token,+ maxAmount,+ period: this._form.period,+ targets: [...this._form.targets],+ expiry,+ };+ this._lastScope = scope;++ let signed = this._signedDelegation;++ if (!signed) {+ this._setStatus('⏳', 'Waiting for signature…');++ let delegation;+ try {+ const caveats = buildScopeCaveats(scope, this._chainId);+ delegation = encodeScopedDelegation({+ delegator: this._delegatorAddress,+ delegate: this._delegateAddress,+ caveats,+ expiry,+ chainId: this._chainId,+ });+ } catch (err) {+ this._setStatus('✗', `Scope error: ${err.message}`, 'gm-status--error');+ this._setActions(+ `<button class="gm-btn gm-btn--ghost" id="gm-back-from-err">← Back</button>`,+ );+ this._body+ .querySelector('#gm-back-from-err')+ ?.addEventListener('click', () => this._renderStep(1));+ return;+ }++ try {+ signed = await signDelegation({ ...delegation, scope }, signer);+ this._signedDelegation = signed;+ } catch (err) {+ const reason =+ err?.code === 4001 || err?.code === 'ACTION_REJECTED'+ ? 'Signature rejected.'+ : `Signature failed: ${err.message}`;+ this._setStatus('✗', reason, 'gm-status--error');+ this._setActions(`+ <button class="gm-btn gm-btn--ghost" id="gm-back-from-err">← Back</button>+ <button class="gm-btn gm-btn--primary" id="gm-retry-sign">Retry</button>+ `);+ this._body+ .querySelector('#gm-back-from-err')+ ?.addEventListener('click', () => this._renderStep(1));+ this._body.querySelector('#gm-retry-sign')?.addEventListener('click', () => {+ this._signedDelegation = null;+ this._signAndSubmit();+ });+ return;+ }+ }++ await this._submitDelegation(signed, scope);+ }++ async _submitDelegation(signed, scope) {+ this._setStatus('⏳', 'Submitting…');+ this._setActions('');++ let data;+ try {+ const res = await fetch('/api/permissions/grant', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ agentId: this._agentId,+ chainId: this._chainId,+ delegation: signed,+ scope,+ }),+ });+ data = await res.json();++ if (!res.ok) {+ const msg = data?.message || data?.error || `HTTP ${res.status}`;+ throw Object.assign(new Error(msg), { statusCode: res.status });+ }+ } catch (err) {+ const msg = err.message || String(err);+ const isConflict = err.statusCode === 409;++ this._setStatus(+ '✗',+ isConflict ? 'Already granted.' : `Failed: ${msg}`,+ 'gm-status--error',+ );++ const detail = document.createElement('div');+ detail.className = 'gm-error-detail';+ detail.textContent = msg;+ this._body.querySelector('#gm-status')?.appendChild(detail);++ const retryHtml = isConflict+ ? `<button class="gm-btn gm-btn--ghost" id="gm-done-err">Close</button>`+ : `<button class="gm-btn gm-btn--ghost" id="gm-back-from-err">← Back</button>+ <button class="gm-btn gm-btn--primary" id="gm-retry-submit">Retry submit</button>`;+ this._setActions(retryHtml);++ this._body+ .querySelector('#gm-back-from-err')+ ?.addEventListener('click', () => this._renderStep(1));+ this._body+ .querySelector('#gm-retry-submit')+ ?.addEventListener('click', () => this._submitDelegation(signed, scope));+ this._body.querySelector('#gm-done-err')?.addEventListener('click', () => this.close());+ return;+ }++ this._setStatus('✓', 'Granted ✓', 'gm-status--success');+ this._settle({ ok: true, id: data.id, delegationHash: data.delegationHash });++ setTimeout(() => this._cleanup(), 1500);+ }++ // ── Utilities ──────────────────────────────────────────────────────────────++ _focusFirst() {+ const items = this._focusables();+ if (items.length) {+ try {+ items[0].focus();+ } catch (_) {}+ }+ }++ _focusables() {+ if (!this.overlay) return [];+ return Array.from(+ this.overlay.querySelectorAll(+ 'button:not([disabled]), input:not([disabled]):not([hidden]), ' ++ 'select:not([disabled]), [tabindex]:not([tabindex="-1"])',+ ),+ ).filter((el) => !el.closest('[hidden]'));+ }+}++// ── Convenience global (debug or explicit import only) ─────────────────────────++if (typeof window !== 'undefined' && !window.openGrantPermissions) {+ window.openGrantPermissions = (opts) => new GrantPermissionsModal(opts).open();+}++// ── openGrantModal — skill-facing convenience function ────────────────────────++/**+ * Simplified entry point for skills that want to open the grant modal with a+ * scope preset, without needing to resolve wallet addresses themselves.+ *+ * Connects the wallet to get the delegator address, fetches the agent's+ * delegate address from the permissions metadata endpoint, then opens the+ * GrantPermissionsModal with the preset fields pre-filled.+ *+ * @param {{+ * agentId: string,+ * chainId: number,+ * preset: {+ * token: string,+ * maxAmount: string, // base units (e.g. "10000000" for 10 USDC)+ * period: string,+ * targets?: string[],+ * expiry_days?: number,+ * },+ * delegateAddress?: string, // optional override; otherwise fetched from API+ * }} opts+ * @returns {Promise<{ ok: true, id: string, delegationHash: string } | { ok: false, reason: string }>}+ */+export async function openGrantModal({ agentId, chainId, preset, delegateAddress } = {}) {+ // 1. Connect wallet — delegator is whoever is currently signed in+ let delegatorAddress;+ try {+ const { address } = await ensureWallet();+ delegatorAddress = address;+ } catch (err) {+ return { ok: false, reason: `wallet_connection_failed: ${err.message}` };+ }++ // 2. Resolve delegate (agent smart account) from metadata if not provided+ let delegate = delegateAddress;+ if (!delegate) {+ try {+ const url = `/api/permissions/metadata?agentId=${encodeURIComponent(agentId)}&chainId=${encodeURIComponent(chainId)}`;+ const res = await fetch(url);+ const data = res.ok ? await res.json() : null;+ delegate = data?.delegations?.[0]?.delegate ?? null;+ } catch {+ /* ignore */+ }+ }+ if (!delegate) {+ return { ok: false, reason: 'delegate_address_unknown' };+ }++ // 3. Normalize preset — convert maxAmount from base units to display units+ const tokens = tokensForChain(chainId);+ const tokenMeta = preset?.token+ ? tokens.find((t) => t.address.toLowerCase() === preset.token.toLowerCase())+ : null;+ const decimals = tokenMeta?.decimals ?? 6;++ const presets = {};+ if (preset?.token) presets.token = preset.token;+ if (preset?.period) presets.period = preset.period;+ if (preset?.targets) presets.targets = preset.targets;+ if (preset?.maxAmount) presets.amount = String(Number(preset.maxAmount) / 10 ** decimals);+ if (preset?.expiry_days) {+ presets.expiry = '30d';+ }++ return new GrantPermissionsModal({+ agentId,+ chainId,+ delegatorAddress,+ delegateAddress: delegate,+ presets,+ }).open();+}diff --git a/publish/src/permissions/manage-panel.js b/publish/src/permissions/manage-panel.jsnew file mode 100644index 000000000..3332660c6--- /dev/null+++ b/publish/src/permissions/manage-panel.js@@ -0,0 +1,409 @@+/**+ * Manage Permissions Panel+ *+ * Renders a list of all delegations granted for an agent, with revoke support.+ *+ * Public API:+ * mountManagePanel({ container, agentId, agentWalletAddress?, agentChainId? })+ * → { unmount }+ */++import { BrowserProvider, Contract } from 'ethers';+import { CHAIN_META, addressExplorerUrl, txExplorerUrl } from '../erc8004/chain-meta.js';+import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '../erc7710/abi.js';+import { GrantPermissionsModal } from './grant-modal.js';++// ── Public API ────────────────────────────────────────────────────────────────++/**+ * @param {{+ * container: HTMLElement,+ * agentId: string,+ * agentWalletAddress?: string, // The agent's on-chain address (used as delegate)+ * agentChainId?: number, // Default chain to grant on; if absent the modal asks+ * }} opts+ * @returns {{ unmount: () => void }}+ */+export function mountManagePanel({ container, agentId, agentWalletAddress, agentChainId }) {+ const panel = new ManagePanel(container, agentId, { agentWalletAddress, agentChainId });+ panel.mount();+ return { unmount: () => panel.unmount() };+}++// ── Panel class ───────────────────────────────────────────────────────────────++class ManagePanel {+ constructor(container, agentId, { agentWalletAddress, agentChainId } = {}) {+ this._container = container;+ this._agentId = agentId;+ this._agentWalletAddress = agentWalletAddress || null;+ this._agentChainId = agentChainId || null;+ this._root = null;+ this._delegations = [];+ this._onFocus = null;+ }++ mount() {+ this._root = document.createElement('div');+ this._root.className = 'mp-panel';+ this._root.innerHTML = `+ <div class="mp-header">+ <span class="mp-title">Permissions</span>+ <div class="mp-header-actions">+ <button class="mp-grant-header-btn" id="mp-grant-header-btn" title="Grant new permission" hidden>+ + Grant+ </button>+ <button class="mp-refresh-btn" title="Refresh">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">+ <path d="M17.65 6.35A7.958 7.958 0 0 0 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0 1 12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>+ </svg>+ </button>+ </div>+ </div>+ <div class="mp-list" id="mp-list-${this._agentId}">+ <div class="mp-loading">Loading…</div>+ </div>+ `;+ this._container.appendChild(this._root);++ this._root.querySelector('.mp-refresh-btn').addEventListener('click', () => this._load());+ this._root+ .querySelector('#mp-grant-header-btn')+ .addEventListener('click', () => this._openGrantModal());++ this._onFocus = () => this._load();+ window.addEventListener('focus', this._onFocus);++ this._load();+ }++ unmount() {+ if (this._onFocus) window.removeEventListener('focus', this._onFocus);+ this._root?.remove();+ }++ async _load() {+ try {+ const res = await fetch(+ `/api/permissions/list?agentId=${encodeURIComponent(this._agentId)}&status=all&limit=200`,+ { credentials: 'include' },+ );+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();+ if (!data.ok) throw new Error(data.message || 'list failed');+ this._delegations = data.delegations || [];+ this._render();+ } catch (err) {+ this._listEl().innerHTML = `<div class="mp-error">Failed to load: ${_esc(err.message)}</div>`;+ }+ }++ _render() {+ const el = this._listEl();+ const headerGrantBtn = this._root.querySelector('#mp-grant-header-btn');++ if (!this._delegations.length) {+ if (headerGrantBtn) headerGrantBtn.hidden = true;+ const canGrant = Boolean(this._agentWalletAddress);+ const empty = document.createElement('div');+ empty.className = 'mp-empty';+ empty.innerHTML = `+ <p>No permissions granted yet.</p>+ ${+ canGrant+ ? `<button class="mp-grant-btn" id="mp-grant-btn">Grant permissions</button>`+ : `<p class="mp-empty-hint">Register the agent on-chain first to grant it permissions.</p>`+ }+ `;+ el.innerHTML = '';+ el.appendChild(empty);+ el.querySelector('#mp-grant-btn')?.addEventListener('click', () =>+ this._openGrantModal(),+ );+ return;+ }++ if (headerGrantBtn) headerGrantBtn.hidden = !this._agentWalletAddress;++ el.innerHTML = '';+ for (const d of this._delegations) {+ el.appendChild(this._buildCard(d));+ }+ }++ async _openGrantModal() {+ if (!this._agentWalletAddress) {+ // Defensive: button shouldn't be visible without an agent wallet,+ // but fail loud just in case.+ console.warn('[manage-panel] cannot grant: agent has no wallet address');+ return;+ }++ const result = await new GrantPermissionsModal({+ agentId: this._agentId,+ chainId: this._agentChainId || undefined,+ delegateAddress: this._agentWalletAddress,+ // delegatorAddress is filled by ensureWallet() inside the modal+ }).open();++ if (result?.ok) {+ this._load();+ }+ }++ _buildCard(d) {+ const card = document.createElement('div');+ card.className = `mp-card mp-card--${d.status}`;+ card.dataset.id = d.id;++ const chainMeta = CHAIN_META[d.chain_id];+ const chainName = chainMeta?.shortName ?? `${d.chain_id}`;+ const explorerBase = chainMeta?.explorer ?? '';++ const delegatorUrl = explorerBase+ ? addressExplorerUrl(d.chain_id, d.delegator_address)+ : '#';+ const delegateUrl = explorerBase ? addressExplorerUrl(d.chain_id, d.delegate_address) : '#';++ const scopeText = _scopeSentence(d.scope);+ const usageLine = _usageLine(d.redemption_count, d.last_redeemed_at);+ const badgeClass =+ {+ active: 'mp-badge--active',+ revoked: 'mp-badge--revoked',+ expired: 'mp-badge--expired',+ }[d.status] || '';+ const hashShort = d.delegation_hash+ ? `${d.delegation_hash.slice(0, 8)}…${d.delegation_hash.slice(-6)}`+ : 'unknown hash';+ const isPendingIndexer = !d.delegation_hash;++ card.innerHTML = `+ <div class="mp-card-top">+ <span class="mp-badge ${badgeClass}">${d.status}</span>+ <span class="mp-chain-chip">${_esc(chainName)}</span>+ ${isPendingIndexer ? '<span class="mp-indexer-pending">pending indexer</span>' : ''}+ </div>+ <div class="mp-card-scope">${_esc(scopeText)}</div>+ <div class="mp-card-hash">${_esc(hashShort)}</div>+ <div class="mp-card-usage">${_esc(usageLine)}</div>+ <div class="mp-card-addresses">+ <a class="mp-addr-link" href="${_esc(delegatorUrl)}" target="_blank" rel="noopener noreferrer"+ title="Delegator">+ ${_shortAddr(d.delegator_address)}+ </a>+ <span class="mp-addr-arrow" aria-hidden="true">→</span>+ <a class="mp-addr-link" href="${_esc(delegateUrl)}" target="_blank" rel="noopener noreferrer"+ title="Delegate (agent)">+ ${_shortAddr(d.delegate_address)}+ </a>+ </div>+ <div class="mp-card-actions">+ ${+ d.status === 'active'+ ? `<button class="mp-revoke-btn" data-id="${_esc(d.id)}" data-hash="${_esc(d.delegation_hash || '')}" data-chain="${d.chain_id}">Revoke</button>`+ : ''+ }+ </div>+ <div class="mp-card-error" style="display:none"></div>+ <div class="mp-card-pending" style="display:none"></div>+ `;++ const revokeBtn = card.querySelector('.mp-revoke-btn');+ if (revokeBtn) {+ revokeBtn.addEventListener('click', () => this._handleRevoke(card, d));+ }++ return card;+ }++ async _handleRevoke(card, d) {+ const revokeBtn = card.querySelector('.mp-revoke-btn');+ const errorEl = card.querySelector('.mp-card-error');+ const pendingEl = card.querySelector('.mp-card-pending');++ const _showError = (msg) => {+ errorEl.textContent = msg;+ errorEl.style.display = '';+ revokeBtn.disabled = false;+ revokeBtn.textContent = 'Revoke';+ };++ errorEl.style.display = 'none';+ pendingEl.style.display = 'none';++ if (!window.ethereum) {+ _showError('No wallet detected. Please install MetaMask.');+ return;+ }++ let provider, signer, signerAddress;+ try {+ provider = new BrowserProvider(window.ethereum);+ await provider.send('eth_requestAccounts', []);+ signer = await provider.getSigner();+ signerAddress = (await signer.getAddress()).toLowerCase();+ } catch (err) {+ _showError(`Wallet connect failed: ${err.message}`);+ return;+ }++ const delegatorAddr = (d.delegator_address || '').toLowerCase();+ if (signerAddress !== delegatorAddr) {+ _showError(`Connect with ${_shortAddr(d.delegator_address)} to revoke.`);+ return;+ }++ if (!d.delegation_hash) {+ _showError('Delegation hash unknown — cannot revoke on-chain yet.');+ return;+ }++ const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[d.chain_id];+ if (!managerAddr) {+ _showError(`No DelegationManager deployment for chain ${d.chain_id}.`);+ return;+ }++ // Switch to the correct chain+ try {+ const network = await provider.getNetwork();+ if (Number(network.chainId) !== d.chain_id) {+ await provider.send('wallet_switchEthereumChain', [+ { chainId: '0x' + d.chain_id.toString(16) },+ ]);+ }+ } catch (err) {+ _showError(`Chain switch failed: ${err.message}`);+ return;+ }++ revokeBtn.disabled = true;+ revokeBtn.textContent = 'Sending…';++ let tx;+ try {+ const manager = new Contract(managerAddr, DELEGATION_MANAGER_ABI, signer);+ tx = await manager.disableDelegation(d.delegation_hash);+ } catch (err) {+ _showError(err.message);+ return;+ }++ // Show pending state with explorer link+ const explorerTxUrl = txExplorerUrl(d.chain_id, tx.hash);+ pendingEl.innerHTML = `+ <span class="mp-spinner" aria-hidden="true"></span>+ Revoking…+ ${explorerTxUrl ? `<a href="${_esc(explorerTxUrl)}" target="_blank" rel="noopener noreferrer" class="mp-tx-link">view tx</a>` : ''}+ `;+ pendingEl.style.display = '';+ revokeBtn.textContent = 'Pending…';++ try {+ await tx.wait();+ } catch (err) {+ pendingEl.style.display = 'none';+ _showError(`Transaction failed: ${err.message}`);+ return;+ }++ // Mirror to server+ try {+ const res = await fetch('/api/permissions/revoke', {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ id: d.id, txHash: tx.hash }),+ });+ const data = await res.json();+ if (!data.ok) throw new Error(data.message || 'revoke mirror failed');+ } catch (err) {+ // Server mirror failure is non-fatal — on-chain is source of truth.+ console.warn('[manage-panel] server mirror failed:', err.message);+ }++ // Flip card to revoked optimistically+ pendingEl.style.display = 'none';+ card.classList.remove('mp-card--active');+ card.classList.add('mp-card--revoked');+ card.querySelector('.mp-badge').className = 'mp-badge mp-badge--revoked';+ card.querySelector('.mp-badge').textContent = 'revoked';+ revokeBtn.remove();++ // Background refetch to sync any other changes+ setTimeout(() => this._load(), 2000);+ }++ _listEl() {+ return this._root.querySelector(`#mp-list-${this._agentId}`);+ }+}++// ── Helpers ───────────────────────────────────────────────────────────────────++function _esc(str) {+ return String(str ?? '').replace(+ /[<>&"]/g,+ (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[c],+ );+}++function _shortAddr(addr) {+ if (!addr) return 'unknown';+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}++function _scopeSentence(scope) {+ if (!scope) return 'Unknown scope';+ const { token, maxAmount, period, targets, expiry } = scope;+ const tokenLabel =+ token && token !== 'native'+ ? _shortAddr(token)+ : token === 'native'+ ? 'native token'+ : 'token';+ const amountLabel = maxAmount ? _formatAmount(maxAmount) : '?';+ const periodLabel =+ { daily: 'per day', weekly: 'per week', once: 'once' }[period] || period || '';+ const targetLabel =+ targets?.length === 1+ ? `on ${_shortAddr(targets[0])}`+ : targets?.length > 1+ ? `on ${targets.length} contracts`+ : '';+ const expiryLabel = expiry ? `until ${_formatDate(expiry)}` : '';+ const parts = [+ `Up to ${amountLabel} ${tokenLabel}`,+ periodLabel,+ targetLabel,+ expiryLabel,+ ].filter(Boolean);+ return parts.join(' ');+}++function _formatAmount(raw) {+ const n = Number(raw);+ if (!Number.isFinite(n)) return raw;+ // Assume 6 decimals (USDC-style) for display. Real code would look up token decimals.+ const display = n / 1e6;+ return display >= 1 ? display.toLocaleString() : raw;+}++function _formatDate(unixSeconds) {+ const d = new Date(unixSeconds * 1000);+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });+}++function _usageLine(count, lastAt) {+ const c = count ?? 0;+ const redemptionPart = `${c} redemption${c !== 1 ? 's' : ''}`;+ if (!lastAt) return redemptionPart;+ const diff = Date.now() - new Date(lastAt).getTime();+ let ago;+ if (diff < 60_000) ago = 'just now';+ else if (diff < 3_600_000) ago = `${Math.floor(diff / 60_000)}m ago`;+ else if (diff < 86_400_000) ago = `${Math.floor(diff / 3_600_000)}h ago`;+ else ago = _formatDate(Math.floor(new Date(lastAt).getTime() / 1000));+ return `${redemptionPart} · last used ${ago}`;+}diff --git a/publish/src/permissions/toolkit.js b/publish/src/permissions/toolkit.jsnew file mode 100644index 000000000..ac632234d--- /dev/null+++ b/publish/src/permissions/toolkit.js@@ -0,0 +1,375 @@+/**+ * ERC-7710 delegation toolkit — single facade over all delegation operations.+ * Consumers import from here; never import @metamask/delegation-toolkit directly.+ * Usable in both browser (wallet signer) and Node (relayer signer).+ *+ * Uses ethers v6 directly — @metamask/delegation-toolkit transitive deps exceed+ * 5 MB threshold (@metamask/delegation-abis alone is 6.2 MB unpacked).+ */++import {+ AbiCoder,+ Contract,+ getAddress,+ JsonRpcProvider,+ randomBytes,+ TypedDataEncoder,+} from 'ethers';+import {+ CAVEAT_ENFORCERS,+ DELEGATION_MANAGER_ABI,+ DELEGATION_MANAGER_DEPLOYMENTS,+ DELEGATION_TYPES,+ EIP712_DOMAIN,+ ROOT_AUTHORITY,+} from '../erc7710/abi.js';++// ─── Error type ──────────────────────────────────────────────────────────────++/**+ * Typed error for all delegation operations.+ * `code` matches the canonical OAuth-style error codes from 00-README.md.+ */+export class PermissionError extends Error {+ /**+ * @param {string} code - delegation_expired | delegation_revoked | scope_exceeded |+ * target_not_allowed | delegation_not_found | signature_invalid |+ * chain_not_supported | rate_limited+ * @param {string} message+ */+ constructor(code, message) {+ super(message);+ this.code = code;+ this.name = 'PermissionError';+ }+}++// ─── Internal helpers ────────────────────────────────────────────────────────++/**+ * @param {unknown} addr+ * @param {string} label+ * @returns {string} EIP-55 checksummed address+ * @throws {PermissionError} signature_invalid+ */+function checksum(addr, label) {+ try {+ return getAddress(/** @type {string} */ (addr));+ } catch {+ throw new PermissionError('signature_invalid', `Invalid address for ${label}: ${addr}`);+ }+}++/**+ * @param {number} chainId+ * @returns {string} DelegationManager address+ * @throws {PermissionError} chain_not_supported+ */+function managerAddress(chainId) {+ const addr = DELEGATION_MANAGER_DEPLOYMENTS[chainId];+ if (!addr)+ throw new PermissionError(+ 'chain_not_supported',+ `No DelegationManager deployment for chain ${chainId}`,+ );+ return addr;+}++/**+ * ABI-encode a delegation array into the bytes expected by permissionContexts[i].+ * Format: abi.encode(Delegation[]) per @metamask/delegation-core DELEGATION_ARRAY_ABI_TYPES.+ * @param {object[]} delegations+ * @returns {string} 0x-prefixed hex+ */+function encodePermissionContext(delegations) {+ const coder = AbiCoder.defaultAbiCoder();+ const tuples = delegations.map((d) => [+ d.delegate,+ d.delegator,+ d.authority ?? ROOT_AUTHORITY,+ (d.caveats ?? []).map((c) => [c.enforcer, c.terms ?? '0x', c.args ?? '0x']),+ d.salt ?? 0n,+ d.signature ?? '0x',+ ]);+ return coder.encode(+ ['tuple(address,address,bytes32,tuple(address,bytes,bytes)[],uint256,bytes)[]'],+ [tuples],+ );+}++/**+ * ERC-7579 packed execution calldata for a single call.+ * encodePacked(address target, uint256 value, bytes callData)+ * @param {string} to+ * @param {bigint|number|string} value+ * @param {string} data+ * @returns {string} 0x-prefixed hex+ */+function encodeSingleExecution(to, value, data) {+ const coder = AbiCoder.defaultAbiCoder();+ // abi.encode is safe here — ERC-7579's decodeSingle uses byte-slice offsets+ // but the MetaMask DelegationManager accepts standard abi.encode for single mode.+ return coder.encode(['address', 'uint256', 'bytes'], [to, value ?? 0n, data ?? '0x']);+}++// ERC-7579 single-call, default execution mode (callType=0x01, execType=0x00).+const SINGLE_DEFAULT_MODE = '0x0100000000000000000000000000000000000000000000000000000000000000';++// ─── Public API ──────────────────────────────────────────────────────────────++/**+ * Build an unsigned delegation envelope ready to be EIP-712 signed.+ * Pure and synchronous — no network I/O.+ *+ * @param {{+ * delegator: string,+ * delegate: string,+ * caveats: Array<{ enforcer: string, terms: string, args?: string }>,+ * expiry: number,+ * chainId: number,+ * }} opts+ * @returns {{+ * delegate: string,+ * delegator: string,+ * authority: string,+ * caveats: Array<{ enforcer: string, terms: string, args: string }>,+ * salt: bigint,+ * expiry: number,+ * chainId: number,+ * }}+ * @throws {PermissionError} signature_invalid | delegation_expired | chain_not_supported+ */+export function encodeScopedDelegation({ delegator, delegate, caveats, expiry, chainId }) {+ const delegatorAddr = checksum(delegator, 'delegator');+ const delegateAddr = checksum(delegate, 'delegate');++ if (delegateAddr === delegatorAddr) {+ throw new PermissionError('signature_invalid', 'delegate must differ from delegator');+ }+ if (!Array.isArray(caveats) || caveats.length < 1) {+ throw new PermissionError('signature_invalid', 'at least one caveat is required');+ }+ if (expiry <= Math.floor(Date.now() / 1000) + 60) {+ throw new PermissionError(+ 'delegation_expired',+ 'expiry must be at least 60 seconds in the future',+ );+ }++ managerAddress(chainId); // throws chain_not_supported if unknown++ const normalizedCaveats = caveats.map((c, i) => ({+ enforcer: checksum(c.enforcer, `caveats[${i}].enforcer`),+ terms: c.terms ?? '0x',+ args: c.args ?? '0x',+ }));++ // Cryptographically random 32-byte salt to prevent replay.+ const salt = BigInt('0x' + Buffer.from(randomBytes(32)).toString('hex'));++ return {+ delegate: delegateAddr,+ delegator: delegatorAddr,+ authority: ROOT_AUTHORITY,+ caveats: normalizedCaveats,+ salt,+ expiry,+ chainId,+ };+}++/**+ * Sign a delegation using EIP-712.+ * Returns the delegation enriched with `signature` and `hash`.+ * Only the hash is safe to log — never log the signature itself.+ *+ * @param {{+ * delegate: string,+ * delegator: string,+ * authority: string,+ * caveats: Array<{ enforcer: string, terms: string, args: string }>,+ * salt: bigint,+ * chainId: number,+ * }} delegation - unsigned delegation from encodeScopedDelegation+ * @param {import('ethers').Signer} signer - ethers v6 signer (must support signTypedData)+ * @returns {Promise<{ signature: string, hash: string } & typeof delegation>}+ * @throws {PermissionError} chain_not_supported | signature_invalid+ */+export async function signDelegation(delegation, signer) {+ if (!signer) throw new PermissionError('signature_invalid', 'signer is required');++ const verifyingContract = managerAddress(delegation.chainId);+ const domain = EIP712_DOMAIN({ chainId: delegation.chainId, verifyingContract });++ const typedValue = {+ delegate: delegation.delegate,+ delegator: delegation.delegator,+ authority: delegation.authority ?? ROOT_AUTHORITY,+ caveats: delegation.caveats,+ salt: delegation.salt ?? 0n,+ };++ let signature;+ try {+ signature = await signer.signTypedData(domain, DELEGATION_TYPES, typedValue);+ } catch (err) {+ throw new PermissionError('signature_invalid', `EIP-712 signing failed: ${err.message}`);+ }++ // Compute hash locally using the same encoder ethers uses for signTypedData.+ const hash = TypedDataEncoder.hash(domain, DELEGATION_TYPES, typedValue);++ return { ...delegation, signature, hash };+}++/**+ * Redeem a signed delegation by submitting redeemDelegations to the DelegationManager.+ * Verifies on-chain that the delegation is not revoked before spending gas.+ *+ * @param {{+ * delegation: object,+ * calls: Array<{ to: string, value?: bigint|number|string, data?: string }>,+ * signer: import('ethers').Signer,+ * chainId: number,+ * }} opts+ * @returns {Promise<{ txHash: string, receipt: object }>}+ * @throws {PermissionError} delegation_revoked | chain_not_supported | signature_invalid+ */+export async function redeemDelegation({ delegation, calls, signer, chainId }) {+ if (!signer) throw new PermissionError('signature_invalid', 'signer is required');+ if (!signer.provider)+ throw new PermissionError('chain_not_supported', 'signer has no provider attached');++ const addr = managerAddress(chainId);++ // Pre-flight: check delegation is not disabled on-chain.+ const dmRead = new Contract(addr, DELEGATION_MANAGER_ABI, signer.provider);+ const disabled = await dmRead.disabledDelegations(delegation.hash);+ if (disabled)+ throw new PermissionError('delegation_revoked', 'delegation has been revoked on-chain');++ // Build permissionContexts: one entry per call, each wrapping the same delegation chain.+ const permissionContext = encodePermissionContext([delegation]);+ const permissionContexts = calls.map(() => permissionContext);+ const modes = calls.map(() => SINGLE_DEFAULT_MODE);+ const executionCallDatas = calls.map((c) =>+ encodeSingleExecution(checksum(c.to, 'calls[].to'), c.value ?? 0n, c.data ?? '0x'),+ );++ const dmWrite = new Contract(addr, DELEGATION_MANAGER_ABI, signer);+ const tx = await dmWrite.redeemDelegations(permissionContexts, modes, executionCallDatas);+ const receipt = await tx.wait();++ return {+ txHash: tx.hash,+ receipt: {+ status: receipt.status,+ blockNumber: receipt.blockNumber,+ gasUsed: receipt.gasUsed.toString(),+ },+ };+}++/**+ * Read-only check that a delegation hash is valid on-chain.+ * Checks: not disabled on-chain. Pass `delegation` for expiry + signature checks.+ *+ * @param {{+ * hash: string,+ * chainId: number,+ * rpcUrl?: string,+ * delegation?: object,+ * }} opts+ * @returns {Promise<{ valid: boolean, reason?: string }>}+ * @throws {PermissionError} chain_not_supported (if chain unknown)+ */+export async function isDelegationValid({ hash, chainId, rpcUrl, delegation }) {+ const addr = managerAddress(chainId); // throws if unsupported++ const url =+ rpcUrl ?? (typeof process !== 'undefined' ? process.env[`RPC_URL_${chainId}`] : undefined);+ if (!url) return { valid: false, reason: 'no rpcUrl provided for on-chain check' };++ try {+ const provider = new JsonRpcProvider(url);+ const dm = new Contract(addr, DELEGATION_MANAGER_ABI, provider);++ const disabled = await dm.disabledDelegations(hash);+ if (disabled) return { valid: false, reason: 'delegation_revoked' };++ // Expiry check if full delegation object available.+ if (delegation?.expiry) {+ if (delegation.expiry <= Math.floor(Date.now() / 1000)) {+ return { valid: false, reason: 'delegation_expired' };+ }+ }++ // Signature recovery check if full delegation object available.+ if (delegation?.signature && delegation?.delegator) {+ const verifyingContract = addr;+ const domain = EIP712_DOMAIN({ chainId, verifyingContract });+ const typedValue = {+ delegate: delegation.delegate,+ delegator: delegation.delegator,+ authority: delegation.authority ?? ROOT_AUTHORITY,+ caveats: delegation.caveats,+ salt: delegation.salt,+ };+ const recovered = TypedDataEncoder.recoverAddress(+ domain,+ DELEGATION_TYPES,+ typedValue,+ delegation.signature,+ );+ if (recovered.toLowerCase() !== delegation.delegator.toLowerCase()) {+ return { valid: false, reason: 'signature_invalid' };+ }+ }++ return { valid: true };+ } catch (err) {+ return { valid: false, reason: err.message };+ }+}++/**+ * Map a signed delegation into the manifest permissions.delegations[] shape.+ * Pure and synchronous — no network I/O.+ *+ * @param {{+ * chainId: number,+ * delegator: string,+ * delegate: string,+ * hash: string,+ * uri?: string,+ * scope?: { token: string, maxAmount: string, period: string, targets: string[], expiry: number },+ * expiry?: number,+ * }} signedDelegation+ * @returns {{+ * chainId: number,+ * delegator: string,+ * delegate: string,+ * hash: string,+ * uri?: string,+ * scope: { token: string, maxAmount: string, period: string, targets: string[], expiry: number },+ * }}+ */+export function delegationToManifestEntry(signedDelegation) {+ const { chainId, delegator, delegate, hash, uri, scope, expiry } = signedDelegation;+ return {+ chainId,+ delegator,+ delegate,+ hash,+ ...(uri ? { uri } : {}),+ scope: scope ?? {+ token: 'native',+ maxAmount: '0',+ period: 'once',+ targets: [],+ expiry: expiry ?? 0,+ },+ };+}++export { CAVEAT_ENFORCERS };diff --git a/publish/src/pinning/_retry.js b/publish/src/pinning/_retry.jsnew file mode 100644index 000000000..02903b8d9--- /dev/null+++ b/publish/src/pinning/_retry.js@@ -0,0 +1,81 @@+/**+ * Shared retry + XHR-with-progress helpers.+ */++/**+ * Retry an async operation with exponential backoff.+ * 4xx responses fail fast; 5xx and network errors retry up to maxAttempts.+ *+ * @param {function(): Promise<*>} fn+ * @param {number} [maxAttempts=3]+ * @returns {Promise<*>}+ */+export async function withRetry(fn, maxAttempts = 3) {+ let lastError;+ for (let attempt = 0; attempt < maxAttempts; attempt++) {+ try {+ return await fn();+ } catch (err) {+ // Preserve provider error bodies on 4xx — don't retry+ if (err.status !== undefined && err.status < 500) throw err;+ lastError = err;+ if (attempt < maxAttempts - 1) {+ await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, attempt)));+ }+ }+ }+ throw lastError;+}++/**+ * Fetch wrapper that emits upload progress for blobs >1MB via onProgress(pct).+ * Falls back to plain fetch when onProgress is not provided or blob is small.+ *+ * @param {string} url+ * @param {RequestInit & {onProgress?: function(number): void}} opts+ * @returns {Promise<Response>}+ */+export function fetchWithProgress(url, opts = {}) {+ const { onProgress, body, ...fetchOpts } = opts;+ const size = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.length : 0;++ if (!onProgress || size <= 1024 * 1024) {+ return fetch(url, { ...fetchOpts, body });+ }++ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open(fetchOpts.method || 'POST', url);+ for (const [k, v] of Object.entries(fetchOpts.headers || {})) {+ xhr.setRequestHeader(k, v);+ }+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));+ };+ xhr.onload = () => {+ // Wrap in a minimal Response-like object so callers can use .ok / .json()+ const status = xhr.status;+ const responseText = xhr.responseText;+ resolve({+ ok: status >= 200 && status < 300,+ status,+ headers: { get: (h) => xhr.getResponseHeader(h) },+ text: () => Promise.resolve(responseText),+ json: () => Promise.resolve(JSON.parse(responseText)),+ });+ };+ xhr.onerror = () => reject(new Error('Network error during upload'));+ xhr.send(body);+ });+}++/**+ * Build a StatusError with the status code attached.+ * @param {number} status+ * @param {string} message+ */+export function statusError(status, message) {+ const err = new Error(message);+ err.status = status;+ return err;+}diff --git a/publish/src/pinning/filebase.js b/publish/src/pinning/filebase.jsnew file mode 100644index 000000000..06aaf459e--- /dev/null+++ b/publish/src/pinning/filebase.js@@ -0,0 +1,118 @@+/**+ * Filebase S3-compatible IPFS pinning backend.+ *+ * Filebase exposes an S3 API at https://s3.filebase.com.+ * After a PutObject, the IPFS CID is available via HeadObject in+ * the x-amz-meta-cid response header.+ *+ * The @aws-sdk/client-s3 is dynamically imported so non-Filebase users+ * do not pay the bundle cost.+ *+ * pinDirectory: uploads each file under a common key prefix, then returns the+ * CID of the first file as a best-effort root. Note: Filebase does not expose+ * a true directory-wrapped IPFS CID via S3; for proper directory CIDs use Pinata.+ */++import { withRetry, statusError } from './_retry.js';++export class FilebasePinner {+ /**+ * @param {object} opts+ * @param {string} opts.accessKeyId Filebase S3 access key ID+ * @param {string} opts.secretAccessKey Filebase S3 secret access key+ * @param {string} opts.bucket Target bucket name+ * @param {string} [opts.region='us-east-1']+ */+ constructor({ accessKeyId, secretAccessKey, bucket, region = 'us-east-1' } = {}) {+ this._creds = { accessKeyId, secretAccessKey };+ this._bucket = bucket;+ this._region = region;+ this._client = null;+ }++ async _getClient() {+ if (this._client) return this._client;+ const { S3Client } = await import('@aws-sdk/client-s3');+ this._client = new S3Client({+ region: this._region,+ endpoint: 'https://s3.filebase.com',+ credentials: this._creds,+ // Path-style required by Filebase+ forcePathStyle: true,+ });+ return this._client;+ }++ /**+ * @param {Blob|Uint8Array} blob+ * @param {{name?: string, onProgress?: function(number): void}=} opts+ * @returns {Promise<{cid: string, size: number}>}+ */+ async pinBlob(blob, opts = {}) {+ const { name = `upload-${Date.now()}` } = opts;+ const { PutObjectCommand, HeadObjectCommand } = await import('@aws-sdk/client-s3');+ const client = await this._getClient();++ const body = blob instanceof Uint8Array ? blob : new Uint8Array(await blob.arrayBuffer());+ const size = body.length;++ await withRetry(async () => {+ const res = await client.send(+ new PutObjectCommand({+ Bucket: this._bucket,+ Key: name,+ Body: body,+ ContentType: blob instanceof Blob ? blob.type : 'application/octet-stream',+ }),+ );+ if (res.$metadata?.httpStatusCode >= 500) {+ throw statusError(res.$metadata.httpStatusCode, 'Filebase PutObject failed');+ }+ });++ const head = await withRetry(async () => {+ return client.send(new HeadObjectCommand({ Bucket: this._bucket, Key: name }));+ });++ const cid = head.Metadata?.cid;+ if (!cid) throw new Error('Filebase did not return an IPFS CID in x-amz-meta-cid');++ return { cid, size };+ }++ /**+ * Uploads each file under a shared prefix. Returns the CID of the first file.+ * Not a true directory-wrapped CID — use Pinata for {cid}/{path} resolution.+ *+ * @param {Array<{path: string, data: Blob|Uint8Array}>} files+ * @param {{name?: string, onProgress?: function(number): void}=} opts+ * @returns {Promise<{cid: string, size: number}>}+ */+ async pinDirectory(files, opts = {}) {+ const { name = `dir-${Date.now()}` } = opts;+ let firstCid = null;+ let totalSize = 0;++ for (const { path, data } of files) {+ const key = `${name}/${path}`;+ const { cid, size } = await this.pinBlob(data, { name: key });+ totalSize += size;+ if (!firstCid) firstCid = cid;+ }++ if (!firstCid) throw new Error('No files provided to pinDirectory');+ return { cid: firstCid, size: totalSize };+ }++ /**+ * Delete the S3 object — Filebase will eventually GC the underlying IPFS pin.+ * @param {string} key The S3 key (not CID) used at upload time+ */+ async unpin(key) {+ const { DeleteObjectCommand } = await import('@aws-sdk/client-s3');+ const client = await this._getClient();+ await withRetry(() =>+ client.send(new DeleteObjectCommand({ Bucket: this._bucket, Key: key })),+ );+ }+}diff --git a/publish/src/pinning/index.js b/publish/src/pinning/index.jsnew file mode 100644index 000000000..244885bab--- /dev/null+++ b/publish/src/pinning/index.js@@ -0,0 +1,80 @@+/**+ * Pluggable IPFS pinning abstraction.+ *+ * @typedef {object} Pinner+ * @property {function(Blob|Uint8Array, {name?: string, wrapInDir?: boolean, onProgress?: function(number): void}=): Promise<{cid: string, size: number}>} pinBlob+ * @property {function(Array<{path: string, data: Blob|Uint8Array}>, {onProgress?: function(number): void}=): Promise<{cid: string, size: number}>} pinDirectory+ * @property {function(string): Promise<void>} unpin+ */++import { Web3StoragePinner } from './web3-storage.js';+import { FilebasePinner } from './filebase.js';+import { PinataPinner } from './pinata.js';+import { NullDevPinner } from './null-dev.js';++const PROVIDERS = ['web3-storage', 'filebase', 'pinata', 'null-dev'];++/** @type {Pinner|null} */+let _defaultPinner = null;++/**+ * Build a Pinner from a config object.+ *+ * @param {object} config+ * @param {'web3-storage'|'filebase'|'pinata'|'null-dev'} [config.provider='web3-storage']+ * @param {string} [config.token] API key / JWT for web3-storage or pinata+ * @param {string} [config.accessKeyId] Filebase S3 access key+ * @param {string} [config.secretAccessKey] Filebase S3 secret key+ * @param {string} [config.bucket] Filebase bucket name+ * @returns {Pinner}+ */+export function createPinner(config = {}) {+ const { provider = 'web3-storage', ...opts } = config;+ switch (provider) {+ case 'web3-storage':+ return new Web3StoragePinner(opts);+ case 'filebase':+ return new FilebasePinner(opts);+ case 'pinata':+ return new PinataPinner(opts);+ case 'null-dev':+ return new NullDevPinner(opts);+ default:+ throw new Error(+ `Unknown pinning provider "${provider}". Supported: ${PROVIDERS.join(', ')}`,+ );+ }+}++/**+ * Get the process-wide default pinner.+ *+ * Initialisation order:+ * 1. Explicitly set via setPinner()+ * 2. window.__agent3dPinner (Pinner instance or config object)+ * 3. null-dev (safe fallback — fake CIDs, in-memory storage)+ *+ * @returns {Pinner}+ */+export function getPinner() {+ if (_defaultPinner) return _defaultPinner;++ if (typeof window !== 'undefined' && window.__agent3dPinner) {+ const cfg = window.__agent3dPinner;+ _defaultPinner = typeof cfg.pinBlob === 'function' ? cfg : createPinner(cfg);+ return _defaultPinner;+ }++ _defaultPinner = new NullDevPinner();+ return _defaultPinner;+}++/**+ * Set the process-wide default pinner.+ * @param {Pinner} pinner+ */+export function setPinner(pinner) {+ _defaultPinner = pinner;+}++export { Web3StoragePinner, FilebasePinner, PinataPinner, NullDevPinner };diff --git a/publish/src/pinning/null-dev.js b/publish/src/pinning/null-dev.jsnew file mode 100644index 000000000..8f2385e74--- /dev/null+++ b/publish/src/pinning/null-dev.js@@ -0,0 +1,97 @@+/**+ * Null / dev pinner — no network calls, no credentials needed.+ *+ * Hashes the blob with SHA-256 and returns a fake CID in the form+ * `bafkdev<hex>`. Content is kept in an in-memory Map for the session,+ * so nullDevFetch(cid) resolves the round-trip in tests and dev.+ *+ * CIDs produced here are NOT valid IPFS CIDs and will NOT resolve on+ * public IPFS gateways. Use a real provider in production.+ */++/** @type {Map<string, Uint8Array>} */+const _store = new Map();++async function _sha256Hex(bytes) {+ const hash = await crypto.subtle.digest('SHA-256', bytes);+ return Array.from(new Uint8Array(hash))+ .map((b) => b.toString(16).padStart(2, '0'))+ .join('');+}++async function _toBytes(blob) {+ return blob instanceof Uint8Array ? blob : new Uint8Array(await blob.arrayBuffer());+}++export class NullDevPinner {+ /**+ * @param {Blob|Uint8Array} blob+ * @returns {Promise<{cid: string, size: number}>}+ */+ async pinBlob(blob, _opts = {}) {+ const bytes = await _toBytes(blob);+ const hex = await _sha256Hex(bytes);+ const cid = `bafkdev${hex.slice(0, 40)}`;+ _store.set(cid, bytes);+ return { cid, size: bytes.length };+ }++ /**+ * Stores each file under its path and creates an index entry keyed by dirCid.+ * Resolve individual files with nullDevFetch(dirCid, 'path/to/file').+ *+ * @param {Array<{path: string, data: Blob|Uint8Array}>} files+ * @returns {Promise<{cid: string, size: number}>}+ */+ async pinDirectory(files, _opts = {}) {+ const index = {};+ let totalSize = 0;++ for (const { path, data } of files) {+ const bytes = await _toBytes(data);+ const hex = await _sha256Hex(bytes);+ const fileCid = `bafkdev${hex.slice(0, 40)}`;+ _store.set(fileCid, bytes);+ index[path] = fileCid;+ totalSize += bytes.length;+ }++ const indexBytes = new TextEncoder().encode(JSON.stringify(index));+ const hex = await _sha256Hex(indexBytes);+ const dirCid = `bafkdevdir${hex.slice(0, 36)}`;+ // Store index under a magic suffix so nullDevFetch can locate it+ _store.set(dirCid + '/\x00index', indexBytes);+ return { cid: dirCid, size: totalSize };+ }++ /**+ * Remove pinned content from the in-memory store.+ * @param {string} cid+ */+ async unpin(cid) {+ _store.delete(cid);+ _store.delete(cid + '/\x00index');+ }+}++/**+ * Fetch content pinned by NullDevPinner.+ *+ * @param {string} cid A CID returned by pinBlob or pinDirectory+ * @param {string} [path] File path within a pinned directory+ * @returns {Uint8Array|null}+ */+export function nullDevFetch(cid, path) {+ if (!path) return _store.get(cid) ?? null;++ const indexBytes = _store.get(cid + '/\x00index');+ if (!indexBytes) return null;+ const index = JSON.parse(new TextDecoder().decode(indexBytes));+ const fileCid = index[path];+ return fileCid ? (_store.get(fileCid) ?? null) : null;+}++/** Wipe the entire in-memory store (useful between tests). */+export function nullDevClear() {+ _store.clear();+}diff --git a/publish/src/pinning/pinata.js b/publish/src/pinning/pinata.jsnew file mode 100644index 000000000..d64836707--- /dev/null+++ b/publish/src/pinning/pinata.js@@ -0,0 +1,130 @@+/**+ * Pinata pinning backend.+ *+ * API docs — https://docs.pinata.cloud/api-reference/endpoint/ipfs/pin-file-to-ipfs+ * Auth: Authorization: Bearer <JWT>+ *+ * pinBlob: POST /pinning/pinFileToIPFS (FormData, single file)+ * pinDirectory: POST /pinning/pinFileToIPFS (FormData, multiple files + wrapWithDirectory)+ * unpin: DELETE /pinning/unpin/:cid+ */++import { withRetry, fetchWithProgress, statusError } from './_retry.js';++const BASE = 'https://api.pinata.cloud';++export class PinataPinner {+ /**+ * @param {object} opts+ * @param {string} opts.token Pinata JWT+ */+ constructor({ token } = {}) {+ this._token = token || '';+ }++ /** @returns {object} */+ _headers() {+ return { Authorization: `Bearer ${this._token}` };+ }++ /**+ * @param {Blob|Uint8Array} blob+ * @param {{name?: string, wrapInDir?: boolean, onProgress?: function(number): void}=} opts+ * @returns {Promise<{cid: string, size: number}>}+ */+ async pinBlob(blob, opts = {}) {+ const { name = 'upload', wrapInDir = false, onProgress } = opts;+ const form = new FormData();+ const file = blob instanceof Uint8Array ? new Blob([blob]) : blob;+ form.append('file', file, name);+ form.append('pinataMetadata', JSON.stringify({ name }));+ if (wrapInDir) {+ form.append('pinataOptions', JSON.stringify({ wrapWithDirectory: true }));+ }++ const size = blob instanceof Uint8Array ? blob.length : blob.size;++ const res = await withRetry(() =>+ fetchWithProgress(`${BASE}/pinning/pinFileToIPFS`, {+ method: 'POST',+ headers: this._headers(),+ body: form,+ onProgress,+ }).then(async (r) => {+ if (!r.ok) {+ const body = await r.text().catch(() => '');+ throw statusError(r.status, `Pinata upload failed (${r.status}): ${body}`);+ }+ return r;+ }),+ );++ const data = await res.json();+ return { cid: data.IpfsHash, size };+ }++ /**+ * Upload a set of files as an IPFS directory.+ * Returns a directory-wrapped CID; individual files resolve as {cid}/{path}.+ *+ * @param {Array<{path: string, data: Blob|Uint8Array}>} files+ * @param {{name?: string, onProgress?: function(number): void}=} opts+ * @returns {Promise<{cid: string, size: number}>}+ */+ async pinDirectory(files, opts = {}) {+ const { name = 'directory', onProgress } = opts;+ const form = new FormData();+ let totalSize = 0;++ for (const { path, data } of files) {+ const blob = data instanceof Uint8Array ? new Blob([data]) : data;+ totalSize += blob.size;+ // Pinata treats the filename as the path within the directory+ form.append('file', blob, path);+ }++ form.append('pinataMetadata', JSON.stringify({ name }));+ form.append('pinataOptions', JSON.stringify({ wrapWithDirectory: true }));++ const res = await withRetry(() =>+ fetchWithProgress(`${BASE}/pinning/pinFileToIPFS`, {+ method: 'POST',+ headers: this._headers(),+ body: form,+ onProgress,+ }).then(async (r) => {+ if (!r.ok) {+ const body = await r.text().catch(() => '');+ throw statusError(+ r.status,+ `Pinata directory upload failed (${r.status}): ${body}`,+ );+ }+ return r;+ }),+ );++ const data = await res.json();+ return { cid: data.IpfsHash, size: totalSize };+ }++ /**+ * @param {string} cid+ * @returns {Promise<void>}+ */+ async unpin(cid) {+ const res = await withRetry(() =>+ fetch(`${BASE}/pinning/unpin/${cid}`, {+ method: 'DELETE',+ headers: this._headers(),+ }).then(async (r) => {+ if (!r.ok) {+ const body = await r.text().catch(() => '');+ throw statusError(r.status, `Pinata unpin failed (${r.status}): ${body}`);+ }+ return r;+ }),+ );+ return res;+ }+}diff --git a/publish/src/pinning/web3-storage.js b/publish/src/pinning/web3-storage.jsnew file mode 100644index 000000000..25288cfbe--- /dev/null+++ b/publish/src/pinning/web3-storage.js@@ -0,0 +1,79 @@+/**+ * web3.storage pinning backend.+ *+ * HTTP API v1 — https://web3.storage/docs/reference/http-api/+ * Single file: POST https://api.web3.storage/upload (raw body, Authorization: Bearer)+ * Response: { cid: string }+ *+ * Directory pinning requires CAR format (not implemented here). Use pinata when+ * directory-wrapped CIDs are needed.+ */++import { withRetry, fetchWithProgress, statusError } from './_retry.js';++const UPLOAD_URL = 'https://api.web3.storage/upload';++export class Web3StoragePinner {+ /**+ * @param {object} opts+ * @param {string} opts.token web3.storage API token+ */+ constructor({ token } = {}) {+ this._token = token || '';+ }++ /**+ * @param {Blob|Uint8Array} blob+ * @param {{name?: string, onProgress?: function(number): void}=} opts+ * @returns {Promise<{cid: string, size: number}>}+ */+ async pinBlob(blob, opts = {}) {+ const { name, onProgress } = opts;+ const headers = {+ Authorization: `Bearer ${this._token}`,+ 'Content-Type': blob.type || 'application/octet-stream',+ };+ if (name) headers['X-NAME'] = name;++ const size = blob instanceof Uint8Array ? blob.length : blob.size;++ const res = await withRetry(() =>+ fetchWithProgress(UPLOAD_URL, {+ method: 'POST',+ headers,+ body: blob,+ onProgress,+ }).then(async (r) => {+ if (!r.ok) {+ const body = await r.text().catch(() => '');+ throw statusError(+ r.status,+ `web3.storage upload failed (${r.status}): ${body}`,+ );+ }+ return r;+ }),+ );++ const { cid } = await res.json();+ return { cid, size };+ }++ /**+ * Directory pinning via web3.storage requires CAR format; not supported here.+ * Use Pinata for directory-wrapped CIDs.+ */+ async pinDirectory(_files, _opts = {}) {+ throw statusError(+ 501,+ 'web3.storage pinDirectory requires CAR format — use Pinata for directory-wrapped CIDs',+ );+ }++ /**+ * web3.storage does not expose an HTTP unpin endpoint in v1.+ */+ async unpin(_cid) {+ throw statusError(501, 'web3.storage HTTP API v1 does not support unpin');+ }+}diff --git a/publish/src/pump/agent-token-widget.js b/publish/src/pump/agent-token-widget.jsnew file mode 100644index 000000000..3dfa8ac3e--- /dev/null+++ b/publish/src/pump/agent-token-widget.js@@ -0,0 +1,819 @@+/**+ * AgentTokenWidget — the $AGENT card on the agent passport.+ *+ * Self-contained: pass a mount node + agentId, it figures out the rest. Reads:+ * GET /api/pump/by-agent?agent_id=… (mint + stats + burn history)+ * GET /api/pump/balances?mint=… (live vault balances, polled)+ * GET /api/pump/quote?mint=… (price + graduation status)+ * GET /api/pump/payments-list?mint=… (recent receipts feed)+ *+ * Emits on the protocol bus (when one is passed):+ * `pump-balance` { paymentDelta, buybackDelta, withdrawDelta }+ * `pump-graduated` { mint }+ * `pump-payment` { payer, atomics, skill }+ *+ * Renders four states: not-launched, launching, live (curve), live (AMM).+ * Live state shows: ticker, price, buyback gauge, 3 vault balances, burns,+ * recent payment feed, owner withdraw button, governance explainer.+ */++const POLL_MS = 10_000;++function fmtUsdc(atomics) {+ const n = Number(BigInt(atomics || '0')) / 1_000_000;+ if (n === 0) return '$0.00';+ if (n < 0.01) return `<$0.01`;+ return `$${n.toFixed(n < 1 ? 4 : 2)}`;+}++function fmtSol(lamports) {+ if (!lamports) return '0 SOL';+ const n = Number(lamports) / 1_000_000_000;+ return `${n.toFixed(n < 1 ? 4 : 2)} SOL`;+}++function fmtBps(bps) {+ if (bps == null) return '—';+ return `${(bps / 100).toFixed(bps % 100 === 0 ? 0 : 1)}%`;+}++function shortAddr(s, n = 4) {+ if (!s) return '';+ return `${s.slice(0, n)}…${s.slice(-n)}`;+}++function timeAgo(iso) {+ if (!iso) return '';+ const ms = Date.now() - new Date(iso).getTime();+ if (ms < 60_000) return `${Math.max(1, Math.floor(ms / 1000))}s ago`;+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ago`;+ if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)}h ago`;+ return `${Math.floor(ms / 86_400_000)}d ago`;+}++const STYLES = `+.atok {+ max-width: 520px; margin: 1.5rem auto; padding: 1.25rem 1.4rem;+ border: 1px solid rgba(255,255,255,0.08); border-radius: 14px;+ background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0));+ color: #e5e5e5; font: 14px/1.5 Inter, sans-serif;+}+.atok-head {+ display: flex; align-items: baseline; justify-content: space-between;+ gap: 0.6rem; margin-bottom: 0.25rem;+}+.atok-symbol {+ font-size: 1.05rem; font-weight: 500; letter-spacing: 0.03em;+}+.atok-symbol .atok-sigil { color: rgba(255,255,255,0.45); margin-right: 0.18em; }+.atok-status {+ font-size: 0.7rem; padding: 0.1rem 0.5rem; border-radius: 999px;+ background: rgba(120,200,140,0.12); color: rgba(180,230,200,0.95);+ letter-spacing: 0.03em;+}+.atok-status.curve { background: rgba(120,160,255,0.12); color: rgba(180,210,255,0.95); }+.atok-status.empty { background: rgba(255,255,255,0.04); color: rgba(255,255,255,0.45); }+.atok-status.error { background: rgba(255,140,140,0.1); color: rgba(255,180,180,0.95); }+.atok-price-row {+ display: flex; align-items: baseline; gap: 0.6rem; margin-top: 0.1rem;+}+.atok-price {+ font-size: 1.4rem; font-weight: 300; color: #fff; font-variant-numeric: tabular-nums;+ transition: color 0.4s ease;+}+.atok-price.tick-up { color: #a4f0bc; }+.atok-price.tick-down { color: #f6b3b3; }+.atok-price-label {+ font-size: 0.72rem; color: rgba(255,255,255,0.4); letter-spacing: 0.05em; text-transform: uppercase;+}++.atok-grad-bar {+ height: 4px; background: rgba(255,255,255,0.05); border-radius: 999px;+ margin: 0.9rem 0 0.3rem; overflow: hidden;+}+.atok-grad-fill {+ height: 100%; background: linear-gradient(90deg, #6a93ff, #a4f0bc);+ transition: width 0.6s cubic-bezier(.2,.8,.2,1);+}+.atok-grad-label {+ font-size: 0.7rem; color: rgba(255,255,255,0.5); display: flex; justify-content: space-between;+}++.atok-buyback {+ margin-top: 1rem; padding: 0.7rem 0.85rem; border-radius: 10px;+ background: rgba(255,255,255,0.025);+ display: flex; align-items: center; gap: 0.7rem;+}+.atok-buyback-gauge {+ flex: 1; height: 6px; background: rgba(255,255,255,0.05); border-radius: 999px; overflow: hidden;+}+.atok-buyback-fill {+ height: 100%; background: linear-gradient(90deg, #f6b3b3, #ffd57a, #a4f0bc);+ transition: width 0.8s cubic-bezier(.2,.8,.2,1);+}+.atok-buyback-label {+ font-size: 0.78rem; white-space: nowrap; color: rgba(255,255,255,0.85);+ font-variant-numeric: tabular-nums;+}+.atok-buyback-explain {+ font-size: 0.7rem; color: rgba(255,255,255,0.45); margin-top: 0.35rem; line-height: 1.45;+}+.atok-buyback-explain b { color: rgba(255,255,255,0.85); font-weight: 500; }++.atok-vaults {+ display: grid; grid-template-columns: repeat(3, 1fr);+ gap: 0.5rem; margin-top: 0.9rem;+}+.atok-vault {+ padding: 0.55rem 0.7rem; border-radius: 8px; background: rgba(255,255,255,0.025);+}+.atok-vault-name {+ font-size: 0.65rem; color: rgba(255,255,255,0.45); letter-spacing: 0.06em; text-transform: uppercase;+}+.atok-vault-val {+ font-size: 0.95rem; margin-top: 0.15rem; font-variant-numeric: tabular-nums;+ transition: color 0.4s ease;+}+.atok-vault-val.tick-up { color: #a4f0bc; }+.atok-vault-payment .atok-vault-name { color: rgba(180,210,255,0.6); }+.atok-vault-buyback .atok-vault-name { color: rgba(255,200,140,0.6); }+.atok-vault-withdraw .atok-vault-name { color: rgba(180,230,200,0.6); }++.atok-burned {+ margin-top: 0.7rem; padding: 0.55rem 0.7rem; border-radius: 8px;+ background: rgba(120,200,140,0.06); color: rgba(200,240,210,0.9);+ font-size: 0.78rem;+}+.atok-burned b { color: #d8f5e2; font-weight: 500; }++.atok-feed {+ margin-top: 1rem; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 0.7rem;+}+.atok-feed-title {+ font-size: 0.7rem; letter-spacing: 0.06em; text-transform: uppercase;+ color: rgba(255,255,255,0.45); margin-bottom: 0.4rem;+}+.atok-feed-row {+ display: flex; justify-content: space-between; gap: 0.6rem;+ padding: 0.3rem 0; font-size: 0.8rem; color: rgba(255,255,255,0.78);+}+.atok-feed-row + .atok-feed-row { border-top: 1px solid rgba(255,255,255,0.03); }+.atok-feed-row code { font-family: ui-monospace, monospace; color: rgba(255,255,255,0.5); font-size: 0.75rem; }+.atok-feed-row .atok-buyback-pill {+ font-size: 0.65rem; padding: 0.05rem 0.4rem; border-radius: 999px;+ background: rgba(255,200,140,0.08); color: rgba(255,210,160,0.85); white-space: nowrap;+}++.atok-actions { display: flex; gap: 0.5rem; margin-top: 1rem; }+.atok-btn {+ flex: 1; padding: 0.55rem 0.8rem; border-radius: 8px; cursor: pointer;+ background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.07);+ color: rgba(255,255,255,0.85); font-size: 0.82rem; transition: 0.15s;+}+.atok-btn:hover { background: rgba(255,255,255,0.07); border-color: rgba(255,255,255,0.14); }+.atok-btn[disabled] { opacity: 0.45; cursor: not-allowed; }+.atok-btn-primary {+ background: rgba(120,200,140,0.16); border-color: rgba(120,200,140,0.3); color: #d8f5e2;+}+.atok-btn-primary:hover { background: rgba(120,200,140,0.22); }++.atok-empty {+ text-align: center; padding: 1rem 0.5rem; color: rgba(255,255,255,0.6);+}+.atok-empty-title { font-weight: 500; color: rgba(255,255,255,0.85); margin-bottom: 0.3rem; }+.atok-empty-sub { font-size: 0.82rem; color: rgba(255,255,255,0.5); line-height: 1.5; }++.atok-gov {+ margin-top: 0.8rem; font-size: 0.72rem; color: rgba(255,255,255,0.45);+ border-left: 2px solid rgba(255,200,140,0.2); padding: 0.3rem 0.6rem;+}+.atok-gov b { color: rgba(255,200,140,0.85); font-weight: 500; }++.atok-rep {+ margin-top: 0.7rem; padding: 0.45rem 0.7rem; border-radius: 8px;+ background: rgba(255,200,140,0.05); display: flex; align-items: center; gap: 0.5rem;+ font-size: 0.82rem; color: rgba(255,220,180,0.95);+}+.atok-rep-stars { letter-spacing: 0.04em; color: #ffd57a; }+.atok-rep-num { font-variant-numeric: tabular-nums; color: #fff; }+.atok-rep-meta { color: rgba(255,255,255,0.5); font-size: 0.75rem; }++.atok-mobile-strip {+ display: none;+}++@media (max-width: 640px) {+ .atok { margin: 0.6rem; padding: 1rem; }+ .atok-vaults { grid-template-columns: 1fr 1fr 1fr; gap: 0.35rem; }+ .atok-vault { padding: 0.45rem 0.5rem; }+ .atok-vault-val { font-size: 0.85rem; }+ .atok-mobile-strip {+ display: flex; position: fixed; bottom: 0; left: 0; right: 0;+ padding: 0.7rem 1rem env(safe-area-inset-bottom, 0.7rem);+ background: rgba(8,8,10,0.92); backdrop-filter: blur(12px);+ border-top: 1px solid rgba(255,255,255,0.06); gap: 0.6rem; align-items: center;+ z-index: 50;+ }+ .atok-mobile-price { flex: 1; font-variant-numeric: tabular-nums; }+ .atok-mobile-price small { display: block; font-size: 0.65rem; color: rgba(255,255,255,0.5); }+ .atok-mobile-pay {+ padding: 0.55rem 1rem; border-radius: 8px; cursor: pointer;+ background: rgba(120,200,140,0.18); border: 1px solid rgba(120,200,140,0.3);+ color: #d8f5e2; font-size: 0.85rem;+ }+}+`;++let stylesInjected = false;+function injectStyles() {+ if (stylesInjected) return;+ const tag = document.createElement('style');+ tag.textContent = STYLES;+ document.head.appendChild(tag);+ stylesInjected = true;+}++export class AgentTokenWidget {+ /**+ * @param {object} opts+ * @param {HTMLElement} opts.mount+ * @param {string} opts.agentId+ * @param {boolean} [opts.isOwner]+ * @param {EventTarget} [opts.protocol]+ * @param {object} [opts.identity]+ */+ constructor({ mount, agentId, isOwner = false, protocol = null, identity = null }) {+ this.mount = mount;+ this.agentId = agentId;+ this.isOwner = isOwner;+ this.protocol = protocol;+ this.identity = identity;+ this.token = null; // /api/pump/by-agent payload+ this.balances = null;+ this.quote = null;+ this.feed = [];+ this.reputation = null; // /api/agents/solana-reputation snapshot+ this.lastPrice = null;+ this.lastVaults = null;+ this.lastFeedTop = null;+ this._mobileStrip = null;+ this._poll = null;+ this._destroyed = false;+ this._wsUnsubs = []; // realtime onAccountChange subscriptions+ this._wsConn = null;+ injectStyles();+ }++ async render() {+ this.mount.classList.add('atok-mount');+ this.mount.innerHTML = `<div class="atok"><div class="atok-empty">Loading $AGENT…</div></div>`;+ await this._refresh();+ if (this.token) {+ // Polling is the fallback. Real-time vault subscription kicks in via+ // _ensureRealtime() and shrinks the polling interval to a long beat+ // (60s) used only for stats/feed/quote that lack account-subscriptions.+ this._poll = setInterval(() => this._refresh().catch(() => {}), 60_000);+ this._ensureRealtime().catch(() => {});+ }+ }++ destroy() {+ this._destroyed = true;+ if (this._poll) clearInterval(this._poll);+ this._teardownRealtime();+ if (this._mobileStrip?.parentNode) this._mobileStrip.parentNode.removeChild(this._mobileStrip);+ }++ async _ensureRealtime() {+ if (!this.token || !this.balances) return;+ if (this._wsUnsubs.length) return; // already subscribed+ try {+ const [{ Connection, PublicKey }] = await Promise.all([import('@solana/web3.js')]);+ const url =+ this.token.network === 'devnet'+ ? 'https://api.devnet.solana.com'+ : 'https://api.mainnet-beta.solana.com';+ const conn = new Connection(url, 'confirmed');+ this._wsConn = conn;+ const subscribe = (addr, name) => {+ if (!addr) return;+ try {+ const id = conn.onAccountChange(+ new PublicKey(addr),+ () => this._refreshBalancesOnly().catch(() => {}),+ 'confirmed',+ );+ this._wsUnsubs.push({ id, conn });+ } catch {+ /* ignore subscription failures, polling fallback covers it */+ }+ };+ subscribe(this.balances.payment?.address, 'payment');+ subscribe(this.balances.buyback?.address, 'buyback');+ subscribe(this.balances.withdraw?.address, 'withdraw');+ } catch {+ /* RPC may not support websocket; polling continues */+ }+ }++ _teardownRealtime() {+ for (const sub of this._wsUnsubs) {+ try {+ sub.conn.removeAccountChangeListener(sub.id);+ } catch {+ /* swallow */+ }+ }+ this._wsUnsubs = [];+ this._wsConn = null;+ }++ async _refreshBalancesOnly() {+ if (this._destroyed || !this.token) return;+ try {+ const balRes = await fetch(+ `/api/pump/balances?mint=${this.token.mint}&network=${this.token.network}`,+ ).then((r) => r.json());+ if (balRes.balances) {+ this._compareAndEmit(balRes.balances, this.feed);+ this.balances = balRes.balances;+ this._renderLive();+ }+ } catch {+ /* silent */+ }+ }++ async _refresh() {+ if (this._destroyed) return;+ try {+ const tokenResp = await fetch(`/api/pump/by-agent?agent_id=${this.agentId}`).then((r) =>+ r.json(),+ );+ this.token = tokenResp.data;+ } catch (e) {+ this._renderError(e.message);+ return;+ }++ if (!this.token) {+ this._renderEmpty();+ return;+ }++ // Live state: parallel fetch balances, quote, feed, and reputation+ // overlay. Reputation lookup keys off the agent's metaplex-core asset+ // pubkey from the parent identity (passed in via the `identity` prop).+ try {+ const repAsset = this.identity?.meta?.sol_mint_address || this.identity?.meta?.onchain?.onchain_id || null;+ const [balRes, quoteRes, feedRes, repRes] = await Promise.all([+ fetch(+ `/api/pump/balances?mint=${this.token.mint}&network=${this.token.network}`,+ ).then((r) => r.json()),+ fetch(+ `/api/pump/quote?mint=${this.token.mint}&network=${this.token.network}&direction=buy&sol=1`,+ ).then((r) => r.json()),+ fetch(+ `/api/pump/payments-list?mint=${this.token.mint}&network=${this.token.network}&limit=8`,+ ).then((r) => r.json()),+ repAsset+ ? fetch(+ `/api/agents/solana-reputation?asset=${repAsset}&network=${this.token.network}`,+ )+ .then((r) => r.json())+ .catch(() => null)+ : Promise.resolve(null),+ ]);+ this._compareAndEmit(balRes.balances, feedRes.data);+ this.balances = balRes.balances || null;+ this.quote = quoteRes || null;+ this.feed = feedRes.data || [];+ this.reputation = repRes || null;+ this._renderLive();+ this._ensureRealtime().catch(() => {});+ } catch (e) {+ this._renderError(e.message);+ }+ }++ _compareAndEmit(newBal, newFeed) {+ // Vault deltas → emit pump-balance event so other modules (avatar, etc.)+ // can react to live revenue.+ if (this.lastVaults && newBal && this.protocol?.emit) {+ const dPay = this._delta(newBal.payment, this.lastVaults.payment);+ const dBuy = this._delta(newBal.buyback, this.lastVaults.buyback);+ const dWdr = this._delta(newBal.withdraw, this.lastVaults.withdraw);+ if (dPay || dBuy || dWdr) {+ this.protocol.emit('pump-balance', {+ paymentDelta: dPay,+ buybackDelta: dBuy,+ withdrawDelta: dWdr,+ });+ }+ }+ this.lastVaults = newBal;++ // New top-of-feed → emit pump-payment so avatar can celebrate.+ if (newFeed && newFeed.length) {+ const top = newFeed[0];+ if (this.lastFeedTop && this.lastFeedTop !== top.id) {+ this.protocol?.emit?.('pump-payment', {+ payer: top.payer_wallet,+ atomics: top.amount_atomics,+ skill: top.skill_id,+ tool: top.tool_name,+ });+ }+ this.lastFeedTop = top.id;+ }++ // Graduation transition → one-time celebration.+ if (+ this.quote &&+ this.lastQuoteGraduated === false &&+ this.quote.graduated === true+ ) {+ this.protocol?.emit?.('pump-graduated', { mint: this.token.mint });+ }+ if (this.quote) this.lastQuoteGraduated = this.quote.graduated;+ }++ _delta(a, b) {+ try {+ return Number(BigInt(a?.balance ?? '0') - BigInt(b?.balance ?? '0'));+ } catch {+ return 0;+ }+ }++ _renderEmpty() {+ const ownerCta = this.isOwner+ ? `<div style="margin-top:0.7rem"><a href="/dashboard/pump-launch?agent=${this.agentId}" class="atok-btn atok-btn-primary" style="text-decoration:none;display:inline-block">Launch $AGENT →</a></div>`+ : '';+ this.mount.innerHTML = `+ <div class="atok">+ <div class="atok-head">+ <div class="atok-symbol"><span class="atok-sigil">$</span>AGENT</div>+ <div class="atok-status empty">not launched</div>+ </div>+ <div class="atok-empty">+ <div class="atok-empty-title">No agent token yet</div>+ <div class="atok-empty-sub">+ When this agent launches a pump.fun token, every paid call funds+ an on-chain receipt that splits revenue between an automatic+ buyback and the owner. ${this.isOwner ? 'Configure once, accrue forever.' : 'Be the first to fund it.'}+ </div>+ ${ownerCta}+ </div>+ </div>`;+ }++ _renderError(msg) {+ this.mount.innerHTML = `+ <div class="atok">+ <div class="atok-head">+ <div class="atok-symbol"><span class="atok-sigil">$</span>AGENT</div>+ <div class="atok-status error">offline</div>+ </div>+ <div class="atok-empty"><div class="atok-empty-sub">${msg || 'Could not load token state.'}</div></div>+ </div>`;+ }++ _renderLive() {+ const t = this.token;+ const b = this.balances || {};+ const q = this.quote || {};+ const symbol = t.symbol || 'AGENT';+ const graduated = q.graduated === true;+ const buybackBps = t.buyback_bps || 0;+ const buybackPct = buybackBps / 100;++ // Curve progress+ let progressPct = null;+ if (!graduated && q.bonding_curve) {+ const real = Number(q.bonding_curve.real_token_reserves || 0);+ const virt = Number(q.bonding_curve.virtual_token_reserves || 0);+ if (virt > 0) progressPct = Math.max(0, Math.min(100, (1 - real / virt) * 100));+ }++ // Live price expressed as USDC of 1 SOL → tokens out (curve) or null (AMM).+ const priceText =+ q.quote && q.quote.tokens_out+ ? `${Number(q.quote.tokens_out).toLocaleString()} ${symbol}`+ : graduated+ ? 'graduated'+ : '—';++ const tickClass =+ this.lastPrice != null && q.quote?.tokens_out+ ? Number(q.quote.tokens_out) > Number(this.lastPrice)+ ? 'tick-up'+ : Number(q.quote.tokens_out) < Number(this.lastPrice)+ ? 'tick-down'+ : ''+ : '';+ this.lastPrice = q.quote?.tokens_out;++ const stats = t.stats || {};+ const burns = t.burns || { runs: 0, total_burned: '0' };+ const totalBurned = burns.total_burned && burns.total_burned !== '0'+ ? `<div class="atok-burned">🔥 <b>${fmtUsdc(burns.total_burned)}</b> burned across ${burns.runs} buyback${burns.runs === 1 ? '' : 's'}.</div>`+ : '';++ const projection =+ stats.confirmed_payments > 0+ ? `${fmtUsdc((BigInt(stats.total_atomics || '0') * BigInt(buybackBps)) / 10_000n)} routed to buyback so far across <b>${stats.unique_payers}</b> unique payer${stats.unique_payers === 1 ? '' : 's'}.`+ : `If this agent earns <b>$10/mo</b>, buyback burns <b>${fmtUsdc((10_000_000n * BigInt(buybackBps)) / 10_000n)}/mo</b> of $${symbol}.`;++ const solscanCluster = this.token.network === 'devnet' ? '?cluster=devnet' : '';+ const feedRows = (this.feed || [])+ .slice(0, 5)+ .map((p) => {+ const why = p.tool_name+ ? `<code>${p.tool_name}</code>`+ : p.skill_id+ ? `<code>${p.skill_id}</code>`+ : 'paid call';+ const buybackShare = (BigInt(p.amount_atomics || '0') * BigInt(buybackBps)) / 10_000n;+ const pdaLink = p.invoice_pda+ ? `<a href="https://solscan.io/account/${p.invoice_pda}${solscanCluster}" target="_blank" rel="noopener" title="Open on-chain invoice receipt" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">PDA↗</a>`+ : '';+ const txLink = p.tx_signature+ ? `<a href="https://solscan.io/tx/${p.tx_signature}${solscanCluster}" target="_blank" rel="noopener" title="Open settlement tx" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">tx↗</a>`+ : '';+ return `+ <div class="atok-feed-row">+ <div>${shortAddr(p.payer_wallet, 4)} · ${why}</div>+ <div style="display:flex;gap:0.5rem;align-items:center;">+ <span>${fmtUsdc(p.amount_atomics)}</span>+ ${buybackBps > 0 ? `<span class="atok-buyback-pill">+${fmtUsdc(buybackShare)} 🔥</span>` : ''}+ ${pdaLink}+ ${txLink}+ <span style="color:rgba(255,255,255,0.35);font-size:0.7rem;">${timeAgo(p.confirmed_at || p.created_at)}</span>+ </div>+ </div>`;+ })+ .join('');++ // Burns feed (separate from payments)+ const burnsFeedRows = (t.burns_feed || [])+ .slice(0, 5)+ .map((b) => `+ <div class="atok-feed-row">+ <div>🔥 burn</div>+ <div style="display:flex;gap:0.5rem;align-items:center;">+ <span>${fmtUsdc(b.burn_amount || '0')}</span>+ ${b.tx_signature ? `<a href="https://solscan.io/tx/${b.tx_signature}${solscanCluster}" target="_blank" rel="noopener" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">tx↗</a>` : ''}+ <span style="color:rgba(255,255,255,0.35);font-size:0.7rem;">${timeAgo(b.created_at)}</span>+ </div>+ </div>`)+ .join('');+ const burnsBlock = burnsFeedRows+ ? `<div class="atok-feed">+ <div class="atok-feed-title">Buybacks</div>+ ${burnsFeedRows}+ </div>`+ : '';++ // Reputation overlay+ const rep = this.reputation;+ const repBlock = rep && rep.feedback?.total > 0+ ? `<div class="atok-rep" title="Reputation drives auto-governance of buyback share.">+ <span class="atok-rep-stars">${'★'.repeat(Math.round(rep.feedback.score_avg_weighted || rep.feedback.score_avg || 0))}${'☆'.repeat(5 - Math.round(rep.feedback.score_avg_weighted || rep.feedback.score_avg || 0))}</span>+ <span class="atok-rep-num">${(rep.feedback.score_avg_weighted || rep.feedback.score_avg || 0).toFixed(2)}</span>+ <span class="atok-rep-meta">· ${rep.feedback.total} review${rep.feedback.total === 1 ? '' : 's'}${rep.feedback.unique_attesters ? ` · ${rep.feedback.unique_attesters} unique` : ''}</span>+ </div>`+ : '';++ const feedBlock = feedRows+ ? `<div class="atok-feed">+ <div class="atok-feed-title">Recent payments</div>+ ${feedRows}+ </div>`+ : stats.confirmed_payments === 0+ ? `<div class="atok-feed">+ <div class="atok-feed-title">Recent payments</div>+ <div class="atok-empty-sub">First payment will fund: <b>${buybackPct}%</b> buyback, <b>${100 - buybackPct}%</b> to owner.</div>+ </div>`+ : '';++ const ownerActions = this.isOwner+ ? `<div class="atok-actions">+ <button class="atok-btn atok-withdraw" ${+ BigInt(b.withdraw?.balance || '0') === 0n ? 'disabled' : ''+ }>+ Withdraw ${fmtUsdc(b.withdraw?.balance || '0')}+ </button>+ <button class="atok-btn atok-governance">Buyback ${fmtBps(buybackBps)} ⚙</button>+ </div>`+ : `<div class="atok-actions">+ <button class="atok-btn atok-btn-primary atok-pay">Pay this agent</button>+ </div>`;++ const govExplain =+ buybackBps > 0+ ? `<div class="atok-gov">+ <b>Buyback ${fmtBps(buybackBps)}</b> of every paid call burns $${symbol}.+ If this agent's reputation drops below <b>3.5★</b> for 7 days, buyback auto-lowers.+ </div>`+ : '';++ this.mount.innerHTML = `+ <div class="atok">+ <div class="atok-head">+ <div class="atok-symbol"><span class="atok-sigil">$</span>${symbol}</div>+ <div class="atok-status ${graduated ? 'live' : 'curve'}">+ ${graduated ? 'graduated' : 'bonding curve'}+ </div>+ </div>++ <div class="atok-price-row">+ <div class="atok-price ${tickClass}">${priceText}</div>+ <div class="atok-price-label">${q.quote ? 'per 1 SOL' : ''}</div>+ </div>++ ${+ progressPct != null+ ? `<div class="atok-grad-bar"><div class="atok-grad-fill" style="width:${progressPct.toFixed(1)}%"></div></div>+ <div class="atok-grad-label"><span>${progressPct.toFixed(1)}% to graduation</span><span>${graduated ? 'AMM' : 'curve'}</span></div>`+ : graduated+ ? `<div class="atok-grad-label" style="margin-top:0.6rem"><span>🎓 Graduated to AMM</span><span></span></div>`+ : ''+ }++ <div class="atok-buyback">+ <div class="atok-buyback-gauge"><div class="atok-buyback-fill" style="width:${buybackPct}%"></div></div>+ <div class="atok-buyback-label">${fmtBps(buybackBps)} buyback</div>+ </div>+ <div class="atok-buyback-explain">${projection}</div>++ <div class="atok-vaults">+ <div class="atok-vault atok-vault-payment">+ <div class="atok-vault-name">Pending</div>+ <div class="atok-vault-val ${this._tickClassFor('payment', b.payment?.balance)}">${fmtUsdc(b.payment?.balance || '0')}</div>+ </div>+ <div class="atok-vault atok-vault-buyback">+ <div class="atok-vault-name">Buyback</div>+ <div class="atok-vault-val ${this._tickClassFor('buyback', b.buyback?.balance)}">${fmtUsdc(b.buyback?.balance || '0')}</div>+ </div>+ <div class="atok-vault atok-vault-withdraw">+ <div class="atok-vault-name">Owner</div>+ <div class="atok-vault-val ${this._tickClassFor('withdraw', b.withdraw?.balance)}">${fmtUsdc(b.withdraw?.balance || '0')}</div>+ </div>+ </div>++ ${totalBurned}+ ${repBlock}+ ${govExplain}+ ${feedBlock}+ ${burnsBlock}+ ${ownerActions}+ </div>+ `;++ this._wireActions();+ this._updateMobileStrip(symbol, priceText);+ }++ _tickClassFor(name, newBal) {+ const last = this._lastVaultBalances || {};+ const cls =+ last[name] != null && newBal != null+ ? BigInt(newBal) > BigInt(last[name])+ ? 'tick-up'+ : ''+ : '';+ this._lastVaultBalances = { ...last, [name]: newBal };+ return cls;+ }++ _wireActions() {+ const wd = this.mount.querySelector('.atok-withdraw');+ if (wd) wd.addEventListener('click', () => this._onWithdraw());+ const gv = this.mount.querySelector('.atok-governance');+ if (gv) gv.addEventListener('click', () => this._onGovernance());+ const pay = this.mount.querySelector('.atok-pay');+ if (pay) pay.addEventListener('click', () => this._onPay());+ }++ async _onWithdraw() {+ const wd = this.mount.querySelector('.atok-withdraw');+ const orig = wd.textContent;+ wd.disabled = true;+ wd.textContent = 'Preparing…';+ try {+ // Lazy-import so non-owner views don't pay the bundle cost.+ const [+ { resolveUsdcAta, signAndSendVTx },+ ] = await Promise.all([import('./pump-modals.js')]);+ const wallet =+ typeof window !== 'undefined' &&+ (window.solana || window.phantom?.solana || window.backpack || window.solflare);+ if (!wallet) throw new Error('No Solana wallet detected. Install Phantom.');+ if (!wallet.isConnected) await wallet.connect?.();+ const authority =+ wallet.publicKey?.toBase58?.() || wallet.publicKey?.toString();+ if (authority !== this.token.agent_authority) {+ throw new Error('Connected wallet is not the agent authority.');+ }+ wd.textContent = 'Resolving ATA…';+ const { ata, existing, connection } = await resolveUsdcAta({+ owner: authority,+ network: this.token.network,+ });+ // If owner has no USDC ATA yet, prepend a creation ix; the offline SDK+ // withdraw ix expects the receiver ATA to exist.+ let createAtaPrep = null;+ if (!existing) {+ const { createAssociatedTokenAccountInstruction, ASSOCIATED_TOKEN_PROGRAM_ID } =+ await import('@solana/spl-token');+ const { PublicKey } = await import('@solana/web3.js');+ createAtaPrep = createAssociatedTokenAccountInstruction(+ new PublicKey(authority),+ ata,+ new PublicKey(authority),+ new PublicKey(+ this.token.network === 'devnet'+ ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'+ : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ ),+ );+ }+ wd.textContent = 'Building tx…';+ const prep = await fetch('/api/pump/withdraw-prep', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ mint: this.token.mint,+ authority_wallet: authority,+ receiver_ata: ata.toBase58(),+ network: this.token.network,+ }),+ }).then((r) => r.json());+ if (prep.error) throw new Error(prep.error_description || prep.error);+ wd.textContent = 'Sign in wallet…';+ const sig = await signAndSendVTx(prep.tx_base64, {+ network: this.token.network,+ prependIxs: createAtaPrep ? [createAtaPrep] : [],+ wallet,+ connection,+ });+ wd.textContent = 'Confirming…';+ const conf = await fetch('/api/pump/withdraw-confirm', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ mint: this.token.mint,+ authority_wallet: authority,+ tx_signature: sig,+ network: this.token.network,+ }),+ }).then((r) => r.json());+ if (conf.error) throw new Error(conf.error_description || conf.error);+ wd.textContent = 'Done 🎉';+ setTimeout(() => this._refresh().catch(() => {}), 1200);+ } catch (e) {+ wd.textContent = `Failed: ${(e.message || String(e)).slice(0, 32)}`;+ setTimeout(() => {+ wd.textContent = orig;+ wd.disabled = false;+ }, 3000);+ }+ }++ _onGovernance() {+ window.dispatchEvent(+ new CustomEvent('pump-governance-open', {+ detail: { mint: this.token.mint, currentBps: this.token.buyback_bps },+ }),+ );+ }++ _onPay() {+ window.dispatchEvent(+ new CustomEvent('pump-pay-open', {+ detail: { mint: this.token.mint, network: this.token.network },+ }),+ );+ }++ _updateMobileStrip(symbol, priceText) {+ if (window.innerWidth > 640) return;+ if (!this._mobileStrip) {+ const el = document.createElement('div');+ el.className = 'atok-mobile-strip';+ document.body.appendChild(el);+ this._mobileStrip = el;+ }+ this._mobileStrip.innerHTML = `+ <div class="atok-mobile-price">+ <div>$${symbol}</div>+ <small>${priceText}</small>+ </div>+ <button class="atok-mobile-pay">Pay</button>`;+ const pay = this._mobileStrip.querySelector('.atok-mobile-pay');+ if (pay) pay.addEventListener('click', () => this._onPay());+ }+}diff --git a/publish/src/pump/pump-modals.js b/publish/src/pump/pump-modals.jsnew file mode 100644index 000000000..fdad6cb1a--- /dev/null+++ b/publish/src/pump/pump-modals.js@@ -0,0 +1,560 @@+/**+ * Pump.fun modals: pay, governance, launch wizard, withdraw confirm.+ *+ * Mounted once per page via mountPumpModals(). Listens on window CustomEvents+ * dispatched by the AgentTokenWidget (pump-pay-open, pump-governance-open,+ * pump-withdraw-prepared) plus an explicit launch trigger.+ *+ * All flows go through the existing prep/confirm endpoints. Wallet signing+ * uses the same Solana wallet adapter pattern as src/erc8004/solana-deploy.js+ * (window.solana / phantom / backpack / solflare). Frontend never holds keys.+ */++const M_STYLES = `+.pmodal-back {+ position: fixed; inset: 0; background: rgba(0,0,0,0.55); backdrop-filter: blur(6px);+ display: flex; align-items: center; justify-content: center; z-index: 1000;+ padding: 1rem; animation: pmodal-in 0.2s ease;+}+@keyframes pmodal-in { from { opacity: 0 } to { opacity: 1 } }+.pmodal {+ background: #0c0c0e; border: 1px solid rgba(255,255,255,0.08); border-radius: 14px;+ max-width: 460px; width: 100%; padding: 1.4rem; color: #e5e5e5;+ font: 14px/1.5 Inter, sans-serif;+ box-shadow: 0 24px 60px rgba(0,0,0,0.5);+}+.pmodal h3 { margin: 0 0 0.3rem; font-weight: 400; font-size: 1.1rem; letter-spacing: -0.01em; }+.pmodal-sub { color: rgba(255,255,255,0.55); font-size: 0.82rem; margin-bottom: 1rem; }+.pmodal-row { display: flex; justify-content: space-between; padding: 0.4rem 0; font-size: 0.85rem; }+.pmodal-row + .pmodal-row { border-top: 1px solid rgba(255,255,255,0.04); }+.pmodal-row b { color: rgba(255,255,255,0.95); font-weight: 500; }+.pmodal-row code { font-family: ui-monospace, monospace; font-size: 0.78rem; color: rgba(255,255,255,0.6); }+.pmodal label { display: block; font-size: 0.78rem; color: rgba(255,255,255,0.55); margin: 0.7rem 0 0.3rem; }+.pmodal input[type="number"], .pmodal input[type="text"], .pmodal select {+ width: 100%; padding: 0.55rem 0.7rem; border-radius: 8px;+ background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);+ color: #fff; font-size: 0.9rem; font-family: inherit;+}+.pmodal input[type="range"] { width: 100%; accent-color: #a4f0bc; }+.pmodal-slider-label {+ display: flex; justify-content: space-between; font-size: 0.78rem;+ color: rgba(255,255,255,0.6); margin-top: 0.4rem;+}+.pmodal-slider-label b { color: #a4f0bc; font-weight: 500; }+.pmodal-actions { display: flex; gap: 0.5rem; margin-top: 1.2rem; }+.pmodal-btn {+ flex: 1; padding: 0.6rem 0.9rem; border-radius: 8px; cursor: pointer;+ background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);+ color: rgba(255,255,255,0.85); font-size: 0.86rem; transition: 0.15s;+}+.pmodal-btn:hover { background: rgba(255,255,255,0.08); }+.pmodal-btn-primary {+ background: rgba(120,200,140,0.18); border-color: rgba(120,200,140,0.32); color: #d8f5e2;+}+.pmodal-btn-primary:hover { background: rgba(120,200,140,0.26); }+.pmodal-btn[disabled] { opacity: 0.45; cursor: not-allowed; }+.pmodal-error { color: #f6b3b3; font-size: 0.8rem; margin-top: 0.6rem; min-height: 1em; }+.pmodal-ok { color: #a4f0bc; font-size: 0.8rem; margin-top: 0.6rem; }+.pmodal-steps { display: flex; gap: 0.4rem; margin-bottom: 0.7rem; }+.pmodal-step {+ flex: 1; height: 3px; border-radius: 99px; background: rgba(255,255,255,0.06);+}+.pmodal-step.done { background: #a4f0bc; }+.pmodal-step.active { background: rgba(164,240,188,0.5); }+.pmodal-receipt {+ margin-top: 0.6rem; padding: 0.7rem 0.85rem; border-radius: 10px;+ background: rgba(120,200,140,0.06); border: 1px solid rgba(120,200,140,0.18);+}+.pmodal-receipt-title { font-size: 0.7rem; letter-spacing: 0.06em; text-transform: uppercase; color: rgba(180,230,200,0.85); margin-bottom: 0.4rem; }+`;++let stylesInjected = false;+function ensureStyles() {+ if (stylesInjected) return;+ const t = document.createElement('style');+ t.textContent = M_STYLES;+ document.head.appendChild(t);+ stylesInjected = true;+}++function detectSolanaWallet() {+ if (typeof window === 'undefined') return null;+ return (+ window.solana ||+ window.phantom?.solana ||+ window.backpack ||+ window.solflare ||+ null+ );+}++function openModal() {+ ensureStyles();+ const back = document.createElement('div');+ back.className = 'pmodal-back';+ const inner = document.createElement('div');+ inner.className = 'pmodal';+ back.appendChild(inner);+ document.body.appendChild(back);+ back.addEventListener('click', (e) => {+ if (e.target === back) close();+ });+ function close() {+ if (back.parentNode) back.parentNode.removeChild(back);+ }+ return { back, inner, close };+}++// Bundled, not loaded from a CDN: same @solana/web3.js + spl-token versions+// the rest of the app uses.+import {+ VersionedTransaction,+ Connection,+ PublicKey,+ Keypair,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddress,+ createAssociatedTokenAccountInstruction,+ getAccount,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++const RPC = (network) =>+ network === 'devnet'+ ? 'https://api.devnet.solana.com'+ : 'https://api.mainnet-beta.solana.com';++const USDC_MINT = {+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',+};++/**+ * Derive the user's USDC associated token account. If the ATA does not yet+ * exist, returns null for `existing` so the caller can prepend a creation ix.+ */+export async function resolveUsdcAta({ owner, network = 'mainnet', currencyMint } = {}) {+ const ownerPk = owner instanceof PublicKey ? owner : new PublicKey(owner);+ const mint = new PublicKey(currencyMint || USDC_MINT[network] || USDC_MINT.mainnet);+ const ata = await getAssociatedTokenAddress(mint, ownerPk, false);+ const conn = new Connection(RPC(network), 'confirmed');+ let existing = null;+ try {+ existing = await getAccount(conn, ata);+ } catch {+ existing = null;+ }+ return { ata, mint, owner: ownerPk, existing, connection: conn };+}++async function signAndSend(txBase64, { extraSigners = [], network = 'mainnet' } = {}) {+ const wallet = detectSolanaWallet();+ if (!wallet) throw new Error('No Solana wallet detected. Install Phantom.');+ if (!wallet.isConnected) await wallet.connect?.();+ const tx = VersionedTransaction.deserialize(+ Uint8Array.from(atob(txBase64), (c) => c.charCodeAt(0)),+ );+ for (const kp of extraSigners) tx.sign([kp]);+ const signed = await wallet.signTransaction(tx);+ const conn = new Connection(RPC(network), 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), {+ skipPreflight: false,+ });+ await conn.confirmTransaction(sig, 'confirmed');+ return sig;+}++/**+ * Sign + send a server-prepared VersionedTransaction. Optionally prepend+ * additional instructions (e.g. ATA creation) before submission. Used by the+ * widget's withdraw flow which needs a CreateATA + Withdraw atomic.+ *+ * Note: prepending ixs requires recompiling to a v0 message because the server+ * already finalized the message. We prepend by deserialising, building a fresh+ * message with the original blockhash + payer + (extra + original) ixs is not+ * possible without reading the original ixs from the message — which we do via+ * `getMessage()` decompile. Fallback: if prependIxs is empty, just re-sign.+ */+export async function signAndSendVTx(+ txBase64,+ { extraSigners = [], network = 'mainnet', prependIxs = [], wallet, connection } = {},+) {+ const w = wallet || detectSolanaWallet();+ if (!w) throw new Error('No Solana wallet detected. Install Phantom.');+ if (!w.isConnected) await w.connect?.();+ const conn = connection || new Connection(RPC(network), 'confirmed');++ const original = VersionedTransaction.deserialize(+ Uint8Array.from(atob(txBase64), (c) => c.charCodeAt(0)),+ );++ let toSign = original;+ if (prependIxs && prependIxs.length) {+ // Decompile original message → splice in prepend ixs → recompile.+ const { TransactionMessage } = await import('@solana/web3.js');+ const decompiled = TransactionMessage.decompile(original.message);+ const merged = new TransactionMessage({+ payerKey: decompiled.payerKey,+ recentBlockhash: decompiled.recentBlockhash,+ instructions: [...prependIxs, ...decompiled.instructions],+ }).compileToV0Message();+ toSign = new VersionedTransaction(merged);+ }++ for (const kp of extraSigners) toSign.sign([kp]);+ const signed = await w.signTransaction(toSign);+ const sig = await conn.sendRawTransaction(signed.serialize(), {+ skipPreflight: false,+ });+ await conn.confirmTransaction(sig, 'confirmed');+ return sig;+}++// ── Pay modal ───────────────────────────────────────────────────────────────+function openPay({ mint, network }) {+ const { inner, close } = openModal();+ let receipt = null;+ inner.innerHTML = `+ <h3>Pay this agent</h3>+ <div class="pmodal-sub">Settles via pump-agent-payments. Funds buyback + owner per the agent's split.</div>+ <label>Amount (USDC)</label>+ <input type="number" min="0.01" step="0.01" value="0.50" id="pmodal-pay-amount" />+ <label>Why <span style="color:rgba(255,255,255,0.4)">(optional — surfaces in the feed)</span></label>+ <input type="text" placeholder="optimize_model" id="pmodal-pay-tool" />+ <label>Window</label>+ <select id="pmodal-pay-window">+ <option value="60">1 minute (single call)</option>+ <option value="3600">1 hour</option>+ <option value="86400">1 day (subscription)</option>+ <option value="2592000">30 days (subscription)</option>+ </select>+ <div class="pmodal-error" id="pmodal-pay-err"></div>+ <div id="pmodal-pay-receipt"></div>+ <div class="pmodal-actions">+ <button class="pmodal-btn" id="pmodal-pay-cancel">Cancel</button>+ <button class="pmodal-btn pmodal-btn-primary" id="pmodal-pay-go">Pay</button>+ </div>+ `;+ inner.querySelector('#pmodal-pay-cancel').addEventListener('click', close);+ inner.querySelector('#pmodal-pay-go').addEventListener('click', async () => {+ const amt = parseFloat(inner.querySelector('#pmodal-pay-amount').value);+ const tool = inner.querySelector('#pmodal-pay-tool').value.trim();+ const win = parseInt(inner.querySelector('#pmodal-pay-window').value, 10);+ const err = inner.querySelector('#pmodal-pay-err');+ const btn = inner.querySelector('#pmodal-pay-go');+ err.textContent = '';+ if (!(amt > 0)) {+ err.textContent = 'Amount must be > 0';+ return;+ }+ const wallet = detectSolanaWallet();+ if (!wallet) {+ err.textContent = 'No Solana wallet detected. Install Phantom.';+ return;+ }+ btn.disabled = true;+ btn.textContent = 'Connecting…';+ try {+ if (!wallet.isConnected) await wallet.connect?.();+ const payer = wallet.publicKey?.toBase58?.() || wallet.publicKey?.toString();+ btn.textContent = 'Resolving ATA…';+ const { ata, existing } = await resolveUsdcAta({ owner: payer, network });+ if (!existing) {+ err.textContent =+ 'Your USDC token account does not exist on this wallet yet. Receive any amount of USDC first, then try again.';+ btn.disabled = false;+ btn.textContent = 'Pay';+ return;+ }+ btn.textContent = 'Preparing…';+ const prep = await fetch('/api/pump/accept-payment-prep', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ mint,+ payer_wallet: payer,+ user_token_account: ata.toBase58(),+ amount_usdc: amt,+ duration_seconds: win,+ tool_name: tool || undefined,+ network,+ }),+ }).then((r) => r.json());+ if (prep.error) throw new Error(prep.error_description || prep.error);+ btn.textContent = 'Sign in wallet…';+ const sig = await signAndSend(prep.tx_base64, { network });+ btn.textContent = 'Confirming…';+ const confirm = await fetch('/api/pump/accept-payment-confirm', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ payment_id: prep.payment_id, tx_signature: sig }),+ }).then((r) => r.json());+ if (confirm.error) throw new Error(confirm.error_description || confirm.error);+ receipt = { ...prep, tx_signature: sig };+ inner.querySelector('#pmodal-pay-receipt').innerHTML = `+ <div class="pmodal-receipt">+ <div class="pmodal-receipt-title">X402 receipt</div>+ <div class="pmodal-row"><span>Invoice</span><code>${prep.invoice_id}</code></div>+ <div class="pmodal-row"><span>Amount</span><b>$${amt.toFixed(2)}</b></div>+ <div class="pmodal-row"><span>Settles</span><a href="https://solscan.io/tx/${sig}${network === 'devnet' ? '?cluster=devnet' : ''}" target="_blank" rel="noopener" style="color:#a4f0bc">${sig.slice(0, 8)}…</a></div>+ </div>`;+ btn.textContent = 'Done';+ } catch (e) {+ err.textContent = e.message || String(e);+ btn.disabled = false;+ btn.textContent = 'Pay';+ }+ });+}++// ── Governance modal (updateBuybackBps) ─────────────────────────────────────+function openGovernance({ mint, currentBps }) {+ const { inner, close } = openModal();+ inner.innerHTML = `+ <h3>Set buyback share</h3>+ <div class="pmodal-sub">What share of every paid call burns $AGENT? Higher = more deflation; lower = more owner takeaway.</div>+ <input type="range" min="0" max="10000" step="50" value="${currentBps || 0}" id="pmodal-gov-slider" />+ <div class="pmodal-slider-label">+ <span>0%</span>+ <b id="pmodal-gov-val">${((currentBps || 0) / 100).toFixed(1)}%</b>+ <span>100%</span>+ </div>+ <div class="pmodal-error" id="pmodal-gov-err"></div>+ <div class="pmodal-actions">+ <button class="pmodal-btn" id="pmodal-gov-cancel">Cancel</button>+ <button class="pmodal-btn pmodal-btn-primary" id="pmodal-gov-go">Update on-chain</button>+ </div>+ `;+ const slider = inner.querySelector('#pmodal-gov-slider');+ const val = inner.querySelector('#pmodal-gov-val');+ slider.addEventListener('input', () => {+ val.textContent = `${(slider.value / 100).toFixed(1)}%`;+ });+ inner.querySelector('#pmodal-gov-cancel').addEventListener('click', close);+ inner.querySelector('#pmodal-gov-go').addEventListener('click', async () => {+ const err = inner.querySelector('#pmodal-gov-err');+ const btn = inner.querySelector('#pmodal-gov-go');+ err.textContent = '';+ btn.disabled = true;+ btn.textContent = 'Preparing…';+ try {+ const wallet = detectSolanaWallet();+ if (!wallet) throw new Error('No Solana wallet detected.');+ if (!wallet.isConnected) await wallet.connect?.();+ const payer = wallet.publicKey?.toBase58?.() || wallet.publicKey?.toString();+ const prep = await fetch('/api/pump/governance-prep', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ mint,+ authority_wallet: payer,+ new_buyback_bps: parseInt(slider.value, 10),+ network: 'mainnet',+ }),+ }).then((r) => r.json());+ if (prep.error) throw new Error(prep.error_description || prep.error);+ btn.textContent = 'Sign in wallet…';+ const sig = await signAndSend(prep.tx_base64, { network: 'mainnet' });+ btn.textContent = `Done · ${sig.slice(0, 6)}…`;+ } catch (e) {+ err.textContent = e.message || String(e);+ btn.disabled = false;+ btn.textContent = 'Update on-chain';+ }+ });+}++// ── Launch wizard ──────────────────────────────────────────────────────────+function openLaunch({ identity, agentId }) {+ const { inner, close } = openModal();+ let step = 1;++ function render() {+ const symbolDefault = (identity?.name || 'AGENT')+ .toUpperCase()+ .replace(/[^A-Z0-9]/g, '')+ .slice(0, 8) || 'AGENT';+ inner.innerHTML = `+ <h3>Launch $${symbolDefault}</h3>+ <div class="pmodal-sub">Pump.fun bonding curve + agent-payments PDA. Three steps.</div>+ <div class="pmodal-steps">+ <div class="pmodal-step ${step >= 1 ? (step === 1 ? 'active' : 'done') : ''}"></div>+ <div class="pmodal-step ${step >= 2 ? (step === 2 ? 'active' : 'done') : ''}"></div>+ <div class="pmodal-step ${step >= 3 ? (step === 3 ? 'active' : 'done') : ''}"></div>+ </div>+ <div id="pmodal-launch-body"></div>+ <div class="pmodal-error" id="pmodal-launch-err"></div>+ <div class="pmodal-actions">+ <button class="pmodal-btn" id="pmodal-launch-back" ${step === 1 ? 'disabled' : ''}>Back</button>+ <button class="pmodal-btn pmodal-btn-primary" id="pmodal-launch-next">${step === 3 ? 'Launch on-chain' : 'Next'}</button>+ </div>+ `;+ const body = inner.querySelector('#pmodal-launch-body');+ if (step === 1) {+ body.innerHTML = `+ <label>Name</label>+ <input type="text" id="pmodal-launch-name" value="${identity?.name || 'Agent'}" />+ <label>Symbol</label>+ <input type="text" id="pmodal-launch-symbol" maxlength="10" value="${symbolDefault}" />+ <label>Metadata URI <span style="color:rgba(255,255,255,0.4)">(IPFS or HTTPS to a JSON manifest with avatar + bio)</span></label>+ <input type="text" id="pmodal-launch-uri" placeholder="https://three.ws/agent/${agentId}/pump-metadata.json" />+ `;+ } else if (step === 2) {+ body.innerHTML = `+ <label>Buyback share</label>+ <input type="range" min="0" max="5000" step="50" value="500" id="pmodal-launch-bps" />+ <div class="pmodal-slider-label">+ <span>0%</span>+ <b id="pmodal-launch-bps-val">5.0%</b>+ <span>50%</span>+ </div>+ <div class="pmodal-row" style="border-top:none;margin-top:0.6rem">+ <span>If this agent earns $10/mo:</span>+ <b id="pmodal-launch-projection">$0.50/mo burned</b>+ </div>+ <label>Creator initial buy <span style="color:rgba(255,255,255,0.4)">(SOL, optional)</span></label>+ <input type="number" id="pmodal-launch-buyin" value="0" min="0" max="50" step="0.1" />+ <div class="pmodal-sub" style="margin-top:0.7rem">+ Buyback share is locked once configured (per the SDK fee-share policy).+ Choose carefully — it can't be changed later via this wizard.+ </div>+ `;+ const bps = body.querySelector('#pmodal-launch-bps');+ const v = body.querySelector('#pmodal-launch-bps-val');+ const proj = body.querySelector('#pmodal-launch-projection');+ const update = () => {+ const pct = bps.value / 100;+ v.textContent = `${pct.toFixed(1)}%`;+ proj.textContent = `$${((10 * pct) / 100).toFixed(2)}/mo burned`;+ };+ bps.addEventListener('input', update);+ } else if (step === 3) {+ const name = inner._formCache?.name || identity?.name;+ const symbol = inner._formCache?.symbol || symbolDefault;+ const bps = inner._formCache?.bps || 500;+ const buyin = inner._formCache?.buyin || 0;+ body.innerHTML = `+ <div class="pmodal-row"><span>Name</span><b>${name}</b></div>+ <div class="pmodal-row"><span>Symbol</span><b>$${symbol}</b></div>+ <div class="pmodal-row"><span>Buyback</span><b>${(bps / 100).toFixed(1)}%</b></div>+ <div class="pmodal-row"><span>Initial buy</span><b>${buyin} SOL</b></div>+ <div class="pmodal-row"><span>Tx contains</span><b>createInstruction + PumpAgent.create</b></div>+ <div class="pmodal-sub" style="margin-top:0.7rem">+ You'll be asked to sign once with your Solana wallet. Both the new+ mint keypair and your wallet co-sign.+ </div>+ `;+ }++ inner.querySelector('#pmodal-launch-back').addEventListener('click', () => {+ step = Math.max(1, step - 1);+ render();+ });+ inner.querySelector('#pmodal-launch-next').addEventListener('click', async () => {+ const errEl = inner.querySelector('#pmodal-launch-err');+ errEl.textContent = '';+ if (step === 1) {+ const name = inner.querySelector('#pmodal-launch-name').value.trim();+ const symbol = inner.querySelector('#pmodal-launch-symbol').value.trim().toUpperCase();+ const uri = inner.querySelector('#pmodal-launch-uri').value.trim();+ if (!name || !symbol || !uri) {+ errEl.textContent = 'All three fields are required.';+ return;+ }+ inner._formCache = { ...(inner._formCache || {}), name, symbol, uri };+ step = 2;+ render();+ } else if (step === 2) {+ const bps = parseInt(inner.querySelector('#pmodal-launch-bps').value, 10);+ const buyin = parseFloat(inner.querySelector('#pmodal-launch-buyin').value || '0');+ inner._formCache = { ...(inner._formCache || {}), bps, buyin };+ step = 3;+ render();+ } else {+ const btn = inner.querySelector('#pmodal-launch-next');+ btn.disabled = true;+ btn.textContent = 'Preparing…';+ try {+ const wallet = detectSolanaWallet();+ if (!wallet) throw new Error('No Solana wallet detected.');+ if (!wallet.isConnected) await wallet.connect?.();+ const payer =+ wallet.publicKey?.toBase58?.() || wallet.publicKey?.toString();+ const f = inner._formCache || {};+ const prep = await fetch('/api/pump/launch-prep', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ agent_id: agentId,+ wallet_address: payer,+ name: f.name,+ symbol: f.symbol,+ uri: f.uri,+ buyback_bps: f.bps || 0,+ sol_buy_in: f.buyin || 0,+ network: 'mainnet',+ }),+ }).then((r) => r.json());+ if (prep.error) throw new Error(prep.error_description || prep.error);++ const mintKp = prep.mint_secret_key_b64+ ? Keypair.fromSecretKey(+ Uint8Array.from(atob(prep.mint_secret_key_b64), (c) => c.charCodeAt(0)),+ )+ : null;+ btn.textContent = 'Sign in wallet…';+ const sig = await signAndSend(prep.tx_base64, {+ extraSigners: mintKp ? [mintKp] : [],+ network: 'mainnet',+ });+ btn.textContent = 'Confirming…';+ const confirm = await fetch('/api/pump/launch-confirm', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ prep_id: prep.prep_id, tx_signature: sig }),+ }).then((r) => r.json());+ if (confirm.error) throw new Error(confirm.error_description || confirm.error);+ btn.textContent = 'Launched 🎉';+ setTimeout(() => {+ close();+ window.location.reload();+ }, 1200);+ } catch (e) {+ errEl.textContent = e.message || String(e);+ const btn = inner.querySelector('#pmodal-launch-next');+ if (btn) {+ btn.disabled = false;+ btn.textContent = 'Launch on-chain';+ }+ }+ }+ });+ }+ render();+}++// ── Mount ──────────────────────────────────────────────────────────────────+export function mountPumpModals({ identity, agentId } = {}) {+ if (typeof window === 'undefined') return;+ if (window.__pumpModalsMounted) return;+ window.__pumpModalsMounted = true;++ window.addEventListener('pump-pay-open', (e) => openPay(e.detail || {}));+ window.addEventListener('pump-governance-open', (e) =>+ openGovernance(e.detail || {}),+ );+ window.addEventListener('pump-launch-open', (e) =>+ openLaunch(e.detail || { identity, agentId }),+ );+}++export function openPumpLaunchWizard(identity, agentId) {+ openLaunch({ identity, agentId });+}diff --git a/publish/src/reputation-page.js b/publish/src/reputation-page.jsnew file mode 100644index 000000000..f491e6171--- /dev/null+++ b/publish/src/reputation-page.js@@ -0,0 +1,17 @@+/**+ * Reputation page entry point for Vite bundling.+ * Exports the main reputation page logic.+ */++import { getReputation, getRecentReviews, submitReputation } from './erc8004/reputation.js';+import { JsonRpcProvider, BrowserProvider } from 'ethers';+import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++export {+ getReputation,+ getRecentReviews,+ submitReputation,+ JsonRpcProvider,+ BrowserProvider,+ REGISTRY_DEPLOYMENTS,+};diff --git a/publish/src/reputation-ui.js b/publish/src/reputation-ui.jsnew file mode 100644index 000000000..c1c82d975--- /dev/null+++ b/publish/src/reputation-ui.js@@ -0,0 +1,494 @@+/**+ * ReputationDashboard — UI controller for on-chain agent reviews.+ *+ * Fetches reputation data (aggregated stats + recent reviews) from the ERC-8004+ * Reputation Registry, renders them into a container, and handles wallet-gated+ * review submissions with optimistic updates.+ */++import { JsonRpcProvider } from 'ethers';+import { getReputation, getRecentReviews, submitReputation } from './erc8004/reputation.js';+import { ensureWallet } from './erc8004/agent-registry.js';+import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++const CHAIN_NAMES = {+ 1: 'Ethereum',+ 10: 'Optimism',+ 56: 'BSC',+ 100: 'Gnosis',+ 137: 'Polygon',+ 250: 'Fantom',+ 324: 'zkSync Era',+ 1284: 'Moonbeam',+ 5000: 'Mantle',+ 8453: 'Base',+ 42161: 'Arbitrum One',+ 42220: 'Celo',+ 43114: 'Avalanche',+ 59144: 'Linea',+ 534352: 'Scroll',+ 97: 'BSC Testnet',+ 11155111: 'Ethereum Sepolia',+ 84532: 'Base Sepolia',+ 421614: 'Arbitrum Sepolia',+ 11155420: 'Optimism Sepolia',+ 80002: 'Polygon Amoy',+ 43113: 'Avalanche Fuji',+};++function getExplorerUrl(chainId, txHash) {+ const base = {+ 1: 'https://etherscan.io',+ 10: 'https://optimistic.etherscan.io',+ 56: 'https://bscscan.com',+ 100: 'https://gnosisscan.io',+ 137: 'https://polygonscan.com',+ 250: 'https://ftmscan.com',+ 324: 'https://explorer.zksync.io',+ 1284: 'https://moonscan.io',+ 5000: 'https://explorer.mantle.xyz',+ 8453: 'https://basescan.org',+ 42161: 'https://arbiscan.io',+ 42220: 'https://celoscan.io',+ 43114: 'https://snowtrace.io',+ 59144: 'https://lineascan.build',+ 534352: 'https://scrollscan.com',+ 97: 'https://testnet.bscscan.com',+ 11155111: 'https://sepolia.etherscan.io',+ 84532: 'https://sepolia.basescan.org',+ 421614: 'https://sepolia.arbiscan.io',+ 11155420: 'https://sepolia-optimism.etherscan.io',+ 80002: 'https://amoy.polygonscan.com',+ 43113: 'https://testnet.snowtrace.io',+ }[chainId];++ if (!base) return null;+ return `${base}/tx/${txHash}`;+}++export class ReputationDashboard {+ constructor(container, { agentId, chainId = 84532 }) {+ this.container = container;+ this.agentId = agentId;+ this.chainId = chainId;+ this.reviews = [];+ this.reputation = { total: 0, count: 0, average: 0 };+ this.connectedAddress = null;+ this.reviewListeners = [];+ this.pollInterval = null;+ this.lastTxHash = null;+ }++ /**+ * Load reputation data and render.+ */+ async load() {+ try {+ await this._fetchReputation();+ this._render();+ } catch (err) {+ console.error('[ReputationDashboard] load failed:', err);+ this._renderError(err);+ }+ }++ /**+ * Fetch getReputation + getRecentReviews using ethers.js provider.+ */+ async _fetchReputation() {+ if (!REGISTRY_DEPLOYMENTS[this.chainId]) {+ throw new Error(`Chain ${this.chainId} is not supported.`);+ }++ // Pick an RPC URL per chain.+ const rpcUrl = this._getRpcUrl(this.chainId);+ const provider = new JsonRpcProvider(rpcUrl);++ const reputation = await getReputation({+ agentId: this.agentId,+ runner: provider,+ chainId: this.chainId,+ });++ const reviews = await getRecentReviews({+ agentId: this.agentId,+ runner: provider,+ chainId: this.chainId,+ fromBlock: 0,+ });++ this.reputation = reputation;+ this.reviews = reviews.sort((a, b) => b.blockNumber - a.blockNumber);+ }++ _getRpcUrl(chainId) {+ const rpcMap = {+ 1: 'https://eth.llamarpc.com',+ 10: 'https://optimism.llamarpc.com',+ 56: 'https://bsc.llamarpc.com',+ 100: 'https://gnosischain.publicnode.com',+ 137: 'https://polygon.llamarpc.com',+ 250: 'https://fantom.publicnode.com',+ 324: 'https://zksync.publicnode.com',+ 1284: 'https://moonbeam.publicnode.com',+ 5000: 'https://mantle.publicnode.com',+ 8453: 'https://base.llamarpc.com',+ 42161: 'https://arbitrum.llamarpc.com',+ 42220: 'https://celo.publicnode.com',+ 43114: 'https://avalanche.publicnode.com',+ 59144: 'https://linea.publicnode.com',+ 534352: 'https://scroll.publicnode.com',+ 97: 'https://bsc-testnet.publicnode.com',+ 11155111: 'https://ethereum-sepolia.publicnode.com',+ 84532: 'https://base-sepolia.publicnode.com',+ 421614: 'https://arbitrum-sepolia.publicnode.com',+ 11155420: 'https://optimism-sepolia.publicnode.com',+ 80002: 'https://polygon-amoy.publicnode.com',+ 43113: 'https://avalanche-fuji.publicnode.com',+ };+ return rpcMap[chainId] || 'https://eth.llamarpc.com';+ }++ /**+ * Submit a reputation review.+ */+ async submit({ rating, comment }) {+ if (!Number.isInteger(rating) || rating < 1 || rating > 5) {+ throw new Error('Rating must be 1-5.');+ }++ try {+ const walletInfo = await ensureWallet();+ this.connectedAddress = walletInfo.address;++ const txHash = await submitReputation({+ agentId: this.agentId,+ score: rating,+ comment,+ signer: walletInfo.signer,+ chainId: this.chainId,+ });++ this.lastTxHash = txHash;++ // Optimistically add review to list (marked as pending).+ const optimisticReview = {+ agentId: this.agentId,+ from: this.connectedAddress,+ score: rating,+ comment,+ blockNumber: -1, // Pending marker+ txHash,+ pending: true,+ };+ this.reviews.unshift(optimisticReview);++ // Notify listeners+ this.reviewListeners.forEach((fn) => fn(optimisticReview));++ // Start polling to replace pending with confirmed+ this._startPolling();++ return txHash;+ } catch (err) {+ if (err.code === 'ACTION_REJECTED' || err.message.includes('user rejected')) {+ throw new Error('Transaction rejected.');+ }+ throw err;+ }+ }++ _startPolling() {+ if (this.pollInterval) return;+ this.pollInterval = setInterval(() => this._pollForConfirmation(), 5000);+ setTimeout(() => this._stopPolling(), 120000); // Stop after 2 minutes+ }++ _stopPolling() {+ if (this.pollInterval) {+ clearInterval(this.pollInterval);+ this.pollInterval = null;+ }+ }++ async _pollForConfirmation() {+ try {+ const rpcUrl = this._getRpcUrl(this.chainId);+ const provider = new JsonRpcProvider(rpcUrl);++ const receipt = await provider.getTransactionReceipt(this.lastTxHash);+ if (receipt) {+ // Transaction confirmed; reload reviews.+ await this._fetchReputation();+ this._render();+ this._stopPolling();+ }+ } catch (err) {+ console.warn('[ReputationDashboard] poll failed:', err.message);+ }+ }++ onReviewAdded(fn) {+ this.reviewListeners.push(fn);+ }++ _render() {+ this.container.innerHTML = '';+ this.container.appendChild(this._createHeader());+ this.container.appendChild(this._createStatsRow());+ this.container.appendChild(this._createReviewList());+ this.container.appendChild(this._createSubmitForm());+ }++ _renderError(err) {+ const errorMsg = err.message || String(err);+ this.container.innerHTML = `+ <div class="rep-error">+ <h3>Unable to load reputation</h3>+ <p>${this._escapeHtml(errorMsg)}</p>+ <button onclick="location.reload()">Retry</button>+ </div>+ `;+ }++ _createHeader() {+ const div = document.createElement('div');+ div.className = 'rep-header';++ const chainName = CHAIN_NAMES[this.chainId] || `Chain ${this.chainId}`;+ const agentDisplay = `${chainName} • Agent #${this.agentId}`;++ div.innerHTML = `+ <div class="rep-header-content">+ <h1>Agent Reputation</h1>+ <p class="rep-header-meta">${agentDisplay}</p>+ </div>+ `;++ return div;+ }++ _createStatsRow() {+ const div = document.createElement('div');+ div.className = 'rep-stats';++ const lastReviewTime = this._getLastReviewTime();++ div.innerHTML = `+ <div class="rep-stat">+ <span class="rep-stat-label">Reviews</span>+ <span class="rep-stat-value">${this.reputation.count}</span>+ </div>+ <div class="rep-stat">+ <span class="rep-stat-label">Rating</span>+ <span class="rep-stat-value">${this.reputation.average.toFixed(1)}</span>+ </div>+ <div class="rep-stat">+ <span class="rep-stat-label">Last Review</span>+ <span class="rep-stat-value">${lastReviewTime}</span>+ </div>+ `;++ return div;+ }++ _getLastReviewTime() {+ if (this.reviews.length === 0) return '—';+ const blockNum = this.reviews[0].blockNumber;+ if (blockNum < 0) return 'Just now';+ // Approximate: 12s per block+ const secondsAgo = Math.round(Date.now() / 1000) - Math.round(blockNum * 12);+ return this._formatTimeAgo(secondsAgo);+ }++ _formatTimeAgo(seconds) {+ if (seconds < 60) return 'just now';+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;+ return `${Math.floor(seconds / 86400)}d ago`;+ }++ _createReviewList() {+ const div = document.createElement('div');+ div.className = 'rep-reviews';++ if (this.reviews.length === 0) {+ div.innerHTML = '<p class="rep-empty">No reviews yet. Be the first!</p>';+ return div;+ }++ const title = document.createElement('h3');+ title.textContent = 'Reviews';+ div.appendChild(title);++ const list = document.createElement('div');+ list.className = 'rep-review-list';++ this.reviews.slice(0, 10).forEach((review) => {+ list.appendChild(this._createReviewItem(review));+ });++ div.appendChild(list);++ if (this.reviews.length > 10) {+ const more = document.createElement('p');+ more.className = 'rep-more-reviews';+ more.textContent = `+${this.reviews.length - 10} more reviews`;+ div.appendChild(more);+ }++ return div;+ }++ _createReviewItem(review) {+ const div = document.createElement('div');+ div.className = `rep-review-item ${review.pending ? 'pending' : ''}`;++ const starHtml = this._renderStars(review.score);+ const explorerUrl = getExplorerUrl(this.chainId, review.txHash);+ const txLink = explorerUrl+ ? `<a href="${explorerUrl}" target="_blank" rel="noopener">View tx</a>`+ : `<span class="rep-tx-hash">${review.txHash.slice(0, 10)}…</span>`;++ div.innerHTML = `+ <div class="rep-review-header">+ <span class="rep-reviewer">${this._truncateAddress(review.from)}</span>+ <span class="rep-stars">${starHtml}</span>+ </div>+ ${review.comment ? `<p class="rep-comment">${this._escapeHtml(review.comment)}</p>` : ''}+ <div class="rep-review-footer">+ ${txLink}+ ${review.pending ? '<span class="rep-pending-badge">Pending</span>' : ''}+ </div>+ `;++ return div;+ }++ _renderStars(score) {+ const full = Math.floor(score);+ let html = '';+ for (let i = 0; i < 5; i++) {+ html += i < full ? '★' : '☆';+ }+ return html;+ }++ _truncateAddress(addr) {+ if (!addr) return 'Anonymous';+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+ }++ _createSubmitForm() {+ const div = document.createElement('div');+ div.className = 'rep-submit-form';++ div.innerHTML = `+ <h3>Leave a Review</h3>+ <form id="rep-form">+ <div class="rep-form-group">+ <label>Rating</label>+ <div class="rep-stars-input">+ ${[1, 2, 3, 4, 5]+ .map(+ (n) => `+ <button+ type="button"+ class="rep-star-btn"+ data-rating="${n}"+ title="${n} star${n > 1 ? 's' : ''}"+ >★</button>+ `,+ )+ .join('')}+ </div>+ <input type="hidden" id="rep-rating" name="rating" value="" />+ </div>++ <div class="rep-form-group">+ <label for="rep-comment">Comment (optional)</label>+ <textarea+ id="rep-comment"+ name="comment"+ placeholder="Share your experience…"+ rows="4"+ maxlength="500"+ ></textarea>+ <small id="rep-char-count">0/500</small>+ </div>++ <button type="submit" class="rep-submit-btn">Submit Review</button>+ <small class="rep-form-hint">Connect wallet to submit</small>+ </form>+ `;++ const form = div.querySelector('#rep-form');+ const ratingInput = form.querySelector('#rep-rating');+ const commentInput = form.querySelector('#rep-comment');+ const charCount = form.querySelector('#rep-char-count');+ const starBtns = form.querySelectorAll('.rep-star-btn');+ let selectedRating = 0;++ starBtns.forEach((btn) => {+ btn.addEventListener('click', (e) => {+ e.preventDefault();+ selectedRating = Number(btn.dataset.rating);+ ratingInput.value = selectedRating;++ starBtns.forEach((b, i) => {+ b.classList.toggle('selected', i < selectedRating);+ });+ });+ });++ commentInput.addEventListener('input', () => {+ charCount.textContent = `${commentInput.value.length}/500`;+ });++ form.addEventListener('submit', async (e) => {+ e.preventDefault();++ if (!selectedRating) {+ alert('Please select a rating.');+ return;+ }++ const comment = commentInput.value.trim();+ const submitBtn = form.querySelector('button[type="submit"]');+ const originalText = submitBtn.textContent;++ try {+ submitBtn.disabled = true;+ submitBtn.textContent = 'Submitting…';++ await this.submit({ rating: selectedRating, comment });++ commentInput.value = '';+ charCount.textContent = '0/500';+ selectedRating = 0;+ ratingInput.value = '';+ starBtns.forEach((b) => b.classList.remove('selected'));++ submitBtn.textContent = 'Review submitted!';+ setTimeout(() => {+ submitBtn.textContent = originalText;+ submitBtn.disabled = false;+ }, 2000);++ this._render();+ } catch (err) {+ alert(`Error: ${err.message}`);+ submitBtn.textContent = originalText;+ submitBtn.disabled = false;+ }+ });++ return div;+ }++ _escapeHtml(text) {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }+}diff --git a/publish/src/runtime/animation-slots.js b/publish/src/runtime/animation-slots.jsnew file mode 100644index 000000000..1fe1e5b74--- /dev/null+++ b/publish/src/runtime/animation-slots.js@@ -0,0 +1,42 @@+// Fixed slot vocabulary for agent animation gestures.+// Each slot maps to a clip name from the loaded animation library.+// Agents can override individual slots via meta.edits.animations.++export const SLOTS = [+ 'idle',+ 'wave',+ 'nod',+ 'shake',+ 'think',+ 'celebrate',+ 'concern',+ 'bow',+ 'point',+ 'shrug',+];++export const DEFAULT_ANIMATION_MAP = {+ idle: 'idle',+ wave: 'reaction',+ nod: 'reaction',+ shake: 'angry',+ think: 'pray',+ celebrate: 'celebrate',+ concern: 'defeated',+ bow: 'sitclap',+ point: 'reaction',+ shrug: 'defeated',+};++/**+ * Resolve a slot name to a concrete animation clip name.+ * Checks the agent's override map first, falls back to DEFAULT_ANIMATION_MAP,+ * then returns the slot name itself as a last resort.+ * @param {string} slot+ * @param {Object|null} overrideMap — agent's meta.edits.animations+ * @returns {string}+ */+export function resolveSlot(slot, overrideMap) {+ if (overrideMap && overrideMap[slot]) return overrideMap[slot];+ return DEFAULT_ANIMATION_MAP[slot] ?? slot;+}diff --git a/publish/src/runtime/delegation-redeem.js b/publish/src/runtime/delegation-redeem.jsnew file mode 100644index 000000000..944ef4466--- /dev/null+++ b/publish/src/runtime/delegation-redeem.js@@ -0,0 +1,351 @@+/**+ * Delegation Redeem Hook+ * ----------------------+ * Runtime adapter: skills call redeemFromSkill() and this module handles+ * delegation lookup, path selection (client vs relayer), pre-flight validation,+ * protocol bus events, and a per-tab rate limiter.+ *+ * Does NOT import viewer or three.js modules.+ * Does NOT use localStorage — cache is in-memory only.+ */++import { protocol, ACTION_TYPES } from '../agent-protocol.js';++// ── Rate limiter (token bucket, per tab) ──────────────────────────────────────++const RATE_LIMIT_MAX = 5;+const RATE_LIMIT_WINDOW_MS = 60_000;++/** @type {{ timestamps: number[] }} */+const _rateState = { timestamps: [] };++function _checkRateLimit() {+ const now = Date.now();+ const cutoff = now - RATE_LIMIT_WINDOW_MS;+ _rateState.timestamps = _rateState.timestamps.filter((t) => t > cutoff);+ if (_rateState.timestamps.length >= RATE_LIMIT_MAX) {+ throw new Error('rate_limited');+ }+ _rateState.timestamps.push(now);+}++// ── Delegation cache (memory-only, 60s TTL) ───────────────────────────────────++const CACHE_TTL_MS = 60_000;++/** @type {Map<string, { envelopes: any[], ts: number }>} */+const _delegationCache = new Map();++// Invalidate on successful revoke events from the bus+protocol.on('permissions.revoke', (action) => {+ const { agentId, chainId } = action.payload || {};+ if (agentId && chainId) {+ _delegationCache.delete(`${agentId}:${chainId}`);+ }+});++// ── Delegation selection ──────────────────────────────────────────────────────++/**+ * @param {any[]} envelopes+ * @param {{ token?: string, maxAmount?: string | bigint } | undefined} scopeHint+ */+function _pickBestDelegation(envelopes, scopeHint) {+ if (!envelopes?.length) return null;+ if (!scopeHint) return envelopes[0];++ const { token, maxAmount } = scopeHint;+ const scored = envelopes+ .map((env) => {+ const scope = env.scope || {};+ const tokenMatch = !token || scope.token === token;+ let amountOk = true;+ if (maxAmount && scope.maxAmount) {+ try {+ amountOk = BigInt(scope.maxAmount) >= BigInt(maxAmount);+ } catch {+ amountOk = false;+ }+ }+ return { env, rank: (tokenMatch ? 2 : 0) + (amountOk ? 1 : 0) };+ })+ .sort((a, b) => b.rank - a.rank);++ return scored[0].rank > 0 ? scored[0].env : null;+}++// ── Public: getActiveDelegation ───────────────────────────────────────────────++/**+ * Fetch the best matching delegation for an agent, with 60s cache.+ * @param {{ agentId: string, chainId: string|number, scopeHint?: { token?: string, maxAmount?: string } }} opts+ * @returns {Promise<object|null>}+ */+export async function getActiveDelegation({ agentId, chainId, scopeHint } = {}) {+ const key = `${agentId}:${chainId}`;+ const cached = _delegationCache.get(key);+ if (cached && Date.now() - cached.ts < CACHE_TTL_MS) {+ return _pickBestDelegation(cached.envelopes, scopeHint);+ }++ const url = `/api/permissions/metadata?agentId=${encodeURIComponent(agentId)}&chainId=${encodeURIComponent(chainId)}`;+ let res;+ try {+ res = await fetch(url);+ } catch (err) {+ return null;+ }+ if (!res.ok) return null;++ const data = await res.json().catch(() => null);+ if (!data) return null;++ const envelopes = Array.isArray(data) ? data : (data.delegations ?? []);+ _delegationCache.set(key, { envelopes, ts: Date.now() });+ return _pickBestDelegation(envelopes, scopeHint);+}++// ── Pre-flight scope validation ───────────────────────────────────────────────++/**+ * Returns an error string if any call violates the delegation scope, else null.+ * @param {any[]} calls+ * @param {object | undefined} scope+ */+function _validateCallsAgainstScope(calls, scope) {+ if (!scope || !calls?.length) return null;++ const { targets, maxAmount } = scope;+ for (const call of calls) {+ if (targets?.length && call.to && !targets.includes(call.to)) {+ return `Call target ${call.to} not in allowed scope targets`;+ }+ if (maxAmount && call.value != null) {+ try {+ if (BigInt(call.value) > BigInt(maxAmount)) {+ return `Call value ${call.value} exceeds scope maxAmount ${maxAmount}`;+ }+ } catch {+ // non-parseable — skip amount check+ }+ }+ }+ return null;+}++// ── Relayer token resolution ──────────────────────────────────────────────────++function _getRelayerToken(agentId) {+ if (typeof window === 'undefined') return null;+ return (+ window.__AGENT_RUNTIME_CONFIG__?.[agentId]?.relayerToken ??+ window.__AGENT_RUNTIME_CONFIG__?.relayerToken ??+ null+ );+}++// ── Client-mode redemption ────────────────────────────────────────────────────++async function _redeemClient(delegation, calls, chainId) {+ if (!delegation.signature) {+ // Metadata endpoint returns a public view without the signature.+ // Client-mode redemption requires the full signed delegation object.+ throw new Error('no_redemption_path');+ }++ const { ensureWallet } = await import('../erc8004/agent-registry.js');+ const { signer } = await ensureWallet();++ const { redeemDelegation } = await import('../permissions/toolkit.js');+ const { txHash } = await redeemDelegation({ delegation, calls, signer, chainId });+ return txHash;+}++// ── Relayer-mode redemption ───────────────────────────────────────────────────++async function _redeemRelayer(delegation, calls, agentId, chainId, skillId) {+ const token = _getRelayerToken(agentId);+ if (!token) throw new Error('no_relayer_token');++ const res = await fetch('/api/permissions/redeem', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${token}`,+ },+ body: JSON.stringify({ delegation, calls, agentId, chainId, skillId }),+ });++ if (!res.ok) {+ const body = await res.json().catch(() => ({ message: res.statusText }));+ throw new Error(body.message || `Relayer returned ${res.status}`);+ }++ const data = await res.json();+ if (!data.txHash) throw new Error('Relayer response missing txHash');+ return data.txHash;+}++// ── Public: redeemFromSkill ───────────────────────────────────────────────────++/**+ * The main entrypoint for skills. Handles path selection, pre-flight, events, and errors.+ * @param {{+ * agentId: string,+ * chainId: string|number,+ * calls: Array<{ to: string, value?: bigint, data?: string }>,+ * skillId: string,+ * mode?: 'client' | 'relayer' | 'auto',+ * }} opts+ * @returns {Promise<{ ok: true, txHash: string } | { ok: false, code: string, message: string }>}+ */+export async function redeemFromSkill({ agentId, chainId, calls, skillId, mode = 'auto' } = {}) {+ // Rate limit — never hits the network when exceeded+ try {+ _checkRateLimit();+ } catch {+ const code = 'rate_limited';+ const message = 'Too many redemption attempts — max 5 per minute per tab';+ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,+ payload: { code, message, skillId },+ agentId,+ sourceSkill: skillId,+ });+ return { ok: false, code, message };+ }++ // Pre-flight: delegation existence+ const delegation = await getActiveDelegation({ agentId, chainId });+ if (!delegation) {+ const code = 'no_delegation';+ const message = 'No active delegation found for this agent/chain';+ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,+ payload: { code, message, skillId },+ agentId,+ sourceSkill: skillId,+ });+ return { ok: false, code, message };+ }++ // Pre-flight: scope validation (cheap, prevents wasted gas)+ const scopeErr = _validateCallsAgainstScope(calls, delegation.scope);+ if (scopeErr) {+ const code = 'scope_violation';+ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,+ payload: { code, message: scopeErr, skillId },+ agentId,+ sourceSkill: skillId,+ });+ return { ok: false, code, message: scopeErr };+ }++ // Resolve auto mode+ let resolvedMode = mode;+ if (mode === 'auto') {+ const hasWallet =+ typeof window !== 'undefined' && !!window.ethereum && !!delegation.signature;+ const hasToken = !!_getRelayerToken(agentId);+ if (hasWallet) resolvedMode = 'client';+ else if (hasToken) resolvedMode = 'relayer';+ else {+ const code = 'no_redemption_path';+ const message = 'No wallet connected and no relayer token available';+ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,+ payload: { code, message, skillId },+ agentId,+ sourceSkill: skillId,+ });+ return { ok: false, code, message };+ }+ }++ if (resolvedMode === 'client' && (typeof window === 'undefined' || !window.ethereum)) {+ const code = 'no_wallet';+ const message = 'client mode requires a connected wallet';+ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,+ payload: { code, message, skillId },+ agentId,+ sourceSkill: skillId,+ });+ return { ok: false, code, message };+ }++ if (resolvedMode === 'relayer' && !_getRelayerToken(agentId)) {+ const code = 'no_relayer_token';+ const message = 'relayer mode requires a bearer token in runtime config';+ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,+ payload: { code, message, skillId },+ agentId,+ sourceSkill: skillId,+ });+ return { ok: false, code, message };+ }++ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_START,+ payload: {+ agentId,+ chainId,+ skillId,+ mode: resolvedMode,+ delegationHash: delegation.hash,+ },+ agentId,+ sourceSkill: skillId,+ });++ try {+ let txHash;+ if (resolvedMode === 'client') {+ txHash = await _redeemClient(delegation, calls, chainId);+ } else {+ txHash = await _redeemRelayer(delegation, calls, agentId, chainId, skillId);+ }++ // Invalidate cache — balance has changed+ _delegationCache.delete(`${agentId}:${chainId}`);++ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_SUCCESS,+ payload: { txHash, skillId, delegationHash: delegation.hash },+ agentId,+ sourceSkill: skillId,+ });++ return { ok: true, txHash };+ } catch (err) {+ const code = err.message || 'unknown_error';+ protocol.emit({+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,+ payload: { code, message: err.message, skillId },+ agentId,+ sourceSkill: skillId,+ });+ return { ok: false, code, message: err.message };+ }+}++// ── Public: subscribeRedeemEvents ─────────────────────────────────────────────++/**+ * Subscribe to all redemption lifecycle events. Returns an unsubscribe function.+ * @param {(action: import('../agent-protocol.js').ActionPayload) => void} handler+ * @returns {() => void} unsubscribe+ */+export function subscribeRedeemEvents(handler) {+ const types = [+ ACTION_TYPES.PERMISSIONS_REDEEM_START,+ ACTION_TYPES.PERMISSIONS_REDEEM_SUCCESS,+ ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,+ ];+ // Use addEventListener directly to avoid __protocolWrapped collision across types+ const wrapped = (e) => handler(e.detail);+ types.forEach((t) => protocol.addEventListener(t, wrapped));+ return () => types.forEach((t) => protocol.removeEventListener(t, wrapped));+}diff --git a/publish/src/runtime/index.js b/publish/src/runtime/index.jsnew file mode 100644index 000000000..94e794067--- /dev/null+++ b/publish/src/runtime/index.js@@ -0,0 +1,236 @@+// Runtime — wires LLM + tool dispatch + speech + memory into a single agent brain.+// Replaces the pattern-matched chatbot stub in nich-agent.js.++import { createProvider } from './providers.js';+import { createTTS, createSTT } from './speech.js';+import { BUILTIN_TOOLS, BUILTIN_HANDLERS, STAGE_TOOLS } from './tools.js';++const MAX_TOOL_ITERATIONS = 8;++export class Runtime extends EventTarget {+ constructor({+ manifest,+ viewer,+ memory,+ skills,+ providerConfig = {},+ voiceConfig = {},+ stage = null,+ agentId = null,+ } = {}) {+ super();+ this.manifest = manifest || {};+ this.viewer = viewer;+ this.memory = memory;+ this.skills = skills;+ this.stage = stage;+ this.agentId = agentId;++ this.provider = createProvider({+ ...this.manifest.brain,+ ...providerConfig,+ });+ this.tts = createTTS({ ...this.manifest.voice?.tts, ...voiceConfig.tts });+ this.stt = createSTT({ ...this.manifest.voice?.stt, ...voiceConfig.stt });++ this.messages = [];+ this._busy = false;+ }++ get systemPrompt() {+ const parts = [];+ if (this.manifest.instructions) parts.push(this.manifest.instructions);+ if (this.memory) {+ parts.push(+ '\n\n<memory>\n' ++ this.memory.contextBlock({+ maxTokens: this.manifest.memory?.maxTokens || 8192,+ }) ++ '\n</memory>',+ );+ }+ if (this.skills) parts.push(this.skills.systemPrompt());+ return parts.join('');+ }++ get tools() {+ const builtinNames = new Set(this.manifest.tools || BUILTIN_TOOLS.map((t) => t.name));+ const builtins = BUILTIN_TOOLS.filter((t) => builtinNames.has(t.name));+ const skillTools = this.skills ? this.skills.allTools() : [];+ const stageTools = this.stage ? STAGE_TOOLS : [];+ return [...builtins, ...stageTools, ...skillTools];+ }++ async send(userText, { voice = false } = {}) {+ if (this._busy) {+ throw new Error('Runtime busy — wait for current turn to finish');+ }+ this._busy = true;+ try {+ this.memory?.note('user_said', { text: userText });+ this.messages.push({ role: 'user', content: userText });+ this.dispatchEvent(+ new CustomEvent('brain:message', {+ detail: { role: 'user', content: userText },+ }),+ );++ const reply = await this._loop();++ if (voice && reply.text && this.tts) {+ this.dispatchEvent(+ new CustomEvent('voice:speech-start', { detail: { text: reply.text } }),+ );+ await this.tts.speak(reply.text);+ this.dispatchEvent(new CustomEvent('voice:speech-end', {}));+ }++ return reply;+ } finally {+ this._busy = false;+ }+ }++ async _loop() {+ let iter = 0;+ let finalText = '';++ while (iter++ < MAX_TOOL_ITERATIONS) {+ const response = await this.provider.complete({+ system: this.systemPrompt,+ messages: this.messages,+ tools: this.tools,+ });++ if (response.thinking) {+ this.dispatchEvent(+ new CustomEvent('brain:thinking', { detail: { content: response.thinking } }),+ );+ }++ if (!response.toolCalls.length) {+ finalText = response.text;+ this.messages.push({ role: 'assistant', content: response.text });+ this.dispatchEvent(+ new CustomEvent('brain:message', {+ detail: { role: 'assistant', content: response.text },+ }),+ );+ break;+ }++ // Record assistant turn with tool calls+ this.messages.push(+ this.provider.formatAssistantWithToolCalls(response.text, response.toolCalls),+ );+ if (response.text) {+ this.dispatchEvent(+ new CustomEvent('brain:message', {+ detail: { role: 'assistant', content: response.text },+ }),+ );+ }++ // Dispatch each tool call+ const results = [];+ for (const call of response.toolCalls) {+ let output,+ isError = false;+ try {+ output = await this._dispatchTool(call);+ } catch (err) {+ output = { error: err.message || String(err) };+ isError = true;+ }+ this.dispatchEvent(+ new CustomEvent('skill:tool-called', {+ detail: { tool: call.name, args: call.input, result: output },+ }),+ );+ results.push({ id: call.id, output, isError });+ }+ this.messages.push(this.provider.formatToolResults(results));+ }++ return { text: finalText };+ }++ async _dispatchTool(call) {+ const ctx = this._context();++ // Skill-provided tools first (they can shadow built-ins intentionally)+ const skill = this.skills?.findSkillForTool(call.name);+ if (skill) return skill.invoke(call.name, call.input, ctx);++ // Built-in+ const handler = BUILTIN_HANDLERS[call.name];+ if (!handler) throw new Error(`Unknown tool: ${call.name}`);+ return handler(call.input, ctx);+ }++ _context() {+ const skills = this.skills;+ return {+ viewer: this.viewer,+ memory: this.memory,+ llm: {+ complete: (prompt, opts) =>+ this.provider.complete({+ system: opts?.system || '',+ messages: [{ role: 'user', content: prompt }],+ tools: opts?.tools,+ }),+ },+ speak: async (text) => {+ if (!this.tts) return;+ this.dispatchEvent(new CustomEvent('voice:speech-start', { detail: { text } }));+ await this.tts.speak(text);+ this.dispatchEvent(new CustomEvent('voice:speech-end', {}));+ },+ listen: (opts) => this.stt?.listen(opts),+ fetch: (url, opts) => fetch(url, opts),+ loadGLB: async (uri) => {+ // Delegates to viewer's loader. Actual wiring in element.js binds this.+ return this.viewer.loadGLB?.(uri);+ },+ loadClip: async (uri) => this.viewer.loadClip?.(uri),+ loadJSON: async (uri) => (await fetch(uri)).json(),+ call: async (toolName, args) => this._dispatchTool({ name: toolName, input: args }),+ stage: this.stage,+ agentId: this.agentId,+ };+ }++ async listen({ onInterim, onFinal } = {}) {+ if (!this.stt) throw new Error('STT not configured');+ this.dispatchEvent(new CustomEvent('voice:listen-start', {}));+ const text = await this.stt.listen({+ onInterim: (t) => {+ this.dispatchEvent(+ new CustomEvent('voice:transcript', { detail: { text: t, final: false } }),+ );+ onInterim?.(t);+ },+ onFinal: (t) => {+ this.dispatchEvent(+ new CustomEvent('voice:transcript', { detail: { text: t, final: true } }),+ );+ onFinal?.(t);+ },+ });+ return text;+ }++ clearConversation() {+ this.messages = [];+ }++ pause() {+ this.tts?.cancel();+ this.stt?.stop();+ }+ destroy() {+ this.pause();+ this.messages = [];+ }+}diff --git a/publish/src/runtime/providers.js b/publish/src/runtime/providers.jsnew file mode 100644index 000000000..7f74f3717--- /dev/null+++ b/publish/src/runtime/providers.js@@ -0,0 +1,116 @@+// 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,+ agentId,+ apiOrigin,+ temperature = 0.7,+ maxTokens = 4096,+ thinking = 'auto',+ } = {}) {+ this.model = model;+ this.apiKey = apiKey;+ this.temperature = temperature;+ this.maxTokens = maxTokens;+ this.thinking = thinking;++ // Priority: explicit proxyURL > direct key > we-pay fallback+ if (proxyURL) {+ this.proxyURL = proxyURL;+ } else if (!apiKey && agentId && apiOrigin) {+ this.proxyURL = `${apiOrigin}/api/llm/anthropic?agent=${encodeURIComponent(agentId)}`;+ } else {+ this.proxyURL = null;+ }+ }++ 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/publish/src/runtime/scene.js b/publish/src/runtime/scene.jsnew file mode 100644index 000000000..350c77b9c--- /dev/null+++ b/publish/src/runtime/scene.js@@ -0,0 +1,325 @@+// SceneController — wraps a Viewer instance with the scene-tool API the runtime+// and skills expect (playClipByName, lookAt, setExpression, loadClip, loadGLB).+//+// Keeps viewer.js untouched while giving agents a coherent control surface.++import { Vector3 } from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { resolveURI } from '../ipfs.js';+import { resolveSlot } from './animation-slots.js';++const EXPRESSION_MAP = {+ neutral: {+ /* reset all */+ },+ happy: { mouthSmile: 1, browInnerUp: 0.3, cheekSquintL: 0.4, cheekSquintR: 0.4 },+ sad: { mouthFrownL: 0.8, mouthFrownR: 0.8, browDownL: 0.6, browDownR: 0.6 },+ surprised: { jawOpen: 0.5, eyeWideL: 0.8, eyeWideR: 0.8, browInnerUp: 0.9 },+ confused: { browInnerUp: 0.5, browOuterUpL: 0.4, mouthPressL: 0.3, mouthPressR: 0.3 },+ focused: { browDownL: 0.4, browDownR: 0.4, eyeSquintL: 0.3, eyeSquintR: 0.3 },+};++export class SceneController {+ constructor(viewer) {+ this.viewer = viewer;+ this._loader = new GLTFLoader();+ this._userTarget = new Vector3(0, 1.6, 2); // approx user head position+ this._animationMap = {};+ this._group = null;+ this._groupMixer = null;+ this._groupClips = null;+ this._mixerHook = null;+ }++ // Expose the underlying Three.js handles skills may need+ get scene() {+ return this.viewer.scene;+ }+ get mixer() {+ return this._groupMixer || this.viewer.mixer;+ }+ get clips() {+ return this._groupClips || this.viewer.clips || [];+ }+ get content() {+ return this._group || this.viewer.content;+ }++ // Scope all scene operations to a sub-group (used by <agent-stage>).+ setGroup(group, { mixer = null, clips = null } = {}) {+ this._group = group;+ this._groupMixer = mixer;+ this._groupClips = clips;+ if (mixer) {+ this._mixerHook = (dt) => {+ mixer.update(dt);+ this.viewer._animating = true;+ this.viewer.invalidate();+ };+ this._addHook(this._mixerHook);+ }+ }++ dispose() {+ if (this._mixerHook) this._removeHook(this._mixerHook);+ if (this._groupMixer) {+ try {+ this._groupMixer.stopAllAction();+ } catch {}+ try {+ this._groupMixer.uncacheRoot(this._group);+ } catch {}+ }+ this._mixerHook = null;+ this._groupMixer = null;+ this._groupClips = null;+ this._group = null;+ }++ /**+ * Set the agent's animation slot override map (from meta.edits.animations).+ * @param {Object|null} map — { slotName: clipName, … }+ */+ setAnimationMap(map) {+ this._animationMap = map || {};+ }++ /**+ * Resolve a slot name (e.g. 'celebrate') to the actual clip name.+ * Falls back to DEFAULT_ANIMATION_MAP, then the slot name itself.+ * @param {string} name+ * @returns {string}+ */+ resolveAnimationSlot(name) {+ return resolveSlot(name, this._animationMap);+ }++ // Delegate raw load for ad-hoc cases+ async load(url, rootPath = '', assetMap = new Map()) {+ return this.viewer.load(url, rootPath, assetMap);+ }++ // --- Animation ---++ playClipByName(name, { loop = false, fade_ms = 200 } = {}) {+ // Try embedded clips (viewer.clips / viewer.mixer) first+ const clip = this._findClip(name);+ const mixer = this.mixer;+ if (clip && mixer) {+ const action = mixer.clipAction(clip);+ action.reset();+ action.setLoop(loop ? 2201 /* LoopRepeat */ : 2200 /* LoopOnce */);+ action.clampWhenFinished = !loop;+ action.fadeIn(fade_ms / 1000);+ action.play();+ if (!this._group) this.viewer.state.actionStates[clip.name] = true;+ this.viewer._animating = true;+ this.viewer.invalidate();+ return true;+ }+ // Fall back to animation manager (external clips from manifest).+ // crossfadeTo/play are async (lazy-load on demand); fire-and-forget is fine.+ const am = this.viewer?.animationManager;+ if (!am || am.isFailed(name)) return false;+ if (loop) am.crossfadeTo(name, fade_ms / 1000);+ else am.play(name);+ return true;+ }++ playAnimationByHint(hint, opts) {+ const lower = hint.toLowerCase();+ // Search embedded clips+ const match = this.clips.find((c) => c.name.toLowerCase().includes(lower));+ if (match) return this.playClipByName(match.name, opts);+ // Search external clips in animation manager+ const am = this.viewer?.animationManager;+ if (am) {+ for (const name of am.clips.keys()) {+ if (name.toLowerCase().includes(lower)) {+ return this.playClipByName(name, opts);+ }+ }+ }+ return false;+ }++ stopClip(name) {+ const mixer = this.mixer;+ if (!mixer) return;+ const clip = name ? this._findClip(name) : null;+ if (clip) {+ const action = mixer.existingAction(clip);+ if (action) action.fadeOut(0.2);+ if (!this._group) this.viewer.state.actionStates[clip.name] = false;+ } else {+ mixer.stopAllAction();+ if (!this._group) {+ for (const k in this.viewer.state.actionStates)+ this.viewer.state.actionStates[k] = false;+ }+ }+ this.viewer.invalidate();+ }++ async play(clip, opts) {+ // Accept either a clip name or an AnimationClip instance.+ if (typeof clip === 'string') return this.playClipByName(clip, opts);+ const mixer = this.mixer;+ if (!mixer || !clip) return false;+ const action = mixer.clipAction(clip);+ action.reset();+ action.fadeIn(opts?.blend ?? 0.2);+ action.play();+ this.viewer._animating = true;+ this.viewer.invalidate();+ return true;+ }++ async loadClip(uri) {+ const resolved = resolveURI(uri);+ return new Promise((resolve, reject) => {+ this._loader.load(+ resolved,+ (gltf) => resolve(gltf.animations?.[0] || null),+ undefined,+ reject,+ );+ });+ }++ async loadGLB(uri) {+ const resolved = resolveURI(uri);+ return new Promise((resolve, reject) => {+ this._loader.load(resolved, resolve, undefined, reject);+ });+ }++ // --- Gaze ---++ lookAt(target) {+ const t = this._resolveTarget(target);+ if (!t) {+ if (target != null) console.warn(`[SceneController] unknown lookAt target: "${target}"`);+ return;+ }+ if (!this.viewer.content) return;+ // Simple head-bone gaze if rig has Head, otherwise root rotation.+ const head = this._findBone(['Head', 'head', 'mixamorigHead']);+ if (head) {+ head.lookAt(t);+ } else {+ this.viewer.content.lookAt(t.x, this.viewer.content.position.y, t.z);+ }+ this.viewer.invalidate();+ }++ _resolveTarget(target) {+ if (target instanceof Vector3) return target;+ if (target === 'camera') return this.viewer.activeCamera.position.clone();+ if (target === 'center') return new Vector3(0, 1, 0);+ if (target === 'user') {+ // In WebXR, track the live XR camera position so lookAt('user') follows the wearer+ if (this.viewer.renderer?.xr?.isPresenting) {+ return this.viewer.renderer.xr.getCamera().position.clone();+ }+ return this._userTarget.clone();+ }+ return null;+ }++ _findBone(names) {+ if (!this.viewer.content) return null;+ // Rebuild cache when content changes+ if (!this._boneCache || this._boneCacheContent !== this.viewer.content) {+ this._boneCache = new Map();+ this._boneCacheContent = this.viewer.content;+ }+ const key = names.join(',');+ if (this._boneCache.has(key)) return this._boneCache.get(key);+ let found = null;+ this.viewer.content.traverse((n) => {+ if (found) return;+ if (n.isBone && names.includes(n.name)) found = n;+ });+ this._boneCache.set(key, found);+ return found;+ }++ // --- Expression (morph targets) ---++ setExpression(preset, intensity = 1) {+ const influences = EXPRESSION_MAP[preset] || EXPRESSION_MAP.neutral;+ if (!this.viewer.content) return;+ this.viewer.content.traverse((mesh) => {+ if (!mesh.morphTargetDictionary || !mesh.morphTargetInfluences) return;+ // Reset all first+ for (let i = 0; i < mesh.morphTargetInfluences.length; i++) {+ mesh.morphTargetInfluences[i] = 0;+ }+ // Apply preset influences by morph target name+ for (const [morphName, value] of Object.entries(influences)) {+ const idx = mesh.morphTargetDictionary[morphName];+ if (idx !== undefined) {+ mesh.morphTargetInfluences[idx] = value * intensity;+ }+ }+ });+ this.viewer.invalidate();+ }++ // --- Movement ---++ moveTo(position, { duration = 600 } = {}) {+ if (!this.viewer.content) return;+ // Cancel any in-progress tween before starting a new one+ if (this._moveToHook) {+ this._removeHook(this._moveToHook);+ this._moveToHook = null;+ }+ const start = this.viewer.content.position.clone();+ const end = new Vector3(position.x || 0, position.y || start.y, position.z || 0);+ const startT = performance.now();+ const tick = (dt) => {+ const elapsed = performance.now() - startT;+ const t = Math.min(elapsed / duration, 1);+ const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;+ this.viewer.content.position.lerpVectors(start, end, eased);+ this.viewer.invalidate();+ if (t >= 1) {+ this._removeHook(tick);+ this._moveToHook = null;+ }+ };+ this._moveToHook = tick;+ this._addHook(tick);+ }++ // --- Per-frame hooks (uses Viewer._afterAnimateHooks extension point) ---++ _addHook(fn) {+ if (!this.viewer._afterAnimateHooks) this.viewer._afterAnimateHooks = [];+ this.viewer._afterAnimateHooks.push(fn);+ this.viewer._animating = true;+ this.viewer.invalidate();+ }++ _removeHook(fn) {+ const hooks = this.viewer._afterAnimateHooks;+ if (!hooks) return;+ const i = hooks.indexOf(fn);+ if (i >= 0) hooks.splice(i, 1);+ }++ // --- Helpers ---++ _findClip(name) {+ if (!this.clips.length) return null;+ const exact = this.clips.find((c) => c.name === name);+ if (exact) return exact;+ const ci = name.toLowerCase();+ return (+ this.clips.find((c) => c.name.toLowerCase() === ci) ||+ this.clips.find((c) => c.name.toLowerCase().includes(ci))+ );+ }+}diff --git a/publish/src/runtime/speech.js b/publish/src/runtime/speech.jsnew file mode 100644index 000000000..42bb7b07a--- /dev/null+++ b/publish/src/runtime/speech.js@@ -0,0 +1,406 @@+// Speech I/O — TTS and STT. Browser-native by default; provider-swappable.++export class BrowserTTS {+ constructor({ voiceId = 'default', rate = 1, pitch = 1, lang = 'en-US' } = {}) {+ this.voiceId = voiceId;+ this.rate = rate;+ this.pitch = pitch;+ this.lang = lang;+ this._queue = [];+ this._speaking = false;+ }++ async speak(text, { onStart, onEnd } = {}) {+ if (!('speechSynthesis' in window)) return;+ return new Promise((resolve) => {+ const utter = new SpeechSynthesisUtterance(text);+ utter.rate = this.rate;+ utter.pitch = this.pitch;+ utter.lang = this.lang;+ const voice = this._pickVoice();+ if (voice) utter.voice = voice;+ utter.onstart = () => {+ this._speaking = true;+ onStart?.();+ };+ utter.onend = () => {+ this._speaking = false;+ onEnd?.();+ resolve();+ };+ utter.onerror = () => {+ this._speaking = false;+ resolve();+ };+ window.speechSynthesis.speak(utter);+ });+ }++ cancel() {+ if ('speechSynthesis' in window) window.speechSynthesis.cancel();+ this._speaking = false;+ }++ get speaking() {+ return this._speaking;+ }++ _pickVoice() {+ if (!('speechSynthesis' in window)) return null;+ const voices = window.speechSynthesis.getVoices();+ if (this.voiceId && this.voiceId !== 'default') {+ const found = voices.find(+ (v) => v.name === this.voiceId || v.voiceURI === this.voiceId,+ );+ if (found) return found;+ }+ return voices.find((v) => v.lang?.startsWith(this.lang.slice(0, 2))) || null;+ }+}++export class BrowserSTT {+ constructor({ language = 'en-US', continuous = false, interimResults = true } = {}) {+ this.language = language;+ this.continuous = continuous;+ this.interimResults = interimResults;+ this._recognition = null;+ this._listening = false;+ }++ _ensure() {+ if (this._recognition) return this._recognition;+ const SR = window.SpeechRecognition || window.webkitSpeechRecognition;+ if (!SR) return null;+ const r = new SR();+ r.lang = this.language;+ r.continuous = this.continuous;+ r.interimResults = this.interimResults;+ this._recognition = r;+ return r;+ }++ async listen({ onInterim, onFinal } = {}) {+ const r = this._ensure();+ if (!r) throw new Error('SpeechRecognition unavailable in this browser');+ return new Promise((resolve, reject) => {+ let finalText = '';+ r.onresult = (ev) => {+ for (let i = ev.resultIndex; i < ev.results.length; i++) {+ const res = ev.results[i];+ const text = res[0].transcript;+ if (res.isFinal) {+ finalText += text;+ onFinal?.(text);+ } else {+ onInterim?.(text);+ }+ }+ };+ r.onerror = (e) => {+ this._listening = false;+ reject(e.error);+ };+ r.onend = () => {+ this._listening = false;+ resolve(finalText.trim());+ };+ this._listening = true;+ try {+ r.start();+ } catch (e) {+ this._listening = false;+ reject(e);+ }+ });+ }++ stop() {+ if (this._recognition && this._listening) this._recognition.stop();+ }++ get listening() {+ return this._listening;+ }+}++/**+ * ElevenLabs TTS — streaming MP3 playback via fetch + MediaSource.+ *+ * Wire format:+ * POST {proxyURL || `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream`}+ * headers: { 'content-type': 'application/json',+ * 'accept': 'audio/mpeg',+ * 'xi-api-key': apiKey } ← only when proxyURL is unset+ * body: { text, model_id, voice_settings: { stability, similarity_boost, style, use_speaker_boost } }+ *+ * Proxy contract (when proxyURL is set):+ * The proxy receives the same JSON body and forwards it to ElevenLabs with a+ * server-side key, then streams the audio response back unchanged. Clients+ * never see the api key. The proxy may also accept `{ voiceId, modelId }` as+ * top-level fields if it wants to encode the path itself.+ *+ * voice_settings mapping:+ * `rate` is mapped onto `style` (0..1) — ElevenLabs has no true playback-+ * rate control on the Turbo models, but `style` shifts delivery+ * pacing, so a higher rate translates to a more emphatic/faster+ * feel. `rate` 0.5..1.5 → `style` 0..1, clamped.+ * `pitch` has no analogue in ElevenLabs voice_settings, so it is dropped+ * with a comment rather than silently misapplied. To get a higher+ * voice, pick a different voiceId.+ * `stability`, `similarity_boost`, `use_speaker_boost` use ElevenLabs'+ * recommended defaults (0.5, 0.75, true) and can be overridden per instance.+ */+export class ElevenLabsTTS {+ constructor({+ voiceId,+ modelId = 'eleven_turbo_v2_5',+ apiKey = null,+ proxyURL = null,+ rate = 1,+ pitch = 1,+ lang = 'en-US',+ stability = 0.5,+ similarityBoost = 0.75,+ useSpeakerBoost = true,+ } = {}) {+ if (!voiceId) throw new Error('ElevenLabsTTS requires voiceId');+ this.voiceId = voiceId;+ this.modelId = modelId;+ this.apiKey = apiKey;+ this.proxyURL = proxyURL;+ this.rate = rate;+ this.pitch = pitch; // unused — see class comment+ this.lang = lang;+ this.stability = stability;+ this.similarityBoost = similarityBoost;+ this.useSpeakerBoost = useSpeakerBoost;++ this._speaking = false;+ this._abort = null; // current AbortController+ this._audio = null; // current <audio> element+ this._mediaSourceURL = null; // for revocation+ this._onEnd = null; // pending resolve+ }++ async speak(text, { onStart, onEnd } = {}) {+ this.cancel();+ if (!text) return;++ this._abort = new AbortController();+ this._speaking = true;++ const url =+ this.proxyURL ||+ `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(this.voiceId)}/stream`;++ const headers = { 'content-type': 'application/json', accept: 'audio/mpeg' };+ // apiKey is only sent when there's no proxy. Proxies must keep keys server-side.+ if (!this.proxyURL && this.apiKey) headers['xi-api-key'] = this.apiKey;++ // Map rate (0.5..1.5) → style (0..1). Clamped to keep delivery natural.+ const rateNorm = Math.min(1.5, Math.max(0.5, this.rate));+ const styleVal = Math.min(1, Math.max(0, (rateNorm - 0.5) / 1.0));++ const body = JSON.stringify({+ text,+ model_id: this.modelId,+ voice_settings: {+ stability: this.stability,+ similarity_boost: this.similarityBoost,+ style: styleVal,+ use_speaker_boost: this.useSpeakerBoost,+ },+ // Forwarded for proxies that prefer a single endpoint+ voiceId: this.voiceId,+ modelId: this.modelId,+ });++ let resp;+ try {+ resp = await fetch(url, {+ method: 'POST',+ headers,+ body,+ signal: this._abort.signal,+ });+ } catch (err) {+ this._speaking = false;+ if (err.name === 'AbortError') return;+ throw err;+ }++ if (!resp.ok) {+ this._speaking = false;+ throw new Error(`ElevenLabs TTS HTTP ${resp.status}`);+ }++ // Try MediaSource first (low-latency streaming). Fall back to buffered+ // playback for browsers that don't support MSE for audio/mpeg (Safari).+ const supportsMSE =+ typeof MediaSource !== 'undefined' && MediaSource.isTypeSupported('audio/mpeg');++ const playStarted = (cb) => {+ if (this._startedFired) return;+ this._startedFired = true;+ cb?.();+ };+ this._startedFired = false;++ return new Promise((resolve) => {+ this._onEnd = () => {+ this._speaking = false;+ this._cleanupAudio();+ onEnd?.();+ this._onEnd = null;+ resolve();+ };++ const finishOnError = () => {+ if (this._onEnd) this._onEnd();+ };++ if (supportsMSE && resp.body) {+ this._playStreamingMSE(resp.body, () => playStarted(onStart), finishOnError);+ } else {+ this._playBuffered(resp, () => playStarted(onStart), finishOnError);+ }+ });+ }++ cancel() {+ if (this._abort) {+ try {+ this._abort.abort();+ } catch {}+ this._abort = null;+ }+ this._cleanupAudio();+ this._speaking = false;+ // Resolve any pending speak() promise so callers don't hang+ if (this._onEnd) this._onEnd();+ }++ get speaking() {+ return this._speaking;+ }++ // ── Internal: streaming via MediaSource ────────────────────────────────++ _playStreamingMSE(stream, onStart, onError) {+ const ms = new MediaSource();+ this._mediaSourceURL = URL.createObjectURL(ms);+ const audio = new Audio(this._mediaSourceURL);+ this._audio = audio;+ audio.preload = 'auto';++ audio.addEventListener('playing', onStart, { once: true });+ audio.addEventListener('ended', () => this._onEnd?.(), { once: true });+ audio.addEventListener('error', () => onError?.(), { once: true });++ ms.addEventListener('sourceopen', async () => {+ let sb;+ try {+ sb = ms.addSourceBuffer('audio/mpeg');+ } catch (err) {+ onError?.();+ return;+ }++ const reader = stream.getReader();+ const queue = [];+ let reading = true;++ const pump = () => {+ if (!reading || sb.updating) return;+ const next = queue.shift();+ if (!next) return;+ try {+ sb.appendBuffer(next);+ } catch {+ reading = false;+ try {+ ms.endOfStream();+ } catch {}+ }+ };++ sb.addEventListener('updateend', pump);++ try {+ while (reading) {+ const { value, done } = await reader.read();+ if (done) {+ reading = false;+ const wait = () => {+ if (sb.updating || queue.length) {+ setTimeout(wait, 30);+ } else {+ try {+ ms.endOfStream();+ } catch {}+ }+ };+ wait();+ break;+ }+ queue.push(value);+ pump();+ }+ } catch (err) {+ if (err.name !== 'AbortError') onError?.();+ }+ });++ audio.play().catch(onError);+ }++ // ── Internal: buffered playback fallback (Safari) ──────────────────────++ async _playBuffered(resp, onStart, onError) {+ try {+ const blob = await resp.blob();+ const url = URL.createObjectURL(blob);+ this._mediaSourceURL = url;+ const audio = new Audio(url);+ this._audio = audio;+ audio.addEventListener('playing', onStart, { once: true });+ audio.addEventListener('ended', () => this._onEnd?.(), { once: true });+ audio.addEventListener('error', () => onError?.(), { once: true });+ await audio.play();+ } catch (err) {+ if (err.name !== 'AbortError') onError?.();+ }+ }++ _cleanupAudio() {+ if (this._audio) {+ try {+ this._audio.pause();+ } catch {}+ this._audio.src = '';+ this._audio = null;+ }+ if (this._mediaSourceURL) {+ try {+ URL.revokeObjectURL(this._mediaSourceURL);+ } catch {}+ this._mediaSourceURL = null;+ }+ this._startedFired = false;+ }+}++export function createTTS(config = {}) {+ const provider = config.provider || 'browser';+ if (provider === 'none') return null;+ if (provider === 'browser') return new BrowserTTS(config);+ if (provider === 'elevenlabs') return new ElevenLabsTTS(config);+ throw new Error(`TTS provider "${provider}" not implemented yet`);+}++export function createSTT(config = {}) {+ const provider = config.provider || 'browser';+ if (provider === 'none') return null;+ if (provider === 'browser') return new BrowserSTT(config);+ throw new Error(`STT provider "${provider}" not implemented yet`);+}diff --git a/publish/src/runtime/tools.js b/publish/src/runtime/tools.jsnew file mode 100644index 000000000..e0202b941--- /dev/null+++ b/publish/src/runtime/tools.js@@ -0,0 +1,174 @@+// Built-in scene-tools — available to every agent without any skill installed.+// See specs/AGENT_MANIFEST.md § Built-in tools.++export const BUILTIN_TOOLS = [+ {+ name: 'wave',+ description: 'Wave at the user. Use for greetings, farewells, or acknowledgments.',+ input_schema: {+ type: 'object',+ properties: {+ duration_ms: { type: 'integer', minimum: 500, maximum: 5000, default: 1500 },+ },+ },+ },+ {+ name: 'lookAt',+ description: "Direct the agent's gaze toward a target.",+ input_schema: {+ type: 'object',+ properties: {+ target: {+ type: 'string',+ enum: ['user', 'camera', 'center'],+ description: 'Where to look',+ },+ },+ required: ['target'],+ },+ },+ {+ name: 'play_clip',+ description: 'Play a named animation clip from the loaded body.',+ input_schema: {+ type: 'object',+ properties: {+ name: { type: 'string' },+ loop: { type: 'boolean', default: false },+ fade_ms: { type: 'integer', default: 200 },+ },+ required: ['name'],+ },+ },+ {+ name: 'setExpression',+ description: 'Set facial expression via morph target preset.',+ input_schema: {+ type: 'object',+ properties: {+ preset: {+ type: 'string',+ enum: ['neutral', 'happy', 'sad', 'surprised', 'confused', 'focused'],+ },+ intensity: { type: 'number', minimum: 0, maximum: 1, default: 1 },+ },+ required: ['preset'],+ },+ },+ {+ name: 'speak',+ description:+ 'Say something out loud via TTS. Use this instead of plain text when voice is on.',+ input_schema: {+ type: 'object',+ properties: { text: { type: 'string' } },+ required: ['text'],+ },+ },+ {+ name: 'remember',+ description:+ 'Save a durable memory about the user, a feedback rule, a project fact, or a reference.',+ input_schema: {+ type: 'object',+ properties: {+ key: { type: 'string', description: 'short snake_case filename, e.g. "user_role"' },+ name: { type: 'string' },+ description: { type: 'string' },+ type: { type: 'string', enum: ['user', 'feedback', 'project', 'reference'] },+ body: { type: 'string' },+ },+ required: ['key', 'name', 'description', 'type', 'body'],+ },+ },+];++// Stage-scoped tools — appended to an agent's tool list only when Runtime is+// attached to an <agent-stage>. See specs/STAGE_SPEC.md.+export const STAGE_TOOLS = [+ {+ name: 'observe_agents',+ description:+ 'List the other agents currently sharing this stage, with their names and positions.',+ input_schema: { type: 'object', properties: {} },+ },+ {+ name: 'say_to_agent',+ description:+ 'Send a message to another agent on the same stage. The target agent will receive it as a user turn and reply in their own chat chrome.',+ input_schema: {+ type: 'object',+ properties: {+ agentId: {+ type: 'string',+ description: 'Target agent id as returned by observe_agents.',+ },+ text: { type: 'string' },+ },+ required: ['agentId', 'text'],+ },+ },+];++export const BUILTIN_HANDLERS = {+ async wave(args, ctx) {+ const dur = args.duration_ms || 1500;+ await ctx.viewer.playAnimationByHint?.('wave', { duration: dur });+ ctx.memory.note('waved', { duration_ms: dur });+ return { ok: true };+ },++ async lookAt(args, ctx) {+ const target = args.target || 'user';+ ctx.viewer.lookAt?.(target);+ return { ok: true, target };+ },++ async play_clip(args, ctx) {+ const { name, loop = false, fade_ms = 200 } = args;+ // Resolve slot name (e.g. 'celebrate') to actual clip via agent's mapping+ const resolved = ctx.viewer.resolveAnimationSlot?.(name) ?? name;+ const played = ctx.viewer.playClipByName?.(resolved, { loop, fade_ms });+ if (!played) {+ if (resolved !== name)+ console.warn(`[play_clip] slot "${name}" → "${resolved}" not found in library`);+ return { ok: false, error: `No clip named "${resolved}"` };+ }+ return { ok: true, name, resolved };+ },++ async setExpression(args, ctx) {+ const { preset, intensity = 1 } = args;+ ctx.viewer.setExpression?.(preset, intensity);+ return { ok: true, preset };+ },++ async speak(args, ctx) {+ await ctx.speak(args.text);+ return { ok: true };+ },++ async remember(args, ctx) {+ const { key, name, description, type, body } = args;+ ctx.memory.write(key, { name, description, type, body });+ return { ok: true, saved: key };+ },++ async observe_agents(args, ctx) {+ if (!ctx.stage) return { ok: false, error: 'not on a stage' };+ const others = ctx.stage+ .getAgents()+ .filter((a) => a.agentId !== ctx.agentId)+ .map(({ agentId, name, position }) => ({ agentId, name, position }));+ return { ok: true, agents: others };+ },++ async say_to_agent(args, ctx) {+ if (!ctx.stage) return { ok: false, error: 'not on a stage' };+ const { agentId, text } = args;+ if (!agentId || !text) return { ok: false, error: 'agentId and text required' };+ const from = ctx.agentId || 'anon';+ ctx.stage.broadcast(from, { kind: 'direct', to: agentId, text });+ return ctx.stage.routeMessage(from, agentId, text);+ },+};diff --git a/publish/src/selfie-capture.js b/publish/src/selfie-capture.jsnew file mode 100644index 000000000..d2c8cc6c8--- /dev/null+++ b/publish/src/selfie-capture.js@@ -0,0 +1,387 @@+/**+ * Selfie capture flow — entry for /create.+ *+ * Manages two steps:+ * 1. Method choice (camera vs upload)+ * 2. 3-photo capture (Frontal / Left / Right) + body/avatar type selectors+ *+ * On submit, dispatches a `selfie:submit` CustomEvent on document with+ * detail = { files: { frontal, left, right }, bodyType, avatarType, method }+ * which the Avaturn pipeline (task 3) will pick up.+ */++const SLOT_KEYS = /** @type {const} */ (['frontal', 'left', 'right']);++const state = {+ method: /** @type {'camera' | 'upload' | null} */ (null),+ bodyType: /** @type {'male' | 'female'} */ ('male'),+ avatarType: /** @type {'v1' | 'v2'} */ ('v1'),+ files: /** @type {Record<string, File | null>} */ ({ frontal: null, left: null, right: null }),+};++const cameraSupported =+ typeof navigator !== 'undefined' &&+ !!navigator.mediaDevices &&+ typeof navigator.mediaDevices.getUserMedia === 'function';++// ── DOM refs ───────────────────────────────────────────────────────────────+const steps = /** @type {NodeListOf<HTMLElement>} */ (+ document.querySelectorAll('.step[data-step]')+);+const backBtn = /** @type {HTMLButtonElement} */ (document.getElementById('back-btn'));+const choiceButtons = /** @type {NodeListOf<HTMLButtonElement>} */ (+ document.querySelectorAll('.choice[data-method]')+);+const unsupportedMsg = document.getElementById('unsupported-msg');+const slotFrames = /** @type {NodeListOf<HTMLElement>} */ (+ document.querySelectorAll('.slot-frame[data-slot]')+);+const slotInputs = /** @type {NodeListOf<HTMLInputElement>} */ (+ document.querySelectorAll('input[data-slot-input]')+);+const submitBar = document.getElementById('submit-bar');+const submitBtn = /** @type {HTMLButtonElement} */ (document.getElementById('submit-btn'));+const bodyBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (+ document.querySelectorAll('[data-body]')+);+const typeBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (+ document.querySelectorAll('[data-type]')+);++// ── Step 1: method picker ──────────────────────────────────────────────────+if (!cameraSupported) {+ const camChoice = /** @type {HTMLButtonElement | null} */ (+ document.querySelector('.choice[data-method="camera"]')+ );+ if (camChoice) {+ camChoice.disabled = true;+ camChoice.setAttribute('aria-disabled', 'true');+ }+ unsupportedMsg?.classList.add('show');+}++choiceButtons.forEach((btn) => {+ btn.addEventListener('click', () => {+ const method = /** @type {'camera'|'upload'|null} */ (btn.getAttribute('data-method'));+ if (!method || btn.disabled) return;+ if (method === 'camera' && !cameraSupported) return;+ state.method = method;+ goToStep('capture');+ });+});++backBtn.addEventListener('click', () => {+ const current = currentStep();+ if (current === 'capture') {+ goToStep('method');+ } else {+ window.location.assign('/');+ }+});++// ── Step 2: slot fill ──────────────────────────────────────────────────────+slotFrames.forEach((frame) => {+ const slot = frame.getAttribute('data-slot');+ if (!slot) return;++ const open = () => {+ if (state.files[slot]) return; // already filled — use retake button to replace+ if (state.method === 'camera') {+ openCamera(slot);+ } else {+ /** @type {HTMLInputElement | null} */ (+ document.querySelector(`input[data-slot-input="${slot}"]`)+ )?.click();+ }+ };++ frame.addEventListener('click', open);+ frame.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ open();+ }+ });++ // Drag + drop+ frame.addEventListener('dragover', (e) => {+ e.preventDefault();+ frame.classList.add('drag');+ });+ frame.addEventListener('dragleave', () => frame.classList.remove('drag'));+ frame.addEventListener('drop', (e) => {+ e.preventDefault();+ frame.classList.remove('drag');+ const file = e.dataTransfer?.files?.[0];+ if (file && isImage(file)) setSlot(slot, file);+ });+});++slotInputs.forEach((input) => {+ input.addEventListener('change', () => {+ const slot = input.getAttribute('data-slot-input');+ const file = input.files?.[0];+ if (slot && file && isImage(file)) setSlot(slot, file);+ input.value = '';+ });+});++// ── Selectors ──────────────────────────────────────────────────────────────+bodyBtns.forEach((btn) => {+ btn.addEventListener('click', () => {+ const val = /** @type {'male'|'female'} */ (btn.getAttribute('data-body'));+ state.bodyType = val;+ bodyBtns.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));+ });+});+typeBtns.forEach((btn) => {+ btn.addEventListener('click', () => {+ const val = /** @type {'v1'|'v2'} */ (btn.getAttribute('data-type'));+ state.avatarType = val;+ typeBtns.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));+ });+});++// ── Submit ─────────────────────────────────────────────────────────────────+submitBtn.addEventListener('click', () => {+ if (!allSlotsFilled()) return;+ document.dispatchEvent(+ new CustomEvent('selfie:submit', {+ detail: {+ files: { ...state.files },+ bodyType: state.bodyType,+ avatarType: state.avatarType,+ method: state.method,+ },+ }),+ );+ // Temporary visual ack until task 3 wires the pipeline.+ submitBtn.textContent = 'Sending…';+ submitBtn.disabled = true;+ submitBtn.classList.remove('ready');+});++// ── Step machine ───────────────────────────────────────────────────────────+/** @returns {'method' | 'capture'} */+function currentStep() {+ const active = document.querySelector('.step.active');+ return /** @type {'method'|'capture'} */ (active?.getAttribute('data-step') || 'method');+}++/** @param {'method' | 'capture'} step */+function goToStep(step) {+ steps.forEach((el) => el.classList.toggle('active', el.getAttribute('data-step') === step));+ if (submitBar) submitBar.hidden = step !== 'capture';+ window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });+}++// ── Slot helpers ───────────────────────────────────────────────────────────+/** @param {File} file */+function isImage(file) {+ return /^image\/(jpeg|png)$/i.test(file.type || '');+}++/**+ * @param {string} slot+ * @param {File} file+ */+function setSlot(slot, file) {+ state.files[slot] = file;+ renderSlot(slot);+ updateSubmit();+}++/** @param {string} slot */+function clearSlot(slot) {+ state.files[slot] = null;+ renderSlot(slot);+ updateSubmit();+}++/** @param {string} slot */+function renderSlot(slot) {+ const frame = /** @type {HTMLElement | null} */ (+ document.querySelector(`.slot-frame[data-slot="${slot}"]`)+ );+ if (!frame) return;+ const file = state.files[slot];++ // Clean up any existing preview / retake artefacts.+ frame.querySelector('img.preview')?.remove();+ frame.querySelector('.slot-retake')?.remove();++ if (!file) {+ frame.classList.remove('filled');+ return;+ }++ frame.classList.add('filled');++ const img = document.createElement('img');+ img.className = 'preview';+ img.alt = `${slot} photo preview`;+ img.src = URL.createObjectURL(file);+ img.onload = () => URL.revokeObjectURL(img.src);+ frame.appendChild(img);++ const retake = document.createElement('button');+ retake.type = 'button';+ retake.className = 'slot-retake';+ retake.setAttribute('aria-label', `Remove ${slot} photo`);+ retake.innerHTML =+ '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15A9 9 0 1 1 18.36 5.64L23 10"/></svg>';+ retake.addEventListener('click', (e) => {+ e.stopPropagation();+ clearSlot(slot);+ });+ frame.appendChild(retake);+}++function allSlotsFilled() {+ return SLOT_KEYS.every((k) => !!state.files[k]);+}++function updateSubmit() {+ const n = SLOT_KEYS.filter((k) => !!state.files[k]).length;+ submitBtn.textContent = n === 3 ? 'Submit' : `Upload ${n}/3`;+ const ready = n === 3;+ submitBtn.disabled = !ready;+ submitBtn.classList.toggle('ready', ready);+}++// ── Camera overlay ─────────────────────────────────────────────────────────+const camOverlay = document.getElementById('cam-overlay');+const camVideo = /** @type {HTMLVideoElement | null} */ (document.getElementById('cam-video'));+const camSlotName = document.getElementById('cam-slot-name');+const camError = document.getElementById('cam-error');+const camActionsLive = document.getElementById('cam-actions-live');+const camActionsReview = document.getElementById('cam-actions-review');++const cam = {+ stream: /** @type {MediaStream | null} */ (null),+ slot: /** @type {string | null} */ (null),+ pendingFile: /** @type {File | null} */ (null),+ pendingUrl: /** @type {string | null} */ (null),+};++/** @param {string} slot */+async function openCamera(slot) {+ if (!camOverlay || !camVideo) return;+ cam.slot = slot;+ if (camSlotName) camSlotName.textContent = slotPretty(slot);+ setCamMode('live');+ camError?.setAttribute('hidden', '');+ camOverlay.classList.add('open');++ try {+ cam.stream = await navigator.mediaDevices.getUserMedia({+ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } },+ audio: false,+ });+ camVideo.srcObject = cam.stream;+ } catch (err) {+ console.warn('[selfie] camera error:', err);+ showCamError('Could not access camera. Check permissions and try again.');+ }+}++function closeCamera() {+ if (cam.stream) {+ cam.stream.getTracks().forEach((t) => t.stop());+ cam.stream = null;+ }+ if (camVideo) camVideo.srcObject = null;+ camOverlay?.classList.remove('open');+ clearPending();+ cam.slot = null;+}++function clearPending() {+ if (cam.pendingUrl) URL.revokeObjectURL(cam.pendingUrl);+ cam.pendingUrl = null;+ cam.pendingFile = null;+ // Remove any transient preview img in the stage.+ document.querySelector('#cam-stage img.preview')?.remove();+}++/** @param {'live' | 'review'} mode */+function setCamMode(mode) {+ if (mode === 'live') {+ camActionsLive?.removeAttribute('hidden');+ camActionsReview?.setAttribute('hidden', '');+ } else {+ camActionsLive?.setAttribute('hidden', '');+ camActionsReview?.removeAttribute('hidden');+ }+}++/** @param {string} msg */+function showCamError(msg) {+ if (!camError) return;+ camError.textContent = msg;+ camError.removeAttribute('hidden');+}++camOverlay?.addEventListener('click', (e) => {+ const target = /** @type {HTMLElement} */ (e.target);+ const action = target.closest('[data-cam-action]')?.getAttribute('data-cam-action');+ if (!action) return;+ if (action === 'cancel') closeCamera();+ else if (action === 'shoot') shoot();+ else if (action === 'retake') {+ clearPending();+ setCamMode('live');+ } else if (action === 'use') confirmCamShot();+});++async function shoot() {+ if (!camVideo || !cam.stream) return;+ const w = camVideo.videoWidth;+ const h = camVideo.videoHeight;+ if (!w || !h) return;+ const canvas = document.createElement('canvas');+ canvas.width = w;+ canvas.height = h;+ const ctx = canvas.getContext('2d');+ if (!ctx) return;+ // Un-mirror: the <video> is CSS-flipped for selfie feel, but the saved file+ // should match what the camera actually sees.+ ctx.drawImage(camVideo, 0, 0, w, h);++ const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', 0.92));+ if (!blob) {+ showCamError('Snapshot failed. Try again.');+ return;+ }+ const file = new File([blob], `${cam.slot || 'photo'}.jpg`, { type: 'image/jpeg' });+ cam.pendingFile = file;+ cam.pendingUrl = URL.createObjectURL(file);++ // Show preview over the video feed.+ const stage = document.getElementById('cam-stage');+ if (stage) {+ const img = document.createElement('img');+ img.className = 'preview';+ img.alt = 'captured preview';+ img.src = cam.pendingUrl;+ stage.appendChild(img);+ }+ setCamMode('review');+}++function confirmCamShot() {+ if (!cam.pendingFile || !cam.slot) return;+ const slot = cam.slot;+ const file = cam.pendingFile;+ closeCamera();+ setSlot(slot, file);+}++// ── Utilities ──────────────────────────────────────────────────────────────+/** @param {string} slot */+function slotPretty(slot) {+ if (slot === 'frontal') return 'Frontal';+ if (slot === 'left') return 'Left';+ if (slot === 'right') return 'Right';+ return slot;+}diff --git a/publish/src/selfie-pipeline.js b/publish/src/selfie-pipeline.jsnew file mode 100644index 000000000..b1693640d--- /dev/null+++ b/publish/src/selfie-pipeline.js@@ -0,0 +1,201 @@+/**+ * Selfie pipeline — bridges the 3-photo capture UI on /create to the Avaturn+ * session endpoint, then hands off to the main app's AvatarCreator modal.+ *+ * Flow:+ * [selfie:submit] → downscale photos → POST /api/onboarding/avaturn-session+ * → on 200 { session_url } → navigate to /#avatarSession=<encoded url>+ * → app.js reads hash, opens AvatarCreator with the session URL+ * → Avaturn iframe runs the editor, fires 'export' with GLB URL+ * → app.js loads the GLB + saves it to the user's account+ */++const ENDPOINT = '/api/onboarding/avaturn-session';+const MAX_DIM = 1024; // downscale so each base64 photo stays well under 2.5MB+const JPEG_QUALITY = 0.88;++document.addEventListener('selfie:submit', (event) => {+ const ev = /** @type {CustomEvent} */ (event);+ run(ev.detail).catch((err) => {+ console.error('[selfie-pipeline]', err);+ setStatus(err.userMessage || 'Something went wrong. Try again.', { error: true });+ resetSubmit();+ });+});++/**+ * @param {{+ * files: Record<'frontal'|'left'|'right', File | null>,+ * bodyType: 'male' | 'female',+ * avatarType: 'v1' | 'v2',+ * method: 'camera' | 'upload' | null,+ * }} detail+ */+async function run(detail) {+ if (!detail?.files?.frontal || !detail.files.left || !detail.files.right) {+ throw withMessage(new Error('missing photos'), 'Please add all 3 photos.');+ }++ setStatus('Preparing photos…');+ const photos = {+ frontal: await fileToDataUrl(detail.files.frontal),+ left: await fileToDataUrl(detail.files.left),+ right: await fileToDataUrl(detail.files.right),+ };++ setStatus('Sending to avatar pipeline…');+ const res = await fetch(ENDPOINT, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ photos,+ body_type: detail.bodyType,+ avatar_type: detail.avatarType,+ }),+ });++ if (!res.ok) {+ const payload = await res.json().catch(() => ({}));+ throw mapApiError(res.status, payload);+ }++ const data = await res.json();+ if (!data.session_url) {+ throw withMessage(new Error('no session_url'), 'The pipeline did not return a session.');+ }++ setStatus('Opening editor…');+ // Hand off to the main viewer, which owns the AvatarCreator modal + GLB loader.+ const target = `/#avatarSession=${encodeURIComponent(data.session_url)}`;+ window.location.assign(target);+}++/**+ * Reads a File, paints it into a canvas clamped to MAX_DIM × MAX_DIM, returns+ * a JPEG data URL. Keeps upload payloads predictable across phone camera sizes.+ * @param {File} file+ */+async function fileToDataUrl(file) {+ const bitmap = await loadBitmap(file);+ const { width, height } = fit(bitmap.width, bitmap.height, MAX_DIM);+ const canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext('2d');+ if (!ctx) throw new Error('2d canvas unsupported');+ ctx.drawImage(bitmap, 0, 0, width, height);+ try {+ bitmap.close?.();+ } catch (_) {+ // ImageBitmap.close is optional on older browsers+ }+ return canvas.toDataURL('image/jpeg', JPEG_QUALITY);+}++/** @param {File} file @returns {Promise<ImageBitmap | HTMLImageElement>} */+async function loadBitmap(file) {+ if (typeof createImageBitmap === 'function') {+ try {+ return await createImageBitmap(file);+ } catch (_) {+ // fall through to <img> fallback+ }+ }+ return new Promise((resolve, reject) => {+ const img = new Image();+ img.onload = () => resolve(img);+ img.onerror = () => reject(new Error('could not decode image'));+ img.src = URL.createObjectURL(file);+ });+}++/**+ * @param {number} w+ * @param {number} h+ * @param {number} max+ */+function fit(w, h, max) {+ if (w <= max && h <= max) return { width: w, height: h };+ const s = Math.min(max / w, max / h);+ return { width: Math.round(w * s), height: Math.round(h * s) };+}++/**+ * @param {number} status+ * @param {{ error?: string, error_description?: string }} payload+ */+function mapApiError(status, payload) {+ const code = payload.error;+ if (status === 401)+ return withMessage(+ new Error(code || 'unauthorized'),+ 'Please sign in to create an avatar.',+ );+ if (status === 413)+ return withMessage(new Error(code || 'too_large'), 'Photos are too large. Try again.');+ if (status === 429)+ return withMessage(+ new Error(code || 'rate_limited'),+ 'Too many attempts — wait a minute and try again.',+ );+ if (status === 501)+ return withMessage(+ new Error(code || 'not_configured'),+ 'Avatar pipeline is not set up on this deployment.',+ );+ if (status === 502)+ return withMessage(+ new Error(code || 'upstream_error'),+ 'Avatar provider is having trouble. Try again shortly.',+ );+ return withMessage(+ new Error(code || `http_${status}`),+ payload.error_description || 'Could not create avatar.',+ );+}++/**+ * @param {Error} err+ * @param {string} userMessage+ */+function withMessage(err, userMessage) {+ /** @type {any} */ (err).userMessage = userMessage;+ return err;+}++// ── UI helpers ─────────────────────────────────────────────────────────────+const submitBtn = /** @type {HTMLButtonElement | null} */ (document.getElementById('submit-btn'));+let errorBanner = /** @type {HTMLElement | null} */ (null);++/** @param {string} text @param {{ error?: boolean }} [opts] */+function setStatus(text, opts = {}) {+ if (submitBtn) {+ submitBtn.textContent = text;+ submitBtn.disabled = true;+ submitBtn.classList.remove('ready');+ }+ if (opts.error) {+ if (!errorBanner) {+ errorBanner = document.createElement('p');+ errorBanner.className = 'unsupported show';+ errorBanner.setAttribute('role', 'alert');+ errorBanner.style.maxWidth = '720px';+ errorBanner.style.margin = '0 auto 16px';+ const bar = document.getElementById('submit-bar');+ bar?.parentNode?.insertBefore(errorBanner, bar);+ }+ errorBanner.textContent = text;+ } else if (errorBanner) {+ errorBanner.remove();+ errorBanner = null;+ }+}++function resetSubmit() {+ if (!submitBtn) return;+ // Re-enable submit for another attempt if photos are still present.+ submitBtn.disabled = false;+ submitBtn.textContent = 'Submit';+ submitBtn.classList.add('ready');+}diff --git a/publish/src/share-panel-builders.js b/publish/src/share-panel-builders.jsnew file mode 100644index 000000000..03a5b7bcf--- /dev/null+++ b/publish/src/share-panel-builders.js@@ -0,0 +1,83 @@+/**+ * Pure, side-effect-free helpers for building share/embed snippets.+ * Kept separate from share-panel.js so tests can import them without+ * pulling in the CSS or any DOM-coupled code.+ *+ * @module share-panel-builders+ */++/** @type {{ readonly bg: 'transparent' | 'dark' | 'light', readonly name: boolean, readonly size: 'small' | 'medium' | 'large' }} */+export const DEFAULT_OPTIONS = Object.freeze({+ bg: 'transparent',+ name: true,+ size: 'medium',+});++/** Iframe pixel dimensions per size keyword. */+export const SIZES = Object.freeze({+ small: { width: 320, height: 420 },+ medium: { width: 420, height: 520 },+ large: { width: 520, height: 680 },+});++/**+ * Build the canonical embed URL for an agent with the given options. Default+ * options are omitted from the query string so the canonical URL stays short.+ *+ * @param {{ origin: string, agentId: string, opts?: Partial<typeof DEFAULT_OPTIONS> }} args+ * @returns {string}+ */+export function buildEmbedUrl({ origin, agentId, opts = {} }) {+ const merged = { ...DEFAULT_OPTIONS, ...opts };+ const url = new URL(`${origin}/agent/${agentId}/embed`);+ if (merged.bg !== DEFAULT_OPTIONS.bg) url.searchParams.set('bg', merged.bg);+ if (merged.name !== DEFAULT_OPTIONS.name) url.searchParams.set('name', '0');+ return url.toString();+}++/**+ * Build the iframe embed snippet. Uses the canonical /agent/{id}/embed URL,+ * declares a transparent CSS background so external sites composite cleanly,+ * and lazy-loads to avoid a network hit on hosts that paginate embeds.+ *+ * @param {{ origin: string, agentId: string, opts?: Partial<typeof DEFAULT_OPTIONS> }} args+ * @returns {string}+ */+export function buildIframeSnippet({ origin, agentId, opts = {} }) {+ const merged = { ...DEFAULT_OPTIONS, ...opts };+ const { width, height } = SIZES[merged.size] || SIZES.medium;+ const src = buildEmbedUrl({ origin, agentId, opts: merged });+ const allow = 'autoplay; xr-spatial-tracking; microphone; camera';+ return (+ `<iframe\n` ++ ` src="${src}"\n` ++ ` width="${width}" height="${height}"\n` ++ ` style="border:0;border-radius:12px;background:transparent"\n` ++ ` allow="${allow}"\n` ++ ` loading="lazy"\n` ++ ` referrerpolicy="strict-origin-when-cross-origin"\n` ++ `></iframe>`+ );+}++/**+ * Build the <agent-3d> web-component embed snippet. The bg / name-plate toggles+ * propagate through `background="..."` and `name-plate="off"` attributes which+ * the element observes (see element.js → _applyBackground / _applyNamePlate).+ *+ * @param {{ origin: string, agentId: string, opts?: Partial<typeof DEFAULT_OPTIONS> }} args+ * @returns {string}+ */+export function buildWebComponentSnippet({ origin, agentId, opts = {} }) {+ const merged = { ...DEFAULT_OPTIONS, ...opts };+ const { width, height } = SIZES[merged.size] || SIZES.medium;+ const attrs = [`agent-id="${agentId}"`];+ if (merged.bg !== DEFAULT_OPTIONS.bg) attrs.push(`background="${merged.bg}"`);+ if (merged.name !== DEFAULT_OPTIONS.name) attrs.push(`name-plate="off"`);+ return (+ `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/script>\n` ++ `<agent-3d ${attrs.join(' ')}\n` ++ ` style="display:block;width:${width}px;height:${height}px"\n` ++ `></agent-3d>`+ );+}diff --git a/publish/src/share-panel.css b/publish/src/share-panel.cssnew file mode 100644index 000000000..b5ac996f3--- /dev/null+++ b/publish/src/share-panel.css@@ -0,0 +1,245 @@+.share-panel-backdrop {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.6);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 9000;+ backdrop-filter: blur(2px);+}++.share-panel-modal {+ background: #1a1a1a;+ border: 1px solid #333;+ border-radius: 12px;+ width: min(560px, calc(100vw - 32px));+ max-height: calc(100vh - 64px);+ overflow-y: auto;+ padding: 24px;+ color: #e8e8e8;+ font-family: system-ui, sans-serif;+ font-size: 14px;+}++.share-panel-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 20px;+}++.share-panel-title {+ font-size: 17px;+ font-weight: 600;+ color: #fff;+ margin: 0;+}++.share-panel-close {+ background: none;+ border: none;+ color: #888;+ font-size: 22px;+ line-height: 1;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 4px;+}++.share-panel-close:hover {+ color: #fff;+ background: #2e2e2e;+}++.share-panel-row {+ margin-bottom: 18px;+}++.share-panel-label {+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.07em;+ color: #888;+ margin-bottom: 6px;+}++.share-panel-field {+ display: flex;+ gap: 6px;+ align-items: flex-start;+}++.share-panel-code {+ flex: 1;+ background: #111;+ border: 1px solid #2e2e2e;+ border-radius: 6px;+ padding: 8px 10px;+ font-family: 'Courier New', monospace;+ font-size: 12px;+ color: #c8d3f5;+ word-break: break-all;+ white-space: pre-wrap;+ line-height: 1.5;+ min-height: 36px;+}++.share-panel-actions {+ display: flex;+ flex-direction: column;+ gap: 6px;+ flex-shrink: 0;+}++.share-panel-btn {+ background: #2a2a2a;+ border: 1px solid #3a3a3a;+ border-radius: 6px;+ color: #d0d0d0;+ cursor: pointer;+ font-size: 12px;+ padding: 6px 12px;+ white-space: nowrap;+ transition:+ background 0.12s,+ color 0.12s;+}++.share-panel-btn:hover {+ background: #383838;+ color: #fff;+}++.share-panel-btn.copied {+ color: #4caf7d;+ border-color: #4caf7d44;+}++.share-panel-og-img {+ display: block;+ width: 100%;+ height: auto;+ border-radius: 6px;+ border: 1px solid #2e2e2e;+ margin-bottom: 8px;+ background: #111;+}++.share-panel-qr {+ display: flex;+ justify-content: center;+ margin-top: 4px;+}++.share-panel-qr canvas {+ border-radius: 6px;+ border: 4px solid #fff;+}++.share-panel-divider {+ border: none;+ border-top: 1px solid #2a2a2a;+ margin: 20px 0;+}++/* ── Customise controls ──────────────────────────────────────────────────────── */++.share-panel-controls {+ display: flex;+ flex-wrap: wrap;+ gap: 12px;+}++.share-panel-fieldset {+ flex: 1 1 140px;+ min-width: 140px;+ border: 1px solid #2a2a2a;+ border-radius: 8px;+ padding: 8px 10px 10px;+ margin: 0;+}++.share-panel-fieldset legend {+ font-size: 10px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: #888;+ padding: 0 4px;+}++.share-panel-segments {+ display: flex;+ gap: 4px;+ flex-wrap: wrap;+}++.share-panel-segment {+ flex: 1;+ min-width: 0;+ background: #1f1f1f;+ border: 1px solid #2e2e2e;+ border-radius: 5px;+ color: #b0b0b0;+ cursor: pointer;+ font-size: 11px;+ padding: 5px 8px;+ white-space: nowrap;+ text-align: center;+ transition:+ background 0.12s,+ color 0.12s,+ border-color 0.12s;+}++.share-panel-segment:hover {+ background: #2a2a2a;+ color: #fff;+}++.share-panel-segment--active {+ background: #2e3a55;+ border-color: #4d6aa3;+ color: #e8eeff;+}++.share-panel-segment--active:hover {+ background: #364568;+}++/* ── Live preview ────────────────────────────────────────────────────────────── */++.share-panel-preview {+ display: flex;+ justify-content: center;+ align-items: center;+ border-radius: 10px;+ background:+ linear-gradient(45deg, #1d1d1d 25%, transparent 25%) 0 0 / 16px 16px,+ linear-gradient(-45deg, #1d1d1d 25%, transparent 25%) 0 8px / 16px 16px,+ linear-gradient(45deg, transparent 75%, #1d1d1d 75%) 8px -8px / 16px 16px,+ linear-gradient(-45deg, transparent 75%, #1d1d1d 75%) 8px 0 / 16px 16px,+ #252525;+ padding: 16px;+ border: 1px solid #2a2a2a;+ min-height: 200px;+}++.share-panel-preview-frame {+ display: block;+ border: 0;+ border-radius: 8px;+ background: transparent;+ max-width: 100%;+ box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4);+}++.share-panel-preview-frame[data-bg='dark'] {+ background: #0b0d10;+}++.share-panel-preview-frame[data-bg='light'] {+ background: #f5f5f5;+}diff --git a/publish/src/share-panel.js b/publish/src/share-panel.jsnew file mode 100644index 000000000..ec61ab7f2--- /dev/null+++ b/publish/src/share-panel.js@@ -0,0 +1,367 @@+import { renderQRToCanvas, renderQRToSVG } from './erc8004/qr.js';+import {+ DEFAULT_OPTIONS,+ SIZES,+ buildEmbedUrl,+ buildIframeSnippet,+ buildWebComponentSnippet,+} from './share-panel-builders.js';+import './share-panel.css';++// Re-export the pure helpers so existing imports keep working.+export {+ buildEmbedUrl,+ buildIframeSnippet,+ buildWebComponentSnippet,+ DEFAULT_OPTIONS,+ SIZES,+} from './share-panel-builders.js';++/**+ * One-click share modal for an agent: link, customisable iframe + web-component+ * snippets with a live preview, OG card, and QR code.+ *+ * @example+ * const panel = new SharePanel({+ * agent: { id, slug, name },+ * container: document.body,+ * });+ * panel.open();+ */++export class SharePanel {+ /**+ * @param {{+ * agent: { id: string, slug?: string, name?: string, thumbnailUrl?: string },+ * container?: HTMLElement,+ * embedOrigin?: string,+ * }} opts+ */+ constructor({ agent, container = document.body, embedOrigin = location.origin }) {+ this._agent = agent;+ this._container = container;+ this._origin = embedOrigin;+ this._backdrop = null;+ this._opener = null;+ this._opts = { ...DEFAULT_OPTIONS };+ this._onKeyDown = this._onKeyDown.bind(this);+ }++ open() {+ if (this._backdrop) return;+ this._opener = document.activeElement;++ const { id, slug, name } = this._agent;+ const link = `${this._origin}/a/${slug || id}`;+ const ogUrl = `${this._origin}/api/a-og?id=${id}`;+ const modalId = `share-panel-title-${id}`;++ const backdrop = document.createElement('div');+ backdrop.className = 'share-panel-backdrop';+ backdrop.setAttribute('role', 'presentation');++ const modal = document.createElement('div');+ modal.className = 'share-panel-modal';+ modal.setAttribute('role', 'dialog');+ modal.setAttribute('aria-modal', 'true');+ modal.setAttribute('aria-labelledby', modalId);+ modal.tabIndex = -1;++ modal.innerHTML = `+ <div class="share-panel-header">+ <h2 class="share-panel-title" id="${modalId}">Share ${name ? _esc(name) : 'Agent'}</h2>+ <button class="share-panel-close" aria-label="Close share panel">×</button>+ </div>++ <div class="share-panel-row" data-section="link">+ <div class="share-panel-label">Link</div>+ <div class="share-panel-field">+ <div class="share-panel-code" data-role="link-code">${_esc(link)}</div>+ <div class="share-panel-actions">+ <button class="share-panel-btn" data-copy-target="link-code">Copy</button>+ <a class="share-panel-btn" href="${_esc(link)}" target="_blank" rel="noopener">Open ↗</a>+ </div>+ </div>+ </div>++ <div class="share-panel-row" data-section="customise">+ <div class="share-panel-label">Customise embed</div>+ <div class="share-panel-controls">+ <fieldset class="share-panel-fieldset">+ <legend>Background</legend>+ <div class="share-panel-segments" role="radiogroup" aria-label="Background">+ ${_segmentBtn('bg', 'transparent', 'Transparent', this._opts.bg)}+ ${_segmentBtn('bg', 'dark', 'Dark', this._opts.bg)}+ ${_segmentBtn('bg', 'light', 'Light', this._opts.bg)}+ </div>+ </fieldset>+ <fieldset class="share-panel-fieldset">+ <legend>Name plate</legend>+ <div class="share-panel-segments" role="radiogroup" aria-label="Name plate">+ ${_segmentBtn('name', 'true', 'On', String(this._opts.name))}+ ${_segmentBtn('name', 'false', 'Off', String(this._opts.name))}+ </div>+ </fieldset>+ <fieldset class="share-panel-fieldset">+ <legend>Size</legend>+ <div class="share-panel-segments" role="radiogroup" aria-label="Size">+ ${_segmentBtn('size', 'small', 'Small', this._opts.size)}+ ${_segmentBtn('size', 'medium', 'Medium', this._opts.size)}+ ${_segmentBtn('size', 'large', 'Large', this._opts.size)}+ </div>+ </fieldset>+ </div>+ </div>++ <div class="share-panel-row" data-section="preview">+ <div class="share-panel-label">Live preview</div>+ <div class="share-panel-preview" data-role="preview-frame-mount"></div>+ </div>++ <div class="share-panel-row" data-section="iframe">+ <div class="share-panel-label">iframe embed</div>+ <div class="share-panel-field">+ <div class="share-panel-code" data-role="iframe-code"></div>+ <div class="share-panel-actions">+ <button class="share-panel-btn" data-copy-target="iframe-code">Copy</button>+ </div>+ </div>+ </div>++ <div class="share-panel-row" data-section="wc">+ <div class="share-panel-label">Web component</div>+ <div class="share-panel-field">+ <div class="share-panel-code" data-role="wc-code"></div>+ <div class="share-panel-actions">+ <button class="share-panel-btn" data-copy-target="wc-code">Copy</button>+ </div>+ </div>+ </div>++ <hr class="share-panel-divider">++ <div class="share-panel-row" data-section="og">+ <div class="share-panel-label">OG preview</div>+ <img class="share-panel-og-img" src="${_esc(ogUrl)}"+ alt="OG preview for ${_esc(name || id)}"+ style="aspect-ratio:1200/630;">+ <div class="share-panel-field" style="margin-top:6px;">+ <div class="share-panel-code" data-role="og-code">${_esc(ogUrl)}</div>+ <div class="share-panel-actions">+ <button class="share-panel-btn" data-copy-target="og-code">Copy URL</button>+ </div>+ </div>+ </div>++ <hr class="share-panel-divider">++ <div class="share-panel-row" data-section="qr">+ <div class="share-panel-label">QR code</div>+ <div class="share-panel-qr" id="share-panel-qr-mount"></div>+ </div>+ `;++ modal.querySelector('.share-panel-close').addEventListener('click', () => this.close());++ // Segment-button toggles+ modal.querySelectorAll('.share-panel-segment').forEach((btn) => {+ btn.addEventListener('click', () => this._onSegmentClick(btn));+ });++ // Copy buttons (resolve target text on click for live snippet content)+ modal.querySelectorAll('[data-copy-target]').forEach((btn) => {+ btn.addEventListener('click', () => this._copy(btn));+ });++ backdrop.addEventListener('click', (e) => {+ if (e.target === backdrop) this.close();+ });++ backdrop.appendChild(modal);+ this._container.appendChild(backdrop);+ this._backdrop = backdrop;++ this._renderSnippets();+ this._mountPreview();+ this._renderQR(link);++ document.addEventListener('keydown', this._onKeyDown);+ const firstBtn = modal.querySelector('button');+ (firstBtn || modal).focus();+ _trapFocus(modal);+ }++ close() {+ if (!this._backdrop) return;+ document.removeEventListener('keydown', this._onKeyDown);+ this._backdrop.remove();+ this._backdrop = null;+ if (this._opener && typeof this._opener.focus === 'function') {+ this._opener.focus();+ }+ this._opener = null;+ }++ // ── Snippet rendering ────────────────────────────────────────────────────────++ _renderSnippets() {+ const m = this._backdrop;+ if (!m) return;+ const args = { origin: this._origin, agentId: this._agent.id, opts: this._opts };+ m.querySelector('[data-role="iframe-code"]').textContent = buildIframeSnippet(args);+ m.querySelector('[data-role="wc-code"]').textContent = buildWebComponentSnippet(args);+ }++ // ── Live preview ─────────────────────────────────────────────────────────────++ _mountPreview() {+ const mount = this._backdrop?.querySelector('[data-role="preview-frame-mount"]');+ if (!mount) return;+ mount.innerHTML = '';+ this._previewMount = mount;+ this._renderPreview();+ }++ _renderPreview() {+ if (!this._previewMount) return;+ const { width, height } = SIZES[this._opts.size];+ const url = new URL(+ buildEmbedUrl({+ origin: this._origin,+ agentId: this._agent.id,+ opts: this._opts,+ }),+ );+ // Always set preview=1 so the embed page skips its origin allow-list+ // gate when the dialog runs on a non-allowlisted host.+ url.searchParams.set('preview', '1');++ const frame = document.createElement('iframe');+ frame.className = 'share-panel-preview-frame';+ frame.src = url.toString();+ frame.width = String(width);+ frame.height = String(height);+ frame.setAttribute('loading', 'lazy');+ frame.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');+ frame.setAttribute('allow', 'autoplay; xr-spatial-tracking');+ frame.setAttribute('aria-label', `Live preview of ${this._agent.name || 'agent'} embed`);+ // Visualise the chosen background while the iframe paints.+ frame.dataset.bg = this._opts.bg;+ this._previewMount.replaceChildren(frame);+ }++ // ── Segment toggles ──────────────────────────────────────────────────────────++ _onSegmentClick(btn) {+ const group = btn.dataset.group;+ const value = btn.dataset.value;+ if (!group) return;++ // Update opts+ if (group === 'name') {+ this._opts.name = value === 'true';+ } else {+ this._opts[group] = value;+ }++ // Update aria-checked + active class for the group+ const groupRoot = btn.closest('.share-panel-segments');+ groupRoot.querySelectorAll('.share-panel-segment').forEach((b) => {+ const active = b === btn;+ b.classList.toggle('share-panel-segment--active', active);+ b.setAttribute('aria-checked', String(active));+ });++ this._renderSnippets();+ this._renderPreview();+ }++ // ── Misc ─────────────────────────────────────────────────────────────────────++ _renderQR(link) {+ const qrMount = this._backdrop?.querySelector('#share-panel-qr-mount');+ if (!qrMount) return;+ try {+ const canvas = renderQRToCanvas(link, { scale: 6, margin: 2 });+ qrMount.appendChild(canvas);+ } catch {+ try {+ qrMount.innerHTML = renderQRToSVG(link, { scale: 6, margin: 2 });+ } catch {+ qrMount.textContent = link;+ }+ }+ }++ _copy(btn) {+ const targetRole = btn.getAttribute('data-copy-target');+ const node = this._backdrop?.querySelector(`[data-role="${targetRole}"]`);+ if (!node) return;+ const text = node.textContent || '';+ navigator.clipboard.writeText(text).then(() => {+ const orig = btn.textContent;+ btn.textContent = 'Copied ✓';+ btn.classList.add('copied');+ setTimeout(() => {+ btn.textContent = orig;+ btn.classList.remove('copied');+ }, 1200);+ });+ }++ _onKeyDown(e) {+ if (e.key === 'Escape') {+ e.preventDefault();+ this.close();+ }+ if (e.key === 'Tab' && this._backdrop) {+ _handleTabTrap(e, this._backdrop.querySelector('.share-panel-modal'));+ }+ }+}++// ── Internal helpers ─────────────────────────────────────────────────────────────++function _segmentBtn(group, value, label, currentValue) {+ const active = String(currentValue) === String(value);+ return (+ `<button type="button"` ++ ` class="share-panel-segment${active ? ' share-panel-segment--active' : ''}"` ++ ` role="radio" aria-checked="${active}"` ++ ` data-group="${_esc(group)}" data-value="${_esc(value)}">${_esc(label)}</button>`+ );+}++function _esc(str) {+ return String(str)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++const FOCUSABLE =+ 'a[href],button:not([disabled]),input,select,textarea,[tabindex]:not([tabindex="-1"])';++function _trapFocus(modal) {+ const els = modal.querySelectorAll(FOCUSABLE);+ if (els.length) els[0].focus();+}++function _handleTabTrap(e, modal) {+ const els = Array.from(modal.querySelectorAll(FOCUSABLE));+ if (!els.length) return;+ const first = els[0];+ const last = els[els.length - 1];+ if (e.shiftKey) {+ if (document.activeElement === first) {+ e.preventDefault();+ last.focus();+ }+ } else {+ if (document.activeElement === last) {+ e.preventDefault();+ first.focus();+ }+ }+}diff --git a/publish/src/skills/index.js b/publish/src/skills/index.jsnew file mode 100644index 000000000..78d486bc2--- /dev/null+++ b/publish/src/skills/index.js@@ -0,0 +1,215 @@+// Skill registry — loads skill bundles and exposes the ctx API.+// See specs/SKILL_SPEC.md++import { resolveURI } from '../ipfs.js';+import { getHost } from './sandbox-host.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, handlersSrc }) {+ this.uri = uri;+ this.manifest = manifest;+ this.name = manifest.name;+ this.version = manifest.version;+ this.instructions = instructions;+ this.tools = tools || [];+ // trusted-main-thread: populated from dynamic import; sandbox: populated from handlersSrc+ this.handlers = handlers || {};+ this.handlersSrc = handlersSrc || null;+ }++ async invoke(toolName, args, ctx) {+ const scoped = { ...ctx, skillBaseURI: this.uri };++ // Owner-signed skills may opt out of the sandbox via sandboxPolicy: "trusted-main-thread"+ if (this.manifest.sandboxPolicy === 'trusted-main-thread') {+ const handler = this.handlers[toolName];+ if (!handler) {+ throw new Error(`Skill "${this.name}" has no handler for tool "${toolName}"`);+ }+ return handler(args, scoped);+ }++ if (!this.handlersSrc) {+ throw new Error(`Skill "${this.name}" has no handler source for tool "${toolName}"`);+ }+ return getHost().invoke(this.uri, toolName, args, this.handlersSrc, 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 isTrusted = manifest.sandboxPolicy === 'trusted-main-thread';++ const [instructions, toolsJSON, handlersData] = await Promise.all([+ this._fetchText(`${uri}SKILL.md`).catch(() => ''),+ this._fetchJSON(`${uri}tools.json`).catch(() => ({ tools: [] })),+ isTrusted+ ? this._fetchHandlers(`${uri}handlers.js`).catch(() => null)+ : this._fetchHandlersSrc(`${uri}handlers.js`).catch(() => null),+ ]);++ const skill = new Skill({+ uri,+ manifest,+ instructions,+ tools: toolsJSON.tools || [],+ handlers: isTrusted ? handlersData || {} : {},+ handlersSrc: isTrusted ? null : handlersData,+ });++ // 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) {+ // Used only for trusted-main-thread skills — direct import into main thread.+ try {+ const mod = await import(/* @vite-ignore */ url);+ return mod;+ } catch (e) {+ console.warn(`[skills] handlers load failed: ${url}`, e);+ return null;+ }+ }++ async _fetchHandlersSrc(url) {+ // Fetch handler source as text for sandboxed execution in the worker.+ const res = await this.fetchFn(url);+ if (!res.ok) throw new Error(`Fetch failed: ${url} (${res.status})`);+ return res.text();+ }++ _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/publish/src/skills/sandbox-host.js b/publish/src/skills/sandbox-host.jsnew file mode 100644index 000000000..cc6f11b70--- /dev/null+++ b/publish/src/skills/sandbox-host.js@@ -0,0 +1,239 @@+// Sandbox host — manages the shared Web Worker that executes skill handlers.+// One worker instance is shared across all skills in a session.++// ?raw imports the worker source as a plain string — no Vite worker plugin,+// no code-split chunk, compatible with both ES and UMD lib builds.+// The worker is created at runtime as a classic-script blob: URL.+import _workerSrc from './sandbox-worker.js?raw';++/** @type {Worker | null} */+let _worker = null;+let _workerBlobUrl = null;++/** @type {Map<string, Promise<void>>} skillURI → install promise */+const _installPromises = new Map();++/** @type {Map<string, { resolve: Function, reject: Function }>} */+const _installCallbacks = new Map();++/** @type {Map<number, { resolve: Function, reject: Function, mainCtx: object }>} */+const _pending = new Map();++/** @type {Map<string, any>} handleId → non-serializable object (AnimationClip, GLTF, …) */+const _handles = new Map();++let _handleCounter = 0;+let _invocationCounter = 0;++// --- Handle registry ---++function _storeHandle(obj) {+ if (obj == null) return null;+ const id = `@h:${++_handleCounter}`;+ _handles.set(id, obj);+ return id;+}++function _resolveHandle(val) {+ if (typeof val === 'string' && val.startsWith('@h:')) return _handles.get(val) ?? val;+ return val;+}++function _resolveArgs(args) {+ if (!Array.isArray(args)) return args;+ return args.map(_resolveHandle);+}++// --- Worker lifecycle ---++function _getWorker() {+ if (!_worker) {+ if (!_workerBlobUrl) {+ const blob = new Blob([_workerSrc], { type: 'text/javascript' });+ _workerBlobUrl = URL.createObjectURL(blob);+ }+ _worker = new Worker(_workerBlobUrl);+ _worker.onmessage = _onMessage;+ _worker.onerror = _onError;+ }+ return _worker;+}++function _onError(err) {+ console.error('[sandbox] worker crashed:', err);+ _worker = null;+ _installPromises.clear();+ _installCallbacks.clear();+ _handles.clear();+ for (const [, p] of _pending) p.reject(new Error('Sandbox worker crashed'));+ _pending.clear();+}++function _onMessage({ data }) {+ switch (data.type) {+ case 'install-ack': {+ const cb = _installCallbacks.get(data.skillURI);+ _installCallbacks.delete(data.skillURI);+ if (data.ok) {+ cb?.resolve();+ } else {+ _installPromises.delete(data.skillURI);+ cb?.reject(new Error(data.error || 'Install failed'));+ }+ break;+ }++ case 'request': {+ // Worker is requesting a ctx method call from the main thread+ const { invocationId, requestId, method, args } = data;+ const inv = _pending.get(invocationId);+ if (!inv) {+ _worker?.postMessage({+ type: 'response',+ requestId,+ error: 'No active invocation',+ });+ return;+ }+ _dispatchCtxRequest(method, args, inv.mainCtx).then(+ (result) =>+ _worker?.postMessage({ type: 'response', requestId, result: result ?? null }),+ (err) =>+ _worker?.postMessage({+ type: 'response',+ requestId,+ error: err.message || String(err),+ }),+ );+ break;+ }++ case 'invoke-result': {+ const { invocationId, result, error } = data;+ const inv = _pending.get(invocationId);+ if (!inv) return;+ _pending.delete(invocationId);+ if (error !== undefined) inv.reject(new Error(error));+ else inv.resolve(result);+ break;+ }+ }+}++// --- ctx dispatch ---++async function _dispatchCtxRequest(method, rawArgs, mainCtx) {+ const args = _resolveArgs(rawArgs);++ switch (method) {+ // viewer+ case 'viewer.play':+ return mainCtx.viewer?.play?.(args[0], args[1]);+ case 'viewer.stop':+ return mainCtx.viewer?.stop?.(args[0]);+ case 'viewer.setExpression':+ return mainCtx.viewer?.setExpression?.(args[0], args[1]);+ case 'viewer.lookAt':+ return mainCtx.viewer?.lookAt?.(args[0]);+ case 'viewer.moveTo':+ return mainCtx.viewer?.moveTo?.(args[0], args[1]);+ case 'viewer.playAnimationByHint':+ return mainCtx.viewer?.playAnimationByHint?.(args[0], args[1]);+ case 'viewer.playClipByName':+ return mainCtx.viewer?.playClipByName?.(args[0], args[1]);++ // memory+ case 'memory.read':+ return mainCtx.memory?.read?.(args[0]);+ case 'memory.write':+ return mainCtx.memory?.write?.(args[0], args[1]);+ case 'memory.note':+ return mainCtx.memory?.note?.(args[0], args[1]);+ case 'memory.recall':+ return mainCtx.memory?.recall?.(args[0]);++ // llm+ case 'llm.complete':+ return mainCtx.llm?.complete?.(args[0], args[1]);+ case 'llm.embed':+ return mainCtx.llm?.embed?.(args[0]);++ // asset loading — results stored as handles because they're non-serializable+ case 'loadClip': {+ const clip = await mainCtx.loadClip?.(args[0]);+ return _storeHandle(clip);+ }+ case 'loadGLB': {+ const gltf = await mainCtx.loadGLB?.(args[0]);+ return _storeHandle(gltf);+ }++ // speech+ case 'speak':+ return mainCtx.speak?.(args[0]);+ case 'listen':+ return mainCtx.listen?.(args[0]);++ // cross-skill call+ case 'call':+ return mainCtx.call?.(args[0], args[1]);++ default:+ throw new Error(`Unknown ctx method: ${method}`);+ }+}++// --- Public API ---++async function _ensureInstalled(skillURI, handlersSrc) {+ if (_installPromises.has(skillURI)) return _installPromises.get(skillURI);++ const promise = new Promise((resolve, reject) => {+ _installCallbacks.set(skillURI, { resolve, reject });+ });+ _installPromises.set(skillURI, promise);+ _getWorker().postMessage({ type: 'install', skillURI, handlersSrc });+ return promise;+}++async function _invoke(skillURI, toolName, args, handlersSrc, mainCtx) {+ await _ensureInstalled(skillURI, handlersSrc);++ const id = ++_invocationCounter;+ const worker = _getWorker();++ return new Promise((resolve, reject) => {+ _pending.set(id, { resolve, reject, mainCtx });+ worker.postMessage({+ type: 'invoke',+ invocationId: id,+ skillURI,+ toolName,+ args,+ skillBaseURI: mainCtx.skillBaseURI || skillURI,+ });+ });+}++function _terminate() {+ if (!_worker) return;+ _worker.terminate();+ _worker = null;+ if (_workerBlobUrl) {+ URL.revokeObjectURL(_workerBlobUrl);+ _workerBlobUrl = null;+ }+ _installPromises.clear();+ _installCallbacks.clear();+ _handles.clear();+ for (const [, p] of _pending) p.reject(new Error('Sandbox terminated'));+ _pending.clear();+}++/**+ * Returns the singleton sandbox host.+ * All skills in a session share one worker for efficient resource use.+ */+export function getHost() {+ return { invoke: _invoke, terminate: _terminate };+}diff --git a/publish/src/skills/sandbox-worker.js b/publish/src/skills/sandbox-worker.jsnew file mode 100644index 000000000..7cb125604--- /dev/null+++ b/publish/src/skills/sandbox-worker.js@@ -0,0 +1,168 @@+// Sandbox worker — executes skill handlers in an isolated Web Worker scope.+// No DOM, no window, no document. Only ctx.* and native worker APIs.++/** @type {Map<string, object>} skillURI → module exports */+const _skillHandlers = new Map();++/** @type {Map<number, { resolve: Function, reject: Function, timeoutId: number }>} */+const _pendingRequests = new Map();++/** @type {Map<string, Promise<void>>} skillURI → install promise (deduplication) */+const _installPromises = new Map();++/** @type {Map<string, { resolve: Function, reject: Function }>} */+const _installCallbacks = new Map();++let _requestId = 0;++self.onmessage = ({ data }) => {+ switch (data.type) {+ case 'install':+ _install(data);+ break;+ case 'invoke':+ _invoke(data);+ break;+ case 'response':+ _handleResponse(data);+ break;+ }+};++async function _install({ skillURI, handlersSrc }) {+ // Deduplicate concurrent install requests for the same skill+ if (_installPromises.has(skillURI)) return;++ const promise = new Promise((resolve, reject) => {+ _installCallbacks.set(skillURI, { resolve, reject });+ });+ _installPromises.set(skillURI, promise);++ let url;+ try {+ const blob = new Blob([handlersSrc], { type: 'text/javascript' });+ url = URL.createObjectURL(blob);+ // Dynamic import from blob URL — works in module workers+ const mod = await import(/* @vite-ignore */ url);+ _skillHandlers.set(skillURI, mod);+ _installCallbacks.get(skillURI)?.resolve();+ self.postMessage({ type: 'install-ack', skillURI, ok: true });+ } catch (err) {+ _installPromises.delete(skillURI);+ _installCallbacks.get(skillURI)?.reject(err);+ _installCallbacks.delete(skillURI);+ self.postMessage({ type: 'install-ack', skillURI, ok: false, error: err.message });+ } finally {+ if (url) URL.revokeObjectURL(url);+ }+}++function _makeCtx(invocationId, skillBaseURI) {+ // Each method sends a request to main thread and awaits a structured-cloneable response.+ // Non-serializable objects (AnimationClip, GLTF) are stored in the host's handle registry+ // and represented here as opaque "@h:N" strings.+ const proxy = (method, args) =>+ new Promise((resolve, reject) => {+ const id = ++_requestId;+ const timeoutId = setTimeout(() => {+ _pendingRequests.delete(id);+ reject(new Error(`ctx.${method} timed out after 30s`));+ }, 30_000);+ _pendingRequests.set(id, { resolve, reject, timeoutId });+ self.postMessage({ type: 'request', invocationId, requestId: id, method, args });+ });++ return {+ viewer: {+ play: (clip, opts) => proxy('viewer.play', [clip, opts]),+ stop: (clipName) => proxy('viewer.stop', [clipName]),+ setExpression: (preset, intensity) =>+ proxy('viewer.setExpression', [preset, intensity]),+ lookAt: (target) => proxy('viewer.lookAt', [target]),+ moveTo: (position, opts) => proxy('viewer.moveTo', [position, opts]),+ playAnimationByHint: (hint, opts) => proxy('viewer.playAnimationByHint', [hint, opts]),+ playClipByName: (name, opts) => proxy('viewer.playClipByName', [name, opts]),+ },+ llm: {+ complete: (prompt, opts) => proxy('llm.complete', [prompt, opts]),+ embed: (text) => proxy('llm.embed', [text]),+ },+ memory: {+ read: (key) => proxy('memory.read', [key]),+ write: (key, value) => proxy('memory.write', [key, value]),+ note: (type, data) => proxy('memory.note', [type, data]),+ recall: (query) => proxy('memory.recall', [query]),+ },+ // Asset loading — results are opaque handle strings; pass back to viewer.play etc.+ loadClip: (uri) => proxy('loadClip', [uri]),+ loadGLB: (uri) => proxy('loadGLB', [uri]),+ // fetch and loadJSON use native worker fetch — no proxy needed+ fetch: (uri, opts) => fetch(uri, opts),+ loadJSON: async (uri) => (await fetch(uri)).json(),+ call: (toolName, toolArgs) => proxy('call', [toolName, toolArgs]),+ speak: (text) => proxy('speak', [text]),+ listen: (opts) => proxy('listen', [opts]),+ skillBaseURI,+ };+}++async function _invoke({ invocationId, skillURI, toolName, args, skillBaseURI }) {+ // Wait for install to complete (handles the install→invoke race)+ const installPromise = _installPromises.get(skillURI);+ if (installPromise) {+ try {+ await installPromise;+ } catch (err) {+ self.postMessage({+ type: 'invoke-result',+ invocationId,+ error: `Install failed: ${err.message}`,+ });+ return;+ }+ }++ const mod = _skillHandlers.get(skillURI);+ if (!mod) {+ self.postMessage({+ type: 'invoke-result',+ invocationId,+ error: `Skill not installed: ${skillURI}`,+ });+ return;+ }++ const fn = mod[toolName];+ if (typeof fn !== 'function') {+ self.postMessage({+ type: 'invoke-result',+ invocationId,+ error: `No handler "${toolName}" in skill "${skillURI}"`,+ });+ return;+ }++ try {+ const ctx = _makeCtx(invocationId, skillBaseURI);+ const result = await fn(args, ctx);+ self.postMessage({ type: 'invoke-result', invocationId, result: result ?? null });+ } catch (err) {+ self.postMessage({+ type: 'invoke-result',+ invocationId,+ error: err.message || String(err),+ });+ }+}++function _handleResponse({ requestId, result, error }) {+ const pending = _pendingRequests.get(requestId);+ if (!pending) return;+ clearTimeout(pending.timeoutId);+ _pendingRequests.delete(requestId);+ if (error !== undefined) {+ pending.reject(new Error(error));+ } else {+ pending.resolve(result);+ }+}diff --git a/publish/src/solana/vanity/grinder-worker.js b/publish/src/solana/vanity/grinder-worker.jsnew file mode 100644index 000000000..69e1436fe--- /dev/null+++ b/publish/src/solana/vanity/grinder-worker.js@@ -0,0 +1,78 @@+/**+ * Vanity grinder Web Worker.+ *+ * Loops Keypair.generate() and reports matches + progress back to the host.+ * The host owns the matcher predicate (passed as serialized config); this+ * worker only decides "does the base58 address match?".+ *+ * Algorithm parity with nirholas/solana-wallet-toolkit+ * (typescript/src/lib/generator.ts).+ */++import { Keypair } from '@solana/web3.js';++const PROGRESS_INTERVAL = 5000;++let running = false;++self.onmessage = (e) => {+ const msg = e.data;+ if (msg?.type === 'start') {+ running = true;+ grind(msg.prefix || '', msg.suffix || '', !!msg.ignoreCase);+ } else if (msg?.type === 'stop') {+ running = false;+ }+};++/**+ * @param {string} prefix+ * @param {string} suffix+ * @param {boolean} ignoreCase+ */+async function grind(prefix, suffix, ignoreCase) {+ const wantPrefix = ignoreCase ? prefix.toLowerCase() : prefix;+ const wantSuffix = ignoreCase ? suffix.toLowerCase() : suffix;+ const pLen = prefix.length;+ const sLen = suffix.length;++ let attempts = 0;+ let intervalStart = performance.now();+ let intervalAttempts = 0;++ while (running) {+ const kp = Keypair.generate();+ const address = kp.publicKey.toBase58();+ attempts++;+ intervalAttempts++;++ const head = pLen+ ? (ignoreCase ? address.substring(0, pLen).toLowerCase() : address.substring(0, pLen))+ : '';+ const tail = sLen+ ? (ignoreCase ? address.slice(-sLen).toLowerCase() : address.slice(-sLen))+ : '';++ if ((!pLen || head === wantPrefix) && (!sLen || tail === wantSuffix)) {+ self.postMessage({+ type: 'match',+ publicKey: address,+ secretKey: kp.secretKey,+ attempts,+ }, [kp.secretKey.buffer]);+ running = false;+ return;+ }++ if (intervalAttempts >= PROGRESS_INTERVAL) {+ const now = performance.now();+ const elapsed = (now - intervalStart) / 1000;+ const rate = elapsed > 0 ? intervalAttempts / elapsed : 0;+ self.postMessage({ type: 'progress', attempts, rate });+ intervalStart = now;+ intervalAttempts = 0;+ // Yield to the event loop so 'stop' messages get processed.+ await new Promise((r) => setTimeout(r, 0));+ }+ }+}diff --git a/publish/src/solana/vanity/grinder.js b/publish/src/solana/vanity/grinder.jsnew file mode 100644index 000000000..5330a6f93--- /dev/null+++ b/publish/src/solana/vanity/grinder.js@@ -0,0 +1,141 @@+/**+ * Solana vanity address grinder — main-thread API.+ *+ * Spawns a pool of Web Workers (one per logical core, capped) that race+ * to find a Keypair whose Base58 public key matches the requested prefix+ * and/or suffix. First match wins; the rest are terminated.+ *+ * Usage:+ * const { publicKey, secretKey, attempts, durationMs } = await grindVanity({+ * prefix: 'AGNT',+ * onProgress: ({ attempts, rate, eta }) => updateUI(...),+ * signal,+ * });+ *+ * The returned `secretKey` is a Uint8Array(64) — Solana's standard+ * Ed25519 keypair format, compatible with `Keypair.fromSecretKey()`.+ *+ * Algorithm parity with nirholas/solana-wallet-toolkit. WASM backend+ * (~10× faster) is a future optimization — see TODO at bottom.+ */++import { validatePattern, estimateAttempts, formatTimeEstimate } from './validation.js';++const DEFAULT_MAX_WORKERS = 8;++/**+ * @typedef {object} GrindOptions+ * @property {string} [prefix] - Base58 prefix to match.+ * @property {string} [suffix] - Base58 suffix to match.+ * @property {boolean} [ignoreCase=false] - Case-insensitive match.+ * @property {number} [maxWorkers] - Cap on workers (defaults to hardwareConcurrency).+ * @property {AbortSignal} [signal] - Cancel the grind.+ * @property {(p: { attempts: number, rate: number, eta: string }) => void} [onProgress]+ */++/**+ * @typedef {object} GrindResult+ * @property {string} publicKey - Base58 address.+ * @property {Uint8Array} secretKey - 64-byte Ed25519 secret key.+ * @property {number} attempts - Total attempts across all workers.+ * @property {number} durationMs - Wall-clock duration.+ * @property {number} workers - Number of workers used.+ */++/**+ * Grind for a vanity Solana address.+ * @param {GrindOptions} opts+ * @returns {Promise<GrindResult>}+ */+export function grindVanity(opts = {}) {+ const { prefix = '', suffix = '', ignoreCase = false, signal, onProgress } = opts;++ if (!prefix && !suffix) {+ return Promise.reject(new Error('prefix or suffix is required'));+ }+ if (prefix) {+ const v = validatePattern(prefix);+ if (!v.valid) return Promise.reject(new Error(`invalid prefix: ${v.errors.join('; ')}`));+ }+ if (suffix) {+ const v = validatePattern(suffix);+ if (!v.valid) return Promise.reject(new Error(`invalid suffix: ${v.errors.join('; ')}`));+ }++ const cores = Math.max(1, Math.min(+ opts.maxWorkers || (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4,+ DEFAULT_MAX_WORKERS,+ ));+ const expected = estimateAttempts((prefix?.length || 0) + (suffix?.length || 0));+ const startedAt = performance.now();++ /** @type {Worker[]} */+ const workers = [];+ const ratesByWorker = new Array(cores).fill(0);+ const attemptsByWorker = new Array(cores).fill(0);++ const stopAll = () => {+ for (const w of workers) {+ try { w.postMessage({ type: 'stop' }); } catch {}+ try { w.terminate(); } catch {}+ }+ workers.length = 0;+ };++ return new Promise((resolve, reject) => {+ const onAbort = () => {+ stopAll();+ reject(new DOMException('vanity grind aborted', 'AbortError'));+ };+ if (signal) {+ if (signal.aborted) return onAbort();+ signal.addEventListener('abort', onAbort, { once: true });+ }++ for (let i = 0; i < cores; i++) {+ const w = new Worker(new URL('./grinder-worker.js', import.meta.url), { type: 'module' });+ workers.push(w);++ w.onmessage = (e) => {+ const msg = e.data;+ if (msg.type === 'match') {+ stopAll();+ if (signal) signal.removeEventListener('abort', onAbort);+ const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0) + msg.attempts;+ resolve({+ publicKey: msg.publicKey,+ secretKey: new Uint8Array(msg.secretKey),+ attempts: totalAttempts,+ durationMs: performance.now() - startedAt,+ workers: cores,+ });+ } else if (msg.type === 'progress') {+ attemptsByWorker[i] = msg.attempts;+ ratesByWorker[i] = msg.rate;+ if (onProgress) {+ const totalRate = ratesByWorker.reduce((a, b) => a + b, 0);+ const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0);+ onProgress({+ attempts: totalAttempts,+ rate: totalRate,+ eta: formatTimeEstimate(Math.max(0, expected - totalAttempts), totalRate),+ });+ }+ }+ };++ w.onerror = (err) => {+ stopAll();+ if (signal) signal.removeEventListener('abort', onAbort);+ reject(err.error || new Error(err.message || 'vanity worker crashed'));+ };++ w.postMessage({ type: 'start', prefix, suffix, ignoreCase });+ }+ });+}++// TODO(perf): drop in a WASM grinder backed by the toolkit's Rust crate+// (nirholas/solana-wallet-toolkit/rust). Expected ~10× over JS Keypair.generate().+// Public API of grindVanity() is intentionally backend-agnostic so the swap is+// transparent to callers.diff --git a/publish/src/solana/vanity/launch-with-vanity.js b/publish/src/solana/vanity/launch-with-vanity.jsnew file mode 100644index 000000000..fc9193b4e--- /dev/null+++ b/publish/src/solana/vanity/launch-with-vanity.js@@ -0,0 +1,73 @@+/**+ * Vanity-launch helper: grind a vanity mint address client-side, POST it to+ * /api/pump/launch-prep so the unsigned tx is built around the vanity pubkey,+ * then return the prep payload + the locally-held mint keypair for co-signing.+ *+ * The mint secret never leaves the browser.+ *+ * Usage:+ * const { prep, mintKeypair } = await launchWithVanity({+ * agentId, walletAddress, name, symbol, uri,+ * suffix: 'pump',+ * onProgress: ({ rate, eta }) => console.log(rate, eta),+ * });+ * // ...co-sign prep.tx_base64 with both `mintKeypair` and the user wallet,+ * // submit, then POST /api/pump/launch-confirm with the tx_signature.+ */++import { Keypair } from '@solana/web3.js';+import { grindVanity } from './grinder.js';++/**+ * @param {object} args+ * @param {string} args.agentId+ * @param {string} args.walletAddress+ * @param {string} args.name+ * @param {string} args.symbol+ * @param {string} args.uri+ * @param {'mainnet'|'devnet'} [args.network]+ * @param {number} [args.buybackBps]+ * @param {number} [args.solBuyIn]+ * @param {string} [args.prefix]+ * @param {string} [args.suffix]+ * @param {boolean} [args.ignoreCase]+ * @param {AbortSignal} [args.signal]+ * @param {(p: { attempts: number, rate: number, eta: string }) => void} [args.onProgress]+ * @param {typeof fetch} [args.fetchImpl]+ * @param {string} [args.endpoint='/api/pump/launch-prep']+ * @returns {Promise<{ prep: object, mintKeypair: Keypair }>}+ */+export async function launchWithVanity(args) {+ const { prefix, suffix, ignoreCase, signal, onProgress } = args;+ if (!prefix && !suffix) throw new Error('prefix or suffix required for vanity launch');++ const ground = await grindVanity({ prefix, suffix, ignoreCase, signal, onProgress });+ const mintKeypair = Keypair.fromSecretKey(ground.secretKey);++ const fetchImpl = args.fetchImpl || globalThis.fetch;+ const res = await fetchImpl(args.endpoint || '/api/pump/launch-prep', {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ agent_id: args.agentId,+ wallet_address: args.walletAddress,+ name: args.name,+ symbol: args.symbol,+ uri: args.uri,+ network: args.network ?? 'mainnet',+ buyback_bps: args.buybackBps ?? 0,+ sol_buy_in: args.solBuyIn ?? 0,+ mint_address: mintKeypair.publicKey.toBase58(),+ }),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(`launch-prep failed: ${res.status} ${body.error_description ?? body.error ?? ''}`);+ }+ const prep = await res.json();+ if (prep.mint !== mintKeypair.publicKey.toBase58()) {+ throw new Error('server returned a different mint than the vanity pubkey we sent');+ }+ return { prep, mintKeypair, vanity: { attempts: ground.attempts, durationMs: ground.durationMs, workers: ground.workers } };+}diff --git a/publish/src/solana/vanity/validation.js b/publish/src/solana/vanity/validation.jsnew file mode 100644index 000000000..23f74c707--- /dev/null+++ b/publish/src/solana/vanity/validation.js@@ -0,0 +1,78 @@+/**+ * Base58 validation for Solana vanity prefixes/suffixes.+ *+ * Algorithm ported from nirholas/solana-wallet-toolkit+ * (typescript/src/lib/validation.ts). The toolkit excludes the four+ * commonly-confused characters (0, O, I, l) per the Bitcoin/Solana+ * Base58 alphabet.+ */++export const BASE58_ALPHABET =+ '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';++const BASE58_CHARS = new Set(BASE58_ALPHABET);++const CONFUSED = {+ '0': '0 (zero) — use 1-9',+ O: 'O (uppercase o) — use other uppercase letters',+ I: 'I (uppercase i) — use other uppercase letters',+ l: 'l (lowercase L) — use other lowercase letters',+};++/** Hard ceiling regardless of paywall — past this, grinding is unrealistic in-browser. */+export const MAX_PATTERN_LENGTH = 6;++/** Length below which vanity is free; >= FREE_THRESHOLD requires the paid product. */+export const FREE_THRESHOLD = 5;++/**+ * Validate a vanity pattern (prefix or suffix).+ * @param {string} pattern+ * @returns {{ valid: boolean, errors: string[] }}+ */+export function validatePattern(pattern) {+ const errors = [];+ if (typeof pattern !== 'string' || pattern.length === 0) {+ return { valid: false, errors: ['pattern is empty'] };+ }+ if (pattern !== pattern.trim()) {+ errors.push('pattern has leading or trailing whitespace');+ }+ if (pattern.length > MAX_PATTERN_LENGTH) {+ errors.push(`length ${pattern.length} exceeds maximum of ${MAX_PATTERN_LENGTH}`);+ }+ for (let i = 0; i < pattern.length; i++) {+ const c = pattern[i];+ if (!BASE58_CHARS.has(c)) {+ const hint = CONFUSED[c];+ errors.push(`invalid character '${c}' at position ${i + 1}${hint ? ` — ${hint}` : ''}`);+ }+ }+ return { valid: errors.length === 0, errors };+}++/**+ * Estimate expected attempts to find a Base58 prefix of the given length.+ * @param {number} length+ * @returns {number}+ */+export function estimateAttempts(length) {+ return Math.pow(58, length);+}++/**+ * Format a duration estimate (seconds) as a human string.+ * @param {number} attempts expected attempts+ * @param {number} ratePerSecond combined rate across worker pool+ * @returns {string}+ */+export function formatTimeEstimate(attempts, ratePerSecond) {+ if (!ratePerSecond || ratePerSecond <= 0) return 'unknown';+ const seconds = attempts / ratePerSecond;+ if (seconds < 1) return 'less than a second';+ if (seconds < 60) return `~${Math.round(seconds)} seconds`;+ if (seconds < 3600) return `~${Math.round(seconds / 60)} minutes`;+ if (seconds < 86400) return `~${Math.round(seconds / 3600)} hours`;+ if (seconds < 31536000) return `~${Math.round(seconds / 86400)} days`;+ return `~${Math.round(seconds / 31536000)} years`;+}diff --git a/publish/src/stage-element.js b/publish/src/stage-element.jsnew file mode 100644index 000000000..69c6c9949--- /dev/null+++ b/publish/src/stage-element.js@@ -0,0 +1,298 @@+// <agent-stage> — shared scene host for multiple <agent-3d> children.+// See specs/STAGE_SPEC.md++import { Group, Vector3 } from 'three';+import { Viewer } from './viewer.js';++const FORMATIONS = ['row', 'circle', 'freeform'];++const STAGE_STYLE = `+ :host {+ display: block;+ position: relative;+ width: 100%;+ height: 480px;+ contain: layout style;+ }+ :host([hidden]) { display: none; }+ .stage-canvas {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ }+ .stage-canvas canvas { display: block; }+ ::slotted(agent-3d) {+ position: absolute;+ pointer-events: none;+ }+`;++class AgentStageElement extends HTMLElement {+ static get observedAttributes() {+ return ['formation'];+ }++ constructor() {+ super();+ this.attachShadow({ mode: 'open' });+ this._viewer = null;+ this._agents = [];+ this._initialized = false;+ }++ connectedCallback() {+ this._renderShell();+ this._initViewer();+ this._mo = new MutationObserver(() => this._repositionAll());+ this._mo.observe(this, { childList: true });+ }++ disconnectedCallback() {+ try {+ this._mo?.disconnect();+ } catch {}+ for (const a of [...this._agents]) this.unregisterAgent(a.element);+ try {+ this._viewer?.dispose?.();+ } catch {}+ this._viewer = null;+ this._initialized = false;+ }++ attributeChangedCallback(name) {+ if (name === 'formation') this._repositionAll();+ }++ get formation() {+ const f = this.getAttribute('formation') || 'row';+ return FORMATIONS.includes(f) ? f : 'row';+ }++ get viewer() {+ return this._viewer;+ }++ _renderShell() {+ const style = document.createElement('style');+ style.textContent = STAGE_STYLE;+ this.shadowRoot.appendChild(style);++ const box = document.createElement('div');+ box.className = 'stage-canvas';+ box.part = 'stage';+ this.shadowRoot.appendChild(box);+ this._canvasBox = box;++ const slot = document.createElement('slot');+ this.shadowRoot.appendChild(slot);+ }++ _initViewer() {+ if (this._initialized) return;+ this._viewer = new Viewer(this._canvasBox, { kiosk: true });+ // Default framing for a human-scale stage.+ this._viewer.defaultCamera.position.set(0, 1.55, 3.4);+ this._viewer.defaultCamera.lookAt(0, 1.2, 0);+ this._viewer.controls.target.set(0, 1.2, 0);+ this._viewer.controls.update();+ try {+ this._viewer.updateLights?.();+ } catch {}+ try {+ this._viewer.updateEnvironment?.();+ } catch {}+ this._viewer.invalidate();+ this._initialized = true;+ }++ // --- Called by <agent-3d> children that detect this parent stage ---++ registerAgent(element, { id, group, manifest }) {+ const finalId = this._uniqueId(id || manifest?.name || 'agent');+ const rec = { id: finalId, element, group, manifest };+ this._agents.push(rec);+ this._viewer?.scene.add(group);+ this._repositionAll();+ this.dispatchEvent(+ new CustomEvent('stage:agent-joined', {+ detail: { agentId: finalId, element, manifest },+ bubbles: true,+ composed: true,+ }),+ );+ return finalId;+ }++ unregisterAgent(element) {+ const i = this._agents.findIndex((a) => a.element === element);+ if (i < 0) return;+ const [rec] = this._agents.splice(i, 1);+ try {+ this._viewer?.scene.remove(rec.group);+ } catch {}+ disposeGroup(rec.group);+ this._repositionAll();+ this.dispatchEvent(+ new CustomEvent('stage:agent-left', {+ detail: { agentId: rec.id, element: rec.element },+ bubbles: true,+ composed: true,+ }),+ );+ }++ _uniqueId(base) {+ let id = base;+ let n = 1;+ const taken = new Set(this._agents.map((a) => a.id));+ while (taken.has(id)) id = `${base}-${n++}`;+ return id;+ }++ // --- Public API ---++ getAgents() {+ return this._agents.map(({ id, group, manifest, element }) => ({+ agentId: id,+ name: manifest?.name || id,+ position: [+ +group.position.x.toFixed(3),+ +group.position.y.toFixed(3),+ +group.position.z.toFixed(3),+ ],+ element,+ }));+ }++ broadcast(fromId, event) {+ const detail = { from: fromId, event };+ for (const a of this._agents) {+ if (a.id === fromId) continue;+ a.element.dispatchEvent(new CustomEvent('stage:message', { detail }));+ }+ this.dispatchEvent(+ new CustomEvent('stage:message', {+ detail,+ bubbles: true,+ composed: true,+ }),+ );+ }++ async routeMessage(fromId, toId, text) {+ const target = this._agents.find((a) => a.id === toId);+ if (!target) return { ok: false, error: `No agent "${toId}" on stage` };+ try {+ const reply = await target.element.say(`[from ${fromId}] ${text}`);+ return { ok: true, reply: reply?.text || '' };+ } catch (e) {+ return { ok: false, error: e?.message || String(e) };+ }+ }++ async addAgent(manifest) {+ const el = document.createElement('agent-3d');+ if (manifest && typeof manifest === 'object') {+ el._inlineManifest = manifest;+ }+ if (!el.hasAttribute('eager')) el.setAttribute('eager', '');+ this.appendChild(el);+ return el;+ }++ removeAgent(agentId) {+ const rec = this._agents.find((a) => a.id === agentId);+ if (rec) rec.element.remove();+ }++ // --- Formation / layout ---++ _repositionAll() {+ const n = this._agents.length;+ if (!n || !this._viewer) return;+ for (let i = 0; i < n; i++) {+ const { element, group, manifest } = this._agents[i];+ const slot = this._slotFor(i, n);+ group.position.copy(slot.world);+ group.lookAt(0, slot.world.y + 1.0, slot.world.z + 5.0);+ // Sub-rect for this child's chrome overlay+ element.style.position = 'absolute';+ element.style.left = slot.dom.left;+ element.style.top = slot.dom.top;+ element.style.width = slot.dom.width;+ element.style.height = slot.dom.height;+ element.style.pointerEvents = 'none';+ }+ this._viewer.invalidate();+ }++ _slotFor(i, n) {+ const f = this.formation;+ const w = 1 / Math.max(n, 1);+ if (f === 'circle') {+ const angle = (i / n) * Math.PI * 2;+ const r = Math.max(0.8, 0.4 * n);+ return {+ world: new Vector3(Math.sin(angle) * r, 0, -Math.cos(angle) * r + r * 0.5),+ dom: {+ left: `${i * w * 100}%`,+ top: '0',+ width: `${w * 100}%`,+ height: '100%',+ },+ };+ }+ if (f === 'freeform') {+ return {+ world: new Vector3(0, 0, 0),+ dom: { left: '0', top: '0', width: '100%', height: '100%' },+ };+ }+ // row+ const spacing = 1.1;+ const x = (i - (n - 1) / 2) * spacing;+ return {+ world: new Vector3(x, 0, 0),+ dom: {+ left: `${i * w * 100}%`,+ top: '0',+ width: `${w * 100}%`,+ height: '100%',+ },+ };+ }+}++function disposeGroup(group) {+ group.traverse((o) => {+ if (o.geometry) {+ try {+ o.geometry.dispose();+ } catch {}+ }+ if (o.material) {+ const mats = Array.isArray(o.material) ? o.material : [o.material];+ for (const m of mats) {+ for (const k of Object.keys(m)) {+ const v = m[k];+ if (v && v.isTexture) {+ try {+ v.dispose();+ } catch {}+ }+ }+ try {+ m.dispose();+ } catch {}+ }+ }+ });+ if (group.parent) group.parent.remove(group);+}++if (!customElements.get('agent-stage')) {+ customElements.define('agent-stage', AgentStageElement);+}++export { AgentStageElement };diff --git a/publish/src/validation-ui.js b/publish/src/validation-ui.jsnew file mode 100644index 000000000..ccee51f34--- /dev/null+++ b/publish/src/validation-ui.js@@ -0,0 +1,289 @@+/**+ * ValidationDashboard — UI controller for browsing and submitting validation records on-chain.+ *+ * Uses:+ * - getLatestValidation() to fetch past validation records+ * - recordValidation() to submit new reports+ * - hashReport() to compute client-side hash+ * - pinFile() for IPFS storage+ * - ethers for wallet connection+ */++import { ensureWallet } from './erc8004/agent-registry.js';+import {+ getLatestValidation,+ recordValidation,+ hashReport,+} from './erc8004/validation-recorder.js';++export class ValidationDashboard {+ constructor(root, els) {+ this.root = root;+ this.els = els;+ this.currentAgentId = null;+ this.currentChainId = null;+ this.currentReport = null;+ this.currentReportHash = null;+ this.signer = null;++ this.setupEventListeners();+ }++ setupEventListeners() {+ this.els.loadBtn.addEventListener('click', () => this.loadRecords());+ this.els.submitBtn.addEventListener('click', () => this.openModal());+ this.els.reportFile.addEventListener('change', (e) => this.handleFileSelect(e));+ this.els.submitReportBtn.addEventListener('click', () => this.submitReport());++ document.addEventListener('dragover', (e) => {+ if (this.els.submitModal.classList.contains('open')) {+ e.preventDefault();+ }+ });++ document.addEventListener('drop', (e) => {+ if (this.els.submitModal.classList.contains('open')) {+ e.preventDefault();+ const files = e.dataTransfer.files;+ if (files.length > 0) {+ this.els.reportFile.files = files;+ this.handleFileSelect({ target: { files } });+ }+ }+ });+ }++ showError(msg) {+ this.els.errorEl.textContent = msg;+ this.els.errorEl.style.display = 'block';+ }++ hideError() {+ this.els.errorEl.style.display = 'none';+ }++ showInfo(msg) {+ this.els.infoEl.textContent = msg;+ this.els.infoEl.style.display = 'block';+ }++ hideInfo() {+ this.els.infoEl.style.display = 'none';+ }++ showToast(msg, isError = false) {+ const toast = document.createElement('div');+ toast.className = `toast ${isError ? 'err' : ''}`;+ toast.textContent = msg;+ document.body.appendChild(toast);+ setTimeout(() => toast.remove(), 3000);+ }++ async loadRecords() {+ this.hideError();+ this.hideInfo();++ const agentId = this.els.agentInput.value.trim();+ const chainId = this.els.chainInput.value.trim();++ if (!agentId || !chainId) {+ this.showError('Please enter both Agent ID and Chain ID');+ return;+ }++ this.currentAgentId = Number(agentId);+ this.currentChainId = Number(chainId);++ try {+ this.els.loadBtn.disabled = true;+ this.showInfo('Loading validation records...');++ const result = await getLatestValidation({+ agentId: this.currentAgentId,+ runner: null,+ chainId: this.currentChainId,+ });++ this.hideInfo();+ this.renderRecords(result);+ } catch (err) {+ this.showError(`Failed to load records: ${err.message}`);+ this.els.recordsContainer.innerHTML = '';+ this.els.emptyState.style.display = 'block';+ } finally {+ this.els.loadBtn.disabled = false;+ }+ }++ renderRecords(records) {+ if (!records || (Array.isArray(records) && records.length === 0)) {+ this.els.recordsContainer.innerHTML = '';+ this.els.emptyState.style.display = 'block';+ return;+ }++ this.els.emptyState.style.display = 'none';+ const recordArray = Array.isArray(records) ? records : [records];++ this.els.recordsContainer.innerHTML = recordArray.map((r) => this.renderRecord(r)).join('');+ }++ renderRecord(record) {+ const verdict = record.verdict || (record.passed ? 'pass' : 'fail');+ const timestamp = record.timestamp+ ? new Date(Number(record.timestamp) * 1000).toLocaleString()+ : 'Unknown';++ const reportUri = record.reportUri || record.proofURI || '';+ const reportHash = record.reportHash || record.proofHash || '';+ const validator = record.validator || 'Unknown';++ return `+ <div class="record">+ <div class="record-header">+ <div class="record-title">+ <h3>${this.escapeHtml(record.kind || 'glb-schema')} Validation</h3>+ <span class="badge ${verdict}">${verdict.toUpperCase()}</span>+ </div>+ </div>+ <div class="record-meta">+ <div class="record-meta-item">+ <div class="record-meta-label">Validator</div>+ <div class="record-meta-value">${this.escapeHtml(validator.substring(0, 10))}…${this.escapeHtml(validator.substring(validator.length - 8))}</div>+ </div>+ <div class="record-meta-item">+ <div class="record-meta-label">Timestamp</div>+ <div class="record-meta-value">${timestamp}</div>+ </div>+ </div>+ <div class="record-meta">+ <div class="record-meta-item" style="flex: 1">+ <div class="record-meta-label">Report Hash</div>+ <div class="record-meta-value">${this.escapeHtml(reportHash.substring(0, 20))}…</div>+ </div>+ </div>+ <div class="record-actions">+ ${reportUri ? `<a href="${this.resolveIPFS(reportUri)}" target="_blank" class="btn">View Report ↗</a>` : ''}+ <button class="btn sec" onclick="navigator.clipboard.writeText('${this.escapeHtml(reportHash)}').then(() => alert('Copied!'))">Copy Hash</button>+ </div>+ </div>+ `;+ }++ openModal() {+ this.els.submitModal.classList.add('open');+ this.currentReport = null;+ this.currentReportHash = null;+ this.els.previewSection.style.display = 'none';+ this.els.hashSection.style.display = 'none';+ this.els.reportFile.value = '';+ this.els.fileStatus.textContent = '';+ this.els.submitReportBtn.disabled = true;+ }++ closeModal() {+ this.els.submitModal.classList.remove('open');+ }++ async handleFileSelect(e) {+ const file = e.target.files?.[0];+ if (!file) {+ this.els.fileStatus.textContent = '';+ this.els.previewSection.style.display = 'none';+ this.els.hashSection.style.display = 'none';+ this.els.submitReportBtn.disabled = true;+ return;+ }++ try {+ const text = await file.text();+ const report = JSON.parse(text);++ this.currentReport = report;+ this.currentReportHash = hashReport(report);++ this.els.fileStatus.textContent = `✓ ${file.name} (${(file.size / 1024).toFixed(1)} KB)`;+ this.els.fileStatus.style.color = '#76d776';++ this.els.previewJson.textContent = JSON.stringify(report, null, 2);+ this.els.previewSection.style.display = 'block';+ this.els.previewError.style.display = 'none';++ this.els.reportHash.value = this.currentReportHash;+ this.els.hashSection.style.display = 'block';++ this.els.submitReportBtn.disabled = false;+ } catch (err) {+ this.els.fileStatus.textContent = '✗ Invalid JSON';+ this.els.fileStatus.style.color = '#ffb3b3';+ this.els.previewError.textContent = err.message;+ this.els.previewError.style.display = 'block';+ this.els.submitReportBtn.disabled = true;+ this.currentReport = null;+ this.currentReportHash = null;+ }+ }++ async submitReport() {+ if (!this.currentReport || !this.currentReportHash) {+ this.showToast('No valid report selected', true);+ return;+ }++ if (!this.currentAgentId || !this.currentChainId) {+ this.showToast('Please load records first to set agent ID and chain', true);+ return;+ }++ try {+ this.els.submitReportBtn.disabled = true;+ this.showToast('Connecting wallet...');++ const wallet = await ensureWallet();+ const signer = wallet.signer;++ this.showToast('Submitting validation record on-chain...');++ const result = await recordValidation({+ agentId: this.currentAgentId,+ report: this.currentReport,+ signer,+ chainId: this.currentChainId,+ apiToken: import.meta.env.VITE_IPFS_API_TOKEN,+ pin: true,+ });++ this.showToast(+ `✓ Validation submitted! TX: ${result.txHash.substring(0, 10)}...`,+ false,+ );++ this.closeModal();++ await new Promise((r) => setTimeout(r, 2000));+ await this.loadRecords();+ } catch (err) {+ this.showToast(`Error: ${err.message}`, true);+ this.els.submitReportBtn.disabled = false;+ }+ }++ resolveIPFS(uri) {+ if (uri?.startsWith('ipfs://')) {+ const cid = uri.slice(7);+ return `https://dweb.link/ipfs/${cid}`;+ }+ return uri;+ }++ escapeHtml(str) {+ const map = {+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+ };+ return str.replace(/[&<>"']/g, (m) => map[m]);+ }+}diff --git a/publish/src/validator.js b/publish/src/validator.jsnew file mode 100644index 000000000..03920e2a3--- /dev/null+++ b/publish/src/validator.js@@ -0,0 +1,216 @@+import { LoaderUtils } from 'three';+import { validateBytes } from 'gltf-validator';++import { ValidatorReport } from './components/validator-report';++const SEVERITY_MAP = ['Errors', 'Warnings', 'Infos', 'Hints'];++export class Validator {+ /**+ * @param {Element} el+ */+ constructor(el) {+ this.el = el;+ this.report = null;+ }++ /**+ * Runs validation against the given file URL and extra resources.+ * @param {string} rootFile+ * @param {string} rootPath+ * @param {Map<string, File>} assetMap+ * @param {Object} response+ * @return {Promise}+ */+ validate(rootFile, rootPath, assetMap, response) {+ // Use Three.js Cache to avoid re-downloading the model.+ // Cache.enabled is set to true in viewer.js.+ const fetchBuffer =+ window.THREE && window.THREE.Cache && window.THREE.Cache.get(rootFile)+ ? Promise.resolve(window.THREE.Cache.get(rootFile)).then((data) => {+ if (data instanceof ArrayBuffer) return data;+ // Cache may hold string for .gltf; convert+ if (typeof data === 'string') return new TextEncoder().encode(data).buffer;+ return fetch(rootFile).then((r) => r.arrayBuffer());+ })+ : fetch(rootFile).then((r) => r.arrayBuffer());++ return fetchBuffer+ .then((buffer) =>+ validateBytes(new Uint8Array(buffer), {+ externalResourceFunction: (uri) =>+ this.resolveExternalResource(uri, rootFile, rootPath, assetMap),+ }),+ )+ .then((report) => this.setReport(report, response))+ .catch((e) => this.setReportException(e));+ }++ /**+ * Loads a resource (either locally or from the network) and returns it.+ * @param {string} uri+ * @param {string} rootFile+ * @param {string} rootPath+ * @param {Map<string, File>} assetMap+ * @return {Promise<Uint8Array>}+ */+ resolveExternalResource(uri, rootFile, rootPath, assetMap) {+ const baseURL = LoaderUtils.extractUrlBase(rootFile);+ const normalizedURL =+ rootPath ++ decodeURI(uri) // validator applies URI encoding.+ .replace(baseURL, '')+ .replace(/^(\.?\/)/, '');++ let objectURL;++ if (assetMap.has(normalizedURL)) {+ const object = assetMap.get(normalizedURL);+ objectURL = URL.createObjectURL(object);+ }++ return fetch(objectURL || baseURL + uri)+ .then((response) => response.arrayBuffer())+ .then((buffer) => {+ if (objectURL) URL.revokeObjectURL(objectURL);+ return new Uint8Array(buffer);+ });+ }++ /**+ * @param {GLTFValidator.Report} report+ * @param {Object} response+ */+ setReport(report, response) {+ report.generator = (report && report.info && report.info.generator) || '';+ report.issues.maxSeverity = -1;+ SEVERITY_MAP.forEach((severity, index) => {+ if (report.issues[`num${severity}`] > 0 && report.issues.maxSeverity === -1) {+ report.issues.maxSeverity = index;+ }+ });+ report.errors = report.issues.messages.filter((msg) => msg.severity === 0);+ report.warnings = report.issues.messages.filter((msg) => msg.severity === 1);+ report.infos = report.issues.messages.filter((msg) => msg.severity === 2);+ report.hints = report.issues.messages.filter((msg) => msg.severity === 3);+ groupMessages(report);+ this.report = report;++ this.setResponse(response);++ function groupMessages(report) {+ const CODES = {+ ACCESSOR_NON_UNIT: {+ message: '{count} accessor elements not of unit length: 0. [AGGREGATED]',+ pointerCounts: {},+ },+ ACCESSOR_ANIMATION_INPUT_NON_INCREASING: {+ message:+ '{count} animation input accessor elements not in ascending order. [AGGREGATED]',+ pointerCounts: {},+ },+ };++ report.errors.forEach((message) => {+ if (!CODES[message.code]) return;+ if (!CODES[message.code].pointerCounts[message.pointer]) {+ CODES[message.code].pointerCounts[message.pointer] = 0;+ }+ CODES[message.code].pointerCounts[message.pointer]++;+ });+ report.errors = report.errors.filter((message) => {+ if (!CODES[message.code]) return true;+ if (!CODES[message.code].pointerCounts[message.pointer]) return true;+ return CODES[message.code].pointerCounts[message.pointer] < 2;+ });+ Object.keys(CODES).forEach((code) => {+ Object.keys(CODES[code].pointerCounts).forEach((pointer) => {+ const count = CODES[code].pointerCounts[pointer];+ if (count < 2) return;+ report.errors.push({+ code: code,+ pointer: pointer,+ message: CODES[code].message.replace('{count}', count),+ });+ });+ });+ }+ }++ /**+ * @param {Object} response+ */+ setResponse(response) {+ const json = response && response.parser && response.parser.json;++ if (!json) return;++ if (json.asset && json.asset.extras) {+ const extras = json.asset.extras;+ this.report.info.extras = {};+ if (extras.author) {+ this.report.info.extras.author = linkify(escapeHTML(extras.author));+ }+ if (extras.license) {+ this.report.info.extras.license = linkify(escapeHTML(extras.license));+ }+ if (extras.source) {+ this.report.info.extras.source = linkify(escapeHTML(extras.source));+ }+ if (extras.title) {+ this.report.info.extras.title = escapeHTML(extras.title);+ }+ }+ }++ /**+ * @param {Error} e+ */+ setReportException(e) {+ this.report = null;+ }++ showLightbox() {+ if (!this.report) return;+ const tab = window.open('', '_blank');+ const reportJSON = _buildDownloadHref(this.report);+ tab.document.body.innerHTML = `+ <!DOCTYPE html>+ <title>glTF 2.0 validation report</title>+ <link href="https://fonts.googleapis.com/css?family=Raleway:300,400" rel="stylesheet">+ <link rel="stylesheet" href="${location.protocol}//${location.host}/style.css">+ <style>+ body { overflow-y: auto; }+ html, body { background: #FFFFFF; }+ </style>+ ${ValidatorReport({ ...this.report, location, reportJSON })}`;+ }+}++function _buildDownloadHref(report) {+ try {+ const { errors, warnings, infos, hints, issues, info, generator } = report;+ const payload = { generator, info, issues, errors, warnings, infos, hints };+ const json = JSON.stringify(payload, null, 2);+ return 'data:application/json;charset=utf-8,' + encodeURIComponent(json);+ } catch {+ return '';+ }+}++function escapeHTML(unsafe) {+ return unsafe+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++function linkify(text) {+ const urlPattern = /\b(?:https?):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;+ const emailAddressPattern = /(([a-zA-Z0-9_\-\.]+)@[a-zA-Z_]+?(?:\.[a-zA-Z]{2,6}))+/gim;+ return text+ .replace(urlPattern, '<a target="_blank" href="$&">$&</a>')+ .replace(emailAddressPattern, '<a target="_blank" href="mailto:$1">$1</a>');+}diff --git a/publish/src/viewer.js b/publish/src/viewer.jsnew file mode 100644index 000000000..447df4990--- /dev/null+++ b/publish/src/viewer.js@@ -0,0 +1,1536 @@+import {+ AxesHelper,+ Box3,+ Cache,+ Color,+ GridHelper,+ LoaderUtils,+ PMREMGenerator,+ PerspectiveCamera,+ PointsMaterial,+ Scene,+ SkeletonHelper,+ Vector3,+ WebGLRenderer,+ LinearToneMapping,+ ACESFilmicToneMapping,+} from 'three';+import Stats from 'three/addons/libs/stats.module.js';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++import { GUI } from 'dat.gui';++import { environments } from './environments.js';+import { createModelInfo } from './model-info.js';+import { canUseQuickLook, openQuickLook } from './ar/quick-look.js';+import { canUseSceneViewer, openSceneViewer } from './ar/scene-viewer.js';+import { WebXRSession } from './ar/webxr.js';+import { buildAnnotations, renderAnnotationCanvas } from './annotations.js';+import {+ DEFAULT_CAMERA,+ Preset,+ MANAGER,+ getDecoders,+ traverseMaterials,+} from './viewer/internal.js';+import { addLights, removeLights } from './viewer/lights.js';+import { getCubeMapTexture } from './viewer/environment.js';+import { takeScreenshot } from './viewer/screenshot.js';+import { setClips, playAllClips } from './viewer/animation.js';+import { AnimationManager } from './animation-manager.js';++Cache.enabled = true;++export class Viewer {+ constructor(el, options) {+ this.el = el;+ this.options = options;++ this.lights = [];+ this.content = null;+ this.mixer = null;+ this.clips = [];+ this.gui = null;++ // External animation system (Mixamo-style)+ this.animationManager = new AnimationManager();+ this._animPanelEl = null;++ this.state = {+ environment:+ options.preset === Preset.ASSET_GENERATOR+ ? environments.find((e) => e.id === 'footprint-court').name+ : environments[1].name,+ background: false,+ playbackSpeed: 1.0,+ actionStates: {},+ camera: DEFAULT_CAMERA,+ wireframe: false,+ skeleton: false,+ grid: false,+ autoRotate: false,++ // Lights+ punctualLights: true,+ exposure: 0.0,+ toneMapping: LinearToneMapping,+ ambientIntensity: 0.3,+ ambientColor: '#FFFFFF',+ directIntensity: 0.8 * Math.PI, // TODO(#116)+ directColor: '#FFFFFF',+ bgColor: '#000000',+ transparentBg: false,++ pointSize: 1.0,++ // Info overlay+ showInfo: true,+ showLabels: false,++ // Avatar follow mode+ followMode: 'mouse',+ };++ this.prevTime = 0;++ this.stats = new Stats();+ this.stats.dom.height = '48px';+ [].forEach.call(this.stats.dom.children, (child) => (child.style.display = ''));++ this.backgroundColor = new Color(this.state.bgColor);++ this.scene = new Scene();+ this.scene.background = this.backgroundColor;++ const fov = options.preset === Preset.ASSET_GENERATOR ? (0.8 * 180) / Math.PI : 60;+ const aspect = el.clientHeight > 0 ? el.clientWidth / el.clientHeight : 1;+ this.defaultCamera = new PerspectiveCamera(fov, aspect, 0.01, 1000);+ this.activeCamera = this.defaultCamera;+ this.scene.add(this.defaultCamera);++ this.renderer = window.renderer = new WebGLRenderer({ antialias: true, alpha: true });+ this.renderer.setClearColor(0x000000, 1);+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));+ this.renderer.setSize(el.clientWidth, el.clientHeight);++ this.pmremGenerator = new PMREMGenerator(this.renderer);+ this.pmremGenerator.compileEquirectangularShader();++ this.neutralEnvironment = this.pmremGenerator.fromScene(new RoomEnvironment()).texture;++ this.controls = new OrbitControls(this.defaultCamera, this.renderer.domElement);+ this.controls.screenSpacePanning = true;+ this._onControlsChange = () => this.invalidate();+ this.controls.addEventListener('change', this._onControlsChange);++ this.el.appendChild(this.renderer.domElement);++ this.cameraCtrl = null;+ this.cameraFolder = null;+ this.animFolder = null;+ this.animCtrls = [];+ this.morphFolder = null;+ this.morphCtrls = [];+ this.skeletonHelpers = [];+ this.gridHelper = null;+ this.axesHelper = null;+ this.modelInfo = null;+ this.annotationEls = [];+ this._tempVec = new Vector3();++ this.addAxesHelper();+ this.addGUI();+ if (options.kiosk) this.gui.close();++ this.animate = this.animate.bind(this);+ this._rafId = null;+ this._visible = true;+ this._tabVisible = !document.hidden;+ this._disposed = false;+ this._loadedEnvironment = null;+ this._guiWrap = null;+ this._needsRender = true;+ this._animating = false;++ this._onVisibilityChange = () => {+ const wasHidden = !this._tabVisible;+ this._tabVisible = !document.hidden;+ if (wasHidden && this._tabVisible) this._needsRender = true;+ this._updateRenderLoop();+ };+ document.addEventListener('visibilitychange', this._onVisibilityChange);++ if (typeof IntersectionObserver !== 'undefined') {+ this._intersectionObserver = new IntersectionObserver(+ (entries) => {+ const wasHidden = !this._visible;+ this._visible = entries[entries.length - 1].isIntersecting;+ if (wasHidden && this._visible) this._needsRender = true;+ this._updateRenderLoop();+ },+ { threshold: 0 },+ );+ this._intersectionObserver.observe(this.el);+ }++ this._onResize = this.resize.bind(this);+ this._onKeyDown = (e) => {+ if (this.isInputFocused()) return;+ if (e.key === 'p' || e.key === 'P') {+ this.takeScreenshot();+ } else if (e.code === 'Space') {+ e.preventDefault();+ this.toggleAnimationPlayback();+ } else if (e.key === 'f' || e.key === 'F') {+ this.frameContent();+ }+ };++ this._onDblClick = () => this.frameContent({ animate: true });++ this._updateRenderLoop();+ window.addEventListener('resize', this._onResize, false);+ window.addEventListener('keydown', this._onKeyDown);+ this.renderer.domElement.addEventListener('dblclick', this._onDblClick);+ }++ invalidate() {+ if (this._disposed) return;+ this._needsRender = true;+ this._updateRenderLoop();+ }++ // Per-agent scene preferences (background, environment, exposure, etc.)+ // persisted to localStorage. Call attachScenePrefs(agentId) once per+ // session — it restores the saved values into state and starts auto-saving+ // future tweaks.+ attachScenePrefs(agentId) {+ if (!agentId || typeof window === 'undefined') return;+ this._prefsKey = `3dagent:scene:${agentId}`;++ try {+ const raw = localStorage.getItem(this._prefsKey);+ if (raw) {+ const saved = JSON.parse(raw);+ const KEYS = [+ 'background',+ 'transparentBg',+ 'bgColor',+ 'autoRotate',+ 'exposure',+ 'environment',+ ];+ let touched = false;+ for (const key of KEYS) {+ if (saved[key] !== undefined && saved[key] !== this.state[key]) {+ this.state[key] = saved[key];+ touched = true;+ }+ }+ if (touched) {+ this.backgroundColor.set(this.state.bgColor);+ this.updateLights();+ this.updateEnvironment();+ this.updateDisplay();+ this.updateBackground();+ this.updateGUI?.();+ }+ }+ } catch {+ /* ignore corrupt prefs */+ }++ const save = () => {+ if (!this._prefsKey) return;+ try {+ const snapshot = {+ background: this.state.background,+ transparentBg: this.state.transparentBg,+ bgColor: this.state.bgColor,+ autoRotate: this.state.autoRotate,+ exposure: this.state.exposure,+ environment: this.state.environment,+ };+ localStorage.setItem(this._prefsKey, JSON.stringify(snapshot));+ } catch {+ /* quota or disabled storage */+ }+ };+ // Debounce to avoid hammering localStorage while users drag a slider.+ let timer = null;+ this._scenePrefsSave = () => {+ if (timer) clearTimeout(timer);+ timer = setTimeout(save, 250);+ };+ }++ // Public hook — controllers (dat.gui, drawer UI) call this after a state+ // change so we persist the latest value.+ notifyScenePrefChange() {+ if (this._scenePrefsSave) this._scenePrefsSave();+ }++ // Spacebar handler: pause/resume the active animation, or play the first+ // available one if nothing is currently selected.+ toggleAnimationPlayback() {+ const a = this.animationManager;+ if (!a) return;+ if (a.currentAction) {+ a.currentAction.paused = !a.currentAction.paused;+ this.invalidate();+ this._recomputeAnimating();+ this._updateRenderLoop();+ return;+ }+ const defs = a.getAnimationDefs?.() || [];+ const first = defs.find((d) => a.isLoaded?.(d.name));+ if (first) {+ a.play(first.name);+ this.invalidate();+ this._recomputeAnimating();+ this._updateRenderLoop();+ }+ }++ // Frame the loaded model with a flattering 3/4 angle. Optionally animates+ // the camera over a short duration ("F" key snaps; double-click animates).+ frameContent({ animate = false, durationMs = 600 } = {}) {+ if (!this.content || !this.defaultCamera || !this.controls) return;+ const box = new Box3().setFromObject(this.content);+ const bbSize = box.getSize(new Vector3());+ const size = bbSize.length();+ if (!isFinite(size) || size === 0) return;+ const bbCenter = box.getCenter(new Vector3());++ const vFovRad = this.defaultCamera.fov * (Math.PI / 180);+ const aspect = Math.max(this.defaultCamera.aspect, 0.01);+ const hFovRad = 2 * Math.atan(Math.tan(vFovRad / 2) * aspect);+ const distV = (bbSize.y / 2 * 1.15) / Math.tan(vFovRad / 2);+ const distH = (bbSize.x / 2 * 1.15) / Math.tan(hFovRad / 2);+ const dist = Math.max(distV, distH);++ const focusY = bbCenter.y + bbSize.y * 0.1;+ const target = new Vector3(bbCenter.x, focusY, bbCenter.z);+ const pos = new Vector3(bbCenter.x + dist * 0.12, focusY, bbCenter.z + dist);++ const bias = this._panelBiasY(dist);+ target.y -= bias;+ pos.y -= bias;++ if (animate) {+ this._tweenCamera(pos, target, durationMs);+ } else {+ this.defaultCamera.position.copy(pos);+ this.controls.target.copy(target);+ this.controls.update();+ this.invalidate();+ }+ }++ /** Returns the Y world-space shift needed to keep the model above the animation panel. */+ _panelBiasY(dist) {+ if (!this._animPanelEl) return 0;+ const panelH = this._animPanelEl.offsetHeight;+ const bottom = parseFloat(getComputedStyle(this._animPanelEl).bottom) || 0;+ const canvasH = this.renderer.domElement.clientHeight;+ if (!canvasH) return 0;+ const frac = (panelH + bottom) / canvasH;+ return frac * Math.tan((this.defaultCamera.fov / 2) * (Math.PI / 180)) * dist;+ }++ // Smooth ease-out camera tween. Both position and OrbitControls.target+ // are interpolated together so the framing stays correct mid-flight.+ _tweenCamera(toPos, toTarget, durationMs = 600) {+ if (this._cameraTweenRaf) cancelAnimationFrame(this._cameraTweenRaf);+ const fromPos = this.defaultCamera.position.clone();+ const fromTarget = this.controls.target.clone();+ const start = performance.now();+ const ease = (t) => 1 - Math.pow(1 - t, 3); // cubic ease-out+ const step = (now) => {+ const t = Math.min(1, (now - start) / durationMs);+ const k = ease(t);+ this.defaultCamera.position.lerpVectors(fromPos, toPos, k);+ this.controls.target.lerpVectors(fromTarget, toTarget, k);+ this.controls.update();+ this.invalidate();+ if (t < 1 && !this._disposed) {+ this._cameraTweenRaf = requestAnimationFrame(step);+ } else {+ this._cameraTweenRaf = null;+ }+ };+ this._cameraTweenRaf = requestAnimationFrame(step);+ }++ _recomputeAnimating() {+ let animating = false;+ if (this.state && this.state.autoRotate) animating = true;+ if (!animating && this.mixer && this.state) {+ for (const key in this.state.actionStates) {+ if (this.state.actionStates[key]) {+ animating = true;+ break;+ }+ }+ }+ // External animation manager also drives the render loop+ if (!animating && this.animationManager.currentAction) {+ animating = true;+ }+ this._animating = animating;+ }++ _updateRenderLoop() {+ if (this._disposed) return;+ const canRun = this._visible && this._tabVisible;+ const shouldRun = canRun && (this._needsRender || this._animating);+ if (shouldRun && this._rafId === null) {+ this.prevTime = performance.now();+ this._rafId = requestAnimationFrame(this.animate);+ } else if (!canRun && this._rafId !== null) {+ cancelAnimationFrame(this._rafId);+ this._rafId = null;+ }+ }++ animate(time) {+ const dt = (time - this.prevTime) / 1000;+ this.prevTime = time;++ this._recomputeAnimating();++ this.controls.update();+ this.stats.update();+ if (this.mixer) this.mixer.update(dt);+ this.animationManager.update(dt);++ // Extension point for the AgentAvatar empathy tick and any other per-frame hooks+ if (this._afterAnimateHooks) {+ for (let i = 0; i < this._afterAnimateHooks.length; i++) {+ this._afterAnimateHooks[i](dt);+ }+ }++ this.render();+ this._needsRender = false;++ if (this._animating && this._visible && this._tabVisible && !this._disposed) {+ this._rafId = requestAnimationFrame(this.animate);+ } else {+ this._rafId = null;+ }+ }++ isInputFocused() {+ const el = document.activeElement;+ return el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable);+ }++ render() {+ this.renderer.render(this.scene, this.activeCamera);+ if (this.state.grid) {+ this.axesCamera.position.copy(this.defaultCamera.position);+ this.axesCamera.lookAt(this.axesScene.position);+ this.axesRenderer.render(this.axesScene, this.axesCamera);+ }+ this.projectAnnotations();+ }++ takeScreenshot() {+ takeScreenshot(this);+ }++ /**+ * Update the AR button visibility and target URLs after a model loads.+ * @param {string|null} glbUrl — absolute or relative URL to the GLB (for Android/WebXR)+ * @param {string|null} usdzUrl — absolute or relative URL to a USDZ (for iOS Quick Look)+ */+ async setARTarget(glbUrl, usdzUrl = null) {+ this._arGlbUrl = glbUrl;+ this._arUsdzUrl = usdzUrl;++ if (!this._arBtn) return;++ const hasGlb = !!glbUrl;+ const hasUsdz = !!usdzUrl;++ const iosOk = hasUsdz && canUseQuickLook();+ const androidOk = hasGlb && canUseSceneViewer();+ const webxrOk = hasGlb && (await WebXRSession.isSupported());++ this._arBtn.hidden = !(iosOk || androidOk || webxrOk);+ }++ async _launchAR() {+ if (canUseQuickLook() && this._arUsdzUrl) {+ openQuickLook(this._arUsdzUrl);+ } else if (canUseSceneViewer() && this._arGlbUrl) {+ openSceneViewer(this._arGlbUrl);+ } else if (this._arGlbUrl) {+ // Desktop WebXR+ if (this._xrSession) {+ await this._xrSession.end();+ this._xrSession = null;+ this._arBtn.classList.remove('ar-btn--active');+ return;+ }+ this._xrSession = new WebXRSession(this, {+ onEnd: () => {+ this._xrSession = null;+ this._arBtn.classList.remove('ar-btn--active');+ },+ });+ await this._xrSession.start();+ this._arBtn.classList.add('ar-btn--active');+ }+ }++ resize() {+ const { clientHeight, clientWidth } = this.el;+ if (clientWidth === 0 || clientHeight === 0) return;++ this.defaultCamera.aspect = clientWidth / clientHeight;+ this.defaultCamera.updateProjectionMatrix();+ this.renderer.setSize(clientWidth, clientHeight);++ this.axesCamera.aspect = this.axesDiv.clientWidth / this.axesDiv.clientHeight;+ this.axesCamera.updateProjectionMatrix();+ this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight);++ this.invalidate();+ }++ load(url, rootPath, assetMap) {+ const baseURL = LoaderUtils.extractUrlBase(url);++ // Load.+ return new Promise((resolve, reject) => {+ // Intercept and override relative URLs.+ MANAGER.setURLModifier((url, path) => {+ // URIs in a glTF file may be escaped, or not. Assume that assetMap is+ // from an un-escaped source, and decode all URIs before lookups.+ // See: https://github.com/nirholas/three.ws/issues/146+ const normalizedURL =+ rootPath ++ decodeURI(url)+ .replace(baseURL, '')+ .replace(/^(\.?\/)/, '');++ if (assetMap.has(normalizedURL)) {+ const blob = assetMap.get(normalizedURL);+ const blobURL = URL.createObjectURL(blob);+ blobURLs.push(blobURL);+ return blobURL;+ }++ return (path || '') + url;+ });++ const blobURLs = [];++ getDecoders().then(({ dracoLoader, ktx2Loader, meshoptDecoder }) => {+ const loader = new GLTFLoader(MANAGER)+ .setCrossOrigin('anonymous')+ .setDRACOLoader(dracoLoader)+ .setKTX2Loader(ktx2Loader.detectSupport(this.renderer))+ .setMeshoptDecoder(meshoptDecoder);++ loader.load(+ url,+ (gltf) => {+ if (window.VIEWER) window.VIEWER.json = gltf;++ const scene = gltf.scene || gltf.scenes[0];+ const clips = gltf.animations || [];++ if (!scene) {+ // Valid, but not supported by this viewer.+ throw new Error(+ 'This model contains no scene, and cannot be viewed here. However,' ++ ' it may contain individual 3D resources.',+ );+ }++ this.setContent(scene, clips);++ blobURLs.forEach(URL.revokeObjectURL);++ // See: https://github.com/google/draco/issues/349+ // DRACOLoader.releaseDecoderModule();++ resolve(gltf);+ },+ undefined,+ reject,+ );+ }, reject);+ });+ }++ /**+ * @param {THREE.Object3D} object+ * @param {Array<THREE.AnimationClip} clips+ */+ setContent(object, clips) {+ this.clear();++ object.updateMatrixWorld(); // nirholas/3d-agent#330++ const box = new Box3().setFromObject(object);+ const size = box.getSize(new Vector3()).length();+ const center = box.getCenter(new Vector3());++ this.controls.reset();++ object.position.x -= center.x;+ object.position.y -= center.y;+ object.position.z -= center.z;++ this.controls.maxDistance = size * 10;++ this.defaultCamera.near = size / 100;+ this.defaultCamera.far = size * 100;+ this.defaultCamera.updateProjectionMatrix();++ // Compute exact camera distance to fit the full bounding box using FOV math.+ // This replaces magic multipliers and correctly accounts for aspect ratio.+ const bbSize = box.getSize(new Vector3());+ const vFovRad = this.defaultCamera.fov * (Math.PI / 180);+ const aspect = Math.max(this.defaultCamera.aspect, 0.01);+ const hFovRad = 2 * Math.atan(Math.tan(vFovRad / 2) * aspect);+ const distV = (bbSize.y / 2 * 1.15) / Math.tan(vFovRad / 2);+ const distH = (bbSize.x / 2 * 1.15) / Math.tan(hFovRad / 2);+ const dist = Math.max(distV, distH);++ // Orbital focus: 10% above bbox centre — upper-chest framing for humanoids.+ const focusY = bbSize.y * 0.1;++ // Final framed camera (the position the user should end up at).+ const framedPos = new Vector3();+ if (this.options.cameraPosition) {+ framedPos.fromArray(this.options.cameraPosition);+ } else {+ // 3/4 angle: slight x offset for depth; z is the FOV-derived distance.+ framedPos.set(dist * 0.12, focusY, dist);+ }+ const orbitalTarget = this.options.cameraPosition+ ? new Vector3()+ : new Vector3(0, focusY, 0);++ // In kiosk / embed modes (and on subsequent loads), snap straight to+ // the framed position. On the first interactive load we tween in from+ // a slightly wider angle so the reveal feels intentional.+ const skipReveal =+ this.options.kiosk || this.options.cameraPosition || this._hasRevealed === true;++ if (skipReveal) {+ this.defaultCamera.position.copy(framedPos);+ this.defaultCamera.lookAt(orbitalTarget);+ } else {+ // Start ~40% wider and slightly higher, then ease into the framed pose.+ const startPos = new Vector3()+ .subVectors(framedPos, orbitalTarget)+ .multiplyScalar(1.4)+ .add(orbitalTarget);+ startPos.y += size / 8;+ this.defaultCamera.position.copy(startPos);+ this.defaultCamera.lookAt(orbitalTarget);+ this._pendingReveal = { framedPos: framedPos.clone(), target: orbitalTarget.clone() };+ this._hasRevealed = true;+ }++ this.setCamera(DEFAULT_CAMERA);++ this.axesCamera.position.copy(this.defaultCamera.position);+ this.axesCamera.lookAt(this.axesScene.position);+ this.axesCamera.near = size / 100;+ this.axesCamera.far = size * 100;+ this.axesCamera.updateProjectionMatrix();+ this.axesCorner.scale.set(size, size, size);++ this.controls.saveState();++ this.scene.add(object);+ this.content = object;++ this.state.punctualLights = true;++ this.content.traverse((node) => {+ if (node.isLight) {+ this.state.punctualLights = false;+ }+ });++ this.setClips(clips);++ // Attach external animation manager to the new content+ this.animationManager.attach(this.content);+ this._setupAnimationPanel();++ // Shift camera down to offset the animation panel overlay so the model+ // isn't clipped by the panel on first load and after each model swap.+ const panelBias = this._panelBiasY(dist);+ if (panelBias > 0) {+ this.controls.target.y -= panelBias;+ this.defaultCamera.position.y -= panelBias;+ if (this._pendingReveal) {+ this._pendingReveal.framedPos.y -= panelBias;+ this._pendingReveal.target.y -= panelBias;+ }+ this.controls.update();+ }++ this.updateLights();+ this.updateGUI();+ this.updateEnvironment();+ this.updateDisplay();+ this.updateModelInfo(object, clips);+ this.updateAnnotations();++ if (window.VIEWER) window.VIEWER.scene = this.content;++ this.invalidate();++ // Smooth first-load camera reveal — runs after the scene is fully wired+ // so OrbitControls and damping pick it up cleanly.+ if (this._pendingReveal) {+ const { framedPos, target } = this._pendingReveal;+ this._pendingReveal = null;+ this._tweenCamera(framedPos, target, 1500);+ }+ }++ setClips(clips) {+ setClips(this, clips);+ }++ playAllClips() {+ playAllClips(this);+ }++ /**+ * @param {string} name+ */+ setCamera(name) {+ if (name === DEFAULT_CAMERA) {+ this.controls.enabled = true;+ this.activeCamera = this.defaultCamera;+ } else {+ this.controls.enabled = false;+ this.content.traverse((node) => {+ if (node.isCamera && node.name === name) {+ this.activeCamera = node;+ }+ });+ }+ this.invalidate();+ }++ updateLights() {+ const state = this.state;+ const lights = this.lights;++ if (state.punctualLights && !lights.length) {+ addLights(this);+ } else if (!state.punctualLights && lights.length) {+ removeLights(this);+ }++ this.renderer.toneMapping = Number(state.toneMapping);+ this.renderer.toneMappingExposure = Math.pow(2, state.exposure);++ if (lights.length === 2) {+ lights[0].intensity = state.ambientIntensity;+ lights[0].color.set(state.ambientColor);+ lights[1].intensity = state.directIntensity;+ lights[1].color.set(state.directColor);+ }++ this.invalidate();+ }++ updateEnvironment() {+ const environment = environments.filter(+ (entry) => entry.name === this.state.environment,+ )[0];++ getCubeMapTexture(this, 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();+ });+ }++ updateDisplay() {+ if (this.skeletonHelpers.length) {+ this.skeletonHelpers.forEach((helper) => this.scene.remove(helper));+ }++ traverseMaterials(this.content, (material) => {+ material.wireframe = this.state.wireframe;++ if (material instanceof PointsMaterial) {+ material.size = this.state.pointSize;+ }+ });++ this.content.traverse((node) => {+ if (node.geometry && node.skeleton && this.state.skeleton) {+ const helper = new SkeletonHelper(node.skeleton.bones[0].parent);+ helper.material.linewidth = 3;+ this.scene.add(helper);+ this.skeletonHelpers.push(helper);+ }+ });++ if (this.state.grid !== Boolean(this.gridHelper)) {+ if (this.state.grid) {+ this.gridHelper = new GridHelper();+ this.axesHelper = new AxesHelper();+ this.axesHelper.renderOrder = 999;+ this.axesHelper.onBeforeRender = (renderer) => renderer.clearDepth();+ this.scene.add(this.gridHelper);+ this.scene.add(this.axesHelper);+ } else {+ this.scene.remove(this.gridHelper);+ this.scene.remove(this.axesHelper);+ this.gridHelper = null;+ this.axesHelper = null;+ this.axesRenderer.clear();+ }+ }++ this.controls.autoRotate = this.state.autoRotate;++ this.invalidate();+ }++ updateBackground() {+ this.backgroundColor.set(this.state.bgColor);+ if (this.state.transparentBg) {+ this.scene.background = null;+ this.renderer.setClearColor(0x000000, 0);+ } else {+ this.scene.background = this.backgroundColor;+ this.renderer.setClearColor(0x000000, 1);+ this.updateEnvironment();+ }+ this.invalidate();+ }++ /**+ * Public setter for the scene background color. Used by the widget runtime+ * + Studio postMessage bridge to apply brand config without touching dat.gui.+ * @param {string|number} color CSS color string or hex int.+ */+ setBackgroundColor(color) {+ this.state.bgColor =+ typeof color === 'string' ? color : '#' + color.toString(16).padStart(6, '0');+ this.state.transparentBg = false;+ this.updateBackground();+ }++ /**+ * Adds AxesHelper.+ *+ * See: https://stackoverflow.com/q/16226693/1314762+ */+ updateModelInfo(object, clips) {+ if (this.modelInfo) {+ this.modelInfo.remove();+ this.modelInfo = null;+ }+ if (this.state.showInfo && object) {+ this.modelInfo = createModelInfo(this.el, object, clips);+ }+ }++ updateAnnotations() {+ // Clear existing+ this.annotationEls.forEach((a) => a.el.remove());+ this.annotationEls = [];++ if (!this.state.showLabels || !this.content) return;++ const annotations = buildAnnotations(this.content);++ annotations.forEach((ann) => {+ const canvas = renderAnnotationCanvas(ann);+ const el = document.createElement('div');+ el.classList.add('annotation-label');+ el.appendChild(canvas);+ this.el.appendChild(el);+ this.annotationEls.push({ el, position: ann.position });+ });++ this.invalidate();+ }++ projectAnnotations() {+ if (this.annotationEls.length === 0) return;++ const width = this.el.clientWidth;+ const height = this.el.clientHeight;+ const halfW = width / 2;+ const halfH = height / 2;+ const tempVec = this._tempVec;++ this.annotationEls.forEach(({ el, position }) => {+ tempVec.copy(position);+ tempVec.project(this.activeCamera);++ // Behind camera check+ if (tempVec.z > 1) {+ el.style.display = 'none';+ return;+ }++ const x = tempVec.x * halfW + halfW;+ const y = -(tempVec.y * halfH) + halfH;++ el.style.display = '';+ el.style.left = x + 'px';+ el.style.top = y + 'px';+ });+ }++ addAxesHelper() {+ this.axesDiv = document.createElement('div');+ this.el.appendChild(this.axesDiv);+ this.axesDiv.classList.add('axes');++ const { clientWidth, clientHeight } = this.axesDiv;++ this.axesScene = new Scene();+ this.axesCamera = new PerspectiveCamera(50, clientWidth / clientHeight, 0.1, 10);+ this.axesScene.add(this.axesCamera);++ this.axesRenderer = new WebGLRenderer({ alpha: true });+ this.axesRenderer.setPixelRatio(window.devicePixelRatio);+ this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight);++ this.axesCamera.up = this.defaultCamera.up;++ this.axesCorner = new AxesHelper(5);+ this.axesScene.add(this.axesCorner);+ this.axesDiv.appendChild(this.axesRenderer.domElement);+ }++ addGUI() {+ const isMobile = window.innerWidth <= 700;+ const gui = (this.gui = new GUI({+ autoPlace: false,+ width: isMobile ? 220 : 260,+ hideable: true,+ }));++ // Display controls.+ const dispFolder = gui.addFolder('Display');+ const envBackgroundCtrl = dispFolder.add(this.state, 'background');+ envBackgroundCtrl.onChange(() => {+ this.updateEnvironment();+ this.notifyScenePrefChange();+ });+ const autoRotateCtrl = dispFolder.add(this.state, 'autoRotate');+ autoRotateCtrl.onChange(() => {+ this.updateDisplay();+ this.notifyScenePrefChange();+ });+ const wireframeCtrl = dispFolder.add(this.state, 'wireframe');+ wireframeCtrl.onChange(() => this.updateDisplay());+ const skeletonCtrl = dispFolder.add(this.state, 'skeleton');+ skeletonCtrl.onChange(() => this.updateDisplay());+ const gridCtrl = dispFolder.add(this.state, 'grid');+ gridCtrl.onChange(() => this.updateDisplay());+ dispFolder.add(this.controls, 'screenSpacePanning');+ const pointSizeCtrl = dispFolder.add(this.state, 'pointSize', 1, 16);+ pointSizeCtrl.onChange(() => this.updateDisplay());+ const transparentCtrl = dispFolder.add(this.state, 'transparentBg').name('transparent bg');+ transparentCtrl.onChange(() => {+ this.updateBackground();+ this.notifyScenePrefChange();+ });+ const bgColorCtrl = dispFolder.addColor(this.state, 'bgColor');+ bgColorCtrl.onChange(() => {+ this.updateBackground();+ this.notifyScenePrefChange();+ });+ dispFolder+ .add({ screenshot: () => this.takeScreenshot() }, 'screenshot')+ .name('Screenshot [P]');+ const infoCtrl = dispFolder.add(this.state, 'showInfo').name('model info');+ infoCtrl.onChange(() => this.updateModelInfo(this.content, this.clips));+ const labelsCtrl = dispFolder.add(this.state, 'showLabels').name('mesh labels');+ labelsCtrl.onChange(() => this.updateAnnotations());++ // Lighting controls.+ const lightFolder = gui.addFolder('Lighting');+ const envMapCtrl = lightFolder.add(+ this.state,+ 'environment',+ environments.map((env) => env.name),+ );+ envMapCtrl.onChange(() => {+ this.updateEnvironment();+ this.notifyScenePrefChange();+ });+ const exposureCtrl = lightFolder.add(this.state, 'exposure', -10, 10, 0.01);+ exposureCtrl.onChange(() => {+ this.updateLights();+ this.notifyScenePrefChange();+ });+ [+ lightFolder.add(this.state, 'toneMapping', {+ Linear: LinearToneMapping,+ 'ACES Filmic': ACESFilmicToneMapping,+ }),+ lightFolder.add(this.state, 'punctualLights').listen(),+ lightFolder.add(this.state, 'ambientIntensity', 0, 2),+ lightFolder.addColor(this.state, 'ambientColor'),+ lightFolder.add(this.state, 'directIntensity', 0, 4), // TODO(#116)+ lightFolder.addColor(this.state, 'directColor'),+ ].forEach((ctrl) => ctrl.onChange(() => this.updateLights()));++ // Animation controls.+ this.animFolder = gui.addFolder('Animation');+ this.animFolder.domElement.style.display = 'none';+ const playbackSpeedCtrl = this.animFolder.add(this.state, 'playbackSpeed', 0, 1);+ playbackSpeedCtrl.onChange((speed) => {+ if (this.mixer) this.mixer.timeScale = speed;+ });+ this.animFolder.add({ playAll: () => this.playAllClips() }, 'playAll');++ // Morph target controls.+ this.morphFolder = gui.addFolder('Morph Targets');+ this.morphFolder.domElement.style.display = 'none';++ // Camera controls.+ this.cameraFolder = gui.addFolder('Cameras');+ this.cameraFolder.domElement.style.display = 'none';++ // Agent controls.+ const agentFolder = gui.addFolder('Agent');+ agentFolder+ .add(this.state, 'followMode', {+ None: 'none',+ 'Follow Mouse': 'mouse',+ 'Follow Keystrokes': 'keystrokes',+ })+ .name('follow mode');++ // Stats.+ const perfFolder = gui.addFolder('Performance');+ const perfLi = document.createElement('li');+ this.stats.dom.style.position = 'static';+ perfLi.appendChild(this.stats.dom);+ perfLi.classList.add('gui-stats');+ perfFolder.__ul.appendChild(perfLi);++ const guiWrap = document.createElement('div');+ this.el.appendChild(guiWrap);+ guiWrap.classList.add('gui-wrap');+ guiWrap.classList.add('gui-wrap--hidden');+ guiWrap.appendChild(gui.domElement);+ this._guiWrap = guiWrap;++ // Toggle button — hides dat.GUI behind an "Advanced" control+ const toggle = document.createElement('button');+ toggle.className = 'gui-toggle';+ // In kiosk/embed there's no GUI surface to expose.+ if (this.options.kiosk) toggle.hidden = true;+ toggle.setAttribute('title', 'Toggle advanced controls');+ toggle.setAttribute('aria-label', 'Toggle advanced controls');+ toggle.innerHTML =+ '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' ++ '<circle cx="12" cy="12" r="3"></circle>' ++ '<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>' ++ '</svg>' ++ '<span class="gui-toggle__label">Controls</span>';+ toggle.addEventListener('click', () => {+ const shown = guiWrap.classList.toggle('gui-wrap--hidden');+ toggle.classList.toggle('gui-toggle--active', !shown);+ });+ this.el.appendChild(toggle);+ this._guiToggle = toggle;++ // AR button — hidden until setARTarget() is called with a supported URL+ const arBtn = document.createElement('button');+ arBtn.className = 'ar-btn';+ arBtn.setAttribute('title', 'View in AR');+ arBtn.setAttribute('aria-label', 'View in AR');+ arBtn.innerHTML =+ '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' ++ '<path d="M1 6l5-3 5 3v5l-5 3-5-3z"></path>' ++ '<path d="M11 3l5 3v5l-5-3z"></path>' ++ '<path d="M1 11l5 3 5-3"></path>' ++ '<path d="M6 9v5"></path>' ++ '<path d="M16 6v5l5 3v-5z"></path>' ++ '<path d="M11 8l5 3"></path>' ++ '</svg>' ++ '<span class="ar-btn__label">AR</span>';+ arBtn.hidden = true;+ arBtn.addEventListener('click', () => this._launchAR());+ this.el.appendChild(arBtn);+ this._arBtn = arBtn;+ this._arGlbUrl = null;+ this._arUsdzUrl = null;+ this._xrSession = null;++ if (isMobile) {+ gui.close();+ } else {+ gui.open();+ }+ }++ updateGUI() {+ this.cameraFolder.domElement.style.display = 'none';++ this.morphCtrls.forEach((ctrl) => ctrl.remove());+ this.morphCtrls.length = 0;+ this.morphFolder.domElement.style.display = 'none';++ this.animCtrls.forEach((ctrl) => ctrl.remove());+ this.animCtrls.length = 0;+ this.animFolder.domElement.style.display = 'none';++ const cameraNames = [];+ const morphMeshes = [];+ this.content.traverse((node) => {+ if (node.geometry && node.morphTargetInfluences) {+ morphMeshes.push(node);+ }+ if (node.isCamera) {+ node.name = node.name || `VIEWER__camera_${cameraNames.length + 1}`;+ cameraNames.push(node.name);+ }+ });++ if (cameraNames.length) {+ this.cameraFolder.domElement.style.display = '';+ if (this.cameraCtrl) this.cameraCtrl.remove();+ const cameraOptions = [DEFAULT_CAMERA].concat(cameraNames);+ this.cameraCtrl = this.cameraFolder.add(this.state, 'camera', cameraOptions);+ this.cameraCtrl.onChange((name) => this.setCamera(name));+ }++ if (morphMeshes.length) {+ this.morphFolder.domElement.style.display = '';+ morphMeshes.forEach((mesh) => {+ if (mesh.morphTargetInfluences.length) {+ const nameCtrl = this.morphFolder.add(+ { name: mesh.name || 'Untitled' },+ 'name',+ );+ this.morphCtrls.push(nameCtrl);+ }+ for (let i = 0; i < mesh.morphTargetInfluences.length; i++) {+ const ctrl = this.morphFolder+ .add(mesh.morphTargetInfluences, i, 0, 1, 0.01)+ .listen();+ Object.keys(mesh.morphTargetDictionary).forEach((key) => {+ if (key && mesh.morphTargetDictionary[key] === i) ctrl.name(key);+ });+ this.morphCtrls.push(ctrl);+ }+ });+ }++ if (this.clips.length) {+ this.animFolder.domElement.style.display = '';+ const actionStates = (this.state.actionStates = {});+ this.clips.forEach((clip, clipIndex) => {+ clip.name = `${clipIndex + 1}. ${clip.name}`;++ // Autoplay the first clip.+ let action;+ if (clipIndex === 0) {+ actionStates[clip.name] = true;+ action = this.mixer.clipAction(clip);+ action.play();+ } else {+ actionStates[clip.name] = false;+ }++ // Play other clips when enabled.+ const ctrl = this.animFolder.add(actionStates, clip.name).listen();+ ctrl.onChange((playAnimation) => {+ action = action || this.mixer.clipAction(clip);+ action.setEffectiveTimeScale(1);+ playAnimation ? action.play() : action.stop();+ this.invalidate();+ });+ this.animCtrls.push(ctrl);+ });+ }+ }++ // ── External Animation Panel (Mixamo-style) ─────────────────────────────++ /**+ * Register a list of external animation definitions (name + URL).+ * @param {Array<{name: string, url: string, label?: string, icon?: string, loop?: boolean}>} defs+ */+ setAnimationDefs(defs) {+ this.animationManager.setAnimationDefs(defs);+ if (this.content) this._setupAnimationPanel();+ }++ /**+ * Create / rebuild the animation selector panel.+ * @private+ */+ _setupAnimationPanel() {+ // Remove existing panel+ if (this._animPanelEl) {+ this._animPanelEl.remove();+ this._animPanelEl = null;+ }++ const defs = this.animationManager.getAnimationDefs();+ if (defs.length === 0) return;++ // Check model has a skeleton (no point showing anim panel for static meshes)+ let hasSkeleton = false;+ this.content.traverse((node) => {+ if (node.isSkinnedMesh) hasSkeleton = true;+ });+ if (!hasSkeleton) return;++ // Create panel container+ const panel = document.createElement('div');+ panel.className = 'anim-panel';+ panel.innerHTML =+ '<div class="anim-panel__header">' ++ '<span class="anim-panel__title">Animations</span>' ++ '<button class="anim-panel__stop" title="Stop all">⏹</button>' ++ '</div>' ++ '<div class="anim-panel__grid"></div>';+ this.el.appendChild(panel);+ this._animPanelEl = panel;++ // Render buttons+ this._renderAnimButtons();++ // Load all animations in background. We deliberately do NOT auto-play+ // the first animation: external Mixamo-rigged FBX clips often retarget+ // imperfectly onto Ready Player Me / Avaturn avatars, which collapses+ // the rig and makes the model look "disappeared" on first load. Show+ // the authored pose instead and let the user pick an animation when+ // they want one.+ this.animationManager.loadAll().then(() => {+ this._renderAnimButtons();+ });++ // Stop button+ panel.querySelector('.anim-panel__stop').addEventListener('click', () => {+ this.animationManager.stopAll();+ this._renderAnimButtons();+ this.invalidate();+ });++ // Listen for changes from AnimationManager+ this.animationManager.onChange = () => {+ this._renderAnimButtons();+ };+ }++ /**+ * Render / re-render animation buttons in the panel.+ * @private+ */+ _renderAnimButtons() {+ if (!this._animPanelEl) return;++ const grid = this._animPanelEl.querySelector('.anim-panel__grid');+ const defs = this.animationManager.getAnimationDefs();+ const activeName = this.animationManager.currentName;++ const ICONS = {+ idle: '🧍',+ breathing: '🧍',+ standing: '🧍',+ walking: '🚶',+ walk: '🚶',+ running: '🏃',+ run: '🏃',+ waving: '👋',+ wave: '👋',+ dancing: '💃',+ dance: '💃',+ sitting: '🪑',+ sit: '🪑',+ jumping: '🦘',+ jump: '🦘',+ talking: '🗣️',+ talk: '🗣️',+ clapping: '👏',+ clap: '👏',+ punching: '👊',+ punch: '👊',+ kicking: '🦵',+ kick: '🦵',+ };++ grid.innerHTML = defs+ .map((def, i) => {+ const loaded = this.animationManager.isLoaded(def.name);+ const isActive = activeName === def.name;+ const icon = def.icon || ICONS[def.name.toLowerCase()] || '▶';+ const label = def.label || def.name.charAt(0).toUpperCase() + def.name.slice(1);+ const keyHint = i < 9 ? i + 1 : '';+ return (+ '<button class="anim-btn' ++ (isActive ? ' anim-btn--active' : '') ++ (loaded ? '' : ' anim-btn--loading') ++ '" data-anim="' ++ def.name ++ '"' ++ ' title="' ++ label ++ (keyHint ? ' — press ' + keyHint : '') ++ '"' ++ (loaded ? '' : ' disabled') ++ '>' ++ (keyHint ? '<span class="anim-btn__key">' + keyHint + '</span>' : '') ++ '<span class="anim-btn__icon">' ++ icon ++ '</span>' ++ '<span class="anim-btn__label">' ++ label ++ '</span>' ++ '</button>'+ );+ })+ .join('');++ // Bind click events+ grid.querySelectorAll('.anim-btn:not([disabled])').forEach((btn) => {+ btn.addEventListener('click', () => {+ const name = btn.dataset.anim;+ this.animationManager.crossfadeTo(name);+ this.invalidate();+ this._recomputeAnimating();+ this._updateRenderLoop();+ });+ });++ // Bind keyboard shortcuts (1-9) — only once. Stored on `this` so+ // dispose() can remove it; otherwise viewer recreations stack handlers.+ if (!this._onAnimHotkey) {+ this._onAnimHotkey = (e) => {+ if (e.target && /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;+ if (e.metaKey || e.ctrlKey || e.altKey) return;+ const n = parseInt(e.key, 10);+ if (!n || n < 1 || n > 9) return;+ const currentDefs = this.animationManager.getAnimationDefs();+ const def = currentDefs[n - 1];+ if (!def || !this.animationManager.isLoaded(def.name)) return;+ this.animationManager.crossfadeTo(def.name);+ this.invalidate();+ this._recomputeAnimating();+ this._updateRenderLoop();+ };+ document.addEventListener('keydown', this._onAnimHotkey);+ }+ }++ clear() {+ if (!this.content) return;++ // Detach external animation manager+ this.animationManager.detach();+ if (this._animPanelEl) {+ this._animPanelEl.remove();+ this._animPanelEl = null;+ }++ if (this.modelInfo) {+ this.modelInfo.remove();+ this.modelInfo = null;+ }++ this.annotationEls.forEach((a) => a.el.remove());+ this.annotationEls = [];++ this.scene.remove(this.content);++ // dispose geometry+ this.content.traverse((node) => {+ if (!node.geometry) return;++ node.geometry.dispose();+ });++ // dispose textures+ traverseMaterials(this.content, (material) => {+ for (const key in material) {+ if (key !== 'envMap' && material[key] && material[key].isTexture) {+ material[key].dispose();+ }+ }+ });++ this.content = null;+ if (!this._disposed) this.invalidate();+ }++ dispose() {+ if (this._disposed) return;+ this._disposed = true;++ if (this._rafId !== null) {+ cancelAnimationFrame(this._rafId);+ this._rafId = null;+ }++ document.removeEventListener('visibilitychange', this._onVisibilityChange);+ window.removeEventListener('resize', this._onResize, false);+ window.removeEventListener('keydown', this._onKeyDown);+ if (this._onDblClick && this.renderer?.domElement) {+ this.renderer.domElement.removeEventListener('dblclick', this._onDblClick);+ }+ if (this._cameraTweenRaf) cancelAnimationFrame(this._cameraTweenRaf);+ if (this._onAnimHotkey) {+ document.removeEventListener('keydown', this._onAnimHotkey);+ this._onAnimHotkey = null;+ }++ if (this._intersectionObserver) {+ this._intersectionObserver.disconnect();+ this._intersectionObserver = null;+ }++ this.clear();++ if (this.mixer) {+ this.mixer.stopAllAction();+ const root = this.mixer.getRoot();+ if (root) this.mixer.uncacheRoot(root);+ this.mixer = null;+ }+ this.clips = [];++ // Dispose external animation system+ this.animationManager.dispose();+ if (this._animPanelEl) {+ this._animPanelEl.remove();+ this._animPanelEl = null;+ }++ if (this.skeletonHelpers.length) {+ this.skeletonHelpers.forEach((helper) => {+ this.scene.remove(helper);+ helper.dispose?.();+ });+ this.skeletonHelpers.length = 0;+ }++ if (this.gridHelper) {+ this.scene.remove(this.gridHelper);+ this.gridHelper.geometry?.dispose();+ this.gridHelper.material?.dispose();+ this.gridHelper = null;+ }+ if (this.axesHelper) {+ this.scene.remove(this.axesHelper);+ this.axesHelper.geometry?.dispose();+ this.axesHelper.material?.dispose();+ this.axesHelper = null;+ }+ if (this.axesCorner) {+ this.axesScene?.remove(this.axesCorner);+ this.axesCorner.geometry?.dispose();+ this.axesCorner.material?.dispose();+ this.axesCorner = null;+ }++ this.lights.forEach((light) => light.parent?.remove(light));+ this.lights = [];++ if (this.annotationEls.length) {+ this.annotationEls.forEach((a) => a.el.remove());+ this.annotationEls = [];+ }+ if (this.modelInfo) {+ this.modelInfo.remove();+ this.modelInfo = null;+ }++ if (this.gui) {+ this.gui.destroy();+ this.gui = null;+ }+ if (this._guiWrap) {+ this._guiWrap.remove();+ this._guiWrap = null;+ }+ if (this._guiToggle) {+ this._guiToggle.remove();+ this._guiToggle = null;+ }++ if (this.stats?.dom) this.stats.dom.remove();++ if (this.controls) {+ if (this._onControlsChange) {+ this.controls.removeEventListener('change', this._onControlsChange);+ this._onControlsChange = null;+ }+ this.controls.dispose();+ this.controls = null;+ }++ if (this._loadedEnvironment) {+ this._loadedEnvironment.dispose();+ this._loadedEnvironment = null;+ }+ if (this.neutralEnvironment) {+ this.neutralEnvironment.dispose();+ this.neutralEnvironment = null;+ }+ if (this.scene) {+ this.scene.environment = null;+ this.scene.background = null;+ }++ if (this.pmremGenerator) {+ this.pmremGenerator.dispose();+ this.pmremGenerator = null;+ }++ if (this.axesRenderer) {+ this.axesRenderer.dispose();+ this.axesRenderer.forceContextLoss?.();+ this.axesRenderer.domElement?.remove();+ this.axesRenderer = null;+ }+ if (this.axesDiv) {+ this.axesDiv.remove();+ this.axesDiv = null;+ }+ this.axesScene = null;+ this.axesCamera = null;++ if (this.renderer) {+ this.renderer.dispose();+ this.renderer.forceContextLoss?.();+ this.renderer.domElement?.remove();+ if (window.renderer === this.renderer) window.renderer = null;+ this.renderer = null;+ }++ this.scene = null;+ this.content = null;+ this.activeCamera = null;+ this.defaultCamera = null;+ this._afterAnimateHooks = null;+ }+}diff --git a/publish/src/viewer/animation.js b/publish/src/viewer/animation.jsnew file mode 100644index 000000000..d01ad2bd0--- /dev/null+++ b/publish/src/viewer/animation.js@@ -0,0 +1,22 @@+import { AnimationMixer } from 'three';++export function setClips(viewer, clips) {+ if (viewer.mixer) {+ viewer.mixer.stopAllAction();+ viewer.mixer.uncacheRoot(viewer.mixer.getRoot());+ viewer.mixer = null;+ }++ viewer.clips = clips;+ if (!clips.length) return;++ viewer.mixer = new AnimationMixer(viewer.content);+}++export function playAllClips(viewer) {+ viewer.clips.forEach((clip) => {+ viewer.mixer.clipAction(clip).reset().play();+ viewer.state.actionStates[clip.name] = true;+ });+ viewer.invalidate();+}diff --git a/publish/src/viewer/environment.js b/publish/src/viewer/environment.jsnew file mode 100644index 000000000..3925b9c71--- /dev/null+++ b/publish/src/viewer/environment.js@@ -0,0 +1,34 @@+import { EXRLoader } from 'three/addons/loaders/EXRLoader.js';++export function getCubeMapTexture(viewer, environment) {+ const { id, path } = environment;++ // neutral (THREE.RoomEnvironment)+ if (id === 'neutral') {+ return Promise.resolve({ envMap: viewer.neutralEnvironment });+ }++ // none+ if (id === '') {+ return Promise.resolve({ envMap: null });+ }++ return new Promise((resolve, reject) => {+ new EXRLoader().load(+ path,+ (texture) => {+ const envMap = viewer.pmremGenerator.fromEquirectangular(texture).texture;+ texture.dispose();++ if (viewer._loadedEnvironment && viewer._loadedEnvironment !== envMap) {+ viewer._loadedEnvironment.dispose();+ }+ viewer._loadedEnvironment = envMap;++ resolve({ envMap });+ },+ undefined,+ reject,+ );+ });+}diff --git a/publish/src/viewer/internal.js b/publish/src/viewer/internal.jsnew file mode 100644index 000000000..53eeaa723--- /dev/null+++ b/publish/src/viewer/internal.js@@ -0,0 +1,47 @@+import { LoadingManager, REVISION } from 'three';++export const DEFAULT_CAMERA = '[default]';+export const Preset = { ASSET_GENERATOR: 'assetgenerator' };++export const MANAGER = new LoadingManager();+const THREE_PATH = `https://unpkg.com/three@0.${REVISION}.x`;++/**+ * Lazy, memoized setup of the Draco/KTX2/Meshopt decoders. Dynamically imports+ * each module the first time a model is loaded, so the first-paint bundle does+ * not pay for decoders that most callers never use.+ *+ * @returns {Promise<{ dracoLoader: DRACOLoader, ktx2Loader: KTX2Loader, meshoptDecoder: any }>}+ */+let _decodersPromise = null;+export function getDecoders() {+ if (_decodersPromise) return _decodersPromise;+ _decodersPromise = Promise.all([+ import('three/addons/loaders/DRACOLoader.js'),+ import('three/addons/loaders/KTX2Loader.js'),+ import('three/addons/libs/meshopt_decoder.module.js'),+ ]).then(([dracoMod, ktx2Mod, meshoptMod]) => {+ const dracoLoader = new dracoMod.DRACOLoader(MANAGER).setDecoderPath(+ `${THREE_PATH}/examples/jsm/libs/draco/gltf/`,+ );+ const ktx2Loader = new ktx2Mod.KTX2Loader(MANAGER).setTranscoderPath(+ `${THREE_PATH}/examples/jsm/libs/basis/`,+ );+ return { dracoLoader, ktx2Loader, meshoptDecoder: meshoptMod.MeshoptDecoder };+ });+ return _decodersPromise;+}++export function traverseMaterials(object, callback) {+ const seen = new Set();+ object.traverse((node) => {+ if (!node.geometry) return;+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ materials.forEach((mat) => {+ if (mat && !seen.has(mat.uuid)) {+ seen.add(mat.uuid);+ callback(mat);+ }+ });+ });+}diff --git a/publish/src/viewer/lights.js b/publish/src/viewer/lights.jsnew file mode 100644index 000000000..98a32f2ef--- /dev/null+++ b/publish/src/viewer/lights.js@@ -0,0 +1,30 @@+import { AmbientLight, DirectionalLight, HemisphereLight } from 'three';+import { Preset } from './internal.js';++export function addLights(viewer) {+ const { state, options } = viewer;++ if (options.preset === Preset.ASSET_GENERATOR) {+ const hemiLight = new HemisphereLight();+ hemiLight.name = 'hemi_light';+ viewer.scene.add(hemiLight);+ viewer.lights.push(hemiLight);+ return;+ }++ const light1 = new AmbientLight(state.ambientColor, state.ambientIntensity);+ light1.name = 'ambient_light';+ viewer.defaultCamera.add(light1);++ const light2 = new DirectionalLight(state.directColor, state.directIntensity);+ light2.position.set(0.5, 0, 0.866); // ~60º+ light2.name = 'main_light';+ viewer.defaultCamera.add(light2);++ viewer.lights.push(light1, light2);+}++export function removeLights(viewer) {+ viewer.lights.forEach((light) => light.parent.remove(light));+ viewer.lights.length = 0;+}diff --git a/publish/src/viewer/screenshot.js b/publish/src/viewer/screenshot.jsnew file mode 100644index 000000000..b9ff956f1--- /dev/null+++ b/publish/src/viewer/screenshot.js@@ -0,0 +1,22 @@+export function takeScreenshot(viewer) {+ // Render a fresh frame then capture via toBlob (avoids preserveDrawingBuffer overhead).+ viewer.renderer.render(viewer.scene, viewer.activeCamera);+ viewer.renderer.domElement.toBlob((blob) => {+ if (!blob) return;+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);+ const url = URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.download = `3d-screenshot-${timestamp}.png`;+ link.href = url;+ link.click();+ URL.revokeObjectURL(url);+ }, 'image/png');+ flashScreenshotFeedback(viewer);+}++export function flashScreenshotFeedback(viewer) {+ const overlay = document.createElement('div');+ overlay.className = 'screenshot-flash';+ viewer.el.appendChild(overlay);+ overlay.addEventListener('animationend', () => overlay.remove());+}diff --git a/publish/src/wallet-auth.js b/publish/src/wallet-auth.jsnew file mode 100644index 000000000..b4a3765c9--- /dev/null+++ b/publish/src/wallet-auth.js@@ -0,0 +1,166 @@+import { ensureWallet } from './erc8004/agent-registry.js';++// ─── Public API ─────────────────────────────────────────────────────────────++/**+ * Sign in with Ethereum (EIP-4361). If a valid session cookie already exists,+ * skip the wallet prompt entirely and return the current user — keeps the user+ * authenticated across the whole site without re-signing.+ *+ * @returns {Promise<{user: object, wallet?: object}>}+ */+export async function signInWithWallet() {+ // Short-circuit: if the session cookie is still valid, no need to prompt+ // the wallet or re-sign anything.+ const existing = await getCurrentUser();+ if (existing) return { user: existing };++ const { signer, address, chainId } = await ensureWallet();++ // GET nonce — sets __Host-csrf-siwe cookie, returns csrf token+ const nonceRes = await fetch('/api/auth/siwe/nonce', {+ credentials: 'include',+ });+ if (!nonceRes.ok) {+ const body = await nonceRes.json().catch(() => ({}));+ throw new Error(body.error_description || 'Failed to fetch nonce');+ }+ const { nonce, csrf } = await nonceRes.json();++ const message = [+ `${location.host} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to three.ws.',+ '',+ `URI: ${location.origin}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${new Date().toISOString()}`,+ ].join('\n');++ const signature = await signer.signMessage(message);++ const verifyRes = await fetch('/api/auth/siwe/verify', {+ method: 'POST',+ credentials: 'include',+ headers: {+ 'content-type': 'application/json',+ 'x-csrf-token': csrf,+ },+ body: JSON.stringify({ message, signature }),+ });++ const data = await verifyRes.json().catch(() => ({}));+ if (!verifyRes.ok) {+ throw new Error(data.error_description || data.error || 'Sign-in failed');+ }+ return data;+}++/** @returns {Promise<void>} */+export async function signOut() {+ await fetch('/api/auth/logout', {+ method: 'POST',+ credentials: 'include',+ }).catch(() => {});+}++/** @returns {Promise<object|null>} */+export async function getCurrentUser() {+ try {+ const res = await fetch('/api/auth/me', { credentials: 'include' });+ if (!res.ok) return null;+ const { user } = await res.json();+ return user ?? null;+ } catch {+ return null;+ }+}++/**+ * Attaches click handler + swaps UI for signed-in chip.+ * @param {HTMLElement} buttonEl+ */+export function wireSigninButton(buttonEl) {+ getCurrentUser().then((user) => {+ if (user) {+ _renderChip(buttonEl, user);+ } else {+ _wireClickHandler(buttonEl);+ }+ });+}++// ─── Internal ────────────────────────────────────────────────────────────────++function _shortAddr(addr) {+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}++function _renderChip(buttonEl, user) {+ const addr = user.wallet_address || '';+ const label = addr ? _shortAddr(addr) : user.display_name || 'Account';++ const chip = document.createElement('span');+ chip.id = 'wallet-chip';+ chip.style.cssText =+ 'display:inline-flex;align-items:center;gap:0.5em;font-size:0.85em;cursor:default;';++ const addrSpan = document.createElement('span');+ addrSpan.textContent = label;+ addrSpan.title = addr;++ const divider = document.createElement('span');+ divider.textContent = '·';+ divider.style.opacity = '0.4';++ const signOutBtn = document.createElement('button');+ signOutBtn.textContent = 'sign out';+ signOutBtn.style.cssText =+ 'background:none;border:none;padding:0;cursor:pointer;text-decoration:underline;font-size:inherit;color:inherit;';+ signOutBtn.addEventListener('click', async () => {+ signOutBtn.disabled = true;+ signOutBtn.textContent = 'signing out…';+ await signOut();+ location.reload();+ });++ chip.append(addrSpan, divider, signOutBtn);+ buttonEl.replaceWith(chip);+}++function _wireClickHandler(buttonEl) {+ const statusEl = document.createElement('span');+ statusEl.style.cssText = 'display:none;font-size:0.8em;margin-left:0.75em;opacity:0.7;';+ buttonEl.insertAdjacentElement('afterend', statusEl);++ let _busy = false;++ buttonEl.addEventListener('click', async () => {+ if (_busy) return;++ if (!window.ethereum) {+ statusEl.style.display = 'inline';+ statusEl.textContent =+ 'No wallet detected — install MetaMask or use a wallet-enabled browser.';+ return;+ }++ _busy = true;+ buttonEl.disabled = true;+ statusEl.style.display = 'inline';+ statusEl.textContent = 'Waiting for wallet…';++ try {+ await signInWithWallet();+ statusEl.textContent = 'Signed in — reloading…';+ location.reload();+ } catch (err) {+ statusEl.textContent = err.message || 'Sign-in failed.';+ buttonEl.disabled = false;+ _busy = false;+ }+ });+}diff --git a/publish/src/wallet/connect-button.js b/publish/src/wallet/connect-button.jsnew file mode 100644index 000000000..77e2ef1fe--- /dev/null+++ b/publish/src/wallet/connect-button.js@@ -0,0 +1,367 @@+/**+ * Unified wallet connect controller + button factory.+ *+ * Usage (Vite-bundled apps):+ * import { createConnectWalletButton } from './wallet/connect-button.js';+ * const ctrl = createConnectWalletButton(mountEl, { onSuccess: (data) => ... });+ */++import { BrowserProvider } from 'ethers';+import { STATES, initialState, reduce } from './state.js';+import { eagerConnectWallet, getWalletState } from '../erc8004/agent-registry.js';++/** Chain IDs that match known ERC-8004 registry deployments. */+const DEFAULT_CHAIN_IDS = [1, 8453, 10, 42161, 11155111, 84532];++const CHAIN_NAMES = {+ 1: 'Mainnet',+ 8453: 'Base',+ 10: 'Optimism',+ 42161: 'Arbitrum One',+ 11155111: 'Sepolia',+ 84532: 'Base Sepolia',+};++const ASYNC_STATES = new Set([+ STATES.DETECTING,+ STATES.REQUESTING_ACCOUNTS,+ STATES.SIGNING,+ STATES.VERIFYING,+]);++/**+ * Build the EIP-4361 SIWE message string.+ * Format must match the parser in api/auth/siwe/verify.js exactly.+ *+ * @param {string} address checksummed Ethereum address+ * @param {number} chainId+ * @param {string} nonce+ * @param {{ domain: string, uri: string, issuedAt: string, expirationTime: string }} ctx+ * @returns {string}+ */+function defaultMessageBuilder(address, chainId, nonce, { domain, uri, issuedAt, expirationTime }) {+ return [+ `${domain} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to three.ws. This does not cost anything and proves wallet ownership.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ `Expiration Time: ${expirationTime}`,+ ].join('\n');+}++/**+ * Headless state machine for wallet connect / SIWE.+ * Emits `change` CustomEvents on state transitions.+ *+ * @fires ConnectWalletController#change+ */+export class ConnectWalletController extends EventTarget {+ /** @type {import('./state.js').ConnectState} */+ #s;+ #opts;+ #onAccountsChanged;+ #onChainChanged;++ /**+ * @param {{+ * allowedChainIds?: number[],+ * nonceUrl?: string,+ * verifyUrl?: string,+ * messageBuilder?: Function,+ * onSuccess?: Function,+ * autoDetect?: boolean,+ * labels?: Record<string, string>,+ * }} [opts]+ */+ constructor(opts = {}) {+ super();+ this.#opts = {+ allowedChainIds: DEFAULT_CHAIN_IDS,+ nonceUrl: '/api/auth/siwe/nonce',+ verifyUrl: '/api/auth/siwe/verify',+ messageBuilder: defaultMessageBuilder,+ onSuccess: null,+ autoDetect: false,+ labels: {},+ ...opts,+ };+ this.#s = initialState();++ this.#onAccountsChanged = (accounts) =>+ this.#dispatch({ type: 'ACCOUNTS_CHANGED', accounts });+ this.#onChainChanged = (chainIdHex) => {+ const chainId = parseInt(chainIdHex, 16);+ this.#dispatch({ type: 'CHAIN_CHANGED', chainId });+ if (!this.#opts.allowedChainIds.includes(chainId)) {+ this.#dispatch({ type: 'WRONG_CHAIN' });+ } else if (this.#s.status === STATES.WRONG_CHAIN) {+ this.#dispatch({ type: 'CHAIN_OK' });+ }+ };++ if (window.ethereum) {+ window.ethereum.on('accountsChanged', this.#onAccountsChanged);+ window.ethereum.on('chainChanged', this.#onChainChanged);+ }++ // Hydrate from any already-resolved silent reconnect (fired during app+ // boot). If the shared registry has a connected address, jump straight+ // to CONNECTED so the button renders the address instead of "Connect+ // wallet" on first paint. If not yet resolved, attempt the silent path+ // here too (idempotent — no popup).+ this.#tryEagerHydrate();+ }++ async #tryEagerHydrate() {+ const existing = getWalletState();+ if (existing.address && existing.chainId) {+ this.#dispatch({+ type: 'ACCOUNTS_RESOLVED',+ address: existing.address,+ chainId: existing.chainId,+ });+ if (!this.#opts.allowedChainIds.includes(existing.chainId)) {+ this.#dispatch({ type: 'WRONG_CHAIN' });+ }+ return;+ }+ const eager = await eagerConnectWallet();+ if (!eager) return;+ this.#dispatch({+ type: 'ACCOUNTS_RESOLVED',+ address: eager.address,+ chainId: eager.chainId,+ });+ if (!this.#opts.allowedChainIds.includes(eager.chainId)) {+ this.#dispatch({ type: 'WRONG_CHAIN' });+ }+ }++ get state() {+ return this.#s.status;+ }+ get address() {+ return this.#s.address;+ }+ get chainId() {+ return this.#s.chainId;+ }+ get error() {+ return this.#s.error;+ }++ /** @param {{ type: string, [k: string]: any }} action */+ #dispatch(action) {+ const next = reduce(this.#s, action);+ if (next === this.#s) return;+ this.#s = next;+ this.dispatchEvent(new CustomEvent('change', { detail: { ...next } }));+ }++ /** Initiate the connect flow from `idle`. Idempotent if already past idle. */+ async connect() {+ if (this.#s.status !== STATES.IDLE) return;+ this.#dispatch({ type: 'CONNECT' });++ if (!window.ethereum) {+ this.#dispatch({ type: 'NO_PROVIDER' });+ return;+ }+ this.#dispatch({ type: 'HAS_PROVIDER' });++ try {+ const provider = new BrowserProvider(window.ethereum);+ await provider.send('eth_requestAccounts', []);+ const signer = await provider.getSigner();+ const address = await signer.getAddress();+ const network = await provider.getNetwork();+ const chainId = Number(network.chainId);+ this.#dispatch({ type: 'ACCOUNTS_RESOLVED', address, chainId });++ if (!this.#opts.allowedChainIds.includes(chainId)) {+ this.#dispatch({ type: 'WRONG_CHAIN' });+ await this.#trySwitchChain(provider);+ }+ } catch (e) {+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });+ }+ }++ /** Attempt to switch to the first allowed chain via wallet_switchEthereumChain. */+ async #trySwitchChain(provider) {+ const target = this.#opts.allowedChainIds[0];+ const hex = '0x' + target.toString(16);+ try {+ await provider.send('wallet_switchEthereumChain', [{ chainId: hex }]);+ // chainChanged event fires and handles the CHAIN_OK dispatch.+ } catch (e) {+ if (e?.code === 4902) {+ this.#dispatch({+ type: 'ERROR',+ error: new Error(+ `Chain ${CHAIN_NAMES[target] || target} is not in your wallet. Add it manually.`,+ ),+ });+ } else if (e?.code !== 4001) {+ // 4001 = user rejected — surface as error; other codes are bugs+ this.#dispatch({+ type: 'ERROR',+ error: e instanceof Error ? e : new Error(String(e)),+ });+ }+ }+ }++ /** Sign a SIWE message and verify with the backend. Call from `connected` state. */+ async signAndVerify() {+ if (this.#s.status !== STATES.CONNECTED && this.#s.status !== STATES.WRONG_CHAIN) return;+ this.#dispatch({ type: 'SIGN' });++ try {+ const provider = new BrowserProvider(window.ethereum);+ const signer = await provider.getSigner();+ const address = await signer.getAddress();++ const nonceRes = await fetch(this.#opts.nonceUrl, { credentials: 'include' });+ if (!nonceRes.ok) throw new Error('Failed to get nonce');+ const { nonce, csrf } = await nonceRes.json();++ const domain = location.host;+ const uri = location.origin;+ const issuedAt = new Date().toISOString();+ const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();++ const message = this.#opts.messageBuilder(address, this.#s.chainId, nonce, {+ domain,+ uri,+ issuedAt,+ expirationTime,+ });++ const signature = await signer.signMessage(message);+ this.#dispatch({ type: 'SIGNATURE_OBTAINED' });++ const verifyRes = await fetch(this.#opts.verifyUrl, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },+ body: JSON.stringify({ message, signature }),+ });+ const data = await verifyRes.json();+ if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');++ this.#dispatch({ type: 'SUCCESS' });+ if (this.#opts.onSuccess) this.#opts.onSuccess(data);+ } catch (e) {+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });+ }+ }++ /** Return to `idle` state, clearing any error. */+ reset() {+ this.#dispatch({ type: 'RESET' });+ }++ /** Remove all event listeners. Call when unmounting in SPA contexts. */+ dispose() {+ if (window.ethereum) {+ window.ethereum.removeListener('accountsChanged', this.#onAccountsChanged);+ window.ethereum.removeListener('chainChanged', this.#onChainChanged);+ }+ }+}++const LABEL_DEFAULTS = {+ idle: 'Connect wallet',+ detecting: 'Detecting…',+ no_provider: 'Install MetaMask',+ requesting_accounts: 'Check your wallet…',+ signing: 'Sign in your wallet…',+ verifying: 'Verifying…',+ success: 'Signed in',+ error: 'Retry',+};++/**+ * Mount a wallet connect button into `mountEl`.+ * The element's contents are replaced with a single `<button class="cwb-btn">`.+ *+ * @param {HTMLElement} mountEl+ * @param {{+ * allowedChainIds?: number[],+ * nonceUrl?: string,+ * verifyUrl?: string,+ * messageBuilder?: Function,+ * onSuccess?: Function,+ * labels?: Record<string, string>,+ * }} [opts]+ * @returns {ConnectWalletController}+ */+export function createConnectWalletButton(mountEl, opts = {}) {+ const labels = { ...LABEL_DEFAULTS, ...(opts.labels || {}) };+ const allowedChainIds = opts.allowedChainIds || DEFAULT_CHAIN_IDS;+ const ctrl = new ConnectWalletController({ ...opts, allowedChainIds });++ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'cwb-btn';++ function render(detail) {+ const s = detail.status;+ btn.setAttribute('data-state', s);+ btn.disabled = ASYNC_STATES.has(s) || s === STATES.SUCCESS;+ btn.setAttribute('aria-busy', ASYNC_STATES.has(s) ? 'true' : 'false');++ if (s === STATES.CONNECTED || s === STATES.WRONG_CHAIN) {+ const addr = detail.address || '';+ const short = addr ? addr.slice(0, 6) + '…' + addr.slice(-4) : '';+ const chainName = CHAIN_NAMES[detail.chainId] || `Chain ${detail.chainId}`;+ btn.textContent =+ s === STATES.WRONG_CHAIN+ ? `Switch to ${CHAIN_NAMES[allowedChainIds[0]] || 'Mainnet'}`+ : `${short} · ${chainName}`;+ } else if (s === STATES.ERROR) {+ btn.textContent = labels.error;+ } else {+ btn.textContent = labels[s] || s;+ }+ }++ function updateClickHandler(status) {+ btn.onclick = null;+ if (status === STATES.NO_PROVIDER) {+ btn.onclick = () => window.open('https://metamask.io', '_blank', 'noopener');+ } else if (status === STATES.CONNECTED) {+ btn.onclick = () => ctrl.signAndVerify();+ } else if (status === STATES.WRONG_CHAIN) {+ btn.onclick = () => ctrl.connect();+ } else if (status === STATES.ERROR) {+ btn.onclick = () => {+ ctrl.reset();+ ctrl.connect();+ };+ } else if (status === STATES.IDLE) {+ btn.onclick = () => ctrl.connect();+ }+ }++ ctrl.addEventListener('change', (e) => {+ render(e.detail);+ updateClickHandler(e.detail.status);+ });++ // Initial render from current state.+ render({ status: ctrl.state, address: ctrl.address, chainId: ctrl.chainId, error: ctrl.error });+ updateClickHandler(ctrl.state);++ mountEl.innerHTML = '';+ mountEl.appendChild(btn);++ return ctrl;+}diff --git a/publish/src/wallet/state.js b/publish/src/wallet/state.jsnew file mode 100644index 000000000..df6c20bef--- /dev/null+++ b/publish/src/wallet/state.js@@ -0,0 +1,80 @@+/**+ * Pure state machine for the wallet connect flow.+ * No side effects — suitable for unit testing.+ */++/** @enum {string} */+export const STATES = Object.freeze({+ IDLE: 'idle',+ DETECTING: 'detecting',+ NO_PROVIDER: 'no_provider',+ REQUESTING_ACCOUNTS: 'requesting_accounts',+ CONNECTED: 'connected',+ WRONG_CHAIN: 'wrong_chain',+ SIGNING: 'signing',+ VERIFYING: 'verifying',+ SUCCESS: 'success',+ ERROR: 'error',+});++/**+ * @typedef {{ status: string, address: string|null, chainId: number|null, error: Error|null }} ConnectState+ */++/** @returns {ConnectState} */+export function initialState() {+ return { status: STATES.IDLE, address: null, chainId: null, error: null };+}++/**+ * Pure reducer — given a state and an action, return the next state.+ * @param {ConnectState} state+ * @param {{ type: string, [k: string]: any }} action+ * @returns {ConnectState}+ */+export function reduce(state, action) {+ switch (action.type) {+ case 'CONNECT':+ if (state.status !== STATES.IDLE) return state;+ return { ...state, status: STATES.DETECTING, error: null };+ case 'NO_PROVIDER':+ return { ...state, status: STATES.NO_PROVIDER };+ case 'HAS_PROVIDER':+ return { ...state, status: STATES.REQUESTING_ACCOUNTS };+ case 'ACCOUNTS_RESOLVED':+ return {+ ...state,+ status: STATES.CONNECTED,+ address: action.address,+ chainId: action.chainId,+ };+ case 'WRONG_CHAIN':+ return { ...state, status: STATES.WRONG_CHAIN };+ case 'CHAIN_OK':+ return { ...state, status: STATES.CONNECTED };+ case 'SIGN':+ if (state.status !== STATES.CONNECTED && state.status !== STATES.WRONG_CHAIN)+ return state;+ return { ...state, status: STATES.SIGNING };+ case 'SIGNATURE_OBTAINED':+ return { ...state, status: STATES.VERIFYING };+ case 'SUCCESS':+ return { ...state, status: STATES.SUCCESS };+ case 'ERROR':+ return { ...state, status: STATES.ERROR, error: action.error ?? null };+ case 'RESET':+ return initialState();+ case 'ACCOUNTS_CHANGED':+ if (!action.accounts || action.accounts.length === 0) return initialState();+ return {+ ...state,+ address: action.accounts[0],+ chainId: state.chainId,+ status: STATES.CONNECTED,+ };+ case 'CHAIN_CHANGED':+ return { ...state, chainId: action.chainId };+ default:+ return state;+ }+}diff --git a/publish/src/widget-types.js b/publish/src/widget-types.jsnew file mode 100644index 000000000..be5643ac8--- /dev/null+++ b/publish/src/widget-types.js@@ -0,0 +1,308 @@+// Widget type registry + brand defaults + per-type config validators.+// Both the Studio UI and the public widget runtime import from here.+//+// `status: 'ready'` widgets have a working runtime. `status: 'pending'`+// widgets save their config but the runtime renders a "coming soon" banner+// — Prompts 01-05 flip these to 'ready' as their runtimes ship.++import { z } from 'zod';++export const WIDGET_TYPES = {+ turntable: {+ label: 'Turntable Showcase',+ desc: 'Hero banner — auto-rotate, no UI, just the avatar.',+ status: 'ready',+ icon: '◎',+ },+ 'animation-gallery': {+ label: 'Animation Gallery',+ desc: 'Click through every clip on a rigged avatar.',+ status: 'ready',+ icon: '▶',+ },+ 'talking-agent': {+ label: 'Talking Agent',+ desc: 'Embodied chat — your agent on your site.',+ status: 'ready',+ icon: '◐',+ },+ passport: {+ label: 'ERC-8004 Passport',+ desc: 'On-chain identity card for any agent.',+ status: 'ready',+ icon: '◊',+ },+ 'hotspot-tour': {+ label: 'Hotspot Tour',+ desc: 'Annotated 3D scene with clickable points of interest.',+ status: 'ready',+ icon: '⌖',+ },+ 'pumpfun-feed': {+ label: 'Pump.fun Live Feed',+ desc: 'Solana agent narrates live pump.fun claims and graduations.',+ status: 'ready',+ icon: '✦',+ },+};++export const WIDGET_TYPE_KEYS = Object.keys(WIDGET_TYPES);++export const BRAND_DEFAULTS = Object.freeze({+ background: '#0a0a0a',+ accent: '#8b5cf6',+ caption: '',+ showControls: true,+ autoRotate: true,+ envPreset: 'neutral',+ cameraPosition: null,+});++const TYPE_DEFAULTS = {+ turntable: { rotationSpeed: 0.5 },+ 'animation-gallery': { defaultClip: '', loopAll: false, showClipPicker: true },+ 'talking-agent': {+ agentName: '',+ agentTitle: 'AI Agent',+ avatar: 'embedded',+ brainProvider: 'anthropic',+ proxyURL: '',+ systemPrompt: '',+ greeting: 'Hi! Ask me anything.',+ temperature: 0.7,+ maxTurns: 20,+ skills: { speak: true, wave: true, lookAt: true, playClip: true, remember: false },+ showChatHistory: true,+ voiceInput: true,+ voiceOutput: true,+ chatPosition: 'right',+ poweredByBadge: true,+ visitorRateLimit: { msgsPerMinute: 8, msgsPerSession: 50 },+ },+ passport: {+ chain: 'base-sepolia',+ agentId: null,+ wallet: null,+ showReputation: true,+ showRecentFeedback: true,+ showValidation: false,+ showRegistrationJSON: true,+ layout: 'portrait',+ badgeSize: 'medium',+ rotationSpeed: 0.6,+ rpcURL: '',+ refreshIntervalSec: 60,+ showPoweredBy: true,+ },+ 'hotspot-tour': { hotspots: [] },+ 'pumpfun-feed': {+ kind: 'all',+ minTier: '',+ autoNarrate: true,+ maxCards: 8,+ },+};++const hexColor = z.string().regex(/^#[0-9a-fA-F]{3,8}$/, 'must be a hex color');+const cameraVec = z.tuple([z.number(), z.number(), z.number()]).nullable();+const envPreset = z.enum(['none', 'neutral', 'venice-sunset', 'footprint-court']);++const brandSchema = z.object({+ background: hexColor.default(BRAND_DEFAULTS.background),+ accent: hexColor.default(BRAND_DEFAULTS.accent),+ caption: z.string().max(280).default(BRAND_DEFAULTS.caption),+ showControls: z.boolean().default(BRAND_DEFAULTS.showControls),+ autoRotate: z.boolean().default(BRAND_DEFAULTS.autoRotate),+ envPreset: envPreset.default(BRAND_DEFAULTS.envPreset),+ cameraPosition: cameraVec.default(BRAND_DEFAULTS.cameraPosition),+});++const TYPE_SCHEMAS = {+ turntable: brandSchema.extend({+ rotationSpeed: z.number().min(0).max(10).default(0.5),+ }),+ 'animation-gallery': brandSchema.extend({+ defaultClip: z.string().max(120).default(''),+ loopAll: z.boolean().default(false),+ showClipPicker: z.boolean().default(true),+ }),+ 'talking-agent': brandSchema+ .extend({+ agentName: z.string().max(80).default(''),+ agentTitle: z.string().max(80).default('AI Agent'),+ avatar: z.enum(['embedded', 'chat-only']).default('embedded'),+ brainProvider: z.enum(['none', 'anthropic', 'custom']).default('anthropic'),+ proxyURL: z.string().url().startsWith('https://').or(z.literal('')).default(''),+ systemPrompt: z.string().max(4000).default(''),+ greeting: z.string().max(280).default('Hi! Ask me anything.'),+ temperature: z.number().min(0).max(1).default(0.7),+ maxTurns: z.number().int().min(1).max(100).default(20),+ skills: z+ .object({+ speak: z.boolean().default(true),+ wave: z.boolean().default(true),+ lookAt: z.boolean().default(true),+ playClip: z.boolean().default(true),+ remember: z.boolean().default(false),+ })+ .default({+ speak: true,+ wave: true,+ lookAt: true,+ playClip: true,+ remember: false,+ }),+ showChatHistory: z.boolean().default(true),+ voiceInput: z.boolean().default(true),+ voiceOutput: z.boolean().default(true),+ chatPosition: z.enum(['right', 'bottom', 'overlay']).default('right'),+ poweredByBadge: z.boolean().default(true),+ visitorRateLimit: z+ .object({+ msgsPerMinute: z.number().int().min(1).max(60).default(8),+ msgsPerSession: z.number().int().min(1).max(500).default(50),+ })+ .default({ msgsPerMinute: 8, msgsPerSession: 50 }),+ })+ .superRefine((cfg, ctx) => {+ if (cfg.brainProvider === 'custom' && !cfg.proxyURL) {+ ctx.addIssue({+ path: ['proxyURL'],+ code: z.ZodIssueCode.custom,+ message: 'proxyURL is required when brainProvider is "custom"',+ });+ }+ }),+ passport: brandSchema.extend({+ chain: z.string().min(1).default('base-sepolia'),+ agentId: z+ .string()+ .regex(/^\d+$/, 'agentId must be a uint256 string')+ .nullable()+ .default(null),+ wallet: z+ .string()+ .regex(/^0x[0-9a-fA-F]{40}$/)+ .nullable()+ .default(null),+ showReputation: z.boolean().default(true),+ showRecentFeedback: z.boolean().default(true),+ showValidation: z.boolean().default(false),+ showRegistrationJSON: z.boolean().default(true),+ layout: z.enum(['portrait', 'landscape', 'badge']).default('portrait'),+ badgeSize: z.enum(['small', 'medium', 'large']).default('medium'),+ rotationSpeed: z.number().min(0).max(10).default(0.6),+ rpcURL: z.string().url().startsWith('https://').or(z.literal('')).default(''),+ refreshIntervalSec: z.number().int().min(0).max(3600).default(60),+ showPoweredBy: z.boolean().default(true),+ }),+ 'hotspot-tour': brandSchema.extend({+ hotspots: z+ .array(+ z.object({+ id: z.string().min(1).max(40),+ label: z.string().min(1).max(120),+ position: z.tuple([z.number(), z.number(), z.number()]),+ body: z.string().max(2000).optional(),+ }),+ )+ .max(40)+ .default([]),+ }),+ 'pumpfun-feed': brandSchema.extend({+ kind: z.enum(['all', 'claims', 'graduations']).default('all'),+ minTier: z.enum(['', 'notable', 'influencer', 'mega']).default(''),+ autoNarrate: z.boolean().default(true),+ maxCards: z.number().int().min(1).max(50).default(8),+ }),+};++export function defaultConfig(type) {+ if (!WIDGET_TYPES[type]) throw new Error(`unknown widget type: ${type}`);+ return { ...BRAND_DEFAULTS, ...(TYPE_DEFAULTS[type] || {}) };+}++export function validateConfig(type, config) {+ const schema = TYPE_SCHEMAS[type];+ if (!schema) throw new Error(`unknown widget type: ${type}`);+ const res = schema.safeParse(config || {});+ if (!res.success) {+ const err = new Error(+ res.error.issues.map((i) => `${i.path.join('.') || 'config'}: ${i.message}`).join('; '),+ );+ err.code = 'validation_error';+ throw err;+ }+ return res.data;+}++export function isReady(type) {+ return WIDGET_TYPES[type]?.status === 'ready';+}++// Server-side counterpart — the API can validate the same way.+export const widgetTypeEnum = z.enum(WIDGET_TYPE_KEYS);+export const widgetConfigSchemas = TYPE_SCHEMAS;++// ---------------------------------------------------------------------------+// Chain registry — used by the passport widget to resolve slugs to chainIds,+// pick a public RPC, and build explorer links.+// ---------------------------------------------------------------------------++export const CHAIN_SLUGS = {+ ethereum: 1,+ optimism: 10,+ bsc: 56,+ polygon: 137,+ base: 8453,+ arbitrum: 42161,+ sepolia: 11155111,+ 'base-sepolia': 84532,+ 'optimism-sepolia': 11155420,+ 'arbitrum-sepolia': 421614,+ 'polygon-amoy': 80002,+};++export const PUBLIC_RPCS = {+ 1: 'https://eth.llamarpc.com',+ 10: 'https://mainnet.optimism.io',+ 56: 'https://bsc-dataseed.binance.org',+ 137: 'https://polygon-rpc.com',+ 8453: 'https://mainnet.base.org',+ 42161: 'https://arb1.arbitrum.io/rpc',+ 11155111: 'https://ethereum-sepolia-rpc.publicnode.com',+ 84532: 'https://sepolia.base.org',+ 11155420: 'https://sepolia.optimism.io',+ 421614: 'https://sepolia-rollup.arbitrum.io/rpc',+ 80002: 'https://rpc-amoy.polygon.technology',+};++export const EXPLORERS = {+ 1: 'https://etherscan.io',+ 10: 'https://optimistic.etherscan.io',+ 56: 'https://bscscan.com',+ 137: 'https://polygonscan.com',+ 8453: 'https://basescan.org',+ 42161: 'https://arbiscan.io',+ 11155111: 'https://sepolia.etherscan.io',+ 84532: 'https://sepolia.basescan.org',+ 11155420: 'https://sepolia-optimism.etherscan.io',+ 421614: 'https://sepolia.arbiscan.io',+ 80002: 'https://amoy.polygonscan.com',+};++/** Resolve a chain reference (slug or numeric id or numeric string) to chainId. */+export function resolveChainId(ref) {+ if (typeof ref === 'number') return ref;+ if (typeof ref !== 'string') return null;+ const slug = ref.toLowerCase();+ if (CHAIN_SLUGS[slug]) return CHAIN_SLUGS[slug];+ const n = Number(slug);+ return Number.isFinite(n) ? n : null;+}++/** Pretty display name for a chainId. */+export function chainLabel(chainId) {+ const entry = Object.entries(CHAIN_SLUGS).find(([, v]) => v === chainId);+ return entry ? entry[0] : `chain-${chainId}`;+}diff --git a/publish/src/widgets.js b/publish/src/widgets.jsnew file mode 100644index 000000000..ba2b0a037--- /dev/null+++ b/publish/src/widgets.js@@ -0,0 +1,91 @@+// Client helpers for /api/widgets. Mirrors src/account.js.+// All write calls send credentials so the session cookie travels with them.+// getWidget() is public — no credentials, so cached CDN responses can be+// shared between visitors loading the same embed URL.++const API = '';++export async function listWidgets({ limit, cursor } = {}) {+ const url = new URL(`${API}/api/widgets`, location.origin);+ if (limit) url.searchParams.set('limit', String(limit));+ if (cursor) url.searchParams.set('cursor', cursor);+ const res = await fetch(url.pathname + url.search, { credentials: 'include' });+ if (res.status === 401) throw err401();+ if (!res.ok) throw await asError(res);+ return res.json();+}++export async function getWidget(id) {+ if (!id) throw new Error('widget id required');+ const res = await fetch(`${API}/api/widgets/${encodeURIComponent(id)}`);+ if (res.status === 404) {+ const e = new Error('widget not found');+ e.code = 'not_found';+ e.status = 404;+ throw e;+ }+ if (!res.ok) throw await asError(res);+ const { widget } = await res.json();+ return widget;+}++export async function createWidget({ type, name, avatar_id, config, is_public }) {+ const data = await postJson('/api/widgets', { type, name, avatar_id, config, is_public });+ return data.widget;+}++export async function updateWidget(id, patch) {+ if (!id) throw new Error('widget id required');+ const res = await fetch(`${API}/api/widgets/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(patch),+ });+ if (res.status === 401) throw err401();+ if (!res.ok) throw await asError(res);+ const { widget } = await res.json();+ return widget;+}++export async function deleteWidget(id) {+ if (!id) throw new Error('widget id required');+ const res = await fetch(`${API}/api/widgets/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ credentials: 'include',+ });+ if (res.status === 401) throw err401();+ if (!res.ok) throw await asError(res);+ return true;+}++async function postJson(path, body) {+ const res = await fetch(`${API}${path}`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ if (res.status === 401) throw err401();+ if (!res.ok) throw await asError(res);+ return res.json();+}++async function asError(res) {+ let data = null;+ try {+ data = await res.json();+ } catch {}+ const e = new Error(data?.error_description || res.statusText || 'request failed');+ e.status = res.status;+ e.code = data?.error || 'request_failed';+ e.data = data;+ return e;+}++function err401() {+ const e = new Error('not_signed_in');+ e.status = 401;+ e.code = 'not_signed_in';+ return e;+}diff --git a/publish/src/widgets/animation-gallery.js b/publish/src/widgets/animation-gallery.jsnew file mode 100644index 000000000..3bd464cf9--- /dev/null+++ b/publish/src/widgets/animation-gallery.js@@ -0,0 +1,343 @@+/**+ * Animation Gallery Widget — a clip browser overlaid on the 3D viewer.+ *+ * Lets visitors tap through every animation clip on a rigged avatar without+ * touching dat.GUI or the full controls chrome. Supports:+ *+ * - `defaultClip` — clip name that autoplays on mount+ * - `loopAll` — chain clips in order on completion+ * - `showClipPicker` — hide the picker UI (used by parent-driven embeds)+ *+ * Parent pages can still send `widget:command` postMessages with+ * `play_clip { name }` to drive playback externally; this widget's UI and+ * external commands coexist.+ */++import { LoopOnce, LoopRepeat } from 'three';++const POLL_INTERVAL_MS = 100;+const POLL_MAX_MS = 8000;++/**+ * @param {import('../viewer.js').Viewer} viewer+ * @param {object} config Gallery config (see widget-types.js 'animation-gallery').+ * @param {HTMLElement} container Root container.+ * @returns {Promise<{ destroy: () => void }>}+ */+export async function mountAnimationGallery(viewer, config, container) {+ const state = {+ destroyed: false,+ currentAction: null,+ currentClipName: null,+ finishedHandler: null,+ panel: null,+ };++ // Turntable look-and-feel by default — autoRotate inherited from brand cfg.+ if (viewer.controls && config.autoRotate !== false) {+ viewer.controls.autoRotate = true;+ if (typeof config.rotationSpeed === 'number') {+ viewer.controls.autoRotateSpeed = config.rotationSpeed;+ }+ }++ const clips = await _waitForClips(viewer);+ if (state.destroyed) return _controller(state);+ if (!clips || clips.length === 0) {+ _renderEmpty(container);+ return _controller(state);+ }++ const cleanNames = clips.map((c) => _stripClipIndex(c.name));+ const initialIdx = _pickInitialIndex(cleanNames, config.defaultClip);++ _stopAllActions(viewer);++ if (config.showClipPicker !== false) {+ state.panel = _renderPicker(container, cleanNames, initialIdx, (idx) => {+ _playAt(viewer, clips, idx, config.loopAll, state);+ _highlight(state.panel, idx);+ });+ }++ _playAt(viewer, clips, initialIdx, config.loopAll, state);++ return _controller(state, () => {+ state.destroyed = true;+ _detachFinished(viewer, state);+ if (state.panel) state.panel.remove();+ });+}++// ─── helpers ──────────────────────────────────────────────────────────────++function _controller(state, destroyFn) {+ return {+ destroy:+ destroyFn ||+ (() => {+ state.destroyed = true;+ }),+ };+}++function _waitForClips(viewer) {+ return new Promise((resolve) => {+ const started = Date.now();+ const poll = () => {+ if (viewer?.clips?.length && viewer.mixer) {+ resolve(viewer.clips.slice());+ return;+ }+ if (Date.now() - started > POLL_MAX_MS) {+ resolve([]);+ return;+ }+ setTimeout(poll, POLL_INTERVAL_MS);+ };+ poll();+ });+}++function _stripClipIndex(name) {+ // viewer.js rewrites clip.name to "1. Original". Show the original.+ const m = /^\d+\.\s*(.*)$/.exec(name);+ return m ? m[1] : name;+}++function _pickInitialIndex(cleanNames, defaultClip) {+ if (!defaultClip) return 0;+ const i = cleanNames.findIndex((n) => n === defaultClip);+ return i >= 0 ? i : 0;+}++function _stopAllActions(viewer) {+ if (!viewer?.mixer) return;+ viewer.mixer.stopAllAction();+ const states = viewer.state?.actionStates;+ if (states) {+ for (const k of Object.keys(states)) states[k] = false;+ }+}++function _detachFinished(viewer, state) {+ if (state.finishedHandler && viewer?.mixer) {+ viewer.mixer.removeEventListener('finished', state.finishedHandler);+ state.finishedHandler = null;+ }+}++function _playAt(viewer, clips, idx, loopAll, state) {+ if (!viewer?.mixer || idx < 0 || idx >= clips.length) return;+ _detachFinished(viewer, state);+ _stopAllActions(viewer);++ const clip = clips[idx];+ const action = viewer.mixer.clipAction(clip);+ action.reset();+ action.enabled = true;+ action.setEffectiveTimeScale(1);+ action.setEffectiveWeight(1);+ action.setLoop(loopAll ? LoopOnce : LoopRepeat, loopAll ? 1 : Infinity);+ action.clampWhenFinished = false;+ action.play();++ if (viewer.state?.actionStates) {+ viewer.state.actionStates[clip.name] = true;+ }++ state.currentAction = action;+ state.currentClipName = clip.name;++ if (loopAll) {+ state.finishedHandler = () => {+ if (state.destroyed) return;+ const next = (idx + 1) % clips.length;+ _playAt(viewer, clips, next, loopAll, state);+ if (state.panel) _highlight(state.panel, next);+ };+ viewer.mixer.addEventListener('finished', state.finishedHandler);+ }++ if (viewer.invalidate) viewer.invalidate();+}++function _renderPicker(container, names, initialIdx, onSelect) {+ const panel = document.createElement('div');+ panel.className = 'anim-gallery-panel';+ panel.setAttribute('role', 'listbox');+ panel.setAttribute('aria-label', 'Animation clips');+ panel.setAttribute('aria-activedescendant', `anim-gallery-opt-${initialIdx}`);+ panel.tabIndex = 0;++ const header = document.createElement('div');+ header.className = 'anim-gallery-header';+ header.textContent = `Clips (${names.length})`;+ panel.appendChild(header);++ const list = document.createElement('ul');+ list.className = 'anim-gallery-list';++ names.forEach((name, i) => {+ const li = document.createElement('li');+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'anim-gallery-item';+ btn.id = `anim-gallery-opt-${i}`;+ btn.setAttribute('role', 'option');+ btn.dataset.idx = String(i);+ btn.textContent = name;+ if (i === initialIdx) {+ btn.classList.add('is-active');+ btn.setAttribute('aria-selected', 'true');+ }+ btn.addEventListener('click', () => onSelect(i));+ li.appendChild(btn);+ list.appendChild(li);+ });++ panel.appendChild(list);++ panel.addEventListener('keydown', (ev) => {+ const current = Number(panel.getAttribute('data-current') || initialIdx);+ let next = current;+ switch (ev.key) {+ case 'ArrowDown':+ case 'j':+ next = (current + 1) % names.length;+ break;+ case 'ArrowUp':+ case 'k':+ next = (current - 1 + names.length) % names.length;+ break;+ case 'Home':+ next = 0;+ break;+ case 'End':+ next = names.length - 1;+ break;+ case 'Enter':+ case ' ':+ onSelect(current);+ ev.preventDefault();+ return;+ default:+ return;+ }+ ev.preventDefault();+ onSelect(next);+ });++ container.appendChild(panel);+ _injectStyles();+ return panel;+}++function _highlight(panel, idx) {+ if (!panel) return;+ panel.setAttribute('data-current', String(idx));+ panel.setAttribute('aria-activedescendant', `anim-gallery-opt-${idx}`);+ panel.querySelectorAll('.anim-gallery-item').forEach((btn) => {+ const active = Number(btn.dataset.idx) === idx;+ btn.classList.toggle('is-active', active);+ btn.setAttribute('aria-selected', active ? 'true' : 'false');+ if (active) btn.scrollIntoView({ block: 'nearest' });+ });+}++function _renderEmpty(container) {+ const empty = document.createElement('div');+ empty.className = 'anim-gallery-empty';+ empty.textContent = 'No animation clips on this model.';+ container.appendChild(empty);+ _injectStyles();+}++let _stylesInjected = false;+function _injectStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.textContent = `+ .anim-gallery-panel {+ position: fixed;+ right: 16px;+ top: 16px;+ max-height: calc(100vh - 32px);+ width: 220px;+ background: rgba(10, 10, 10, 0.82);+ backdrop-filter: blur(12px);+ color: #e0e0e0;+ font-family: Inter, system-ui, sans-serif;+ border-radius: 10px;+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.35);+ z-index: 10;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .anim-gallery-header {+ padding: 10px 14px;+ font-size: 13px;+ font-weight: 600;+ letter-spacing: 0.02em;+ text-transform: uppercase;+ opacity: 0.75;+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);+ }+ .anim-gallery-list {+ list-style: none;+ margin: 0;+ padding: 6px 0;+ overflow-y: auto;+ }+ .anim-gallery-list li { margin: 0; padding: 0; }+ .anim-gallery-item {+ width: 100%;+ text-align: left;+ background: transparent;+ border: 0;+ color: inherit;+ padding: 8px 14px;+ cursor: pointer;+ font: inherit;+ font-size: 13px;+ line-height: 1.35;+ transition: background-color 120ms ease;+ }+ .anim-gallery-item:hover {+ background: rgba(255, 255, 255, 0.06);+ }+ .anim-gallery-item.is-active {+ background: rgba(139, 92, 246, 0.22);+ color: #fff;+ box-shadow: inset 3px 0 0 #8b5cf6;+ }+ .anim-gallery-item:focus-visible {+ outline: 2px solid #8b5cf6;+ outline-offset: -2px;+ }+ .anim-gallery-empty {+ position: fixed;+ right: 16px;+ top: 16px;+ padding: 10px 14px;+ background: rgba(10, 10, 10, 0.82);+ color: #aaa;+ font-family: Inter, system-ui, sans-serif;+ font-size: 13px;+ border-radius: 8px;+ z-index: 10;+ }+ @media (max-width: 520px) {+ .anim-gallery-panel {+ right: 8px;+ top: auto;+ bottom: 8px;+ width: calc(100% - 16px);+ max-height: 40vh;+ }+ }+ `;+ document.head.appendChild(style);+}diff --git a/publish/src/widgets/hotspot-tour.js b/publish/src/widgets/hotspot-tour.jsnew file mode 100644index 000000000..ed02da4b6--- /dev/null+++ b/publish/src/widgets/hotspot-tour.js@@ -0,0 +1,333 @@+/**+ * Hotspot Tour Widget — clickable points-of-interest layered over a 3D scene.+ *+ * Each hotspot is a `{ id, label, position: [x,y,z], body? }` from the widget+ * config. We render a numbered marker at the projected screen position of+ * every hotspot, update those positions per frame (so they track the camera),+ * and on click tween the camera toward the marker while a side panel reveals+ * the body text.+ *+ * Brand config (background, autoRotate, rotationSpeed, env) is applied by+ * app.js _applyWidgetConfig before this runs. We respect autoRotate but flip+ * it off while a hotspot is selected so the framing stays put.+ */++import { Vector3 } from 'three';++const POLL_INTERVAL_MS = 100;+const POLL_MAX_MS = 8000;+const FOCUS_DURATION_MS = 700;++/**+ * @param {import('../viewer.js').Viewer} viewer+ * @param {object} config Hotspot-tour config (see widget-types.js).+ * @param {HTMLElement} container Root container (usually document.body).+ * @returns {Promise<{ destroy: () => void }>}+ */+export async function mountHotspotTour(viewer, config, container) {+ const hotspots = Array.isArray(config.hotspots) ? config.hotspots : [];+ const state = {+ destroyed: false,+ layer: null,+ panel: null,+ markers: [],+ tickHook: null,+ resizeHandler: null,+ selectedId: null,+ autoRotateBefore: viewer?.controls?.autoRotate || false,+ _proj: new Vector3(),+ };++ await _waitForReady(viewer);+ if (state.destroyed) return _controller(state);++ _injectStyles();+ state.layer = _renderLayer(container);+ state.panel = _renderPanel(container, () => _clearSelection(viewer, state));++ for (const h of hotspots) {+ if (!h || !Array.isArray(h.position) || h.position.length !== 3) continue;+ const marker = _renderMarker(state.layer, h, state.markers.length + 1, () => {+ _select(viewer, state, h);+ });+ state.markers.push({ data: h, el: marker, world: new Vector3(...h.position) });+ }++ _updatePositions(viewer, state);++ state.tickHook = () => {+ if (state.destroyed) return;+ _updatePositions(viewer, state);+ };+ if (!viewer._afterAnimateHooks) viewer._afterAnimateHooks = [];+ viewer._afterAnimateHooks.push(state.tickHook);++ state.resizeHandler = () => _updatePositions(viewer, state);+ window.addEventListener('resize', state.resizeHandler);++ return _controller(state, () => {+ state.destroyed = true;+ if (state.tickHook && viewer._afterAnimateHooks) {+ const idx = viewer._afterAnimateHooks.indexOf(state.tickHook);+ if (idx !== -1) viewer._afterAnimateHooks.splice(idx, 1);+ }+ if (state.resizeHandler) {+ window.removeEventListener('resize', state.resizeHandler);+ }+ state.layer?.remove();+ state.panel?.remove();+ if (viewer?.controls) viewer.controls.autoRotate = state.autoRotateBefore;+ });+}++// ─── helpers ──────────────────────────────────────────────────────────────++function _controller(state, destroyFn) {+ return {+ destroy:+ destroyFn ||+ (() => {+ state.destroyed = true;+ }),+ };+}++function _waitForReady(viewer) {+ return new Promise((resolve) => {+ const started = Date.now();+ const poll = () => {+ if (viewer?.content && viewer.defaultCamera && viewer.controls) return resolve();+ if (Date.now() - started > POLL_MAX_MS) return resolve();+ setTimeout(poll, POLL_INTERVAL_MS);+ };+ poll();+ });+}++function _renderLayer(container) {+ const el = document.createElement('div');+ el.className = 'hotspot-layer';+ container.appendChild(el);+ return el;+}++function _renderMarker(layer, hotspot, ordinal, onClick) {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'hotspot-marker';+ btn.setAttribute('data-id', hotspot.id);+ btn.setAttribute('aria-label', hotspot.label);+ btn.title = hotspot.label;+ btn.innerHTML = `<span class="hotspot-marker-dot">${ordinal}</span><span class="hotspot-marker-label">${_escape(hotspot.label)}</span>`;+ btn.addEventListener('click', onClick);+ layer.appendChild(btn);+ return btn;+}++function _renderPanel(container, onClose) {+ const panel = document.createElement('aside');+ panel.className = 'hotspot-panel';+ panel.hidden = true;+ panel.innerHTML = `+ <button type="button" class="hotspot-panel-close" aria-label="Close">×</button>+ <h3 class="hotspot-panel-title"></h3>+ <p class="hotspot-panel-body"></p>+ `;+ panel.querySelector('.hotspot-panel-close').addEventListener('click', onClose);+ container.appendChild(panel);+ return panel;+}++function _select(viewer, state, hotspot) {+ state.selectedId = hotspot.id;++ if (viewer?.controls) viewer.controls.autoRotate = false;++ const target = new Vector3(...hotspot.position);+ const camPos = _focusPosition(viewer, target);+ if (typeof viewer._tweenCamera === 'function') {+ viewer._tweenCamera(camPos, target, FOCUS_DURATION_MS);+ } else if (viewer?.controls) {+ viewer.defaultCamera.position.copy(camPos);+ viewer.controls.target.copy(target);+ viewer.controls.update();+ viewer.invalidate?.();+ }++ state.panel.hidden = false;+ state.panel.querySelector('.hotspot-panel-title').textContent = hotspot.label;+ state.panel.querySelector('.hotspot-panel-body').textContent = hotspot.body || '';++ for (const m of state.markers) {+ m.el.classList.toggle('is-active', m.data.id === hotspot.id);+ }+}++function _clearSelection(viewer, state) {+ state.selectedId = null;+ state.panel.hidden = true;+ for (const m of state.markers) m.el.classList.remove('is-active');+ if (viewer?.controls) viewer.controls.autoRotate = state.autoRotateBefore;+}++// Pull the camera back along the line from the model centre through the+// hotspot, so the hotspot ends up roughly framed in the middle of the canvas.+function _focusPosition(viewer, hotspotPos) {+ const cam = viewer.defaultCamera;+ const center = viewer.controls?.target?.clone() || new Vector3();+ const dir = hotspotPos.clone().sub(center);+ const distFromCenter = Math.max(0.001, dir.length());+ dir.normalize();+ const camDist = cam.position.distanceTo(center);+ // Sit behind the hotspot at roughly the same orbit radius the user already had.+ return hotspotPos.clone().add(dir.multiplyScalar(Math.max(camDist - distFromCenter, 0.5)));+}++function _updatePositions(viewer, state) {+ if (!viewer?.defaultCamera || !viewer.renderer) return;+ const canvas = viewer.renderer.domElement;+ const rect = canvas.getBoundingClientRect();+ const cam = viewer.defaultCamera;++ for (const m of state.markers) {+ state._proj.copy(m.world).project(cam);+ const x = (state._proj.x * 0.5 + 0.5) * rect.width + rect.left;+ const y = (-state._proj.y * 0.5 + 0.5) * rect.height + rect.top;+ const inFront = state._proj.z < 1 && state._proj.z > -1;+ const inFrame =+ state._proj.x >= -1.05 &&+ state._proj.x <= 1.05 &&+ state._proj.y >= -1.05 &&+ state._proj.y <= 1.05;+ if (inFront && inFrame) {+ m.el.style.display = '';+ m.el.style.transform = `translate(${x}px, ${y}px)`;+ } else {+ m.el.style.display = 'none';+ }+ }+}++function _escape(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++let _stylesInjected = false;+function _injectStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.textContent = `+ .hotspot-layer {+ position: fixed;+ inset: 0;+ pointer-events: none;+ z-index: 4;+ }+ .hotspot-marker {+ position: absolute;+ top: 0;+ left: 0;+ transform: translate(-9999px, -9999px);+ margin: -14px 0 0 -14px;+ background: rgba(10, 10, 10, 0.7);+ color: #fff;+ border: 1px solid rgba(255, 255, 255, 0.18);+ border-radius: 999px;+ padding: 0 10px 0 0;+ font: 500 13px/1 Inter, system-ui, sans-serif;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ cursor: pointer;+ pointer-events: auto;+ backdrop-filter: blur(8px);+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35);+ transition: background-color 120ms ease, transform 60ms linear;+ max-width: 220px;+ white-space: nowrap;+ overflow: hidden;+ }+ .hotspot-marker:hover,+ .hotspot-marker.is-active {+ background: rgba(139, 92, 246, 0.85);+ border-color: rgba(255, 255, 255, 0.4);+ }+ .hotspot-marker-dot {+ display: grid;+ place-items: center;+ width: 28px;+ height: 28px;+ border-radius: 999px;+ background: rgba(139, 92, 246, 0.9);+ color: #fff;+ font-weight: 600;+ font-size: 12px;+ flex: 0 0 auto;+ }+ .hotspot-marker.is-active .hotspot-marker-dot {+ background: #fff;+ color: #8b5cf6;+ }+ .hotspot-marker-label {+ text-overflow: ellipsis;+ overflow: hidden;+ }+ .hotspot-panel {+ position: fixed;+ right: 16px;+ top: 16px;+ width: 280px;+ max-height: calc(100vh - 32px);+ background: rgba(10, 10, 10, 0.88);+ color: #e0e0e0;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 12px;+ padding: 16px 18px 18px;+ z-index: 6;+ font: 14px/1.5 Inter, system-ui, sans-serif;+ backdrop-filter: blur(12px);+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45);+ }+ .hotspot-panel[hidden] { display: none; }+ .hotspot-panel-close {+ position: absolute;+ top: 6px;+ right: 8px;+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.6);+ font-size: 22px;+ line-height: 1;+ cursor: pointer;+ }+ .hotspot-panel-close:hover { color: #fff; }+ .hotspot-panel-title {+ margin: 0 24px 8px 0;+ font-size: 15px;+ font-weight: 600;+ color: #fff;+ }+ .hotspot-panel-body {+ margin: 0;+ color: rgba(255, 255, 255, 0.78);+ white-space: pre-wrap;+ }+ @media (max-width: 520px) {+ .hotspot-panel {+ right: 8px;+ left: 8px;+ top: auto;+ bottom: 8px;+ width: auto;+ max-height: 40vh;+ overflow-y: auto;+ }+ .hotspot-marker { max-width: 160px; }+ }+ `;+ document.head.appendChild(style);+}diff --git a/publish/src/widgets/passport.js b/publish/src/widgets/passport.jsnew file mode 100644index 000000000..c8b2f7e2e--- /dev/null+++ b/publish/src/widgets/passport.js@@ -0,0 +1,556 @@+/**+ * ERC-8004 Passport Widget — public, read-only on-chain identity card+ * rendered alongside the 3D avatar canvas.+ *+ * Contract reads run in parallel:+ * IdentityRegistry.ownerOf(agentId) → wallet+ * IdentityRegistry.tokenURI(agentId) → registration JSON URL+ * IdentityRegistry.name()/symbol() → collection label+ * ReputationRegistry.getReputation(id) → (total, count) → average+ * ReputationRegistry event log → recent feedback (if enabled)+ * ValidationRegistry.getLatestValidation → optional proof row+ *+ * No wallet connection, no writes, no feedback submission. That's a v2 task.+ */++import { Contract, JsonRpcProvider } from 'ethers';+import {+ IDENTITY_REGISTRY_ABI,+ REPUTATION_REGISTRY_ABI,+ REGISTRY_DEPLOYMENTS,+} from '../erc8004/index.js';+import {+ CHAIN_SLUGS,+ PUBLIC_RPCS,+ EXPLORERS,+ resolveChainId,+ chainLabel,+} from '../widget-types.js';+import { resolveURI, isDecentralizedURI } from '../ipfs.js';++const CACHE_PREFIX = 'erc8004-passport:';+const STALE_TTL_MS = 1000 * 60 * 60 * 24; // 24h hard ceiling on stale cache++/**+ * Mount the passport widget.+ *+ * @param {import('../viewer.js').Viewer} viewer The three.js viewer instance.+ * @param {object} config Passport config (see widget-types.js passport schema).+ * @param {HTMLElement} container Root container. The widget takes this over.+ * @param {string} [widgetId] Optional cache-busting key.+ * @returns {Promise<{ destroy: () => void }>}+ */+export async function mountPassport(viewer, config, container, widgetId) {+ const state = {+ config,+ widgetId: widgetId || `${config.chain}:${config.agentId}`,+ cacheKey: `${CACHE_PREFIX}${config.chain}:${config.agentId}`,+ chainId: resolveChainId(config.chain),+ data: null,+ lastVerifiedAt: null,+ destroyed: false,+ pollTimer: null,+ visibilityHandler: null,+ };++ _applyTurntable(viewer, config);+ _kioskifyCanvas(viewer, container);++ const panel = document.createElement('div');+ panel.className = `passport-panel passport-layout--${config.layout} passport-badge-size--${config.badgeSize}`;+ container.appendChild(panel);++ const root = container;+ root.classList.add('passport-widget', `passport-root--${config.layout}`);++ _renderLoading(panel, config);++ // Hydrate from cache immediately so the panel has content before RPC responds.+ const cached = _readCache(state.cacheKey);+ if (cached && cached.data) {+ state.data = cached.data;+ state.lastVerifiedAt = cached.savedAt;+ _render(panel, state);+ }++ await _refresh(state, panel);++ if (config.refreshIntervalSec > 0) {+ const tick = () => {+ if (state.destroyed) return;+ if (document.hidden) return;+ _refresh(state, panel).catch(() => {+ /* keep stale */+ });+ };+ state.pollTimer = setInterval(tick, config.refreshIntervalSec * 1000);++ state.visibilityHandler = () => {+ if (!document.hidden) tick();+ };+ document.addEventListener('visibilitychange', state.visibilityHandler);+ }++ return {+ destroy() {+ state.destroyed = true;+ if (state.pollTimer) clearInterval(state.pollTimer);+ if (state.visibilityHandler) {+ document.removeEventListener('visibilitychange', state.visibilityHandler);+ }+ panel.remove();+ root.classList.remove('passport-widget', `passport-root--${config.layout}`);+ },+ };+}++// ---------------------------------------------------------------------------+// RPC + contract reads+// ---------------------------------------------------------------------------++function _pickRpc(config, chainId) {+ if (config.rpcURL) {+ // Require HTTPS per the security spec.+ if (!/^https:\/\//i.test(config.rpcURL)) {+ console.warn('[passport] ignoring non-HTTPS rpcURL');+ } else {+ return config.rpcURL;+ }+ }+ return PUBLIC_RPCS[chainId] || null;+}++async function _refresh(state, panel) {+ const { config, chainId } = state;++ if (!chainId) {+ _renderError(panel, `Unknown chain "${config.chain}".`, state);+ return;+ }+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment || !deployment.identityRegistry) {+ _renderError(panel, `No ERC-8004 registry deployed on ${chainLabel(chainId)}.`, state);+ return;+ }+ if (!config.agentId) {+ _renderError(panel, 'No agent id configured.', state);+ return;+ }+ if (!/^\d+$/.test(String(config.agentId))) {+ _renderError(panel, 'Invalid agent id.', state);+ return;+ }++ const rpcURL = _pickRpc(config, chainId);+ if (!rpcURL) {+ _renderError(panel, `No RPC available for ${chainLabel(chainId)}.`, state);+ return;+ }++ try {+ const provider = new JsonRpcProvider(rpcURL, chainId, { staticNetwork: true });+ const identity = new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);+ const reputation = deployment.reputationRegistry+ ? new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider)+ : null;++ const agentId = BigInt(config.agentId);++ // ownerOf will revert for non-existent tokens; catch that specifically.+ const [ownerRes, tokenURIRes, nameRes, symbolRes, repRes] = await Promise.allSettled([+ identity.ownerOf(agentId),+ identity.tokenURI(agentId),+ identity.name(),+ identity.symbol(),+ reputation && config.showReputation+ ? reputation.getReputation(agentId)+ : Promise.resolve(null),+ ]);++ if (ownerRes.status === 'rejected') {+ _renderError(panel, 'Agent not found on this chain.', state);+ return;+ }++ const wallet = ownerRes.value;+ const tokenURI = tokenURIRes.status === 'fulfilled' ? tokenURIRes.value : '';+ const name = nameRes.status === 'fulfilled' ? nameRes.value : '';+ const symbol = symbolRes.status === 'fulfilled' ? symbolRes.value : '';+ let reputationData = null;+ if (repRes.status === 'fulfilled' && repRes.value) {+ const [total, count] = repRes.value;+ const n = Number(count);+ const t = Number(total);+ reputationData = { total: t, count: n, average: n === 0 ? 0 : t / n };+ }++ let feedback = [];+ if (reputation && config.showRecentFeedback) {+ feedback = await _fetchRecentFeedback(reputation, agentId, provider).catch(() => []);+ }++ let manifest = null;+ if (tokenURI) {+ manifest = await _fetchManifest(tokenURI).catch(() => null);+ }++ state.data = {+ wallet,+ tokenURI,+ name,+ symbol,+ reputation: reputationData,+ feedback,+ manifest,+ };+ state.lastVerifiedAt = Date.now();++ _writeCache(state.cacheKey, { data: state.data, savedAt: state.lastVerifiedAt });+ _render(panel, state);+ } catch (err) {+ console.warn('[passport] refresh failed:', err.message || err);+ // Leave whatever stale data we had; update the status label.+ _render(panel, state, { staleReason: 'RPC error' });+ }+}++/**+ * Query the last N ReputationSubmitted events for this agent.+ * Scoped to the recent history to avoid full-log scans.+ */+async function _fetchRecentFeedback(contract, agentId, provider) {+ const latest = await provider.getBlockNumber();+ const LOOKBACK = 200_000;+ const fromBlock = Math.max(0, latest - LOOKBACK);+ const filter = contract.filters.ReputationSubmitted(agentId);+ const events = await contract.queryFilter(filter, fromBlock, latest);+ return events+ .slice(-5)+ .reverse()+ .map((ev) => ({+ from: ev.args.submitter,+ score: Number(ev.args.score),+ comment: _sanitizeText(ev.args.comment || ''),+ txHash: ev.transactionHash,+ }));+}++async function _fetchManifest(tokenURI) {+ const resolved = isDecentralizedURI(tokenURI) ? resolveURI(tokenURI) : tokenURI;+ if (!/^https?:\/\//i.test(resolved)) return null;+ const res = await fetch(resolved, { mode: 'cors' });+ if (!res.ok) throw new Error(`manifest fetch ${res.status}`);+ const ct = res.headers.get('content-type') || '';+ if (!ct.includes('json') && !resolved.endsWith('.json')) {+ // Only fetch JSON — never render tokenURI HTML.+ return null;+ }+ const json = await res.json();+ return _pickManifestFields(json);+}++/** Allow-list the fields we render. Drop everything else. */+function _pickManifestFields(raw) {+ if (!raw || typeof raw !== 'object') return null;+ return {+ name: typeof raw.name === 'string' ? raw.name.slice(0, 120) : '',+ description: typeof raw.description === 'string' ? raw.description.slice(0, 500) : '',+ image: typeof raw.image === 'string' ? raw.image : '',+ agentRegistry: typeof raw.agentRegistry === 'string' ? raw.agentRegistry.slice(0, 200) : '',+ };+}++// ---------------------------------------------------------------------------+// Rendering+// ---------------------------------------------------------------------------++function _renderLoading(panel, config) {+ panel.innerHTML = `+ <div class="passport-card" role="status">+ <div class="passport-skeleton">+ <div class="passport-skeleton-row"></div>+ <div class="passport-skeleton-row short"></div>+ <div class="passport-skeleton-row"></div>+ </div>+ <span class="passport-loading-label">Loading on-chain identity…</span>+ </div>+ ${config.showPoweredBy ? _poweredByHTML(config) : ''}+ `;+}++function _renderError(panel, message, state) {+ const { config } = state;+ panel.innerHTML = `+ <div class="passport-card passport-card--error" role="alert">+ <div class="passport-error-icon" aria-hidden="true">!</div>+ <div class="passport-error-msg">${_escapeHTML(message)}</div>+ </div>+ ${config.showPoweredBy ? _poweredByHTML(config) : ''}+ `;+}++function _render(panel, state, opts = {}) {+ const { config, chainId, data, lastVerifiedAt } = state;+ if (!data) {+ // No data and no error path yet — leave whatever's up.+ return;+ }++ const explorer = EXPLORERS[chainId] || '';+ const walletShort = _shortAddr(data.wallet);+ const agentName = data.manifest?.name || data.name || `Agent #${config.agentId}`;+ const verifiedISO = lastVerifiedAt ? new Date(lastVerifiedAt).toISOString() : '';+ const verifiedRel = lastVerifiedAt ? _relativeTime(lastVerifiedAt) : '';+ const stale = Boolean(opts.staleReason);++ const repBlock =+ config.showReputation && data.reputation+ ? `+ <div class="passport-row passport-row--reputation">+ <span class="passport-star" aria-hidden="true">★</span>+ <span class="passport-rep-avg">${data.reputation.count === 0 ? '—' : data.reputation.average.toFixed(2)}</span>+ <span class="passport-rep-count">(${data.reputation.count} ${data.reputation.count === 1 ? 'review' : 'reviews'})</span>+ </div>+ `+ : '';++ const feedbackBlock =+ config.showRecentFeedback && data.feedback && data.feedback.length+ ? `+ <div class="passport-section passport-section--feedback">+ <div class="passport-section-title">Recent feedback</div>+ <ul class="passport-feedback-list">+ ${data.feedback+ .map(+ (f) => `+ <li class="passport-feedback-item">+ <span class="passport-feedback-comment">${_escapeHTML(f.comment || '—')}</span>+ <span class="passport-feedback-meta">${_shortAddr(f.from)} · ${f.score}★</span>+ </li>+ `,+ )+ .join('')}+ </ul>+ </div>+ `+ : '';++ const jsonBlock =+ config.showRegistrationJSON && data.tokenURI+ ? `+ <div class="passport-section passport-section--json">+ <a class="passport-json-link" href="${_escapeAttr(_resolveForLink(data.tokenURI))}" target="_blank" rel="noopener noreferrer">+ View passport JSON ↗+ </a>+ </div>+ `+ : '';++ const explorerLink = explorer+ ? `+ <a class="passport-explorer-link" href="${_escapeAttr(`${explorer}/address/${data.wallet}`)}" target="_blank" rel="noopener noreferrer" title="View on explorer">↗</a>+ `+ : '';++ const chainSlug = chainLabel(chainId);++ const staleBanner = stale+ ? `+ <div class="passport-stale">Offline · last verified ${_escapeHTML(verifiedRel)}</div>+ `+ : '';++ if (config.layout === 'badge') {+ panel.innerHTML = `+ <div class="passport-badge" role="group" aria-label="ERC-8004 Passport">+ <div class="passport-badge-name" title="${_escapeAttr(agentName)}">${_escapeHTML(agentName)}</div>+ <div class="passport-badge-line">+ <span class="passport-badge-id">#${_escapeHTML(String(config.agentId))}</span>+ <span class="passport-badge-sep">·</span>+ <span class="passport-badge-chain">${_escapeHTML(chainSlug)}</span>+ <span class="passport-badge-check" aria-label="Registered on-chain">✓</span>+ </div>+ ${+ config.showReputation && data.reputation+ ? `+ <div class="passport-badge-rep">+ <span class="passport-star" aria-hidden="true">★</span>+ ${data.reputation.count === 0 ? '—' : data.reputation.average.toFixed(2)}+ </div>+ `+ : ''+ }+ ${staleBanner}+ </div>+ ${config.showPoweredBy ? _poweredByHTML(config) : ''}+ `;+ return;+ }++ panel.innerHTML = `+ <div class="passport-card">+ <div class="passport-header">+ <div class="passport-name">${_escapeHTML(agentName)}</div>+ <div class="passport-check" aria-label="Registered on-chain" title="Registered on-chain">✓</div>+ </div>+ <div class="passport-subhead">+ <span class="passport-id">Agent #${_escapeHTML(String(config.agentId))}</span>+ <span class="passport-sep">·</span>+ <span class="passport-chain">${_escapeHTML(chainSlug)}</span>+ </div>+ <div class="passport-wallet-row">+ <button type="button" class="passport-wallet" data-copy="${_escapeAttr(data.wallet)}" title="Copy ${_escapeAttr(data.wallet)}">+ ${_escapeHTML(walletShort)}+ </button>+ ${explorerLink}+ </div>+ ${repBlock}+ ${feedbackBlock}+ ${jsonBlock}+ ${+ lastVerifiedAt+ ? `+ <div class="passport-verified" title="${_escapeAttr(verifiedISO)}">+ ${stale ? 'Last verified' : 'Verified'} ${_escapeHTML(verifiedRel)}+ </div>+ `+ : ''+ }+ </div>+ ${config.showPoweredBy ? _poweredByHTML(config) : ''}+ `;++ const copyBtn = panel.querySelector('.passport-wallet[data-copy]');+ if (copyBtn) {+ copyBtn.addEventListener('click', () => {+ const addr = copyBtn.dataset.copy;+ if (!addr) return;+ navigator.clipboard+ ?.writeText(addr)+ .then(() => {+ copyBtn.classList.add('passport-wallet--copied');+ setTimeout(() => copyBtn.classList.remove('passport-wallet--copied'), 1200);+ })+ .catch(() => {+ /* ignore */+ });+ });+ }+}++function _poweredByHTML(_config) {+ return `+ <a class="passport-powered-by" href="https://three.ws/" target="_blank" rel="noopener noreferrer">+ 3dagent+ </a>+ `;+}++// ---------------------------------------------------------------------------+// Viewer setup+// ---------------------------------------------------------------------------++function _applyTurntable(viewer, config) {+ if (!viewer || !viewer.controls) return;+ if (config.autoRotate === false) return;+ viewer.state.autoRotate = true;+ viewer.controls.autoRotate = true;+ viewer.controls.autoRotateSpeed = (config.rotationSpeed ?? 0.6) * 4;+ viewer.invalidate?.();+}++function _kioskifyCanvas(_viewer, container) {+ // Reduce viewer chrome for embed contexts.+ const validator = document.querySelector('.validator-toggle');+ if (validator) validator.style.display = 'none';+ const header = document.querySelector('header');+ if (header) header.style.display = 'none';+ container.classList.add('passport-canvas-host');+}++// ---------------------------------------------------------------------------+// Cache+// ---------------------------------------------------------------------------++function _readCache(key) {+ try {+ const raw = localStorage.getItem(key);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (!parsed?.savedAt) return null;+ if (Date.now() - parsed.savedAt > STALE_TTL_MS) return null;+ return parsed;+ } catch {+ return null;+ }+}++function _writeCache(key, payload) {+ try {+ // Wallet & tokenURI are strings. Only persist serialisable fields.+ const safe = {+ savedAt: payload.savedAt,+ data: {+ wallet: payload.data.wallet,+ tokenURI: payload.data.tokenURI,+ name: payload.data.name,+ symbol: payload.data.symbol,+ reputation: payload.data.reputation,+ feedback: payload.data.feedback,+ manifest: payload.data.manifest,+ },+ };+ localStorage.setItem(key, JSON.stringify(safe));+ } catch {+ /* quota / privacy mode — ignore */+ }+}++// ---------------------------------------------------------------------------+// Utilities+// ---------------------------------------------------------------------------++function _shortAddr(addr) {+ if (!addr || typeof addr !== 'string') return '';+ if (addr.length < 12) return addr;+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}++function _escapeHTML(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++function _escapeAttr(s) {+ return _escapeHTML(s);+}++function _sanitizeText(s) {+ // Strip anything that looks like a tag. Feedback is plain text.+ return String(s ?? '')+ .replace(/<[^>]*>/g, '')+ .slice(0, 500);+}++function _relativeTime(ts) {+ const diff = Date.now() - ts;+ const sec = Math.floor(diff / 1000);+ if (sec < 60) return 'just now';+ const min = Math.floor(sec / 60);+ if (min < 60) return `${min}m ago`;+ const hr = Math.floor(min / 60);+ if (hr < 24) return `${hr}h ago`;+ const day = Math.floor(hr / 24);+ return `${day}d ago`;+}++function _resolveForLink(uri) {+ return isDecentralizedURI(uri) ? resolveURI(uri) : uri;+}++// Re-export for Studio later.+export { CHAIN_SLUGS };diff --git a/publish/src/widgets/pumpfun-feed.js b/publish/src/widgets/pumpfun-feed.jsnew file mode 100644index 000000000..60ae66b63--- /dev/null+++ b/publish/src/widgets/pumpfun-feed.js@@ -0,0 +1,212 @@+/**+ * Pump.fun Live Feed Widget+ *+ * DOM overlay on top of the 3D viewer. Subscribes to /api/agents/pumpfun-feed+ * (SSE) and renders a stack of cards. When `autoNarrate` is on, the agent+ * narrates each event through the existing protocol bus — speak + emote+ * routed through the Empathy Layer (see src/CLAUDE.md "Empathy Layer").+ *+ * Config (validated in widget-types.js):+ * - kind 'all' | 'claims' | 'graduations'+ * - minTier '' | 'notable' | 'influencer' | 'mega'+ * - autoNarrate boolean+ * - maxCards 1..50+ */++const FEED_PATH = '/api/agents/pumpfun-feed';+const TIER_BADGE = { mega: '🔥🔥', influencer: '🔥', notable: '⭐' };++/**+ * @param {import('../viewer.js').Viewer} viewer+ * @param {object} config+ * @param {HTMLElement} container parent element to attach the overlay to+ * @param {{ protocol?: any }} [ctx]+ */+export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {+ const root = document.createElement('div');+ root.className = 'pumpfun-feed';+ root.style.cssText = [+ 'position:absolute',+ 'right:16px',+ 'top:16px',+ 'width:320px',+ 'max-height:80%',+ 'overflow-y:auto',+ 'pointer-events:auto',+ 'z-index:5',+ 'font-family:ui-sans-serif,system-ui,-apple-system,sans-serif',+ 'color:#fff',+ ].join(';');+ (container || document.body).appendChild(root);++ const status = document.createElement('div');+ status.style.cssText = 'opacity:0.6;font-size:12px;padding:4px 8px';+ status.textContent = 'Connecting to pump.fun feed…';+ root.appendChild(status);++ const stack = document.createElement('div');+ root.appendChild(stack);++ const params = new URLSearchParams();+ params.set('kind', config.kind || 'all');+ if (config.minTier) params.set('minTier', config.minTier);++ const es = new EventSource(`${FEED_PATH}?${params.toString()}`, {+ withCredentials: true,+ });++ const maxCards = Math.max(1, Math.min(50, config.maxCards || 8));+ const protocol = ctx.protocol || (typeof window !== 'undefined' ? window.VIEWER?.agent_protocol : null);+ let narrateOn = config.autoNarrate !== false;++ const onNarrateToggle = (e) => {+ narrateOn = !!e.detail?.on;+ };+ (container || document.body).addEventListener('pumpfun-feed:set-narrate', onNarrateToggle);++ let focusMint = null;+ const matchesFocus = (ev) =>+ !focusMint || ev?.mint === focusMint || ev?.token_mint === focusMint;++ const onFocus = (e) => {+ focusMint = e.detail?.mint || null;+ // Mark visually when a filter is active.+ status.textContent = focusMint+ ? `Live · pump.fun · ${focusMint.slice(0, 6)}…${focusMint.slice(-4)}`+ : 'Live · pump.fun';+ // Highlight: pulse the badge once.+ status.style.transition = 'color .2s';+ status.style.color = focusMint ? '#6ce0c8' : '';+ };+ (container || document.body).addEventListener('pumpfun-feed:focus-mint', onFocus);++ es.addEventListener('open', () => {+ status.textContent = focusMint+ ? `Live · pump.fun · ${focusMint.slice(0, 6)}…${focusMint.slice(-4)}`+ : 'Live · pump.fun';+ });++ es.addEventListener('claim', (msg) => {+ const ev = safeJson(msg.data);+ if (!ev) return;+ if (!matchesFocus(ev)) return;+ addCard(stack, renderClaim(ev), maxCards);+ if (narrateOn) narrateClaim(protocol, ev);+ });++ es.addEventListener('graduation', (msg) => {+ const ev = safeJson(msg.data);+ if (!ev) return;+ if (!matchesFocus(ev)) return;+ addCard(stack, renderGraduation(ev), maxCards);+ if (narrateOn) narrateGraduation(protocol, ev);+ });++ es.addEventListener('error', () => {+ if (es.readyState === EventSource.CLOSED) {+ status.textContent = 'Disconnected.';+ }+ });++ es.addEventListener('close', () => {+ status.textContent = 'Reconnecting…';+ });++ return {+ destroy() {+ try {+ es.close();+ } catch {}+ (container || document.body).removeEventListener('pumpfun-feed:focus-mint', onFocus);+ (container || document.body).removeEventListener('pumpfun-feed:set-narrate', onNarrateToggle);+ root.remove();+ },+ };+}++function addCard(stack, el, max) {+ stack.prepend(el);+ while (stack.children.length > max) stack.lastChild?.remove();+}++function renderClaim(ev) {+ const el = document.createElement('div');+ el.style.cssText = cardStyle(ev.fake_claim ? '#3a1418' : ev.first_time_claim ? '#0d2d1a' : '#161616');+ const tier = ev.tier ? `${TIER_BADGE[ev.tier] || ''} ${ev.tier}` : '';+ const sol = ev.amount_sol != null ? `${Number(ev.amount_sol).toFixed(3)} SOL` : '';+ el.innerHTML = `+ <div style="display:flex;justify-content:space-between;font-size:11px;opacity:0.7">+ <span>${ev.first_time_claim ? '🚨 FIRST CLAIM' : 'Claim'}</span>+ <span>${tier}</span>+ </div>+ <div style="font-weight:600;margin-top:4px">${escapeHtml(ev.github_user ? '@' + ev.github_user : ev.claimer || '—')}</div>+ <div style="font-size:12px;opacity:0.85">${sol}${ev.token_symbol ? ' · $' + escapeHtml(ev.token_symbol) : ''}</div>+ ${ev.ai_take ? `<div style="font-size:11px;opacity:0.75;margin-top:4px;font-style:italic">${escapeHtml(ev.ai_take)}</div>` : ''}+ `;+ return el;+}++function renderGraduation(ev) {+ const el = document.createElement('div');+ el.style.cssText = cardStyle('#1a1632');+ el.innerHTML = `+ <div style="font-size:11px;opacity:0.7">🎓 Graduation</div>+ <div style="font-weight:600;margin-top:4px">${escapeHtml(ev.name || ev.symbol || ev.mint)}</div>+ ${ev.symbol ? `<div style="font-size:12px;opacity:0.85">$${escapeHtml(ev.symbol)}</div>` : ''}+ `;+ return el;+}++function cardStyle(bg) {+ return [+ `background:${bg}`,+ 'border:1px solid rgba(255,255,255,0.08)',+ 'border-radius:8px',+ 'padding:10px 12px',+ 'margin-bottom:6px',+ 'box-shadow:0 2px 6px rgba(0,0,0,0.3)',+ ].join(';');+}++function narrateClaim(protocol, ev) {+ if (!protocol) return;+ if (ev.first_time_claim) {+ protocol.emit({ type: 'emote', payload: { trigger: 'celebration', weight: 0.9 } });+ protocol.emit({+ type: 'speak',+ payload: {+ text: `First-time claim: ${ev.github_user ? '@' + ev.github_user : 'unknown'}${ev.ai_take ? ' — ' + ev.ai_take : ''}`,+ sentiment: 0.7,+ },+ });+ } else if (ev.fake_claim) {+ protocol.emit({ type: 'emote', payload: { trigger: 'concern', weight: 0.7 } });+ protocol.emit({+ type: 'speak',+ payload: { text: `Fake claim from ${ev.github_user || ev.claimer}.`, sentiment: -0.5 },+ });+ } else if (ev.tier === 'mega' || ev.tier === 'influencer') {+ protocol.emit({ type: 'emote', payload: { trigger: 'curiosity', weight: 0.5 } });+ }+}++function narrateGraduation(protocol, ev) {+ if (!protocol) return;+ protocol.emit({ type: 'gesture', payload: { name: 'wave', duration: 1500 } });+ protocol.emit({+ type: 'speak',+ payload: { text: `Graduation: ${ev.symbol || ev.name || 'a token'} hit PumpAMM.`, sentiment: 0.6 },+ });+}++function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++function safeJson(s) {+ try {+ return JSON.parse(s);+ } catch {+ return null;+ }+}diff --git a/publish/src/widgets/talking-agent.js b/publish/src/widgets/talking-agent.jsnew file mode 100644index 000000000..42c807ef5--- /dev/null+++ b/publish/src/widgets/talking-agent.js@@ -0,0 +1,171 @@+/**+ * Talking Agent Widget — embodied chat panel wired to /api/widgets/:id/chat.+ *+ * The chat endpoint owns brain dispatch (Anthropic / custom proxy / none) plus+ * visitor rate limiting, so the widget never sees an API key. We post the+ * visitor's turn + history, parse the SSE response for { reply, actions }, and+ * surface actions on the SceneController (wave / lookAt / playClip / remember).+ *+ * Action shape from the endpoint (camelCase, single layer):+ * { type: 'wave' }+ * { type: 'lookAt', target: 'user'|'camera'|'model' }+ * { type: 'playClip', name: '<clip-name>' }+ * { type: 'remember', content: '<note>' }+ */++import { NichAgent } from '../nich-agent.js';+import { ACTION_TYPES } from '../agent-protocol.js';++/**+ * @param {import('../viewer.js').Viewer} viewer+ * @param {object} config Talking-agent config (see widget-types.js).+ * @param {HTMLElement} container Root container (usually document.body).+ * @param {{+ * widgetId: string,+ * getSceneCtrl: () => (import('../runtime/scene.js').SceneController|null),+ * protocol?: import('../agent-protocol.js').AgentProtocol,+ * identity?: import('../agent-identity.js').AgentIdentity,+ * }} ctx+ * @returns {Promise<{ destroy: () => void }>}+ */+export async function mountTalkingAgent(viewer, config, container, ctx) {+ const { widgetId, getSceneCtrl, protocol = null, identity = null } = ctx || {};+ const isPreview = !widgetId;++ const history = [];+ let destroyed = false;++ const agent = new NichAgent(container, protocol, null, identity, null, {+ layout: 'embedded',+ position: config.chatPosition || 'right',+ greeting: config.greeting || 'Hi! Ask me anything.',+ title: config.agentName || undefined,+ theme: { accent: config.accent, background: config.background, caption: config.caption },+ showPoweredBy: config.poweredByBadge !== false,+ voiceInput: config.voiceInput !== false,+ voiceOutput: config.voiceOutput !== false,+ skipDefaultListeners: true,+ onSend: async (text) => {+ if (isPreview) {+ return { reply: 'Preview mode — save your widget to enable live chat.' };+ }+ try {+ const result = await dispatchChat(widgetId, text, history.slice(-20));+ if (result.reply) {+ history.push({ role: 'user', content: text });+ history.push({ role: 'assistant', content: result.reply });+ }+ queueMicrotask(() => runActions(result.actions, getSceneCtrl, protocol));+ return { reply: result.reply, error: result.error };+ } catch (err) {+ console.warn('[talking-agent] chat dispatch failed', err.message);+ return { error: 'Chat is unavailable right now.' };+ }+ },+ });++ return {+ destroy() {+ if (destroyed) return;+ destroyed = true;+ try {+ agent.panel?.remove();+ agent.toggleBtn?.remove();+ } catch {}+ },+ };+}++// ── SSE round-trip ─────────────────────────────────────────────────────────++async function dispatchChat(widgetId, message, history) {+ const res = await fetch(`/api/widgets/${encodeURIComponent(widgetId)}/chat`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ body: JSON.stringify({ message, history }),+ });++ if (res.status === 429) {+ const data = await res.json().catch(() => ({}));+ const wait = data.retry_after ? ` Try again in ${data.retry_after}s.` : '';+ return { reply: '', actions: [], error: `Slow down a moment.${wait}` };+ }+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ return { reply: '', actions: [], error: data.error_description || 'Chat backend error.' };+ }++ const text = await res.text();+ return parseSse(text);+}++function parseSse(text) {+ let reply = '';+ const actions = [];+ let error = null;+ for (const block of text.split(/\n\n+/)) {+ if (!block.trim()) continue;+ let event = 'message';+ let data = '';+ for (const line of block.split('\n')) {+ if (line.startsWith('event:')) event = line.slice(6).trim();+ else if (line.startsWith('data:')) data += line.slice(5).trim();+ }+ if (!data) continue;+ let payload;+ try {+ payload = JSON.parse(data);+ } catch {+ continue;+ }+ if (event === 'message') {+ if (typeof payload.reply === 'string') reply += payload.reply;+ if (Array.isArray(payload.actions)) actions.push(...payload.actions);+ } else if (event === 'error') {+ error = payload.message || 'Chat backend error.';+ }+ }+ return { reply, actions, error };+}++// ── Action dispatch ────────────────────────────────────────────────────────++function runActions(actions, getSceneCtrl, protocol) {+ if (!Array.isArray(actions) || !actions.length) return;+ const sceneCtrl = getSceneCtrl?.();+ for (const action of actions) {+ if (!action || typeof action.type !== 'string') continue;+ try {+ runOne(action, sceneCtrl, protocol);+ } catch (err) {+ console.warn('[talking-agent] action failed', action.type, err.message);+ }+ }+}++function runOne(action, sceneCtrl, protocol) {+ switch (action.type) {+ case 'wave':+ sceneCtrl?.playAnimationByHint?.('wave', { duration: 1500 });+ return;+ case 'lookAt': {+ const target = action.target === 'model' ? 'center' : action.target;+ sceneCtrl?.lookAt?.(target);+ return;+ }+ case 'playClip':+ if (typeof action.name === 'string') sceneCtrl?.playClipByName?.(action.name);+ return;+ case 'remember':+ if (protocol && typeof action.content === 'string') {+ protocol.emit({+ type: ACTION_TYPES.REMEMBER,+ payload: { type: 'user', content: action.content },+ });+ }+ return;+ default:+ console.warn('[talking-agent] unknown action type:', action.type);+ }+}diff --git a/publish/src/widgets/turntable.js b/publish/src/widgets/turntable.jsnew file mode 100644index 000000000..d904a09d8--- /dev/null+++ b/publish/src/widgets/turntable.js@@ -0,0 +1,52 @@+/**+ * Turntable Showcase Widget — chromeless hero banner.+ *+ * Brand config (background, env, autoRotate, rotationSpeed, cameraPosition)+ * is applied by app.js _applyWidgetConfig before this runs. The mount+ * handler's job is just to:+ *+ * - frame the avatar nicely so it's centered in the viewport+ * - guarantee autoRotate is on (config can opt-out by passing false)+ * - apply rotationSpeed (default 0.5)+ *+ * No DOM, no chrome, no controls.+ */++const POLL_INTERVAL_MS = 100;+const POLL_MAX_MS = 8000;++/**+ * @param {import('../viewer.js').Viewer} viewer+ * @param {object} config Turntable config (see widget-types.js 'turntable').+ * @returns {Promise<{ destroy: () => void }>}+ */+export async function mountTurntable(viewer, config) {+ const speed = typeof config.rotationSpeed === 'number' ? config.rotationSpeed : 0.5;+ if (viewer?.controls) {+ viewer.controls.autoRotate = config.autoRotate !== false;+ viewer.controls.autoRotateSpeed = speed;+ }++ await _waitForContent(viewer);+ if (viewer?.frameContent && viewer.content) {+ viewer.frameContent({ animate: false });+ }++ return {+ destroy() {+ if (viewer?.controls) viewer.controls.autoRotate = false;+ },+ };+}++function _waitForContent(viewer) {+ return new Promise((resolve) => {+ const started = Date.now();+ const poll = () => {+ if (viewer?.content) return resolve();+ if (Date.now() - started > POLL_MAX_MS) return resolve();+ setTimeout(poll, POLL_INTERVAL_MS);+ };+ poll();+ });+}