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: agent activation onboarding, platform treasury, and x402 merchant updates
nirholas271835054ebc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 70d847337..44a045ca3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Fixed /play getting stuck on "too many requests"** — Opening /play could dead-end on a "Something went wrong — too many requests" screen, especially from a shared network or after a couple of reloads. The wallet sign-in step was sharing the same strict rate limit as login and trading, so a small burst of page loads exhausted it. Sign-in now has its own generous limit sized for a busy world, and if that check ever can't be reached, /play opens anyway instead of blocking — the game server still verifies token-gated worlds on entry. (`/play`) `[fix]`- **Hardened Redis credentials against dashboard paste errors** — A trailing newline or stray space on the Upstash Redis token — the kind that creeps in when pasting into a dashboard — was being sent verbatim in the auth header and rejected as WRONGPASS, while the URL still resolved. The result was thousands of failures an hour: paid endpoints denying, the payments feed not loading, usage telemetry and caches going dark. Redis credentials are now trimmed at the source (matching how wallet addresses, RPC URLs, and certificates are already sanitized), so a single stray character can never silently take the limiter, feed, and caches offline. `[fix, infra]`- **Improved resilience during database outages** — API endpoints now return HTTP 503 (Service Unavailable) with a Retry-After header instead of 500 when the database is temporarily unreachable, so clients and caches know to back off and retry rather than treating it as a permanent error. Background crons skip their tick gracefully and log a warning instead of firing repeated alert storms. A single deduped ops alert now covers the whole outage. `[fix, infra]`+- **Live agent screens restored and refreshed in monochrome** — Watching agents work — their live screens, avatar cam, and activity feed — is back. A missing rate-limit binding had been crashing the endpoints behind the scenes, so the roster on /agents-live never populated, agents couldn't broadcast frames, and tasks wouldn't queue; all three paths now respond correctly. The Live Agents grid and the single-agent screen viewer were also rebuilt in a crisp monochrome palette, and the watch grid now pauses its streams when the tab is in the background so it stays light on bandwidth. (`/agents-live`) `[fix, improvement]`- **Live Agents mission control + one-click session launcher** — New /agents-live page shows a real-time grid of every AI agent with an active screen stream — watch their screens and avatar feeds live, all in one view. Agent owners now get a "Start Live Session" panel on any watch view: click Generate credentials, copy the Docker or Node launch command, run it anywhere, and the agent browser session starts streaming to the screen canvas instantly. Sessions are signed 7-day bearer tokens, no extra setup required. (`/agents-live`) `[feature]`- **Manage your AWS Marketplace API key — new keys & usage page** — AWS Marketplace subscribers (and anyone with an x402 subscription key) now have a home for it at /billing/keys. See every key with its billing source — AWS Marketplace or on-chain — live status, rate limit, total calls, and when it was last used. Rotate a key to get a fresh secret in one click (AWS-billed keys stay linked to your AWS account and keep metering correctly), or revoke a native key outright. The post-subscribe welcome flow now points here, so a lost key is always recoverable by rotating instead of being stuck. (`/billing/keys`) `[feature]`- **Money Pulse now shows whether agent trading is viable** — The Pulse page gained a Trading viability panel — the honest signal behind the headline Trades counter. It shows what's actually flowing through agent wallets: trades over 24h and 7 days, the SOL deployed into buys (what the trading is costing), the average trade size, how many wallets are trading right now, and — once positions close — the realized profit-and-loss with a win rate, alongside a 7-day trade sparkline and the top trading agents. The 24h trade count reconciles exactly with the headline counter, so the panel can never drift from the number at the top of the page. Every figure is a real, on-chain custody event or a closed position priced against real fills — never synthetic. (`/pulse`) `[feature, improvement]`diff --git a/api/_lib/agent-activation.js b/api/_lib/agent-activation.jsnew file mode 100644index 000000000..ef5ff5dd8--- /dev/null+++ b/api/_lib/agent-activation.js@@ -0,0 +1,353 @@+// @ts-check+// Agent activation — the onboarding "Go Live" welcome grant.+//+// Distinct from USER activation (api/_lib/activation.js, the first-3D-win+// milestone): this is the AGENT-wallet cold-start fix.+//+// The cold-start problem: a freshly created agent gets a custodial wallet, but on+// mainnet that wallet starts at ◎0. With no funds it can never make its first+// transaction, so it never appears on the Money Pulse and never counts as an+// active wallet. The funnel dead-ends at "wallet created".+//+// Activation fixes that with a real, one-time, on-chain platform grant: the+// treasury sends a small amount of SOL to the agent's wallet and the transfer is+// recorded as a genuine `tip` custody event. The agent is now BOTH funded (it can+// transact) AND active (it shows on the Pulse, in tips, and in active-wallet+// counts) — from a single, honest, explorer-verifiable transaction the owner can+// see. It is a welcome bonus, framed as exactly that; there is nothing synthetic.+//+// Guarantees:+// · Exactly one grant per agent — enforced by the agent_activations primary key+// and a pending→confirmed status mutex, so concurrent POSTs can't double-spend.+// · Owner-only, real agents only (platform circulation agents are excluded).+// · A rolling daily cap bounds spend; per-IP/user rate limiting lives at the route.+// · Fully inert + graceful when no treasury is configured (status: not_configured).++import { sql } from './db.js';+import {+ isConfigured,+ getTreasuryKeypair,+ transferSol,+ lamportBalance,+ treasuryConnection,+ treasuryNetwork,+ FEE_BUFFER,+ SOL,+} from './platform-treasury.js';+import { ensureAgentWallet } from './agent-wallet.js';+import { recordCustodyEvent } from './agent-trade-guards.js';+import { solUsdPrice, explorerTxUrl } from './avatar-wallet.js';+import { publishFeedEvent } from './feed.js';+import { insertNotification } from './notify.js';++// Env override so a flow can point activation at its own funded wallet; otherwise+// the shared operator treasury (CIRCULATION_TREASURY_SECRET) funds the grant.+const TREASURY_ENV_OVERRIDE = 'AGENT_ACTIVATION_TREASURY_SECRET';++function clampNumber(v, dflt, lo, hi) {+ const n = Number(v);+ if (!Number.isFinite(n)) return dflt;+ return Math.min(hi, Math.max(lo, n));+}++/** Resolved activation configuration from env. Cheap + side-effect free. */+export function activationConfig() {+ const enabledRaw = String(process.env.AGENT_ACTIVATION_ENABLED ?? '').toLowerCase();+ const enabled = enabledRaw === '1' || enabledRaw === 'true' || enabledRaw === 'yes';+ // Grant size in SOL. Small on purpose: enough to fund a first real action ++ // fees, not a faucet to farm. 0.0001–0.05 SOL hard-bounded.+ const grantSol = clampNumber(process.env.AGENT_ACTIVATION_GRANT_SOL, 0.004, 0.0001, 0.05);+ const dailyCap = clampNumber(process.env.AGENT_ACTIVATION_DAILY_CAP, 500, 1, 100_000);+ return {+ enabled,+ configured: isConfigured(TREASURY_ENV_OVERRIDE),+ network: treasuryNetwork(),+ grantSol,+ grantLamports: Math.round(grantSol * SOL),+ dailyCap,+ };+}++/** True when this agent is platform-operated (circulation) rather than a real user's. */+function isCirculationAgent(agent) {+ return String(agent?.meta?.circulation ?? '') === 'true';+}++// Load the activation ledger row for an agent (or null). Tolerates the table not+// existing yet (pre-migration) so status reads never 500 a profile.+async function loadActivationRow(agentId) {+ try {+ const [row] = await sql`+ select agent_id, user_id, network, status, signature, lamports, usd, created_at, confirmed_at+ from agent_activations where agent_id = ${agentId} limit 1+ `;+ return row || null;+ } catch (err) {+ if (err?.code === '42P01') return null; // table not migrated yet+ throw err;+ }+}++// Shape a confirmed ledger row into the public activation receipt.+function receipt(row, network) {+ if (!row || row.status !== 'confirmed') return null;+ const sol = row.lamports != null ? Number(row.lamports) / SOL : null;+ return {+ signature: row.signature,+ explorer: row.signature ? explorerTxUrl(row.signature, row.network || network) : null,+ sol,+ usd: row.usd != null ? Number(row.usd) : null,+ activated_at: row.confirmed_at || row.created_at,+ network: row.network || network,+ };+}++/**+ * Read-only activation status for an agent, from the owner's perspective. Used by+ * the wallet hub to decide which state to render. Never mutates, never throws on+ * infra trouble (degrades to a safe "can't determine" shape).+ *+ * @param {{ agent: any, isOwner: boolean }} args+ */+export async function getActivationStatus({ agent, isOwner }) {+ const cfg = activationConfig();+ const row = await loadActivationRow(agent.id).catch(() => null);+ const activated = !!row && row.status === 'confirmed';+ const pending = !!row && row.status === 'pending';+ const circulation = isCirculationAgent(agent);+ const hasWallet = !!(agent.solana_address || agent.meta?.solana_address);++ // Eligibility = a real, owned, not-yet-activated agent on a configured+enabled+ // platform. A missing wallet is NOT a blocker — activation provisions it.+ let eligible = false;+ let reason = null;+ if (!isOwner) reason = 'not_owner';+ else if (circulation) reason = 'platform_agent';+ else if (activated) reason = 'already_activated';+ else if (pending) reason = 'in_progress';+ else if (!cfg.enabled || !cfg.configured) reason = 'not_configured';+ else eligible = true;++ return {+ enabled: cfg.enabled && cfg.configured,+ network: cfg.network,+ grant_sol: cfg.grantSol,+ activated,+ pending,+ eligible,+ reason,+ has_wallet: hasWallet,+ receipt: activated ? receipt(row, cfg.network) : null,+ };+}++// Count confirmed grants in the last 24h for the rolling daily cap.+async function confirmedToday() {+ try {+ const [r] = await sql`+ select count(*)::int as count from agent_activations+ where status = 'confirmed' and created_at > now() - interval '24 hours'+ `;+ return r?.count ?? 0;+ } catch (err) {+ if (err?.code === '42P01') return 0;+ throw err;+ }+}++// Ensure the ledger table exists even if the migration hasn't run yet (mirrors the+// circulation engine's self-healing schema guard). Idempotent + cheap.+let _ensured = false;+async function ensureSchema() {+ if (_ensured) return;+ await sql`+ create table if not exists agent_activations (+ agent_id uuid primary key,+ user_id uuid,+ network text not null default 'mainnet',+ status text not null default 'pending',+ signature text,+ lamports bigint,+ usd numeric,+ created_at timestamptz not null default now(),+ confirmed_at timestamptz+ )+ `;+ await sql`create index if not exists agent_activations_confirmed on agent_activations (created_at desc) where status = 'confirmed'`;+ _ensured = true;+}++/**+ * Activate an agent: send the one-time on-chain welcome grant and record it as a+ * real tip custody event. Idempotent and concurrency-safe. Never throws for an+ * expected condition — returns a typed `{ ok, code }` the route maps to HTTP.+ *+ * @param {{ agentId: string, userId: string }} args+ * @returns {Promise<{ ok: boolean, code?: string, message?: string, already?: boolean,+ * pending?: boolean, signature?: string, explorer?: string|null, sol?: number,+ * usd?: number|null, network?: string }>}+ */+export async function activateAgent({ agentId, userId }) {+ const [agent] = await sql`+ select id, user_id, name, meta from agent_identities+ where id = ${agentId} and deleted_at is null limit 1+ `;+ if (!agent) return { ok: false, code: 'not_found', message: 'agent not found' };+ if (agent.user_id !== userId) return { ok: false, code: 'forbidden', message: 'not your agent' };+ if (isCirculationAgent(agent)) {+ return { ok: false, code: 'platform_agent', message: 'platform agents are already live' };+ }++ const cfg = activationConfig();++ // Already activated? Return the existing receipt — idempotent, no second grant.+ const existing = await loadActivationRow(agentId).catch(() => null);+ if (existing?.status === 'confirmed') {+ const r = receipt(existing, cfg.network);+ return { ok: true, already: true, ...r };+ }+ if (existing?.status === 'pending') {+ return { ok: true, already: true, pending: true, network: existing.network || cfg.network };+ }++ if (!cfg.enabled || !cfg.configured) {+ return { ok: false, code: 'not_configured', message: 'activation is not available right now' };+ }++ // Rolling daily cap — a soft global spend bound.+ if ((await confirmedToday()) >= cfg.dailyCap) {+ return { ok: false, code: 'cap_reached', message: 'daily activation cap reached — try again tomorrow' };+ }++ await ensureSchema();++ // Provision the wallet if it isn't already (lazy-mint path), then resolve the+ // destination address.+ let address = agent.meta?.solana_address || null;+ try {+ const w = await ensureAgentWallet(agentId, userId, { reason: 'activation' });+ if (w?.address) address = w.address;+ } catch (err) {+ console.error('[agent-activation] wallet provision failed', err?.message);+ return { ok: false, code: 'wallet_unavailable', message: 'could not prepare the agent wallet' };+ }+ if (!address) {+ return { ok: false, code: 'wallet_unavailable', message: 'agent has no wallet to fund' };+ }++ // Claim the single grant slot. ON CONFLICT DO NOTHING is the mutex: if a+ // concurrent request already inserted, we get no row back and bail as "pending".+ const [claim] = await sql`+ insert into agent_activations (agent_id, user_id, network, status)+ values (${agentId}, ${userId}, ${cfg.network}, 'pending')+ on conflict (agent_id) do nothing+ returning agent_id+ `;+ if (!claim) {+ const row = await loadActivationRow(agentId).catch(() => null);+ if (row?.status === 'confirmed') return { ok: true, already: true, ...receipt(row, cfg.network) };+ return { ok: true, already: true, pending: true, network: cfg.network };+ }++ // From here a failure must release the claim so the owner can retry.+ const releaseClaim = () =>+ sql`delete from agent_activations where agent_id = ${agentId} and status = 'pending'`.catch(+ () => {},+ );++ let treasuryKp;+ try {+ treasuryKp = await getTreasuryKeypair(TREASURY_ENV_OVERRIDE);+ } catch (err) {+ await releaseClaim();+ return { ok: false, code: 'not_configured', message: 'activation is not available right now' };+ }++ const conn = treasuryConnection(cfg.network);+ const lamports = cfg.grantLamports;++ // Confirm the treasury can cover the grant + a fee buffer before sending, so a+ // dry treasury yields a clean message instead of a raw RPC failure.+ try {+ const have = await lamportBalance(conn, treasuryKp.publicKey.toBase58());+ if (have < BigInt(lamports) + BigInt(FEE_BUFFER)) {+ await releaseClaim();+ return { ok: false, code: 'treasury_low', message: 'activation is temporarily paused' };+ }+ } catch {+ /* balance probe is best-effort; the transfer below is the real gate */+ }++ let signature;+ try {+ signature = await transferSol(conn, treasuryKp, address, lamports);+ } catch (err) {+ console.error('[agent-activation] grant transfer failed', err?.message);+ await releaseClaim();+ return { ok: false, code: 'transfer_failed', message: 'the grant could not be sent — try again' };+ }++ // Price the grant in USD (best-effort) so the Pulse can value it.+ let usd = null;+ try {+ const px = await solUsdPrice();+ if (px) usd = (lamports / SOL) * px;+ } catch {+ /* usd is decoration */+ }++ // Record the grant as a real inbound tip — this is what lands the agent on the+ // Money Pulse and in active-wallet / tip counts. Idempotent on (agent, key).+ await recordCustodyEvent({+ agentId,+ userId: null,+ eventType: 'tip',+ category: 'tip',+ network: cfg.network,+ asset: 'SOL',+ amountLamports: lamports,+ usd,+ destination: address,+ signature,+ status: 'confirmed',+ idempotencyKey: `activation:${agentId}`,+ meta: {+ source: 'activation_grant',+ from: 'three.ws',+ label: 'Activation welcome grant',+ block_time: new Date().toISOString(),+ decimals: 9,+ },+ }).catch((e) => console.warn('[agent-activation] custody event failed', e?.message));++ await sql`+ update agent_activations+ set status = 'confirmed', signature = ${signature}, lamports = ${String(lamports)},+ usd = ${usd}, confirmed_at = now()+ where agent_id = ${agentId}+ `;++ // Announce on the live ticker + notify the owner. Fire-and-forget — never block.+ publishFeedEvent({+ type: 'agent-activated',+ ts: Date.now(),+ actor: agent.name,+ agentId,+ name: agent.name,+ }).catch(() => {});+ insertNotification(userId, 'agent_activated', {+ agent_id: agentId,+ agent_name: agent.name,+ sol: lamports / SOL,+ signature,+ }).catch(() => {});++ return {+ ok: true,+ signature,+ explorer: explorerTxUrl(signature, cfg.network),+ sol: lamports / SOL,+ usd,+ network: cfg.network,+ };+}diff --git a/api/_lib/migrations/20260629080000_agent_activation.sql b/api/_lib/migrations/20260629080000_agent_activation.sqlnew file mode 100644index 000000000..6a84de57a--- /dev/null+++ b/api/_lib/migrations/20260629080000_agent_activation.sql@@ -0,0 +1,30 @@+-- Agent activation grants — the onboarding "Go Live" welcome grant.+--+-- When a real owner activates their agent, the platform treasury sends a small,+-- one-time, on-chain SOL grant to the agent's custodial wallet. That transfer is+-- recorded as a real `tip` custody event (api/_lib/activation.js), so the agent+-- instantly appears on the Money Pulse as an active, funded wallet — solving the+-- cold-start dead-end where a fresh agent sits at ◎0 and can never make its first+-- transaction.+--+-- This table is the idempotency + anti-sybil ledger: exactly one grant per agent+-- (agent_id primary key), with a status mutex so concurrent activation POSTs can+-- never double-spend. The engine also creates it lazily, so this migration is+-- belt-and-suspenders (matches the circulation_actions pattern).++create table if not exists agent_activations (+ agent_id uuid primary key,+ user_id uuid,+ network text not null default 'mainnet',+ status text not null default 'pending', -- pending | confirmed+ signature text,+ lamports bigint,+ usd numeric,+ created_at timestamptz not null default now(),+ confirmed_at timestamptz+);++-- Daily-cap query counts confirmed grants in a rolling window.+create index if not exists agent_activations_confirmed+ on agent_activations (created_at desc)+ where status = 'confirmed';diff --git a/api/_lib/platform-treasury.js b/api/_lib/platform-treasury.jsnew file mode 100644index 000000000..38a78ae21--- /dev/null+++ b/api/_lib/platform-treasury.js@@ -0,0 +1,157 @@+// @ts-check+// Shared platform-treasury rail.+//+// A single operator-funded Solana wallet that the platform uses to seed small,+// real, on-chain grants — today: the agent activation "Go Live" welcome grant+// (api/_lib/activation.js). The autonomous circulation engine+// (api/_lib/circulation.js) keeps its own treasury plumbing for its hot path;+// this module is the canonical, reusable helper for everything else, so new+// platform-funded flows don't each re-implement keypair decoding + transfers.+//+// The secret is read from CIRCULATION_TREASURY_SECRET (the existing operator+// treasury) so no new key needs provisioning; a flow may override it with its+// own secret env var. With no secret set, isConfigured() is false and callers+// degrade gracefully — nothing is ever inert-but-pretending.++import { solanaConnection } from './agent-pumpfun.js';++const SOL = 1_000_000_000;+// tx fee + compute headroom kept on the treasury beyond the amount it sends.+export const FEE_BUFFER = Math.floor(0.0009 * SOL);++/** The treasury network — mainnet unless the operator runs circulation on devnet. */+export function treasuryNetwork() {+ return process.env.CIRCULATION_NETWORK === 'devnet' ? 'devnet' : 'mainnet';+}++/**+ * Resolve the treasury secret. `overrideEnv` lets a specific flow point at its+ * own funded wallet; otherwise the shared operator treasury is used.+ * @param {string} [overrideEnv]+ */+function treasurySecret(overrideEnv) {+ const override = overrideEnv ? String(process.env[overrideEnv] || '').trim() : '';+ if (override) return override;+ return String(process.env.CIRCULATION_TREASURY_SECRET || '').trim();+}++/** Whether a treasury secret is configured (so a flow can fail soft, not hard). */+export function isConfigured(overrideEnv) {+ return treasurySecret(overrideEnv).length > 0;+}++// Decode a 64-byte secret key in base58, base64, or JSON-array form (mirrors the+// circulation decoder so operators can paste whichever format their tooling emits).+function decodeSecretKey(secret, bs58) {+ let bytes = null;+ try {+ const d = bs58.decode(secret);+ if (d.length === 64) bytes = d;+ } catch {+ /* not base58 */+ }+ if (!bytes) {+ try {+ const b = Buffer.from(secret, 'base64');+ if (b.length === 64) bytes = b;+ } catch {+ /* not base64 */+ }+ }+ if (!bytes) {+ try {+ const arr = JSON.parse(secret);+ if (Array.isArray(arr) && arr.length === 64) bytes = Uint8Array.from(arr);+ } catch {+ /* not json */+ }+ }+ return bytes ? Uint8Array.from(bytes) : null;+}++/**+ * Recover the treasury Keypair. Throws a typed Error when unset/malformed — the+ * caller is expected to have gated on isConfigured() first for the soft path.+ * @param {string} [overrideEnv]+ */+export async function getTreasuryKeypair(overrideEnv) {+ const secret = treasurySecret(overrideEnv);+ if (!secret) {+ const e = new Error('treasury secret unset');+ // @ts-ignore — tagged for callers that map it to a clean "not configured".+ e.code = 'treasury_unset';+ throw e;+ }+ const { Keypair } = await import('@solana/web3.js');+ const bs58 = (await import('bs58')).default;+ const bytes = decodeSecretKey(secret, bs58);+ if (!bytes) {+ throw new Error('treasury secret must be a 64-byte base58, base64, or JSON-array secret key');+ }+ return Keypair.fromSecretKey(bytes);+}++/** Lamport balance of an address on the treasury's connection. */+export async function lamportBalance(conn, address) {+ const { PublicKey } = await import('@solana/web3.js');+ return BigInt(await conn.getBalance(new PublicKey(address), 'confirmed'));+}++/**+ * Sign + send a SOL transfer from `fromKp` to `toAddress`. Retries once on an+ * expired blockhash (the hash can lapse between fetch and send under RPC/key+ * latency); a fresh hash is valid for ~60s. Returns the confirmed signature.+ */+export async function transferSol(conn, fromKp, toAddress, lamports) {+ const {+ PublicKey,+ SystemProgram,+ TransactionMessage,+ VersionedTransaction,+ ComputeBudgetProgram,+ } = await import('@solana/web3.js');+ const toPk = new PublicKey(toAddress);++ const MAX_ATTEMPTS = 2;+ let lastErr;+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');+ const message = new TransactionMessage({+ payerKey: fromKp.publicKey,+ recentBlockhash: blockhash,+ instructions: [+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 60_000 }),+ ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000 }),+ SystemProgram.transfer({ fromPubkey: fromKp.publicKey, toPubkey: toPk, lamports }),+ ],+ }).compileToV0Message();+ const tx = new VersionedTransaction(message);+ tx.sign([fromKp]);+ try {+ const signature = await conn.sendTransaction(tx, { maxRetries: 5 });+ const conf = await conn.confirmTransaction(+ { signature, blockhash, lastValidBlockHeight },+ 'confirmed',+ );+ if (conf.value?.err) {+ throw new Error('transfer failed on-chain: ' + JSON.stringify(conf.value.err));+ }+ return signature;+ } catch (err) {+ const msg = err?.message || '';+ if (attempt < MAX_ATTEMPTS - 1 && /Blockhash not found|BlockhashNotFound/i.test(msg)) {+ lastErr = err;+ continue;+ }+ throw err;+ }+ }+ throw lastErr;+}++/** The shared Solana RPC connection for a network (re-export for convenience). */+export function treasuryConnection(network) {+ return solanaConnection(network || treasuryNetwork());+}++export { SOL };diff --git a/api/agents/[id].js b/api/agents/[id].jsindex 83c73468e..af2d7044a 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -62,6 +62,11 @@ export default wrap(async function handler(req, res) {return mod.default(req, res, id, action);}+ if (sub === 'activate') {+ const mod = await import('./_id/activate.js');+ return mod.default(req, res, id, action);+ }+if (sub === 'recovery') {const mod = await import('./recovery.js');return mod.default(req, res, id, action, parts);diff --git a/api/agents/_id/activate.js b/api/agents/_id/activate.jsnew file mode 100644index 000000000..e62257a3d--- /dev/null+++ b/api/agents/_id/activate.js@@ -0,0 +1,83 @@+// /api/agents/:id/activate+// GET — owner-only activation status (which "Go Live" state to render)+// POST — claim the one-time on-chain welcome grant (the activation faucet)+//+// Activation funds the agent's custodial wallet with a small, real, one-time SOL+// grant from the platform treasury and records it as a genuine tip custody event,+// so the agent immediately becomes a funded + active wallet on the Money Pulse.+// See api/_lib/agent-activation.js for the full rationale and guarantees.++import { sql } from '../../_lib/db.js';+import {+ getSessionUser,+ authenticateBearer,+ extractBearer,+ hasScope,+} from '../../_lib/auth.js';+import { cors, json, method, error } from '../../_lib/http.js';+import { requireCsrf } from '../../_lib/csrf.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { rateLimited } from '../../_lib/http.js';+import { activateAgent, getActivationStatus } from '../../_lib/agent-activation.js';++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, source: 'session', scope: null };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId, source: 'bearer', scope: bearer.scope || '' };+ return null;+}++export default async function handler(req, res, id) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');++ // Bearer callers mutate the agent, so they need the avatars:write scope (session+ // cookie callers are not scope-constrained — they're the agent's human owner).+ if (req.method === 'POST' && auth.source === 'bearer' && !hasScope(auth.scope, 'avatars:write')) {+ return error(res, 403, 'insufficient_scope', 'avatars:write required');+ }++ const [agent] = await sql`+ select id, user_id, name, meta from agent_identities+ where id = ${id} and deleted_at is null limit 1+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ const isOwner = agent.user_id === auth.userId;++ if (req.method === 'GET') {+ // Status is an owner-only signal (it drives owner onboarding UI); a visitor+ // gets the inert, not-eligible shape rather than the owner's reasons.+ const status = await getActivationStatus({+ agent: { id: agent.id, meta: agent.meta, solana_address: agent.meta?.solana_address },+ isOwner,+ });+ return json(res, 200, { data: status });+ }++ // POST — perform activation.+ if (!isOwner) return error(res, 403, 'forbidden', 'not your agent');+ if (!(await requireCsrf(req, res, auth.userId))) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const result = await activateAgent({ agentId: id, userId: auth.userId });+ if (result.ok) return json(res, 200, { data: result });++ const STATUS = {+ not_found: 404,+ forbidden: 403,+ platform_agent: 409,+ not_configured: 503,+ cap_reached: 429,+ treasury_low: 503,+ wallet_unavailable: 503,+ transfer_failed: 502,+ };+ const code = result.code || 'activation_failed';+ return error(res, STATUS[code] || 400, code, result.message || 'activation failed');+}diff --git a/api/x402-merchant.js b/api/x402-merchant.jsindex d1ab09f88..ccfa73d91 100644--- a/api/x402-merchant.js+++ b/api/x402-merchant.js@@ -165,7 +165,7 @@ const DEFAULTS = {business_name: null,support_email: null,logo_url: null,- accent_color: '#0a84ff',+ accent_color: '#111111',payout_evm: null,payout_solana: null,default_network: 'solana',@@ -294,7 +294,7 @@ async function handleUpsert(req, res) {business_name = ${next.business_name},support_email = ${next.support_email},logo_url = ${next.logo_url},- accent_color = ${next.accent_color ?? '#0a84ff'},+ accent_color = ${next.accent_color ?? '#111111'},payout_evm = ${next.payout_evm},payout_solana = ${next.payout_solana},default_network = ${next.default_network ?? 'solana'},diff --git a/api/x402-skus.js b/api/x402-skus.jsindex c9e42ef0a..39838950e 100644--- a/api/x402-skus.js+++ b/api/x402-skus.js@@ -43,7 +43,7 @@ const createSchema = z.object({accent_color: z.string().regex(/^#[0-9a-fA-F]{6}$/)- .default('#0a84ff'),+ .default('#111111'),success_url: httpsUrl.optional(),// Storefront display fields — optional, never block a paid call.price_atomics: zdiff --git a/data/changelog.json b/data/changelog.jsonindex 2ec16bdb1..727b8b117 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-27",+ "title": "Live agent screens restored and refreshed in monochrome",+ "summary": "Watching agents work — their live screens, avatar cam, and activity feed — is back. A missing rate-limit binding had been crashing the endpoints behind the scenes, so the roster on /agents-live never populated, agents couldn't broadcast frames, and tasks wouldn't queue; all three paths now respond correctly. The Live Agents grid and the single-agent screen viewer were also rebuilt in a crisp monochrome palette, and the watch grid now pauses its streams when the tab is in the background so it stays light on bandwidth.",+ "tags": ["fix", "improvement"],+ "link": "/agents-live"+ },{"date": "2026-06-27","title": "Restored token-launch, agent payments, and on-chain endpoints",diff --git a/pages/agent-screen.html b/pages/agent-screen.htmlindex 02419320d..1d00bb6d5 100644--- a/pages/agent-screen.html+++ b/pages/agent-screen.html@@ -5,7 +5,7 @@<meta charset="utf-8" /><title>Agent Screen · three.ws</title><meta name="viewport" content="width=device-width, initial-scale=1.0" />- <meta name="theme-color" content="#060a12" />+ <meta name="theme-color" content="#0a0a0b" /><meta name="description" content="Watch your agent in real time — see their screen and avatar as they autonomously trade, browse, and act." /><meta property="og:type" content="website" />@@ -38,7 +38,7 @@display: flex;flex-direction: column;min-height: 100vh;- background: #060a12;+ background: #0a0a0b;}/* ── header ── */@@ -70,7 +70,7 @@.asc-agent-name {font-size: 0.95rem;font-weight: 680;- color: #eef2fa;+ color: #f4f4f5;letter-spacing: -0.01em;}.asc-live-badge {@@ -138,7 +138,7 @@display: flex;flex-direction: column;border-right: 1px solid rgba(255,255,255,0.06);- background: #04060d;+ background: #070708;position: relative;}.asc-screen-label {@@ -204,7 +204,7 @@min-width: 0;display: flex;flex-direction: column;- background: #060a14;+ background: #0c0c0e;}/* ── webcam section ── */@@ -231,7 +231,7 @@border-radius: 14px;overflow: hidden;border: 2px solid rgba(255,255,255,0.1);- background: #0a0d1a;+ background: #141416;box-shadow: 0 4px 24px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.04);aspect-ratio: 4/3;width: 100%;@@ -317,10 +317,11 @@padding: 1px 6px;border-radius: 4px;}- .asc-log-type.screenshot { background: rgba(255,255,255,0.15); color: #d4d4d8; }- .asc-log-type.trade { background: rgba(255,255,255,0.15); color: #ffffff; }- .asc-log-type.analysis { background: rgba(255,255,255,0.15); color: #d4d4d8; }- .asc-log-type.activity { background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.5); }+ /* Monochrome log taxonomy — distinguished by tone + a left tick, not hue. */+ .asc-log-type.screenshot { background: rgba(255,255,255,0.10); color: rgba(255,255,255,0.7); box-shadow: inset 2px 0 0 rgba(255,255,255,0.4); }+ .asc-log-type.trade { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 2px 0 0 #fff; }+ .asc-log-type.analysis { background: rgba(255,255,255,0.10); color: rgba(255,255,255,0.7); box-shadow: inset 2px 0 0 rgba(255,255,255,0.55); }+ .asc-log-type.activity { background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.45); }.asc-log-text { color: rgba(255,255,255,0.78); }.asc-log-empty {display: flex;@@ -357,10 +358,10 @@gap: 1.2rem;text-align: center;padding: 2rem;- color: #e8edf7;+ color: #f4f4f5;font-family: system-ui, sans-serif;}- .asc-no-agent h2 { margin: 0; font-size: 1.15rem; font-weight: 680; color: #c8d4f0; }+ .asc-no-agent h2 { margin: 0; font-size: 1.15rem; font-weight: 680; color: #d4d4d8; }.asc-no-agent p { margin: 0; font-size: 0.88rem; color: rgba(255,255,255,0.45); max-width: 340px; }.asc-no-agent a {display: inline-flex;@@ -447,7 +448,7 @@margin: 0;font-size: 0.92rem;font-weight: 680;- color: #dce6ff;+ color: #e4e4e7;letter-spacing: -0.01em;}.ws-setup-step-head p {@@ -502,7 +503,7 @@.ws-agent-name {font-size: 0.82rem;font-weight: 660;- color: #dce6ff;+ color: #e4e4e7;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;diff --git a/public/changelog.json b/public/changelog.jsonindex d8ad801f8..884cce9bd 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T20:28:37.906Z",+ "generated_at": "2026-06-27T20:29:18.653Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -140,6 +140,17 @@"infra"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Live agent screens restored and refreshed in monochrome",+ "summary": "Watching agents work — their live screens, avatar cam, and activity feed — is back. A missing rate-limit binding had been crashing the endpoints behind the scenes, so the roster on /agents-live never populated, agents couldn't broadcast frames, and tasks wouldn't queue; all three paths now respond correctly. The Live Agents grid and the single-agent screen viewer were also rebuilt in a crisp monochrome palette, and the watch grid now pauses its streams when the tab is in the background so it stays light on bandwidth.",+ "link": "/agents-live",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-06-27","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 3d1ff2452..add27224e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -110,6 +110,14 @@<category>fix</category><description>API endpoints now return HTTP 503 (Service Unavailable) with a Retry-After header instead of 500 when the database is temporarily unreachable, so clients and caches know to back off and retry rather than treating it as a permanent error. Background crons skip their tick gracefully and log a warning instead of firing repeated alert storms. A single deduped ops alert now covers the whole outage.</description></item>+ <item>+ <title>Live agent screens restored and refreshed in monochrome</title>+ <link>https://three.ws/agents-live</link>+ <guid isPermaLink="false">2026-06-27:Live agent screens restored and refreshed in monochrome</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Watching agents work — their live screens, avatar cam, and activity feed — is back. A missing rate-limit binding had been crashing the endpoints behind the scenes, so the roster on /agents-live never populated, agents couldn't broadcast frames, and tasks wouldn't queue; all three paths now respond correctly. The Live Agents grid and the single-agent screen viewer were also rebuilt in a crisp monochrome palette, and the watch grid now pauses its streams when the tab is in the background so it stays light on bandwidth.</description>+ </item><item><title>Live Agents mission control + one-click session launcher</title><link>https://three.ws/agents-live</link>diff --git a/public/dashboard/x402.html b/public/dashboard/x402.htmlindex 1f9648873..2a3a475c9 100644--- a/public/dashboard/x402.html+++ b/public/dashboard/x402.html@@ -331,7 +331,7 @@</label><label>Accent color- <input name="accent_color" type="color" value="#0a84ff" />+ <input name="accent_color" type="color" value="#111111" /></label></div><label id="bodyLabel" style="display:none">diff --git a/public/features.json b/public/features.jsonindex 8b0f9fc98..67462b93f 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T20:21:36.176Z",+ "generated_at": "2026-06-27T20:29:18.629Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -382,6 +382,16 @@"tags": [],"showcase": false},+ {+ "path": "/capture",+ "title": "Scene Capture — Video to 3D Point Cloud",+ "description": "Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.",+ "added": "2026-06-27",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/forge-nim","title": "Forge · NIM — Self-Hosted Image to 3D",diff --git a/public/llms-full.txt b/public/llms-full.txtindex f95eab6e4..263b52628 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -238,6 +238,12 @@ URL: https://three.ws/splatRender Gaussian-splat and radiance-field avatars in the browser — the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.+### Scene Capture — Video to 3D Point Cloud++URL: https://three.ws/capture++Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.+### Forge · NIM — Self-Hosted Image to 3DURL: https://three.ws/forge-nimdiff --git a/public/llms.txt b/public/llms.txtindex 5a68aaf39..0571decfb 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -49,6 +49,7 @@ Create and customize an agent.- [Forge — Text to 3D](https://three.ws/forge): Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.- [Avatar Engines Atlas](https://three.ws/avatar-engines): A curated, factual atlas of the open-source and commercial engines that build high-quality and photoreal 3D human avatars — Gaussian-splat heads, single-photo humans, text→avatar generators, and the rigs three.ws already animates. Technique, license, compute, and integration status for each.- [Splat Viewer — Photoreal Gaussian Avatars](https://three.ws/splat): Render Gaussian-splat and radiance-field avatars in the browser — the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.+- [Scene Capture — Video to 3D Point Cloud](https://three.ws/capture): Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.- [Forge · NIM — Self-Hosted Image to 3D](https://three.ws/forge-nim): Drive a self-hosted TRELLIS NIM (nvcr.io/nim/microsoft/trellis) directly: drop a photo, hit /v1/infer, and get the textured GLB back synchronously as base64 — rendered live and downloadable.- [Text → 3D — Nemotron → FLUX → TRELLIS](https://three.ws/forge-spark): Describe an object and watch it become a textured 3D mesh: Nemotron sharpens the prompt, FLUX paints a clean reference, and TRELLIS reconstructs the model — served on NVIDIA NIM, quiet and always on.- [Studio — Object + Avatar from text](https://three.ws/forge-studio): One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.diff --git a/public/nav-data.js b/public/nav-data.jsindex bbd8bb339..dd36cfb7e 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -84,6 +84,12 @@ export const NAV_GROUPS = [badge: 'New',desc: 'Render photoreal Gaussian-splat avatars in the browser — load a .ply / .splat by URL or upload',},+ {+ title: 'Scene Capture',+ href: '/capture',+ badge: 'New',+ desc: 'Video → 3D scene — reconstruct any space into an explorable point cloud, rendered live in the browser',+ },{title: 'CA → x402',href: '/ca2x402',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex f59c5cbdc..965a6ca1b 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 349 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 350 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 349 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 350 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -259,7 +259,7 @@<section class="sm-section" id="build"><header>- <h2>Build<span class="sm-count" data-count>45</span></h2>+ <h2>Build<span class="sm-count" data-count>46</span></h2><p class="sm-section-desc">Create and customize an agent.</p></header><ul class="sm-list">@@ -361,6 +361,13 @@<span class="sm-desc">Render Gaussian-splat and radiance-field avatars in the browser — the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.</span></a></li>+ <li>+ <a href="/capture">+ <span class="sm-title">Scene Capture — Video to 3D Point Cloud</span>+ <span class="sm-path">/capture</span>+ <span class="sm-desc">Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.</span>+ </a>+ </li><li><a href="/forge-nim"><span class="sm-title">Forge · NIM — Self-Hosted Image to 3D</span>diff --git a/scripts/capture-verify.mjs b/scripts/capture-verify.mjsnew file mode 100644index 000000000..3bfda31ff--- /dev/null+++ b/scripts/capture-verify.mjs@@ -0,0 +1,69 @@+// Temporary browser verification for /capture — drives the point-cloud renderer+// client-side (sample cloud + real .ply upload), checks states + console health.+import { chromium } from 'playwright';++const BASE = process.env.BASE_URL || 'http://localhost:3001';+const PLY = process.env.PLY_PATH;+const SHOT = process.env.SHOT || '/tmp/capture.png';++const browser = await chromium.launch();+const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });+const errors = [];+page.on('console', (m) => { if (m.type() === 'error') errors.push(`[error] ${m.text()}`); });+page.on('pageerror', (e) => errors.push(`[pageerror] ${e}`));++await page.goto(`${BASE}/capture`, { waitUntil: 'domcontentloaded' });+await page.waitForSelector('#pc-stage', { timeout: 15000 });++const h1 = (await page.textContent('.pc-head h1'))?.trim();+console.log('h1:', JSON.stringify(h1));+console.log('idle overlay visible:', await page.isVisible('#pc-idle'));++// 1) Sample cloud render.+await page.click('#pc-sample');+await page.waitForSelector('#pc-host canvas', { timeout: 15000 });+await page.waitForFunctionTimeout?.(() => {}, 0).catch(() => {});+await page.waitForFunction(() => !document.getElementById('pc-hud').hidden, { timeout: 15000 });+const sampleLabel = (await page.textContent('#pc-hud-label'))?.trim();+const canvasBox = await page.$eval('#pc-host canvas', (c) => ({ w: c.width, h: c.height }));+console.log('SAMPLE → hud label:', JSON.stringify(sampleLabel), 'canvas:', canvasBox);+console.log('point-size slider enabled:', await page.isEnabled('#pc-size'));++// Verify the canvas actually painted non-black pixels (the cloud is visible).+const painted = await page.$eval('#pc-host canvas', (c) => {+ const gl = c.getContext('webgl2') || c.getContext('webgl');+ const px = new Uint8Array(4 * 64);+ // sample a small strip near the centre+ const x = Math.floor(c.width / 2), y = Math.floor(c.height / 2);+ gl.readPixels(x, y, 8, 8, gl.RGBA, gl.UNSIGNED_BYTE, px);+ let lit = 0;+ for (let i = 0; i < px.length; i += 4) if (px[i] + px[i + 1] + px[i + 2] > 30) lit++;+ return lit;+});+console.log('lit centre pixels (of 64):', painted);++// 2) Interactions: point size + recenter (must not throw).+await page.fill('#pc-size', '2.4').catch(async () => { await page.$eval('#pc-size', (e) => { e.value = '2.4'; e.dispatchEvent(new Event('input', { bubbles: true })); }); });+await page.click('#pc-recenter');+await page.waitForTimeout(400);++// 3) Real .ply upload (worker-format file) → exact point count in HUD.+if (PLY) {+ await page.setInputFiles('#pc-file', PLY);+ await page.waitForFunction(() => /\d+ points/.test(document.getElementById('pc-hud-label').textContent), { timeout: 15000 });+ const plyLabel = (await page.textContent('#pc-hud-label'))?.trim();+ console.log('PLY UPLOAD → hud label:', JSON.stringify(plyLabel));+ console.log('download button visible:', await page.isVisible('#pc-download'));+}++// 4) Responsive sanity at mobile width.+await page.setViewportSize({ width: 375, height: 812 });+await page.waitForTimeout(300);+const stageW = await page.$eval('#pc-stage', (e) => e.getBoundingClientRect().width);+console.log('mobile stage width:', Math.round(stageW));+await page.setViewportSize({ width: 1440, height: 900 });++await page.screenshot({ path: SHOT });+console.log('screenshot:', SHOT);+console.log('CONSOLE ERRORS:', errors.length ? errors.join('\n') : 'none');+await browser.close();diff --git a/src/agent-screen.js b/src/agent-screen.jsindex c48105660..806c9f714 100644--- a/src/agent-screen.js+++ b/src/agent-screen.js@@ -199,7 +199,7 @@ async function renderSetup() {<div class="ws-step-num${step2Done ? ' done' : ''}">${step2Done ? '✓' : '2'}</div><div><h3>Generate an API key</h3>- <p>Used as <code style="font-size:0.78rem;color:#8a9fff">AGENT_JWT</code> — authenticates the worker as you</p>+ <p>Used as <code style="font-size:0.78rem;color:#d4d4d8">AGENT_JWT</code> — authenticates the worker as you</p></div></div><div class="ws-setup-step-body">@@ -214,7 +214,7 @@ async function renderSetup() {</div>${apiKey? `<p class="ws-key-note"><strong>Save this key now.</strong> It won't be shown again. It grants access to your account — treat it like a password.</p>`- : `<p class="ws-key-note">Creates a new <code style="font-size:0.78rem">agents:write</code>-scoped API key. You can manage keys at <a href="/dashboard-next/developers" style="color:#7aabff">Developers →</a></p>`+ : `<p class="ws-key-note">Creates a new <code style="font-size:0.78rem">agents:write</code>-scoped API key. You can manage keys at <a href="/dashboard-next/developers" style="color:#d4d4d8">Developers →</a></p>`}</div></div>@@ -225,7 +225,7 @@ async function renderSetup() {<div class="ws-step-num">${step1Done && step2Done ? '3' : '3'}</div><div><h3>Run the worker</h3>- <p>Copy and run in your terminal from the <code style="font-size:0.78rem;color:#8a9fff">workers/agent-screen-worker/</code> directory</p>+ <p>Copy and run in your terminal from the <code style="font-size:0.78rem;color:#d4d4d8">workers/agent-screen-worker/</code> directory</p></div></div><div class="ws-setup-step-body">@@ -238,7 +238,7 @@ async function renderSetup() {<button class="ws-btn ws-btn-copy ws-cmd-copy" id="ws-copy-cmd">Copy</button><pre id="ws-cmd-pre">${buildCommand()}</pre></div>- ${activeTab === 'bb' ? `<p class="ws-key-note" style="margin-top:0.7rem">Get your Browserbase key + project ID at <a href="https://browserbase.com" target="_blank" rel="noopener" style="color:#7aabff">browserbase.com</a> — no Docker needed, the browser runs in their cloud.</p>` : ''}+ ${activeTab === 'bb' ? `<p class="ws-key-note" style="margin-top:0.7rem">Get your Browserbase key + project ID at <a href="https://browserbase.com" target="_blank" rel="noopener" style="color:#d4d4d8">browserbase.com</a> — no Docker needed, the browser runs in their cloud.</p>` : ''}${selectedAgent && apiKey ? `<div class="ws-status-ok"><span>✓</span>@@ -610,7 +610,7 @@ async function boot(id) {setTimeout(() => { taskStatus.textContent = ''; taskStatus.className = 'asc-task-status'; }, 5000);} else if (res.status === 401) {taskStatus.className = 'asc-task-status err';- taskStatus.innerHTML = 'Sign in to send tasks. <a href="/login" style="color:#7aabff">Sign in →</a>';+ taskStatus.innerHTML = 'Sign in to send tasks. <a href="/login" style="color:#d4d4d8">Sign in →</a>';} else {taskStatus.className = 'asc-task-status err';taskStatus.textContent = j.message || j.error_description || 'Could not queue task — try again';diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.jsindex e760ed548..4b49d9585 100644--- a/src/agent-wallet-hub/index.js+++ b/src/agent-wallet-hub/index.js@@ -22,6 +22,7 @@ import { getVisibleTabs } from './registry.js';// Tab modules — importing each one runs its registerWalletTab() side effect.// To add a tab later: drop a file in ./tabs/ and add one import line here.import './tabs/balance.js';+import './tabs/activate.js';import './tabs/portfolio.js';import './tabs/pulse.js';import './tabs/reputation.js';diff --git a/src/agent-wallet-hub/tabs/activate.js b/src/agent-wallet-hub/tabs/activate.jsnew file mode 100644index 000000000..5e0261735--- /dev/null+++ b/src/agent-wallet-hub/tabs/activate.js@@ -0,0 +1,304 @@+/**+ * Agent Wallet hub — Go Live tab (the activation faucet, fully built).+ *+ * Owner-only onboarding surface that solves the cold-start dead-end: a fresh+ * agent's wallet starts at ◎0 and can never make its first transaction, so it+ * never shows on the Money Pulse. Activation claims a one-time, real, on-chain+ * welcome grant from the platform treasury — funding the wallet AND landing the+ * agent on the Pulse as an active, funded wallet in a single explorer-verifiable+ * transaction.+ *+ * Every state is designed: loading skeleton, eligible (the hero CTA), activating+ * (in-flight), live (the on-chain receipt + what-next), pending (a concurrent+ * claim settling), already-funded, and unavailable (treasury not configured) —+ * none of them a dead end. Backend: GET/POST /api/agents/:id/activate.+ */++import { registerWalletTab } from '../registry.js';+import { consumeCsrfToken } from '../../api.js';+import { formatSol, explorerTxUrl } from '../util.js';++const GO_STYLE_ID = 'awh-activate-style';+const GO_STYLE = `+.awh-go { display: flex; flex-direction: column; gap: var(--space-4,16px); }+.awh-go-hero { position: relative; overflow: hidden; border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-lg,14px); background:+ radial-gradient(120% 140% at 0% 0%, rgba(255,255,255,.06), transparent 60%),+ var(--surface-1, rgba(255,255,255,.03)); padding: var(--space-6,24px) var(--space-5,20px); }+.awh-go-kicker { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .12em; color: var(--ink-dim,#888); margin: 0 0 var(--space-2,8px); }+.awh-go-title { font-family: var(--font-display, system-ui); font-size: var(--text-xl,1.618rem); line-height: 1.12; font-weight: 600; color: var(--ink-bright,#fff); margin: 0 0 var(--space-3,12px); letter-spacing: -.01em; }+.awh-go-lede { font-size: var(--text-md,.8125rem); line-height: 1.6; color: var(--ink,#e8e8e8); margin: 0 0 var(--space-4,16px); max-width: 52ch; }+.awh-go-grant { display: inline-flex; align-items: baseline; gap: 8px; padding: 6px 12px; border-radius: var(--radius-pill,999px); border: 1px solid var(--stroke,rgba(255,255,255,.08)); background: var(--surface-2,rgba(255,255,255,.05)); font-family: var(--font-mono, ui-monospace, monospace); margin-bottom: var(--space-4,16px); }+.awh-go-grant b { font-size: var(--text-ui,.875rem); color: var(--ink-bright,#fff); font-weight: 600; }+.awh-go-grant span { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform: uppercase; letter-spacing: .06em; }++.awh-go-list { list-style: none; margin: 0 0 var(--space-5,20px); padding: 0; display: grid; gap: 10px; }+.awh-go-list li { display: flex; align-items: flex-start; gap: 10px; font-size: var(--text-sm,.764rem); line-height: 1.5; color: var(--ink-dim,#888); }+.awh-go-list li strong { color: var(--ink,#e8e8e8); font-weight: 600; }+.awh-go-tick { flex: none; width: 18px; height: 18px; border-radius: 50%; display: grid; place-items: center; margin-top: 1px; border: 1px solid var(--stroke-strong,rgba(255,255,255,.14)); color: var(--ink-bright,#fff); font-size: 10px; line-height: 1; }++.awh-go-cta { appearance: none; font: inherit; font-size: var(--text-ui,.875rem); font-weight: 600; color: #0a0a0a; background: var(--accent,#fff); border: 1px solid var(--accent,#fff); border-radius: var(--radius-md,10px); padding: 11px 20px; cursor: pointer; display: inline-flex; align-items: center; gap: 9px; transition: transform var(--duration-instant,80ms) var(--ease-standard,ease), background var(--duration-fast,140ms), opacity var(--duration-fast,140ms); }+.awh-go-cta:hover:not(:disabled) { background: color-mix(in srgb, var(--accent,#fff) 88%, #000); transform: translateY(-1px); }+.awh-go-cta:active:not(:disabled) { transform: translateY(0); }+.awh-go-cta:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: var(--focus-ring-offset,2px); }+.awh-go-cta:disabled { opacity: .55; cursor: progress; }+.awh-go-hint { margin: 10px 0 0; font-size: var(--text-2xs,.6875rem); color: var(--ink-faint, rgba(255,255,255,.45)); }+.awh-go-err { margin: 12px 0 0; padding: 9px 12px; border-radius: var(--radius-md,10px); font-size: var(--text-sm,.764rem); line-height: 1.45; color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 9%, transparent); border: 1px solid color-mix(in srgb, var(--warn,#fbbf24) 28%, transparent); }++.awh-go-spin { width: 14px; height: 14px; border-radius: 50%; border: 2px solid rgba(0,0,0,.25); border-top-color: #0a0a0a; animation: awh-go-spin .7s linear infinite; }++/* Live receipt */+.awh-go-live-badge { display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-2xs,.6875rem); font-weight: 600; padding: 3px 10px; border-radius: var(--radius-pill,999px); color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 14%, transparent); border: 1px solid color-mix(in srgb, var(--success,#4ade80) 35%, transparent); margin-bottom: var(--space-3,12px); }+.awh-go-live-badge::before { content:''; width: 7px; height: 7px; border-radius: 50%; background: var(--success,#4ade80); box-shadow: 0 0 6px color-mix(in srgb, var(--success,#4ade80) 60%, transparent); }+.awh-go-receipt { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--stroke,rgba(255,255,255,.08)); border: 1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); overflow: hidden; margin: var(--space-3,12px) 0 var(--space-4,16px); }+.awh-go-cell { background: var(--bg-1,#1a1a1a); padding: 12px 14px; }+.awh-go-cell dt { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim,#888); margin: 0 0 4px; }+.awh-go-cell dd { margin: 0; font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); font-family: var(--font-mono, ui-monospace, monospace); }+.awh-go-next { display: flex; flex-wrap: wrap; gap: var(--space-2,8px); }++.awh-go-skel { display: flex; flex-direction: column; gap: 14px; }+.awh-go-skel span { background: var(--surface-2,rgba(255,255,255,.05)); border-radius: var(--radius-sm,6px); animation: awh-go-skel 1.4s ease-in-out infinite; height: 16px; }+.awh-go-skel span.t { height: 28px; width: 60%; } .awh-go-skel span.l { width: 85%; } .awh-go-skel span.m { width: 45%; } .awh-go-skel span.b { height: 42px; width: 180px; border-radius: var(--radius-md,10px); }++@keyframes awh-go-spin { to { transform: rotate(360deg); } }+@keyframes awh-go-skel { 0%,100% { opacity: .5; } 50% { opacity: 1; } }+@media (max-width: 480px) { .awh-go-receipt { grid-template-columns: 1fr; } }+@media (prefers-reduced-motion: reduce) { .awh-go-spin, .awh-go-skel span { animation: none; } .awh-go-cta:hover:not(:disabled) { transform: none; } }+`;++function injectGoStyle() {+ if (typeof document === 'undefined' || document.getElementById(GO_STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = GO_STYLE_ID;+ tag.textContent = GO_STYLE;+ document.head.appendChild(tag);+}++// fetch helper — never throws, always a designed result (mirrors give.js/withdraw.js).+async function call(url, { method = 'GET', body = null } = {}) {+ try {+ const opts = { method, credentials: 'include', headers: {} };+ if (body != null) {+ opts.headers['content-type'] = 'application/json';+ opts.body = JSON.stringify(body);+ }+ if (method !== 'GET') {+ const token = await consumeCsrfToken();+ if (token) opts.headers['x-csrf-token'] = token;+ }+ const r = await fetch(url, opts);+ let j = null;+ try { j = await r.json(); } catch { /* empty body */ }+ if (!r.ok) {+ return {+ ok: false,+ status: r.status,+ code: j?.error || 'error',+ message: j?.error_description || `request failed (${r.status})`,+ };+ }+ return { ok: true, status: r.status, data: j?.data ?? j };+ } catch (err) {+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };+ }+}++registerWalletTab({+ id: 'activate',+ label: 'Go Live',+ order: 15,+ ownerOnly: true,+ mount({ panel, ctx }) {+ injectGoStyle();+ const { escapeHtml, toast } = ctx;+ const agentName = ctx.agent?.name || 'this agent';++ let destroyed = false;+ let loaded = false;+ let busy = false;+ let status = null; // { enabled, eligible, reason, grant_sol, activated, pending, receipt }+ let errorMsg = null;++ function skeleton() {+ return `+ <div class="awh-card awh-go-skel" aria-busy="true" aria-label="Loading activation">+ <span class="t"></span><span class="l"></span><span class="m"></span><span class="b"></span>+ </div>`;+ }++ function valueList() {+ return `+ <ul class="awh-go-list">+ <li><span class="awh-go-tick" aria-hidden="true">✓</span><span><strong>Funds the wallet</strong> — real SOL lands in ${escapeHtml(agentName)}'s custodial wallet so it can make its first move.</span></li>+ <li><span class="awh-go-tick" aria-hidden="true">✓</span><span><strong>Goes live on the Money Pulse</strong> — the grant is a real on-chain tip, so ${escapeHtml(agentName)} counts as an active wallet instantly.</span></li>+ <li><span class="awh-go-tick" aria-hidden="true">✓</span><span><strong>One-time & verifiable</strong> — a single explorer-checkable transaction. No strings, no second grant.</span></li>+ </ul>`;+ }++ function eligibleView() {+ const grant = formatSol(status.grant_sol);+ return `+ <div class="awh-go">+ <div class="awh-go-hero">+ <p class="awh-go-kicker">Activate</p>+ <h2 class="awh-go-title">Bring ${escapeHtml(agentName)} to life</h2>+ <p class="awh-go-lede">Claim a one-time welcome grant. It funds this agent's wallet and puts it on the live Money Pulse — the moment every other agent on three.ws can see it's real and active.</p>+ <div class="awh-go-grant"><b>◎${escapeHtml(grant)}</b><span>welcome grant</span></div>+ ${valueList()}+ <button class="awh-go-cta" type="button" data-act="go">+ <span data-host="cta-label">Activate ${escapeHtml(agentName)}</span>+ </button>+ <p class="awh-go-hint">Sent on Solana ${escapeHtml(status.network || 'mainnet')} from the three.ws treasury.</p>+ <div data-host="err">${errorMsg ? `<div class="awh-go-err">${escapeHtml(errorMsg)}</div>` : ''}</div>+ </div>+ </div>`;+ }++ function liveView(receipt) {+ const sol = receipt?.sol != null ? formatSol(receipt.sol) : '—';+ const when = receipt?.activated_at ? new Date(receipt.activated_at).toLocaleString() : '—';+ const exp = receipt?.explorer || (receipt?.signature ? explorerTxUrl(receipt.signature, receipt.network) : null);+ const sig = receipt?.signature ? `${receipt.signature.slice(0, 8)}…${receipt.signature.slice(-6)}` : '—';+ return `+ <div class="awh-go">+ <div class="awh-go-hero">+ <span class="awh-go-live-badge">Live</span>+ <h2 class="awh-go-title">${escapeHtml(agentName)} is live</h2>+ <p class="awh-go-lede">The welcome grant landed on-chain. ${escapeHtml(agentName)} is funded and now appears on the Money Pulse as an active wallet.</p>+ <dl class="awh-go-receipt">+ <div class="awh-go-cell"><dt>Grant</dt><dd>◎${escapeHtml(sol)} SOL</dd></div>+ <div class="awh-go-cell"><dt>When</dt><dd>${escapeHtml(when)}</dd></div>+ <div class="awh-go-cell"><dt>Transaction</dt><dd>${exp ? `<a class="awh-act-sig" href="${escapeHtml(exp)}" target="_blank" rel="noopener">${escapeHtml(sig)} ↗</a>` : escapeHtml(sig)}</dd></div>+ <div class="awh-go-cell"><dt>Network</dt><dd>${escapeHtml(receipt?.network || 'mainnet')}</dd></div>+ </dl>+ <div class="awh-go-next">+ <a class="awh-btn awh-btn--primary" href="/pulse">See it on the Money Pulse ↗</a>+ <button class="awh-btn" type="button" data-act="tab-pulse">Your wallet story</button>+ <button class="awh-btn" type="button" data-act="tab-deposit">Add more funds</button>+ </div>+ </div>+ </div>`;+ }++ function pendingView() {+ return `+ <div class="awh-go">+ <div class="awh-go-hero">+ <p class="awh-go-kicker">Activating</p>+ <h2 class="awh-go-title">Sending ${escapeHtml(agentName)}'s grant…</h2>+ <p class="awh-go-lede">The on-chain welcome grant is settling. This usually takes a few seconds — refresh to see the confirmation.</p>+ <button class="awh-go-cta" type="button" data-act="refresh"><span>Refresh status</span></button>+ </div>+ </div>`;+ }++ function unavailableView() {+ // reason: not_configured (treasury off) | platform_agent | not_owner+ let title = 'Activation is paused';+ let lede = 'The activation grant is temporarily unavailable. You can still fund this agent yourself from the Deposit tab — that also brings it to life on the Pulse.';+ if (status?.reason === 'platform_agent') {+ title = 'Already live';+ lede = 'This is a platform-operated agent — it is already active on the Money Pulse. Activation is for agents you create.';+ }+ return `+ <div class="awh-go">+ <div class="awh-go-hero">+ <p class="awh-go-kicker">Go Live</p>+ <h2 class="awh-go-title">${escapeHtml(title)}</h2>+ <p class="awh-go-lede">${escapeHtml(lede)}</p>+ <div class="awh-go-next">+ <button class="awh-btn awh-btn--primary" type="button" data-act="tab-deposit">Fund from Deposit</button>+ <a class="awh-btn" href="/pulse">Open the Money Pulse ↗</a>+ </div>+ </div>+ </div>`;+ }++ function render() {+ if (destroyed) return;+ if (!loaded) { panel.innerHTML = skeleton(); return; }+ if (!status) { panel.innerHTML = unavailableView(); wire(); return; }+ if (status.activated && status.receipt) panel.innerHTML = liveView(status.receipt);+ else if (status.pending) panel.innerHTML = pendingView();+ else if (status.eligible) panel.innerHTML = eligibleView();+ else panel.innerHTML = unavailableView();+ wire();+ }++ function wire() {+ panel.querySelector('[data-act="go"]')?.addEventListener('click', activate);+ panel.querySelector('[data-act="refresh"]')?.addEventListener('click', () => { loaded = false; render(); load(); });+ panel.querySelector('[data-act="tab-pulse"]')?.addEventListener('click', () => ctx.openTab('pulse'));+ panel.querySelector('[data-act="tab-deposit"]')?.addEventListener('click', () => ctx.openTab('deposit'));+ }++ async function load() {+ const r = await call(`/api/agents/${ctx.agentId}/activate`);+ if (destroyed) return;+ loaded = true;+ status = r.ok ? r.data : null;+ render();+ }++ async function activate() {+ if (busy) return;+ busy = true;+ errorMsg = null;+ const btn = panel.querySelector('[data-act="go"]');+ const label = panel.querySelector('[data-host="cta-label"]');+ if (btn) btn.disabled = true;+ if (label) label.innerHTML = `<span class="awh-go-spin" aria-hidden="true"></span> Activating…`;++ const r = await call(`/api/agents/${ctx.agentId}/activate`, { method: 'POST' });+ busy = false;+ if (destroyed) return;++ if (r.ok) {+ const d = r.data || {};+ if (d.pending && !d.signature) {+ status = { ...(status || {}), pending: true, eligible: false };+ render();+ return;+ }+ // Confirmed (fresh grant or already-activated receipt).+ status = {+ ...(status || {}),+ activated: true,+ eligible: false,+ pending: false,+ receipt: {+ signature: d.signature,+ explorer: d.explorer,+ sol: d.sol,+ usd: d.usd,+ network: d.network,+ activated_at: d.activated_at || new Date().toISOString(),+ },+ };+ render();+ toast(d.already ? `${agentName} is already live` : `◎${formatSol(d.sol)} SOL granted — ${agentName} is live`);+ return;+ }++ // Designed failure — keep the CTA, surface a recoverable message.+ errorMsg =+ r.code === 'not_configured' || r.code === 'treasury_low'+ ? 'Activation is paused right now. You can fund this agent from the Deposit tab instead — that also brings it live.'+ : r.code === 'cap_reached'+ ? "Today's activation grants are all claimed. Try again tomorrow, or fund from the Deposit tab now."+ : r.message || 'Activation failed — please try again.';+ render();+ }++ render();++ return {+ onShow() {+ if (!loaded) load();+ else render();+ },+ destroy() {+ destroyed = true;+ },+ };+ },+});diff --git a/src/pulse.css b/src/pulse.cssindex 344f0d872..c1995377b 100644--- a/src/pulse.css+++ b/src/pulse.css@@ -55,8 +55,10 @@.px-net-btn.active { color: var(--ink-bright, #fff); background: var(--surface-3, rgba(255,255,255,.08)); }.px-net-btn:focus-visible { outline: 2px solid var(--ink-bright, #fff); outline-offset: 2px; }-/* Headline counters — a tidy 3×2 grid; the volume lead is emphasised, not wider. */-.px-counters { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-sm, 10px); margin: var(--space-xl, 40px) 0 var(--space-md, 16px); }+/* Headline counters — a 4-col grid where the volume lead spans two cells, so the+ seven counters tile evenly (4 + 3 with the lead double-wide) with no orphan. */+.px-counters { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-sm, 10px); margin: var(--space-xl, 40px) 0 var(--space-md, 16px); }+.px-counter--lead { grid-column: span 2; }.px-counter { background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.07));border-radius: var(--radius-lg, 14px); padding: var(--space-md, 16px) var(--space-sm, 14px); text-align: center;transition: border-color .16s ease, background .16s ease; }diff --git a/vercel.json b/vercel.jsonindex b133675f2..a847bd479 100644--- a/vercel.json+++ b/vercel.json@@ -1973,6 +1973,10 @@"src": "/api/agents/([^/]+)/solana/([^/]+)","dest": "/api/agents/[id]"},+ {+ "src": "/api/agents/([^/]+)/activate",+ "dest": "/api/agents/[id]"+ },{"src": "/api/agents/([^/]+)/alpha/([^/]+)","dest": "/api/agents/[id]"