Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(llm): llm pricing + usage cost tracking, a2a lib, mannequin avatar, agent-registry/env updates

nirholas1b73a26058e1
diff --git a/.env.example b/.env.example
index 828c7432f..55f8f21a2 100644
--- a/.env.example
+++ b/.env.example
@@ -63,6 +63,15 @@ OPENROUTER_API_KEY=
# Groq — fastest hosted Llama (sub-second). Get a key at https://console.groq.com
GROQ_API_KEY=
+# NVIDIA NIM — free, OpenAI-compatible inference for 100+ hosted models
+# (Nemotron, DeepSeek, Kimi, MiniMax, Llama 4). One key unlocks all of them at
+# https://integrate.api.nvidia.com/v1. Powers the NVIDIA providers in
+# /api/brain/chat and a free fallback tier in the embed proxy (/api/llm/anthropic).
+# Get a free key (no credit card) at https://build.nvidia.com → any model → "Get API Key".
+# NOTE: this is the hosted-API var. NGC_API_KEY is only for self-hosted NIM Docker
+# containers (nvcr.io) — not used here. Same secret value, different name/path.
+NVIDIA_API_KEY=
+
# OpenAI — used for gpt-4o-mini fallback. Get a key at https://platform.openai.com
OPENAI_API_KEY=
diff --git a/api/_lib/a2a/mandate.js b/api/_lib/a2a/mandate.js
new file mode 100644
index 000000000..61a4454d3
--- /dev/null
+++ b/api/_lib/a2a/mandate.js
@@ -0,0 +1,285 @@
+// Intent Mandate — AP2-style budgeted authorization for autonomous agent spend.
+//
+// Modeled on Google's Agent Payments Protocol (AP2) "Intent Mandate": a
+// cryptographically signed, verifiable credential that a user issues up-front
+// to authorize an agent to spend on their behalf, later and autonomously,
+// within hard constraints (total budget, per-call cap, currency, networks, and
+// optionally a resource allowlist). The agent carries the mandate through each
+// transaction; the server verifies it before releasing any payment.
+//
+// We sign mandates as compact JWS (JWT) with a dedicated symmetric secret
+// (env.A2A_MANDATE_SECRET) using `jose` — the same library this codebase
+// already uses for session auth and offer/receipt signing. The platform is the
+// mandate authority: a user authenticates to the issuance endpoint, the server
+// binds their userId into the `owner` claim and signs. Verification is fully
+// offline (no DB/chain round-trip), so it stays on the hot path of every
+// autonomous payment without adding latency.
+//
+// Budget ENFORCEMENT across multiple calls lives in spend-ledger.js — the
+// mandate states the cap; the ledger tracks cumulative spend against it. This
+// module owns issuance, signature verification, and per-call policy checks.
+
+import * as jose from 'jose';
+
+import { env } from '../env.js';
+
+export const MANDATE_TYPE = 'a2a-intent-mandate';
+export const MANDATE_VERSION = 1;
+
+// Networks an agent may be authorized to pay over. Mirrors the EVM `exact`
+// schemes the A2A x402 client supports (see api/_lib/x402/a2a-client.js).
+export const SUPPORTED_NETWORKS = [
+ 'eip155:8453', // Base mainnet
+ 'eip155:84532', // Base Sepolia
+ 'eip155:1', // Ethereum mainnet
+ 'eip155:137', // Polygon
+ 'eip155:42161', // Arbitrum One
+];
+
+// Upper bound on mandate lifetime — a budgeted authorization should be
+// short-lived; 90 days is the ceiling, callers pick shorter.
+export const MAX_TTL_SECONDS = 90 * 24 * 60 * 60;
+
+export class MandateError extends Error {
+ constructor(code, message, status = 400) {
+ super(message);
+ this.name = 'MandateError';
+ this.code = code;
+ this.status = status;
+ }
+}
+
+function secretKey() {
+ const secret = env.A2A_MANDATE_SECRET;
+ if (!secret) {
+ throw new MandateError(
+ 'mandate_signing_unconfigured',
+ 'A2A_MANDATE_SECRET (or JWT_SECRET) must be set to issue or verify mandates',
+ 500,
+ );
+ }
+ return new TextEncoder().encode(secret);
+}
+
+// Atomic-units are integers (e.g. USDC has 6 decimals → 1 USDC = 1_000_000).
+// Accept string or number/bigint; normalize to a positive BigInt. Rejects
+// anything non-integer, negative, or zero.
+function toPositiveAtomics(value, field) {
+ let bi;
+ try {
+ bi = typeof value === 'bigint' ? value : BigInt(String(value).trim());
+ } catch {
+ throw new MandateError('invalid_amount', `${field} must be an integer atomic amount`);
+ }
+ if (bi <= 0n) throw new MandateError('invalid_amount', `${field} must be greater than zero`);
+ return bi;
+}
+
+/**
+ * Issue (sign) an Intent Mandate. Returns the compact JWS plus the decoded
+ * mandate for the caller to echo back to the user.
+ *
+ * @param {object} opts
+ * @param {string} opts.ownerUserId Authenticated user authorizing the spend.
+ * @param {string} opts.subjectAgentId Agent permitted to spend under this mandate.
+ * @param {string|number|bigint} opts.maxAtomics Total budget across all calls.
+ * @param {string|number|bigint} opts.perCallAtomics Per-call ceiling.
+ * @param {string} [opts.currency='USDC'] Currency symbol the mandate covers.
+ * @param {string[]} [opts.networks] Allowed networks (subset of SUPPORTED_NETWORKS).
+ * @param {string[]} [opts.resources=[]] Allowed peer endpoint prefixes; [] = any.
+ * @param {string} [opts.purpose=''] Human-readable scope note.
+ * @param {number} opts.ttlSec Lifetime in seconds (1..MAX_TTL_SECONDS).
+ * @returns {Promise<{ jws: string, mandate: object }>}
+ */
+export async function issueIntentMandate({
+ ownerUserId,
+ subjectAgentId,
+ maxAtomics,
+ perCallAtomics,
+ currency = 'USDC',
+ networks,
+ resources = [],
+ purpose = '',
+ ttlSec,
+}) {
+ if (!ownerUserId) throw new MandateError('invalid_owner', 'ownerUserId is required');
+ if (!subjectAgentId) throw new MandateError('invalid_subject', 'subjectAgentId is required');
+
+ const max = toPositiveAtomics(maxAtomics, 'maxAtomics');
+ const perCall = toPositiveAtomics(perCallAtomics, 'perCallAtomics');
+ if (perCall > max) {
+ throw new MandateError('invalid_amount', 'perCallAtomics cannot exceed maxAtomics');
+ }
+
+ const nets = Array.isArray(networks) && networks.length ? networks : ['eip155:8453'];
+ const unsupported = nets.filter((n) => !SUPPORTED_NETWORKS.includes(n));
+ if (unsupported.length) {
+ throw new MandateError('unsupported_network', `unsupported network(s): ${unsupported.join(', ')}`);
+ }
+
+ if (!Array.isArray(resources)) {
+ throw new MandateError('invalid_resources', 'resources must be an array of URL prefixes');
+ }
+ for (const r of resources) {
+ if (typeof r !== 'string' || !/^https?:\/\//i.test(r)) {
+ throw new MandateError('invalid_resources', `resource "${r}" must be an http(s) URL prefix`);
+ }
+ }
+
+ const ttl = Number(ttlSec);
+ if (!Number.isFinite(ttl) || ttl < 1 || ttl > MAX_TTL_SECONDS) {
+ throw new MandateError('invalid_ttl', `ttlSec must be between 1 and ${MAX_TTL_SECONDS}`);
+ }
+
+ const nowSec = Math.floor(Date.now() / 1000);
+ const claims = {
+ typ: MANDATE_TYPE,
+ ver: MANDATE_VERSION,
+ owner: ownerUserId,
+ // Mandate-specific scope lives under `m` to keep registered JWT claims clean.
+ m: {
+ maxAtomics: max.toString(),
+ perCallAtomics: perCall.toString(),
+ currency,
+ networks: nets,
+ resources,
+ purpose: String(purpose || ''),
+ },
+ };
+
+ const jws = await new jose.SignJWT(claims)
+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
+ .setSubject(subjectAgentId)
+ .setIssuer(env.APP_ORIGIN)
+ .setIssuedAt(nowSec)
+ .setExpirationTime(nowSec + ttl)
+ .setJti(jti())
+ .sign(secretKey());
+
+ return { jws, mandate: decodeFromClaims(claims, { sub: subjectAgentId, exp: nowSec + ttl, iat: nowSec, jti: claims.jti }) };
+}
+
+function jti() {
+ // jose has no built-in jti; use a 128-bit random hex. crypto.randomUUID is
+ // available in Node ≥ 16 and the edge runtime.
+ return globalThis.crypto.randomUUID();
+}
+
+// Shape the verified/issued claims into a flat, ergonomic mandate object.
+function decodeFromClaims(claims, registered) {
+ const m = claims.m || {};
+ return {
+ mandateId: registered.jti,
+ ownerUserId: claims.owner,
+ subjectAgentId: registered.sub,
+ maxAtomics: m.maxAtomics,
+ perCallAtomics: m.perCallAtomics,
+ currency: m.currency,
+ networks: Array.isArray(m.networks) ? m.networks : [],
+ resources: Array.isArray(m.resources) ? m.resources : [],
+ purpose: m.purpose || '',
+ issuedAt: registered.iat,
+ expiresAt: registered.exp,
+ };
+}
+
+/**
+ * Verify a mandate's signature and expiry, returning the decoded mandate.
+ * Throws MandateError('invalid_mandate', …, 401) on any signature/expiry
+ * failure — callers map that to a 401/403 as appropriate.
+ *
+ * @param {string} jws
+ * @returns {Promise<object>} decoded mandate
+ */
+export async function verifyIntentMandate(jws) {
+ if (!jws || typeof jws !== 'string') {
+ throw new MandateError('invalid_mandate', 'mandate (compact JWS) is required', 400);
+ }
+ let payload;
+ try {
+ ({ payload } = await jose.jwtVerify(jws, secretKey(), {
+ issuer: env.APP_ORIGIN,
+ algorithms: ['HS256'],
+ }));
+ } catch (err) {
+ const expired = err?.code === 'ERR_JWT_EXPIRED';
+ throw new MandateError(
+ expired ? 'mandate_expired' : 'invalid_mandate',
+ expired ? 'mandate has expired' : `mandate verification failed: ${err.message}`,
+ 401,
+ );
+ }
+ if (payload.typ !== MANDATE_TYPE) {
+ throw new MandateError('invalid_mandate', 'not an intent mandate', 401);
+ }
+ const mandate = decodeFromClaims(payload, {
+ jti: payload.jti,
+ sub: payload.sub,
+ iat: payload.iat,
+ exp: payload.exp,
+ });
+ if (!mandate.maxAtomics || !mandate.perCallAtomics) {
+ throw new MandateError('invalid_mandate', 'mandate is missing budget claims', 401);
+ }
+ return mandate;
+}
+
+/**
+ * Assert a single proposed payment is within the mandate's policy. Does NOT
+ * check cumulative budget — that's spend-ledger.js. Throws MandateError with a
+ * specific code on the first violation.
+ *
+ * @param {object} opts
+ * @param {object} opts.mandate Decoded mandate from verifyIntentMandate.
+ * @param {string|number|bigint} opts.amountAtomics Proposed payment amount.
+ * @param {string} opts.network Network the payment will settle on (CAIP-2).
+ * @param {string} [opts.resource] Peer endpoint URL being paid.
+ * @param {string} [opts.currency] Currency of the proposed payment.
+ * @param {number} [opts.nowSec] Override for testing.
+ */
+export function assertMandateAllows({ mandate, amountAtomics, network, resource, currency, nowSec }) {
+ if (!mandate || typeof mandate !== 'object') {
+ throw new MandateError('invalid_mandate', 'mandate is required', 400);
+ }
+ const now = Number.isFinite(nowSec) ? nowSec : Math.floor(Date.now() / 1000);
+ if (mandate.expiresAt && now >= mandate.expiresAt) {
+ throw new MandateError('mandate_expired', 'mandate has expired', 401);
+ }
+
+ const amount = toPositiveAtomics(amountAtomics, 'amount');
+ const perCall = BigInt(mandate.perCallAtomics);
+ if (amount > perCall) {
+ throw new MandateError(
+ 'amount_over_per_call',
+ `payment ${amount} exceeds per-call cap ${perCall}`,
+ 402,
+ );
+ }
+
+ if (currency && mandate.currency && currency !== mandate.currency) {
+ throw new MandateError(
+ 'currency_mismatch',
+ `mandate authorizes ${mandate.currency}, payment is ${currency}`,
+ 402,
+ );
+ }
+
+ if (network && mandate.networks.length && !mandate.networks.includes(network)) {
+ throw new MandateError(
+ 'network_not_allowed',
+ `mandate does not authorize network ${network}`,
+ 402,
+ );
+ }
+
+ if (resource && mandate.resources.length) {
+ const allowed = mandate.resources.some((prefix) => resource.startsWith(prefix));
+ if (!allowed) {
+ throw new MandateError(
+ 'resource_not_allowed',
+ `mandate does not authorize paying ${resource}`,
+ 402,
+ );
+ }
+ }
+}
diff --git a/api/_lib/a2a/reputation-gate.js b/api/_lib/a2a/reputation-gate.js
new file mode 100644
index 000000000..e7dcaeb89
--- /dev/null
+++ b/api/_lib/a2a/reputation-gate.js
@@ -0,0 +1,111 @@
+// Reputation gate — refuse to pay a peer agent whose on-chain ERC-8004
+// reputation is below the caller's threshold.
+//
+// Trust is the missing half of autonomous payments: budget caps stop an agent
+// overspending, but they don't stop it paying a scammer. ERC-8004's Reputation
+// Registry (getReputation(agentId) → (totalScore, count)) is the standard
+// trust signal; this module reads it server-side and enforces a minimum average
+// score and/or minimum review count before a mandate-authorized payment is
+// allowed to proceed.
+//
+// The on-chain read is injectable (`read` option) so tests run without RPC and
+// callers can swap in an indexer. When reputation gating is requested but no
+// RPC URL is configured AND no threshold is set, the gate is a no-op; if a
+// threshold IS set without a usable reader, it fails closed.
+
+import { Contract, JsonRpcProvider } from 'ethers';
+
+import { env } from '../env.js';
+import { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } from '../../../src/erc8004/abi.js';
+
+export class ReputationError extends Error {
+ constructor(code, message, status = 403) {
+ super(message);
+ this.name = 'ReputationError';
+ this.code = code;
+ this.status = status;
+ }
+}
+
+/**
+ * Read aggregated ERC-8004 reputation for an agent.
+ * @param {object} opts
+ * @param {number|bigint|string} opts.agentId
+ * @param {number} opts.chainId
+ * @param {string} [opts.rpcUrl] Defaults to env.A2A_REPUTATION_RPC_URL.
+ * @returns {Promise<{ average: number, count: number, total: number }>}
+ */
+export async function readReputationOnchain({ agentId, chainId, rpcUrl }) {
+ const url = rpcUrl || env.A2A_REPUTATION_RPC_URL;
+ if (!url) throw new ReputationError('reputation_rpc_unconfigured', 'no RPC URL for reputation reads', 500);
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ if (!deployment?.reputationRegistry) {
+ throw new ReputationError(
+ 'reputation_registry_missing',
+ `no Reputation Registry deployed on chain ${chainId}`,
+ 500,
+ );
+ }
+ const provider = new JsonRpcProvider(url);
+ const contract = new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);
+ 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 };
+}
+
+/**
+ * Assert a peer agent meets the reputation bar. Throws ReputationError when it
+ * doesn't. A no-op when neither a minimum average nor minimum count is set.
+ *
+ * @param {object} opts
+ * @param {number|bigint|string} [opts.agentId] On-chain agentId of the peer.
+ * @param {number} [opts.chainId]
+ * @param {number} [opts.minAverage=0] Required average score.
+ * @param {number} [opts.minCount=0] Required number of reviews.
+ * @param {string} [opts.rpcUrl]
+ * @param {(o:object)=>Promise<{average:number,count:number}>} [opts.read] Injectable reader.
+ * @returns {Promise<{ average: number, count: number } | null>} The reputation read, or null when gating was skipped.
+ */
+export async function assertReputationOk({
+ agentId,
+ chainId,
+ minAverage = 0,
+ minCount = 0,
+ rpcUrl,
+ read = readReputationOnchain,
+}) {
+ const gated = minAverage > 0 || minCount > 0;
+ if (!gated) return null; // No threshold requested — nothing to enforce.
+
+ if (agentId === undefined || agentId === null || agentId === '') {
+ throw new ReputationError(
+ 'reputation_required',
+ 'a reputation threshold was set but no peer agentId was provided to evaluate',
+ );
+ }
+
+ let rep;
+ try {
+ rep = await read({ agentId, chainId, rpcUrl });
+ } catch (err) {
+ if (err instanceof ReputationError) throw err;
+ // Reader blew up (RPC down, etc). Fail closed — we cannot prove the peer is
+ // trustworthy, and the caller explicitly asked us to gate on trust.
+ throw new ReputationError('reputation_unavailable', `reputation read failed: ${err.message}`, 502);
+ }
+
+ if (minCount > 0 && rep.count < minCount) {
+ throw new ReputationError(
+ 'reputation_too_few_reviews',
+ `peer has ${rep.count} review(s); ${minCount} required`,
+ );
+ }
+ if (minAverage > 0 && rep.average < minAverage) {
+ throw new ReputationError(
+ 'reputation_too_low',
+ `peer average ${rep.average.toFixed(2)} is below required ${minAverage}`,
+ );
+ }
+ return rep;
+}
diff --git a/api/_lib/a2a/spend-ledger.js b/api/_lib/a2a/spend-ledger.js
new file mode 100644
index 000000000..751cf7fd4
--- /dev/null
+++ b/api/_lib/a2a/spend-ledger.js
@@ -0,0 +1,186 @@
+// Mandate spend ledger — enforces an Intent Mandate's TOTAL budget across the
+// many autonomous payments made under it.
+//
+// A mandate (mandate.js) declares the caps; this ledger tracks cumulative spend
+// keyed by mandateId so the (N+1)th call can't push lifetime spend over the
+// authorized maximum. The check-and-increment is atomic so concurrent calls
+// under the same mandate can't both slip past the cap.
+//
+// Storage mirrors api/_lib/x402/idempotency-cache.js: Upstash Redis in
+// production (atomic INCRBY), an in-process Map fallback for dev/CI/tests. In
+// production without Redis the fallback only guards a single function replica —
+// set UPSTASH_REDIS_REST_URL/TOKEN for cross-replica budget enforcement.
+//
+// Amounts are atomic units (USDC has 6 decimals). They comfortably fit in a
+// JS-safe integer for any realistic mandate budget; we guard against callers
+// passing values beyond Number.MAX_SAFE_INTEGER so Redis INCRBY (int64) and the
+// memory path agree.
+
+import { Redis } from '@upstash/redis';
+import { env } from '../env.js';
+
+const IS_PROD = process.env.VERCEL_ENV === 'production' || process.env.NODE_ENV === 'production';
+
+let redis = null;
+if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {
+ redis = new Redis({
+ url: env.UPSTASH_REDIS_REST_URL,
+ token: env.UPSTASH_REDIS_REST_TOKEN,
+ });
+} else if (IS_PROD) {
+ console.warn(
+ '[a2a-spend-ledger] UPSTASH_REDIS_REST_URL/TOKEN not set; using per-instance ' +
+ 'memory fallback. Cross-replica mandate budget enforcement requires Redis.',
+ );
+}
+
+const KEY_PREFIX = 'a2a:spend:';
+
+// In-memory fallback. Map<key, { spent: number, expiresAt: number }>.
+const memoryStore = new Map();
+
+function fullKey(mandateId) {
+ return `${KEY_PREFIX}${mandateId}`;
+}
+
+function asSafeInt(value, field) {
+ const n = typeof value === 'bigint' ? Number(value) : Number(value);
+ if (!Number.isInteger(n) || n < 0) {
+ throw new Error(`${field} must be a non-negative integer atomic amount`);
+ }
+ if (n > Number.MAX_SAFE_INTEGER) {
+ throw new Error(`${field} exceeds the maximum supported atomic amount`);
+ }
+ return n;
+}
+
+function memoryGet(key) {
+ const slot = memoryStore.get(key);
+ if (!slot) return 0;
+ if (slot.expiresAt && slot.expiresAt < Date.now()) {
+ memoryStore.delete(key);
+ return 0;
+ }
+ return slot.spent;
+}
+
+function memorySet(key, spent, ttlSec) {
+ const prev = memoryStore.get(key);
+ memoryStore.set(key, {
+ spent,
+ // Preserve the original expiry across increments so a long-lived mandate's
+ // window doesn't slide forward on every payment.
+ expiresAt: prev?.expiresAt || (ttlSec > 0 ? Date.now() + ttlSec * 1000 : 0),
+ });
+}
+
+/**
+ * Current cumulative spend under a mandate, in atomic units.
+ * @param {string} mandateId
+ * @returns {Promise<number>}
+ */
+export async function spent(mandateId) {
+ const key = fullKey(mandateId);
+ if (!redis) return memoryGet(key);
+ try {
+ const raw = await redis.get(key);
+ return raw ? Number(raw) : 0;
+ } catch (err) {
+ console.error('[a2a-spend-ledger] get failed:', err?.message || err);
+ // Fail closed: if we can't read the ledger we can't prove headroom.
+ throw new Error('spend ledger unavailable');
+ }
+}
+
+/**
+ * Atomically reserve `amount` against a mandate's total `cap`. Returns
+ * { ok: true, spent } when the reservation fits, or { ok: false, spent, cap }
+ * when it would exceed the cap (no funds reserved in that case).
+ *
+ * `ttlSec` sets the key's expiry on first reservation so a mandate's ledger is
+ * garbage-collected after the mandate itself expires.
+ *
+ * @param {string} mandateId
+ * @param {number|bigint} amount Atomic units to reserve.
+ * @param {number|bigint} cap Total authorized atomic units (mandate.maxAtomics).
+ * @param {number} ttlSec Seconds until the ledger key expires.
+ * @returns {Promise<{ ok: boolean, spent: number, cap: number }>}
+ */
+export async function reserve(mandateId, amount, cap, ttlSec) {
+ const amt = asSafeInt(amount, 'amount');
+ const capInt = asSafeInt(cap, 'cap');
+ const key = fullKey(mandateId);
+
+ if (!redis) {
+ const current = memoryGet(key);
+ if (current + amt > capInt) return { ok: false, spent: current, cap: capInt };
+ memorySet(key, current + amt, ttlSec);
+ return { ok: true, spent: current + amt, cap: capInt };
+ }
+
+ // Atomic increment, then roll back if it overshot. INCRBY is the only
+ // primitive that's safe under concurrency; check-then-set would race.
+ let total;
+ try {
+ total = await redis.incrby(key, amt);
+ } catch (err) {
+ console.error('[a2a-spend-ledger] incrby failed:', err?.message || err);
+ throw new Error('spend ledger unavailable');
+ }
+ if (total === amt && ttlSec > 0) {
+ // First write created the key — set its lifetime. Best-effort.
+ try {
+ await redis.expire(key, ttlSec);
+ } catch {
+ /* expiry is GC hygiene; the cap check below still holds */
+ }
+ }
+ if (total > capInt) {
+ try {
+ await redis.decrby(key, amt);
+ } catch (err) {
+ console.error('[a2a-spend-ledger] rollback decrby failed:', err?.message || err);
+ }
+ return { ok: false, spent: total - amt, cap: capInt };
+ }
+ return { ok: true, spent: total, cap: capInt };
+}
+
+/**
+ * Release a previously-reserved amount (e.g. the payment failed downstream).
+ * Floors at zero so a double-release can't drive the ledger negative.
+ *
+ * @param {string} mandateId
+ * @param {number|bigint} amount
+ * @returns {Promise<number>} the resulting cumulative spend
+ */
+export async function release(mandateId, amount) {
+ const amt = asSafeInt(amount, 'amount');
+ const key = fullKey(mandateId);
+
+ if (!redis) {
+ const current = memoryGet(key);
+ const next = Math.max(0, current - amt);
+ memorySet(key, next, 0);
+ return next;
+ }
+
+ try {
+ const total = await redis.decrby(key, amt);
+ if (total < 0) {
+ await redis.set(key, 0, { keepTtl: true });
+ return 0;
+ }
+ return total;
+ } catch (err) {
+ console.error('[a2a-spend-ledger] release failed:', err?.message || err);
+ // A failed release leaves budget over-reserved (conservative) — never throw
+ // into the caller's failure path, which is already handling a payment error.
+ return -1;
+ }
+}
+
+/** Test-only hook to drop the in-memory store between tests. */
+export function _resetMemoryStore() {
+ memoryStore.clear();
+}
diff --git a/api/_lib/agent-registry.js b/api/_lib/agent-registry.js
index fb379a2ac..886ee9cf7 100644
--- a/api/_lib/agent-registry.js
+++ b/api/_lib/agent-registry.js
@@ -51,6 +51,23 @@ export async function isAgentRegistered(umi, asset) {
return identity !== null;
}
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Wait until the asset account is visible to the RPC. A freshly-minted asset can
+ * lag the node that simulates the register tx — the program then reads an empty
+ * account and rejects it as `InvalidCoreAsset` (0x4). Bounded poll closes that
+ * race for the mint-then-register path; already-minted assets resolve first try.
+ */
+async function waitForAsset(umi, assetPk, { tries = 12, delayMs = 1500 } = {}) {
+ for (let i = 0; i < tries; i++) {
+ const acct = await umi.rpc.getAccount(assetPk).catch(() => null);
+ if (acct?.exists && acct.data?.length) return true;
+ await sleep(delayMs);
+ }
+ return false;
+}
+
/**
* Register an already-minted Core asset into the Metaplex Agent Registry.
* Idempotent: if the identity PDA already exists, returns it without sending a tx.
@@ -72,13 +89,30 @@ export async function registerAgentIdentity({ umi, authoritySigner, asset, colle
return { identityPda: identityPda.toString(), signature: null, alreadyRegistered: true };
}
- const result = await registerIdentityV1(umi, {
- asset: assetPk,
- ...(collectionAddr ? { collection: umiPublicKey(collectionAddr) } : {}),
- payer: authoritySigner,
- authority: authoritySigner,
- agentRegistrationUri: registrationUri,
- }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
+ // Make sure the asset has propagated before the program reads it, then send
+ // with a couple of retries — `InvalidCoreAsset` (0x4) on a just-minted asset
+ // is the propagation race, not a real rejection, and clears within seconds.
+ await waitForAsset(umi, assetPk);
+ const build = () =>
+ registerIdentityV1(umi, {
+ asset: assetPk,
+ ...(collectionAddr ? { collection: umiPublicKey(collectionAddr) } : {}),
+ payer: authoritySigner,
+ authority: authoritySigner,
+ agentRegistrationUri: registrationUri,
+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
+
+ let result;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ result = await build();
+ break;
+ } catch (err) {
+ const racey = /Invalid Core Asset|custom program error: 0x4/i.test(err?.message || '');
+ if (!racey || attempt >= 4) throw err;
+ await sleep(2000);
+ }
+ }
return {
identityPda: identityPda.toString(),
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 6532f7010..f17c9a1a1 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -16,6 +16,10 @@ function trimSlash(s) {
return s ? s.replace(/\/$/, '') : s;
}
+// Platform owner wallets with standing admin access, independent of env config.
+// Public addresses, safe to commit. Unioned with ADMIN_ADDRESSES (see below).
+const BUILT_IN_ADMIN_ADDRESSES = ['9MjzHaTB6Jko4YKo9mDzJSaGnktzhbebgsnqPpYWnXC7'];
+
// PEM / certificate env values are frequently stored with literal "\n" escapes
// (Vercel/IBM/Okta dashboards collapse real newlines). Restore them so the
// crypto libraries get a valid multi-line PEM. Returns undefined when unset.
@@ -75,6 +79,28 @@ export const env = {
return opt('JWT_KID', 'k1');
},
+ // ── Agent-to-agent (A2A) autonomous payments ────────────────────────────
+ // Secret that signs Intent Mandates (AP2-style budgeted spend authorizations).
+ // Dedicated by preference; falls back to JWT_SECRET so the feature works in
+ // dev/CI without extra config. Production should set a distinct value so
+ // rotating session auth never invalidates outstanding mandates and vice versa.
+ get A2A_MANDATE_SECRET() {
+ return opt('A2A_MANDATE_SECRET') || this.JWT_SECRET;
+ },
+ // EVM private key for the autonomous payer wallet that signs EIP-3009
+ // authorizations when an agent pays a peer under a mandate. MUST be a wallet
+ // the platform funds with USDC — never a payment-receiving X402_PAY_TO_* key.
+ // Unset → the a2a-call endpoint returns a designed 501 instead of paying.
+ get A2A_PAYER_PRIVATE_KEY() {
+ return opt('A2A_PAYER_PRIVATE_KEY');
+ },
+ // RPC URL used for read-only ERC-8004 reputation lookups when gating which
+ // peers an agent is allowed to pay. Optional — reputation gating is opt-in
+ // per call and skipped when no RPC is configured and no threshold is set.
+ get A2A_REPUTATION_RPC_URL() {
+ return opt('A2A_REPUTATION_RPC_URL') || opt('EVM_RPC_URL');
+ },
+
get PASSWORD_ROUNDS() {
return parseInt(opt('PASSWORD_ROUNDS', '11'), 10);
},
@@ -261,11 +287,13 @@ export const env = {
// Comma-separated wallet addresses (EVM or Solana) that have admin access.
// Bootstrap: set to your own wallet address. Can also be promoted via DB is_admin flag.
+ // BUILT_IN_ADMIN_ADDRESSES are platform owners baked in so admin access survives
+ // without env config; they are unioned with anything ADMIN_ADDRESSES supplies.
+ // Addresses are normalised to lower-case to match the lookup in requireAdmin.
get ADMIN_ADDRESSES() {
const raw = opt('ADMIN_ADDRESSES', '');
return new Set(
- raw
- .split(',')
+ [...BUILT_IN_ADMIN_ADDRESSES, ...raw.split(',')]
.map((a) => a.trim().toLowerCase())
.filter(Boolean),
);
diff --git a/api/_lib/llm-pricing.js b/api/_lib/llm-pricing.js
new file mode 100644
index 000000000..e373cca75
--- /dev/null
+++ b/api/_lib/llm-pricing.js
@@ -0,0 +1,55 @@
+// LLM cost model. Converts a provider/model/token-usage triple into a cost in
+// micro-USD (1 unit = $0.000001) so usage_events.cost_micro_usd can be summed
+// without float drift. This is the single source of truth for "what did that
+// call cost us" — the admin spend dashboard reads the events this priced.
+//
+// Anthropic prices are list price per 1M tokens (input / output), current as of
+// the Claude model catalog. Groq and OpenRouter are platform-funded free tiers
+// (we hold the key, callers pay nothing), so their marginal cost to us is $0 —
+// they are intentionally priced at zero, not omitted, so the dashboard can show
+// "calls served free" alongside paid spend.
+
+// USD per 1,000,000 tokens, [input, output]. Keys are matched by prefix so a
+// dated alias (claude-haiku-4-5-20251001) resolves to its family price.
+const PRICE_PER_MTOK = {
+ 'claude-opus-4-8': [5, 25],
+ 'claude-opus-4-7': [5, 25],
+ 'claude-opus-4-6': [5, 25],
+ 'claude-opus-4-5': [5, 25],
+ 'claude-sonnet-4-6': [3, 15],
+ 'claude-sonnet-4-5': [3, 15],
+ 'claude-haiku-4-5': [1, 5],
+};
+
+// Providers whose marginal cost to the platform is zero (platform-funded keys).
+const FREE_PROVIDERS = new Set(['groq', 'openrouter', 'nvidia']);
+
+function priceForModel(model) {
+ if (!model) return null;
+ // Longest-prefix match so 'claude-haiku-4-5-20251001' hits 'claude-haiku-4-5'
+ // and never a shorter, wrong family.
+ let best = null;
+ for (const key of Object.keys(PRICE_PER_MTOK)) {
+ if (model.startsWith(key) && (!best || key.length > best.length)) best = key;
+ }
+ return best ? PRICE_PER_MTOK[best] : null;
+}
+
+// Compute the cost of one completion in micro-USD. Returns an integer (rounded)
+// or 0 when the provider is free or the model is unpriced — never null, so the
+// caller can always record a numeric cost.
+export function costMicroUsd({ provider, model, input = 0, output = 0 } = {}) {
+ if (provider && FREE_PROVIDERS.has(provider)) return 0;
+ const price = priceForModel(model);
+ if (!price) return 0;
+ const [inPerM, outPerM] = price;
+ // tokens / 1e6 * usdPerM * 1e6 micro-usd == tokens * usdPerM
+ const usdMicros = input * inPerM + output * outPerM;
+ return Math.round(usdMicros);
+}
+
+// Whether we have a real price for this model (vs. defaulting to 0). Lets the
+// dashboard distinguish "free provider" from "paid provider we can't price yet".
+export function isPriced(model) {
+ return priceForModel(model) != null;
+}
diff --git a/api/_lib/llm.js b/api/_lib/llm.js
index 149abbe20..a3286e2e5 100644
--- a/api/_lib/llm.js
+++ b/api/_lib/llm.js
@@ -16,6 +16,8 @@
// api/persona/extract.js and api/persona/preview.js.
import { env } from './env.js';
+import { recordEvent } from './usage.js';
+import { costMicroUsd } from './llm-pricing.js';
const GROQ_MODEL = 'llama-3.3-70b-versatile';
const OPENROUTER_MODEL = 'meta-llama/llama-3.3-70b-instruct';
@@ -122,12 +124,21 @@ export function llmConfigured(opts = {}) {
// Returns { text, provider, model, usage:{input,output}, raw }.
// Throws LlmUnavailableError when no provider is configured, or the last
// upstream error (with .status = 502) when every provider failed.
-export async function llmComplete({ system, user, maxTokens = 1024, anthropicKey = null, anthropicModel = null, serverAnthropic = false, timeoutMs = 30_000 }) {
+//
+// `track` is optional attribution for the spend ledger. When supplied, every
+// successful completion records a kind:'llm' usage event carrying the provider,
+// model, token counts, and computed cost (micro-USD) — this is what makes
+// platform LLM spend visible on the admin dashboard. The fields it accepts —
+// { userId, agentId, avatarId, clientId, apiKeyId, tool } — are all optional;
+// pass whatever the call site knows. Recording is fire-and-forget (see
+// recordEvent), so it never delays or fails the completion.
+export async function llmComplete({ system, user, maxTokens = 1024, anthropicKey = null, anthropicModel = null, serverAnthropic = false, timeoutMs = 30_000, track = null }) {
const chain = providerChain({ anthropicKey, anthropicModel, serverAnthropic });
if (!chain.length) throw new LlmUnavailableError();
let lastErr;
for (const p of chain) {
+ const startedAt = Date.now();
let upstream;
try {
upstream = await fetch(p.url, {
@@ -146,13 +157,39 @@ export async function llmComplete({ system, user, maxTokens = 1024, anthropicKey
continue;
}
const data = await upstream.json();
+ const usage = p.extractUsage(data);
+ recordLlmSpend(p, usage, Date.now() - startedAt, track);
return {
text: (p.extractText(data) || '').trim(),
provider: p.name,
model: p.model,
- usage: p.extractUsage(data),
+ usage,
raw: data,
};
}
throw lastErr || new LlmUnavailableError();
}
+
+// Fire-and-forget spend ledger write for one completion. Attribution comes from
+// the caller's optional `track`; the cost is derived from the provider/model
+// (free providers price to 0). Never throws — recordEvent swallows its own
+// errors and the cost math is total.
+function recordLlmSpend(provider, usage, latencyMs, track) {
+ const input = usage?.input ?? 0;
+ const output = usage?.output ?? 0;
+ recordEvent({
+ kind: 'llm',
+ provider: provider.name,
+ model: provider.model,
+ inputTokens: input,
+ outputTokens: output,
+ costMicroUsd: costMicroUsd({ provider: provider.name, model: provider.model, input, output }),
+ latencyMs,
+ userId: track?.userId ?? null,
+ agentId: track?.agentId ?? null,
+ avatarId: track?.avatarId ?? null,
+ clientId: track?.clientId ?? null,
+ apiKeyId: track?.apiKeyId ?? null,
+ tool: track?.tool ?? null,
+ });
+}
diff --git a/api/_lib/migrations/20260608010000_usage_events_llm_cost.sql b/api/_lib/migrations/20260608010000_usage_events_llm_cost.sql
new file mode 100644
index 000000000..4fd70b91d
--- /dev/null
+++ b/api/_lib/migrations/20260608010000_usage_events_llm_cost.sql
@@ -0,0 +1,24 @@
+-- usage_events — LLM cost accounting columns.
+--
+-- usage_events already logs that an LLM call happened (kind='llm') but not which
+-- provider/model served it, how many tokens it burned, or what it cost. Without
+-- that, platform LLM spend (e.g. the Anthropic credit balance) is invisible.
+--
+-- This migration is purely additive and idempotent — safe to run repeatedly and
+-- against a DB that already has the columns. Cost is stored in micro-USD
+-- (1 cost_micro_usd = $0.000001) as a bigint so spend sums never drift on floats.
+
+alter table usage_events add column if not exists provider text;
+alter table usage_events add column if not exists model text;
+alter table usage_events add column if not exists input_tokens int;
+alter table usage_events add column if not exists output_tokens int;
+alter table usage_events add column if not exists cost_micro_usd bigint;
+
+-- Spend reads scan llm events over a time window and group by provider/model.
+create index if not exists usage_events_llm_time
+ on usage_events(created_at desc)
+ where kind = 'llm';
+
+create index if not exists usage_events_llm_provider_time
+ on usage_events(provider, created_at desc)
+ where kind = 'llm' and provider is not null;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index b2050b04b..bb0d411ca 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -732,6 +732,16 @@ create index if not exists solana_creds_kind on solana_credentials(kind,
alter table usage_events add column if not exists agent_id uuid references agent_identities(id) on delete set null;
create index if not exists usage_events_agent_time on usage_events(agent_id, created_at desc) where agent_id is not null;
+-- LLM cost accounting (see migrations/20260608010000_usage_events_llm_cost.sql).
+-- cost_micro_usd is micro-USD ($0.000001) as bigint so spend sums never drift.
+alter table usage_events add column if not exists provider text;
+alter table usage_events add column if not exists model text;
+alter table usage_events add column if not exists input_tokens int;
+alter table usage_events add column if not exists output_tokens int;
+alter table usage_events add column if not exists cost_micro_usd bigint;
+create index if not exists usage_events_llm_time on usage_events(created_at desc) where kind = 'llm';
+create index if not exists usage_events_llm_provider_time on usage_events(provider, created_at desc) where kind = 'llm' and provider is not null;
+
-- ── agent_registrations_pending — transient prep records for 2-step registration ─────
create table if not exists agent_registrations_pending (
id uuid primary key default gen_random_uuid(),
diff --git a/api/_lib/usage.js b/api/_lib/usage.js
index d0c6e7bfb..9a161cd73 100644
--- a/api/_lib/usage.js
+++ b/api/_lib/usage.js
@@ -8,7 +8,7 @@ export function recordEvent(evt) {
queueMicrotask(async () => {
try {
await withDbRetry(() => sql`
- insert into usage_events (user_id, api_key_id, client_id, avatar_id, agent_id, kind, tool, status, bytes, latency_ms, meta)
+ insert into usage_events (user_id, api_key_id, client_id, avatar_id, agent_id, kind, tool, status, bytes, latency_ms, meta, provider, model, input_tokens, output_tokens, cost_micro_usd)
values (
${evt.userId ?? null},
${evt.apiKeyId ?? null},
@@ -20,7 +20,12 @@ export function recordEvent(evt) {
${evt.status ?? 'ok'},
${evt.bytes ?? null},
${evt.latencyMs ?? null},
- ${JSON.stringify(evt.meta ?? {})}::jsonb
+ ${JSON.stringify(evt.meta ?? {})}::jsonb,
+ ${evt.provider ?? null},
+ ${evt.model ?? null},
+ ${evt.inputTokens ?? null},
+ ${evt.outputTokens ?? null},
+ ${evt.costMicroUsd ?? null}
)
`);
} catch (err) {
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 69893a2ae..632410a95 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -171,9 +171,9 @@ const PROVIDERS = {
'nvidia-nemotron-nano': {
label: 'Nemotron Nano 9B',
network: 'NVIDIA NIM',
- tier: 'fast',
+ tier: 'balanced',
maxOutput: 8192,
- description: 'Compact, low-latency Nemotron. Great default for simple agent turns.',
+ description: 'Compact Nemotron with built-in reasoning. Strong quality per token.',
native: () => (env.NVIDIA_API_KEY ? nvidia('nvidia/nvidia-nemotron-nano-9b-v2') : null),
},
'nvidia-deepseek-v4': {
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index a5867f5b5..c54d4c7b8 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -278,12 +278,19 @@ export default wrap(async (req, res) => {
// Ordered fallback chain for 429 / 5xx from OpenRouter free tier:
// 1. Requested model (e.g. llama-3.3-70b:free)
- // 2. meta-llama/llama-3.1-8b-instruct:free (smaller free model)
- // 3. claude-haiku-4-5-20251001 (paid Anthropic — last resort)
+ // 2. meta-llama/llama-3.1-8b-instruct:free (smaller free model)
+ // 3. meta/llama-4-maverick-17b-128e-instruct (free NVIDIA NIM tier)
+ // 4. claude-haiku-4-5-20251001 (paid Anthropic — last resort)
+ // The NVIDIA free tier sits ahead of paid Anthropic so a rate-limited OpenRouter
+ // free model exhausts every free option before any per-token cost is incurred.
+ // A non-reasoning model is used here on purpose: a reasoning model can spend a
+ // small max_tokens budget entirely on (dropped) reasoning_content and return an
+ // empty completion to the embedded agent.
const modelFallbacks = [
requestedModel,
...([
'meta-llama/llama-3.1-8b-instruct:free',
+ 'meta/llama-4-maverick-17b-128e-instruct',
'claude-haiku-4-5-20251001',
].filter((m) => m !== requestedModel)),
];
diff --git a/public/avatars/mannequin.glb b/public/avatars/mannequin.glb
new file mode 100644
index 000000000..5dee3a6ce
Binary files /dev/null and b/public/avatars/mannequin.glb differ
diff --git a/scripts/bake-mannequin-glb.mjs b/scripts/bake-mannequin-glb.mjs
new file mode 100644
index 000000000..7338ed833
--- /dev/null
+++ b/scripts/bake-mannequin-glb.mjs
@@ -0,0 +1,72 @@
+// Bake the procedural /pose mannequin into a real GLB asset.
+//
+// The mannequin is generated in code (src/pose-mannequin.js) from Three.js
+// primitives — it has no on-disk model. This script instantiates that exact
+// class in its rest pose and exports it through GLTFExporter, so the baked
+// asset and the live /pose figure stay a single source of truth: change the
+// proportions in pose-mannequin.js, re-run this, and the GLB follows.
+//
+// Output: public/avatars/mannequin.glb (the universal base avatar).
+//
+// Usage: node scripts/bake-mannequin-glb.mjs [--build male|female] [--out path]
+
+import { writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+// GLTFExporter's binary path reads the assembled Blob through a FileReader,
+// which exists in browsers but not in Node. Provide a minimal shim backed by
+// Node's global Blob before importing the exporter.
+if (typeof globalThis.FileReader === 'undefined') {
+ globalThis.FileReader = class {
+ readAsArrayBuffer(blob) {
+ blob.arrayBuffer().then((buf) => {
+ this.result = buf;
+ this.onloadend?.();
+ }).catch((err) => {
+ this.error = err;
+ this.onerror?.(err);
+ });
+ }
+ };
+}
+
+import { Scene } from 'three';
+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+import { Mannequin } from '../src/pose-mannequin.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(__dirname, '..');
+
+function arg(flag, fallback) {
+ const i = process.argv.indexOf(flag);
+ return i !== -1 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
+}
+
+const build = arg('--build', 'male');
+const outPath = resolve(repoRoot, arg('--out', 'public/avatars/mannequin.glb'));
+
+// Build the figure in its neutral rest pose (all joint rotations zero → the
+// figure stands upright, arms at sides). Name it so downstream loaders and the
+// pose rig can recognise the root.
+const mannequin = new Mannequin({ build, color: '#d4d4d8' });
+mannequin.resetPose();
+
+const scene = new Scene();
+scene.name = 'three-ws-mannequin';
+scene.add(mannequin.root);
+
+const exporter = new GLTFExporter();
+const result = await exporter.parseAsync(scene, {
+ binary: true,
+ // No textures on the mannequin, so embedImages is a no-op — kept explicit
+ // for parity with the /pose export path.
+ embedImages: true,
+ onlyVisible: true,
+});
+
+const buffer = Buffer.from(result instanceof ArrayBuffer ? result : new Uint8Array(result));
+writeFileSync(outPath, buffer);
+
+const kb = (buffer.byteLength / 1024).toFixed(1);
+console.log(`Baked ${build} mannequin → ${outPath} (${kb} KB)`);
diff --git a/scripts/login-scroll-probe.mjs b/scripts/login-scroll-probe.mjs
new file mode 100644
index 000000000..7532baec5
--- /dev/null
+++ b/scripts/login-scroll-probe.mjs
@@ -0,0 +1,47 @@
+import puppeteer from 'puppeteer';
+
+const base = process.argv[2] || 'http://localhost:3001';
+const browser = await puppeteer.launch({ args: ['--no-sandbox', '--use-gl=swiftshader', '--enable-webgl'] });
+const page = await browser.newPage();
+await page.setViewport({ width: 1440, height: 900 });
+await page.goto(`${base}/login.html`, { waitUntil: 'networkidle2' });
+await new Promise(r => setTimeout(r, 2500));
+
+const probe = async () => page.evaluate(() => {
+ const wrap = document.getElementById('login-avatar-wrap');
+ const canvas = document.getElementById('avatar-canvas');
+ const wr = wrap?.getBoundingClientRect();
+ const cr = canvas?.getBoundingClientRect();
+ const cs = wrap ? getComputedStyle(wrap) : null;
+ return {
+ scrollY: window.scrollY,
+ docScroll: document.scrollingElement?.scrollTop,
+ bodyScrollH: document.body.scrollHeight,
+ innerH: window.innerHeight,
+ canvasPos: canvas ? getComputedStyle(canvas).position : null,
+ canvasTop: cr ? Math.round(cr.top) : null,
+ wrapDisplay: cs?.display,
+ wrapPos: cs?.position,
+ wrapTop: wr ? Math.round(wr.top) : null,
+ wrapH: wr ? Math.round(wr.height) : null,
+ };
+});
+
+const before = await probe();
+await page.evaluate(() => window.scrollTo(0, 400));
+await new Promise(r => setTimeout(r, 600));
+const after = await probe();
+
+console.log('BEFORE scroll:', JSON.stringify(before));
+console.log('AFTER scroll:', JSON.stringify(after));
+console.log('canvas moved on scroll?', before.canvasTop !== after.canvasTop, `(Δ${after.canvasTop - before.canvasTop})`);
+
+await page.evaluate(() => window.scrollTo(0, 0));
+await new Promise(r => setTimeout(r, 600));
+await page.screenshot({ path: '/tmp/login-scroll0.png' });
+await page.evaluate(() => window.scrollTo(0, 400));
+await new Promise(r => setTimeout(r, 600));
+await page.screenshot({ path: '/tmp/login-scroll400.png' });
+console.log('screenshots written');
+
+await browser.close();
diff --git a/sdk/agent-sdk/tsconfig.json b/sdk/agent-sdk/tsconfig.json
index 039e0b4d1..6d05c0ddb 100644
--- a/sdk/agent-sdk/tsconfig.json
+++ b/sdk/agent-sdk/tsconfig.json
@@ -1,7 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
- "outDir": "dist"
+ "outDir": "dist",
+ "types": ["node"]
},
- "include": ["src"]
+ "include": ["src"],
+ "exclude": ["dist", "node_modules"]
}
diff --git a/src/game/boot-avatar.js b/src/game/boot-avatar.js
index 0e08d1d3f..f6fa08dc3 100644
--- a/src/game/boot-avatar.js
+++ b/src/game/boot-avatar.js
@@ -25,7 +25,7 @@ import {
AVATAR_DEFAULT, loadManifest, getLocomotionDefs, CLIP_IDLE,
resolveAvatarUrl, dracoLoader,
} from './avatar-rig.js';
-import { getPlayAvatar } from './play-handoff.js';
+import { getRequestedAvatar } from './play-handoff.js';
import { log } from '../shared/log.js';
const REDUCED_MOTION = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
@@ -65,14 +65,16 @@ function boot() {
window.addEventListener('resize', sizeToBox, { passive: true });
- // Preview the avatar the player has actually chosen (persisted in cc-avatar by
- // the lobby / a create→play handoff), not a generic default — so the first
- // character they see while the scene loads is *theirs*. DRACO is wired in
+ // Preview the avatar this session should show — an `?avatar=` deep link (an
+ // agent's GLB via a "See in 3D" link) if present, otherwise the one the player
+ // chose (persisted in cc-avatar by the lobby / a create→play handoff) — not a
+ // generic default, so the first character they see while the scene loads is the
+ // right one. DRACO is wired in
// because most avatar GLBs are compressed. Falls back to the default on any
// resolve/load failure so a broken pick never wedges the loader.
const loader = new GLTFLoader();
loader.setDRACOLoader(dracoLoader);
- resolveAvatarUrl(getPlayAvatar())
+ resolveAvatarUrl(getRequestedAvatar())
.then((chosen) => loader.loadAsync(chosen).catch(() => loader.loadAsync(AVATAR_DEFAULT)))
.then(async (gltf) => {
if (!alive) return;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index a97166b67..392124415 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 } from './play-handoff.js';
+import { GUEST_SENTINEL, uploadPendingGuestAvatar, getPlayCosmetics, setPlayCosmetics, getRequestedAvatar } from './play-handoff.js';
import { applyLoadout } from './cosmetics-loadout.js';
import { serializeLoadout } from '../../multiplayer/src/cosmetics-catalog.js';
import { AccessoryManager } from '../agent-accessories.js';
@@ -723,7 +723,10 @@ export class CoinCommunities {
this._accessoryMgr = null;
this._previewItem = null;
this.localAnim = new AnimationManager();
- const avatarInput = this.ui.getAvatar();
+ // 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();
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/game/play-handoff.js b/src/game/play-handoff.js
index a1dfa04f3..f98bb0da9 100644
--- a/src/game/play-handoff.js
+++ b/src/game/play-handoff.js
@@ -36,6 +36,18 @@ export function getPlayAvatar() {
try { return localStorage.getItem(CC_AVATAR_KEY) || ''; } catch { return ''; }
}
+// The avatar a world should actually show this session. An `?avatar=<glb|id>`
+// URL param wins over the saved pick — that's how "See in 3D" links drop an
+// agent's avatar into a world without overwriting the visitor's own cc-avatar.
+// Falls back to the persisted avatar (and that to the default) when absent.
+export function getRequestedAvatar() {
+ try {
+ const fromUrl = new URLSearchParams(location.search).get('avatar');
+ if (fromUrl && fromUrl.trim()) return fromUrl.trim();
+ } catch { /* no URL access — fall through to the saved avatar */ }
+ return getPlayAvatar();
+}
+
// Persist the avatar every world reads. Prefer a canonical id; fall back to a
// loadable URL/path or the guest sentinel. Returns the stored value.
export function setPlayAvatar(value) {
diff --git a/src/solana/vanity/grinder-worker.js b/src/solana/vanity/grinder-worker.js
index 40758876b..da397ec3b 100644
--- a/src/solana/vanity/grinder-worker.js
+++ b/src/solana/vanity/grinder-worker.js
@@ -4,8 +4,15 @@
* Loops keypair generation inside a WASM module (Rust + ed25519-dalek)
* and reports matches + progress back to the host. The hot loop runs
* entirely inside WASM in fixed-size batches; between batches the worker
- * yields to its event loop so 'stop' messages from the host can be
- * processed promptly (bounded abort latency).
+ * yields to its event loop so 'stop'/'pause' messages from the host get
+ * processed promptly (bounded latency, one batch).
+ *
+ * Control messages from the host:
+ * - start : begin a fresh grind (resets the attempt counter)
+ * - pause : exit the hot loop, freeing the core, but keep the worker and
+ * its accumulated attempt count alive
+ * - resume : re-enter the hot loop, continuing the attempt count
+ * - stop : exit the hot loop for good (host terminates the worker)
*
* Algorithm parity with nirholas/solana-wallet-toolkit
* (typescript/src/lib/generator.ts). The WASM module is built from
@@ -15,11 +22,17 @@
import init, { grind } from './wasm/vanity_grinder.js';
// Keep batches small enough that one WASM call returns within ~200 ms even
-// on slow CPUs — abort latency is bounded by one batch.
+// on slow CPUs — pause/abort latency is bounded by one batch.
const BATCH_SIZE = 5000;
const PROGRESS_INTERVAL_MS = 250;
let running = false;
+// Guards against two grindLoop()s racing if 'resume' arrives before the
+// previous loop has fully unwound.
+let looping = false;
+// Survives pause/resume so the host's per-worker totals stay monotonic.
+let attempts = 0;
+let cfg = { prefix: '', suffix: '', ignoreCase: false };
let wasmReady = null;
function ensureWasm() {
@@ -38,34 +51,40 @@ function ensureWasm() {
self.onmessage = (e) => {
const msg = e.data;
if (msg?.type === 'start') {
+ cfg = { prefix: msg.prefix || '', suffix: msg.suffix || '', ignoreCase: !!msg.ignoreCase };
+ attempts = 0;
+ running = true;
+ kick();
+ } else if (msg?.type === 'resume') {
running = true;
- grindLoop(msg.prefix || '', msg.suffix || '', !!msg.ignoreCase);
- } else if (msg?.type === 'stop') {
+ kick();
+ } else if (msg?.type === 'pause' || msg?.type === 'stop') {
running = false;
}
};
-/**
- * @param {string} prefix
- * @param {string} suffix
- * @param {boolean} ignoreCase
- */
-async function grindLoop(prefix, suffix, ignoreCase) {
+/** Start the hot loop unless one is already in flight. */
+function kick() {
+ if (!looping) grindLoop();
+}
+
+async function grindLoop() {
+ looping = true;
try {
await ensureWasm();
} catch (err) {
self.postMessage({ type: 'error', message: String(err?.message || err) });
+ looping = false;
return;
}
- let attempts = 0;
let lastProgress = performance.now();
- let lastProgressAttempts = 0;
+ let lastProgressAttempts = attempts;
const seed = new Uint8Array(32);
while (running) {
crypto.getRandomValues(seed);
- const hit = grind(prefix, suffix, ignoreCase, BATCH_SIZE, seed);
+ const hit = grind(cfg.prefix, cfg.suffix, cfg.ignoreCase, BATCH_SIZE, seed);
attempts += BATCH_SIZE;
if (hit) {
@@ -76,7 +95,7 @@ async function grindLoop(prefix, suffix, ignoreCase) {
attempts,
}, [hit.secretKey.buffer]);
running = false;
- return;
+ break;
}
const now = performance.now();
@@ -86,8 +105,10 @@ async function grindLoop(prefix, suffix, ignoreCase) {
self.postMessage({ type: 'progress', attempts, rate });
lastProgress = now;
lastProgressAttempts = attempts;
- // Yield to the event loop so 'stop' messages get processed.
+ // Yield to the event loop so 'pause'/'stop' messages get processed.
await new Promise((r) => setTimeout(r, 0));
}
}
+
+ looping = false;
}
diff --git a/src/solana/vanity/grinder.js b/src/solana/vanity/grinder.js
index 849e04e13..3cd0f40c2 100644
--- a/src/solana/vanity/grinder.js
+++ b/src/solana/vanity/grinder.js
@@ -29,9 +29,23 @@ const DEFAULT_MAX_WORKERS = 8;
* @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 {number} [maxWorkers] - Number of workers to spawn (1..hardwareConcurrency). Defaults to min(hardwareConcurrency, 8).
* @property {AbortSignal} [signal] - Cancel the grind.
- * @property {(p: { attempts: number, rate: number, eta: string }) => void} [onProgress]
+ * @property {GrindController} [controller] - Opt-in handle for pause/resume/stop. Methods are wired in once workers spawn.
+ * @property {(p: { attempts: number, rate: number, eta: string, paused?: boolean }) => void} [onProgress]
+ */
+
+/**
+ * @typedef {object} GrindController
+ * Pass a plain object as `opts.controller`; grindVanity attaches the methods
+ * below once the worker pool is live. Pausing exits each worker's hot loop —
+ * the cores are genuinely freed — while preserving accumulated attempts so
+ * resume picks up where it left off.
+ * @property {() => void} [pause] - Suspend all workers (no-op if already paused/finished).
+ * @property {() => void} [resume] - Resume all workers (no-op if not paused).
+ * @property {() => void} [stop] - Abort the grind (rejects the promise with AbortError).
+ * @property {boolean} [paused] - Current paused state.
+ * @property {number} [workers] - Number of workers actually spawned.
*/
/**
@@ -63,10 +77,12 @@ export function grindVanity(opts = {}) {
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 hardware = (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4;
+ // An explicit maxWorkers is honored up to the machine's core count;
+ // without one we default to a conservative min(hardware, 8) so we don't
+ // peg every core by surprise.
+ const requested = opts.maxWorkers || Math.min(hardware, DEFAULT_MAX_WORKERS);
+ const cores = Math.max(1, Math.min(requested, hardware));
const expected = estimateAttempts((prefix?.length || 0) + (suffix?.length || 0));
const startedAt = performance.now();