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(a2a): a2a call + mandate endpoints, agent-3d shared module, vanity + login refinements
nirholas1fe8b9a8c2ed
diff --git a/api/_lib/agent-delegate.js b/api/_lib/agent-delegate.jsindex bed49fae1..09f8212ee 100644--- a/api/_lib/agent-delegate.js+++ b/api/_lib/agent-delegate.js@@ -42,6 +42,10 @@ export async function runAgentDelegation({ toAgentId, message }) {user: message,maxTokens: 1024,anthropicModel: model,+ // Lead with the agent's chosen Claude model on the platform key, then+ // degrade to the free providers if it's unset or Anthropic is down.+ serverAnthropic: true,+ track: { agentId: toAgentId, tool: 'agent.delegate' },});return { response: result.text, agentId: toAgentId, model: result.model };}diff --git a/api/agents/a2a-call.js b/api/agents/a2a-call.jsnew file mode 100644index 000000000..b4183d914--- /dev/null+++ b/api/agents/a2a-call.js@@ -0,0 +1,226 @@+// POST /api/agents/a2a-call — autonomous, mandate-authorized agent-to-agent payment.+//+// This is the load-bearing piece of agent-to-agent commerce: it lets one of the+// caller's agents discover a peer's paid A2A skill, pay for it under a signed+// Intent Mandate, and return the peer's result — without a human approving each+// individual payment. Safety comes from three gates, all enforced here before a+// single token moves:+//+// 1. Mandate signature + per-call policy (mandate.js): is this spend authorized+// at all, on this network, to this peer, in this currency, under the per-call cap?+// 2. Cumulative budget (spend-ledger.js): would this push lifetime spend under+// the mandate over its total cap? Reserved atomically, released on failure.+// 3. Reputation (reputation-gate.js): does the peer clear the caller's ERC-8004+// trust bar? Opt-in per call.+//+// Settlement itself reuses the existing A2A x402 client (api/_lib/x402/a2a-client.js)+// so this inherits the spec-compliant two-leg handshake and EIP-3009 signing.++import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, rateLimited, readJson, respondError, wrap } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';+import { assertMandateAllows, MandateError, verifyIntentMandate } from '../_lib/a2a/mandate.js';+import { release, reserve } from '../_lib/a2a/spend-ledger.js';+import { assertReputationOk, ReputationError } from '../_lib/a2a/reputation-gate.js';+import {+ A2AClientError,+ buildEvmExactPayload,+ createPrivateKeySigner,+ requestQuote,+ submitPayment,+} from '../_lib/x402/a2a-client.js';++const DEFAULT_NETWORK_PREFERENCE = ['eip155:8453', 'eip155:84532', 'eip155:1'];++// Choose the accept entry to pay against, honoring the caller's network+// preference and only ever picking an EVM `exact` scheme (what the client signs).+function pickAccept(accepts, preference) {+ const order = preference?.length ? preference : DEFAULT_NETWORK_PREFERENCE;+ for (const net of order) {+ const match = accepts.find((a) => a.network === net && a.scheme === 'exact');+ if (match) return match;+ }+ for (const a of accepts) {+ if (a.scheme === 'exact' && /^eip155:\d+$/.test(a.network)) return a;+ }+ throw new A2AClientError(+ 'no_supported_accept',+ 'peer offered no supported (scheme=exact, EVM) accept entry',+ { accepts: accepts.map(({ network, scheme }) => ({ network, scheme })) },+ );+}++// Normalize the on-chain asset name to a currency symbol for the mandate check.+function currencyOf(accept) {+ const name = accept?.extra?.name || '';+ return /usdc|usd coin/i.test(name) ? 'USDC' : name || undefined;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ const userId = session?.id ?? bearer?.userId;++ const rl = await limits.mcpAgentPay(userId || 'anon');+ if (!rl.success) return rateLimited(res, rl, 'a2a payment rate limit exceeded');++ const body = await readJson(req);+ const {+ mandate: mandateJws,+ endpoint,+ text = 'Initiate paid skill.',+ networkPreference,+ reputation,+ } = body || {};++ if (!endpoint || typeof endpoint !== 'string') {+ return error(res, 400, 'validation_error', 'endpoint (peer A2A URL) is required');+ }++ // The peer endpoint is fully caller-controlled and we make a server-side+ // request to it — guard against SSRF into internal addresses.+ let safeEndpoint;+ try {+ safeEndpoint = (await assertSafePublicUrl(endpoint, { allowHttp: false })).toString();+ } catch (err) {+ if (err instanceof SsrfBlockedError) {+ return error(res, 400, 'invalid_endpoint', err.message);+ }+ throw err;+ }++ // ── Gate 1a: mandate is valid and belongs to this user ──────────────────+ let mandate;+ try {+ mandate = await verifyIntentMandate(mandateJws);+ } catch (err) {+ if (err instanceof MandateError) return error(res, err.status, err.code, err.message);+ throw err;+ }+ if (mandate.ownerUserId !== userId) {+ return error(res, 403, 'mandate_not_yours', 'this mandate was issued to a different user');+ }++ // ── Discover the peer's price (first leg of the A2A handshake) ──────────+ let quote;+ try {+ quote = await requestQuote({ endpoint: safeEndpoint, text });+ } catch (err) {+ if (err instanceof A2AClientError) {+ return error(res, 502, 'quote_failed', `could not get a quote from peer: ${err.message}`);+ }+ throw err;+ }++ let accept;+ try {+ accept = pickAccept(quote.required.accepts, networkPreference);+ } catch (err) {+ return error(res, 422, err.code || 'no_supported_accept', err.message);+ }+ const amount = accept.amount;+ const network = accept.network;++ // ── Gate 1b: per-call policy ────────────────────────────────────────────+ try {+ assertMandateAllows({+ mandate,+ amountAtomics: amount,+ network,+ resource: safeEndpoint,+ currency: currencyOf(accept),+ });+ } catch (err) {+ if (err instanceof MandateError) return error(res, err.status, err.code, err.message);+ throw err;+ }++ // ── Gate 3: peer reputation (opt-in) ────────────────────────────────────+ if (reputation && typeof reputation === 'object') {+ try {+ await assertReputationOk({+ agentId: reputation.agentId,+ chainId: reputation.chainId,+ minAverage: Number(reputation.minAverage) || 0,+ minCount: Number(reputation.minCount) || 0,+ });+ } catch (err) {+ if (err instanceof ReputationError) {+ return respondError(res, err.status, err.code, err);+ }+ throw err;+ }+ }++ // ── Gate 2: reserve against the total budget (atomic) ───────────────────+ const nowSec = Math.floor(Date.now() / 1000);+ const ledgerTtl = Math.max(60, (mandate.expiresAt || nowSec) - nowSec);+ const reservation = await reserve(mandate.mandateId, amount, mandate.maxAtomics, ledgerTtl);+ if (!reservation.ok) {+ return error(res, 402, 'budget_exceeded', 'mandate budget would be exceeded by this payment', {+ spent: reservation.spent,+ cap: reservation.cap,+ amount,+ });+ }++ // ── Settle ──────────────────────────────────────────────────────────────+ const payerKey = env.A2A_PAYER_PRIVATE_KEY;+ if (!payerKey) {+ await release(mandate.mandateId, amount);+ return error(+ res,+ 501,+ 'payer_not_configured',+ 'autonomous payer wallet is not configured (set A2A_PAYER_PRIVATE_KEY)',+ );+ }++ try {+ const signer = await createPrivateKeySigner(payerKey);+ const resource = quote.required.resource || { url: safeEndpoint, mimeType: 'application/json' };+ const paymentPayload = await buildEvmExactPayload({ accept, signer, resource });+ const result = await submitPayment({+ endpoint: safeEndpoint,+ taskId: quote.taskId,+ paymentPayload,+ });++ if (result.state !== 'completed') {+ await release(mandate.mandateId, amount);+ return error(res, 502, 'payment_failed', result.receipts?.[0]?.errorReason || `peer task ended in state ${result.state}`, {+ state: result.state,+ receipts: result.receipts || [],+ });+ }++ const artifacts = Array.isArray(result.task?.artifacts) ? result.task.artifacts : [];+ return json(res, 200, {+ ok: true,+ mandate_id: mandate.mandateId,+ task_id: quote.taskId,+ amount,+ network,+ currency: currencyOf(accept) || null,+ payer: signer.address,+ spent: reservation.spent,+ cap: reservation.cap,+ receipts: result.receipts || [],+ artifacts,+ });+ } catch (err) {+ // Any failure after reservation but before a confirmed settlement must+ // release the hold so the mandate's budget isn't silently consumed.+ await release(mandate.mandateId, amount);+ if (err instanceof A2AClientError) {+ return error(res, 502, err.code || 'payment_failed', err.message, { details: err.details });+ }+ return respondError(res, err.status || 502, 'payment_failed', err);+ }+});diff --git a/api/agents/a2a-mandate.js b/api/agents/a2a-mandate.jsnew file mode 100644index 000000000..ea387600d--- /dev/null+++ b/api/agents/a2a-mandate.js@@ -0,0 +1,64 @@+// POST /api/agents/a2a-mandate — issue an Intent Mandate.+//+// A user authorizes one of their agents to spend autonomously on their behalf,+// up to a total budget and per-call cap, over specified networks, optionally+// restricted to a set of peer endpoints. The server binds the authenticated+// userId into the mandate and signs it; the agent later presents the returned+// JWS to /api/agents/a2a-call to pay peers without a human in the loop.+//+// This is the human-consent step of AP2: the mandate is the verifiable record+// that the user authorized this class of spend before any autonomous payment.++import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { issueIntentMandate, MandateError, MAX_TTL_SECONDS, SUPPORTED_NETWORKS } from '../_lib/a2a/mandate.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ const userId = session?.id ?? bearer?.userId;++ const rl = await limits.mcpAgent(userId || 'anon');+ if (!rl.success) return rateLimited(res, rl, 'mandate issuance rate limit exceeded');++ const body = await readJson(req);+ const {+ subjectAgentId,+ maxAtomics,+ perCallAtomics,+ currency = 'USDC',+ networks = ['eip155:8453'],+ resources = [],+ purpose = '',+ ttlSec = 24 * 60 * 60,+ } = body || {};++ try {+ const { jws, mandate } = await issueIntentMandate({+ ownerUserId: userId,+ subjectAgentId,+ maxAtomics,+ perCallAtomics,+ currency,+ networks,+ resources,+ purpose,+ ttlSec,+ });+ return json(res, 201, {+ ok: true,+ mandate: jws,+ details: mandate,+ supported_networks: SUPPORTED_NETWORKS,+ max_ttl_seconds: MAX_TTL_SECONDS,+ });+ } catch (err) {+ if (err instanceof MandateError) return error(res, err.status, err.code, err.message);+ throw err;+ }+});diff --git a/api/agents/talk.js b/api/agents/talk.jsindex bf4a904a8..9fbaf1884 100644--- a/api/agents/talk.js+++ b/api/agents/talk.js@@ -81,7 +81,16 @@ export default wrap(async (req, res) => {const started = Date.now();let result;try {- result = await llmComplete({ system: systemPrompt, user: message, maxTokens: 1024, anthropicModel: model });+ result = await llmComplete({+ system: systemPrompt,+ user: message,+ maxTokens: 1024,+ anthropicModel: model,+ // Lead with Claude on the platform key; falls back to the free+ // providers automatically if it's unset or Anthropic errors.+ serverAnthropic: true,+ track: { agentId: agent.id, tool: 'agent.talk' },+ });} catch (err) {if (err instanceof LlmUnavailableError) {return error(res, 503, 'llm_unavailable', 'agent delegation is not available right now');diff --git a/api/llm/anthropic.js b/api/llm/anthropic.jsindex c54d4c7b8..b019bd9d5 100644--- a/api/llm/anthropic.js+++ b/api/llm/anthropic.js@@ -17,6 +17,7 @@ import { cors, error, method, wrap, readJson, json, rateLimited } from '../_lib/import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { recordEvent, logger } from '../_lib/usage.js';+import { costMicroUsd } from '../_lib/llm-pricing.js';import { readEmbedPolicy } from '../_lib/embed-policy.js';const log = logger('llm.anthropic');@@ -466,6 +467,11 @@ export default wrap(async (req, res) => {bytes: 0,latencyMs,status: 'ok',+ provider: route.provider || 'anthropic',+ model: usedModel,+ inputTokens,+ outputTokens,+ costMicroUsd: costMicroUsd({ provider: route.provider || 'anthropic', model: usedModel, input: inputTokens, output: outputTokens }),meta: { model: usedModel, requested_model: requestedModel, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },});return;@@ -513,6 +519,11 @@ export default wrap(async (req, res) => {bytes: upstreamText.length,latencyMs,status: 'ok',+ provider: route.provider || 'anthropic',+ model: usedModel,+ inputTokens,+ outputTokens,+ costMicroUsd: costMicroUsd({ provider: route.provider || 'anthropic', model: usedModel, input: inputTokens, output: outputTokens }),meta: { model: usedModel, requested_model: requestedModel, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },});diff --git a/public/login.html b/public/login.htmlindex f34cc0318..07889b7fa 100644--- a/public/login.html+++ b/public/login.html@@ -996,6 +996,7 @@agent.standOn(avatarWrap, { anchor: 'bottom-center', offsetY: -50 });avatarWrap?.classList.remove('loading');+ window.__agent = agent; /* TEMP probe */window.addEventListener('resize', () => {agent.standOn(avatarWrap, { anchor: 'bottom-center', offsetY: -50 });diff --git a/public/vanity-wallet.html b/public/vanity-wallet.htmlindex 580863eb7..3996e7122 100644--- a/public/vanity-wallet.html+++ b/public/vanity-wallet.html@@ -74,6 +74,42 @@.chip:hover { background: #242424; border-color: rgba(255,255,255,0.2); }.chip-est { color: #555; margin-left: .35rem; font-family: system-ui, sans-serif; }+ /* ── Compute / core selector ── */+ .cores { margin-top: 1.1rem; padding-top: 1rem; border-top: 1px solid var(--border); }+ .cores .cores-head { display: flex; justify-content: space-between; align-items: baseline; }+ .cores .cores-head label { margin: 0; }+ .cores .cores-val { font-family: ui-monospace, monospace; font-size: .85rem; color: var(--fg); }+ .cores .cores-val b { color: #fff; font-size: 1rem; }+ .cores-row { display: flex; align-items: center; gap: .75rem; margin-top: .55rem; }+ .cores-row input[type=range] {+ flex: 1; -webkit-appearance: none; appearance: none; height: 5px; border-radius: 999px;+ background: #2a2a2a; outline: none; cursor: pointer; margin: 0;+ }+ .cores-row input[type=range]::-webkit-slider-thumb {+ -webkit-appearance: none; appearance: none; width: 18px; height: 18px; border-radius: 50%;+ background: #fff; cursor: pointer; border: 3px solid #000; box-shadow: 0 0 0 1px rgba(255,255,255,0.2);+ transition: transform .1s;+ }+ .cores-row input[type=range]::-webkit-slider-thumb:hover { transform: scale(1.15); }+ .cores-row input[type=range]::-moz-range-thumb {+ width: 18px; height: 18px; border-radius: 50%; background: #fff; cursor: pointer;+ border: 3px solid #000; box-shadow: 0 0 0 1px rgba(255,255,255,0.2);+ }+ .cores-row input[type=range]:disabled { opacity: .4; cursor: not-allowed; }+ .cores-row input[type=range]:focus-visible { box-shadow: 0 0 0 2px rgba(255,255,255,0.35); }+ .cores .cores-hint { font-size: .72rem; color: var(--muted); margin-top: .45rem; }+ .cores-ticks { display: flex; gap: .35rem; margin-top: .55rem; }+ .cores-ticks button {+ font: inherit; font-size: .72rem; padding: .2rem .55rem; border-radius: 999px;+ border: 1px solid rgba(255,255,255,0.1); background: #1a1a1a; color: #bbb; cursor: pointer;+ }+ .cores-ticks button:hover { background: #242424; border-color: rgba(255,255,255,0.2); }+ .cores-ticks button[aria-pressed=true] { background: #fff; color: #000; border-color: #fff; font-weight: 600; }++ .progress.paused { opacity: .75; }+ .paused-tag { display: inline-block; padding: .1rem .5rem; border-radius: 999px; font-size: .7rem; font-weight: 600;+ background: var(--warn-bg); color: var(--warn-fg); border: 1px solid rgba(251,191,36,0.2); margin-left: .5rem; vertical-align: middle; }+.actions { display: flex; gap: .55rem; margin-top: 1.25rem; align-items: center; flex-wrap: wrap; }.btn { font: inherit; padding: .55rem 1.1rem; border-radius: 6px; border: 1px solid rgba(255,255,255,0.12); background: #1a1a1a; color: var(--fg); cursor: pointer; }.btn:hover { background: #222; }@@ -184,16 +220,30 @@<button class="chip" data-prefix="NPC" type="button">NPC<span class="chip-est"></span></button></div>+ <div class="cores">+ <div class="cores-head">+ <label for="core-count">Compute — CPU cores to use</label>+ <span class="cores-val"><b id="core-count-val">4</b> / <span id="core-max">8</span></span>+ </div>+ <div class="cores-row">+ <input id="core-count" type="range" min="1" max="8" value="4" step="1"+ aria-label="Number of CPU cores to use for grinding" />+ </div>+ <div class="cores-ticks" id="core-ticks" aria-label="Quick core presets"></div>+ <div class="cores-hint" id="cores-hint">More cores = faster, but a heavier load on your machine. Pause anytime to free them.</div>+ </div>+<div class="actions"><button id="grind" class="btn primary" type="button" disabled>Generate wallet</button>- <button id="cancel" class="btn" type="button" hidden>Cancel</button>+ <button id="pause" class="btn" type="button" hidden>Pause</button>+ <button id="stop" class="btn" type="button" hidden>Stop</button></div><div id="progress" hidden class="progress"><div class="live"><div><div class="stat" id="rate">0/s</div>- <div style="font-size:.75rem;color:#555">tries/sec across <span id="cores">?</span> cores</div>+ <div style="font-size:.75rem;color:#555">tries/sec across <span id="cores">?</span> cores<span id="paused-tag" class="paused-tag" hidden>paused</span></div></div><div style="text-align:right"><div class="stat"><span id="attempts">0</span></div>@@ -321,8 +371,50 @@const $ = (id) => document.getElementById(id);const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';const RATE_PER_CORE = 5000;- const cores = Math.max(1, Math.min(navigator.hardwareConcurrency || 4, 8));- $('cores').textContent = cores;++ // ── Core selection ─────────────────────────────────────────────────+ // The machine's logical core count is the ceiling; default to a+ // conservative half (min 1) so we don't peg the whole CPU by surprise.+ const HW_CORES = Math.max(1, navigator.hardwareConcurrency || 4);+ const DEFAULT_CORES = Math.max(1, Math.min(HW_CORES, Math.round(HW_CORES / 2) || 1));+ let cores = DEFAULT_CORES;++ const coreSlider = $('core-count');+ coreSlider.max = String(HW_CORES);+ coreSlider.value = String(DEFAULT_CORES);+ $('core-max').textContent = HW_CORES;+ $('core-count-val').textContent = DEFAULT_CORES;+ $('cores').textContent = DEFAULT_CORES;++ // Quick presets: 1, half, max — deduped for low-core machines.+ const presetVals = [...new Set([1, DEFAULT_CORES, HW_CORES])].sort((a, b) => a - b);+ const presetLabel = (n) => n === 1 ? '1 core' : n === HW_CORES ? `Max (${n})` : `${n}`;+ $('core-ticks').innerHTML = presetVals+ .map((n) => `<button type="button" data-cores="${n}" aria-pressed="${n === DEFAULT_CORES}">${presetLabel(n)}</button>`)+ .join('');++ function setCores(n) {+ cores = Math.max(1, Math.min(HW_CORES, n | 0));+ coreSlider.value = String(cores);+ $('core-count-val').textContent = cores;+ $('core-ticks').querySelectorAll('button').forEach((b) => {+ b.setAttribute('aria-pressed', String(Number(b.dataset.cores) === cores));+ });+ refreshChipEstimates();+ update();+ }++ function refreshChipEstimates() {+ document.querySelectorAll('.chip').forEach((c) => {+ const est = c.querySelector('.chip-est');+ if (est) est.textContent = ' ' + fmtTime(estSeconds(c.dataset.prefix.length));+ });+ }++ coreSlider.addEventListener('input', () => setCores(Number(coreSlider.value)));+ $('core-ticks').querySelectorAll('button').forEach((b) => {+ b.addEventListener('click', () => setCores(Number(b.dataset.cores)));+ });function esc(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' })[c]); }function sample(prefix = '') {@@ -403,6 +495,30 @@// ── Grind ──────────────────────────────────────────────────────────let abort = null;+ let controls = null; // GrindController for pause/resume/stop+ let scanLoop = null;++ // Toggle the core controls — they can only change between runs, since+ // the worker pool size is fixed for the lifetime of a grind.+ function setCoreControlsDisabled(disabled) {+ coreSlider.disabled = disabled;+ $('core-ticks').querySelectorAll('button').forEach((b) => { b.disabled = disabled; });+ }++ function setPaused(paused) {+ $('pause').textContent = paused ? 'Resume' : 'Pause';+ $('pause').classList.toggle('primary', paused);+ $('paused-tag').hidden = !paused;+ $('progress').classList.toggle('paused', paused);+ }++ function endGrindUI() {+ if (scanLoop) { clearInterval(scanLoop); scanLoop = null; }+ $('pause').hidden = true;+ $('stop').hidden = true;+ setPaused(false);+ setCoreControlsDisabled(false);+ }$('grind').addEventListener('click', async () => {const prefix = $('prefix').value.trim();@@ -414,52 +530,66 @@}$('grind').hidden = true;- $('cancel').hidden = false;+ $('pause').hidden = false;+ $('stop').hidden = false;+ setPaused(false);+ setCoreControlsDisabled(true);$('progress').hidden = false;$('result').hidden = true;$('error').hidden = true;$('attempts').textContent = '0';$('rate').textContent = '0/s';+ $('cores').textContent = cores;$('eta').textContent = fmtTime(estSeconds(prefix.length));$('scan').innerHTML = `<span class="pfx" style="background:linear-gradient(90deg,#ffd54f,#ff8a65);padding:0 3px;border-radius:3px;font-weight:700;color:var(--bg-1)">${esc(prefix)}</span><span style="color:#555">${esc(sample(prefix).slice(prefix.length))}</span>`;stopPreviewLoop();- // Animate the scan line during grind.- const scanLoop = setInterval(() => {+ // Animate the scan line during grind (frozen while paused).+ scanLoop = setInterval(() => {+ if (controls?.paused) return;const restNode = $('scan').lastElementChild;if (restNode) restNode.textContent = sample(prefix).slice(prefix.length);}, 100);abort = new AbortController();+ controls = {};try {const result = await grindVanity({prefix,+ maxWorkers: cores,+ controller: controls,signal: abort.signal,- onProgress: ({ attempts, rate, eta }) => {+ onProgress: ({ attempts, rate, eta, paused }) => {$('attempts').textContent = attempts.toLocaleString();- $('rate').textContent = `${Math.round(rate).toLocaleString()}/s`;+ $('rate').textContent = paused ? 'paused' : `${Math.round(rate).toLocaleString()}/s`;$('eta').textContent = eta;},});- clearInterval(scanLoop);renderResult(result, prefix);} catch (err) {- clearInterval(scanLoop);+ endGrindUI();if (err?.name !== 'AbortError') {$('error').textContent = `Grind failed: ${err.message || err}`;$('error').hidden = false;}$('grind').hidden = false;- $('cancel').hidden = true;$('progress').hidden = true;startPreviewLoop();+ } finally {+ controls = null;}});- $('cancel').addEventListener('click', () => abort?.abort());+ $('pause').addEventListener('click', () => {+ if (!controls) return;+ if (controls.paused) { controls.resume(); setPaused(false); }+ else { controls.pause(); setPaused(true); }+ });++ $('stop').addEventListener('click', () => abort?.abort());function renderResult(result, prefix) {- $('cancel').hidden = true;+ endGrindUI();$('grind').hidden = false;$('grind').textContent = 'Generate another';$('progress').hidden = true;@@ -557,6 +687,7 @@<option value="">— select an agent —</option>${agents.map((a) => `<option value="${esc(a.id)}">${esc(a.name)} ${a.meta?.solana_address ? '(already has wallet)' : ''}</option>`).join('')}</select>+ <div id="assign-replace-warn" hidden style="margin-top:.5rem;padding:.5rem .65rem;border:1px solid var(--danger);border-radius:8px;background:rgba(255,90,90,.06);font-size:.78rem;line-height:1.45"></div><div class="custody"><label><input type="checkbox" id="assign-ack" />@@ -574,16 +705,49 @@const ack = document.getElementById('assign-ack');const btn = document.getElementById('assign-btn');const status = document.getElementById('assign-status');-- function refresh() { btn.disabled = !sel.value || !ack.checked; }+ const warn = document.getElementById('assign-replace-warn');++ // Existing Solana address per agent, so selecting an agent that already+ // has a wallet switches the flow to an explicit replace instead of+ // dead-ending on a 409 from POST /api/agents/:id/solana.+ const walletByAgent = Object.fromEntries(agents.map((a) => [a.id, a.meta?.solana_address || null]));+ const truncAddr = (a) => `${a.slice(0, 4)}…${a.slice(-4)}`;++ function refresh() {+ const existing = sel.value ? walletByAgent[sel.value] : null;+ if (existing) {+ warn.innerHTML = `<strong style="color:var(--danger)">This agent already has a wallet</strong> (<code style="font-family:ui-monospace,monospace">${esc(truncAddr(existing))}</code>). Assigning will <strong>replace</strong> it — the old wallet is detached and can no longer sign for this agent. Make sure you have its key backed up.`;+ warn.hidden = false;+ btn.textContent = 'Replace wallet';+ } else {+ warn.hidden = true;+ btn.textContent = 'Assign to agent';+ }+ btn.disabled = !sel.value || !ack.checked;+ }sel.addEventListener('change', refresh);ack.addEventListener('change', refresh);btn.addEventListener('click', async () => {+ const replacing = !!walletByAgent[sel.value];btn.disabled = true;- status.textContent = 'assigning…';+ status.textContent = replacing ? 'replacing…' : 'assigning…';status.style.color = '#888';try {+ // Replacing an existing wallet: detach it first so the POST below+ // provisions cleanly instead of being rejected with a 409.+ if (replacing) {+ const del = await fetch(`/api/agents/${encodeURIComponent(sel.value)}/solana`, {+ method: 'DELETE',+ credentials: 'include',+ });+ if (!del.ok) {+ const delData = await del.json().catch(() => ({}));+ status.innerHTML = `<span style="color:var(--danger)">Could not remove the existing wallet: ${esc(delData.error_description || del.status)}</span>`;+ btn.disabled = false;+ return;+ }+ }const r = await fetch(`/api/agents/${encodeURIComponent(sel.value)}/solana`, {method: 'POST',credentials: 'include',@@ -603,6 +767,7 @@btn.disabled = false;return;}+ walletByAgent[sel.value] = addr;const agentName = sel.options[sel.selectedIndex].text.replace(/\s*\(already.*\)$/, '');host.innerHTML = `<div class="assigned-ok">diff --git a/scripts/avatar-pos.mjs b/scripts/avatar-pos.mjsnew file mode 100644index 000000000..f320c62da--- /dev/null+++ b/scripts/avatar-pos.mjs@@ -0,0 +1,16 @@+import puppeteer from 'puppeteer';+const b = await puppeteer.launch({ args:['--no-sandbox','--use-gl=swiftshader','--enable-webgl'] });+const p = await b.newPage();+await p.setViewport({ width:1440, height:900 });+await p.goto('http://localhost:3001/login.html', { waitUntil:'networkidle2' });+await new Promise(r=>setTimeout(r,3000));+const read = ()=>p.evaluate(()=>{+ const a=window.__agent; if(!a||!a.avatar) return {err:'no agent/avatar'};+ const s=a.worldToScreen(a.avatar.position.x, a.avatar.position.y);+ return { scrollY:window.scrollY, avatarScreenX:Math.round(s.x), avatarScreenY:Math.round(s.y), wx:+a.avatar.position.x.toFixed(3), wy:+a.avatar.position.y.toFixed(3) };+});+await p.evaluate(()=>window.scrollTo(0,0)); await new Promise(r=>setTimeout(r,400));+console.log('scroll0 ', JSON.stringify(await read()));+await p.evaluate(()=>window.scrollTo(0,400)); await new Promise(r=>setTimeout(r,400));+console.log('scroll400', JSON.stringify(await read()));+await b.close();diff --git a/src/agent-protocol.js b/src/agent-protocol.jsindex e423ceaba..0be23d860 100644--- a/src/agent-protocol.js+++ b/src/agent-protocol.js@@ -20,6 +20,9 @@ export const ACTION_TYPES = {SENTIMENT_ANALYZED: 'sentiment-analyzed', // sentiment analysis was performedREMEMBER: 'remember', // agent stored a memorySIGN: 'sign', // agent signs an action with its wallet+ PAY_INTENT: 'pay-intent', // agent is about to pay a peer agent for a skill+ PAY_SETTLED: 'pay-settled', // an agent-to-agent payment settled on-chain+ PAY_FAILED: 'pay-failed', // an agent-to-agent payment attempt failedLOAD_START: 'load-start', // model/asset loading startedLOAD_PROGRESS: 'load-progress', // model/asset download progress (bytes)LOAD_END: 'load-end', // model/asset loading finisheddiff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 392124415..0de2df2c4 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -36,7 +36,7 @@ import {loadManifest, getEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,CLIP_IDLE, CLIP_WALK,} from './avatar-rig.js';-import { GUEST_SENTINEL, uploadPendingGuestAvatar, getPlayCosmetics, setPlayCosmetics, getRequestedAvatar } from './play-handoff.js';+import { GUEST_SENTINEL, uploadPendingGuestAvatar, getPlayCosmetics, setPlayCosmetics } from './play-handoff.js';import { applyLoadout } from './cosmetics-loadout.js';import { serializeLoadout } from '../../multiplayer/src/cosmetics-catalog.js';import { AccessoryManager } from '../agent-accessories.js';@@ -318,8 +318,11 @@ export class CoinCommunities {this._playReady = this._ensurePlayAccess();// Deep link: /play?coin=<mint>&name=&symbol=&image= drops straight into a- // coin's community, so a community is a shareable URL.+ // coin's community, so a community is a shareable URL. An optional+ // `?avatar=<glb|id>` rides along (used by "See in 3D" links) and is shown+ // for this session only — never persisted over the player's saved avatar.const p = new URLSearchParams(location.search);+ this._urlAvatar = (p.get('avatar') || '').trim();const mint = p.get('coin');if (mint) {const tier = p.get('tier') === 'holders' ? 'holders' : 'general';@@ -725,8 +728,8 @@ export class CoinCommunities {this.localAnim = new AnimationManager();// An `?avatar=` deep link (a "See in 3D" link carrying an agent's GLB) shows// that avatar for the session without overwriting the player's saved pick;- // otherwise use whatever they selected in the lobby.- const avatarInput = getRequestedAvatar() || this.ui.getAvatar();+ // otherwise use whatever they selected in the lobby (preset / paste / upload).+ const avatarInput = this._urlAvatar || this.ui.getAvatar();const url = await resolveAvatarUrl(avatarInput);const { height: localHeight, fallback: avatarFallback } = await buildAvatar(this.localRig, url, this.localAnim);// Backed out while the avatar GLB was loading — stop before we open a room.diff --git a/src/shared/agent-3d.js b/src/shared/agent-3d.jsnew file mode 100644index 000000000..cccd2b5b0--- /dev/null+++ b/src/shared/agent-3d.js@@ -0,0 +1,60 @@+// Shared helpers for showing an agent's 3D avatar in a real environment.+//+// Every agent has a 3D avatar. If a record carries a custom GLB we use it;+// otherwise we fall back to the baked mannequin (/avatars/mannequin.glb — the+// same figure /pose renders, exported by scripts/bake-mannequin-glb.mjs). That+// makes the "See in 3D" affordance universal: no agent is ever avatar-less, so+// the button is never dead or disabled.++import { findAvatar3D } from '../erc8004/queries.js';++// The universal base avatar. Lives in /public, so it's a plain served path.+export const MANNEQUIN_GLB = '/avatars/mannequin.glb';++// $three is the only coin — its community is the world we drop visitors into.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const GLB_RE = /\.(glb|gltf|vrm)(\?|#|$)/i;++// Resolve an agent record (from any surface — marketplace, directory, ERC-8004)+// to a loadable 3D model URL, falling back to the mannequin.+export function agentAvatarGlb(agent) {+ if (!agent) return MANNEQUIN_GLB;++ // Marketplace / avatar-service shapes carry an explicit GLB URL.+ const direct = agent.avatar_glb_url || agent.base_model_url || agent.glb_url || agent.model_url;+ if (typeof direct === 'string' && GLB_RE.test(direct)) return direct;++ // ERC-8004 on-chain agents expose their model through registration metadata.+ try {+ if (agent.metadata) {+ const fromMeta = findAvatar3D(agent.metadata);+ if (fromMeta) return fromMeta;+ }+ } catch { /* metadata malformed — fall through to the base avatar */ }++ // `avatar` is a GLB on the directory but a 2D image elsewhere — use it only+ // when it actually points at a model.+ if (typeof agent.avatar === 'string' && GLB_RE.test(agent.avatar)) return agent.avatar;++ return MANNEQUIN_GLB;+}++// True when the agent ships its own 3D model (vs. wearing the base mannequin).+// Lets surfaces label the CTA precisely ("See in 3D" vs "Preview as mannequin").+export function hasCustomAvatar(agent) {+ return agentAvatarGlb(agent) !== MANNEQUIN_GLB;+}++// Build the /play deep link that drops the agent's avatar into the $three world.+// The avatar rides in `?avatar=` and is shown for the session only — it never+// overwrites the visitor's saved avatar (see play-handoff.getRequestedAvatar).+export function seeInWorldHref(agent) {+ const q = new URLSearchParams({+ avatar: agentAvatarGlb(agent),+ coin: THREE_MINT,+ name: (agent?.name || 'three.ws').toString().slice(0, 40),+ symbol: 'three',+ });+ return `/play?${q.toString()}`;+}diff --git a/src/solana/vanity/grinder.js b/src/solana/vanity/grinder.jsindex 3cd0f40c2..04094c13c 100644--- a/src/solana/vanity/grinder.js+++ b/src/solana/vanity/grinder.js@@ -149,5 +149,31 @@ export function grindVanity(opts = {}) {w.postMessage({ type: 'start', prefix, suffix, ignoreCase });}++ // Wire the opt-in controller now that the pool is live.+ const controller = opts.controller;+ if (controller) {+ controller.paused = false;+ controller.workers = cores;+ controller.pause = () => {+ if (controller.paused || workers.length === 0) return;+ controller.paused = true;+ for (const w of workers) {+ try { w.postMessage({ type: 'pause' }); } catch {}+ }+ if (onProgress) {+ const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0);+ onProgress({ attempts: totalAttempts, rate: 0, eta: 'paused', paused: true });+ }+ };+ controller.resume = () => {+ if (!controller.paused || workers.length === 0) return;+ controller.paused = false;+ for (const w of workers) {+ try { w.postMessage({ type: 'resume' }); } catch {}+ }+ };+ controller.stop = onAbort;+ }});}