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(bounties): pump bounties surface + pump-go lib
nirholas0fbeb6292186
diff --git a/README.md b/README.mdindex dc4e1b378..e39f8c1fd 100644--- a/README.md+++ b/README.md@@ -404,6 +404,20 @@ three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM GraSix showcase surfaces put it on screen, cross-linked by an in-page suite switcher: the [Agent Galaxy](https://three.ws/ibm/galaxy) (semantic 3D star-map), the [Granite Oracle](https://three.ws/ibm/oracle) (narrated forecast), the [Digital Twin](https://three.ws/ibm/twin) (back-test + what-if), the [Trust Layer](https://three.ws/ibm/trust-layer) (Guardian + hash-chained audit ledger), [Granite Proof](https://three.ws/ibm/proof) (a Guardian-governed forecast notarized on Solana), and [Granite Vision](https://three.ws/ibm/vision). The standalone connector [`@three-ws/ibm-watsonx-mcp`](packages/ibm-watsonx-mcp/) exposes watsonx.ai to any MCP host — it is community-built and not an IBM product; the hosted platform integration is what runs on IBM watsonx.ai.+### Pay-per-call Granite over MCP (x402)++The world's first **x402-enabled MCP server on IBM Cloud**: [`@three-ws/ibm-x402-mcp`](packages/ibm-x402-mcp/) turns IBM Granite into a metered utility any AI agent can call. The operator holds the IBM credentials and funds inference; the caller pays **a few cents of USDC per call** — no IBM Cloud account, no subscription, no API-key signup. Full guide: **[docs/ibm-x402-mcp.md](docs/ibm-x402-mcp.md)**.++| Tool | What it does | Price |+| ---- | ------------ | ----- |+| `ibm_granite_chat` | Conversational AI — Q&A, drafting, reasoning | $0.02 |+| `ibm_granite_code` | Generate / review / refactor / explain / test / document code | $0.025 |+| `ibm_granite_embed` | Batch text embeddings (1–64) for RAG, search, clustering | $0.005 |+| `ibm_granite_analyze` | Structured doc analysis — entities, sentiment, risk, next steps | $0.04 |+| `ibm_granite_forecast` | Zero-shot time-series forecasting via Granite TTM | $0.05 |++The same five tools ship over two transports: **stdio** (`npx @three-ws/ibm-x402-mcp`, for Claude Desktop / Code / Cursor, paid on Solana) and **Streamable HTTP** (`https://three.ws/api/ibm-mcp`, for hosted clients and watsonx Orchestrate, paid on Base or Solana). An unpaid `tools/call` returns a `402` quoting the exact USDC price; x402-capable clients pay and retry automatically, settling on-chain only after the tool succeeds. Independent project integrating IBM Granite via watsonx.ai — not an IBM product.+---## Screenshotsdiff --git a/api/_lib/mcp-dispatch.js b/api/_lib/mcp-dispatch.jsindex 497f5389e..e8b9cce75 100644--- a/api/_lib/mcp-dispatch.js+++ b/api/_lib/mcp-dispatch.js@@ -37,7 +37,7 @@ function summarize(args) {export function makeDispatcher({ serverInfo, instructions, catalog, tools, logName }) {const log = logger(logName);- async function onToolCall(params, auth, started) {+ async function onToolCall(params, auth, started, req) {const { name, arguments: args = {} } = params || {};const tool = tools[name];if (!tool) throw rpcError(-32602, `unknown tool: ${name}`);@@ -60,7 +60,7 @@ export function makeDispatcher({ serverInfo, instructions, catalog, tools, logNatool: name,};try {- const result = await tool.handler(args, auth);+ const result = await tool.handler(args, auth, req);recordEvent({...event,latencyMs: Date.now() - started,@@ -86,7 +86,7 @@ export function makeDispatcher({ serverInfo, instructions, catalog, tools, logNa}}- return async function dispatch(msg, auth, _req) {+ return async function dispatch(msg, auth, req) {const started = Date.now();const id = msg.id;const isNotification = id === undefined;@@ -110,7 +110,8 @@ export function makeDispatcher({ serverInfo, instructions, catalog, tools, logNaif (method === 'ping') return ok(id, {});if (method === 'notifications/initialized') return null;if (method === 'tools/list') return ok(id, { tools: catalog });- if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started));+ if (method === 'tools/call')+ return ok(id, await onToolCall(msg.params, auth, started, req));if (method === 'resources/list') return ok(id, { resources: [] });if (method === 'resources/templates/list') return ok(id, { resourceTemplates: [] });if (method === 'prompts/list') return ok(id, { prompts: [] });@@ -123,7 +124,11 @@ export function makeDispatcher({ serverInfo, instructions, catalog, tools, logNareturn {jsonrpc: '2.0',id,- error: { code: err.code || -32603, message: err.message || 'internal error', data: err.data },+ error: {+ code: err.code || -32603,+ message: err.message || 'internal error',+ data: err.data,+ },};}};diff --git a/api/_lib/pump-go.js b/api/_lib/pump-go.jsnew file mode 100644index 000000000..1e67a6fbd--- /dev/null+++ b/api/_lib/pump-go.js@@ -0,0 +1,188 @@+// pump.fun GO — read-only client for the public bounties API.+//+// GO (pump.fun/go/bounties) is two layers (mapped from mainnet observation):+// • on-chain — the `pump_bounties` Anchor program (goGz…KiV) holding reward+// escrow in PDA vaults and running the bounty/dispute/award lifecycle.+// • off-chain — a PUBLIC read REST API at livestream-api.pump.fun serving the+// bounty content (title/body/criteria/rewards/attachments), bridged back to+// chain by `onChainBountyId`.+//+// Reads require NO auth — these are public endpoints. (Likes/submissions/deletes+// need a pump.fun SIWS JWT; out of scope for the read-only board.) We fetch with+// a browser-like UA + a hard timeout, and normalize the verbose upstream Task+// into a lean, UI-friendly shape. The normalizers are pure so they unit-test+// without the network.++const REST_BASE = 'https://livestream-api.pump.fun';+const PROGRAM_ID = 'goGzNYTYkSEe4hUqz6dPmY5uf3CTt36AQAoujXDrKiV';+const WSOL_MINT = 'So11111111111111111111111111111111111111112';+const TIMEOUT_MS = 10_000;+const MAX_LIMIT = 50;++// Upstream error with an HTTP status, so handlers surface a real envelope rather+// than a misleading empty list when pump.fun is down.+export class PumpGoError extends Error {+ constructor(message, status = 502) {+ super(message);+ this.name = 'PumpGoError';+ this.status = status;+ this.code = 'pump_go_upstream';+ }+}++async function pumpGoGet(path) {+ let res;+ try {+ res = await fetch(`${REST_BASE}${path}`, {+ headers: {+ accept: 'application/json',+ 'user-agent': 'Mozilla/5.0 (compatible; three.ws/1.0; +https://three.ws)',+ origin: 'https://pump.fun',+ referer: 'https://pump.fun/',+ },+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ } catch (e) {+ throw new PumpGoError(`pump.fun GO unreachable: ${e.message}`, 504);+ }+ if (res.status === 404) throw new PumpGoError('bounty not found', 404);+ if (!res.ok) throw new PumpGoError(`pump.fun GO upstream ${res.status}`, 502);+ try {+ return await res.json();+ } catch {+ throw new PumpGoError('pump.fun GO returned non-JSON', 502);+ }+}++function clampLimit(limit, fallback = 30) {+ return Math.min(Math.max(parseInt(limit, 10) || fallback, 1), MAX_LIMIT);+}++// USD for a reward leg from the parallel rewardLegsUsd array (only when priced).+function legUsd(legsUsd, mint) {+ const m = (legsUsd || []).find((x) => x.mintAddress === mint);+ return m && m.priced ? (m.usdValue ?? null) : null;+}++// atomic string → human float by decimals. Display only — never on-chain math.+function fromAtomic(atomic, decimals) {+ const n = Number(atomic);+ if (!Number.isFinite(n)) return null;+ return n / 10 ** (decimals || 0);+}++export function normalizeTask(t) {+ if (!t || typeof t !== 'object') return null;+ const legsUsd = t.rewardLegsUsd || [];+ const legs = (t.rewardLegs || []).map((l) => ({+ mint: l.mintAddress,+ tokenProgram: l.tokenProgramId,+ decimals: l.decimalsSnapshot,+ amount: fromAtomic(l.amountAtomic, l.decimalsSnapshot),+ remaining: fromAtomic(l.remainingAmountAtomic, l.decimalsSnapshot),+ amountAtomic: l.amountAtomic,+ isSol: l.mintAddress === WSOL_MINT,+ vault: l.rewardVaultAddress,+ usd: legUsd(legsUsd, l.mintAddress),+ }));+ const solLeg = legs.find((l) => l.isSol);+ return {+ taskId: t.taskId,+ title: t.title || '',+ bodyMarkdown: t.bodyMarkdown || '',+ status: t.status || null,+ submissionVisibility: t.submissionVisibility || null,+ coinAddress: t.coinAddress || null,+ creator: {+ address: t.creatorAddress || null,+ xFollowers: t.creatorXFollowerCount ?? null,+ xVerified: !!t.creatorXVerified,+ },+ criteria: Array.isArray(t.criteria)+ ? t.criteria.map((c) => ({+ id: c.id,+ text: c.text,+ required: !!c.required,+ order: c.order ?? 0,+ }))+ : [],+ createdAt: t.createdAt || null,+ publishedAt: t.publishedAt || null,+ fundedAt: t.fundedAt || null,+ expiresAt: t.expiresAt || null,+ counts: {+ submissions: t.counts?.submissionCount ?? 0,+ disputes: t.counts?.disputeCount ?? 0,+ },+ likeCount: t.likeCount ?? 0,+ reward: {+ totalUsd: t.rewardTotalUsd ?? null,+ pricedAt: t.rewardPricedAt || null,+ sol: solLeg ? solLeg.amount : null,+ legs,+ },+ attachments: (t.attachments || []).map((a) => ({+ filename: a.filename,+ kind: a.kind,+ contentType: a.contentType,+ size: a.size,+ url: a.url,+ })),+ onChain: {+ programId: t.pumpBountiesProgramId || PROGRAM_ID,+ bountyId: t.onChainBountyId || null,+ config: t.chainConfigSnapshot || null,+ },+ // Present only on the detail endpoint.+ rewardDistribution: t.rewardDistribution ?? null,+ };+}++export function normalizeSubmission(s) {+ if (!s || typeof s !== 'object') return null;+ return {+ submissionId: s.submissionId,+ taskId: s.taskId,+ body: s.bodyMarkdown || '',+ requester: s.requesterAddress || null,+ likeCount: s.likeCount ?? 0,+ createdAt: s.createdAt || null,+ publishedAt: s.publishedAt || null,+ updatedAt: s.updatedAt || null,+ attachments: (s.attachments || []).map((a) => ({+ filename: a.filename,+ kind: a.kind,+ contentType: a.contentType,+ size: a.size,+ url: a.url,+ })),+ };+}++export async function listBounties({ limit = 30, cursor = null, status = null } = {}) {+ const qs = new URLSearchParams();+ qs.set('limit', String(clampLimit(limit)));+ if (cursor) qs.set('cursor', cursor);+ if (status) qs.set('status', status);+ const data = await pumpGoGet(`/bounties/tasks?${qs}`);+ const items = (data.items || []).map(normalizeTask).filter(Boolean);+ return { items, nextCursor: data.nextCursor || null };+}++export async function getBounty(taskId) {+ const data = await pumpGoGet(`/bounties/tasks/${encodeURIComponent(taskId)}`);+ return normalizeTask(data);+}++export async function getSubmissions(taskId, { limit = 30 } = {}) {+ const qs = new URLSearchParams();+ qs.set('limit', String(clampLimit(limit)));+ const data = await pumpGoGet(`/bounties/tasks/${encodeURIComponent(taskId)}/submissions?${qs}`);+ const raw = data.items || (Array.isArray(data) ? data : []);+ return {+ items: raw.map(normalizeSubmission).filter(Boolean),+ nextCursor: data.nextCursor || null,+ };+}++export { REST_BASE, PROGRAM_ID, WSOL_MINT };diff --git a/api/pump-bounties.js b/api/pump-bounties.jsnew file mode 100644index 000000000..0b4c3967a--- /dev/null+++ b/api/pump-bounties.js@@ -0,0 +1,39 @@+// GET /api/pump-bounties — read-only mirror of pump.fun GO's public bounty list.+//+// Proxies livestream-api.pump.fun/bounties/tasks (public, no auth) through a+// short server cache so we hit pump.fun rarely and serve every visitor from+// cache. Pagination is cursor-based (pass `cursor` = the previous page's+// `nextCursor`); `status` filters; `limit` caps at 50.++import { cors, json, error, wrap, method } from './_lib/http.js';+import { cacheGet, cacheSet } from './_lib/cache.js';+import { listBounties, PumpGoError } from './_lib/pump-go.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://localhost');+ const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '30', 10), 1), 50);+ const cursor = url.searchParams.get('cursor') || null;+ const status = url.searchParams.get('status') || null;++ const cacheKey = `pumpgo:list:${limit}:${cursor || '_'}:${status || '_'}`;+ const cached = await cacheGet(cacheKey).catch(() => null);+ if (cached) {+ res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');+ return json(res, 200, cached);+ }++ let data;+ try {+ data = await listBounties({ limit, cursor, status });+ } catch (e) {+ if (e instanceof PumpGoError) return error(res, e.status, e.code, e.message);+ throw e;+ }++ await cacheSet(cacheKey, data, 30).catch(() => {});+ res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');+ return json(res, 200, data);+});diff --git a/api/pump-bounties/[id].js b/api/pump-bounties/[id].jsnew file mode 100644index 000000000..7149e8cbc--- /dev/null+++ b/api/pump-bounties/[id].js@@ -0,0 +1,47 @@+// GET /api/pump-bounties/:id — a single pump.fun GO bounty + its submissions.+//+// `id` is the off-chain task uuid. Fetches the bounty detail and (best-effort)+// its submissions in parallel from the public livestream-api, normalizes, and+// caches briefly. A submissions failure degrades to an empty list rather than+// failing the whole page — the bounty itself is the primary content.++import { cors, json, error, wrap, method } from '../_lib/http.js';+import { cacheGet, cacheSet } from '../_lib/cache.js';+import { isUuid } from '../_lib/validate.js';+import { getBounty, getSubmissions, PumpGoError } from '../_lib/pump-go.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const id = req.query?.id || req.url?.split('/').pop()?.split('?')[0];+ if (!id || !isUuid(id)) return error(res, 400, 'bad_request', 'valid bounty taskId required');++ const cacheKey = `pumpgo:task:${id}`;+ const cached = await cacheGet(cacheKey).catch(() => null);+ if (cached) {+ res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');+ return json(res, 200, cached);+ }++ let bounty, submissions;+ try {+ [bounty, submissions] = await Promise.all([+ getBounty(id),+ getSubmissions(id, { limit: 50 }).catch(() => ({ items: [], nextCursor: null })),+ ]);+ } catch (e) {+ if (e instanceof PumpGoError) return error(res, e.status, e.code, e.message);+ throw e;+ }+ if (!bounty) return error(res, 404, 'not_found', 'bounty not found');++ const payload = {+ bounty,+ submissions: submissions.items,+ submissionsCursor: submissions.nextCursor,+ };+ await cacheSet(cacheKey, payload, 30).catch(() => {});+ res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');+ return json(res, 200, payload);+});diff --git a/docs/ibm-x402-mcp.md b/docs/ibm-x402-mcp.mdnew file mode 100644index 000000000..431857633--- /dev/null+++ b/docs/ibm-x402-mcp.md@@ -0,0 +1,351 @@+# IBM Granite x402 MCP — pay-per-call AI for agents++> The world's first **x402-enabled MCP server on IBM Cloud**. Any AI agent or MCP+> client can call IBM Granite foundation models and pay **per call in USDC** — no+> IBM Cloud account, no subscription, no API-key signup.++Every AI agent needs three things: a **body** (its 3D avatar), a **brain**+(an LLM with memory), and a **wallet** (to pay for the jobs it runs). This is the+wallet half of the brain — three.ws is an **IBM Business Partner**, and this suite+is how an agent reaches enterprise-grade **IBM Granite** inference and settles the+bill itself, in USDC, over [x402](https://x402.org).++This is the developer guide for the `@three-ws/ibm-x402-mcp` tool suite. For the+broader IBM integration (the platform showcase, Guardian Trust Layer, the+credentials-based `@three-ws/ibm-watsonx-mcp` connector) see **[docs/ibm.md](./ibm.md)**.+For the x402 protocol primitives used elsewhere on the platform see+**[docs/x402.md](./x402.md)**.++---++## Why this exists++A normal MCP server that wraps a hosted model forces every caller to bring their+own provider account, API key, and billing relationship. That kills the agent+use case: an autonomous agent can't sign up for IBM Cloud, accept terms, and+provision a watsonx.ai project mid-task.++The x402 MCP suite flips the model. **The operator** holds the IBM credentials+and funds inference; **the caller** pays a few cents of USDC per call and gets the+result. Settlement is on-chain, instant, and requires nothing but a wallet the+agent already controls. That's the unlock — Granite becomes a metered utility any+agent can consume the moment it has USDC.++| | Credentials connector ([`ibm-watsonx-mcp`](../packages/ibm-watsonx-mcp/)) | **x402 suite ([`ibm-x402-mcp`](../packages/ibm-x402-mcp/))** |+|---|---|---|+| Who pays IBM | The **caller** (their `WATSONX_*` key) | The **operator** (one shared key) |+| Caller needs IBM Cloud account | Yes | **No** |+| Caller pays per call | No (flat IBM billing) | **Yes — USDC on Solana/Base** |+| Best for | A developer wiring their own watsonx.ai key into their own client | An **agent** that wants Granite on demand and will pay for it |++---++## The five tools++Each tool is independently priced. Prices are the source of truth in+[`src/tools/`](../packages/ibm-x402-mcp/src/tools/) and mirrored here.++| Tool | What it does | Model | Price |+|---|---|---|---|+| `ibm_granite_chat` | Conversational AI — Q&A, drafting, reasoning, instruction following | Granite 3 8B Instruct | **$0.02** |+| `ibm_granite_code` | Generate / review / refactor / explain / test / document code | Granite 3 8B Instruct | **$0.025** |+| `ibm_granite_embed` | Batch text embeddings (1–64 inputs) for RAG, search, clustering | Granite Embedding 278M Multilingual | **$0.005** |+| `ibm_granite_analyze` | Structured document analysis — entities, sentiment, risk flags, summary, next steps | Granite 3 8B Instruct | **$0.04** |+| `ibm_granite_forecast` | Zero-shot time-series forecasting, no training | Granite TTM (Tiny Time Mixer) | **$0.05** |++All Granite 3 tools also process German, Spanish, French, Portuguese, Japanese,+Korean, Italian, Dutch, Chinese, Arabic, and Czech.++---++## Two transports, one tool suite++The exact same five tools — identical schemas, prices, and output shapes — ship+over two transports:++| Transport | Endpoint | For | Payment |+|---|---|---|---|+| **stdio** (npm) | `npx @three-ws/ibm-x402-mcp` | Local MCP hosts: Claude Desktop, Claude Code, Cursor | Per-call USDC on **Solana** |+| **Streamable HTTP** (remote) | `https://three.ws/api/ibm-mcp` | Hosted clients, watsonx Orchestrate, custom agents | Per-call USDC on **Base or Solana** |++The stdio package is [`packages/ibm-x402-mcp`](../packages/ibm-x402-mcp/). The+remote endpoint is [`api/ibm-mcp.js`](../api/ibm-mcp.js) backed by+[`api/_mcpibm/`](../api/_mcpibm/), reusing the platform's server-side watsonx+client and x402 settlement infra. Both are registered with the MCP Registry:+`io.github.nirholas/ibm-x402-mcp` (stdio) and+`io.github.nirholas/ibm-x402-mcp-remote` (HTTP, see [`server-ibm.json`](../server-ibm.json)).++### Dual-mode access on the remote endpoint++watsonx Orchestrate is not x402-capable, so the hosted endpoint supports two+paths:++- **Anonymous callers pay per call.** An unpaid `tools/call` returns a `402`+ quoting the exact per-tool price, advertised on Base and Solana mainnet.+ x402-capable clients pay and retry automatically; settlement runs *after* the+ tool succeeds.+- **Authenticated three.ws principals (Bearer / OAuth) call without per-call+ payment** — the operator-funded path. A watsonx Orchestrate connection supplies+ a Bearer credential, making the tools included-in-connection rather than billed+ per USDC call.++---++## How a paid call works++```+MCP Client (Claude Desktop / Cursor / agent)+ │ tools/call (no payment yet)+ ▼+ibm-x402-mcp ──► 402 PaymentRequired {price: $0.02 USDC, payTo: <wallet>, network: solana}+ ▲+ │ tools/call (signed USDC transfer in _meta["x402/payment"])+ ▼+ibm-x402-mcp+ ├──► PayAI Facilitator verify + settle USDC on-chain+ ├──► IBM watsonx.ai inference with operator Bearer token+ └──► result + _meta["x402/payment-response"] (settlement receipt)+```++1. Client calls a tool without payment → server returns a `402 PaymentRequired`+ envelope quoting the USDC price and the receiving Solana address.+2. Client builds and signs a Solana USDC transfer.+3. Client retries with the signed tx in `_meta["x402/payment"]`.+4. Server verifies via the [PayAI facilitator](https://facilitator.payai.network),+ calls watsonx.ai, then settles the payment.+5. Response carries the result plus a settlement receipt in+ `_meta["x402/payment-response"]`.++x402-capable MCP clients run this whole loop automatically — to the agent it+looks like one tool call that happens to cost a few cents.++---++## Quickstart — call it (end user)++You only need a wallet with USDC. Wire the server into your MCP client:++```json+{+ "mcpServers": {+ "ibm-x402": {+ "command": "npx",+ "args": ["-y", "@three-ws/ibm-x402-mcp"],+ "env": {+ "MCP_SVM_PAYMENT_ADDRESS": "operator-wallet-address"+ }+ }+ }+}+```++> The stdio package is one process: it both **serves** tools and, when *you* run+> it, the operator env (`WATSONX_*` + receiving wallet) belongs to whoever hosts+> it. To consume someone else's hosted suite without running watsonx yourself,+> point your client at the remote endpoint `https://three.ws/api/ibm-mcp`.++Inspect the tools interactively:++```bash+npx -y @modelcontextprotocol/inspector npx @three-ws/ibm-x402-mcp+```++---++## Quickstart — run it (server operator)++You supply IBM credentials and a wallet to receive payments; your callers supply+only USDC.++```bash+MCP_SVM_PAYMENT_ADDRESS=<your-solana-wallet> \+WATSONX_API_KEY=<ibm-api-key> \+WATSONX_PROJECT_ID=<watsonx-project-id> \+npx @three-ws/ibm-x402-mcp+```++### Configuration++**Required**++| Env var | Description |+|---|---|+| `MCP_SVM_PAYMENT_ADDRESS` | Solana wallet that receives USDC payments from callers |+| `WATSONX_API_KEY` | IBM Cloud API key — [create one](https://cloud.ibm.com/iam/apikeys) |+| `WATSONX_PROJECT_ID` | watsonx.ai project id (Project → Manage → General → Project ID) |++**Optional**++| Env var | Default | Description |+|---|---|---|+| `WATSONX_SPACE_ID` | — | Deployment space id (alternative to `WATSONX_PROJECT_ID`) |+| `WATSONX_URL` | `https://us-south.ml.cloud.ibm.com` | Regional inference host |+| `WATSONX_MODEL_ID` | `ibm/granite-3-8b-instruct` | Default chat/generation model |+| `WATSONX_EMBED_MODEL_ID` | `ibm/granite-embedding-278m-multilingual` | Default embedding model |+| `X402_FEE_PAYER_SOLANA` | three.ws fee payer | Solana account sponsoring tx fees |+| `X402_FACILITATOR_URL` | `https://facilitator.payai.network` | x402 payment facilitator |+| `X402_FACILITATOR_TOKEN` | — | Bearer token for the facilitator (optional) |+| `X402_ASSET_MINT_SOLANA` | USDC mainnet mint | USDC mint override |++Regional hosts: `us-south`, `eu-de`, `eu-gb`, `jp-tok`, `au-syd`, `ca-tor` →+e.g. `https://eu-de.ml.cloud.ibm.com`.++The server **fails fast**: a missing payment address or missing IBM credentials+exits at startup with an actionable message — a running server that can't receive+USDC or reach watsonx is useless, so it never silently degrades.++---++## Tool reference++### `ibm_granite_chat` — $0.02++Conversational completion. Send an ordered array of role/content messages; get+the assistant reply plus token usage.++```jsonc+{+ "messages": [+ { "role": "system", "content": "You are an expert data engineer." },+ { "role": "user", "content": "Design a lakehouse schema for IoT sensor telemetry." }+ ],+ "max_new_tokens": 1024, // 1–4096, default 1024+ "temperature": 0.7 // 0–2, default 0.7+}+```++`messages` accepts 1–50 entries. Optional `model` overrides the default chat+model.++### `ibm_granite_code` — $0.025++Six code tasks via Granite instruct models.++```jsonc+{+ "task": "review", // generate | review | refactor | explain | test | document+ "prompt": "def calculate_roi(revenue, cost): return revenue / cost",+ "language": "Python" // optional hint+}+```++- **generate** — new code from a description+- **review** — severity-ranked bugs / security / improvement findings+- **refactor** — clarity, performance, best practices+- **explain** — plain-language walkthrough+- **test** — unit tests+- **document** — inline docs / docstrings++Optional `context` supplies surrounding code or constraints.++### `ibm_granite_embed` — $0.005++Batch-embeds 1–64 texts (up to 8,000 chars each), one dense float vector per+input. Use for semantic search, RAG retrieval, clustering, dedup, and+cross-language similarity.++```jsonc+{+ "inputs": [+ "enterprise data governance",+ "cloud-native AI pipeline",+ "real-time analytics"+ ]+}+```++### `ibm_granite_analyze` — $0.04++Extracts a machine-readable JSON analysis from any text — entities, sentiment+(label + score), key findings, severity-tagged risk flags, a 3-sentence summary,+and 3 actionable next steps. Extraction is tailored per `analysis_type`.++```jsonc+{+ "document": "This Software License Agreement is entered into between...",+ "analysis_type": "contract" // general | contract | financial | technical | medical | sentiment+}+```++`document` accepts up to 24,000 chars. Examples of type-specific extraction:+`contract` → parties, obligations, termination/penalty clauses; `financial` →+metrics, red flags, forward-looking statements.++### `ibm_granite_forecast` — $0.05++Zero-shot numeric forecasting via IBM Granite TTM — no training. Provide 64–1024+ISO-8601 timestamps and aligned numeric values at a uniform cadence; receive a+forecast horizon as timestamped points.++```jsonc+{+ "timestamps": ["2025-01-01T00:00:00Z", "2025-01-02T00:00:00Z", "..."],+ "values": [12500, 13200, 0],+ "freq": "1D", // pandas-style: 1min, 5min, 1h, 1D, 1W, 1ME, ...+ "prediction_length": 14, // optional, 1–96; defaults to model horizon+ "label": "daily_revenue_usd" // optional, echoed back for traceability+}+```++`timestamps` and `values` must be equal length. Example response:++```jsonc+{+ "ok": true,+ "label": "daily_revenue_usd",+ "model": "ibm/granite-ttm-512-96-r2",+ "inputWindow": 512,+ "forecastSteps": 14,+ "forecast": [+ { "timestamp": "2025-06-07T00:00:00Z", "value": 1420 },+ { "timestamp": "2025-06-08T00:00:00Z", "value": 1388 }+ ]+}+```++Use for revenue, traffic, demand, sensor, energy, and financial series.++### Error shape++Tools never throw to the client. On bad input or an upstream watsonx failure they+return a structured error:++```jsonc+{ "ok": false, "error": "watsonx_error", "message": "...", "status": 400 }+```++Codes: `invalid_input` (caller-side), `watsonx_error` (upstream, carries the+HTTP `status`), `internal_error` (unexpected).++---++## Discovery (x402 Bazaar)++Each tool declares an x402 discovery extension, so the suite is browsable in the+[x402 Bazaar](./mcp-x402-bazaar.md) alongside its schema, example input, and+example output. Agents can find Granite tools by capability and price without+knowing the server up front.++---++## Affiliation++three.ws is an **IBM Business Partner**. This npm package is an independent,+open-source project (Apache-2.0) built by three.ws that integrates IBM Granite via+watsonx.ai — IBM Cloud Partner Center requires third-party MCP listings to state+this, so to be precise: the package itself is **not an IBM product** and is not+operated by IBM. Granite, watsonx, and watsonx.ai are trademarks of IBM.+Catalog/listing copy is maintained in+[`CATALOG.md`](../packages/ibm-x402-mcp/CATALOG.md); support policy in+[`SUPPORT.md`](../packages/ibm-x402-mcp/SUPPORT.md).++---++## See also++- [docs/ibm.md](./ibm.md) — the full IBM Granite / watsonx integration and showcase+- [docs/x402.md](./x402.md) — the x402 payment protocol on three.ws+- [docs/mcp.md](./mcp.md) — wiring MCP servers into a client+- [docs/mcp-x402-bazaar.md](./mcp-x402-bazaar.md) — x402 service discovery+- [packages/ibm-x402-mcp](../packages/ibm-x402-mcp/) — the npm package source+- npm: [`@three-ws/ibm-x402-mcp`](https://www.npmjs.com/package/@three-ws/ibm-x402-mcp)diff --git a/docs/ibm.md b/docs/ibm.mdindex e59c108fb..b3eb64aa3 100644--- a/docs/ibm.md+++ b/docs/ibm.md@@ -283,6 +283,7 @@ Unit tests for the same paths live in [`tests/`](../tests/) (`granite-oracle`, `- [How it works](./how-it-works.md) — the platform mental model- [Agent system](./agent-system.md) — the brain abstraction Granite plugs into+- [IBM Granite x402 MCP](./ibm-x402-mcp.md) — pay-per-call Granite for agents (USDC, no IBM account)- [MCP](./mcp.md) — wiring MCP servers into a client- [REST API](./api-reference.md) — the full endpoint reference- [Configuration](./configuration.md) — all environment variablesdiff --git a/docs/mcp-3d-studio.md b/docs/mcp-3d-studio.mdindex c8c9ed907..40defa997 100644--- a/docs/mcp-3d-studio.md+++ b/docs/mcp-3d-studio.md@@ -1,52 +1,141 @@# three.ws 3D Studio — MCP server-Turn text or an image into an interactive, textured 3D model — directly from-Claude, Cursor, or any MCP client. A focused companion to the main three.ws MCP-server, registered separately as **`io.github.nirholas/threews-3d-studio`**.+Turn text or an image into an interactive, **animation-ready** 3D model — and rig,+animate, pose, edit, retexture, and analyze it — directly from Claude, Cursor,+watsonx Orchestrate, or any MCP client. A focused companion to the main three.ws+MCP server, registered separately as **`io.github.nirholas/threews-3d-studio`**.- **Endpoint:** `https://three.ws/api/mcp-3d`-- **Transport:** Streamable HTTP (MCP `2025-06-18`)+- **Transport:** Streamable HTTP (MCP `2025-06-18`, JSON-RPC 2.0)- **Auth:** OAuth 2.1 (same three.ws authorization server as `/api/mcp`) or x402-- **Backend:** Microsoft TRELLIS image→3D and FLUX text→image, on Replicate+- **Backends:** Microsoft TRELLIS image→3D + FLUX text→image (Replicate, platform-keyed); Meshy / Tripo native geometry (BYOK); VAST-AI UniRig auto-rig; IBM Granite (watsonx.ai) for prompt direction + material generation-## Tools+## The pipeline-| Tool | What it does |-|------|--------------|-| `text_to_3d(prompt, aspect_ratio?)` | Text → reference image → reconstructed GLB. Returns a `job_id` and the intermediate preview image. |-| `image_to_3d(image_url, prompt?)` | Reconstruct a GLB from a single reference image. Returns a `job_id`. |-| `generation_status(job_id)` | Poll a job. When done, returns the GLB URL **and** an inline `<model-viewer>` artifact. |-| `preview_3d(glb_url, …)` | Render any public GLB as an interactive `<model-viewer>` artifact (orbit, AR, auto-rotate). |-| `inspect_model(url)` | Structural stats: meshes, triangles, materials, textures, extensions. |-| `optimize_model(url)` | Actionable size/perf suggestions: Draco/Meshopt, KTX2, triangle budget. |+The tools compose into one flow — each step's output feeds the next:-Generation is asynchronous: `text_to_3d` / `image_to_3d` return a `job_id`-immediately, then you poll `generation_status` (reconstruction is typically-30–90s). When a job finishes, `generation_status` returns a `text/html`-resource — display it as an inline 3D artifact.+```+direct_prompt ─▶ text_to_3d ─┐+ image_to_3d ─┴▶ generation_status ─▶ auto_rig_model ─▶ apply_animation+ └─▶ pose_model+mesh ops: remesh_model · stylize_model · segment_model · retexture_model · retexture_region · generate_material+analyze: inspect_model · optimize_model preview: preview_3d+```-## Use on claude.ai+> "Optimize this idea, generate it, rig it, and make it wave." → `direct_prompt`+> → `text_to_3d` → poll `generation_status` → `auto_rig_model` → poll →+> `apply_animation(animation: "wave")`.-Add the connector with URL `https://three.ws/api/mcp-3d` and complete the OAuth-flow. Then:+## Tools-> "Make a 3D model of a low-poly red fox sitting upright."+### Generate++| Tool | What it does |+| ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `text_to_3d(prompt, aspect_ratio?, tier?, path?, backend?)` | Text → reference image → reconstructed GLB. Returns a `job_id` + the intermediate preview image. |+| `image_to_3d(image_url \| image_urls[], prompt?, tier?, path?, backend?)` | Reconstruct a GLB from 1–4 reference views (multi-view removes back-of-object hallucination). Returns a `job_id`. |+| `generation_status(job_id)` | Poll any job. When done, returns the GLB URL **and** an inline `<model-viewer>` artifact. Provider-aware: routes geometry/self-host jobs to the right upstream. |++### Rig, animate & pose++| Tool | What it does |+| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |+| `auto_rig_model(glb_url)` | Add a humanoid skeleton + per-vertex skin weights to a static GLB (VAST-AI UniRig). Returns a `job_id`; poll for the rigged GLB. |+| `list_animations(category?)` | The curated, retargetable animation-clip catalogue (names, categories, loop flags). |+| `apply_animation(model_url, animation, format?, speed?)` | Retarget a preset clip onto a rigged GLB — returns the retargeted `AnimationClip` JSON (or a baked animated GLB). |+| `pose_model(prompt)` | Map a pose description to a deterministic seed + full Euler joint-rotation map from the in-repo preset library. Free, deterministic. |++### Edit & process the mesh++| Tool | What it does |+| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |+| `remesh_model(mesh_url, operation?, target_faces?, output_format?)` | Repair, simplify (quadric decimation), or convert format (incl. FBX with skeleton for Unity/Unreal). |+| `stylize_model(mesh_url, style?, resolution?, output_format?)` | One-pass geometric restyle: `voxel`, `brick` (LEGO-like), `voronoi` lattice, `lowpoly`. |+| `segment_model(mesh_url, method?, max_parts?, …)` | Split into named, separable parts (each a node) + a parts manifest. |+| `retexture_model(mesh_url, prompt, num_views?, texture_size?)` | Paint a fresh texture from a prompt (SDXL + ControlNet depth, multi-view back-projection). |+| `retexture_region(mesh_url, mask_url, prompt?, color?, …)` | Magic-brush: repaint only a masked UV region, feathering the seam. |+| `generate_material(description, name?)` | IBM Granite → a glTF 2.0 PBR material (base color, metallic, roughness, emissive). |++### Assist, analyze & preview++| Tool | What it does |+| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `direct_prompt(idea, style?)` | IBM Granite rewrites a vague/multi-subject idea into one optimized single-subject `text_to_3d` prompt + structured directives. |+| `inspect_model(url)` | Structural stats: meshes, triangles, materials, textures, animations, extensions. |+| `optimize_model(url)` | Actionable size/perf suggestions: Draco/Meshopt, KTX2, triangle budget. |+| `preview_3d(glb_url, …)` | Render any public GLB as an interactive `<model-viewer>` artifact (orbit, AR, auto-rotate). |++Generation, rigging, and most mesh ops are **asynchronous**: the tool returns a+`job_id` immediately, then you poll `generation_status` (reconstruction is+typically 30–90s; rigging 30–90s; texture jobs 2–5 min). When a job finishes,+`generation_status` returns a `text/html` resource — display it as an inline 3D+artifact.++## Quality tiers & generation paths++`text_to_3d` / `image_to_3d` take three optional axes (see+[`api/_lib/forge-tiers.js`](../api/_lib/forge-tiers.js)):++- **`tier`** — `draft` (~12k poly, fast), `standard` (~30k, default), `high`+ (~200k + PBR, slower). Honoured by poly-aware backends; on the TRELLIS default+ it's recorded as provenance.+- **`path`** — `image` (FLUX→TRELLIS reference-image reconstruction, the+ platform-keyed default) or `geometry` (native text/image→mesh, cleaner+ topology).+- **`backend`** — force a specific engine; defaults to the best for the path.++| Backend | Path(s) | Key | Notes |+| ----------- | --------------- | --------- | ------------------------------------ |+| `trellis` | image | platform | Fast default. No poly target. |+| `meshy` | geometry, image | **BYOK** | Native text→geometry, quad topology. |+| `tripo` | geometry, image | **BYOK** | Cleanest quad topology. |+| `hunyuan3d` | image | self-host | High-poly, image-conditioned (GCP). |++**BYOK note:** the geometry backends (Meshy/Tripo) have no platform key. Supply+your own via the `x-forge-provider-key` request header (or a key stored on your+three.ws account). Without one, the geometry path returns a designed `needs_key`+result and the **image path still works keyless**. The job handle for a geometry+job is an opaque forge token; `generation_status` decodes it and re-resolves the+key per poll.++## IBM Granite tools++`direct_prompt` and `generate_material` call IBM Granite foundation models via+watsonx.ai. They're **operator-funded**: set `WATSONX_API_KEY` and+`WATSONX_PROJECT_ID` on the server and end users pay nothing extra for them — no+IBM Cloud account required on the caller side. If watsonx isn't configured, both+return a clear "not configured" error rather than failing mid-call.++## Use on claude.ai / watsonx Orchestrate-Claude calls `text_to_3d`, polls `generation_status`, and renders the result as-a live, orbitable 3D artifact in the chat.+Add the connector with URL `https://three.ws/api/mcp-3d` and complete the OAuth+flow (or connect it from the watsonx Orchestrate MCP catalog). Then:-## Configuration+> "Make a 3D model of a low-poly red fox sitting upright, rig it, and make it idle."-The server needs a Replicate token (already used by the avatar regen pipeline):+The assistant calls `text_to_3d`, polls `generation_status`, renders the result+as a live orbitable artifact, then `auto_rig_model` → `apply_animation(animation:+"idle")` for a moving character.-| Env | Purpose | Default |-|-----|---------|---------|-| `REPLICATE_API_TOKEN` | Required. From replicate.com/account. | — |-| `REPLICATE_RECONSTRUCT_MODEL` | image→3D model. | `firtoz/trellis` |-| `REPLICATE_TXT2IMG_MODEL` | text→image model for `text_to_3d`. | `black-forest-labs/flux-schnell` |+## Configuration-Rate limits: generation is capped at 12 jobs/hour per principal (real GPU-spend); status polling at 240/min.+| Env | Purpose | Default |+| --------------------------------------------------- | ------------------------------------------------------------------------------------- | -------------------------------- |+| `REPLICATE_API_TOKEN` | Required. Powers reconstruction, rigging, remesh, retexture. | — |+| `REPLICATE_RECONSTRUCT_MODEL` | image→3D model. | `firtoz/trellis` |+| `REPLICATE_TXT2IMG_MODEL` | text→image model for `text_to_3d`. | `black-forest-labs/flux-schnell` |+| `REPLICATE_RERIG_MODEL` | Auto-rig model. Without it, `auto_rig_model` reports "not configured". | — |+| `GCP_RECONSTRUCTION_URL` / `GCP_RECONSTRUCTION_KEY` | Optional self-host backend (Hunyuan3D, masked region retexture). | — |+| `WATSONX_API_KEY` / `WATSONX_PROJECT_ID` | Enable `direct_prompt` + `generate_material`. | — |+| `APP_ORIGIN` | Origin used to load the animation manifest for `list_animations` / `apply_animation`. | request host |+| `MCP_POSE_PREVIEW_BASE` | Base URL for `pose_model` preview links. | `https://three.ws/pose` |++Geometry backends (Meshy/Tripo) take a **per-request** key via the+`x-forge-provider-key` header — never an env var.++Rate limits: generation/rig/mesh jobs are capped per principal (real GPU spend);+status polling is capped per minute. `pose_model`, `list_animations`,+`inspect_model`, and `optimize_model` are lightweight.## Publishing to the MCP Registrydiff --git a/packages/ibm-x402-mcp/README.md b/packages/ibm-x402-mcp/README.mdindex fd9dba7f8..8c7ab21d0 100644--- a/packages/ibm-x402-mcp/README.md+++ b/packages/ibm-x402-mcp/README.md@@ -5,6 +5,7 @@An [MCP](https://modelcontextprotocol.io) server that exposes IBM Granite foundation models as pay-per-use tools via the [x402](https://x402.org) payment protocol. End users pay **USDC on Solana** per call — no IBM Cloud account required.> Built by [three.ws](https://three.ws). Listed on IBM Cloud Partner Center.+> Full developer guide: **[docs/ibm-x402-mcp.md](https://github.com/nirholas/three.ws/blob/main/docs/ibm-x402-mcp.md)**.---@@ -63,6 +64,8 @@ npx @three-ws/ibm-x402-mcp| `WATSONX_EMBED_MODEL_ID` | `ibm/granite-embedding-278m-multilingual` | Default embedding model || `X402_FEE_PAYER_SOLANA` | three.ws fee payer | Solana account sponsoring tx fees || `X402_FACILITATOR_URL` | `https://facilitator.payai.network` | x402 payment facilitator |+| `X402_FACILITATOR_TOKEN` | — | Bearer token for the facilitator |+| `X402_ASSET_MINT_SOLANA` | USDC mainnet mint | USDC mint override |Regional hosts: `us-south`, `eu-de`, `eu-gb`, `jp-tok`, `au-syd`, `ca-tor`→ e.g. `https://eu-de.ml.cloud.ibm.com`diff --git a/pages/bounties.html b/pages/bounties.htmlnew file mode 100644index 000000000..9f7c646a3--- /dev/null+++ b/pages/bounties.html@@ -0,0 +1,70 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Bounties · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta+ name="description"+ content="Browse live pump.fun GO bounties — rewards, submissions, and on-chain escrow — on three.ws."+ />+ <meta name="theme-color" content="#0a0a0f" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Bounties · three.ws" />+ <meta+ property="og:description"+ content="Live pump.fun GO bounties — rewards, submissions, on-chain escrow."+ />+ <meta property="og:url" content="https://three.ws/bounties" />+ <meta name="twitter:card" content="summary_large_image" />+ <link rel="stylesheet" href="/pump-bounties.css" />+ </head>+ <body>+ <header class="topbar">+ <a href="/" class="brand">+ <span class="dot"></span>+ three.ws+ <span class="badge-go">Bounties</span>+ </a>+ <div class="topbar-right">+ <a href="/go" class="btn btn-ghost btn-sm">$THREE board</a>+ <a+ href="https://pump.fun/go/bounties"+ target="_blank"+ rel="noopener noreferrer"+ class="btn btn-primary btn-sm"+ >Open on pump.fun ↗</a+ >+ </div>+ </header>++ <main class="wrap">+ <div class="page-head">+ <h1>Bounty Board <span class="src-tag">Live · pump.fun GO</span></h1>+ <p>+ Every open bounty on pump.fun GO — task, reward, submissions, and the on-chain+ escrow backing it. Read-only and live; click any bounty for the full brief and+ proof feed.+ </p>+ </div>++ <div class="controls">+ <div class="seg" id="sort-seg" role="tablist" aria-label="Sort bounties">+ <button data-sort="reward" class="active">Top reward</button>+ <button data-sort="newest">Newest</button>+ <button data-sort="submissions">Most subs</button>+ <button data-sort="likes">Most liked</button>+ </div>+ <div class="spacer"></div>+ <button id="refresh-btn" class="btn btn-ghost btn-sm" aria-label="Refresh">+ ↻ Refresh+ </button>+ </div>++ <div class="grid" id="grid"></div>+ </main>++ <script type="module" src="/src/bounties.js"></script>+ </body>+</html>diff --git a/pages/bounty.html b/pages/bounty.htmlnew file mode 100644index 000000000..9fe05297c--- /dev/null+++ b/pages/bounty.html@@ -0,0 +1,53 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Bounty · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta+ name="description"+ content="A pump.fun GO bounty on three.ws — brief, reward, on-chain escrow, and submissions."+ />+ <meta name="theme-color" content="#0a0a0f" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Bounty · three.ws" />+ <link rel="stylesheet" href="/pump-bounties.css" />+ </head>+ <body>+ <header class="topbar">+ <a href="/" class="brand">+ <span class="dot"></span>+ three.ws+ <span class="badge-go">Bounties</span>+ </a>+ <div class="topbar-right">+ <a href="/bounties" class="btn btn-ghost btn-sm">← All bounties</a>+ </div>+ </header>++ <main class="wrap">+ <div id="root">+ <div class="detail">+ <div>+ <div class="skeleton skel-line" style="width: 40%"></div>+ <div class="skeleton skel-line" style="width: 80%; height: 30px"></div>+ <div class="detail-section">+ <div class="skeleton skel-line" style="width: 100%"></div>+ <div class="skeleton skel-line" style="width: 90%"></div>+ <div class="skeleton skel-line" style="width: 70%"></div>+ </div>+ </div>+ <div>+ <div class="side-card">+ <div class="skeleton skel-line" style="width: 50%; height: 30px"></div>+ <div class="skeleton skel-line" style="width: 80%"></div>+ </div>+ </div>+ </div>+ </div>+ </main>++ <script type="module" src="/src/bounty-detail.js"></script>+ </body>+</html>diff --git a/public/features.json b/public/features.jsonindex cc42c4341..dc4d992fb 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-08T05:30:39.887Z",+ "generated_at": "2026-06-08T07:30:07.453Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/pump-bounties.css b/public/pump-bounties.cssnew file mode 100644index 000000000..21d7a8005--- /dev/null+++ b/public/pump-bounties.css@@ -0,0 +1,594 @@+/* pump.fun GO bounty board — shared styles for /bounties (list) and /bounty/:id (detail). */+* {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+}+:root {+ --bg: #0a0a0f;+ --surface: #111118;+ --panel: rgba(255, 255, 255, 0.04);+ --panel-hover: rgba(255, 255, 255, 0.07);+ --border: rgba(255, 255, 255, 0.08);+ --text: #f0f0f8;+ --muted: rgba(240, 240, 248, 0.5);+ --muted-2: rgba(240, 240, 248, 0.32);+ --accent: #7c5cff;+ --accent-glow: rgba(124, 92, 255, 0.18);+ --green: #22c55e;+ --green-bg: rgba(34, 197, 94, 0.12);+ --amber: #f59e0b;+ --amber-bg: rgba(245, 158, 11, 0.12);+ --blue: #3b82f6;+ --blue-bg: rgba(59, 130, 246, 0.12);+ --sol: #14f195;+ --radius: 14px;+}+html,+body {+ background: var(--bg);+ color: var(--text);+ min-height: 100vh;+}+body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;+ -webkit-font-smoothing: antialiased;+ background:+ radial-gradient(900px 500px at 70% -5%, rgba(124, 92, 255, 0.12), transparent 60%),+ radial-gradient(700px 400px at 0% 30%, rgba(20, 241, 149, 0.05), transparent 55%), var(--bg);+}+a {+ color: inherit;+ text-decoration: none;+}+button {+ cursor: pointer;+ border: none;+ background: none;+ color: inherit;+ font: inherit;+}+img {+ display: block;+ max-width: 100%;+}++/* Top bar */+.topbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 14px clamp(16px, 4vw, 40px);+ position: sticky;+ top: 0;+ z-index: 20;+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ background: linear-gradient(180deg, rgba(10, 10, 15, 0.9) 70%, transparent);+ border-bottom: 1px solid var(--border);+}+.brand {+ display: flex;+ align-items: center;+ gap: 10px;+ font-weight: 800;+ font-size: 17px;+ letter-spacing: -0.5px;+}+.brand .dot {+ width: 10px;+ height: 10px;+ border-radius: 50%;+ background: var(--accent);+ box-shadow: 0 0 12px var(--accent);+}+.brand .badge-go {+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.08em;+ background: var(--accent);+ color: #fff;+ padding: 2px 8px;+ border-radius: 5px;+ text-transform: uppercase;+}+.topbar-right {+ display: flex;+ align-items: center;+ gap: 8px;+}+.btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 8px 16px;+ border-radius: 8px;+ font-size: 13px;+ font-weight: 600;+ transition:+ opacity 0.15s,+ transform 0.1s,+ background 0.15s;+}+.btn:active {+ transform: scale(0.97);+}+.btn-primary {+ background: var(--accent);+ color: #fff;+}+.btn-primary:hover {+ opacity: 0.88;+}+.btn-ghost {+ background: var(--panel);+ color: var(--text);+ border: 1px solid var(--border);+}+.btn-ghost:hover {+ background: var(--panel-hover);+}+.btn-sm {+ padding: 6px 12px;+ font-size: 12px;+}++.wrap {+ max-width: 1180px;+ margin: 0 auto;+ padding: 0 clamp(12px, 3vw, 32px) 100px;+}++/* Header */+.page-head {+ padding: 38px 0 22px;+}+.page-head h1 {+ font-size: clamp(26px, 4vw, 38px);+ font-weight: 800;+ letter-spacing: -1px;+ display: flex;+ align-items: center;+ gap: 12px;+ flex-wrap: wrap;+}+.page-head .src-tag {+ font-size: 12px;+ font-weight: 600;+ color: var(--muted);+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 999px;+ padding: 4px 12px;+}+.page-head p {+ margin-top: 10px;+ color: var(--muted);+ font-size: 14px;+ max-width: 620px;+ line-height: 1.6;+}++/* Controls */+.controls {+ display: flex;+ align-items: center;+ gap: 10px;+ flex-wrap: wrap;+ padding: 6px 0 20px;+ position: sticky;+ top: 57px;+ z-index: 10;+ background: linear-gradient(180deg, var(--bg) 70%, transparent);+}+.seg {+ display: inline-flex;+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 3px;+ gap: 2px;+}+.seg button {+ padding: 7px 13px;+ font-size: 12.5px;+ font-weight: 600;+ color: var(--muted);+ border-radius: 8px;+ transition:+ color 0.14s,+ background 0.14s;+}+.seg button:hover {+ color: var(--text);+}+.seg button.active {+ color: #fff;+ background: var(--accent);+}+.spacer {+ flex: 1;+}++/* Grid + cards */+.grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));+ gap: 14px;+}+.card {+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ overflow: hidden;+ display: flex;+ flex-direction: column;+ transition:+ border-color 0.15s,+ transform 0.12s,+ box-shadow 0.15s;+ cursor: pointer;+}+.card:hover {+ border-color: rgba(124, 92, 255, 0.4);+ transform: translateY(-2px);+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);+}+.card-thumb {+ height: 150px;+ background: #0d0d14 center / cover no-repeat;+ border-bottom: 1px solid var(--border);+ position: relative;+ flex-shrink: 0;+}+.card-thumb.empty {+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--muted-2);+ font-size: 30px;+ background: radial-gradient(120px 80px at 50% 30%, rgba(124, 92, 255, 0.12), transparent);+}+.card-body {+ padding: 14px 16px 16px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ flex: 1;+}+.card-title {+ font-size: 15px;+ font-weight: 700;+ line-height: 1.35;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.card-reward {+ display: flex;+ align-items: baseline;+ gap: 8px;+ margin-top: auto;+}+.reward-usd {+ font-size: 20px;+ font-weight: 800;+ color: var(--green);+ letter-spacing: -0.5px;+}+.reward-token {+ font-size: 12px;+ color: var(--muted);+ font-weight: 600;+}+.card-meta {+ display: flex;+ align-items: center;+ gap: 12px;+ flex-wrap: wrap;+ font-size: 12px;+ color: var(--muted);+}+.card-meta .m {+ display: inline-flex;+ align-items: center;+ gap: 4px;+}+.card-meta svg {+ width: 13px;+ height: 13px;+ opacity: 0.8;+}++.badge {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ padding: 4px 9px;+ border-radius: 6px;+}+.badge-open {+ background: var(--green-bg);+ color: var(--green);+}+.badge-pending {+ background: var(--amber-bg);+ color: var(--amber);+}+.badge-closed {+ background: var(--panel);+ color: var(--muted);+}+.badge-float {+ position: absolute;+ top: 10px;+ left: 10px;+ backdrop-filter: blur(6px);+ background: rgba(10, 10, 15, 0.6);+}+.verified {+ color: var(--blue);+}++/* Skeleton + states */+.skeleton {+ background: linear-gradient(90deg, var(--panel) 25%, var(--panel-hover) 50%, var(--panel) 75%);+ background-size: 200% 100%;+ animation: shimmer 1.4s infinite;+ border-radius: 8px;+}+@keyframes shimmer {+ 0% {+ background-position: 200% 0;+ }+ 100% {+ background-position: -200% 0;+ }+}+.skel-card {+ height: 280px;+ border-radius: var(--radius);+}+.empty,+.errbox {+ grid-column: 1 / -1;+ padding: 70px 20px;+ text-align: center;+ color: var(--muted);+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 12px;+}+.empty .ico,+.errbox .ico {+ font-size: 40px;+ opacity: 0.5;+}+.empty h3,+.errbox h3 {+ font-size: 17px;+ color: var(--text);+}+.empty p,+.errbox p {+ font-size: 13px;+ max-width: 360px;+ line-height: 1.6;+}+.load-more {+ grid-column: 1 / -1;+ margin: 18px auto 0;+ padding: 11px 22px;+ border-radius: 10px;+ font-size: 13px;+ font-weight: 600;+ color: var(--text);+ background: var(--panel);+ border: 1px solid var(--border);+ transition: background 0.15s;+}+.load-more:hover {+ background: var(--panel-hover);+}+.load-more[disabled] {+ opacity: 0.6;+ cursor: default;+}++/* ── Detail page ── */+.detail {+ display: grid;+ grid-template-columns: 1fr 340px;+ gap: 28px;+ align-items: start;+ padding-top: 26px;+}+@media (max-width: 900px) {+ .detail {+ grid-template-columns: 1fr;+ }+}+.detail h1 {+ font-size: clamp(22px, 3.5vw, 32px);+ font-weight: 800;+ letter-spacing: -0.6px;+ line-height: 1.2;+ margin: 12px 0 14px;+}+.crumbs {+ font-size: 13px;+ color: var(--muted);+}+.crumbs a:hover {+ color: var(--text);+}+.detail-section {+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 18px 20px;+ margin-bottom: 16px;+}+.detail-section h2 {+ font-size: 12px;+ font-weight: 700;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--muted);+ margin-bottom: 12px;+}+.body-md {+ font-size: 14.5px;+ line-height: 1.7;+ color: rgba(240, 240, 248, 0.86);+ white-space: pre-wrap;+ word-break: break-word;+}+.criteria-li {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ padding: 9px 0;+ border-bottom: 1px solid var(--border);+ font-size: 14px;+}+.criteria-li:last-child {+ border-bottom: none;+}+.criteria-li .chk {+ flex-shrink: 0;+ width: 18px;+ height: 18px;+ border-radius: 5px;+ border: 1.5px solid var(--border);+ color: var(--accent);+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 11px;+ margin-top: 1px;+}+.criteria-li .req {+ font-size: 10px;+ color: var(--amber);+ font-weight: 700;+ text-transform: uppercase;+ margin-left: auto;+ flex-shrink: 0;+}+.gallery {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));+ gap: 10px;+}+.gallery a {+ display: block;+ border-radius: 10px;+ overflow: hidden;+ border: 1px solid var(--border);+ aspect-ratio: 4 / 3;+ background: #0d0d14;+}+.gallery img {+ width: 100%;+ height: 100%;+ object-fit: cover;+}++/* Reward / chain side panel */+.side-card {+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 18px 20px;+ margin-bottom: 16px;+}+.reward-hero {+ font-size: 34px;+ font-weight: 800;+ color: var(--green);+ letter-spacing: -1px;+}+.reward-sub {+ color: var(--muted);+ font-size: 13px;+ margin-top: 2px;+}+.leg-row,+.kv {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ font-size: 13px;+ padding: 9px 0;+ border-bottom: 1px solid var(--border);+}+.leg-row:last-child,+.kv:last-child {+ border-bottom: none;+}+.kv .k {+ color: var(--muted);+}+.kv .v {+ font-weight: 600;+ font-family: ui-monospace, 'JetBrains Mono', monospace;+ font-size: 12px;+}+.kv .v a {+ color: var(--accent);+}+.kv .v a:hover {+ text-decoration: underline;+}+.mono {+ font-family: ui-monospace, 'JetBrains Mono', monospace;+}++/* Submissions */+.sub {+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 14px 16px;+ margin-bottom: 10px;+ background: rgba(255, 255, 255, 0.02);+}+.sub-head {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 12px;+ color: var(--muted);+ margin-bottom: 8px;+}+.sub-avatar {+ width: 22px;+ height: 22px;+ border-radius: 50%;+ background: linear-gradient(135deg, var(--accent), var(--sol));+ flex-shrink: 0;+}+.sub-body {+ font-size: 13.5px;+ line-height: 1.6;+ color: rgba(240, 240, 248, 0.82);+ white-space: pre-wrap;+ word-break: break-word;+}+.sub-likes {+ margin-left: auto;+ color: #ff6b81;+ font-weight: 600;+}+.skel-line {+ height: 14px;+ margin-bottom: 10px;+}diff --git a/src/bounties.js b/src/bounties.jsnew file mode 100644index 000000000..95e0970fe--- /dev/null+++ b/src/bounties.js@@ -0,0 +1,220 @@+// Bounties list — three.ws/bounties+//+// Mirrors pump.fun GO's public bounty board via our cached proxy+// (/api/pump-bounties). Cursor-paginated; sort is applied client-side over the+// loaded set. Read-only.++const API = '/api/pump-bounties';+const PAGE = 30;++let items = [];+let nextCursor = null;+let loading = false;+let sortKey = 'reward';++const grid = () => document.getElementById('grid');++// ── Boot ──────────────────────────────────────────────────────────────────────++function init() {+ bindControls();+ load(true);+}++function bindControls() {+ document.getElementById('sort-seg').addEventListener('click', (e) => {+ const btn = e.target.closest('button[data-sort]');+ if (!btn) return;+ document.querySelectorAll('#sort-seg button').forEach((b) => b.classList.remove('active'));+ btn.classList.add('active');+ sortKey = btn.dataset.sort;+ renderGrid();+ });+ document.getElementById('refresh-btn').addEventListener('click', () => load(true));+ grid().addEventListener('click', (e) => {+ const card = e.target.closest('.card[data-id]');+ if (card) location.href = `/bounty/${card.dataset.id}`;+ });+}++// ── Data ──────────────────────────────────────────────────────────────────────++async function load(reset = false) {+ if (loading) return;+ loading = true;+ if (reset) {+ items = [];+ nextCursor = null;+ grid().innerHTML = skeletons(8);+ } else {+ setLoadMore('Loading…', true);+ }++ try {+ const url = new URL(API, location.origin);+ url.searchParams.set('limit', String(PAGE));+ if (!reset && nextCursor) url.searchParams.set('cursor', nextCursor);+ const r = await fetch(url);+ const data = await r.json();+ if (!r.ok) throw new Error(data.error_description || data.error || `HTTP ${r.status}`);++ items = reset ? data.items || [] : items.concat(data.items || []);+ nextCursor = data.nextCursor || null;+ renderGrid();+ } catch (err) {+ if (reset) {+ grid().innerHTML = errorState(err.message);+ } else {+ setLoadMore('Retry', false);+ }+ } finally {+ loading = false;+ }+}++// ── Render ────────────────────────────────────────────────────────────────────++function sorted() {+ const by = {+ reward: (a, b) => (b.reward.totalUsd || 0) - (a.reward.totalUsd || 0),+ newest: (a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0),+ submissions: (a, b) => (b.counts.submissions || 0) - (a.counts.submissions || 0),+ likes: (a, b) => (b.likeCount || 0) - (a.likeCount || 0),+ }[sortKey];+ return [...items].sort(by);+}++function renderGrid() {+ const el = grid();+ if (!items.length) {+ el.innerHTML = emptyState();+ return;+ }+ el.innerHTML = sorted().map(card).join('');+ if (nextCursor) {+ const btn = document.createElement('button');+ btn.className = 'load-more';+ btn.id = 'load-more';+ btn.textContent = 'Load more';+ btn.addEventListener('click', () => load(false));+ el.appendChild(btn);+ }+}++function card(b) {+ const img = b.attachments.find(+ (a) => a.kind === 'image' || /^image\//.test(a.contentType || ''),+ );+ const thumb = img+ ? `<div class="card-thumb" style="background-image:url('${esc(img.url)}')">${statusBadge(b.status, true)}</div>`+ : `<div class="card-thumb empty">🎯${statusBadge(b.status, true)}</div>`;+ const usd = b.reward.totalUsd != null ? `$${fmtNum(b.reward.totalUsd)}` : '—';+ const token = b.reward.sol != null ? `◎ ${fmtNum(b.reward.sol)} SOL` : tokenLabel(b);+ const left = timeLeft(b.expiresAt);++ return `+ <article class="card" data-id="${esc(b.taskId)}">+ ${thumb}+ <div class="card-body">+ <div class="card-title">${esc(b.title) || 'Untitled bounty'}</div>+ <div class="card-reward">+ <span class="reward-usd">${usd}</span>+ ${token ? `<span class="reward-token">${esc(token)}</span>` : ''}+ </div>+ <div class="card-meta">+ <span class="m">${iconUser()} ${shortAddr(b.creator.address)}${b.creator.xVerified ? ` <span class="verified" title="X verified">✔</span>` : ''}</span>+ <span class="m">${iconSubs()} ${b.counts.submissions} subs</span>+ <span class="m">♥ ${b.likeCount}</span>+ ${left ? `<span class="m">⏳ ${esc(left)}</span>` : ''}+ </div>+ </div>+ </article>`;+}++function statusBadge(status, float = false) {+ const s = String(status || '').toUpperCase();+ let cls = 'badge-pending',+ label = s.replace(/_/g, ' ');+ if (s === 'OPEN' || s === 'ACTIVE' || s === 'PUBLISHED') {+ cls = 'badge-open';+ label = 'Open';+ } else if (s.includes('PENDING')) {+ cls = 'badge-pending';+ label = 'Resolving';+ } else if (+ s.includes('CLOSED') ||+ s.includes('AWARD') ||+ s.includes('RESOLVED') ||+ s.includes('REFUND')+ ) {+ cls = 'badge-closed';+ label = label.charAt(0) + label.slice(1).toLowerCase();+ }+ if (!label) label = 'Bounty';+ return `<span class="badge ${cls}${float ? ' badge-float' : ''}">${esc(label)}</span>`;+}++function tokenLabel(b) {+ const leg = b.reward.legs && b.reward.legs[0];+ if (!leg || leg.amount == null) return '';+ return `${fmtNum(leg.amount)} tokens`;+}++// ── States ────────────────────────────────────────────────────────────────────++function skeletons(n) {+ return Array.from({ length: n }, () => `<div class="skeleton skel-card"></div>`).join('');+}+function emptyState() {+ return `<div class="empty"><div class="ico">🎯</div><h3>No open bounties right now</h3><p>The pump.fun GO board is quiet at the moment. Check back shortly.</p></div>`;+}+function errorState(msg) {+ return `<div class="errbox"><div class="ico">⚠️</div><h3>Couldn't load bounties</h3><p>${esc(msg)}</p><button class="btn btn-ghost btn-sm" onclick="location.reload()">Try again</button></div>`;+}+function setLoadMore(text, disabled) {+ const b = document.getElementById('load-more');+ if (b) {+ b.textContent = text;+ b.disabled = disabled;+ }+}++// ── Helpers ───────────────────────────────────────────────────────────────────++function esc(str) {+ if (str == null) return '';+ return String(str)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}+function fmtNum(n) {+ const x = Number(n) || 0;+ if (x >= 1000) return x.toLocaleString('en-US', { maximumFractionDigits: 0 });+ if (x >= 1) return x.toLocaleString('en-US', { maximumFractionDigits: 2 });+ return x.toLocaleString('en-US', { maximumFractionDigits: 4 });+}+function timeLeft(iso) {+ if (!iso) return '';+ const ms = new Date(iso) - Date.now();+ if (ms <= 0) return 'expired';+ const d = Math.floor(ms / 86400000);+ const h = Math.floor((ms % 86400000) / 3600000);+ if (d > 0) return `${d}d ${h}h`;+ const m = Math.floor((ms % 3600000) / 60000);+ return `${h}h ${m}m`;+}+function shortAddr(a) {+ if (!a) return 'anon';+ return a.length > 12 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a;+}+function iconUser() {+ return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="8" r="3.2"/><path d="M5 20c0-3.3 3.1-5.5 7-5.5s7 2.2 7 5.5"/></svg>`;+}+function iconSubs() {+ return `<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M17 9H7m10 0l-4-4m4 4l-4 4M3 4v12"/></svg>`;+}++init();diff --git a/src/bounty-detail.js b/src/bounty-detail.jsnew file mode 100644index 000000000..76023f1a1--- /dev/null+++ b/src/bounty-detail.js@@ -0,0 +1,238 @@+// Bounty detail — three.ws/bounty/:taskId+//+// Renders a single pump.fun GO bounty from our cached proxy+// (/api/pump-bounties/:id): the brief + acceptance criteria, the reward+// breakdown, the on-chain escrow bridge (program / vault / creator → Solscan),+// and the public submission feed. Read-only.++const SOLSCAN = 'https://solscan.io/account/';++const taskId = (() => {+ const seg = location.pathname.split('/').filter(Boolean);+ // /bounty/:id+ const fromPath = seg[0] === 'bounty' ? seg[1] : null;+ return fromPath || new URLSearchParams(location.search).get('id') || '';+})();++async function init() {+ if (!taskId) return fail('No bounty specified.');+ try {+ const r = await fetch(`/api/pump-bounties/${encodeURIComponent(taskId)}`);+ const data = await r.json();+ if (!r.ok) throw new Error(data.error_description || data.error || `HTTP ${r.status}`);+ render(data.bounty, data.submissions || []);+ } catch (err) {+ fail(err.message);+ }+}++function render(b, submissions) {+ document.title = `${b.title || 'Bounty'} · three.ws`;+ const img = b.attachments.filter(+ (a) => a.kind === 'image' || /^image\//.test(a.contentType || ''),+ );++ document.getElementById('root').innerHTML = `+ <div class="crumbs"><a href="/bounties">Bounties</a> · ${esc(statusLabel(b.status))}</div>+ <div class="detail">+ <div>+ <h1>${esc(b.title) || 'Untitled bounty'}</h1>++ <div class="detail-section">+ <h2>The brief</h2>+ <div class="body-md">${esc(b.bodyMarkdown) || '<span style="color:var(--muted)">No description provided.</span>'}</div>+ </div>++ ${+ b.criteria.length+ ? `<div class="detail-section">+ <h2>Acceptance criteria</h2>+ ${b.criteria+ .slice()+ .sort((a, c) => (a.order || 0) - (c.order || 0))+ .map(+ (c) => `<div class="criteria-li">+ <span class="chk">${c.required ? '✓' : ''}</span>+ <span>${esc(c.text)}</span>+ ${c.required ? '<span class="req">Required</span>' : ''}+ </div>`,+ )+ .join('')}+ </div>`+ : ''+ }++ ${+ img.length+ ? `<div class="detail-section">+ <h2>Attachments</h2>+ <div class="gallery">${img+ .map(+ (a) =>+ `<a href="${esc(a.url)}" target="_blank" rel="noopener noreferrer"><img src="${esc(a.url)}" alt="${esc(a.filename || 'attachment')}" loading="lazy" /></a>`,+ )+ .join('')}</div>+ </div>`+ : ''+ }++ <div class="detail-section">+ <h2>Submissions · ${submissions.length}</h2>+ ${+ submissions.length+ ? submissions.map(submission).join('')+ : `<div style="color:var(--muted);font-size:13px;">No public submissions yet.</div>`+ }+ </div>+ </div>++ <aside>+ <div class="side-card">+ <div class="reward-hero">${b.reward.totalUsd != null ? '$' + fmtNum(b.reward.totalUsd) : '—'}</div>+ <div class="reward-sub">reward pool${b.reward.pricedAt ? ' · priced live' : ''}</div>+ <div style="margin-top:14px">+ ${b.reward.legs+ .map(+ (l) => `<div class="leg-row">+ <span>${l.isSol ? '◎ SOL' : `<a class="mono" href="${SOLSCAN}${esc(l.mint)}" target="_blank" rel="noopener noreferrer" style="color:var(--accent)">${shortAddr(l.mint)}</a>`}</span>+ <span style="font-weight:700">${fmtNum(l.amount)}${l.usd != null ? ` <span style="color:var(--muted);font-weight:500">($${fmtNum(l.usd)})</span>` : ''}</span>+ </div>`,+ )+ .join('')}+ </div>+ </div>++ <div class="side-card">+ <div class="kv"><span class="k">Status</span><span class="v">${esc(statusLabel(b.status))}</span></div>+ <div class="kv"><span class="k">Submissions</span><span class="v">${b.counts.submissions}</span></div>+ <div class="kv"><span class="k">Likes</span><span class="v">${b.likeCount}</span></div>+ ${b.expiresAt ? `<div class="kv"><span class="k">Expires</span><span class="v">${esc(timeLeft(b.expiresAt))}</span></div>` : ''}+ <div class="kv"><span class="k">Creator</span><span class="v"><a href="${SOLSCAN}${esc(b.creator.address)}" target="_blank" rel="noopener noreferrer">${shortAddr(b.creator.address)}</a>${b.creator.xVerified ? ' <span class="verified">✔</span>' : ''}</span></div>+ ${b.coinAddress ? `<div class="kv"><span class="k">Coin</span><span class="v"><a href="https://pump.fun/coin/${esc(b.coinAddress)}" target="_blank" rel="noopener noreferrer">${shortAddr(b.coinAddress)} ↗</a></span></div>` : ''}+ </div>++ <div class="side-card">+ <h2 style="font-size:12px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin-bottom:12px">On-chain escrow</h2>+ <div class="kv"><span class="k">Program</span><span class="v"><a href="${SOLSCAN}${esc(b.onChain.programId)}" target="_blank" rel="noopener noreferrer">${shortAddr(b.onChain.programId)}</a></span></div>+ ${b.onChain.bountyId ? `<div class="kv"><span class="k">Bounty ID</span><span class="v">${esc(b.onChain.bountyId)}</span></div>` : ''}+ ${b.reward.legs+ .filter((l) => l.vault)+ .map(+ (l) =>+ `<div class="kv"><span class="k">${l.isSol ? 'SOL vault' : 'Token vault'}</span><span class="v"><a href="${SOLSCAN}${esc(l.vault)}" target="_blank" rel="noopener noreferrer">${shortAddr(l.vault)}</a></span></div>`,+ )+ .join('')}+ ${onChainFees(b.onChain.config)}+ </div>++ <a href="https://pump.fun/go/bounties" target="_blank" rel="noopener noreferrer" class="btn btn-primary btn-sm" style="width:100%;justify-content:center">Submit on pump.fun ↗</a>+ </aside>+ </div>`;+}++function submission(s) {+ const img = s.attachments.filter(+ (a) => a.kind === 'image' || /^image\//.test(a.contentType || ''),+ );+ return `+ <div class="sub">+ <div class="sub-head">+ <span class="sub-avatar"></span>+ <span class="mono">${shortAddr(s.requester)}</span>+ <span>· ${esc(timeAgo(s.createdAt))}</span>+ <span class="sub-likes">♥ ${s.likeCount}</span>+ </div>+ ${s.body ? `<div class="sub-body">${esc(s.body)}</div>` : ''}+ ${+ img.length+ ? `<div class="gallery" style="margin-top:10px">${img+ .map(+ (a) =>+ `<a href="${esc(a.url)}" target="_blank" rel="noopener noreferrer"><img src="${esc(a.url)}" alt="proof" loading="lazy" /></a>`,+ )+ .join('')}</div>`+ : ''+ }+ </div>`;+}++function onChainFees(cfg) {+ if (!cfg) return '';+ const lamports = (v) => (v != null ? Number(v) / 1e9 : null);+ const pub = lamports(cfg.publishFeeLamports);+ const dispute = lamports(cfg.disputeFeeLamports);+ const win =+ cfg.disputeWindowSeconds != null+ ? Math.round(Number(cfg.disputeWindowSeconds) / 3600)+ : null;+ const rows = [];+ if (pub != null)+ rows.push(+ `<div class="kv"><span class="k">Publish fee</span><span class="v">◎ ${fmtNum(pub)}</span></div>`,+ );+ if (dispute != null)+ rows.push(+ `<div class="kv"><span class="k">Dispute fee</span><span class="v">◎ ${fmtNum(dispute)}</span></div>`,+ );+ if (win != null)+ rows.push(+ `<div class="kv"><span class="k">Dispute window</span><span class="v">${win}h</span></div>`,+ );+ return rows.join('');+}++// ── States / helpers ──────────────────────────────────────────────────────────++function fail(msg) {+ document.getElementById('root').innerHTML = `+ <div class="errbox" style="padding:90px 20px">+ <div class="ico">⚠️</div>+ <h3>Couldn't load this bounty</h3>+ <p>${esc(msg)}</p>+ <a href="/bounties" class="btn btn-ghost btn-sm">← Back to bounties</a>+ </div>`;+}++function statusLabel(status) {+ const s = String(status || '').replace(/_/g, ' ');+ return s ? s.charAt(0) + s.slice(1).toLowerCase() : 'Bounty';+}+function esc(str) {+ if (str == null) return '';+ return String(str)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}+function fmtNum(n) {+ const x = Number(n) || 0;+ if (x >= 1000) return x.toLocaleString('en-US', { maximumFractionDigits: 0 });+ if (x >= 1) return x.toLocaleString('en-US', { maximumFractionDigits: 2 });+ return x.toLocaleString('en-US', { maximumFractionDigits: 4 });+}+function timeLeft(iso) {+ if (!iso) return '';+ const ms = new Date(iso) - Date.now();+ if (ms <= 0) return 'expired';+ const d = Math.floor(ms / 86400000);+ const h = Math.floor((ms % 86400000) / 3600000);+ return d > 0 ? `${d}d ${h}h` : `${h}h`;+}+function timeAgo(iso) {+ if (!iso) return '';+ const s = Math.floor((Date.now() - new Date(iso)) / 1000);+ if (s < 60) return `${s}s ago`;+ const m = Math.floor(s / 60);+ if (m < 60) return `${m}m ago`;+ const h = Math.floor(m / 60);+ if (h < 24) return `${h}h ago`;+ return `${Math.floor(h / 24)}d ago`;+}+function shortAddr(a) {+ if (!a) return 'anon';+ return a.length > 12 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a;+}++init();diff --git a/tasks/mcp-agent-selfsufficiency/01-memory-mcp-tools.md b/tasks/mcp-agent-selfsufficiency/01-memory-mcp-tools.mdnew file mode 100644index 000000000..511f128e7--- /dev/null+++ b/tasks/mcp-agent-selfsufficiency/01-memory-mcp-tools.md@@ -0,0 +1,113 @@+# Task 01 — Memory MCP tools (`remember` / `recall` / `forget`)++**Pillar:** Brain (LLM memory). **Server:** main `/api/mcp`.+**Read first:** [`README.md`](README.md) (shared conventions, MCP authoring+contract, Definition of Done) and `/CLAUDE.md`.++## Goal++Give agents persistent, recallable memory **through MCP**. The entire memory+backend already exists and is battle-tested — it is simply not exposed as MCP+tools. After this task, an agent connected to `/api/mcp` can store a memory,+recall the most relevant memories for a query, and forget one — closing the+"brain (LLM **memory**)" half of the narrative that IBM Granite _inference_+(`/api/ibm-mcp`) does not cover.++## What already exists (wire to this — do not rebuild)++- **REST endpoint:** `api/agent-memory.js` - `GET /api/agent-memory?agentId=` — list an agent's memories (owner only),+ ordered `salience DESC, created_at DESC`, excluding expired (`expires_at`). - `POST /api/agent-memory` — upsert a memory: `{ agentId, type, content, tags,+context, salience, expires_at }`. `type ∈ {user, feedback, project,+reference}`; `salience` default `0.5`. - `DELETE /api/agent-memory/:id` — forget (owner only). - Ownership is enforced via `agent_identities.user_id` (see `resolveAuth` and+ the `SELECT user_id FROM agent_identities WHERE id = ${agentId}` checks).+- **DB table:** `agent_memories (id, agent_id, type, content, tags, context,+salience, created_at, expires_at, updated_at)`.+- **Semantic recall:** `api/agents/_id/embed.js` produces Voyage AI embeddings+ (`voyage-3-lite`, 1024-dim) used for similarity search; an `AgentMemory.recall()`+ helper exists (find it — search `recall(` and `agent_memories`) that ranks by+ salience + vector similarity. **Reuse the existing recall logic**; do not+ re-implement embedding/ranking from scratch.++Read all of `api/agent-memory.js` and the recall helper before writing.++## Build++Create `api/_mcp/tools/memory.js` exporting `toolDefs` with three tools, and wire+it into `api/_mcp/catalog.js` (`import { toolDefs as memoryDefs }` → add to+`allDefs`).++### `remember` (scope: `memory:write`)++Store a memory for one of the caller's agents.++- Inputs: `agent_id` (required, uuid), `content` (required, 1–4000 chars),+ `type` (enum user|feedback|project|reference, default `reference`), `tags`+ (string[] optional), `context` (string optional), `salience` (number 0–1+ optional, default 0.5), `expires_at` (ISO-8601 string optional).+- Behavior: verify `agent_identities.user_id === auth.userId` (reuse the+ endpoint's ownership query); upsert into `agent_memories`; if an embedding+ step is part of the existing write path, run it. Return the stored memory id ++ fields.++### `recall` (scope: `memory:read`)++Retrieve the most relevant memories for a query.++- Inputs: `agent_id` (required), `query` (required, 1–1000 chars), `limit`+ (int 1–50, default 8), `type` (optional filter).+- Behavior: ownership check, then call the existing `AgentMemory.recall()` (or+ equivalent) — semantic similarity over the query embedding, blended with+ salience, excluding expired. Return an ordered list of `{ id, type, content,+tags, salience, score }`.++### `forget` (scope: `memory:write`)++Delete a memory the caller owns.++- Inputs: `memory_id` (required), or (`agent_id` + `memory_id`).+- Behavior: ownership check (join `agent_memories` → `agent_identities.user_id`,+ mirroring `handleDelete`), delete, return `{ ok: true, id }`.++## Requirements & edge cases++- **Ownership on every tool.** Reuse `api/agent-memory.js`'s ownership query —+ do not trust `agent_id` from input. If the agent isn't owned by `auth.userId`+ (or `auth.userId` is null on the x402 path), return a designed error+ ("sign in with three.ws OAuth and pass an agent you own"), not a throw.+- Register `memory:read` and `memory:write` in the OAuth scope list (find where+ scopes like `avatars:read` / `avatars:delete` are defined — `api/_mcp/auth.js`+ / `api/_lib/auth.js`) so they can actually be granted.+- Recall with zero stored memories returns an empty list with a helpful message,+ not an error.+- If embeddings/Voyage are unconfigured, recall must still work by falling back+ to salience + recency ordering (the existing helper likely already does this —+ preserve that behavior; do not introduce a new failure mode).+- Respect a sensible rate limit (reuse an existing limiter from+ `api/_lib/rate-limit.js`; recall/remember are cheap but DB-backed).++## Wiring checklist++- [ ] `api/_mcp/tools/memory.js` created; `toolDefs` = [remember, recall, forget].+- [ ] Imported + added to `allDefs` in `api/_mcp/catalog.js`.+- [ ] `memory:read` / `memory:write` scopes registered and grantable.+- [ ] `INSTRUCTIONS` in `api/_mcp/dispatch.js` mention memory if appropriate.+- [ ] `server.json` description updated to mention agent memory.++## Definition of Done++All items in [`README.md`](README.md) → "Definition of Done", plus:++- [ ] Catalog assembles: `node --input-type=module -e "import('./api/_mcp/catalog.js').then(m=>console.log(m.TOOL_CATALOG.map(t=>t.name).join(', ')))"` lists `remember, recall, forget`.+- [ ] `tests/api/mcp-memory.test.js`: ownership rejection, schema validation,+ a happy-path remember→recall→forget round-trip (mock `sql`/embed at the+ module boundary), and the "no memories" empty case. Green.+- [ ] Manually verified via MCP inspector against `npm run dev`: `remember` then+ `recall` returns the stored item ranked first.++## Out of scope++- A dedicated memory MCP server (memory belongs on the main agent server).+- Auto-seeding memory from external sources (Farcaster seed already exists at+ `api/agents/_id/memory-seed-farcaster.js` — leave it).+- Wiring memory into IBM Granite chat (that's a future "memory-aware inference"+ task; this task only exposes store/recall/forget).diff --git a/tasks/mcp-agent-selfsufficiency/02-avatar-persist-and-render.md b/tasks/mcp-agent-selfsufficiency/02-avatar-persist-and-render.mdnew file mode 100644index 000000000..acb217b40--- /dev/null+++ b/tasks/mcp-agent-selfsufficiency/02-avatar-persist-and-render.md@@ -0,0 +1,106 @@+# Task 02 — Persist & render an avatar (`save_avatar` / `render_avatar_image`)++**Pillar:** Body. **Server:** 3D Studio `/api/mcp-3d` (+ reuse on main `/api/mcp`).+**Read first:** [`README.md`](README.md) and `/CLAUDE.md`.++## Goal++The 3D Studio MCP can already _generate_ a GLB (`text_to_3d` → `generation_status`+→ glb_url), but an agent cannot **persist** that GLB as a durable, named avatar,+nor get a **rendered image** of it — both require the web app today. This task+makes the body pipeline end-to-end over MCP: generate → **save** → **render**.+Saving is the connective tissue that later unlocks embedding (Task 04), on-chain+identity (Task 03), and OG/social images.++## What already exists (wire to this — do not rebuild)++- **Avatar storage / CRUD:** `api/avatars.js` and `api/agents.js`. Read them for+ the create/persist path — avatars live in the DB with a `model_url` (GLB in R2)+ and metadata (name, slug, visibility, owner `user_id`). Find the function that+ creates an avatar record + the R2 upload helper (search `putObject`,+ `model_url`, `INSERT INTO ... avatars`/`agent_identities`). Reuse it.+- **MCP read tools already exist** on `/api/mcp`: `list_my_avatars`, `get_avatar`,+ `delete_avatar` (`api/_mcp/tools/avatars.js`) — match their scope/ownership+ style (`avatars:read`, `avatars:delete`).+- **Render-to-image endpoint:** `api/avatar/render.js` —+ `GET /api/avatar/render?avatar=<uuid>&scene=&pose=&expression=&size=&bg=&format=`.+ Renders a stored avatar to PNG/JPEG/WebP via headless chromium + three.js and+ caches in R2. Scenes: `full-body | upper-body | portrait | headshot`. Pose ids+ come from `src/pose-presets.js`. **Note:** it currently requires a stored+ `avatar` UUID (it reads `avatar.model_url`).++Read `api/avatars.js`, `api/agents.js` (the create path), and `api/avatar/render.js`+fully before writing.++## Build++### A) `save_avatar` — add to `api/_mcp3d/tools/studio.js` (scope: `avatars:write`)++Persist a public GLB URL (e.g. one returned by `generation_status`) as a durable+avatar owned by the caller.++- Inputs: `glb_url` (required, public https), `name` (required, 1–80 chars),+ `visibility` (enum `public|unlisted|private`, default `unlisted`),+ `source_prompt` (optional), `tags` (string[] optional).+- Behavior:+ 1. SSRF-guard the `glb_url` (reuse `isPublicHttpsUrl` already in studio.js).+ 2. Require `auth.userId` (return a designed "sign in to save" error if null).+ 3. Copy the GLB into durable storage (reuse the existing R2 upload / the forge+ `materializeCreation` pattern — search `materializeCreation` in+ `api/_lib/forge-store.js`) so the avatar survives provider URL expiry.+ 4. Create the avatar record (reuse the avatars create function) with+ `model_url` = durable URL, owner = `auth.userId`.+ 5. Return `{ avatar_id, slug, model_url, view_url }` where `view_url` is the+ public avatar page.+- This bridges Studio → the avatar system: after `save_avatar`, the existing+ `get_avatar` / `render_avatar` / Task 04 embed all work on the result.++### B) `render_avatar_image` — add to `api/_mcp/tools/avatars.js` (scope: `avatars:read`)++Render a stored avatar to an image and return its URL.++- Inputs: `avatar_id` (required, uuid), `scene` (enum full-body|upper-body|+ portrait|headshot, default upper-body), `pose` (optional preset id),+ `expression` (optional ARKit-52 morph object), `size` (int 64–2048, default+ 512), `bg` (string, default transparent), `format` (enum png|jpeg|webp,+ default png).+- Behavior: verify the avatar is the caller's or public (reuse the+ ownership/visibility check `get_avatar` uses), then produce the render URL via+ the **same code path** as `api/avatar/render.js`. Prefer calling the render+ endpoint's own logic over duplicating the chromium pipeline — if the render+ logic isn't importable, extract the param-building + cache-key + invocation+ into a small shared helper used by both the endpoint and this tool (no+ duplicated chromium code). Return `{ image_url, scene, cached }`.++## Requirements & edge cases++- **No duplicated render pipeline.** If you must share logic, extract a helper+ (`api/_lib/avatar-render.js` or similar) imported by both — delete-aggressively,+ per CLAUDE.md.+- Ownership/visibility: `render_avatar_image` may render public avatars owned by+ others (matches `get_avatar`), but `save_avatar` always writes to `auth.userId`.+- Validate `pose` against `src/pose-presets.js` ids and `expression` as a plain+ object (reuse the validation in `api/avatar/render.js`).+- Designed states: missing avatar → clear not-found; chromium/render failure →+ actionable error, never a fabricated image URL.+- Register `avatars:write` scope if it doesn't already exist.++## Definition of Done++All items in [`README.md`](README.md) → "Definition of Done", plus:++- [ ] `/api/mcp-3d` catalog lists `save_avatar`; `/api/mcp` catalog lists+ `render_avatar_image` (assembly check for both).+- [ ] `tests/api/mcp-avatar-persist.test.js`: save happy-path (mock R2 + DB),+ `auth.userId:null` rejection, SSRF rejection of a non-public glb_url, and a+ render happy-path (mock the render layer) + bad-pose rejection. Green.+- [ ] `server-3d.json` and `server.json` descriptions updated.+- [ ] Manually verified end-to-end via inspector: `text_to_3d` →+ `generation_status` → `save_avatar` → `render_avatar_image` returns an image+ URL.++## Out of scope++- New non-GLB export formats (FBX/USDZ already partly handled by `remesh_model`).+- Avatar editing UI. Adding `render_avatar_image` to the 3D Studio server (keep+ it on `/api/mcp` next to the other avatar tools).diff --git a/tasks/mcp-agent-selfsufficiency/03-register-agent-onchain.md b/tasks/mcp-agent-selfsufficiency/03-register-agent-onchain.mdnew file mode 100644index 000000000..e4dd2d941--- /dev/null+++ b/tasks/mcp-agent-selfsufficiency/03-register-agent-onchain.md@@ -0,0 +1,103 @@+# Task 03 — Register an agent on-chain (`register_agent` / `identity_check`)++**Pillar:** Network / on-chain digital identity. **Server:** main `/api/mcp`+(agent-centric tools) — confirm placement; `/api/mcp-agent` is acceptable if it+fits the wallet/identity grouping better.+**Read first:** [`README.md`](README.md) and `/CLAUDE.md`.++## Goal++This is the "bootstrap problem." On-chain identity exists (Metaplex Agent+Registry on Solana, ERC-8004 on EVM, Solana memo attestations), but MCP can only+**read** reputation/passport — an agent cannot **register** itself. After this+task, an agent connected over MCP can mint its on-chain identity and screen for+impersonation, closing the "every digital identity needs a network" pillar.++## What already exists (wire to this — do not rebuild)++- **Metaplex Agent Registry (Solana), server-custodial:** `api/_lib/agent-registry.js`+ - `registerAgentIdentity(...)` — registers a Core asset into the Metaplex Agent+ Registry and mints an Agent Identity PDA. **Custody is held by the collection+ authority (three.ws), not the end user** — so this path can run **server-side+ without the user signing a wallet transaction**. This is the path to expose+ over MCP (headless agents cannot pop a browser wallet).+ - Related: `api/_lib/onchain-deploy.js` mints the Core asset (deploy step,+ separate from registry enrollment). Read both to understand the two-step flow+ and whether `registerAgentIdentity` handles or requires a prior deploy.+- **ERC-8004 (EVM):** `src/erc8004/agent-registry.js` — requires the **user's+ browser wallet** (ethers `BrowserProvider`) + IPFS upload + `register()` on the+ Identity Registry contract. **Not headless-signable**, so do NOT try to drive+ it from MCP. Instead, for the EVM path, `register_agent` should return a+ **prepared, designed "continue in browser" payload** (the registration JSON ++ the deep link to the web register flow) — never fabricate a transaction or+ claim success.+- **Identity integrity:** `api/agents/identity-check.js` (POST) — Granite+ embedding + cosine comparison against public agents (impersonation detection) ++ Granite Guardian content screening → `clear | review | block` verdict. REST+ only today.+- **Existing read tools** (`api/_mcp/tools/solana.js`): `solana_agent_passport`,+ `solana_agent_reputation`, `solana_agent_attestations` — match their style.++Read `api/_lib/agent-registry.js`, `api/_lib/onchain-deploy.js`,+`api/agents/identity-check.js`, and `api/agents.js` (how an agent row maps to an+owner + any existing registration metadata column) before writing.++## Build++### `register_agent` (scope: `agents:write` / `identity:write`)++Register one of the caller's agents on-chain.++- Inputs: `agent_id` (required, uuid), `chain` (enum `solana|base`, default+ `solana`), `force` (bool optional — re-register if already registered).+- Behavior: - Ownership check (`agent_identities.user_id === auth.userId`); reject the+ x402-payer/null path with a designed "sign in" error. - If already registered (check the agent's registration metadata) and not+ `force`: return the existing identity (idempotent), do not double-mint. - **`chain: solana`** → call the server-custodial `registerAgentIdentity(...)`+ path (deploy Core asset first if required). Persist the resulting Agent+ Identity PDA / registration URI back onto the agent record. Return+ `{ status: 'registered', chain, agent_pda, registration_uri, explorer_url }`. - **`chain: base`** (EVM/ERC-8004) → build the registration JSON via the+ existing ERC-8004 helper and return `{ status: 'needs_wallet_signature',+chain, registration_json, continue_url }` pointing at the web register flow.+ This is a **designed state**, not an error — the EVM path genuinely needs the+ user's wallet; surface that honestly with everything pre-filled. - If Solana registry env/keys are unconfigured → designed "registration not+ configured on this deployment" error (never a fake PDA).++### `identity_check` (scope: `agents:read`)++Screen an agent (or a proposed name/description) for impersonation + policy.++- Inputs: `agent_id` (optional) OR (`name` + `description`), to match what+ `api/agents/identity-check.js` accepts.+- Behavior: call the same logic as the identity-check endpoint (extract a shared+ helper if it isn't importable — no duplicated Granite calls). Return+ `{ verdict: 'clear'|'review'|'block', similar_agents: [...], reasons: [...] }`.++## Requirements & edge cases++- **Never fabricate an on-chain result.** Every returned PDA / tx / URI must come+ from a real call. Unconfigured or wallet-required → designed states.+- **Idempotent** registration (guard against double-mint with `force` opt-in).+- Persist the registration result onto the agent record so the existing read+ tools (`solana_agent_passport`, etc.) reflect it immediately.+- Reuse `api/agents/identity-check.js` logic for `identity_check`; do not+ re-implement embeddings/Guardian.+- Register the new scope(s) and gate writes; reject `auth.userId === null`.+- `$THREE` only — if any registration metadata references a token, it is `$THREE`.++## Definition of Done++All items in [`README.md`](README.md) → "Definition of Done", plus:++- [ ] Catalog lists `register_agent`, `identity_check` (assembly check).+- [ ] `tests/api/mcp-register-agent.test.js`: ownership rejection, idempotent+ re-register without `force`, the `base` chain `needs_wallet_signature`+ designed payload, the unconfigured-Solana designed error, and an+ `identity_check` verdict path (mock the registry + Granite layers). Green.+- [ ] `server.json` (and `server-agent.json` if placed there) description updated.+- [ ] Manually verified: `register_agent(chain:solana)` against a dev/devnet+ config returns a real PDA + explorer URL, and a second call is idempotent.++## Out of scope++- Driving the EVM wallet signature headlessly (return the prepared payload only).+- New on-chain contracts. SNS domain attachment (a separate, smaller follow-up).diff --git a/tasks/mcp-agent-selfsufficiency/04-embed-code-tool.md b/tasks/mcp-agent-selfsufficiency/04-embed-code-tool.mdnew file mode 100644index 000000000..055a2bf27--- /dev/null+++ b/tasks/mcp-agent-selfsufficiency/04-embed-code-tool.md@@ -0,0 +1,98 @@+# Task 04 — Embed code tool (`get_embed_code`)++**Pillar:** Embed ("as easy as a YouTube video"). **Server:** main `/api/mcp`.+**Read first:** [`README.md`](README.md) and `/CLAUDE.md`.++## Goal++The post's promise is "embed a persistent, on-chain 3D avatar into any platform+as easy as embedding a YouTube video." The embed **infrastructure** is mature+(oEmbed, iframe pages, Open Graph, model-viewer), but there is no MCP tool that+hands an agent a **copy-paste embed snippet / shareable URL**. After this task,+an agent can call one tool and get exactly the HTML to paste into Notion,+Webflow, Framer, a blog, etc.++## What already exists (wire to this — do not rebuild)++- **oEmbed (agents):** `api/agent-oembed.js` —+ `GET /api/oembed?url=<agent-url>` returns oEmbed JSON (`type: rich`) with an+ `html` field containing the `<iframe>` to the embed page, plus width/height.+ Supports JSON + XML, sandbox attributes, camera controls. Handles both+ on-chain agents (`/a/:chainId/:agentId`) and regular agents (`/agent/:id`).+- **oEmbed (forge creations):** `api/play-oembed.js` — same, for Forge 3D+ creations (`/forge?share=:id` / play URLs).+- **Embed pages:** `/agent/:id/embed`, `/a/:chainId/:agentId/embed` (the iframe+ targets), and the Forge share view.+- **Open Graph images:** `api/agent/:id/og`, `api/a-og`, `api/forge-og` (social+ cards) — useful as a `thumbnail_url` in the response.++Read `api/agent-oembed.js` and `api/play-oembed.js` fully; reuse their+URL-resolution + HTML-building logic. The site origin resolution pattern is in+`api/_mcp/tools/animations.js` (`resolveOrigin(req)`) — `req` is available to the+handler.++## Build++### `get_embed_code` (scope: `avatars:read` — read-only)++Return ready-to-paste embed artifacts for an agent or a Forge creation.++- Inputs (one of):+ - `agent_id` (uuid) — embed a regular agent, OR+ - `chain_id` + `onchain_agent_id` — embed an on-chain agent, OR+ - `creation_id` — embed a Forge 3D creation.+ - Plus options: `width` (int, default 480), `height` (int, default 360),+ `autorotate` (bool, default true), `ar` (bool, default true).+- Behavior:+ - Resolve the canonical public URL for the target (reuse the oEmbed resolver).+ If the target requires ownership/visibility (a private avatar), verify the+ caller may share it (reuse `get_avatar`'s visibility check); otherwise return+ a designed "make it public/unlisted first" error.+ - Build the embed `<iframe>` HTML via the **same logic** the oEmbed endpoint+ uses (extract a shared helper if not importable — no duplicated HTML+ string-building).+ - Return:+ ```json+ {+ "embed_html": "<iframe src=\"https://three.ws/agent/<id>/embed\" ...></iframe>",+ "share_url": "https://three.ws/agent/<id>",+ "oembed_url": "https://three.ws/api/oembed?url=...",+ "thumbnail_url": "https://three.ws/api/agent/<id>/og",+ "width": 480,+ "height": 360+ }+ ```+ - Also return a `content` text block with the raw snippet so a chat client+ shows it as copyable text, **and** (optional, nice) a `type: resource`+ `text/html` artifact so MCP clients that render HTML show a live preview+ (mirror how `preview_3d` returns a model-viewer resource).++## Requirements & edge cases++- **No duplicated embed/oEmbed logic.** Extract a shared builder if needed; both+ the existing endpoint and this tool call it.+- Exactly one of `agent_id` / (`chain_id`+`onchain_agent_id`) / `creation_id`+ must be provided — validate and return a clear error otherwise.+- Private/unlisted handling: don't leak a private agent's embed to a+ non-owner. Owner may embed their own private item; others only public/unlisted.+- Width/height bounds sane (e.g. 240–1920 / 180–1080); clamp, don't error.+- Origin must be the real site origin (`resolveOrigin(req)` / `APP_ORIGIN`), never+ hardcoded `localhost`.++## Definition of Done++All items in [`README.md`](README.md) → "Definition of Done", plus:++- [ ] `/api/mcp` catalog lists `get_embed_code` (assembly check).+- [ ] `tests/api/mcp-embed.test.js`: agent embed, on-chain agent embed, forge+ creation embed, the "exactly one target" validation, and a private-not-owner+ rejection. The returned `embed_html` contains the correct `/embed` URL and+ respects width/height. Green.+- [ ] `server.json` description mentions embeddable output.+- [ ] Manually verified: paste the returned `embed_html` into a blank HTML file+ and the avatar renders.++## Out of scope++- Platform-specific shortcodes (WordPress/Discord) — the oEmbed + iframe is the+ universal answer. Building new embed pages (they exist).diff --git a/tasks/mcp-agent-selfsufficiency/05-wallet-provision-and-monetize.md b/tasks/mcp-agent-selfsufficiency/05-wallet-provision-and-monetize.mdnew file mode 100644index 000000000..44b48ebe3--- /dev/null+++ b/tasks/mcp-agent-selfsufficiency/05-wallet-provision-and-monetize.md@@ -0,0 +1,105 @@+# Task 05 — Provision & monetize a wallet (`provision_wallet` / `monetize_endpoint`)++**Pillar:** Wallet (jobs with x402). **Server:** agent wallet `/api/mcp-agent`.+**Read first:** [`README.md`](README.md) and `/CLAUDE.md`.++## Goal++The wallet pillar is currently **consumption-only** over MCP: an agent can check+status (`wallet_status`) and spend (`pay_and_call`), but it cannot **create/fund**+a wallet or **earn** — both require the web app. This task makes the wallet+two-sided: an agent can provision its own wallet and expose a paid x402 endpoint+to earn USDC, completing "a wallet (jobs with x402)."++## What already exists (wire to this — do not rebuild)++- **Agent wallet MCP tools** (`api/_mcpagent/tools.js`): `wallet_status`,+ `find_services`, `pay_and_call`. Match their style, auth, and spend-cap logic.+- **Solana wallet management (REST):** `api/agents/solana-wallet.js` —+ list address, check balance, **provision a wallet**, plus+ `api/agents/.../solana/activity` (recent signatures) and+ `api/agents/.../solana/airdrop` (devnet 1 SOL). Find the provisioning function+ (search `provision`, `getOrCreate`, `agent_wallets`/`solana_address`).+- **Wallet internals:** `api/_lib/agent-wallet.js` (provisioning/custody),+ `api/_lib/x402-user-payer.js` (the payer side). Read these to understand how a+ wallet is created and custodied per agent.+- **Monetization / earn:** there is an existing monetize path — the+ `monetize-service` skill and `api/_lib/x402-paid-endpoint.js` (paid-endpoint+ wrapper), plus the bazaar discovery (`api/mcp-bazaar.js`) where a service gets+ listed. Read `api/_lib/x402-paid-endpoint.js` and the monetize skill/flow, and+ any `agent_services` / paid-endpoint registry table, to see how an agent+ publishes a priced endpoint that others can `pay_and_call`.++Read `api/agents/solana-wallet.js`, `api/_lib/agent-wallet.js`, and the+monetize/paid-endpoint code fully before writing.++## Build++### `provision_wallet` (scope: `wallet:write`)++Create (or return the existing) custodial wallet for one of the caller's agents.++- Inputs: `agent_id` (required, uuid), `cluster` (enum `mainnet|devnet`, default+ `mainnet`), `airdrop` (bool, default false — devnet only).+- Behavior:+ - Ownership check (`agent_identities.user_id === auth.userId`); reject the null+ x402 path with a designed "sign in" error.+ - Idempotent: if the agent already has a wallet, return it (do not re-create).+ - Provision via the existing `api/agents/solana-wallet.js` / `agent-wallet.js`+ path. If `cluster:devnet` and `airdrop:true`, trigger the existing devnet+ airdrop. **Never** airdrop or fabricate balances on mainnet.+ - Return `{ agent_id, address, cluster, sol_balance, usdc_balance, created }`.++### `monetize_endpoint` (scope: `wallet:write` / `services:write`)++Publish a priced x402 endpoint so other agents can pay this agent to use it.++- Inputs: `agent_id` (required), `name` (required), `description` (required),+ `price_usdc` (required, number > 0), `target_url` (required, the upstream the+ agent already serves), `method` (enum GET|POST, default POST), `input_schema`+ (optional JSON Schema object), `network` (enum `base|solana`, default per the+ existing default).+- Behavior:+ - Ownership check. Validate `target_url` (public https, SSRF-guard).+ - Register the priced endpoint via the existing paid-endpoint / monetize+ mechanism (`api/_lib/x402-paid-endpoint.js` + whatever registry the+ `monetize-service` skill writes to) so it becomes discoverable by+ `find_services` / the bazaar and callable by `pay_and_call`.+ - Return `{ service_id, resource_url, price_usdc, network, bazaar_listed }`.+ - If the wallet/monetize prerequisites aren't met (no provisioned wallet, no+ payout address), return a designed error telling the caller to+ `provision_wallet` first — do not half-create a listing.++## Requirements & edge cases++- **Idempotency** on `provision_wallet`; **no mainnet airdrops/fabricated funds.**+- Ownership + scope on both tools; reject `auth.userId === null`.+- `monetize_endpoint` must produce a **real, discoverable** listing that+ `find_services`/bazaar surface and `pay_and_call` can hit — verify the loop+ closes (list → discover → pay). If the existing monetize flow needs a payout+ wallet, enforce that prerequisite (link to `provision_wallet`).+- Reuse spend-cap / rate-limit conventions from `api/_mcpagent/tools.js`.+- `$THREE` is the only coin; prices are in **USDC** (the x402 settlement asset) —+ do not introduce any other token.+- Register `wallet:write` (and `services:write` if used) scopes.++## Definition of Done++All items in [`README.md`](README.md) → "Definition of Done", plus:++- [ ] `/api/mcp-agent` catalog lists `provision_wallet`, `monetize_endpoint`+ (assembly check).+- [ ] `tests/api/mcp-wallet-provision.test.js`: provision happy-path + idempotent+ second call, ownership/null rejection, mainnet-airdrop refusal, a+ `monetize_endpoint` listing happy-path (mock the registry + wallet layers),+ SSRF rejection of a non-public `target_url`, and the "no wallet → provision+ first" designed error. Green.+- [ ] `server-agent.json` description updated to reflect provisioning + earning.+- [ ] Manually verified on **devnet**: `provision_wallet` → `monetize_endpoint`+ → the listing appears via `find_services` / bazaar `search_services`.++## Out of scope++- Token launch (pump.fun coin launch stays REST-only for now).+- Cross-chain bridging. Changing the custody model. Fiat on-ramp (the `fund`+ skill covers that).diff --git a/tasks/mcp-agent-selfsufficiency/README.md b/tasks/mcp-agent-selfsufficiency/README.mdnew file mode 100644index 000000000..0c037039b--- /dev/null+++ b/tasks/mcp-agent-selfsufficiency/README.md@@ -0,0 +1,160 @@+# Initiative: make the agent self-sufficient over MCP++**Goal.** Today the three.ws platform exposes the **read/consume** half of every+capability over MCP, but the **create/write** half still requires the web app.+An AI agent connected through MCP (Claude, Cursor, watsonx Orchestrate) can+_observe and spend_, but it cannot bootstrap itself end-to-end. This initiative+closes that gap so an agent can give itself a **body, brain (memory), wallet,+on-chain identity, and an embed** — entirely through MCP, matching the public+IBM-partnership narrative: _"Every AI needs a body, a brain (LLM memory), a+wallet (jobs with x402), and every digital identity needs a network."_++Each task below is a **self-contained brief** meant to be run in its own fresh+chat. They are independent and can be done in any order, but the recommended+sequence (each unlocks the next in the agent lifecycle) is 01 → 02 → 03 → 04 → 05.++| # | Task | Pillar | New MCP tools |+| --- | ------------------------------------------------------------------ | ------------------ | --------------------------------------- |+| 01 | [Memory tools](01-memory-mcp-tools.md) | Brain (LLM memory) | `remember`, `recall`, `forget` |+| 02 | [Persist & render avatar](02-avatar-persist-and-render.md) | Body | `save_avatar`, `render_avatar_image` |+| 03 | [Register agent on-chain](03-register-agent-onchain.md) | Network / identity | `register_agent`, `identity_check` |+| 04 | [Embed code tool](04-embed-code-tool.md) | Embed | `get_embed_code` |+| 05 | [Provision & monetize wallet](05-wallet-provision-and-monetize.md) | Wallet | `provision_wallet`, `monetize_endpoint` |++---++## Shared conventions (read before any task)++These apply to every task. Each task brief restates the critical bits, but this+is the canonical reference.++### Project rules (non-negotiable — see `/CLAUDE.md`)++- **No mocks, no fake data, no placeholders, no TODOs, no stubs.** Wire to the+ real endpoints/DB/contracts that already exist. If a credential is missing,+ surface a clean, designed "not configured" state — never fabricate output.+- **`$THREE` is the only coin.** Contract `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.+ Never reference any other token anywhere (code, tests, fixtures, docs).+- **Errors handled at boundaries** (network, user input); internal code trusts+ itself. Every state designed (loading/empty/error/success).+- Match existing naming, file organization, and abstractions. Read before you+ write. Delete dead code. Keep the repo root clean.++### The MCP tool authoring contract++A tool is a plain object in a `toolDefs` array exported from a file under+`api/_mcp*/tools/`:++```js+{+ name: 'tool_name', // snake_case, unique within the server+ title: 'Human title',+ description: 'What it does + when to use it (LLMs read this to choose it).',+ scope: 'namespace:action', // OPTIONAL — gate behind an OAuth scope (see below)+ inputSchema: { // JSON Schema; additionalProperties:false+ type: 'object',+ properties: { /* ... */ },+ required: [ /* ... */ ],+ additionalProperties: false,+ },+ async handler(args, auth, req) {+ // args — validated input (ajv compiled the schema at catalog load)+ // auth — { userId, scope, apiKeyId, clientId, rateKey } (userId is the+ // authenticated three.ws user id; null on the x402-payer path)+ // req — the raw Node request (headers, etc.). Threaded by BOTH dispatchers.+ // Return an MCP tool result:+ return {+ content: [{ type: 'text', text: '...human-readable...' }],+ structuredContent: { /* machine-readable result */ },+ // isError: true // on a handled failure+ };+ },+}+```++Wiring a new tool file into a server:++1. Create `api/_mcp<server>/tools/<name>.js` exporting `toolDefs`.+2. Import it in that server's `catalog.js` and add to the `allDefs` array.+3. The shared `catalog.js` strips `scope`/`handler` for `tools/list` and+ ajv-compiles each `inputSchema` — a malformed schema throws at load, so the+ assembly check below is a real test.+4. If the tool should appear in the server's `initialize` instructions, update+ the `INSTRUCTIONS` string in that server's `dispatch.js`.++**Servers and their dispatchers** (both pass `(args, auth, req)` to handlers):++| Server | Endpoint | Dispatcher | tools dir | catalog |+| ------------ | ----------------- | ---------------------------- | ------------------- | ------------------------ |+| main | `/api/mcp` | `api/_mcp/dispatch.js` (own) | `api/_mcp/tools/` | `api/_mcp/catalog.js` |+| 3D Studio | `/api/mcp-3d` | shared `makeDispatcher` | `api/_mcp3d/tools/` | `api/_mcp3d/catalog.js` |+| agent wallet | `/api/mcp-agent` | shared `makeDispatcher` | `api/_mcpagent/` | `api/_mcpagent/...` |+| bazaar | `/api/mcp-bazaar` | shared `makeDispatcher` | `api/_mcpbazaar/` | — |+| IBM Granite | `/api/ibm-mcp` | shared (`_mcpibm`) | `api/_mcpibm/` | `api/_mcpibm/catalog.js` |++Each server has a registry manifest at the repo root: `server.json` (main),+`server-3d.json`, `server-agent.json`, `server-bazaar.json`, `server-ibm.json`.+Update the relevant manifest `description` if a task materially changes a+server's capability surface.++### Auth, ownership, and scopes++- `auth.userId` is the authenticated three.ws user. **Any write tool MUST verify+ ownership** before mutating: an agent record lives in the `agent_identities`+ table with a `user_id` column — confirm `agent_identities.user_id === auth.userId`+ (the existing REST endpoints do exactly this; reuse their query/helper).+- Gate write tools behind a scope via the `scope:` field (e.g.+ `memory:write`, `avatars:write`). Read tools that only return the caller's own+ data use a read scope (e.g. `memory:read`). Look at `delete_avatar` in+ `api/_mcp/tools/avatars.js` (`scope: 'avatars:delete'`) and `api/_mcp/auth.js` /+ `api/_lib/auth.js` for how scopes are defined and checked, and register any+ new scope in the OAuth scope list so it can actually be granted.+- The x402-payer path has `auth.userId === null`. Write tools that need an owner+ must return a clear "sign in with three.ws OAuth to use this tool" error in+ that case rather than throwing.++### Definition of Done (every task)++A task is complete only when ALL of these hold — state explicitly which you+verified:++- [ ] New tool file(s) created and wired into the server's `catalog.js`.+- [ ] `server-*.json` description and the server's `dispatch.js` `INSTRUCTIONS`+ updated if the capability surface changed.+- [ ] **Real wiring** to the existing endpoint/DB/contract — no mock, no stub,+ no fabricated data. Missing-credential path returns a designed error.+- [ ] Ownership + scope enforced on every write tool; x402-payer (`userId:null`)+ handled.+- [ ] `node --check` passes on every changed `.js` file.+- [ ] **Catalog assembles** — the assembly command below ajv-compiles every+ schema and proves the handlers resolve; it must list your new tool names.+- [ ] A vitest spec is added under `tests/api/` covering the new tools+ (schema/validation + a happy path with the DB/HTTP layer mocked at the+ module boundary, mirroring `tests/api/mcp-3d.test.js`) and passes.+- [ ] `npx prettier --write` then `--check` clean on all changed files.+- [ ] `git diff` self-reviewed; every changed line justified.++### Verification commands cheat-sheet++```bash+# Syntax-check a changed tool file:+node --check api/_mcp<server>/tools/<name>.js++# Catalog assembles (ajv-compiles every schema, resolves every handler):+node --input-type=module -e "import('./api/_mcp<server>/catalog.js').then(m=>{for(const t of m.TOOL_CATALOG)if(!t.name||!t.description||!t.inputSchema)throw new Error('bad entry '+t.name);console.log('tools:',m.TOOL_CATALOG.length,m.TOOL_CATALOG.map(t=>t.name).join(', '));})"++# Run your spec + formatting:+npx vitest run tests/api/<spec>.test.js+npx prettier --check <files>++# Inspect live locally:+npm run dev+npx @modelcontextprotocol/inspector http://localhost:5173/api/<endpoint>+```++### Note for whoever runs these++This repo is worked by a **concurrent agent fleet sharing one worktree on+`main`** — files and commits can shift mid-task. Stage explicit paths, re-check+`git status` before committing, and never `git pull`/`fetch` from the `threeD`+mirror (canonical remote is `threews`). Do not push without explicit approval.diff --git a/tests/pump-go.test.js b/tests/pump-go.test.jsnew file mode 100644index 000000000..ebadb0f65--- /dev/null+++ b/tests/pump-go.test.js@@ -0,0 +1,146 @@+// Unit tests for the pump.fun GO client's pure normalizers.+//+// The upstream Task shape is verbose and reward amounts arrive as atomic strings+// across multiple legs; the UI relies on normalizeTask flattening that correctly+// (USD joined by mint, SOL leg detected, atomic→human, the on-chain bridge kept).+// Fixture mirrors a real livestream-api.pump.fun/bounties/tasks item.++import { describe, it, expect } from 'vitest';+import { normalizeTask, normalizeSubmission, WSOL_MINT } from '../api/_lib/pump-go.js';++const TASK = {+ taskId: 'b4a26396-75a7-4bce-a3b5-e3c99aaa73c1',+ creatorAddress: 'Epb1111111111111111111111111111111111111111',+ creatorXFollowerCount: 1200,+ creatorXVerified: true,+ title: 'Tweet about $three',+ bodyMarkdown: 'Make a thread.',+ submissionVisibility: 'PUBLIC',+ status: 'PENDING_RESOLUTION',+ createdAt: '2026-06-07T21:12:25.592Z',+ publishedAt: '2026-06-07T21:13:00.000Z',+ fundedAt: '2026-06-07T21:14:00.000Z',+ expiresAt: '2026-06-14T21:12:25.592Z',+ counts: { disputeCount: 1, submissionCount: 4 },+ likeCount: 9,+ criteria: [+ { id: 'c1', text: 'Image attached', required: true, order: 0 },+ { id: 'c2', text: 'Tag the project', required: false, order: 1 },+ ],+ pumpBountiesProgramId: 'goGzNYTYkSEe4hUqz6dPmY5uf3CTt36AQAoujXDrKiV',+ onChainBountyId: '7027385768702475239',+ chainConfigSnapshot: { publishFeeLamports: '10000000', disputeWindowSeconds: '28800' },+ rewardLegs: [+ {+ mintAddress: WSOL_MINT,+ tokenProgramId: 'Tokenkeg...',+ amountAtomic: '500000000',+ remainingAmountAtomic: '250000000',+ decimalsSnapshot: 9,+ rewardVaultAddress: 'H8Rt1111111111111111111111111111111111111111',+ },+ ],+ rewardLegsUsd: [{ mintAddress: WSOL_MINT, priceUsd: 64.7, priced: true, usdValue: 32.35 }],+ rewardTotalUsd: 32.35,+ rewardPricedAt: '2026-06-07T21:20:00.000Z',+ attachments: [+ {+ filename: 'banner.png',+ kind: 'image',+ contentType: 'image/webp',+ size: 108448,+ url: 'https://s3/x.png',+ },+ ],+ coinAddress: '6oEoK1111111111111111111111111111111111111',+};++describe('normalizeTask', () => {+ const n = normalizeTask(TASK);++ it('flattens core fields', () => {+ expect(n.taskId).toBe(TASK.taskId);+ expect(n.title).toBe('Tweet about $three');+ expect(n.status).toBe('PENDING_RESOLUTION');+ expect(n.counts).toEqual({ submissions: 4, disputes: 1 });+ expect(n.likeCount).toBe(9);+ expect(n.criteria).toHaveLength(2);+ expect(n.criteria[0]).toEqual({+ id: 'c1',+ text: 'Image attached',+ required: true,+ order: 0,+ });+ });++ it('detects the SOL leg and converts atomics to human amounts', () => {+ expect(n.reward.totalUsd).toBe(32.35);+ expect(n.reward.sol).toBe(0.5); // 500000000 / 1e9+ const leg = n.reward.legs[0];+ expect(leg.isSol).toBe(true);+ expect(leg.amount).toBe(0.5);+ expect(leg.remaining).toBe(0.25);+ expect(leg.usd).toBe(32.35); // joined from rewardLegsUsd by mint+ expect(leg.vault).toBe('H8Rt1111111111111111111111111111111111111111');+ });++ it('keeps the on-chain bridge + creator + attachments', () => {+ expect(n.onChain.programId).toBe('goGzNYTYkSEe4hUqz6dPmY5uf3CTt36AQAoujXDrKiV');+ expect(n.onChain.bountyId).toBe('7027385768702475239');+ expect(n.creator).toEqual({+ address: TASK.creatorAddress,+ xFollowers: 1200,+ xVerified: true,+ });+ expect(n.attachments[0].url).toBe('https://s3/x.png');+ });++ it('leaves reward.sol null when no leg is wSOL', () => {+ const tokenOnly = normalizeTask({+ ...TASK,+ rewardLegs: [+ { mintAddress: 'TokenMint1111', amountAtomic: '1000000', decimalsSnapshot: 6 },+ ],+ rewardLegsUsd: [],+ });+ expect(tokenOnly.reward.sol).toBeNull();+ expect(tokenOnly.reward.legs[0].amount).toBe(1); // 1e6 / 1e6+ expect(tokenOnly.reward.legs[0].usd).toBeNull();+ });++ it('returns null for garbage input', () => {+ expect(normalizeTask(null)).toBeNull();+ expect(normalizeTask('nope')).toBeNull();+ });+});++describe('normalizeSubmission', () => {+ it('flattens a submission', () => {+ const s = normalizeSubmission({+ submissionId: 's1',+ taskId: 't1',+ bodyMarkdown: 'Done it.',+ requesterAddress: 'GXrz11mhPwVNEfERQC7Set4vwKWfGDJotVj9W9F5Y7XV',+ likeCount: 3,+ createdAt: '2026-06-08T07:08:31.689Z',+ attachments: [+ {+ filename: 'p.png',+ kind: 'image',+ contentType: 'image/png',+ size: 1,+ url: 'https://s3/p',+ },+ ],+ });+ expect(s.submissionId).toBe('s1');+ expect(s.body).toBe('Done it.');+ expect(s.requester).toBe('GXrz11mhPwVNEfERQC7Set4vwKWfGDJotVj9W9F5Y7XV');+ expect(s.likeCount).toBe(3);+ expect(s.attachments[0].url).toBe('https://s3/p');+ });++ it('returns null for garbage', () => {+ expect(normalizeSubmission(undefined)).toBeNull();+ });+});diff --git a/vercel.json b/vercel.jsonindex e6a9952c5..763fde4b5 100644--- a/vercel.json+++ b/vercel.json@@ -455,6 +455,14 @@"src": "/go/?","dest": "/go.html"},+ {+ "src": "/bounties/?",+ "dest": "/bounties.html"+ },+ {+ "src": "/bounty/([^/]+)/?",+ "dest": "/bounty.html"+ },{"src": "/pump-live/?","dest": "/pump-live.html"diff --git a/vite.config.js b/vite.config.jsindex fa211f540..379f1b72e 100644--- a/vite.config.js+++ b/vite.config.js@@ -1,6 +1,14 @@import { defineConfig } from 'vite';import { resolve } from 'path';-import { readFileSync, readdirSync, cpSync, createReadStream, existsSync, statSync, rmSync } from 'fs';+import {+ readFileSync,+ readdirSync,+ cpSync,+ createReadStream,+ existsSync,+ statSync,+ rmSync,+} from 'fs';import { extname, basename } from 'path';import { VitePWA } from 'vite-plugin-pwa';import { nodePolyfills } from 'vite-plugin-node-polyfills';@@ -54,10 +62,10 @@ function discoverDashboardNextInputs() {const CODESPACE_HMR =process.env.CODESPACE_NAME && process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN? {- host: `${process.env.CODESPACE_NAME}-3000.${process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN}`,- protocol: 'wss',- clientPort: 443,- }+ host: `${process.env.CODESPACE_NAME}-3000.${process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN}`,+ protocol: 'wss',+ clientPort: 443,+ }: undefined;const appConfig = {@@ -97,23 +105,25 @@ const appConfig = {},...(X402_PAY_DEV_URL? {- '/api/x402-pay': {- target: X402_PAY_DEV_URL,- changeOrigin: true,- secure: false,- configure: (proxy) => {- proxy.on('error', (err, _req, res) => {- if (!res || res.headersSent || res.writableEnded) return;- res.statusCode = 502;- res.setHeader('content-type', 'application/json');- res.end(JSON.stringify({- error: 'bad_gateway',- message: `x402-pay dev helper unreachable at ${X402_PAY_DEV_URL}: ${err.message}`,- }));- });+ '/api/x402-pay': {+ target: X402_PAY_DEV_URL,+ changeOrigin: true,+ secure: false,+ configure: (proxy) => {+ proxy.on('error', (err, _req, res) => {+ if (!res || res.headersSent || res.writableEnded) return;+ res.statusCode = 502;+ res.setHeader('content-type', 'application/json');+ res.end(+ JSON.stringify({+ error: 'bad_gateway',+ message: `x402-pay dev helper unreachable at ${X402_PAY_DEV_URL}: ${err.message}`,+ }),+ );+ });+ },},- },- }+ }: {}),'/api': {target: DEV_API_PROXY,@@ -146,10 +156,12 @@ const appConfig = {}res.statusCode = 502;res.setHeader('content-type', 'application/json');- res.end(JSON.stringify({- error: 'bad_gateway',- message: `api proxy → ${DEV_API_PROXY} failed: ${err.message}`,- }));+ res.end(+ JSON.stringify({+ error: 'bad_gateway',+ message: `api proxy → ${DEV_API_PROXY} failed: ${err.message}`,+ }),+ );});},},@@ -200,29 +212,42 @@ const appConfig = {// large bundles (Three.js, ethers) without affecting the output.reportCompressedSize: false,rollupOptions: {- external: ['/studio/launch-panel.js', '/studio/fees-panel.js', './fees-panel.js', '/crypto-optional.js', /^@pump-fun\/agent-payments-sdk(\/.*)?$/],+ external: [+ '/studio/launch-panel.js',+ '/studio/fees-panel.js',+ './fees-panel.js',+ '/crypto-optional.js',+ /^@pump-fun\/agent-payments-sdk(\/.*)?$/,+ ],output: {manualChunks(id) {if (id.includes('node_modules/three/')) {- if (id.includes('three/examples/') || id.includes('three/addons/')) return 'three-addons';+ if (id.includes('three/examples/') || id.includes('three/addons/'))+ return 'three-addons';return 'three-core';}if (id.includes('node_modules/ethers/')) return 'ethers';- if (id.includes('node_modules/@solana/') || id.includes('node_modules/@coral-xyz/')) return 'solana';+ if (+ id.includes('node_modules/@solana/') ||+ id.includes('node_modules/@coral-xyz/')+ )+ return 'solana';if (id.includes('node_modules/@mediapipe/')) return 'mediapipe';},// A few entries need stable, unhashed filenames so plain public/// scripts can load them by a predictable URL without knowing the// build hash: footer.js → /footer-bot.js, nav.js → /walk-companion.js.entryFileNames: (chunk) =>- chunk.name === 'footer-bot' || chunk.name === 'walk-companion' || chunk.name === 'notifications'+ chunk.name === 'footer-bot' ||+ chunk.name === 'walk-companion' ||+ chunk.name === 'notifications'? `${chunk.name}.js`: 'assets/[name]-[hash].js',},input: {'footer-bot': resolve(__dirname, 'src/footer-bot.js'),'walk-companion': resolve(__dirname, 'src/walk-companion.js'),- 'notifications': resolve(__dirname, 'src/notifications.js'),+ notifications: resolve(__dirname, 'src/notifications.js'),app: resolve(__dirname, 'pages/app.html'),'app-demo': resolve(__dirname, 'pages/app-demo.html'),'app-next': resolve(__dirname, 'pages/app-next.html'),@@ -248,7 +273,7 @@ const appConfig = {widget: resolve(__dirname, 'pages/widget.html'),launchpad: resolve(__dirname, 'pages/launchpad.html'),start: resolve(__dirname, 'pages/start.html'),- create: resolve(__dirname, 'pages/create.html'),+ create: resolve(__dirname, 'pages/create.html'),'create-agent': resolve(__dirname, 'pages/create-agent.html'),forge: resolve(__dirname, 'pages/forge.html'),segment: resolve(__dirname, 'pages/segment.html'),@@ -262,18 +287,18 @@ const appConfig = {'import-rpm': resolve(__dirname, 'pages/import-rpm.html'),marketplace: resolve(__dirname, 'pages/marketplace.html'),'agent-edit': resolve(__dirname, 'pages/agent-edit.html'),- 'avatar-edit': resolve(__dirname, 'pages/avatar-edit.html'),- 'create-video': resolve(__dirname, 'pages/create/video.html'),- 'extension-privacy': resolve(__dirname, 'pages/extension-privacy.html'),- 'extension-terms': resolve(__dirname, 'pages/extension-terms.html'),- 'embed-walk': resolve(__dirname, 'pages/embed-walk.html'),+ 'avatar-edit': resolve(__dirname, 'pages/avatar-edit.html'),+ 'create-video': resolve(__dirname, 'pages/create/video.html'),+ 'extension-privacy': resolve(__dirname, 'pages/extension-privacy.html'),+ 'extension-terms': resolve(__dirname, 'pages/extension-terms.html'),+ 'embed-walk': resolve(__dirname, 'pages/embed-walk.html'),'agent-embed': resolve(__dirname, 'pages/agent-embed.html'),'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),'avatar-wallet-chat': resolve(__dirname, 'pages/avatar-wallet-chat.html'),- 'agent-exchange': resolve(__dirname, 'pages/agent-exchange.html'),+ 'agent-exchange': resolve(__dirname, 'pages/agent-exchange.html'),'demo-economy': resolve(__dirname, 'pages/demo-economy.html'),- 'live': resolve(__dirname, 'pages/live.html'),+ live: resolve(__dirname, 'pages/live.html'),'agent-economy': resolve(__dirname, 'pages/agent-economy.html'),'overlay-control': resolve(__dirname, 'pages/overlay-control.html'),'mocap-studio': resolve(__dirname, 'pages/mocap-studio.html'),@@ -286,6 +311,8 @@ const appConfig = {unstoppable: resolve(__dirname, 'pages/unstoppable.html'),shopper: resolve(__dirname, 'pages/shopper.html'),go: resolve(__dirname, 'pages/go.html'),+ bounties: resolve(__dirname, 'pages/bounties.html'),+ bounty: resolve(__dirname, 'pages/bounty.html'),'pump-live': resolve(__dirname, 'pages/pump-live.html'),'bulk-launch': resolve(__dirname, 'pages/bulk-launch.html'),'pump-dashboard': resolve(__dirname, 'pages/pump-dashboard.html'),@@ -303,7 +330,7 @@ const appConfig = {brain: resolve(__dirname, 'pages/brain.html'),voice: resolve(__dirname, 'pages/voice.html'),galaxy: resolve(__dirname, 'pages/galaxy.html'),- 'ar-page': resolve(__dirname, 'pages/ar.html'),+ 'ar-page': resolve(__dirname, 'pages/ar.html'),creating: resolve(__dirname, 'pages/creating.html'),pricing: resolve(__dirname, 'pages/pricing.html'),'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),@@ -360,35 +387,50 @@ const appConfig = {'demos-3d-home': resolve(__dirname, 'public/demos/3d-home.html'),'demos-halfbody-xr': resolve(__dirname, 'public/demos/halfbody-xr.html'),// /demos/agents/* — agent interaction lab.- 'agents-index': resolve(__dirname, 'public/demos/agents/index.html'),- 'agents-cursor-follower': resolve(__dirname, 'public/demos/agents/cursor-follower.html'),- 'agents-high-five': resolve(__dirname, 'public/demos/agents/high-five.html'),- 'agents-pickup-drop': resolve(__dirname, 'public/demos/agents/pickup-drop.html'),- 'agents-fall-from-top': resolve(__dirname, 'public/demos/agents/fall-from-top.html'),- 'agents-trampoline': resolve(__dirname, 'public/demos/agents/trampoline.html'),- 'agents-wrecking-ball': resolve(__dirname, 'public/demos/agents/wrecking-ball.html'),- 'agents-climb-title': resolve(__dirname, 'public/demos/agents/climb-title.html'),- 'agents-skateboard': resolve(__dirname, 'public/demos/agents/skateboard.html'),- 'agents-sit-in-body': resolve(__dirname, 'public/demos/agents/sit-in-body.html'),- 'agents-scroll-inertia': resolve(__dirname, 'public/demos/agents/scroll-inertia.html'),- 'agents-walks-gutter': resolve(__dirname, 'public/demos/agents/walks-gutter.html'),- 'agents-holds-cta': resolve(__dirname, 'public/demos/agents/holds-cta.html'),- 'agents-falls-asleep': resolve(__dirname, 'public/demos/agents/falls-asleep.html'),- 'agents-builds-button': resolve(__dirname, 'public/demos/agents/builds-button.html'),- 'agents-face-mocap': resolve(__dirname, 'public/demos/agents/face-mocap.html'),- 'agents-gemini-live': resolve(__dirname, 'public/demos/agents/gemini-live.html'),- 'agents-auto-rig': resolve(__dirname, 'public/demos/agents/auto-rig.html'),+ 'agents-index': resolve(__dirname, 'public/demos/agents/index.html'),+ 'agents-cursor-follower': resolve(+ __dirname,+ 'public/demos/agents/cursor-follower.html',+ ),+ 'agents-high-five': resolve(__dirname, 'public/demos/agents/high-five.html'),+ 'agents-pickup-drop': resolve(__dirname, 'public/demos/agents/pickup-drop.html'),+ 'agents-fall-from-top': resolve(+ __dirname,+ 'public/demos/agents/fall-from-top.html',+ ),+ 'agents-trampoline': resolve(__dirname, 'public/demos/agents/trampoline.html'),+ 'agents-wrecking-ball': resolve(+ __dirname,+ 'public/demos/agents/wrecking-ball.html',+ ),+ 'agents-climb-title': resolve(__dirname, 'public/demos/agents/climb-title.html'),+ 'agents-skateboard': resolve(__dirname, 'public/demos/agents/skateboard.html'),+ 'agents-sit-in-body': resolve(__dirname, 'public/demos/agents/sit-in-body.html'),+ 'agents-scroll-inertia': resolve(+ __dirname,+ 'public/demos/agents/scroll-inertia.html',+ ),+ 'agents-walks-gutter': resolve(__dirname, 'public/demos/agents/walks-gutter.html'),+ 'agents-holds-cta': resolve(__dirname, 'public/demos/agents/holds-cta.html'),+ 'agents-falls-asleep': resolve(__dirname, 'public/demos/agents/falls-asleep.html'),+ 'agents-builds-button': resolve(+ __dirname,+ 'public/demos/agents/builds-button.html',+ ),+ 'agents-face-mocap': resolve(__dirname, 'public/demos/agents/face-mocap.html'),+ 'agents-gemini-live': resolve(__dirname, 'public/demos/agents/gemini-live.html'),+ 'agents-auto-rig': resolve(__dirname, 'public/demos/agents/auto-rig.html'),'aws-marketplace-welcome': resolve(__dirname, 'pages/aws-marketplace/welcome.html'),- 'aws': resolve(__dirname, 'pages/aws/index.html'),- 'agent-trade': resolve(__dirname, 'pages/agent-trade.html'),- 'ibm-galaxy': resolve(__dirname, 'pages/ibm/galaxy.html'),- 'ibm-trust-layer': resolve(__dirname, 'pages/ibm/trust-layer.html'),- 'ibm-oracle': resolve(__dirname, 'pages/ibm/oracle.html'),- 'ibm-vision': resolve(__dirname, 'pages/ibm/vision.html'),- 'ibm-proof': resolve(__dirname, 'pages/ibm/proof.html'),- 'ibm-twin': resolve(__dirname, 'pages/ibm/twin.html'),- 'ibm-identity': resolve(__dirname, 'pages/ibm/identity.html'),- support: resolve(__dirname, 'pages/support.html'),+ aws: resolve(__dirname, 'pages/aws/index.html'),+ 'agent-trade': resolve(__dirname, 'pages/agent-trade.html'),+ 'ibm-galaxy': resolve(__dirname, 'pages/ibm/galaxy.html'),+ 'ibm-trust-layer': resolve(__dirname, 'pages/ibm/trust-layer.html'),+ 'ibm-oracle': resolve(__dirname, 'pages/ibm/oracle.html'),+ 'ibm-vision': resolve(__dirname, 'pages/ibm/vision.html'),+ 'ibm-proof': resolve(__dirname, 'pages/ibm/proof.html'),+ 'ibm-twin': resolve(__dirname, 'pages/ibm/twin.html'),+ 'ibm-identity': resolve(__dirname, 'pages/ibm/identity.html'),+ support: resolve(__dirname, 'pages/support.html'),// dashboard-next prototype — sub-pages auto-discovered so the parallel// agents that land new pages/dashboard-next/*.html files don't have to// touch this config to register them as Rollup inputs.@@ -426,7 +468,8 @@ const appConfig = {'a-embed.html','agent-token-page.html',]);- const RE = /<script[^>]*id=["']vite-plugin-pwa:register-sw["'][^>]*><\/script>\s*/g;+ const RE =+ /<script[^>]*id=["']vite-plugin-pwa:register-sw["'][^>]*><\/script>\s*/g;const outDir = resolvePath(__dirname, 'dist');const stripped = [];const walk = (dir) => {@@ -500,25 +543,25 @@ const appConfig = {'/agents': resolve(root, 'public/agents/index.html'),'/agents/': resolve(root, 'public/agents/index.html'),'/start': resolve(root, 'pages/start.html'),- '/start/': resolve(root, 'pages/start.html'),- '/create': resolve(root, 'pages/create.html'),+ '/start/': resolve(root, 'pages/start.html'),+ '/create': resolve(root, 'pages/create.html'),'/create-agent': resolve(root, 'pages/create-agent.html'),'/create/selfie': resolve(root, 'pages/create-selfie.html'),'/create/selfie/': resolve(root, 'pages/create-selfie.html'),'/create/prompt': resolve(root, 'pages/create-prompt.html'),'/create/prompt/': resolve(root, 'pages/create-prompt.html'),- '/create/character': resolve(root, 'pages/create-character.html'),- '/create/character/': resolve(root, 'pages/create-character.html'),- '/create/video': resolve(root, 'pages/create/video.html'),- '/create/video/': resolve(root, 'pages/create/video.html'),- '/extension/privacy': resolve(root, 'pages/extension-privacy.html'),- '/extension/privacy/': resolve(root, 'pages/extension-privacy.html'),- '/extension/terms': resolve(root, 'pages/extension-terms.html'),- '/extension/terms/': resolve(root, 'pages/extension-terms.html'),- '/embed/walk': resolve(root, 'pages/embed-walk.html'),- '/embed/walk/': resolve(root, 'pages/embed-walk.html'),- '/paywall': resolve(root, 'public/paywall.html'),- '/paywall/': resolve(root, 'public/paywall.html'),+ '/create/character': resolve(root, 'pages/create-character.html'),+ '/create/character/': resolve(root, 'pages/create-character.html'),+ '/create/video': resolve(root, 'pages/create/video.html'),+ '/create/video/': resolve(root, 'pages/create/video.html'),+ '/extension/privacy': resolve(root, 'pages/extension-privacy.html'),+ '/extension/privacy/': resolve(root, 'pages/extension-privacy.html'),+ '/extension/terms': resolve(root, 'pages/extension-terms.html'),+ '/extension/terms/': resolve(root, 'pages/extension-terms.html'),+ '/embed/walk': resolve(root, 'pages/embed-walk.html'),+ '/embed/walk/': resolve(root, 'pages/embed-walk.html'),+ '/paywall': resolve(root, 'public/paywall.html'),+ '/paywall/': resolve(root, 'public/paywall.html'),'/scan': resolve(root, 'pages/scan.html'),'/scan/': resolve(root, 'pages/scan.html'),'/worlds': resolve(root, 'pages/worlds.html'),@@ -586,6 +629,8 @@ const appConfig = {'/glossary/': resolve(root, 'pages/glossary.html'),'/go': resolve(root, 'pages/go.html'),'/go/': resolve(root, 'pages/go.html'),+ '/bounties': resolve(root, 'pages/bounties.html'),+ '/bounties/': resolve(root, 'pages/bounties.html'),'/pump-live': resolve(root, 'pages/pump-live.html'),'/pump-live/': resolve(root, 'pages/pump-live.html'),'/pump-dashboard': resolve(root, 'pages/pump-dashboard.html'),@@ -623,7 +668,10 @@ const appConfig = {'/agenc/room': resolve(root, 'pages/agenc/room.html'),'/agenc/room/': resolve(root, 'pages/agenc/room.html'),'/aws-marketplace/welcome': resolve(root, 'pages/aws-marketplace/welcome.html'),- '/aws-marketplace/welcome/': resolve(root, 'pages/aws-marketplace/welcome.html'),+ '/aws-marketplace/welcome/': resolve(+ root,+ 'pages/aws-marketplace/welcome.html',+ ),'/aws-marketplace/error': resolve(root, 'pages/aws-marketplace/welcome.html'),'/aws-marketplace/error/': resolve(root, 'pages/aws-marketplace/welcome.html'),'/aws': resolve(root, 'pages/aws/index.html'),@@ -661,7 +709,7 @@ const appConfig = {'/lipsync/': resolve(root, 'public/demos/lipsync-tts.html'),'/lipsync/mic': resolve(root, 'public/demos/lipsync-mic.html'),'/lipsync/mic/': resolve(root, 'public/demos/lipsync-mic.html'),-'/launch-week': resolve(root, 'pages/three-ws-launch-week.html'),+ '/launch-week': resolve(root, 'pages/three-ws-launch-week.html'),'/launch-week/': resolve(root, 'pages/three-ws-launch-week.html'),'/launchpad': resolve(root, 'pages/launchpad.html'),'/launchpad/': resolve(root, 'pages/launchpad.html'),@@ -726,7 +774,11 @@ const appConfig = {const url = req.url || '/';// Don't intercept Vite's internal html-proxy / module requests —// it needs to serve the inline-script content for our HTML.- if (url.includes('html-proxy') || url.includes('@id/') || url.includes('@vite/'))+ if (+ url.includes('html-proxy') ||+ url.includes('@id/') ||+ url.includes('@vite/')+ )return next();const path = url.split('?')[0];// /api/* is handled by the http proxy in server.proxy above —@@ -812,19 +864,28 @@ const appConfig = {}// /demos/<slug> or /demos/<slug>.html → resolves to public/demos/<slug>.html on diskelse if (!filePath && /^\/demos\/[a-z0-9-]+(\.html)?\/?$/.test(path)) {- const slug = path.replace(/^\/demos\//, '').replace(/\.html$/, '').replace(/\/$/, '');+ const slug = path+ .replace(/^\/demos\//, '')+ .replace(/\.html$/, '')+ .replace(/\/$/, '');filePath = resolve(root, `public/demos/${slug}.html`);}// /demos/agents/<slug>(.html)? → public/demos/agents/<slug>.html.// Goes through transformIndexHtml so the inline `'three'` imports// inside each demo's <script type="module"> get bundled.else if (!filePath && /^\/demos\/agents\/[a-z0-9-]+(\.html)?\/?$/.test(path)) {- const slug = path.replace(/^\/demos\/agents\//, '').replace(/\.html$/, '').replace(/\/$/, '');+ const slug = path+ .replace(/^\/demos\/agents\//, '')+ .replace(/\.html$/, '')+ .replace(/\/$/, '');filePath = resolve(root, `public/demos/agents/${slug}.html`);}// /demo/coin/<base58 mint> → demo/coin index hydrates from the// mint address in the URL path. Mirrors vercel.json.- else if (!filePath && /^\/demo\/coin\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)) {+ else if (+ !filePath &&+ /^\/demo\/coin\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)+ ) {filePath = resolve(root, 'public/demo/coin/index.html');}// /tutorials/<slug> → dedicated tutorial viewer template@@ -841,9 +902,14 @@ const appConfig = {filePath = resolve(root, 'pages/marketplace.html');else if (!filePath && /^\/marketplace\/avatars\/[^/]+\/?$/.test(path))filePath = resolve(root, 'pages/marketplace.html');- else if (!filePath && /^\/marketplace\/(tools|skills|animations|onchain)\/[^/]+\/?$/.test(path))+ else if (+ !filePath &&+ /^\/marketplace\/(tools|skills|animations|onchain)\/[^/]+\/?$/.test(path)+ )filePath = resolve(root, 'pages/marketplace.html');// /agents/:id → rich detail page (UUID expected, validated client-side)+ else if (!filePath && /^\/bounty\/[^/]+\/?$/.test(path))+ filePath = resolve(root, 'pages/bounty.html');else if (!filePath && /^\/agents\/[^/]+\/?$/.test(path))filePath = resolve(root, 'pages/agent-detail.html');else if (!filePath && /^\/agent\/[^/]+\/edit$/.test(path))@@ -876,7 +942,10 @@ const appConfig = {else if (!filePath && /^\/town\/?$/.test(path))filePath = resolve(root, 'pages/communities.html');// /communities/:mint → coin profile deep link- else if (!filePath && /^\/communities\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path))+ else if (+ !filePath &&+ /^\/communities\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)+ )filePath = resolve(root, 'pages/communities.html');// /@<handle> → public live profile pageelse if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))@@ -923,28 +992,31 @@ const appConfig = {// Catches the long tail of bundled root-level pages (community,// playground, embed, profile, …) without bloating fileMap.else if (!filePath && /^\/[a-z0-9][a-z0-9-]*(\.html)?\/?$/.test(path)) {- const slug = path.replace(/^\//, '').replace(/\.html$/, '').replace(/\/$/, '');+ const slug = path+ .replace(/^\//, '')+ .replace(/\.html$/, '')+ .replace(/\/$/, '');const candidate = resolve(root, `pages/${slug}.html`);if (existsSync(candidate)) filePath = candidate;}// /footer-bot.js — serve the Vite-processed src/footer-bot.js at a- // stable URL in dev so footer.js can load it without knowing the hash.- if (path === '/footer-bot.js') {- req.url = '/src/footer-bot.js';- return next();- }- // /walk-companion.js — same trick for nav.js's Walk Companion module- // (built to a stable, unhashed name in prod; served from src in dev).- if (path === '/walk-companion.js') {- req.url = '/src/walk-companion.js';- return next();- }- // /notifications.js — nav.js loads this module for the per-user inbox.- if (path === '/notifications.js') {- req.url = '/src/notifications.js';- return next();- }- // Avatar Studio (rebranded Character Studio fork) — serve the+ // stable URL in dev so footer.js can load it without knowing the hash.+ if (path === '/footer-bot.js') {+ req.url = '/src/footer-bot.js';+ return next();+ }+ // /walk-companion.js — same trick for nav.js's Walk Companion module+ // (built to a stable, unhashed name in prod; served from src in dev).+ if (path === '/walk-companion.js') {+ req.url = '/src/walk-companion.js';+ return next();+ }+ // /notifications.js — nav.js loads this module for the per-user inbox.+ if (path === '/notifications.js') {+ req.url = '/src/notifications.js';+ return next();+ }+ // Avatar Studio (rebranded Character Studio fork) — serve the// production build out of character-studio/build/ at /avatar-studio/*// so the demo iframe works in dev. Run `npm run build --prefix// character-studio` first to populate the build dir.@@ -955,11 +1027,36 @@ const appConfig = {return createReadStream(indexPath).pipe(res);}res.statusCode = 503;- return res.end('Avatar Studio build missing — run `npm run build --prefix character-studio`');+ return res.end(+ 'Avatar Studio build missing — run `npm run build --prefix character-studio`',+ );}if (path.startsWith('/avatar-studio/')) {const ext = path.split('.').pop().toLowerCase();- const mimes = { js: 'application/javascript', map: 'application/json', css: 'text/css', json: 'application/json', html: 'text/html', ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav', glb: 'model/gltf-binary', gltf: 'model/gltf+json', vrm: 'application/octet-stream', obj: 'text/plain', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', svg: 'image/svg+xml', ico: 'image/x-icon', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', wasm: 'application/wasm' };+ const mimes = {+ js: 'application/javascript',+ map: 'application/json',+ css: 'text/css',+ json: 'application/json',+ html: 'text/html',+ ogg: 'audio/ogg',+ mp3: 'audio/mpeg',+ wav: 'audio/wav',+ glb: 'model/gltf-binary',+ gltf: 'model/gltf+json',+ vrm: 'application/octet-stream',+ obj: 'text/plain',+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ svg: 'image/svg+xml',+ ico: 'image/x-icon',+ woff2: 'font/woff2',+ woff: 'font/woff',+ ttf: 'font/ttf',+ otf: 'font/otf',+ wasm: 'application/wasm',+ };const rel = path.slice('/avatar-studio/'.length);const fileDisk = resolve(root, 'character-studio/build', rel);if (existsSync(fileDisk) && statSync(fileDisk).isFile()) {@@ -992,10 +1089,16 @@ const appConfig = {order: 'pre',handler(_html, ctx) {const EMBED_FILES = new Set([- 'widget.html', 'embed.html', 'avatar-embed.html',- 'agent-embed.html', 'a-embed.html',+ 'widget.html',+ 'embed.html',+ 'avatar-embed.html',+ 'agent-embed.html',+ 'a-embed.html',]);- const filename = (ctx.filename || ctx.path || '').replace(/\\/g, '/').split('/').pop();+ const filename = (ctx.filename || ctx.path || '')+ .replace(/\\/g, '/')+ .split('/')+ .pop();if (EMBED_FILES.has(filename)) return [];const SNIPPET = `!function(t,e){var o,n,p,r;e.__SV||(window.posthog&&window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",p.onerror=function(){window.__posthog_blocked=!0},(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias set_config reset opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing get_distinct_id get_session_id get_session_replay_url register register_once unregister on onFeatureFlags reloadFeatureFlags getFeatureFlag getFeatureFlagPayload isFeatureEnabled addExceptionStep captureException".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('phc_kvi8nrXqrNkLNy2NhaiwkbGyj77XpSJo54P5k2ZHYo9n',{api_host:'/ingest',ui_host:'https://us.posthog.com',defaults:'2026-01-30',person_profiles:'identified_only'})`;return [{ tag: 'script', children: SNIPPET, injectTo: 'head' }];@@ -1019,15 +1122,22 @@ const appConfig = {order: 'pre',handler(_html, ctx) {const EMBED_FILES = new Set([- 'widget.html', 'embed.html', 'avatar-embed.html',- 'agent-embed.html', 'a-embed.html',+ 'widget.html',+ 'embed.html',+ 'avatar-embed.html',+ 'agent-embed.html',+ 'a-embed.html',]);- const filename = (ctx.filename || ctx.path || '').replace(/\\/g, '/').split('/').pop();+ const filename = (ctx.filename || ctx.path || '')+ .replace(/\\/g, '/')+ .split('/')+ .pop();if (EMBED_FILES.has(filename)) return [];return [{tag: 'script',- children: 'window.va=window.va||function(){(window.vaq=window.vaq||[]).push(arguments)};',+ children:+ 'window.va=window.va||function(){(window.vaq=window.vaq||[]).push(arguments)};',injectTo: 'head',},{@@ -1048,17 +1158,25 @@ const appConfig = {order: 'pre',handler(_html, ctx) {const EMBED_FILES = new Set([- 'widget.html', 'embed.html', 'avatar-embed.html',- 'agent-embed.html', 'a-embed.html',+ 'widget.html',+ 'embed.html',+ 'avatar-embed.html',+ 'agent-embed.html',+ 'a-embed.html',]);- const filename = (ctx.filename || ctx.path || '').replace(/\\/g, '/').split('/').pop();+ const filename = (ctx.filename || ctx.path || '')+ .replace(/\\/g, '/')+ .split('/')+ .pop();if (EMBED_FILES.has(filename)) return [];- return [{- tag: 'script',- attrs: { type: 'module' },- children: `import('/src/view-transitions.js').then(m=>m.enableViewTransitions()).catch(()=>{});`,- injectTo: 'head',- }];+ return [+ {+ tag: 'script',+ attrs: { type: 'module' },+ children: `import('/src/view-transitions.js').then(m=>m.enableViewTransitions()).catch(()=>{});`,+ injectTo: 'head',+ },+ ];},},},@@ -1069,7 +1187,13 @@ const appConfig = {transformIndexHtml: {order: 'pre',handler() {- return [{ tag: 'meta', attrs: { name: 'has-three-bundle', content: 'true' }, injectTo: 'head' }];+ return [+ {+ tag: 'meta',+ attrs: { name: 'has-three-bundle', content: 'true' },+ injectTo: 'head',+ },+ ];},},},@@ -1081,7 +1205,8 @@ const appConfig = {// getter always returns undefined and whose setter is a no-op — every// three.js instance's check then passes silently. Runs in head-prepend// so it executes before model-viewer's bundled three or our app bundle.- const GUARD = 'try{Object.defineProperty(window,"__THREE__",{configurable:true,get:function(){return undefined},set:function(){}})}catch(_){}';+ const GUARD =+ 'try{Object.defineProperty(window,"__THREE__",{configurable:true,get:function(){return undefined},set:function(){}})}catch(_){}';return {name: 'three-multi-instance-guard',transformIndexHtml: {@@ -1102,24 +1227,33 @@ const appConfig = {sequential: true,order: 'post',async handler() {- const { readdirSync, statSync, readFileSync, writeFileSync } = await import('fs');+ const { readdirSync, statSync, readFileSync, writeFileSync } =+ await import('fs');const { join } = await import('path');const distDir = resolve(__dirname, 'dist');if (!existsSync(distDir)) return;const MARKER = 'Object.defineProperty(window,"__THREE__"';- const LEGACY = /<script>\s*window\.__THREE__\s*=\s*window\.__THREE__\s*\|\|\s*["'][^"']+["']\s*;?\s*<\/script>\s*/g;+ const LEGACY =+ /<script>\s*window\.__THREE__\s*=\s*window\.__THREE__\s*\|\|\s*["'][^"']+["']\s*;?\s*<\/script>\s*/g;const tag = `<script>${GUARD}</script>`;const walk = (dir) => {for (const entry of readdirSync(dir)) {const full = join(dir, entry);let stat;- try { stat = statSync(full); } catch { continue; }+ try {+ stat = statSync(full);+ } catch {+ continue;+ }if (stat.isDirectory()) walk(full);else if (entry.endsWith('.html')) {const html = readFileSync(full, 'utf8');let next = html.replace(LEGACY, '');if (!next.includes(MARKER)) {- next = next.replace(/<head(\s[^>]*)?>/i, (m) => `${m}\n\t\t${tag}`);+ next = next.replace(+ /<head(\s[^>]*)?>/i,+ (m) => `${m}\n\t\t${tag}`,+ );}if (next !== html) writeFileSync(full, next);}@@ -1157,9 +1291,13 @@ const appConfig = {cpSync(resolve(__dirname, 'src'), resolve(__dirname, 'dist/src'), {recursive: true,});- cpSync(resolve(__dirname, 'pump-fun-skills'), resolve(__dirname, 'dist/pump-fun-skills'), {- recursive: true,- });+ cpSync(+ resolve(__dirname, 'pump-fun-skills'),+ resolve(__dirname, 'dist/pump-fun-skills'),+ {+ recursive: true,+ },+ );},},{@@ -1172,7 +1310,9 @@ const appConfig = {closeBundle() {const src = resolve(__dirname, 'character-studio/build');if (!existsSync(src)) {- console.warn('[copy-avatar-studio] character-studio/build/ missing — run `npm run build --prefix character-studio` first');+ console.warn(+ '[copy-avatar-studio] character-studio/build/ missing — run `npm run build --prefix character-studio` first',+ );return;}cpSync(src, resolve(__dirname, 'dist/avatar-studio'), { recursive: true });@@ -1198,7 +1338,10 @@ const appConfig = {const text = await resp.text();const rewritten = text.replace(R2_PUBLIC_RE, '/r2-proxy/');res.statusCode = resp.status;- res.setHeader('content-type', resp.headers.get('content-type') || 'application/json');+ res.setHeader(+ 'content-type',+ resp.headers.get('content-type') || 'application/json',+ );res.end(rewritten);} catch (err) {next();@@ -1219,14 +1362,14 @@ const appConfig = {const m = url.match(/^\/api\/widgets\/(wdgt_demo_[A-Za-z0-9_-]+)(?:[?#]|$)/);if (!m) return next();try {- const mod = await server.ssrLoadModule(- '/api/widgets/_demo-fixtures.js',- );+ const mod = await server.ssrLoadModule('/api/widgets/_demo-fixtures.js');const widget = mod.getDemoWidget(m[1]);if (!widget) {res.statusCode = 404;res.setHeader('content-type', 'application/json');- res.end(JSON.stringify({ error: 'not_found', message: 'widget not found' }));+ res.end(+ JSON.stringify({ error: 'not_found', message: 'widget not found' }),+ );return;}res.statusCode = 200;@@ -1236,7 +1379,9 @@ const appConfig = {} catch (err) {res.statusCode = 500;res.setHeader('content-type', 'application/json');- res.end(JSON.stringify({ error: 'fixture_load_failed', message: err.message }));+ res.end(+ JSON.stringify({ error: 'fixture_load_failed', message: err.message }),+ );}});},@@ -1363,7 +1508,12 @@ const appConfig = {icons: [{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },- { src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },+ {+ src: 'pwa-512x512.png',+ sizes: '512x512',+ type: 'image/png',+ purpose: 'maskable',+ },],shortcuts: [{@@ -1463,7 +1613,8 @@ const appConfig = {handler: 'NetworkOnly',},{- urlPattern: /^https?:\/\/[^/]+\/(embed|a-embed|agent-embed|avatar-embed)(\/.*|\?.*|#.*|$)/i,+ urlPattern:+ /^https?:\/\/[^/]+\/(embed|a-embed|agent-embed|avatar-embed)(\/.*|\?.*|#.*|$)/i,handler: 'NetworkOnly',},{