Skip to content

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

feat: add payment gate modal for skill payments

nirholas78220fab9583
diff --git a/api/_lib/migrations/2026-04-30-skills-marketplace.sql b/api/_lib/migrations/2026-04-30-skills-marketplace.sql
index a8d67926f..f709ca8a7 100644
--- a/api/_lib/migrations/2026-04-30-skills-marketplace.sql
+++ b/api/_lib/migrations/2026-04-30-skills-marketplace.sql
@@ -1,8 +1,9 @@
--- Migration: skills marketplace tables.
+-- Migration: skills marketplace tables + seed data.
-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-30-skills-marketplace.sql
+-- Idempotent.
-- ── marketplace_skills ───────────────────────────────────────────────────────
-create table marketplace_skills (
+create table if not exists marketplace_skills (
id uuid primary key default gen_random_uuid(),
author_id uuid references users(id) on delete set null,
name text not null,
@@ -17,13 +18,13 @@ create table marketplace_skills (
updated_at timestamptz not null default now()
);
-create index marketplace_skills_category_idx on marketplace_skills(category);
-create index marketplace_skills_author_idx on marketplace_skills(author_id);
-create index marketplace_skills_popular_idx on marketplace_skills(install_count desc);
-create index marketplace_skills_new_idx on marketplace_skills(created_at desc);
+create index if not exists marketplace_skills_category_idx on marketplace_skills(category);
+create index if not exists marketplace_skills_author_idx on marketplace_skills(author_id);
+create index if not exists marketplace_skills_popular_idx on marketplace_skills(install_count desc);
+create index if not exists marketplace_skills_new_idx on marketplace_skills(created_at desc);
-- ── skill_installs ───────────────────────────────────────────────────────────
-create table skill_installs (
+create table if not exists skill_installs (
id uuid primary key default gen_random_uuid(),
user_id uuid references users(id) on delete cascade,
skill_id uuid references marketplace_skills(id) on delete cascade,
@@ -31,10 +32,10 @@ create table skill_installs (
unique (user_id, skill_id)
);
-create index skill_installs_user_idx on skill_installs(user_id);
+create index if not exists skill_installs_user_idx on skill_installs(user_id);
-- ── skill_ratings ────────────────────────────────────────────────────────────
-create table skill_ratings (
+create table if not exists skill_ratings (
id uuid primary key default gen_random_uuid(),
user_id uuid references users(id) on delete cascade,
skill_id uuid references marketplace_skills(id) on delete cascade,
@@ -55,7 +56,7 @@ insert into marketplace_skills (author_id, name, slug, description, category, sc
(
null,
'TradingView Charts',
- 'tradingview-charts',
+ 'tradingview',
'Display interactive TradingView price charts for any symbol.',
'finance',
$json$[
@@ -187,7 +188,7 @@ insert into marketplace_skills (author_id, name, slug, description, category, sc
{"name": "memo", "type": "string", "description": "Optional memo string to attach"},
{"name": "network", "type": "string", "description": "mainnet or devnet. Default: mainnet"}
],
- "body": "// see chat/src/tools.js → walletToolSchema solana_transfer"
+ "body": "const _token = args.token || 'SOL';\nconst _network = args.network || 'mainnet';\nconst wallet = window.__wallet;\nif (!wallet || wallet.type !== 'solana') throw new Error('No Solana wallet connected. Please connect a Solana wallet first.');\nconst buildRes = await fetch('/api/tx/solana/build-transfer', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ sender: wallet.address, recipient: args.recipient, amount: args.amount, token: _token, memo: args.memo, network: _network }),\n});\nif (!buildRes.ok) {\n const err = await buildRes.json().catch(() => ({}));\n throw new Error(err.message || 'Failed to build transaction');\n}\nconst { transaction: txBase64 } = await buildRes.json();\nawait window.requestWalletApproval({\n network: _network === 'devnet' ? 'Solana Devnet' : 'Solana',\n from: wallet.address,\n to: args.recipient,\n amount: String(args.amount),\n token: _token,\n memo: args.memo,\n});\nconst txBytes = Uint8Array.from(atob(txBase64), c => c.charCodeAt(0));\nif (!window.solana.signAndSendTransaction) throw new Error('Wallet does not support signAndSendTransaction');\nconst { Transaction } = await import('https://esm.sh/@solana/web3.js@1');\nconst tx = Transaction.from(txBytes);\nconst result = await window.solana.signAndSendTransaction(tx);\nconst signature = result.signature;\nconst explorerUrl = 'https://solscan.io/tx/' + signature + (_network === 'devnet' ? '?cluster=devnet' : '');\nreturn { contentType: 'application/tx-result', content: { status: 'success', txHash: signature, network: _network === 'devnet' ? 'Solana Devnet' : 'Solana', from: wallet.address, to: args.recipient, amount: String(args.amount), token: _token, explorerUrl } };"
},
"type": "function",
"function": {
@@ -217,7 +218,7 @@ insert into marketplace_skills (author_id, name, slug, description, category, sc
{"name": "amount", "type": "number", "description": "Amount of input token in human-readable units"},
{"name": "slippageBps", "type": "number", "description": "Max slippage in basis points (100 = 1%). Default: 50"}
],
- "body": "// see chat/src/tools.js → walletToolSchema solana_swap"
+ "body": "const _slippageBps = args.slippageBps || 50;\nconst wallet = window.__wallet;\nif (!wallet || wallet.type !== 'solana') throw new Error('No Solana wallet connected.');\nconst buildRes = await fetch('/api/tx/solana/build-swap', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ sender: wallet.address, inputMint: args.inputMint, outputMint: args.outputMint, amount: args.amount, slippageBps: _slippageBps }),\n});\nif (!buildRes.ok) {\n const err = await buildRes.json().catch(() => ({}));\n throw new Error(err.message || 'Failed to get swap route');\n}\nconst { transaction: txBase64, outputAmount, priceImpactPct } = await buildRes.json();\nawait window.requestWalletApproval({\n network: 'Solana',\n from: wallet.address,\n to: 'Jupiter (DEX aggregator)',\n amount: String(args.amount),\n token: args.inputMint.slice(0, 6) + '... -> ' + args.outputMint.slice(0, 6) + '...',\n memo: '~' + outputAmount + ' out, ' + priceImpactPct + '% price impact',\n});\nconst txBytes = Uint8Array.from(atob(txBase64), c => c.charCodeAt(0));\nconst { Transaction } = await import('https://esm.sh/@solana/web3.js@1');\nconst tx = Transaction.from(txBytes);\nconst result = await window.solana.signAndSendTransaction(tx);\nconst signature = result.signature;\nreturn { contentType: 'application/tx-result', content: { status: 'success', txHash: signature, network: 'Solana', from: wallet.address, to: args.outputMint, amount: String(outputAmount), token: args.outputMint.slice(0, 8) + '...', explorerUrl: 'https://solscan.io/tx/' + signature } };"
},
"type": "function",
"function": {
@@ -246,7 +247,7 @@ insert into marketplace_skills (author_id, name, slug, description, category, sc
{"name": "token", "type": "string", "description": "ETH for native token, or an ERC20 contract address. Default: ETH"},
{"name": "decimals", "type": "number", "description": "Token decimals (required for ERC20, ignored for ETH). Default: 18"}
],
- "body": "// see chat/src/tools.js → walletToolSchema evm_transfer"
+ "body": "const wallet = window.__wallet;\nif (!wallet || wallet.type !== 'evm') throw new Error('No EVM wallet connected. Please connect MetaMask or a compatible wallet.');\nconst _token = args.token || 'ETH';\nconst _decimals = args.decimals !== undefined ? args.decimals : 18;\nconst chainNames = { 1: 'Ethereum', 8453: 'Base', 10: 'Optimism', 42161: 'Arbitrum', 137: 'Polygon' };\nconst networkName = chainNames[wallet.chainId] || 'Chain ' + wallet.chainId;\nawait window.requestWalletApproval({ network: networkName, from: wallet.address, to: args.recipient, amount: args.amount, token: _token === 'ETH' ? 'ETH' : _token.slice(0, 8) + '...' });\nlet txHash;\nif (_token === 'ETH') {\n const valueHex = '0x' + BigInt(Math.round(parseFloat(args.amount) * 1e18)).toString(16);\n txHash = await window.ethereum.request({ method: 'eth_sendTransaction', params: [{ from: wallet.address, to: args.recipient, value: valueHex }] });\n} else {\n const amountBigInt = BigInt(Math.round(parseFloat(args.amount) * 10 ** _decimals));\n const paddedTo = args.recipient.slice(2).padStart(64, '0');\n const paddedAmount = amountBigInt.toString(16).padStart(64, '0');\n txHash = await window.ethereum.request({ method: 'eth_sendTransaction', params: [{ from: wallet.address, to: _token, data: '0xa9059cbb' + paddedTo + paddedAmount }] });\n}\nconst explorerBases = { 1: 'https://etherscan.io/tx/', 8453: 'https://basescan.org/tx/', 10: 'https://optimistic.etherscan.io/tx/', 42161: 'https://arbiscan.io/tx/', 137: 'https://polygonscan.com/tx/' };\nconst explorerUrl = (explorerBases[wallet.chainId] || 'https://etherscan.io/tx/') + txHash;\nreturn { contentType: 'application/tx-result', content: { status: 'pending', txHash, network: networkName, chainId: wallet.chainId, from: wallet.address, to: args.recipient, amount: args.amount, token: _token === 'ETH' ? 'ETH' : _token.slice(0, 10) + '...', explorerUrl } };"
},
"type": "function",
"function": {
@@ -276,7 +277,7 @@ insert into marketplace_skills (author_id, name, slug, description, category, sc
{"name": "decimals", "type": "number", "description": "Decimals of fromToken. Default: 18"},
{"name": "slippage", "type": "number", "description": "Max slippage percentage (e.g. 1 for 1%). Default: 1"}
],
- "body": "// see chat/src/tools.js → walletToolSchema evm_swap"
+ "body": "const wallet = window.__wallet;\nif (!wallet || wallet.type !== 'evm') throw new Error('No EVM wallet connected.');\nconst _decimals = args.decimals !== undefined ? args.decimals : 18;\nconst _slippage = args.slippage !== undefined ? args.slippage : 1;\nconst chainNames = { 1: 'Ethereum', 8453: 'Base', 10: 'Optimism', 42161: 'Arbitrum', 137: 'Polygon' };\nconst networkName = chainNames[wallet.chainId] || 'Chain ' + wallet.chainId;\nconst amountWei = BigInt(Math.round(parseFloat(args.amount) * 10 ** _decimals)).toString();\nconst quoteUrl = 'https://api.1inch.dev/swap/v5.2/' + wallet.chainId + '/swap?src=' + args.fromToken + '&dst=' + args.toToken + '&amount=' + amountWei + '&from=' + wallet.address + '&slippage=' + _slippage + '&disableEstimate=true';\nconst quoteRes = await fetch(quoteUrl, { headers: { 'Accept': 'application/json' } });\nif (!quoteRes.ok) {\n const err = await quoteRes.json().catch(() => ({}));\n throw new Error(err.description || 'Failed to get swap quote from 1inch');\n}\nconst quote = await quoteRes.json();\nconst toAmountHuman = (Number(quote.toAmount) / 10 ** 18).toFixed(6);\nawait window.requestWalletApproval({ network: networkName, from: wallet.address, to: '1inch Router', amount: args.amount, token: args.fromToken.slice(0,8) + '... -> ' + args.toToken.slice(0,8) + '...', memo: '~' + toAmountHuman + ' out' });\nconst ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';\nif (args.fromToken.toLowerCase() !== ETH_ADDRESS.toLowerCase()) {\n const paddedOwner = wallet.address.slice(2).padStart(64, '0');\n const paddedSpender = quote.tx.to.slice(2).padStart(64, '0');\n const allowanceHex = await window.ethereum.request({ method: 'eth_call', params: [{ to: args.fromToken, data: '0xdd62ed3e' + paddedOwner + paddedSpender }, 'latest'] });\n if (BigInt(allowanceHex || '0x0') < BigInt(amountWei)) {\n await window.ethereum.request({ method: 'eth_sendTransaction', params: [{ from: wallet.address, to: args.fromToken, data: '0x095ea7b3' + paddedSpender + 'f'.repeat(64) }] });\n }\n}\nconst txHash = await window.ethereum.request({ method: 'eth_sendTransaction', params: [{ from: wallet.address, to: quote.tx.to, data: quote.tx.data, value: quote.tx.value || '0x0' }] });\nconst explorerBases = { 1: 'https://etherscan.io/tx/', 8453: 'https://basescan.org/tx/', 10: 'https://optimistic.etherscan.io/tx/', 42161: 'https://arbiscan.io/tx/', 137: 'https://polygonscan.com/tx/' };\nconst explorerUrl = (explorerBases[wallet.chainId] || 'https://etherscan.io/tx/') + txHash;\nreturn { contentType: 'application/tx-result', content: { status: 'pending', txHash, network: networkName, chainId: wallet.chainId, from: wallet.address, to: args.toToken, amount: '~' + toAmountHuman, token: args.toToken.slice(0, 10) + '...', explorerUrl } };"
},
"type": "function",
"function": {
@@ -298,6 +299,41 @@ insert into marketplace_skills (author_id, name, slug, description, category, sc
]$json$::jsonb,
'{crypto,solana,evm,defi,wallet}',
true
+),
+
+(
+ null,
+ 'QR Code',
+ 'qr-code',
+ 'Generate a QR code image for any text or URL.',
+ 'utilities',
+ $json$[
+ {
+ "clientDefinition": {
+ "id": "qr-code-001",
+ "name": "QRCode",
+ "description": "Generates a QR code image for any text or URL.",
+ "arguments": [
+ {"name": "text", "type": "string", "description": "Text or URL to encode as a QR code"}
+ ],
+ "body": "const encoded = encodeURIComponent(args.text);\nconst url = 'https://api.qrserver.com/v1/create-qr-code/?size=256x256&data=' + encoded;\nreturn { contentType: 'text/html', content: '<div style=\"text-align:center;padding:16px\"><img src=\"' + url + '\" style=\"max-width:256px\" alt=\"QR Code\"><p style=\"font-family:monospace;font-size:12px;word-break:break-all\">' + args.text + '</p></div>' };"
+ },
+ "type": "function",
+ "function": {
+ "name": "QRCode",
+ "description": "Generates and displays a QR code for the given text or URL.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "text": {"type": "string", "description": "Text or URL to encode as QR code"}
+ },
+ "required": ["text"]
+ }
+ }
+ }
+ ]$json$::jsonb,
+ '{qr,encode,url,utilities}',
+ true
)
on conflict (slug) do nothing;
diff --git a/api/_lib/migrations/2026-04-30-skills-seed.sql b/api/_lib/migrations/2026-04-30-skills-seed.sql
new file mode 100644
index 000000000..96e9ff605
--- /dev/null
+++ b/api/_lib/migrations/2026-04-30-skills-seed.sql
@@ -0,0 +1,177 @@
+-- Migration: skills marketplace seed data
+-- Inserts 15 ready-to-use skills into marketplace_skills.
+-- All rows: author_id = null (system skills), is_public = true.
+-- Idempotent via ON CONFLICT (slug) DO NOTHING.
+
+begin;
+
+insert into marketplace_skills (name, slug, description, category, tags, schema_json, is_public, author_id) values
+
+(
+ 'TradingView Charts',
+ 'tradingview-charts',
+ 'Display interactive TradingView price charts for any symbol including crypto, stocks, and forex.',
+ 'finance',
+ '{"charts","trading","crypto","stocks"}',
+ '[{"clientDefinition":{"id":"tradingview-chart-001","name":"TradingViewChart","description":"Displays an interactive TradingView chart for a given symbol.","arguments":[{"name":"symbol","type":"string","description":"Trading symbol e.g. BINANCE:BTCUSDT, NASDAQ:AAPL"},{"name":"interval","type":"string","description":"Chart interval: 1, 5, 15, 30, 60, D, W, M"},{"name":"theme","type":"string","description":"light or dark"}],"body":"const symbol = args.symbol || ''BINANCE:BTCUSDT'';\nconst interval = args.interval || ''D'';\nconst theme = args.theme || ''light'';\nconst html = `<!DOCTYPE html><html><head><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style></head><body><div id=\"tv_chart\" style=\"width:100%;height:100vh\"></div><script src=\"https://s3.tradingview.com/tv.js\"><\\/script><script>new TradingView.widget({container_id:\"tv_chart\",symbol:${JSON.stringify(symbol)},interval:${JSON.stringify(interval)},theme:${JSON.stringify(theme)},style:\"1\",width:\"100%\",height:\"100%\",toolbar_bg:\"#f1f3f6\",hide_side_toolbar:false,allow_symbol_change:true});<\\/script></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"TradingViewChart","description":"Display an interactive TradingView chart. Use for any request to show a price chart, candlestick chart, or market data visualization.","parameters":{"type":"object","properties":{"symbol":{"type":"string","description":"Trading symbol e.g. BINANCE:BTCUSDT, NASDAQ:AAPL, FX:EURUSD"},"interval":{"type":"string","enum":["1","5","15","30","60","D","W","M"],"description":"Chart interval"},"theme":{"type":"string","enum":["light","dark"],"description":"Chart theme"}},"required":["symbol"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Web Search',
+ 'web-search',
+ 'Search the web via DuckDuckGo and return an abstract and top related topics.',
+ 'utility',
+ '{"search","web","duckduckgo"}',
+ '[{"clientDefinition":{"id":"pack-websearch-001","name":"WebSearch","description":"Search the web via DuckDuckGo.","arguments":[{"name":"query","type":"string","description":"Search query"}],"body":"const res = await fetch(''https://api.duckduckgo.com/?q='' + encodeURIComponent(args.query) + ''&format=json&no_html=1'');\nconst d = await res.json();\nconst topics = (d.RelatedTopics || []).slice(0, 3).map(t => t.Text).filter(Boolean);\nreturn JSON.stringify({ abstract: d.AbstractText || '''', topics });"},"type":"function","function":{"name":"WebSearch","description":"Search the web via DuckDuckGo and return an abstract and top related topics.","parameters":{"type":"object","properties":{"query":{"type":"string","description":"Search query"}},"required":["query"]}}}]',
+ true,
+ null
+),
+
+(
+ 'QR Code Generator',
+ 'qr-code',
+ 'Render a QR code image for any URL or text using the qrserver.com API.',
+ 'utility',
+ '{"qr","barcode","encode"}',
+ '[{"clientDefinition":{"id":"qr-code-001","name":"QRCode","description":"Renders a QR code image for any text or URL.","arguments":[{"name":"text","type":"string","description":"Text or URL to encode"},{"name":"size","type":"number","description":"Size in pixels (default 200)"}],"body":"const t = encodeURIComponent(args.text || '''');\nconst s = args.size || 200;\nconst src = `https://api.qrserver.com/v1/create-qr-code/?size=${s}x${s}&data=${t}`;\nconst html = `<!DOCTYPE html><html><head><style>body{margin:0;display:flex;align-items:center;justify-content:center;height:100vh;background:#fff}</style></head><body><img src=\"${src}\" alt=\"QR code\" style=\"max-width:100%;height:auto\" /></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"QRCode","description":"Generate and display a QR code for any text or URL.","parameters":{"type":"object","properties":{"text":{"type":"string","description":"Text or URL to encode in the QR code"},"size":{"type":"number","description":"Image size in pixels, default 200"}},"required":["text"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Calculator',
+ 'calculator',
+ 'Evaluate mathematical expressions safely without using eval.',
+ 'utility',
+ '{"math","calculate","expression"}',
+ '[{"clientDefinition":{"id":"calculator-001","name":"Calculator","description":"Evaluates a mathematical expression and returns the result.","arguments":[{"name":"expression","type":"string","description":"Math expression to evaluate, e.g. 2 + 2 * 3"}],"body":"try {\n const result = new Function(''return ('' + args.expression + '')'')();\n if (typeof result !== ''number'' || !isFinite(result)) throw new Error(''Result is not a finite number'');\n return { expression: args.expression, result };\n} catch (e) {\n return { expression: args.expression, error: e.message };\n}"},"type":"function","function":{"name":"Calculator","description":"Evaluate a mathematical expression and return the numeric result. Use for arithmetic, percentages, or any calculation the user needs.","parameters":{"type":"object","properties":{"expression":{"type":"string","description":"Mathematical expression, e.g. \"(10 + 5) * 3 / 2\""}},"required":["expression"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Markdown Preview',
+ 'markdown-preview',
+ 'Render user-supplied Markdown as styled HTML in a live preview iframe.',
+ 'productivity',
+ '{"markdown","preview","render","docs"}',
+ '[{"clientDefinition":{"id":"markdown-preview-001","name":"MarkdownPreview","description":"Renders Markdown text as styled HTML.","arguments":[{"name":"markdown","type":"string","description":"Markdown text to render"}],"body":"const md = args.markdown || '''';\n// Simple markdown-to-html: headers, bold, italic, code, lists, links\nfunction mdToHtml(s) {\n return s\n .replace(/&/g, ''&amp;'').replace(/</g, ''&lt;'').replace(/>/g, ''&gt;'')\n .replace(/```([\\s\\S]*?)```/g, (_, c) => `<pre><code>${c.trim()}</code></pre>`)\n .replace(/`([^`]+)`/g, ''<code>$1</code>'')\n .replace(/^#{6}\\s+(.+)$/gm, ''<h6>$1</h6>'')\n .replace(/^#{5}\\s+(.+)$/gm, ''<h5>$1</h5>'')\n .replace(/^#{4}\\s+(.+)$/gm, ''<h4>$1</h4>'')\n .replace(/^###\\s+(.+)$/gm, ''<h3>$1</h3>'')\n .replace(/^##\\s+(.+)$/gm, ''<h2>$1</h2>'')\n .replace(/^#\\s+(.+)$/gm, ''<h1>$1</h1>'')\n .replace(/\\*\\*(.+?)\\*\\*/g, ''<strong>$1</strong>'')\n .replace(/\\*(.+?)\\*/g, ''<em>$1</em>'')\n .replace(/^-\\s+(.+)$/gm, ''<li>$1</li>'')\n .replace(/(<li>.*<\\/li>)/gs, ''<ul>$1</ul>'')\n .replace(/\\[(.+?)\\]\\((.+?)\\)/g, ''<a href=\"$2\" target=\"_blank\">$1</a>'')\n .replace(/\\n\\n/g, ''</p><p>'')\n .replace(/^(?!<[hup])(.+)$/gm, ''$1'');\n}\nconst body = mdToHtml(md);\nconst html = `<!DOCTYPE html><html><head><style>body{font-family:system-ui,sans-serif;max-width:720px;margin:2rem auto;padding:0 1rem;line-height:1.6;color:#1a1a1a}h1,h2,h3,h4,h5,h6{margin-top:1.5em}code{background:#f4f4f4;padding:.2em .4em;border-radius:3px;font-size:.9em}pre{background:#f4f4f4;padding:1em;border-radius:5px;overflow:auto}pre code{background:none;padding:0}a{color:#0070f3}ul{padding-left:1.5em}</style></head><body><p>${body}</p></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"MarkdownPreview","description":"Render Markdown text as a styled HTML preview. Use when the user wants to see formatted documentation, notes, or any Markdown content.","parameters":{"type":"object","properties":{"markdown":{"type":"string","description":"Markdown text to render"}},"required":["markdown"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Color Palette Generator',
+ 'color-palette',
+ 'Generate a 5-colour palette as HTML swatches from a theme description.',
+ 'media',
+ '{"color","palette","design","ui"}',
+ '[{"clientDefinition":{"id":"color-palette-001","name":"ColorPalette","description":"Generates a 5-colour palette as swatches from a theme description.","arguments":[{"name":"theme","type":"string","description":"Theme description, e.g. sunset, ocean, forest, neon"}],"body":"const theme = (args.theme || ''default'').toLowerCase();\n// Deterministic palette generator from theme string\nfunction strToSeed(s) { let h = 0; for (const c of s) h = Math.imul(31, h) + c.charCodeAt(0) | 0; return Math.abs(h); }\nfunction hslToHex(h, s, l) {\n s /= 100; l /= 100;\n const a = s * Math.min(l, 1 - l);\n const f = n => { const k = (n + h / 30) % 12; const c = l - a * Math.max(-1, Math.min(k - 3, Math.min(9 - k, 1))); return Math.round(255 * c).toString(16).padStart(2, ''0''); };\n return `#${f(0)}${f(8)}${f(4)}`;\n}\nconst seed = strToSeed(theme);\nconst baseHue = seed % 360;\nconst colors = [\n hslToHex(baseHue, 80, 40),\n hslToHex((baseHue + 30) % 360, 70, 55),\n hslToHex((baseHue + 60) % 360, 60, 65),\n hslToHex((baseHue + 180) % 360, 50, 45),\n hslToHex((baseHue + 210) % 360, 40, 70),\n];\nconst swatches = colors.map(c => `<div style=\"display:flex;align-items:center;gap:12px;margin:8px 0\"><div style=\"width:60px;height:60px;border-radius:8px;background:${c};box-shadow:0 2px 4px rgba(0,0,0,.2)\"></div><div><code style=\"font-size:1.1em\">${c}</code></div></div>`).join('''');\nconst html = `<!DOCTYPE html><html><head><style>body{font-family:system-ui,sans-serif;padding:1.5rem;background:#fafafa}h2{margin:0 0 1rem;font-size:1rem;color:#555}</style></head><body><h2>Palette for &ldquo;${theme}&rdquo;</h2>${swatches}</body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"ColorPalette","description":"Generate a harmonious 5-colour palette as visual swatches from a theme or mood description.","parameters":{"type":"object","properties":{"theme":{"type":"string","description":"Theme or mood description, e.g. \"ocean\", \"sunset\", \"corporate blue\""}},"required":["theme"]}}}]',
+ true,
+ null
+),
+
+(
+ 'JSON Formatter',
+ 'json-formatter',
+ 'Pretty-print and validate JSON input with syntax highlighting.',
+ 'developer',
+ '{"json","format","validate","developer"}',
+ '[{"clientDefinition":{"id":"json-formatter-001","name":"JSONFormatter","description":"Pretty-prints and validates JSON input.","arguments":[{"name":"json","type":"string","description":"JSON string to format"}],"body":"let parsed, formatted, isValid = true, errorMsg = '''';\ntry {\n parsed = JSON.parse(args.json);\n formatted = JSON.stringify(parsed, null, 2);\n} catch (e) {\n isValid = false;\n errorMsg = e.message;\n formatted = args.json;\n}\nfunction esc(s) { return s.replace(/&/g,''&amp;'').replace(/</g,''&lt;'').replace(/>/g,''&gt;''); }\nfunction highlight(s) {\n return esc(s).replace(\n /(\"(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\\"])*\"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)/g,\n match => {\n let cls = ''number'';\n if (/^\"|/.test(match)) cls = /:$/.test(match) ? ''key'' : ''string'';\n else if (/true|false/.test(match)) cls = ''boolean'';\n else if (/null/.test(match)) cls = ''null'';\n return `<span class=\"${cls}\">${match}</span>`;\n }\n );\n}\nconst html = `<!DOCTYPE html><html><head><style>body{margin:0;font-family:monospace;font-size:13px;background:#1e1e1e;color:#d4d4d4}pre{padding:1rem;margin:0;overflow:auto;height:100vh;box-sizing:border-box}.key{color:#9cdcfe}.string{color:#ce9178}.number{color:#b5cea8}.boolean{color:#569cd6}.null{color:#569cd6}.error{background:#5a1a1a;color:#f88;padding:.5rem 1rem;font-size:12px}</style></head><body>${isValid?'''':`<div class=\"error\">Invalid JSON: ${esc(errorMsg)}</div>`}<pre>${highlight(formatted)}</pre></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"JSONFormatter","description":"Pretty-print and syntax-highlight JSON. Use when the user wants to format, view, or validate a JSON string.","parameters":{"type":"object","properties":{"json":{"type":"string","description":"JSON string to format and validate"}},"required":["json"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Regex Tester',
+ 'regex-tester',
+ 'Test a regular expression against input text and highlight all matches.',
+ 'developer',
+ '{"regex","regexp","pattern","test"}',
+ '[{"clientDefinition":{"id":"regex-tester-001","name":"RegexTester","description":"Tests a regular expression against input text and highlights matches.","arguments":[{"name":"pattern","type":"string","description":"Regular expression pattern (without delimiters)"},{"name":"flags","type":"string","description":"Regex flags, e.g. gi"},{"name":"text","type":"string","description":"Input text to test against"}],"body":"const pat = args.pattern || '''';\nconst flags = (args.flags || ''g'').includes(''g'') ? args.flags || ''g'' : (args.flags || '''') + ''g'';\nconst text = args.text || '''';\nfunction esc(s) { return s.replace(/&/g,''&amp;'').replace(/</g,''&lt;'').replace(/>/g,''&gt;''); }\nlet highlighted, matchCount = 0, error = '''';\ntry {\n const re = new RegExp(pat, flags);\n const matches = [...text.matchAll(re)];\n matchCount = matches.length;\n highlighted = esc(text).replace(new RegExp(esc(pat), flags), m => `<mark>${esc(m)}</mark>`);\n} catch (e) {\n error = e.message;\n highlighted = esc(text);\n}\nconst html = `<!DOCTYPE html><html><head><style>body{font-family:system-ui,sans-serif;padding:1rem;color:#1a1a1a}.meta{font-size:12px;color:#666;margin-bottom:.5rem}.pattern{font-family:monospace;background:#f4f4f4;padding:.2em .4em;border-radius:3px}.output{font-family:monospace;font-size:14px;white-space:pre-wrap;word-break:break-all;line-height:1.6;background:#fafafa;padding:1rem;border-radius:5px;border:1px solid #e0e0e0}mark{background:#ffe066;border-radius:2px}.error{color:#c00;font-size:13px;margin-bottom:.5rem}</style></head><body><div class=\"meta\">${error?`<div class=\"error\">Error: ${esc(error)}</div>`:''}<span class=\"pattern\">/${esc(pat)}/${esc(flags)}</span> — <strong>${matchCount}</strong> match${matchCount===1?'''':''es''}</div><div class=\"output\">${highlighted}</div></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"RegexTester","description":"Test a regular expression against input text and highlight all matches. Use when the user wants to validate, debug, or demonstrate a regex pattern.","parameters":{"type":"object","properties":{"pattern":{"type":"string","description":"Regex pattern without delimiters"},"flags":{"type":"string","description":"Regex flags e.g. \"gi\", default \"g\""},"text":{"type":"string","description":"Text to test the pattern against"}},"required":["pattern","text"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Unit Converter',
+ 'unit-converter',
+ 'Convert between common units: length, weight, temperature, volume, and speed.',
+ 'utility',
+ '{"units","convert","measurement","calculator"}',
+ '[{"clientDefinition":{"id":"unit-converter-001","name":"UnitConverter","description":"Converts a value between common units.","arguments":[{"name":"value","type":"number","description":"Numeric value to convert"},{"name":"from","type":"string","description":"Source unit, e.g. km, lb, celsius"},{"name":"to","type":"string","description":"Target unit, e.g. miles, kg, fahrenheit"}],"body":"const conversions = {\n // length (base: meter)\n m:1, meter:1, meters:1, km:1000, kilometer:1000, kilometers:1000,\n cm:0.01, centimeter:0.01, centimeters:0.01, mm:0.001,\n mile:1609.344, miles:1609.344, ft:0.3048, foot:0.3048, feet:0.3048,\n inch:0.0254, inches:0.0254, yard:0.9144, yards:0.9144,\n // weight (base: kg)\n kg:1, kilogram:1, kilograms:1, g:0.001, gram:0.001, grams:0.001,\n lb:0.453592, lbs:0.453592, pound:0.453592, pounds:0.453592,\n oz:0.0283495, ounce:0.0283495, ounces:0.0283495,\n // volume (base: liter)\n l:1, liter:1, liters:1, ml:0.001, milliliter:0.001, milliliters:0.001,\n gallon:3.78541, gallons:3.78541, quart:0.946353, quarts:0.946353,\n pint:0.473176, pints:0.473176, cup:0.24, cups:0.24, floz:0.0295735,\n // speed (base: m/s)\n mps:1, kph:0.277778, mph:0.44704, knot:0.514444, knots:0.514444,\n};\nconst from = (args.from || '''').toLowerCase().trim();\nconst to = (args.to || '''').toLowerCase().trim();\nconst value = Number(args.value);\n// Temperature special case\nfunction convertTemp(v, f, t) {\n let celsius;\n if (f===''celsius''||f===''c'') celsius=v;\n else if (f===''fahrenheit''||f===''f'') celsius=(v-32)*5/9;\n else if (f===''kelvin''||f===''k'') celsius=v-273.15;\n else return null;\n if (t===''celsius''||t===''c'') return celsius;\n if (t===''fahrenheit''||t===''f'') return celsius*9/5+32;\n if (t===''kelvin''||t===''k'') return celsius+273.15;\n return null;\n}\nconst tempUnits = [''c'',''f'',''k'',''celsius'',''fahrenheit'',''kelvin''];\nlet result;\nif (tempUnits.includes(from) || tempUnits.includes(to)) {\n result = convertTemp(value, from, to);\n if (result === null) return { error: `Cannot convert ${from} to ${to}` };\n} else {\n const fFactor = conversions[from];\n const tFactor = conversions[to];\n if (!fFactor) return { error: `Unknown unit: ${args.from}` };\n if (!tFactor) return { error: `Unknown unit: ${args.to}` };\n result = (value * fFactor) / tFactor;\n}\nreturn { value: args.value, from: args.from, to: args.to, result: +result.toPrecision(8) };"},"type":"function","function":{"name":"UnitConverter","description":"Convert a value between units of length, weight, temperature, volume, or speed.","parameters":{"type":"object","properties":{"value":{"type":"number","description":"Value to convert"},"from":{"type":"string","description":"Source unit e.g. km, lb, celsius, mph"},"to":{"type":"string","description":"Target unit e.g. miles, kg, fahrenheit, kph"}},"required":["value","from","to"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Mermaid Diagram',
+ 'mermaid-diagram',
+ 'Render a Mermaid.js diagram (flowchart, sequence, Gantt, etc.) in an iframe using the CDN build.',
+ 'developer',
+ '{"mermaid","diagram","flowchart","uml","developer"}',
+ '[{"clientDefinition":{"id":"mermaid-diagram-001","name":"MermaidDiagram","description":"Renders a Mermaid.js diagram in an iframe.","arguments":[{"name":"diagram","type":"string","description":"Mermaid diagram definition, e.g. graph TD; A-->B"}],"body":"const diagram = args.diagram || ''graph TD\\n A --> B'';\nfunction esc(s) { return s.replace(/&/g,''&amp;'').replace(/</g,''&lt;'').replace(/>/g,''&gt;'').replace(/\"/g,''&quot;''); }\nconst html = `<!DOCTYPE html><html><head><style>body{margin:0;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fafafa;font-family:system-ui,sans-serif}.mermaid{max-width:100%;padding:1rem}</style></head><body><pre class=\"mermaid\">${esc(diagram)}</pre><script type=\"module\">import mermaid from ''https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs''; mermaid.initialize({startOnLoad:true,theme:''default''});<\\/script></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"MermaidDiagram","description":"Render a Mermaid.js diagram. Use for flowcharts, sequence diagrams, Gantt charts, class diagrams, ER diagrams, or any diagram the user wants to visualise.","parameters":{"type":"object","properties":{"diagram":{"type":"string","description":"Mermaid diagram definition, e.g. \"graph TD; A-->B; B-->C\""}},"required":["diagram"]}}}]',
+ true,
+ null
+),
+
+(
+ 'CSV Table Viewer',
+ 'csv-table',
+ 'Render CSV input as a sortable HTML table.',
+ 'data',
+ '{"csv","table","data","spreadsheet"}',
+ '[{"clientDefinition":{"id":"csv-table-001","name":"CSVTable","description":"Renders CSV text as an interactive sortable HTML table.","arguments":[{"name":"csv","type":"string","description":"CSV text to display"}],"body":"const csv = args.csv || '''';\nfunction parseCSV(text) {\n return text.trim().split(''\\n'').map(line => {\n const cols = []; let cur = '''', inQ = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === ''\"'' && !inQ) { inQ = true; continue; }\n if (ch === ''\"'' && inQ && line[i+1] === ''\"'') { cur += ''\"''; i++; continue; }\n if (ch === ''\"'' && inQ) { inQ = false; continue; }\n if (ch === '','' && !inQ) { cols.push(cur); cur = ''''; continue; }\n cur += ch;\n }\n cols.push(cur);\n return cols;\n });\n}\nfunction esc(s) { return String(s).replace(/&/g,''&amp;'').replace(/</g,''&lt;'').replace(/>/g,''&gt;''); }\nconst rows = parseCSV(csv);\nif (!rows.length) return { contentType: ''text/html'', content: ''<p>No data</p>'' };\nconst [headers, ...data] = rows;\nconst thead = `<tr>${headers.map(h=>`<th onclick=\"sortBy(this)\" style=\"cursor:pointer\">${esc(h)} <span class=arr>▲</span></th>`).join('''')}</tr>`;\nconst tbody = data.map(r=>`<tr>${r.map(c=>`<td>${esc(c)}</td>`).join('''')}</tr>`).join('''');\nconst html = `<!DOCTYPE html><html><head><style>body{font-family:system-ui,sans-serif;padding:1rem;margin:0}table{border-collapse:collapse;width:100%;font-size:13px}th,td{border:1px solid #ddd;padding:6px 10px;text-align:left}th{background:#f0f0f0;user-select:none}tr:nth-child(even){background:#fafafa}tr:hover{background:#f0f7ff}.arr{font-size:10px;opacity:.6}</style></head><body><table><thead>${thead}</thead><tbody id=tb>${tbody}</tbody></table><script>let lastTh=null,asc=true;function sortBy(th){const idx=[...th.parentElement.children].indexOf(th);if(lastTh===th){asc=!asc}else{asc=true;if(lastTh)lastTh.querySelector(''.arr'').textContent=''▲''}lastTh=th;th.querySelector(''.arr'').textContent=asc?''▲'':''▼'';const tb=document.getElementById(''tb'');const rows=[...tb.rows];rows.sort((a,b)=>{const av=a.cells[idx]?.textContent||'''';const bv=b.cells[idx]?.textContent||'''';const an=parseFloat(av),bn=parseFloat(bv);return isNaN(an)||isNaN(bn)?av.localeCompare(bv)*(asc?1:-1):(an-bn)*(asc?1:-1)});rows.forEach(r=>tb.appendChild(r));}<\\/script></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"CSVTable","description":"Render CSV data as a sortable HTML table. Use when the user provides CSV data and wants to view or explore it.","parameters":{"type":"object","properties":{"csv":{"type":"string","description":"CSV text (first row is treated as headers)"}},"required":["csv"]}}}]',
+ true,
+ null
+),
+
+(
+ 'World Clock',
+ 'world-clock',
+ 'Show the current time in multiple timezones side by side.',
+ 'utility',
+ '{"clock","timezone","time","world"}',
+ '[{"clientDefinition":{"id":"world-clock-001","name":"WorldClock","description":"Shows current time in multiple timezones side by side.","arguments":[{"name":"timezones","type":"string","description":"Comma-separated IANA timezone names, e.g. America/New_York,Europe/London,Asia/Tokyo"}],"body":"const zones = (args.timezones || ''America/New_York,Europe/London,Asia/Tokyo,Australia/Sydney'').split('','').map(z=>z.trim()).filter(Boolean);\nfunction esc(s){return String(s).replace(/&/g,''&amp;'').replace(/</g,''&lt;'').replace(/>/g,''&gt;'');}\nfunction clockCard(tz) {\n const now = new Date();\n const time = now.toLocaleTimeString(''en-US'',{timeZone:tz,hour:''2-digit'',minute:''2-digit'',second:''2-digit'',hour12:true});\n const date = now.toLocaleDateString(''en-US'',{timeZone:tz,weekday:''short'',month:''short'',day:''numeric''});\n const city = tz.split(''/'').pop().replace(/_/g,'' '');\n return `<div class=card><div class=city>${esc(city)}</div><div class=tz>${esc(tz)}</div><div class=time id=\"t-${esc(tz.replace(/\\//g,''-''))}\">--:--:--</div><div class=date id=\"d-${esc(tz.replace(/\\//g,''-''))}\">${esc(date)}</div></div>`;\n}\nconst cards = zones.map(clockCard).join('''');\nconst tzJson = JSON.stringify(zones);\nconst html = `<!DOCTYPE html><html><head><style>body{margin:0;font-family:system-ui,sans-serif;background:#0f172a;color:#fff;display:flex;flex-wrap:wrap;gap:1rem;padding:1rem;box-sizing:border-box}.card{background:#1e293b;border-radius:12px;padding:1.25rem 1.5rem;min-width:160px;flex:1}.city{font-size:1.2rem;font-weight:600}.tz{font-size:11px;color:#64748b;margin:.2rem 0 .5rem}.time{font-size:2rem;font-weight:700;font-variant-numeric:tabular-nums;letter-spacing:-.5px}.date{font-size:12px;color:#94a3b8;margin-top:.25rem}</style></head><body>${cards}<script>const zones=${tzJson};function tick(){zones.forEach(tz=>{const now=new Date();const id=tz.replace(/\\//g,''-'');const tel=document.getElementById(''t-''+id);const del=document.getElementById(''d-''+id);if(tel)tel.textContent=now.toLocaleTimeString(''en-US'',{timeZone:tz,hour:''2-digit'',minute:''2-digit'',second:''2-digit'',hour12:true});if(del)del.textContent=now.toLocaleDateString(''en-US'',{timeZone:tz,weekday:''short'',month:''short'',day:''numeric''});})}tick();setInterval(tick,1000);<\\/script></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"WorldClock","description":"Display the current time in multiple timezones side by side, updating every second. Use for time zone comparisons or scheduling across regions.","parameters":{"type":"object","properties":{"timezones":{"type":"string","description":"Comma-separated IANA timezone names, e.g. \"America/New_York,Europe/London,Asia/Tokyo\""}},"required":["timezones"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Image from URL',
+ 'image-from-url',
+ 'Display an image from a URL in a resizable preview iframe.',
+ 'media',
+ '{"image","preview","url","media"}',
+ '[{"clientDefinition":{"id":"image-from-url-001","name":"ImageFromURL","description":"Renders an image from a URL in a resizable preview.","arguments":[{"name":"url","type":"string","description":"Image URL to display"},{"name":"alt","type":"string","description":"Alt text for the image"}],"body":"const url = args.url || '''';\nconst alt = args.alt || ''Image'';\nfunction esc(s){return String(s).replace(/&/g,''&amp;'').replace(/</g,''&lt;'').replace(/>/g,''&gt;'').replace(/\"/g,''&quot;'');}\nconst html = `<!DOCTYPE html><html><head><style>body{margin:0;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;background:#1a1a1a;padding:1rem;box-sizing:border-box}img{max-width:100%;max-height:90vh;object-fit:contain;border-radius:6px;box-shadow:0 4px 24px rgba(0,0,0,.5)}.url{color:#888;font-family:monospace;font-size:11px;margin-top:.75rem;word-break:break-all;max-width:600px;text-align:center}</style></head><body><img src=\"${esc(url)}\" alt=\"${esc(alt)}\" /><div class=url>${esc(url)}</div></body></html>`;\nreturn { contentType: ''text/html'', content: html };"},"type":"function","function":{"name":"ImageFromURL","description":"Display an image from a URL in a full preview. Use when the user provides an image URL and wants to see it rendered.","parameters":{"type":"object","properties":{"url":{"type":"string","description":"Direct URL to the image"},"alt":{"type":"string","description":"Descriptive alt text"}},"required":["url"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Base64 Codec',
+ 'base64-codec',
+ 'Encode or decode text to/from Base64.',
+ 'developer',
+ '{"base64","encode","decode","codec"}',
+ '[{"clientDefinition":{"id":"base64-codec-001","name":"Base64Codec","description":"Encodes or decodes text using Base64.","arguments":[{"name":"input","type":"string","description":"Text or Base64 string to process"},{"name":"mode","type":"string","description":"encode or decode (default: encode)"}],"body":"const input = args.input || '''';\nconst mode = (args.mode || ''encode'').toLowerCase();\nlet output, error = '''';\ntry {\n if (mode === ''decode'') {\n output = atob(input.replace(/\\s/g, ''''));\n } else {\n output = btoa(unescape(encodeURIComponent(input)));\n }\n} catch (e) {\n error = e.message;\n output = '''';\n}\nreturn { mode, input, output: output || '''', ...(error ? { error } : {}) };"},"type":"function","function":{"name":"Base64Codec","description":"Encode text to Base64 or decode Base64 back to text.","parameters":{"type":"object","properties":{"input":{"type":"string","description":"Text to encode, or Base64 string to decode"},"mode":{"type":"string","enum":["encode","decode"],"description":"\"encode\" converts text to Base64; \"decode\" converts Base64 to text. Default: encode"}},"required":["input"]}}}]',
+ true,
+ null
+),
+
+(
+ 'Word Counter',
+ 'word-counter',
+ 'Count words, characters, sentences, and estimated reading time for any text.',
+ 'productivity',
+ '{"words","count","text","writing","productivity"}',
+ '[{"clientDefinition":{"id":"word-counter-001","name":"WordCounter","description":"Counts words, characters, sentences, and reading time.","arguments":[{"name":"text","type":"string","description":"Text to analyse"}],"body":"const text = args.text || '''';\nconst words = text.trim() ? text.trim().split(/\\s+/).length : 0;\nconst chars = text.length;\nconst charsNoSpace = text.replace(/\\s/g, '''').length;\nconst sentences = text.trim() ? (text.match(/[.!?]+/g) || []).length || 1 : 0;\nconst paragraphs = text.trim() ? text.split(/\\n\\s*\\n/).filter(p=>p.trim()).length || 1 : 0;\nconst readingTimeSec = Math.ceil(words / (238 / 60)); // 238 wpm average\nconst minutes = Math.floor(readingTimeSec / 60);\nconst seconds = readingTimeSec % 60;\nconst readingTime = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;\nreturn { words, characters: chars, charactersNoSpaces: charsNoSpace, sentences, paragraphs, readingTime };"},"type":"function","function":{"name":"WordCounter","description":"Count words, characters, sentences, paragraphs, and estimated reading time for a piece of text.","parameters":{"type":"object","properties":{"text":{"type":"string","description":"Text to analyse"}},"required":["text"]}}}]',
+ true,
+ null
+)
+
+on conflict (slug) do nothing;
+
+commit;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 6ee7b656a..6659171bd 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -702,3 +702,52 @@ create table if not exists pumpfun_signals (
create index if not exists pumpfun_signals_wallet on pumpfun_signals(wallet, seen_at desc);
create index if not exists pumpfun_signals_agent on pumpfun_signals(agent_asset, seen_at desc) where agent_asset is not null;
create index if not exists pumpfun_signals_kind on pumpfun_signals(kind, seen_at desc);
+
+-- ── marketplace_skills — community skill registry ────────────────────────────
+-- schema_json: jsonb array matching the ToolPack schema used in chat/src/tools.js.
+-- Each element: { clientDefinition: {...}, type, function: { name, description, parameters } }
+create table if not exists marketplace_skills (
+ id uuid primary key default gen_random_uuid(),
+ author_id uuid references users(id) on delete set null,
+ name text not null,
+ slug text not null unique,
+ description text not null,
+ category text not null default 'general',
+ schema_json jsonb not null,
+ tags text[] not null default '{}',
+ is_public boolean not null default true,
+ install_count integer not null default 0,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists marketplace_skills_category_idx on marketplace_skills(category);
+create index if not exists marketplace_skills_author_idx on marketplace_skills(author_id);
+create index if not exists marketplace_skills_popular_idx on marketplace_skills(install_count desc);
+create index if not exists marketplace_skills_new_idx on marketplace_skills(created_at desc);
+
+do $$ begin
+ create trigger marketplace_skills_set_updated_at before update on marketplace_skills
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+-- ── skill_installs — tracks which users have installed which skills ───────────
+create table if not exists skill_installs (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid references users(id) on delete cascade,
+ skill_id uuid references marketplace_skills(id) on delete cascade,
+ installed_at timestamptz not null default now(),
+ unique (user_id, skill_id)
+);
+
+create index if not exists skill_installs_user_idx on skill_installs(user_id);
+
+-- ── skill_ratings ────────────────────────────────────────────────────────────
+create table if not exists skill_ratings (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid references users(id) on delete cascade,
+ skill_id uuid references marketplace_skills(id) on delete cascade,
+ rating smallint not null check (rating between 1 and 5),
+ created_at timestamptz not null default now(),
+ unique (user_id, skill_id)
+);
diff --git a/api/agents/[id]/pricing/[skill].js b/api/agents/[id]/pricing/[skill].js
index 265065e5d..d4b310cf7 100644
--- a/api/agents/[id]/pricing/[skill].js
+++ b/api/agents/[id]/pricing/[skill].js
@@ -25,10 +25,15 @@ async function resolveUserId(req) {
// PUT /api/agents/:id/pricing/:skill — create or update a skill price (owner only)
// DELETE /api/agents/:id/pricing/:skill — soft-delete; ?hard=true for permanent removal
-export default wrap(async (req, res, id, skill) => {
+export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'PUT,DELETE,OPTIONS', credentials: true })) return;
if (!method(req, res, ['PUT', 'DELETE'])) return;
+ const urlParts = new URL(req.url, 'http://x').pathname.split('/').filter(Boolean);
+ // /api/agents/{id}/pricing/{skill}
+ const id = urlParts[2];
+ const skill = urlParts[4];
+
if (!skill || !SKILL_RE.test(skill)) {
return error(res, 400, 'validation_error', 'skill must be alphanumeric + hyphens, max 64 chars');
}
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index 2c71692d5..70b6c8586 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -191,7 +191,11 @@ async function handleDetail(req, res, id) {
`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
- const auth = await resolveAuth(req).catch(() => null);
+ const [auth, priceRows] = await Promise.all([
+ resolveAuth(req).catch(() => null),
+ sql`SELECT skill, currency_mint, chain, amount FROM agent_skill_prices WHERE agent_id = ${id} AND is_active = true`,
+ ]);
+
let bookmarked = false;
if (auth) {
const [b] =
@@ -199,10 +203,14 @@ async function handleDetail(req, res, id) {
bookmarked = !!b;
}
+ const skill_prices = Object.fromEntries(
+ priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),
+ );
+
return json(
res,
200,
- { data: { agent: toDetail(row), bookmarked } },
+ { data: { agent: { ...toDetail(row), skill_prices }, bookmarked } },
{ 'cache-control': 'public, max-age=15' },
);
}
diff --git a/api/skills/[id].js b/api/skills/[id].js
new file mode 100644
index 000000000..35c6edce8
--- /dev/null
+++ b/api/skills/[id].js
@@ -0,0 +1,167 @@
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const updateSchema = z.object({
+ name: z.string().trim().min(2).max(80).optional(),
+ description: z.string().trim().max(500).optional(),
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
+ is_public: z.boolean().optional(),
+ schema_json: z
+ .array(
+ z
+ .object({
+ function: z
+ .object({ name: z.string(), parameters: z.record(z.any()) })
+ .passthrough(),
+ })
+ .passthrough(),
+ )
+ .min(1)
+ .optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT', 'DELETE'])) return;
+
+ const id = req.query?.id;
+ if (!id || !UUID_RE.test(id)) return error(res, 404, 'not_found', 'skill not found');
+
+ if (req.method === 'GET') return handleGet(req, res, id);
+ if (req.method === 'PUT') return handleUpdate(req, res, id);
+ return handleDelete(req, res, id);
+});
+
+async function resolveOptionalAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, plan: session.plan };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId, plan: null };
+ return null;
+}
+
+function toSkill(row, { includeInstalled = false } = {}) {
+ const skill = {
+ id: row.id,
+ name: row.name,
+ slug: row.slug,
+ description: row.description,
+ category: row.category,
+ tags: row.tags || [],
+ install_count: row.install_count || 0,
+ avg_rating: Number(row.avg_rating) || 0,
+ rating_count: row.rating_count || 0,
+ schema_json: row.schema_json,
+ author: row.author_id
+ ? { id: row.author_id, display_name: row.author_display_name }
+ : null,
+ created_at: row.created_at,
+ };
+ if (includeInstalled) skill.installed = !!row.installed;
+ return skill;
+}
+
+async function handleGet(req, res, id) {
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const auth = await resolveOptionalAuth(req);
+ const userId = auth?.userId ?? null;
+
+ const [row] = await sql`
+ SELECT
+ ms.*,
+ u.display_name AS author_display_name,
+ ROUND(COALESCE(AVG(sr.rating), 0)::numeric, 1)::float AS avg_rating,
+ COUNT(sr.rating)::int AS rating_count,
+ CASE WHEN ${userId}::uuid IS NOT NULL
+ THEN EXISTS(
+ SELECT 1 FROM skill_installs si
+ WHERE si.skill_id = ms.id AND si.user_id = ${userId}::uuid
+ )
+ ELSE NULL END AS installed
+ FROM marketplace_skills ms
+ LEFT JOIN users u ON u.id = ms.author_id AND u.deleted_at IS NULL
+ LEFT JOIN skill_ratings sr ON sr.skill_id = ms.id
+ WHERE ms.id = ${id} AND ms.is_public = true
+ GROUP BY ms.id, ms.author_id, u.display_name
+ `;
+
+ if (!row) return error(res, 404, 'not_found', 'skill not found');
+
+ return json(res, 200, { skill: toSkill(row, { includeInstalled: userId != null }) });
+}
+
+async function handleUpdate(req, res, id) {
+ const auth = await resolveOptionalAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.chatUser(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [skill] = await sql`
+ SELECT id, author_id FROM marketplace_skills WHERE id = ${id}
+ `;
+ if (!skill) return error(res, 404, 'not_found', 'skill not found');
+
+ if (skill.author_id !== auth.userId) {
+ // Fallback: check admin status via DB (handles bearer auth where plan isn't cached)
+ const [u] = await sql`SELECT plan FROM users WHERE id = ${auth.userId} AND deleted_at IS NULL`;
+ if (u?.plan !== 'admin') return error(res, 403, 'forbidden', 'not your skill');
+ }
+
+ const body = parse(updateSchema, await readJson(req));
+ if (Object.keys(body).length === 0) {
+ return error(res, 400, 'validation_error', 'no fields to update');
+ }
+
+ const updates = [];
+ if (body.name !== undefined) updates.push(sql`name = ${body.name}`);
+ if (body.description !== undefined) updates.push(sql`description = ${body.description}`);
+ if (body.tags !== undefined) updates.push(sql`tags = ${body.tags}`);
+ if (body.is_public !== undefined) updates.push(sql`is_public = ${body.is_public}`);
+ if (body.schema_json !== undefined)
+ updates.push(sql`schema_json = ${JSON.stringify(body.schema_json)}::jsonb`);
+ updates.push(sql`updated_at = now()`);
+
+ const setClauses = updates.reduce((acc, frag) => sql`${acc}, ${frag}`);
+
+ const [updated] = await sql`
+ UPDATE marketplace_skills SET ${setClauses} WHERE id = ${id} RETURNING *
+ `;
+
+ const [author] = updated.author_id
+ ? await sql`SELECT id, display_name FROM users WHERE id = ${updated.author_id}`
+ : [null];
+ updated.author_display_name = author?.display_name ?? null;
+ updated.avg_rating = 0;
+ updated.rating_count = 0;
+
+ return json(res, 200, { skill: toSkill(updated) });
+}
+
+async function handleDelete(req, res, id) {
+ const auth = await resolveOptionalAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.chatUser(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [skill] = await sql`
+ SELECT id, author_id FROM marketplace_skills WHERE id = ${id}
+ `;
+ if (!skill) return error(res, 404, 'not_found', 'skill not found');
+ if (skill.author_id !== auth.userId) return error(res, 403, 'forbidden', 'not your skill');
+
+ // skill_installs and skill_ratings cascade-delete on marketplace_skills delete
+ await sql`DELETE FROM marketplace_skills WHERE id = ${id}`;
+
+ res.statusCode = 204;
+ res.end();
+}
diff --git a/api/skills/[id]/install.js b/api/skills/[id]/install.js
new file mode 100644
index 000000000..8db0e3606
--- /dev/null
+++ b/api/skills/[id]/install.js
@@ -0,0 +1,54 @@
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, error, method, wrap } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST', 'DELETE'])) return;
+
+ const id = req.query?.id;
+ if (!id || !UUID_RE.test(id)) return error(res, 404, 'not_found', 'skill not found');
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.chatUser(userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [skill] = await sql`SELECT id FROM marketplace_skills WHERE id = ${id} AND is_public = true`;
+ if (!skill) return error(res, 404, 'not_found', 'skill not found');
+
+ if (req.method === 'POST') {
+ // Atomically insert and increment only if the row is new
+ await sql`
+ WITH ins AS (
+ INSERT INTO skill_installs (user_id, skill_id)
+ VALUES (${userId}, ${id})
+ ON CONFLICT (user_id, skill_id) DO NOTHING
+ RETURNING id
+ )
+ UPDATE marketplace_skills
+ SET install_count = install_count + 1
+ WHERE marketplace_skills.id = ${id} AND EXISTS (SELECT 1 FROM ins)
+ `;
+ return json(res, 200, { installed: true });
+ }
+
+ // DELETE — uninstall
+ await sql`
+ WITH del AS (
+ DELETE FROM skill_installs
+ WHERE user_id = ${userId} AND skill_id = ${id}
+ RETURNING id
+ )
+ UPDATE marketplace_skills
+ SET install_count = GREATEST(0, install_count - 1)
+ WHERE marketplace_skills.id = ${id} AND EXISTS (SELECT 1 FROM del)
+ `;
+ return json(res, 200, { installed: false });
+});
diff --git a/api/skills/[id]/rate.js b/api/skills/[id]/rate.js
new file mode 100644
index 000000000..684a518b8
--- /dev/null
+++ b/api/skills/[id]/rate.js
@@ -0,0 +1,52 @@
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, error, method, readJson, wrap } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const rateSchema = z.object({
+ rating: z.number().int().min(1).max(5),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = req.query?.id;
+ if (!id || !UUID_RE.test(id)) return error(res, 404, 'not_found', 'skill not found');
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.chatUser(userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [skill] = await sql`SELECT id FROM marketplace_skills WHERE id = ${id} AND is_public = true`;
+ if (!skill) return error(res, 404, 'not_found', 'skill not found');
+
+ const { rating } = parse(rateSchema, await readJson(req));
+
+ await sql`
+ INSERT INTO skill_ratings (user_id, skill_id, rating)
+ VALUES (${userId}, ${id}, ${rating})
+ ON CONFLICT (user_id, skill_id) DO UPDATE SET rating = EXCLUDED.rating, created_at = now()
+ `;
+
+ const [stats] = await sql`
+ SELECT
+ ROUND(AVG(rating)::numeric, 1)::float AS avg_rating,
+ COUNT(*)::int AS rating_count
+ FROM skill_ratings
+ WHERE skill_id = ${id}
+ `;
+
+ return json(res, 200, {
+ avg_rating: Number(stats.avg_rating) || 0,
+ rating_count: stats.rating_count || 0,
+ });
+});
diff --git a/api/skills/categories.js b/api/skills/categories.js
new file mode 100644
index 000000000..b9a38199a
--- /dev/null
+++ b/api/skills/categories.js
@@ -0,0 +1,27 @@
+import { sql } from '../_lib/db.js';
+import { json, error, method, wrap } from '../_lib/http.js';
+
+function toLabel(slug) {
+ return slug.charAt(0).toUpperCase() + slug.slice(1);
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET'])) return;
+
+ const rows = await sql`
+ select category, count(*)::int as count
+ from marketplace_skills
+ where is_public = true
+ group by category
+ having count(*) > 0
+ order by count desc
+ `;
+
+ const categories = rows.map((r) => ({
+ slug: r.category,
+ label: toLabel(r.category),
+ count: r.count,
+ }));
+
+ json(res, 200, { categories }, { 'cache-control': 'public, max-age=60' });
+});
diff --git a/api/skills/index.js b/api/skills/index.js
new file mode 100644
index 000000000..d5f40d7a6
--- /dev/null
+++ b/api/skills/index.js
@@ -0,0 +1,225 @@
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const VALID_SORTS = new Set(['popular', 'new', 'az']);
+
+const skillSlug = z
+ .string()
+ .trim()
+ .min(1)
+ .max(60)
+ .regex(/^[a-z0-9-]+$/, 'slug must be lowercase alphanumeric with hyphens');
+
+const publishSchema = z.object({
+ name: z.string().trim().min(2).max(80),
+ slug: skillSlug,
+ description: z.string().trim().max(500),
+ category: z.string().trim().min(1).max(50).default('general'),
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).default([]),
+ schema_json: z
+ .array(
+ z
+ .object({
+ function: z
+ .object({ name: z.string(), parameters: z.record(z.any()) })
+ .passthrough(),
+ })
+ .passthrough(),
+ )
+ .min(1),
+ is_public: z.boolean().default(true),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'GET') return handleList(req, res);
+ return handlePublish(req, res);
+});
+
+async function resolveOptionalAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, plan: session.plan };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId, plan: null };
+ return null;
+}
+
+function toSkill(row, { includeInstalled = false, includeSchema = false } = {}) {
+ const skill = {
+ id: row.id,
+ name: row.name,
+ slug: row.slug,
+ description: row.description,
+ category: row.category,
+ tags: row.tags || [],
+ install_count: row.install_count || 0,
+ avg_rating: Number(row.avg_rating) || 0,
+ rating_count: row.rating_count || 0,
+ author: row.author_id
+ ? { id: row.author_id, display_name: row.author_display_name }
+ : null,
+ created_at: row.created_at,
+ };
+ if (includeInstalled) skill.installed = !!row.installed;
+ if (includeSchema) skill.schema_json = row.schema_json;
+ return skill;
+}
+
+async function handleList(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const q = (url.searchParams.get('q') || '').trim().slice(0, 80) || null;
+ const category = url.searchParams.get('category') || null;
+ const sortParam = url.searchParams.get('sort') || '';
+ const sort = VALID_SORTS.has(sortParam) ? sortParam : 'popular';
+ const cursor = url.searchParams.get('cursor') || null;
+ const limit = Math.min(50, Math.max(1, Number(url.searchParams.get('limit')) || 20));
+ const installedOnly = url.searchParams.get('installed') === 'true';
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const auth = await resolveOptionalAuth(req);
+ const userId = auth?.userId ?? null;
+
+ if (installedOnly && !userId) {
+ return error(res, 401, 'unauthorized', 'sign in required to filter by installed');
+ }
+
+ if (cursor && !UUID_RE.test(cursor)) {
+ return error(res, 400, 'validation_error', 'invalid cursor');
+ }
+
+ const qLike = q ? `%${q}%` : null;
+
+ // Fetch cursor pivot values for keyset pagination
+ let cursorInstallCount = null;
+ let cursorCreatedAt = null;
+ let cursorName = null;
+ if (cursor) {
+ const [cr] = await sql`
+ SELECT install_count, created_at, name
+ FROM marketplace_skills
+ WHERE id = ${cursor} AND is_public = true
+ `;
+ if (cr) {
+ cursorInstallCount = cr.install_count;
+ cursorCreatedAt = cr.created_at;
+ cursorName = cr.name;
+ }
+ }
+
+ // Build sort-specific ORDER BY and cursor condition as sql fragments
+ let orderBy;
+ let cursorCond;
+ if (sort === 'new') {
+ orderBy = sql`ms.created_at DESC, ms.id DESC`;
+ cursorCond =
+ cursor && cursorCreatedAt != null
+ ? sql`AND (ms.created_at < ${cursorCreatedAt} OR (ms.created_at = ${cursorCreatedAt} AND ms.id::text < ${cursor}))`
+ : sql``;
+ } else if (sort === 'az') {
+ orderBy = sql`ms.name ASC, ms.id ASC`;
+ cursorCond =
+ cursor && cursorName != null
+ ? sql`AND (ms.name > ${cursorName} OR (ms.name = ${cursorName} AND ms.id::text > ${cursor}))`
+ : sql``;
+ } else {
+ // popular (default)
+ orderBy = sql`ms.install_count DESC, ms.id DESC`;
+ cursorCond =
+ cursor && cursorInstallCount != null
+ ? sql`AND (ms.install_count < ${cursorInstallCount} OR (ms.install_count = ${cursorInstallCount} AND ms.id::text < ${cursor}))`
+ : sql``;
+ }
+
+ const rows = await sql`
+ SELECT
+ ms.id, ms.name, ms.slug, ms.description, ms.category, ms.tags,
+ ms.install_count, ms.created_at, ms.author_id,
+ u.display_name AS author_display_name,
+ ROUND(COALESCE(AVG(sr.rating), 0)::numeric, 1)::float AS avg_rating,
+ COUNT(sr.rating)::int AS rating_count,
+ CASE WHEN ${userId}::uuid IS NOT NULL
+ THEN EXISTS(
+ SELECT 1 FROM skill_installs si
+ WHERE si.skill_id = ms.id AND si.user_id = ${userId}::uuid
+ )
+ ELSE NULL END AS installed
+ FROM marketplace_skills ms
+ LEFT JOIN users u ON u.id = ms.author_id AND u.deleted_at IS NULL
+ LEFT JOIN skill_ratings sr ON sr.skill_id = ms.id
+ WHERE ms.is_public = true
+ ${cursorCond}
+ AND (${category}::text IS NULL OR ms.category = ${category})
+ AND (
+ ${qLike}::text IS NULL
+ OR ms.name ILIKE ${qLike}
+ OR ms.description ILIKE ${qLike}
+ OR EXISTS (SELECT 1 FROM unnest(ms.tags) t WHERE t ILIKE ${qLike})
+ )
+ AND (
+ NOT ${installedOnly}
+ OR EXISTS(
+ SELECT 1 FROM skill_installs
+ WHERE skill_id = ms.id AND user_id = ${userId}::uuid
+ )
+ )
+ GROUP BY ms.id, ms.author_id, u.display_name
+ ORDER BY ${orderBy}
+ LIMIT ${limit + 1}
+ `;
+
+ const hasMore = rows.length > limit;
+ const skills = rows.slice(0, limit).map((r) => toSkill(r, { includeInstalled: userId != null }));
+
+ return json(res, 200, {
+ skills,
+ next_cursor: hasMore ? rows[limit - 1].id : null,
+ });
+}
+
+async function handlePublish(req, res) {
+ const auth = await resolveOptionalAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.chatUser(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(publishSchema, await readJson(req));
+
+ let row;
+ try {
+ [row] = await sql`
+ INSERT INTO marketplace_skills (author_id, name, slug, description, category, tags, schema_json, is_public)
+ VALUES (
+ ${auth.userId},
+ ${body.name},
+ ${body.slug},
+ ${body.description},
+ ${body.category},
+ ${body.tags},
+ ${JSON.stringify(body.schema_json)}::jsonb,
+ ${body.is_public}
+ )
+ RETURNING *
+ `;
+ } catch (err) {
+ if (err.code === '23505') return error(res, 409, 'conflict', 'slug already taken');
+ throw err;
+ }
+
+ const [author] = await sql`SELECT id, display_name FROM users WHERE id = ${auth.userId}`;
+ row.author_id = author.id;
+ row.author_display_name = author.display_name;
+ row.avg_rating = 0;
+ row.rating_count = 0;
+
+ return json(res, 201, { skill: toSkill(row, { includeInstalled: true, includeSchema: true }) });
+}
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index f87b79451..27e40020b 100644
--- a/chat/src/App.svelte
+++ b/chat/src/App.svelte
@@ -76,6 +76,7 @@
import WebsiteFlow from './manus/flows/WebsiteFlow.svelte';
import DesktopFlow from './manus/flows/DesktopFlow.svelte';
import RevenueDashboard from './manus/pages/RevenueDashboard.svelte';
+ import SkillsMarketplaceModal from './SkillsMarketplaceModal.svelte';
marked.use(
markedKatex({
@@ -1843,6 +1844,17 @@
</div>
{/if}
</div>
+ <button
+ class="relative flex items-center gap-1 rounded-full p-3 transition-colors hover:bg-gray-100"
+ on:click={() => (showSkillsMarketplace = true)}
+ title="Skills Marketplace"
+ >
+ <Icon icon={feGrid} strokeWidth={3} class="m-auto h-4 w-4 text-slate-700" />
+ <span class="hidden sm:inline text-[12px] text-slate-700">Skills</span>
+ {#if $toolSchema.length > 0}
+ <span class="ml-1 rounded-full bg-indigo-500 px-1.5 py-0.5 text-[10px] text-white">{$toolSchema.length}</span>
+ {/if}
+ </button>
<button
data-trigger="knobs"
class="flex rounded-full p-3 transition-colors hover:bg-gray-100"
@@ -2021,6 +2033,8 @@
}}
/>
+<SkillsMarketplaceModal bind:open={showSkillsMarketplace} />
+
{#if innerWidth <= 1215 && !$config.explicitToolView}
<Modal
bind:open={toolcallModalOpen}
@@ -2132,40 +2146,42 @@
{/if}
{/if}
-<style lang="postcss">
+<style>
:global(.standalone .input-floating) {
- @apply bottom-[32px];
+ bottom: 32px;
}
:global(.standalone .scrollable) {
- @apply pb-[100px];
+ padding-bottom: 100px;
}
:global(.standalone .settings-trigger-container) {
- @apply pb-10;
+ padding-bottom: 2.5rem;
}
:global(.markdown.prose :where(p):not(:where([class~='not-prose'], [class~='not-prose'] *))) {
- @apply my-3;
+ margin-top: 0.75rem;
+ margin-bottom: 0.75rem;
}
:global(
.markdown.prose
:where(.prose > :first-child):not(:where([class~='not-prose'], [class~='not-prose'] *))
) {
- @apply mt-0;
+ margin-top: 0;
}
:global(
.markdown.prose
:where(.prose > :last-child):not(:where([class~='not-prose'], [class~='not-prose'] *))
) {
- @apply mb-0;
+ margin-bottom: 0;
}
:global(.markdown.prose :where(a):not(:where([class~='not-prose'], [class~='not-prose'] *))) {
- @apply text-ink;
+ color: #1A1A1A;
}
:global(.markdown.prose :where(pre):not(:where([class~='not-prose'], [class~='not-prose'] *))) {
- @apply bg-paper-deep border-rule;
+ background-color: #EBE8E0;
+ border-color: #E5E3DC;
}
</style>
diff --git a/chat/src/NotificationBell.svelte b/chat/src/NotificationBell.svelte
new file mode 100644
index 000000000..98127ac6c
--- /dev/null
+++ b/chat/src/NotificationBell.svelte
@@ -0,0 +1,135 @@
+<script>
+ import { onMount } from 'svelte';
+ import { currentUser } from './stores.js';
+ import Icon from './Icon.svelte';
+ import { feBell } from './feather.js';
+
+ let notifications = [];
+ let unreadCount = 0;
+ let open = false;
+ let loading = false;
+ let el;
+
+ async function fetchNotifications() {
+ if (!$currentUser) return;
+ try {
+ const res = await fetch('/api/notifications', { credentials: 'include' });
+ if (!res.ok) return;
+ const data = await res.json();
+ notifications = data.notifications ?? [];
+ unreadCount = data.unread_count ?? 0;
+ } catch {
+ // silent
+ }
+ }
+
+ async function markAllRead() {
+ try {
+ await fetch('/api/notifications/read-all', { method: 'POST', credentials: 'include' });
+ notifications = notifications.map((n) => ({ ...n, read_at: n.read_at ?? new Date().toISOString() }));
+ unreadCount = 0;
+ } catch {
+ // silent
+ }
+ }
+
+ function toggle() {
+ open = !open;
+ if (open) fetchNotifications();
+ }
+
+ function handleWindowClick(e) {
+ if (el && !el.contains(e.target)) open = false;
+ }
+
+ function formatPayload(n) {
+ if (n.type === 'payment_received') {
+ const amt = (n.payload.net_amount / 1_000_000).toFixed(2);
+ return `${n.payload.agent_name ?? 'Agent'} received ${amt} USDC for ${n.payload.skill}`;
+ }
+ if (n.type === 'withdrawal_completed') {
+ const amt = (n.payload.amount / 1_000_000).toFixed(2);
+ return `Withdrawal of ${amt} USDC sent`;
+ }
+ if (n.type === 'withdrawal_failed') {
+ const amt = (n.payload.amount / 1_000_000).toFixed(2);
+ return `Withdrawal of ${amt} USDC failed`;
+ }
+ return n.type;
+ }
+
+ function formatTime(iso) {
+ const d = new Date(iso);
+ const now = new Date();
+ const diffMs = now - d;
+ const diffMin = Math.floor(diffMs / 60000);
+ if (diffMin < 1) return 'just now';
+ if (diffMin < 60) return `${diffMin}m ago`;
+ const diffH = Math.floor(diffMin / 60);
+ if (diffH < 24) return `${diffH}h ago`;
+ return d.toLocaleDateString();
+ }
+
+ onMount(() => {
+ fetchNotifications();
+ const interval = setInterval(() => {
+ if (!open && $currentUser) fetchNotifications();
+ }, 60_000);
+ return () => clearInterval(interval);
+ });
+</script>
+
+<svelte:window on:click={handleWindowClick} on:focus={() => { if ($currentUser) fetchNotifications(); }} />
+
+{#if $currentUser}
+<div class="relative" bind:this={el}>
+ <button
+ class="relative rounded p-2 text-ink hover:bg-paper-deep"
+ aria-label="Notifications"
+ on:click={toggle}
+ >
+ <Icon icon={feBell} class="h-5 w-5" />
+ {#if unreadCount > 0}
+ <span class="absolute right-1 top-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white">
+ {unreadCount > 9 ? '9+' : unreadCount}
+ </span>
+ {/if}
+ </button>
+
+ {#if open}
+ <div class="absolute right-0 top-full z-50 mt-2 w-80 rounded-lg border border-rule bg-paper shadow-lg">
+ <div class="flex items-center justify-between border-b border-rule px-4 py-2">
+ <span class="text-sm font-semibold text-ink">Notifications</span>
+ {#if unreadCount > 0}
+ <button
+ class="text-xs text-ink-soft hover:text-ink"
+ on:click={markAllRead}
+ >Mark all read</button>
+ {/if}
+ </div>
+
+ {#if notifications.length === 0}
+ <p class="px-4 py-6 text-center text-sm text-ink-soft">No notifications yet</p>
+ {:else}
+ <ul class="max-h-72 overflow-y-auto">
+ {#each notifications as n (n.id)}
+ <li class="border-b border-rule last:border-0 {n.read_at ? 'opacity-60' : ''}">
+ <div class="flex items-start gap-2 px-4 py-3">
+ {#if !n.read_at}
+ <span class="mt-1.5 h-2 w-2 shrink-0 rounded-full bg-blue-500"></span>
+ {:else}
+ <span class="mt-1.5 h-2 w-2 shrink-0"></span>
+ {/if}
+ <div class="min-w-0">
+ <p class="text-sm text-ink">{formatPayload(n)}</p>
+ <p class="text-xs text-ink-soft">{formatTime(n.created_at)}</p>
+ </div>
+ </div>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+ {/if}
+</div>
+{/if}
diff --git a/chat/src/SkillsMarketplaceModal.svelte b/chat/src/SkillsMarketplaceModal.svelte
index c673ba151..64d3e8c6c 100644
--- a/chat/src/SkillsMarketplaceModal.svelte
+++ b/chat/src/SkillsMarketplaceModal.svelte
@@ -15,9 +15,14 @@
let page = null;
let hasMore = false;
let sort = 'popular';
- let expandedSkillId = null;
let installPending = {};
- let ratingPending = {};
+
+ // Detail expansion state
+ let expandedSkillId = null;
+ let detailLoading = false;
+ let detail = null;
+ let userRating = null;
+ let hoverStar = 0;
// Publish state
let publishForm = {
@@ -50,12 +55,55 @@
let schemaValid = null;
let schemaErrorMsg = '';
- $: categories = [...new Set(skills.map((s) => s.category).filter(Boolean))];
+ let categories = [];
+
+ async function loadCategories() {
+ try {
+ const res = await fetch('/api/skills/categories');
+ if (!res.ok) return;
+ const data = await res.json();
+ categories = data.categories || [];
+ } catch {
+ // leave categories empty
+ }
+ }
+
+ // helpers
+
+ function relativeDate(iso) {
+ const diff = Date.now() - new Date(iso).getTime();
+ const days = Math.floor(diff / 86400000);
+ if (days === 0) return 'today';
+ if (days === 1) return 'yesterday';
+ if (days < 30) return `${days} days ago`;
+ if (days < 365) return `${Math.floor(days / 30)} months ago`;
+ return `${Math.floor(days / 365)} years ago`;
+ }
function isInstalled(skill) {
return $toolSchema.some((g) => g.name === skill.name);
}
+ function formatRating(avg, count) {
+ if (!count) return 'No ratings yet';
+ return `⭐ ${Number(avg).toFixed(1)} (${count})`;
+ }
+
+ function schemaPreview(schema_json) {
+ if (!Array.isArray(schema_json) || schema_json.length === 0) return null;
+ const first = schema_json[0];
+ const fn = first?.function ?? first;
+ const params = Object.keys(fn?.parameters?.properties ?? {});
+ return {
+ name: fn?.name ?? '?',
+ description: fn?.description ?? '',
+ params,
+ extra: schema_json.length - 1
+ };
+ }
+
+ // skills API
+
async function loadSkills(reset = false) {
loading = true;
try {
@@ -99,34 +147,43 @@
loadSkills(true);
}
- async function toggleInstall(skill) {
- if (!$currentUser) return;
+ // install / uninstall
+
+ async function toggleInstall(skill, e) {
+ e?.stopPropagation();
+ if (!$currentUser) { notify('Sign in to install skills', 'info'); return; }
installPending = { ...installPending, [skill.id]: true };
const wasInstalled = isInstalled(skill);
- // Optimistic update
if (!wasInstalled) {
- $toolSchema = [...$toolSchema, { name: skill.name, schema: skill.schema_json }];
+ const schema = detail?.id === skill.id ? (detail.schema_json ?? []) : (skill.schema_json ?? []);
+ $toolSchema = [...$toolSchema, { name: skill.name, schema }];
} else {
$toolSchema = $toolSchema.filter((g) => g.name !== skill.name);
}
try {
const method = wasInstalled ? 'DELETE' : 'POST';
- const res = await fetch(`/api/skills/${skill.id}/install`, {
- method,
- credentials: 'include'
- });
+ const res = await fetch(`/api/skills/${skill.id}/install`, { method, credentials: 'include' });
if (!res.ok) throw new Error('Request failed');
+ if (!wasInstalled) {
+ const data = await res.json().catch(() => null);
+ if (data?.schema_json) {
+ $toolSchema = [
+ ...$toolSchema.filter((g) => g.name !== skill.name),
+ { name: skill.name, schema: data.schema_json }
+ ];
+ }
+ }
skills = skills.map((s) =>
s.id === skill.id
? { ...s, install_count: (s.install_count || 0) + (wasInstalled ? -1 : 1) }
: s
);
+ if (detail?.id === skill.id) detail = { ...detail, is_installed: !wasInstalled };
} catch (e) {
- // Rollback
if (!wasInstalled) {
$toolSchema = $toolSchema.filter((g) => g.name !== skill.name);
} else {
- $toolSchema = [...$toolSchema, { name: skill.name, schema: skill.schema_json }];
+ $toolSchema = [...$toolSchema, { name: skill.name, schema: skill.schema_json ?? [] }];
}
notify(e.message, 'error');
} finally {
@@ -136,32 +193,78 @@
}
}
- async function rateSkill(skill, stars) {
+ // detail expansion
+
+ async function toggleExpand(skill) {
+ if (expandedSkillId === skill.id) {
+ expandedSkillId = null;
+ detail = null;
+ return;
+ }
+ expandedSkillId = skill.id;
+ detail = null;
+ userRating = null;
+ hoverStar = 0;
+ detailLoading = true;
+ try {
+ const res = await fetch(`/api/skills/${skill.id}`);
+ if (!res.ok) throw new Error('Failed to load details');
+ detail = await res.json();
+ userRating = detail.user_rating ?? null;
+ } catch (e) {
+ notify(e.message, 'error');
+ expandedSkillId = null;
+ } finally {
+ detailLoading = false;
+ }
+ }
+
+ // rating
+
+ async function submitRating(skillId, rating) {
if (!$currentUser) return;
- ratingPending = { ...ratingPending, [skill.id]: true };
try {
- const res = await fetch(`/api/skills/${skill.id}/rate`, {
+ const res = await fetch(`/api/skills/${skillId}/rate`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ rating: stars })
+ body: JSON.stringify({ rating })
});
if (!res.ok) throw new Error('Rating failed');
const data = await res.json();
+ userRating = rating;
+ if (detail?.id === skillId) {
+ detail = { ...detail, avg_rating: data.avg_rating, rating_count: data.rating_count };
+ }
skills = skills.map((s) =>
- s.id === skill.id
+ s.id === skillId
? { ...s, avg_rating: data.avg_rating, rating_count: data.rating_count }
: s
);
} catch (e) {
notify(e.message, 'error');
- } finally {
- const next = { ...ratingPending };
- delete next[skill.id];
- ratingPending = next;
}
}
+ // copy slug
+
+ async function copySlug(slug, e) {
+ e?.stopPropagation();
+ try {
+ await navigator.clipboard.writeText(slug);
+ } catch {
+ const ta = document.createElement('textarea');
+ ta.value = slug;
+ document.body.appendChild(ta);
+ ta.select();
+ document.execCommand('copy');
+ document.body.removeChild(ta);
+ }
+ notify('Copied!', 'success');
+ }
+
+ // publish
+
function nameToSlug(name) {
return name
.toLowerCase()
@@ -226,19 +329,29 @@
}
}
- $: if (open && skills.length === 0) loadSkills(true);
+ // init and keyboard
- function formatRating(avg, count) {
- if (!count) return 'No ratings yet';
- return `⭐ ${Number(avg).toFixed(1)} (${count})`;
+ $: if (open && skills.length === 0) {
+ Promise.all([loadSkills(true), loadCategories()]);
}
$: tagPills = publishForm.tags
.split(',')
.map((t) => t.trim())
.filter(Boolean);
+
+ function handleKeydown(e) {
+ if (!open) return;
+ if (e.key === 'Escape' && expandedSkillId !== null) {
+ e.stopPropagation();
+ expandedSkillId = null;
+ detail = null;
+ }
+ }
</script>
+<svelte:window on:keydown={handleKeydown} />
+
<Modal bind:open class="md:w-[820px] max-w-[820px]">
<!-- Tab bar -->
<div class="-mx-5 mb-4 flex border-b border-slate-200 px-5">
@@ -290,7 +403,7 @@
<div class="mb-4 flex gap-x-2">
<input
type="text"
- placeholder="Search skills…"
+ placeholder="Search skills..."
bind:value={searchQuery}
on:input={handleSearchInput}
class="min-w-0 flex-1 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
@@ -301,7 +414,7 @@
>
<option value="popular">Popular</option>
<option value="newest">Newest</option>
- <option value="az">A–Z</option>
+ <option value="az">A-Z</option>
</select>
</div>
@@ -324,23 +437,23 @@
</div>
{#if loading && skills.length === 0}
- <p class="mt-8 text-center text-[13px] text-slate-400">Loading skills…</p>
+ <p class="mt-8 text-center text-[13px] text-slate-400">Loading skills...</p>
{:else if skills.length === 0}
<p class="mt-8 text-center text-[13px] text-slate-400">No skills found</p>
{:else}
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
{#each skills as skill (skill.id)}
- <div class="flex flex-col rounded-lg border border-slate-200 {expandedSkillId === skill.id ? 'border-indigo-300 ring-1 ring-indigo-200' : ''}">
- <!-- Card main row -->
- <!-- svelte-ignore a11y-click-events-have-key-events -->
- <!-- svelte-ignore a11y-no-static-element-interactions -->
- <div
- class="flex cursor-pointer items-start justify-between gap-x-3 px-3 py-3"
- on:click={(e) => {
- if (e.target.closest('button')) return;
- expandedSkillId = expandedSkillId === skill.id ? null : skill.id;
- }}
- >
+ <!-- Card -->
+ <!-- svelte-ignore a11y-click-events-have-key-events -->
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
+ <div
+ class="cursor-pointer rounded-lg border px-3 py-3 transition-colors {expandedSkillId === skill.id
+ ? 'border-indigo-300 bg-indigo-50/30 ring-1 ring-indigo-200'
+ : 'border-slate-200 hover:border-slate-300'}"
+ on:click={() => toggleExpand(skill)}
+ aria-expanded={expandedSkillId === skill.id}
+ >
+ <div class="flex items-start justify-between gap-x-3">
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-x-1.5 gap-y-1">
<span class="text-[13px] font-medium text-slate-800">{skill.name}</span>
@@ -356,66 +469,174 @@
<div class="mt-1.5 flex items-center gap-x-3 text-[11px] text-slate-400">
<span>{skill.install_count || 0} installs</span>
<span>{formatRating(skill.avg_rating, skill.rating_count)}</span>
- <span>by {skill.author_name || 'System'}</span>
+ <span>by {skill.author?.display_name || skill.author_name || 'System'}</span>
</div>
</div>
{#if !$currentUser}
<span class="shrink-0 text-[11px] text-slate-400">Sign in to install</span>
{:else if installPending[skill.id]}
- <span class="shrink-0 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] text-slate-400"
- >…</span
+ <span
+ class="shrink-0 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] text-slate-400"
+ >...</span
>
{:else if isInstalled(skill)}
<button
class="shrink-0 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] text-slate-500 transition-colors hover:border-red-200 hover:bg-red-50 hover:text-red-600"
- on:click|stopPropagation={() => toggleInstall(skill)}
+ on:click={(e) => toggleInstall(skill, e)}
>
Remove
</button>
{:else}
<button
class="shrink-0 rounded-lg border border-slate-200 bg-slate-50 px-3 py-1.5 text-[11px] font-medium text-slate-700 transition-colors hover:bg-slate-100"
- on:click|stopPropagation={() => toggleInstall(skill)}
+ on:click={(e) => toggleInstall(skill, e)}
>
Install
</button>
{/if}
</div>
+ </div>
- <!-- Expanded view -->
- {#if expandedSkillId === skill.id}
- <div class="border-t border-slate-100 px-3 pb-3 pt-2.5">
- <p class="text-[12px] leading-relaxed text-slate-600">
- {skill.description || 'No description'}
- </p>
- {#if skill.tags && skill.tags.length}
- <div class="mt-2 flex flex-wrap gap-1">
- {#each skill.tags as tag}
- <span class="rounded-full bg-indigo-50 px-2 py-0.5 text-[10px] text-indigo-600"
- >{tag}</span
- >
- {/each}
+ <!-- Inline detail expansion (spans both grid columns) -->
+ {#if expandedSkillId === skill.id}
+ <div
+ class="col-span-1 rounded-lg border border-indigo-200 bg-white p-4 sm:col-span-2"
+ role="region"
+ aria-label="{skill.name} details"
+ >
+ {#if detailLoading}
+ <div class="flex animate-pulse flex-col gap-2">
+ <div class="h-3 w-3/4 rounded bg-slate-200"></div>
+ <div class="h-3 w-1/2 rounded bg-slate-200"></div>
+ <div class="h-3 w-2/3 rounded bg-slate-200"></div>
+ <div class="mt-1 h-16 rounded bg-slate-200"></div>
+ </div>
+ {:else if detail}
+ <div class="flex flex-col gap-4 md:flex-row">
+
+ <!-- Left column (60%) -->
+ <div class="flex flex-col gap-2 md:flex-[6]">
+ <p class="text-[13px] leading-relaxed text-slate-700">{detail.description || ''}</p>
+ {#if detail.tags?.length}
+ <div class="flex flex-wrap gap-1">
+ {#each detail.tags as tag}
+ <span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] text-slate-600"
+ >{tag}</span
+ >
+ {/each}
+ </div>
+ {/if}
+ <p class="text-[12px] text-slate-500">
+ By {detail.author?.display_name ?? 'the 3D-Agent team'}
+ </p>
+ <p class="text-[11px] text-slate-400">
+ {detail.install_count ?? 0} installs{detail.created_at
+ ? ` - Published ${relativeDate(detail.created_at)}`
+ : ''}
+ </p>
</div>
- {/if}
- <!-- Star rating -->
- <div class="mt-3">
- <p class="mb-1 text-[11px] text-slate-400">Rate this skill</p>
- <div class="flex gap-x-0.5">
- {#each [1, 2, 3, 4, 5] as star}
- <button
- disabled={!$currentUser || ratingPending[skill.id]}
- class="text-lg leading-none transition-transform hover:scale-110 disabled:opacity-40"
- on:click={() => rateSkill(skill, star)}
+
+ <!-- Right column (40%) -->
+ <div class="flex flex-col gap-3 md:flex-[4]">
+
+ <!-- Star rating -->
+ <div>
+ <div
+ class="flex items-center gap-0.5"
+ title={$currentUser ? undefined : 'Sign in to rate'}
>
- {(skill.avg_rating || 0) >= star ? '⭐' : '☆'}
- </button>
- {/each}
+ {#each [1, 2, 3, 4, 5] as star}
+ <button
+ class="text-xl leading-none transition-transform duration-100 {$currentUser && !userRating
+ ? 'cursor-pointer hover:scale-110'
+ : 'cursor-default'}"
+ style="color: {userRating && star <= userRating
+ ? '#6366f1'
+ : hoverStar >= star ||
+ (!userRating && star <= Math.round(detail.avg_rating ?? 0))
+ ? '#f59e0b'
+ : '#d1d5db'}"
+ on:click={() => {
+ if ($currentUser && !userRating) submitRating(detail.id, star);
+ }}
+ on:mouseenter={() => {
+ if ($currentUser && !userRating) hoverStar = star;
+ }}
+ on:mouseleave={() => (hoverStar = 0)}
+ tabindex={$currentUser && !userRating ? 0 : -1}
+ aria-label="Rate {star} star{star > 1 ? 's' : ''}"
+ >*</button>
+ {/each}
+ <span class="ml-1.5 text-[11px] text-slate-400">
+ {detail.avg_rating
+ ? Number(detail.avg_rating).toFixed(1)
+ : 'No ratings'}
+ ({detail.rating_count ?? 0})
+ </span>
+ </div>
+ {#if !$currentUser}
+ <p class="mt-0.5 text-[11px] text-slate-400">Sign in to rate</p>
+ {:else if userRating}
+ <p class="mt-0.5 text-[11px] text-indigo-500">You rated {userRating}/5</p>
+ {/if}
+ </div>
+
+ <!-- Schema preview -->
+ {#if detail.schema_json}
+ {@const preview = schemaPreview(detail.schema_json)}
+ {#if preview}
+ <div>
+ <p class="mb-1 text-[11px] font-medium text-slate-600">Schema preview</p>
+ <pre
+ class="overflow-x-auto whitespace-pre-wrap break-words rounded border border-slate-100 bg-slate-50 p-2 text-[11px] leading-relaxed"
+ ><code>{preview.name}
+{preview.description}{preview.params.length
+ ? `\nparams: ${preview.params.join(', ')}`
+ : ''}{preview.extra > 0
+ ? `\nand ${preview.extra} more tool${preview.extra > 1 ? 's' : ''}`
+ : ''}</code></pre>
+ </div>
+ {/if}
+ {/if}
+
</div>
</div>
- </div>
- {/if}
- </div>
+
+ <!-- Action row -->
+ <div class="mt-4 flex items-center gap-2 border-t border-slate-100 pt-3">
+ {#if !$currentUser}
+ <span class="text-[12px] text-slate-400">Sign in to install skills</span>
+ {:else if installPending[skill.id]}
+ <span
+ class="rounded-lg border border-slate-200 px-3 py-1.5 text-[12px] text-slate-400"
+ >...</span
+ >
+ {:else if isInstalled(skill)}
+ <button
+ class="rounded-lg border border-slate-200 px-3 py-1.5 text-[12px] text-slate-500 transition-colors hover:border-red-200 hover:bg-red-50 hover:text-red-600"
+ on:click={(e) => toggleInstall(skill, e)}
+ >
+ Remove skill
+ </button>
+ {:else}
+ <button
+ class="rounded-lg border border-indigo-200 bg-indigo-50 px-3 py-1.5 text-[12px] font-medium text-indigo-700 transition-colors hover:bg-indigo-100"
+ on:click={(e) => toggleInstall(skill, e)}
+ >
+ Install skill
+ </button>
+ {/if}
+ <button
+ class="rounded-lg border border-slate-200 px-3 py-1.5 text-[12px] text-slate-600 transition-colors hover:bg-slate-50"
+ on:click={(e) => copySlug(skill.slug, e)}
+ >
+ Copy slug
+ </button>
+ </div>
+ {/if}
+ </div>
+ {/if}
{/each}
</div>
@@ -425,7 +646,7 @@
disabled={loading}
on:click={() => loadSkills(false)}
>
- {loading ? 'Loading…' : 'Load more'}
+ {loading ? 'Loading...' : 'Load more'}
</button>
{/if}
{/if}
@@ -463,10 +684,11 @@
</div>
<div class="flex flex-col gap-y-1">
- <label class="text-[12px] font-medium text-slate-600">Description</label>
+ <label for="pf-desc" class="text-[12px] font-medium text-slate-600">Description</label>
<textarea
+ id="pf-desc"
bind:value={publishForm.description}
- placeholder="Describe what this skill does…"
+ placeholder="Describe what this skill does..."
rows="3"
class="resize-none rounded-lg border border-slate-200 px-3 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
/>
@@ -474,8 +696,9 @@
<div class="flex gap-x-3">
<div class="flex flex-1 flex-col gap-y-1">
- <label class="text-[12px] font-medium text-slate-600">Category</label>
+ <label for="pf-cat" class="text-[12px] font-medium text-slate-600">Category</label>
<input
+ id="pf-cat"
type="text"
list="skill-categories"
bind:value={publishForm.category}
@@ -490,8 +713,9 @@
</div>
<div class="flex flex-1 flex-col gap-y-1">
- <label class="text-[12px] font-medium text-slate-600">Tags (comma-separated)</label>
+ <label for="pf-tags" class="text-[12px] font-medium text-slate-600">Tags (comma-separated)</label>
<input
+ id="pf-tags"
type="text"
bind:value={publishForm.tags}
placeholder="search, web, api"
@@ -511,8 +735,9 @@
{/if}
<div class="flex flex-col gap-y-1">
- <label class="text-[12px] font-medium text-slate-600">Schema (JSON)</label>
+ <label for="pf-schema" class="text-[12px] font-medium text-slate-600">Schema (JSON)</label>
<textarea
+ id="pf-schema"
bind:value={publishForm.schemaText}
rows="10"
spellcheck="false"
@@ -527,7 +752,7 @@
Validate JSON
</button>
{#if schemaValid === true}
- <span class="text-[11px] text-green-600">✓ Valid</span>
+ <span class="text-[11px] text-green-600">Valid</span>
{:else if schemaValid === false}
<span class="text-[11px] text-red-500">{schemaErrorMsg}</span>
{/if}
@@ -554,7 +779,7 @@
class="self-start rounded-lg bg-indigo-600 px-4 py-2 text-[13px] font-medium text-white transition-colors hover:bg-indigo-700 disabled:opacity-50"
on:click={publishSkill}
>
- {publishLoading ? 'Publishing…' : 'Publish skill'}
+ {publishLoading ? 'Publishing...' : 'Publish skill'}
</button>
</div>
{/if}
diff --git a/chat/src/manus/TopNav.svelte b/chat/src/manus/TopNav.svelte
index ffb78b27b..c06414743 100644
--- a/chat/src/manus/TopNav.svelte
+++ b/chat/src/manus/TopNav.svelte
@@ -3,6 +3,7 @@
import Icon from '../Icon.svelte';
import { feMenu, feX } from '../feather.js';
import WalletConnect from '../WalletConnect.svelte';
+ import NotificationBell from '../NotificationBell.svelte';
import FeaturesDropdown from './dropdowns/FeaturesDropdown.svelte';
import SolutionsDropdown from './dropdowns/SolutionsDropdown.svelte';
import ResourcesDropdown from './dropdowns/ResourcesDropdown.svelte';
@@ -155,6 +156,7 @@
<!-- RIGHT: auth buttons + hamburger -->
<div class="flex items-center gap-2">
<div class="hidden items-center gap-2 md:flex">
+ <NotificationBell />
<WalletConnect />
</div>
<button
diff --git a/public/chat/index.html b/public/chat/index.html
index 45a956354..bd2f18930 100644
--- a/public/chat/index.html
+++ b/public/chat/index.html
@@ -43,8 +43,8 @@
}
}
</script>
- <script type="module" crossorigin src="/chat/assets/index-CNGGMqFP.js"></script>
- <link rel="stylesheet" crossorigin href="/chat/assets/index-BeH6JEv0.css">
+ <script type="module" crossorigin src="/chat/assets/index-CGS445lX.js"></script>
+ <link rel="stylesheet" crossorigin href="/chat/assets/index-Ciwx7Aa1.css">
</head>
<body>
<div id="app"></div>
diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.js
index e527b769e..35e0895f1 100644
--- a/public/dashboard/dashboard.js
+++ b/public/dashboard/dashboard.js
@@ -33,6 +33,15 @@ export const api = {
patchAgentAnimations: (agentId, animations) =>
j('PUT', `/api/agents/${encodeURIComponent(agentId)}/animations`, { animations }),
presignAnimation: (body) => j('POST', '/api/animations/presign', body),
+ listAgents: () => j('GET', '/api/agents'),
+ getRevenue: (params) => {
+ const q = new URLSearchParams();
+ if (params.from) q.set('from', params.from);
+ if (params.to) q.set('to', params.to);
+ if (params.agent_id) q.set('agent_id', params.agent_id);
+ if (params.granularity) q.set('granularity', params.granularity);
+ return j('GET', `/api/billing/revenue?${q.toString()}`);
+ },
};
async function j(method, path, body) {
@@ -86,7 +95,9 @@ const tabs = {
embed: renderEmbed,
keys: renderKeys,
mcp: renderMcp,
+ monetization: renderMonetization,
billing: renderBilling,
+ revenue: renderRevenue,
account: renderAccount,
};
@@ -1623,6 +1634,256 @@ function renderAgentRows(list, onchainAgents, dbAgents) {
}
}
+// ── Monetization ─────────────────────────────────────────────────────────────
+async function renderMonetization(root) {
+ root.innerHTML = `
+ <h1>Monetization</h1>
+ <p class="sub">Set prices for your agent's skills and configure payout wallets.</p>
+ <div id="mon-body"><div class="muted">Loading…</div></div>
+ `;
+ const body = root.querySelector('#mon-body');
+
+ const CURRENCIES = [
+ { label: 'Solana USDC', mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', chain: 'solana' },
+ { label: 'Base USDC', mint: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', chain: 'base' },
+ ];
+
+ const toHuman = (amount) => (Number(amount) / 1_000_000).toFixed(6).replace(/\.?0+$/, '');
+ const toBigint = (human) => Math.round(parseFloat(human) * 1_000_000);
+
+ let agent, prices, wallets;
+ try {
+ const [agentRes, walletsRes] = await Promise.all([
+ fetch('/api/agents/me', { credentials: 'include' }),
+ fetch('/api/billing/payout-wallets', { credentials: 'include' }),
+ ]);
+ if (!agentRes.ok) throw new Error('Could not load agent');
+ const agentData = await agentRes.json();
+ agent = agentData.agent;
+ wallets = walletsRes.ok ? (await walletsRes.json()).wallets || [] : [];
+
+ const pricesRes = await fetch(`/api/agents/${agent.id}/pricing`, { credentials: 'include' });
+ prices = pricesRes.ok ? (await pricesRes.json()).prices || [] : [];
+ } catch (e) {
+ body.innerHTML = `<div class="err">${esc(e.message || 'Failed to load monetization data')}</div>`;
+ return;
+ }
+
+ const agentId = agent.id;
+ const skills = agent.skills || [];
+
+ const priceMap = {};
+ prices.forEach((p) => { priceMap[p.skill] = p; });
+
+ const solWallet = wallets.find((w) => w.chain === 'solana');
+ const baseWallet = wallets.find((w) => w.chain === 'base' || w.chain === 'evm');
+
+ body.innerHTML = `
+ <div style="margin-bottom:32px">
+ <h3 style="margin:0 0 14px; font-size:15px">Skill Prices</h3>
+ <div id="mon-prices" style="display:flex;flex-direction:column;gap:8px">
+ ${skills.length === 0 && prices.length === 0 ? '<div class="muted">No skills registered on this agent yet.</div>' : ''}
+ </div>
+ <div id="mon-add-price" style="margin-top:10px"></div>
+ </div>
+ <div>
+ <h3 style="margin:0 0 14px; font-size:15px">Payout Wallets</h3>
+ <div style="display:flex;flex-direction:column;gap:12px;max-width:520px">
+ <div class="card">
+ <div class="row" style="gap:8px;margin-bottom:10px">
+ <strong style="font-size:13px">Solana (USDC)</strong>
+ ${solWallet ? `<span class="tag">Configured</span>` : ''}
+ </div>
+ <div class="row" style="gap:8px">
+ <input id="mon-sol-addr" type="text" placeholder="Solana address (base58)" value="${attr(solWallet?.address || '')}" style="flex:1;font-size:13px">
+ <button class="btn sec" id="mon-sol-save" style="white-space:nowrap">Set payout</button>
+ </div>
+ <div id="mon-sol-msg" class="muted" style="margin-top:6px;font-size:12px;min-height:16px"></div>
+ </div>
+ <div class="card">
+ <div class="row" style="gap:8px;margin-bottom:10px">
+ <strong style="font-size:13px">Base (USDC)</strong>
+ ${baseWallet ? `<span class="tag">Configured</span>` : ''}
+ </div>
+ <div class="row" style="gap:8px">
+ <input id="mon-base-addr" type="text" placeholder="Base address (0x…)" value="${attr(baseWallet?.address || '')}" style="flex:1;font-size:13px">
+ <button class="btn sec" id="mon-base-save" style="white-space:nowrap">Set payout</button>
+ </div>
+ <div id="mon-base-msg" class="muted" style="margin-top:6px;font-size:12px;min-height:16px"></div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ const pricesEl = body.querySelector('#mon-prices');
+
+ function wireRemove(btn, row, skill) {
+ btn.addEventListener('click', async () => {
+ const msg = row.querySelector('[data-msg]');
+ msg.style.color = '#888';
+ msg.textContent = 'Removing…';
+ try {
+ const r = await fetch(
+ `/api/agents/${agentId}/pricing/${encodeURIComponent(skill)}?hard=true`,
+ { method: 'DELETE', credentials: 'include' },
+ );
+ if (!r.ok) {
+ const d = await r.json().catch(() => ({}));
+ throw new Error(d.error_description || `HTTP ${r.status}`);
+ }
+ row.remove();
+ } catch (e) {
+ msg.style.color = '#ffb3b3';
+ msg.textContent = e.message;
+ }
+ });
+ }
+
+ const makeRow = (skill, price) => {
+ const row = document.createElement('div');
+ row.style.cssText =
+ 'display:grid;grid-template-columns:minmax(100px,1fr) 150px 1fr auto auto auto;align-items:center;gap:10px;padding:10px 12px;background:var(--panel);border:1px solid var(--border);border-radius:10px';
+ const defMint = price?.currency_mint || CURRENCIES[0].mint;
+ row.innerHTML = `
+ <span style="font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${attr(skill)}">${esc(skill)}</span>
+ <input type="number" min="0.000001" step="0.000001" placeholder="Amount (USDC)"
+ value="${price ? attr(toHuman(price.amount)) : ''}"
+ style="font-size:13px;width:100%" data-amount>
+ <select style="font-size:13px;width:100%" data-currency>
+ ${CURRENCIES.map((c) => `<option value="${attr(c.mint)}" data-chain="${attr(c.chain)}" ${c.mint === defMint ? 'selected' : ''}>${esc(c.label)}</option>`).join('')}
+ </select>
+ <label class="toggle" title="Active">
+ <input type="checkbox" ${!price || price.is_active ? 'checked' : ''} data-active>
+ <span class="track"></span>
+ <span class="label">Active</span>
+ </label>
+ <div style="display:inline-flex;gap:6px">
+ <button class="btn" style="font-size:12px;padding:5px 10px;white-space:nowrap" data-save>Save</button>
+ ${price ? `<button class="btn sec" style="font-size:12px;padding:5px 10px;color:#ffb3b3" data-remove>Remove</button>` : ''}
+ </div>
+ <div data-msg style="font-size:12px;min-width:54px"></div>
+ `;
+
+ const msg = row.querySelector('[data-msg]');
+
+ row.querySelector('[data-save]').addEventListener('click', async () => {
+ const amountRaw = row.querySelector('[data-amount]').value;
+ const amount = toBigint(amountRaw);
+ if (!amountRaw || isNaN(amount) || amount <= 0) {
+ msg.style.color = '#ffb3b3';
+ msg.textContent = 'Enter a valid amount';
+ return;
+ }
+ const sel = row.querySelector('[data-currency]');
+ const currencyMint = sel.value;
+ const chain = sel.options[sel.selectedIndex].dataset.chain;
+ const isActive = row.querySelector('[data-active]').checked;
+ msg.style.color = '#888';
+ msg.textContent = 'Saving…';
+ try {
+ const r = await fetch(
+ `/api/agents/${agentId}/pricing/${encodeURIComponent(skill)}`,
+ {
+ method: 'PUT',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ currency_mint: currencyMint, chain, amount, is_active: isActive }),
+ },
+ );
+ if (!r.ok) {
+ const d = await r.json().catch(() => ({}));
+ throw new Error(d.error_description || `HTTP ${r.status}`);
+ }
+ if (!row.querySelector('[data-remove]')) {
+ const removeBtn = document.createElement('button');
+ removeBtn.className = 'btn sec';
+ removeBtn.style.cssText = 'font-size:12px;padding:5px 10px;color:#ffb3b3';
+ removeBtn.dataset.remove = '';
+ removeBtn.textContent = 'Remove';
+ row.querySelector('[data-save]').parentNode.appendChild(removeBtn);
+ wireRemove(removeBtn, row, skill);
+ }
+ msg.style.color = '#9a8cff';
+ msg.textContent = 'Saved ✓';
+ setTimeout(() => { msg.textContent = ''; }, 2000);
+ } catch (e) {
+ msg.style.color = '#ffb3b3';
+ msg.textContent = e.message;
+ }
+ });
+
+ const removeBtn = row.querySelector('[data-remove]');
+ if (removeBtn) wireRemove(removeBtn, row, skill);
+
+ return row;
+ };
+
+ const renderedSkills = new Set();
+ skills.forEach((skill) => {
+ pricesEl.appendChild(makeRow(skill, priceMap[skill] || null));
+ renderedSkills.add(skill);
+ });
+ prices.forEach((p) => {
+ if (!renderedSkills.has(p.skill)) pricesEl.appendChild(makeRow(p.skill, p));
+ });
+
+ const addPriceEl = body.querySelector('#mon-add-price');
+ addPriceEl.innerHTML = `<button class="btn sec" id="mon-add-custom" style="font-size:12px">+ Add custom skill price</button>`;
+ addPriceEl.querySelector('#mon-add-custom').addEventListener('click', () => {
+ const wrap = document.createElement('div');
+ wrap.style.cssText = 'display:flex;gap:8px;margin-top:8px;align-items:center';
+ wrap.innerHTML = `
+ <input type="text" placeholder="Skill name" style="font-size:13px;width:180px" id="mon-new-skill">
+ <button class="btn sec" style="font-size:12px" id="mon-new-confirm">Add</button>
+ <button class="btn sec" style="font-size:12px" id="mon-new-cancel">Cancel</button>
+ `;
+ addPriceEl.appendChild(wrap);
+ wrap.querySelector('#mon-new-confirm').addEventListener('click', () => {
+ const name = wrap.querySelector('#mon-new-skill').value.trim();
+ if (!name) return;
+ wrap.remove();
+ pricesEl.appendChild(makeRow(name, null));
+ });
+ wrap.querySelector('#mon-new-cancel').addEventListener('click', () => wrap.remove());
+ });
+
+ const saveWallet = async (chain, addrInput, msgEl) => {
+ const address = addrInput.value.trim();
+ if (!address) {
+ msgEl.style.color = '#ffb3b3';
+ msgEl.textContent = 'Enter an address';
+ return;
+ }
+ msgEl.style.color = '#888';
+ msgEl.textContent = 'Saving…';
+ try {
+ const r = await fetch('/api/billing/payout-wallets', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ address, chain, agent_id: agentId, is_default: true }),
+ });
+ if (!r.ok) {
+ const d = await r.json().catch(() => ({}));
+ throw new Error(d.error_description || `HTTP ${r.status}`);
+ }
+ msgEl.style.color = '#9a8cff';
+ msgEl.textContent = 'Saved ✓';
+ setTimeout(() => { msgEl.textContent = ''; }, 2000);
+ } catch (e) {
+ msgEl.style.color = '#ffb3b3';
+ msgEl.textContent = e.message;
+ }
+ };
+
+ body.querySelector('#mon-sol-save').addEventListener('click', () =>
+ saveWallet('solana', body.querySelector('#mon-sol-addr'), body.querySelector('#mon-sol-msg')),
+ );
+ body.querySelector('#mon-base-save').addEventListener('click', () =>
+ saveWallet('base', body.querySelector('#mon-base-addr'), body.querySelector('#mon-base-msg')),
+ );
+}
+
// ── Billing & usage ─────────────────────────────────────────────────────────
async function renderBilling(root) {
root.innerHTML = `
@@ -1686,6 +1947,144 @@ async function renderBilling(root) {
`;
}
+// ── Revenue dashboard ────────────────────────────────────────────────────────
+function formatUSDC(lamports) {
+ return (lamports / 1_000_000).toLocaleString('en-US', {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }) + ' USDC';
+}
+
+function revenueBarChart(timeseries) {
+ if (!timeseries.length) return '<div class="muted" style="text-align:center;padding:24px 0">No data for this period.</div>';
+ const W = 600, H = 160, PAD = { top: 12, right: 8, bottom: 28, left: 8 };
+ const max = Math.max(...timeseries.map((r) => r.net_total), 1);
+ const barW = Math.max(4, Math.floor((W - PAD.left - PAD.right) / timeseries.length) - 2);
+ const innerW = W - PAD.left - PAD.right;
+ const innerH = H - PAD.top - PAD.bottom;
+ const bars = timeseries.map((r, i) => {
+ const x = PAD.left + Math.round((i / timeseries.length) * innerW);
+ const barH = Math.max(2, Math.round((r.net_total / max) * innerH));
+ const y = PAD.top + innerH - barH;
+ const label = r.period.slice(5); // MM-DD
+ return `<rect x="${x}" y="${y}" width="${barW}" height="${barH}" fill="#6c5cff" rx="2">
+ <title>${r.period}: ${formatUSDC(r.net_total)}</title></rect>
+ <text x="${x + barW / 2}" y="${H - 6}" text-anchor="middle" font-size="9" fill="var(--muted)">${label}</text>`;
+ });
+ return `<svg viewBox="0 0 ${W} ${H}" style="width:100%;height:${H}px;display:block">${bars.join('')}</svg>`;
+}
+
+async function renderRevenue(root) {
+ root.innerHTML = `
+ <h1>Revenue</h1>
+ <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px">
+ <select id="rev-agent" style="padding:6px 10px;border-radius:6px;border:1px solid var(--border);background:var(--surface);color:inherit">
+ <option value="">All agents</option>
+ </select>
+ <select id="rev-range" style="padding:6px 10px;border-radius:6px;border:1px solid var(--border);background:var(--surface);color:inherit">
+ <option value="7">Last 7 days</option>
+ <option value="30" selected>Last 30 days</option>
+ <option value="90">Last 90 days</option>
+ </select>
+ </div>
+ <div id="rev-body"><div class="muted">Loading…</div></div>
+ `;
+
+ const agentSel = root.querySelector('#rev-agent');
+ const rangeSel = root.querySelector('#rev-range');
+
+ // Populate agent list
+ try {
+ const { agents } = await api.listAgents();
+ for (const a of agents) {
+ const opt = document.createElement('option');
+ opt.value = a.id;
+ opt.textContent = a.name || a.id.slice(0, 8);
+ agentSel.appendChild(opt);
+ }
+ } catch {}
+
+ async function load() {
+ const body = root.querySelector('#rev-body');
+ body.innerHTML = '<div class="muted">Loading…</div>';
+ const days = parseInt(rangeSel.value, 10);
+ const from = new Date(Date.now() - days * 86400_000).toISOString();
+ const agentId = agentSel.value || null;
+ const gran = days <= 7 ? 'day' : days <= 90 ? 'day' : 'week';
+ let data;
+ try {
+ data = await api.getRevenue({ from, agent_id: agentId, granularity: gran });
+ } catch (e) {
+ body.innerHTML = `<div class="err">${esc(e.message)}</div>`;
+ return;
+ }
+ const { summary, by_skill, timeseries } = data;
+
+ if (summary.payment_count === 0 && !by_skill.length) {
+ body.innerHTML = `
+ <div class="card" style="text-align:center;padding:48px 24px">
+ <div style="font-size:40px;margin-bottom:12px">💰</div>
+ <h3 style="margin:0 0 8px">No revenue yet</h3>
+ <p class="muted" style="margin:0">Payments will appear here once your agent skills are called.</p>
+ </div>`;
+ return;
+ }
+
+ body.innerHTML = `
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:20px">
+ <div class="card">
+ <div class="muted" style="font-size:12px;margin-bottom:4px">Gross earnings</div>
+ <div style="font-size:20px;font-weight:700">${esc(formatUSDC(summary.gross_total))}</div>
+ </div>
+ <div class="card">
+ <div class="muted" style="font-size:12px;margin-bottom:4px">Platform fees</div>
+ <div style="font-size:20px;font-weight:700;color:#ff5c5c">−${esc(formatUSDC(summary.fee_total))}</div>
+ </div>
+ <div class="card">
+ <div class="muted" style="font-size:12px;margin-bottom:4px">Net earnings</div>
+ <div style="font-size:20px;font-weight:700;color:#00e5a0">${esc(formatUSDC(summary.net_total))}</div>
+ </div>
+ <div class="card">
+ <div class="muted" style="font-size:12px;margin-bottom:4px">Payments</div>
+ <div style="font-size:20px;font-weight:700">${esc(String(summary.payment_count))}</div>
+ </div>
+ </div>
+ <div class="card" style="margin-bottom:20px">
+ <h3 style="margin:0 0 12px">Daily earnings</h3>
+ ${revenueBarChart(timeseries)}
+ </div>
+ ${by_skill.length ? `
+ <div class="card">
+ <h3 style="margin:0 0 12px">Skill breakdown</h3>
+ <table style="width:100%;border-collapse:collapse">
+ <thead>
+ <tr style="text-align:left;border-bottom:1px solid var(--border)">
+ <th style="padding:6px 8px 10px;font-weight:600;font-size:13px">Skill</th>
+ <th style="padding:6px 8px 10px;font-weight:600;font-size:13px;text-align:right">Net earnings</th>
+ <th style="padding:6px 8px 10px;font-weight:600;font-size:13px;text-align:right">Transactions</th>
+ </tr>
+ </thead>
+ <tbody>
+ ${by_skill.map((s) => `<tr style="border-bottom:1px solid var(--border)">
+ <td style="padding:8px">${esc(s.skill)}</td>
+ <td style="padding:8px;text-align:right;font-variant-numeric:tabular-nums">${esc(formatUSDC(s.net_total))}</td>
+ <td style="padding:8px;text-align:right">${esc(String(s.count))}</td>
+ </tr>`).join('')}
+ </tbody>
+ </table>
+ </div>` : ''}
+ `;
+ }
+
+ agentSel.addEventListener('change', load);
+ rangeSel.addEventListener('change', load);
+ await load();
+
+ // Re-fetch on page focus (no WebSocket needed)
+ const onFocus = () => load();
+ window.addEventListener('focus', onFocus, { once: true });
+}
+
// ── Widgets ─────────────────────────────────────────────────────────────────
// Saved 3D experiences the user has generated in the Studio. Each gets its own
// card with a live, lazy-loaded preview iframe. Editing happens in /studio —
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index af5ea2a31..6a4f0bde4 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -1137,7 +1137,9 @@
<a href="#embed" data-tab="embed">Embed</a>
<a href="#keys" data-tab="keys">API keys</a>
<a href="#mcp" data-tab="mcp">MCP</a>
+ <a href="#monetization" data-tab="monetization">Monetization</a>
<a href="#billing" data-tab="billing">Plan &amp; usage</a>
+ <a href="#revenue" data-tab="revenue">Revenue</a>
<a href="#account" data-tab="account">Account</a>
<a href="/dashboard/wallets">Wallets</a>
<a href="/vanity-wallet">Vanity wallet ✦</a>
diff --git a/public/marketplace.css b/public/marketplace.css
index dcc3c4634..86abe76ef 100644
--- a/public/marketplace.css
+++ b/public/marketplace.css
@@ -784,3 +784,37 @@ body.market-page {
position: static;
}
}
+
+.paid-badge {
+ background: #fef3c7;
+ color: #92400e;
+ font-weight: 600;
+}
+
+.skill-entry {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ background: var(--mk-panel-2);
+ border-radius: 6px;
+ padding: 3px 8px;
+ font-size: 12px;
+ color: var(--mk-text-1);
+}
+
+.price-badge {
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ padding: 1px 5px;
+}
+
+.price-paid {
+ background: #d1fae5;
+ color: #065f46;
+}
+
+.price-free {
+ background: var(--mk-panel-3, #e5e7eb);
+ color: var(--mk-text-3);
+}
diff --git a/src/components/payment-gate-modal.jsx b/src/components/payment-gate-modal.jsx
new file mode 100644
index 000000000..aaad37368
--- /dev/null
+++ b/src/components/payment-gate-modal.jsx
@@ -0,0 +1,79 @@
+import vhtml from 'vhtml';
+/** @jsx vhtml */
+
+import { isUserRejection } from '../onchain/adapters/index.js';
+
+/**
+ * Show a blocking modal asking the caller to pay before a priced skill executes.
+ *
+ * @param {{
+ * skill: string,
+ * amount: string,
+ * currencySymbol: string,
+ * chain: string,
+ * onPay: (opts: { setStatus: (msg: string) => void }) => Promise<string>,
+ * onCancel?: () => void,
+ * }} opts
+ * @returns {Promise<string>} Resolves with intentId. Rejects with code=PAYMENT_CANCELLED on cancel.
+ */
+export function showPaymentGateModal({ skill, amount, currencySymbol, chain, onPay, onCancel }) {
+ return new Promise((resolve, reject) => {
+ const overlay = document.createElement('div');
+ overlay.className = 'pgm-overlay';
+ overlay.innerHTML = (
+ <div class="pgm-modal" role="dialog" aria-modal="true" aria-label="Skill payment required">
+ <h3>This skill requires payment</h3>
+ <p class="pgm-price">
+ <strong>{skill}</strong> costs{' '}
+ <strong>
+ {amount} {currencySymbol}
+ </strong>
+ {chain && <span class="pgm-chain"> on {chain}</span>}
+ </p>
+ <p class="pgm-status" role="status" aria-live="polite"></p>
+ <div class="pgm-actions">
+ <button class="pgm-cancel" type="button">
+ Cancel
+ </button>
+ <button class="pgm-pay" type="button">
+ Pay
+ </button>
+ </div>
+ </div>
+ );
+ document.body.appendChild(overlay);
+
+ const cancelBtn = overlay.querySelector('.pgm-cancel');
+ const payBtn = overlay.querySelector('.pgm-pay');
+ const statusEl = overlay.querySelector('.pgm-status');
+
+ function close() {
+ overlay.remove();
+ }
+
+ cancelBtn.addEventListener('click', () => {
+ close();
+ onCancel?.();
+ reject(Object.assign(new Error('Payment cancelled'), { code: 'PAYMENT_CANCELLED' }));
+ });
+
+ payBtn.addEventListener('click', async () => {
+ payBtn.disabled = true;
+ cancelBtn.disabled = true;
+ statusEl.textContent = 'Processing…';
+ try {
+ const intentId = await onPay({ setStatus: (msg) => { statusEl.textContent = msg; } });
+ close();
+ resolve(intentId);
+ } catch (err) {
+ if (isUserRejection(err)) {
+ statusEl.textContent = 'Payment declined in wallet. You can try again.';
+ } else {
+ statusEl.textContent = err.message || 'Payment failed.';
+ }
+ payBtn.disabled = false;
+ cancelBtn.disabled = false;
+ }
+ });
+ });
+}
diff --git a/src/marketplace.js b/src/marketplace.js
index 322291459..bdf098ec9 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -181,6 +181,7 @@ function renderCard(a) {
<span class="stat-pill">⊙ ${a.views_count || 0}</span>
<span class="stat-pill">⑂ ${a.forks_count || 0}</span>
${skills ? `<span class="stat-pill">▤ ${skills}</span>` : ''}
+ ${a.has_paid_skills ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}
</div>
<div class="footer">
<span>${date}</span>
@@ -262,8 +263,16 @@ function renderDetail(a, bookmarked) {
$('d-skills-count').textContent = skillsArr.length;
$('d-library-count').textContent = libraryArr.length;
+ const skillPrices = a.skill_prices || {};
$('d-skills').innerHTML = skillsArr.length
- ? skillsArr.map((s) => `<span class="stat-pill">${escapeHtml(typeof s === 'string' ? s : s.name || '')}</span>`).join(' ')
+ ? skillsArr.map((s) => {
+ const name = typeof s === 'string' ? s : (s.name || '');
+ const price = skillPrices[name];
+ const badge = price
+ ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`
+ : `<span class="price-badge price-free">Free</span>`;
+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
+ }).join(' ')
: '<div>This Agent includes the following Skills to help you complete more tasks.</div>';
$('d-library').innerHTML = libraryArr.length
? libraryArr.map((l) => `<span class="stat-pill">${escapeHtml(typeof l === 'string' ? l : l.name || '')}</span>`).join(' ')
diff --git a/src/skills/index.js b/src/skills/index.js
index 78d486bc2..4d907ec87 100644
--- a/src/skills/index.js
+++ b/src/skills/index.js
@@ -41,7 +41,14 @@ export class Skill {
}
async invoke(toolName, args, ctx) {
- const scoped = { ...ctx, skillBaseURI: this.uri };
+ const paymentProof = ctx?.agentId
+ ? await checkPaymentGate(toolName, ctx.agentId)
+ : null;
+ const scoped = {
+ ...ctx,
+ skillBaseURI: this.uri,
+ ...(paymentProof && { paymentProof }),
+ };
// Owner-signed skills may opt out of the sandbox via sandboxPolicy: "trusted-main-thread"
if (this.manifest.sandboxPolicy === 'trusted-main-thread') {
@@ -213,3 +220,88 @@ export class SkillRegistry {
}
}
}
+
+// ── Payment gate ──────────────────────────────────────────────────────────────
+
+const KNOWN_MINT_SYMBOLS = {
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v': 'USDC',
+ '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU': 'USDC',
+ 'So11111111111111111111111111111111111111112': 'SOL',
+};
+
+function mintSymbol(mint) {
+ return KNOWN_MINT_SYMBOLS[mint] || `${String(mint).slice(0, 4)}…${String(mint).slice(-4)}`;
+}
+
+async function fetchAgentSnippet(agentId) {
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, { credentials: 'include' });
+ if (!r.ok) return {};
+ const data = await r.json();
+ const payments = data?.agent?.payments || data?.agent?.meta?.payments || data?.payments;
+ return { payments, meta: { payments } };
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Returns the intentId string if payment was collected, null if the skill is free.
+ * Throws (with code=PAYMENT_CANCELLED) if the user dismisses the modal.
+ */
+async function checkPaymentGate(toolName, agentId) {
+ if (typeof document === 'undefined') return null;
+
+ let manifest;
+ try {
+ const r = await fetch(
+ `/api/agents/x402/manifest?agent_id=${encodeURIComponent(agentId)}&skill=${encodeURIComponent(toolName)}`,
+ { credentials: 'include' },
+ );
+ if (r.status !== 200) return null;
+ manifest = await r.json();
+ if (manifest?.version !== 'x402/0.1' || manifest?.kind !== 'agent-skill') return null;
+ } catch {
+ return null;
+ }
+
+ const [{ showPaymentGateModal }, { getPaymentsAdapter }, { getAdapter }] = await Promise.all([
+ import('../components/payment-gate-modal.jsx'),
+ import('../onchain/payments/index.js'),
+ import('../onchain/adapters/index.js'),
+ ]);
+
+ const progressLabels = {
+ connect: 'Connecting wallet…',
+ prep: 'Building payment…',
+ sign: 'Sign in your wallet…',
+ submit: 'Submitting…',
+ confirm: 'Verifying…',
+ };
+
+ return showPaymentGateModal({
+ skill: toolName,
+ amount: manifest.amount,
+ currencySymbol: mintSymbol(manifest.currency),
+ chain: 'Solana',
+ onPay: async ({ setStatus }) => {
+ const wallet = getAdapter('solana');
+ if (!wallet.isAvailable()) {
+ throw Object.assign(
+ new Error('No Solana wallet detected. Please install Phantom or Backpack.'),
+ { code: 'NO_PROVIDER' },
+ );
+ }
+ const agentSnippet = await fetchAgentSnippet(agentId);
+ const adapter = getPaymentsAdapter('pumpfun');
+ const paid = await adapter.payAgent({
+ agent: { id: agentId, ...agentSnippet },
+ currencyMint: manifest.currency,
+ amount: manifest.amount,
+ onProgress: (step) => setStatus(progressLabels[step] || step),
+ });
+ return paid.intentId;
+ },
+ onCancel: () => {},
+ });
+}
diff --git a/tests/_helpers/monetization.js b/tests/_helpers/monetization.js
new file mode 100644
index 000000000..e0c4aaca4
--- /dev/null
+++ b/tests/_helpers/monetization.js
@@ -0,0 +1,69 @@
+import { Readable } from 'node:stream';
+
+let counter = 0;
+
+export function createTestAgent(overrides = {}) {
+ const userId = `user-${++counter}`;
+ const agentId = `agent-${counter}-test-0000-0000-000000000000`;
+ const agent = {
+ id: agentId,
+ user_id: userId,
+ name: 'Test Agent',
+ meta: {
+ payments: {
+ configured: true,
+ provider: 'pumpfun',
+ mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ receiver: 'So11111111111111111111111111111111111111112',
+ cluster: 'mainnet',
+ default_price: { amount: '1000000', currency: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' },
+ },
+ },
+ ...overrides,
+ };
+ return { agent, session: { id: userId } };
+}
+
+export function createTestUser() {
+ const userId = `user-${++counter}`;
+ return { session: { id: userId } };
+}
+
+export function makeReq({ method = 'GET', url = '/', headers = {}, body = null, query = null } = {}) {
+ const base = body
+ ? Readable.from([Buffer.from(JSON.stringify(body))])
+ : Readable.from([]);
+ base.method = method;
+ base.url = url;
+ base.headers = {
+ host: 'localhost',
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ if (query) base.query = query;
+ return base;
+}
+
+export function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+export async function invoke(handler, reqOpts) {
+ const req = makeReq(reqOpts);
+ const res = makeRes();
+ await handler(req, res);
+ const payload = res.body ? JSON.parse(res.body) : null;
+ return { res, status: res.statusCode, body: payload };
+}
diff --git a/tests/agent-monetization.test.js b/tests/agent-monetization.test.js
new file mode 100644
index 000000000..f8770b1c6
--- /dev/null
+++ b/tests/agent-monetization.test.js
@@ -0,0 +1,552 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { createTestAgent, createTestUser, invoke } from './_helpers/monetization.js';
+
+// ── Mock state ────────────────────────────────────────────────────────────────
+
+const authState = { session: null, bearer: null };
+const sqlState = { queue: [], calls: [] };
+const rlState = { success: true };
+
+// ── Mocks ─────────────────────────────────────────────────────────────────────
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+}));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: rlState.success })),
+ publicIp: vi.fn(async () => ({ success: rlState.success })),
+ pricingPerIp: vi.fn(async () => ({ success: rlState.success })),
+ withdrawalPerUser: vi.fn(async () => ({ success: rlState.success })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+// ── Handler imports (after mocks) ─────────────────────────────────────────────
+
+const { default: pricingSkillHandler } = await import('../api/agents/[id]/pricing/[skill].js');
+const { default: pricingIndexHandler } = await import('../api/agents/[id]/pricing/index.js');
+const { default: x402Handler } = await import('../api/agents/x402/[action].js');
+const { default: revenueHandler } = await import('../api/billing/revenue.js');
+const { default: withdrawalsHandler } = await import('../api/billing/withdrawals/index.js');
+
+// ── Reset between tests ───────────────────────────────────────────────────────
+
+beforeEach(() => {
+ authState.session = null;
+ authState.bearer = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+ rlState.success = true;
+});
+
+// ── 1. Pricing CRUD ───────────────────────────────────────────────────────────
+
+describe('Pricing CRUD', () => {
+ it('owner can set a new skill price', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // agent lookup
+ sqlState.queue.push([]); // no existing price
+ sqlState.queue.push([]); // upsert (no RETURNING)
+ sqlState.queue.push([
+ {
+ id: 'price-1',
+ skill: 'answer-question',
+ currency_mint: 'USDC-MINT',
+ chain: 'solana',
+ amount: 1000000,
+ is_active: true,
+ },
+ ]);
+
+ const { status, body } = await invoke(pricingSkillHandler, {
+ method: 'PUT',
+ url: `/api/agents/${agent.id}/pricing/answer-question`,
+ body: { currency_mint: 'USDC-MINT', chain: 'solana', amount: 1000000 },
+ });
+
+ expect(status).toBe(201);
+ expect(body.amount).toBe(1000000);
+ expect(body.skill).toBe('answer-question');
+ });
+
+ it('owner can update an existing skill price', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ sqlState.queue.push([{ id: 'price-1' }]); // existing price
+ sqlState.queue.push([]); // upsert
+ sqlState.queue.push([{ id: 'price-1', skill: 'echo', currency_mint: 'MINT', chain: 'solana', amount: 500000, is_active: true }]);
+
+ const { status } = await invoke(pricingSkillHandler, {
+ method: 'PUT',
+ url: `/api/agents/${agent.id}/pricing/echo`,
+ body: { currency_mint: 'MINT', chain: 'solana', amount: 500000 },
+ });
+
+ expect(status).toBe(200);
+ });
+
+ it('non-owner gets 403', async () => {
+ const { agent } = createTestAgent();
+ const { session: otherSession } = createTestUser();
+ authState.session = otherSession;
+
+ // agent belongs to a different user_id
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+
+ const { status, body } = await invoke(pricingSkillHandler, {
+ method: 'PUT',
+ url: `/api/agents/${agent.id}/pricing/echo`,
+ body: { currency_mint: 'MINT', chain: 'solana', amount: 1000 },
+ });
+
+ expect(status).toBe(403);
+ expect(body.error).toBe('forbidden');
+ });
+
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke(pricingSkillHandler, {
+ method: 'PUT',
+ url: '/api/agents/agent-1/pricing/echo',
+ body: { currency_mint: 'MINT', chain: 'solana', amount: 1000 },
+ });
+
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('owner can list active skill prices', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id }]); // agent lookup
+ sqlState.queue.push([
+ { id: 'price-1', skill: 'echo', currency_mint: 'MINT', chain: 'solana', amount: 1000000, is_active: true },
+ { id: 'price-2', skill: 'summarize', currency_mint: 'MINT', chain: 'solana', amount: 2000000, is_active: true },
+ ]);
+
+ const { status, body } = await invoke(pricingIndexHandler, {
+ method: 'GET',
+ url: `/api/agents/${agent.id}/pricing`,
+ });
+
+ expect(status).toBe(200);
+ expect(body.prices).toHaveLength(2);
+ expect(body.prices[0].amount).toBe(1000000);
+ });
+
+ it('owner can soft-delete a skill price', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ sqlState.queue.push([]); // update
+
+ const { status, body } = await invoke(pricingSkillHandler, {
+ method: 'DELETE',
+ url: `/api/agents/${agent.id}/pricing/echo`,
+ });
+
+ expect(status).toBe(200);
+ expect(body.deleted).toBe(true);
+ });
+});
+
+// ── 2. x402 Manifest ──────────────────────────────────────────────────────────
+
+describe('x402 Manifest', () => {
+ it('returns manifest when agent has payments configured', async () => {
+ const { agent } = createTestAgent();
+
+ sqlState.queue.push([agent]);
+
+ const { status, body } = await invoke(x402Handler, {
+ method: 'GET',
+ url: `/api/agents/x402/manifest?agent_id=${agent.id}&skill=echo`,
+ });
+
+ expect(status).toBe(200);
+ expect(body.agent_id).toBe(agent.id);
+ expect(body.skill).toBe('echo');
+ expect(body.amount).toBeDefined();
+ expect(body.intent_url).toBe('/api/agents/payments/pay-prep');
+ });
+
+ it('uses skill-level price from meta.skill_prices when available', async () => {
+ const { agent } = createTestAgent({
+ meta: {
+ payments: { configured: true, receiver: 'recv-wallet', cluster: 'mainnet' },
+ skill_prices: { 'answer-question': { amount: '5000000', currency: 'USDC-MINT' } },
+ },
+ });
+
+ sqlState.queue.push([agent]);
+
+ const { status, body } = await invoke(x402Handler, {
+ method: 'GET',
+ url: `/api/agents/x402/manifest?agent_id=${agent.id}&skill=answer-question`,
+ });
+
+ expect(status).toBe(200);
+ expect(body.amount).toBe('5000000');
+ expect(body.currency).toBe('USDC-MINT');
+ });
+
+ it('returns 404 when agent does not exist', async () => {
+ sqlState.queue.push([]); // no agent
+
+ const { status, body } = await invoke(x402Handler, {
+ method: 'GET',
+ url: '/api/agents/x402/manifest?agent_id=nonexistent&skill=echo',
+ });
+
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('returns 409 when agent has not enabled payments', async () => {
+ const { agent } = createTestAgent({ meta: { payments: { configured: false } } });
+
+ sqlState.queue.push([agent]);
+
+ const { status, body } = await invoke(x402Handler, {
+ method: 'GET',
+ url: `/api/agents/x402/manifest?agent_id=${agent.id}&skill=echo`,
+ });
+
+ expect(status).toBe(409);
+ expect(body.error).toBe('no_payments');
+ });
+
+ it('returns 400 when agent_id or skill is missing', async () => {
+ const { status, body } = await invoke(x402Handler, {
+ method: 'GET',
+ url: '/api/agents/x402/manifest?agent_id=agent-1',
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+});
+
+// ── 3. Revenue Attribution ────────────────────────────────────────────────────
+
+describe('Revenue Attribution', () => {
+ it('consuming a paid intent creates a revenue event with correct fee', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+ const intentId = 'intent-test-001';
+
+ // agent lookup (needs user_id for insertNotification)
+ sqlState.queue.push([agent]);
+ // verifyPaid: intent is paid, amount matches default_price
+ sqlState.queue.push([
+ {
+ id: intentId,
+ agent_id: agent.id,
+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ amount: '1000000',
+ status: 'paid',
+ paid_at: new Date().toISOString(),
+ payload: null,
+ end_time: null,
+ },
+ ]);
+ // consumeIntent UPDATE and revenue event INSERT both hit empty queue → []
+
+ const { status, body } = await invoke(x402Handler, {
+ method: 'POST',
+ url: '/api/agents/x402/invoke',
+ headers: { 'x-payment-intent': intentId },
+ body: { agent_id: agent.id, skill: 'echo', args: { msg: 'hello' } },
+ });
+
+ expect(status).toBe(200);
+ expect(body.ok).toBe(true);
+ expect(body.intent_id).toBe(intentId);
+
+ // Verify revenue event INSERT was called with correct fee (2.5% of 1_000_000)
+ const revenueCall = sqlState.calls.find((c) =>
+ c.query.includes('agent_revenue_events'),
+ );
+ expect(revenueCall).toBeDefined();
+ expect(revenueCall.values).toContain(25000); // fee: floor(1_000_000 * 250 / 10_000)
+ expect(revenueCall.values).toContain(975000); // net: 1_000_000 - 25_000
+ });
+
+ it('unpaid request (no intent header) receives 402', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([agent]); // agent lookup
+
+ const { status } = await invoke(x402Handler, {
+ method: 'POST',
+ url: '/api/agents/x402/invoke',
+ // no x-payment-intent header → verifyPaid returns null → emit402
+ body: { agent_id: agent.id, skill: 'echo', args: {} },
+ });
+
+ expect(status).toBe(402);
+ });
+
+ it('second invoke with already-consumed intent returns 402', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+ const intentId = 'intent-double-001';
+
+ // First invoke: intent is paid → succeeds
+ sqlState.queue.push([agent]);
+ sqlState.queue.push([{
+ id: intentId,
+ agent_id: agent.id,
+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ amount: '1000000',
+ status: 'paid',
+ paid_at: new Date().toISOString(),
+ payload: null,
+ end_time: null,
+ }]);
+
+ const { status: first } = await invoke(x402Handler, {
+ method: 'POST',
+ url: '/api/agents/x402/invoke',
+ headers: { 'x-payment-intent': intentId },
+ body: { agent_id: agent.id, skill: 'echo', args: {} },
+ });
+ expect(first).toBe(200);
+
+ // Second invoke: intent is consumed → verifyPaid finds no 'paid' row → 402
+ sqlState.queue.push([agent]);
+ sqlState.queue.push([]); // empty result: no 'paid' intent → verifyPaid returns null
+
+ const { status: second } = await invoke(x402Handler, {
+ method: 'POST',
+ url: '/api/agents/x402/invoke',
+ headers: { 'x-payment-intent': intentId },
+ body: { agent_id: agent.id, skill: 'echo', args: {} },
+ });
+ expect(second).toBe(402);
+ });
+});
+
+// ── 4. Revenue Dashboard ──────────────────────────────────────────────────────
+
+describe('Revenue Dashboard', () => {
+ it('returns correct revenue totals', async () => {
+ authState.session = { id: 'user-1' };
+
+ // revenue.js calls sql`` for agentFilter when agentId is null
+ sqlState.queue.push([]); // agentFilter = sql``
+ // summary query
+ sqlState.queue.push([
+ {
+ gross_total: 1000000n,
+ fee_total: 25000n,
+ net_total: 975000n,
+ payment_count: 1,
+ currency_mint: 'USDC-MINT',
+ chain: 'solana',
+ },
+ ]);
+ // by_skill query
+ sqlState.queue.push([{ skill: 'echo', net_total: 975000n, count: 1 }]);
+ // timeseries query
+ sqlState.queue.push([{ period: '2026-04-01T00:00:00.000Z', net_total: 975000n, count: 1 }]);
+
+ const { status, body } = await invoke(revenueHandler, {
+ method: 'GET',
+ url: '/api/billing/revenue',
+ });
+
+ expect(status).toBe(200);
+ expect(body.summary.gross_total).toBe(1000000);
+ expect(body.summary.net_total).toBe(975000);
+ expect(body.summary.payment_count).toBe(1);
+ expect(body.by_skill).toHaveLength(1);
+ expect(body.by_skill[0].skill).toBe('echo');
+ expect(body.timeseries).toHaveLength(1);
+ });
+
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke(revenueHandler, {
+ method: 'GET',
+ url: '/api/billing/revenue',
+ });
+
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('returns 400 on invalid granularity param', async () => {
+ authState.session = { id: 'user-1' };
+
+ // granularity is read from req.query, pass it via query option
+ const { status, body } = await invoke(revenueHandler, {
+ method: 'GET',
+ url: '/api/billing/revenue',
+ query: { granularity: 'invalid' },
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+});
+
+// ── 5. Withdrawals ────────────────────────────────────────────────────────────
+
+describe('Withdrawals', () => {
+ const VALID_WITHDRAWAL = {
+ amount: 1_000_000, // minimum withdrawal is 1 USDC (1_000_000 raw units)
+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ chain: 'solana',
+ to_address: 'So11111111111111111111111111111111111111112',
+ };
+
+ it('owner can request a withdrawal when balance is sufficient', async () => {
+ authState.session = { id: 'user-1' };
+
+ // balance check
+ sqlState.queue.push([{ earned: 10_000_000n, pending_amount: 0n }]);
+ // insert withdrawal
+ sqlState.queue.push([
+ {
+ id: 'w-1',
+ agent_id: null,
+ amount: 1_000_000,
+ currency_mint: VALID_WITHDRAWAL.currency_mint,
+ chain: 'solana',
+ to_address: VALID_WITHDRAWAL.to_address,
+ status: 'pending',
+ tx_signature: null,
+ created_at: '2026-04-30T00:00:00Z',
+ updated_at: '2026-04-30T00:00:00Z',
+ },
+ ]);
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/billing/withdrawals',
+ body: VALID_WITHDRAWAL,
+ });
+
+ expect(status).toBe(201);
+ expect(body.withdrawal.status).toBe('pending');
+ expect(body.withdrawal.amount).toBe(1_000_000);
+ });
+
+ it('over-withdrawal is rejected with 422', async () => {
+ authState.session = { id: 'user-1' };
+
+ // available: 2_000_000, request: 9_999_999_999
+ sqlState.queue.push([{ earned: 2_000_000n, pending_amount: 0n }]);
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/billing/withdrawals',
+ body: { ...VALID_WITHDRAWAL, amount: 9_999_999_999 },
+ });
+
+ expect(status).toBe(422);
+ expect(body.error).toBe('insufficient_balance');
+ });
+
+ it('below-minimum withdrawal is rejected with 422', async () => {
+ authState.session = { id: 'user-1' };
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/billing/withdrawals',
+ body: { ...VALID_WITHDRAWAL, amount: 500_000 },
+ });
+
+ expect(status).toBe(422);
+ expect(body.error).toBe('below_minimum');
+ });
+
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/billing/withdrawals',
+ body: VALID_WITHDRAWAL,
+ });
+
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('owner can list withdrawal history', async () => {
+ authState.session = { id: 'user-1' };
+
+ sqlState.queue.push([
+ { id: 'w-1', amount: 1_000_000, status: 'pending', created_at: '2026-04-30T00:00:00Z' },
+ ]);
+ sqlState.queue.push([{ total: 1 }]);
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'GET',
+ url: '/api/billing/withdrawals',
+ });
+
+ expect(status).toBe(200);
+ expect(body.withdrawals).toHaveLength(1);
+ expect(body.total).toBe(1);
+ });
+});
+
+// ── 6. Rate Limiting ──────────────────────────────────────────────────────────
+
+describe('Rate Limiting', () => {
+ it('manifest endpoint returns 429 when rate limit is exceeded', async () => {
+ rlState.success = false;
+
+ const { status, body } = await invoke(x402Handler, {
+ method: 'GET',
+ url: '/api/agents/x402/manifest?agent_id=agent-1&skill=echo',
+ });
+
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+
+ it('withdrawals endpoint returns 429 when rate limit is exceeded', async () => {
+ authState.session = { id: 'user-1' };
+ rlState.success = false;
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/billing/withdrawals',
+ body: { amount: 1_000_000, currency_mint: 'MINT', chain: 'solana', to_address: 'addr' },
+ });
+
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+
+ it('pricing endpoint returns 429 when rate limit is exceeded', async () => {
+ authState.session = { id: 'user-1' };
+ rlState.success = false;
+
+ const { status, body } = await invoke(pricingIndexHandler, {
+ method: 'GET',
+ url: '/api/agents/agent-1/pricing',
+ });
+
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 8aea10a56..cf711fc47 100644
--- a/vercel.json
+++ b/vercel.json
@@ -214,6 +214,7 @@
{ "src": "/api/dca-strategies", "dest": "/api/dca-strategies" },
{ "src": "/api/billing/summary", "dest": "/api/billing/summary" },
+ { "src": "/api/billing/revenue", "dest": "/api/billing/revenue" },
{ "src": "/my-agents", "dest": "/public/my-agents/index.html" },
{ "src": "/my-agents/", "dest": "/public/my-agents/index.html" },