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(platform): expand agent tooling, bounties, MCP catalog, and x402 reliability

nirholasfb533a6ec71b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4d0772d8a..ecf5c47db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,11 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-09-25
+
+- **Props the platform pays Forge to make now land in the /forged gallery**: Every half hour the platform pays its own Forge to make a new 3D prop for the public /forged gallery. A standard generation takes 20 to 55 seconds, but the paying side gave up after 20. Forge still finished the model and took the payment, so most of those props were paid for, never saved to the gallery, and logged as failed. The paying side now waits up to 90 seconds for a generation. Each paid prop lands in the gallery, and the payment health numbers stop counting these successful payments as failures. (`/forged`) `[fix, infra]`
+- **The model catalog AI clients read now shows the real price of every model**: The three://models resource that Claude and other MCP clients read listed free models with no price and left some paid models blank. Free models now read as costing nothing, and a model served through a partner route is priced at the model that actually answers, so an assistant comparing costs for you works from real numbers. (`/docs/mcp`) `[fix, sdk]`
+
## 2026-09-24
- **Docs · Trade receipts** (`/docs/trade-receipts`): Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.
diff --git a/api/_lib/agents-v1/runs.js b/api/_lib/agents-v1/runs.js
index aea835ae6..c02833113 100644
--- a/api/_lib/agents-v1/runs.js
+++ b/api/_lib/agents-v1/runs.js
@@ -25,6 +25,7 @@ import { providerChainFor } from '../llm-tool-chain.js';
import { isFreeLane } from '../llm-pricing.js';
import { agentToolSchemas, agentToolHandlers } from '../agent-tools.js';
import { debitCredits } from '../credits.js';
+import { assertAgentBudget, InferenceBillingError } from '../inference-billing.js';
import { AGENT_SYSTEM_NOTE, createAgentLoop, finalAnswer, initialLoopState, loopFinished } from '../agent-loop.js';
const LEASE_SECONDS = 120;
@@ -305,6 +306,15 @@ export async function stepRun(runId, { owner = `step:${randomUUID()}` } = {}) {
});
}
+ // A run that can spend on paid lanes is held to its agent's inference
+ // budget before every model step, the same budget chat completions and the
+ // strategy loop answer to. The first refusal in a window stops the agent's
+ // automations and notifies the owner (assertAgentBudget latches it).
+ if (toNumber(run.budget_credits_usd) > 0) {
+ const refused = await agentBudgetRefusal(run);
+ if (refused) return finalize(run, 'budget_exhausted', refused);
+ }
+
const events = [];
const { schemas, handlers } = toolsFor(run);
const loop = createAgentLoop({
@@ -346,10 +356,11 @@ export async function stepRun(runId, { owner = `step:${randomUUID()}` } = {}) {
userId: run.user_id,
amountUsd: costUsd,
action: 'agent_run_step',
- refType: 'agent_run',
- refId: run.id,
+ // Booked against the agent, so its inference budget counts run spend.
+ refType: 'agent',
+ refId: String(run.agent_id),
idempotencyKey: `agent_run:${run.id}:${run.step_count + 1}`,
- meta: { agentId: run.agent_id },
+ meta: { agentId: run.agent_id, runId: run.id },
});
spent += costUsd;
} catch (err) {
@@ -382,6 +393,21 @@ export async function stepRun(runId, { owner = `step:${randomUUID()}` } = {}) {
return row;
}
+/** The run's refusal when its agent's inference budget is used up, else null. */
+async function agentBudgetRefusal(run) {
+ const [agent] = await sql`SELECT id, name, meta FROM agent_identities WHERE id = ${run.agent_id} LIMIT 1`;
+ if (!agent) return null;
+ try {
+ await assertAgentBudget({ userId: run.user_id, agent });
+ return null;
+ } catch (err) {
+ if (err instanceof InferenceBillingError) {
+ return { error: err.message, note: err.code };
+ }
+ throw err;
+ }
+}
+
async function persistEvents(run, events) {
let costUsd = 0;
const rows = [];
diff --git a/api/_lib/bounties/sources/devfolio.js b/api/_lib/bounties/sources/devfolio.js
new file mode 100644
index 000000000..880758ab2
--- /dev/null
+++ b/api/_lib/bounties/sources/devfolio.js
@@ -0,0 +1,101 @@
+// Hackathons open for applications on a second public hackathon platform.
+//
+// Its search endpoint returns every event whose applications are open, with
+// the full description, prize list, themes and registration deadline. Prize
+// money is stated inside prize descriptions ("a total cash prize pool of
+// $1,000"), so the reward is the largest amount the organizer wrote down,
+// never an estimate.
+
+import { fetchUpstreamJson } from '../../upstream-fetch.js';
+import { markdownToText, tagList } from '../normalize.js';
+
+export const id = 'devfolio';
+export const label = 'Hackathon platform';
+export const venue = 'Devfolio';
+export const venueUrl = 'https://devfolio.co/hackathons';
+
+const PAGE_SIZE = 50;
+const AMOUNT_RE = /([$₹])\s?([\d,]+(?:\.\d+)?)\s*([kKmM]|lakh|lakhs|L)?\b/g;
+
+/** Largest stated prize amount in free text, preferring USD. Pure. */
+export function largestPrize(texts) {
+ const best = { USD: 0, INR: 0 };
+ for (const t of texts) {
+ for (const m of String(t || '').matchAll(AMOUNT_RE)) {
+ let n = Number(m[2].replace(/,/g, ''));
+ if (!Number.isFinite(n)) continue;
+ const unit = (m[3] || '').toLowerCase();
+ if (unit === 'k') n *= 1_000;
+ else if (unit === 'm') n *= 1_000_000;
+ else if (unit.startsWith('l')) n *= 100_000;
+ const cur = m[1] === '$' ? 'USD' : 'INR';
+ if (n > best[cur]) best[cur] = n;
+ }
+ }
+ if (best.USD > 0) return { amount: best.USD, currency: 'USD' };
+ if (best.INR > 0) return { amount: best.INR, currency: 'INR' };
+ return { amount: null, currency: null };
+}
+
+/** Map one search hit to a listing. Pure. */
+export function mapHackathon(s) {
+ if (!s?.uuid || !s.name || !s.slug) return null;
+ const prizes = Array.isArray(s.prizes) ? s.prizes : [];
+ const { amount, currency } = largestPrize([...prizes.map((p) => `${p.name || ''} ${p.desc || ''}`), s.desc]);
+ const themes = (s.themes || []).map((t) => (typeof t === 'string' ? t : t?.name)).filter(Boolean);
+ const where = s.is_online ? 'Online' : [s.city, s.country].filter(Boolean).join(', ') || s.location || null;
+ const body = markdownToText(s.desc || '');
+ const deadline = s.hackathon_setting?.reg_ends_at || s.ends_at || null;
+ return {
+ source: id,
+ externalId: String(s.uuid),
+ kind: 'hackathon',
+ title: s.name,
+ summary: [s.tagline, where].filter(Boolean).join(' · ') || null,
+ body,
+ url: `https://${s.slug}.devfolio.co/`,
+ venue,
+ venueUrl,
+ sponsor: s.hosted_by?.name || null,
+ sponsorLogo: typeof s.cover_img === 'string' && /^https:\/\//.test(s.cover_img) ? s.cover_img : null,
+ rewardAmount: amount,
+ rewardCurrency: currency,
+ rewardUsd: currency === 'USD' ? amount : null,
+ deadline,
+ requirements: [
+ 'Apply to the hackathon before registration closes.',
+ s.team_size ? `Teams of ${s.team_min || 1} to ${s.team_size}.` : null,
+ s.is_online ? null : `Attend in person${where ? ` in ${where}` : ''}.`,
+ 'Submit the project on the hackathon page before judging.',
+ ].filter(Boolean),
+ skills: tagList(themes),
+ agentEligible: s.is_online ? null : false,
+ submitMode: 'checklist',
+ status: 'open',
+ submissionsCount: Number.isFinite(s.projects_submitted) ? s.projects_submitted : null,
+ raw: { starts_at: s.starts_at || null, ends_at: s.ends_at || null, participants: s.participants_count ?? null, online: !!s.is_online },
+ };
+}
+
+export async function fetchListings() {
+ const out = [];
+ for (let from = 0; from < 200; from += PAGE_SIZE) {
+ const data = await fetchUpstreamJson(
+ 'https://api.devfolio.co/api/search/hackathons',
+ {
+ method: 'POST',
+ headers: { accept: 'application/json', 'content-type': 'application/json', 'user-agent': 'three.ws-bounty-feed' },
+ body: JSON.stringify({ type: 'application_open', from, size: PAGE_SIZE }),
+ },
+ { name: 'bounties-devfolio', timeoutMs: 12_000, label: 'hackathon platform' },
+ );
+ const hits = Array.isArray(data?.hits?.hits) ? data.hits.hits : [];
+ for (const h of hits) {
+ const l = mapHackathon(h?._source);
+ if (l) out.push(l);
+ }
+ const total = Number(data?.hits?.total?.value || 0);
+ if (hits.length < PAGE_SIZE || from + PAGE_SIZE >= total) break;
+ }
+ return out;
+}
diff --git a/api/_lib/bounties/sources/devpost.js b/api/_lib/bounties/sources/devpost.js
new file mode 100644
index 000000000..a10aa65c5
--- /dev/null
+++ b/api/_lib/bounties/sources/devpost.js
@@ -0,0 +1,105 @@
+// Open hackathons from the largest public hackathon directory.
+//
+// Its hackathon index is served as JSON to its own listing page, sorted by
+// prize pool, with the open state, dates, themes, organizer and total prize
+// amount per event. Three pages covers every open event with a cash prize.
+
+import { fetchUpstreamJson } from '../../upstream-fetch.js';
+import { htmlToText, tagList } from '../normalize.js';
+
+export const id = 'devpost';
+export const label = 'Hackathon directory';
+export const venue = 'Devpost';
+export const venueUrl = 'https://devpost.com/hackathons';
+
+const PAGES = 3;
+const SYMBOLS = { $: 'USD', '€': 'EUR', '£': 'GBP', '₹': 'INR', '¥': 'JPY' };
+const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
+
+/** "$<span>740,000</span>" -> { amount: 740000, currency: 'USD' }. Pure. */
+export function parsePrize(html) {
+ const text = htmlToText(html || '').replace(/\s+/g, '');
+ const m = /^([$€£₹¥])([\d,]+(?:\.\d+)?)/.exec(text);
+ if (!m) return { amount: null, currency: null };
+ const amount = Number(m[2].replace(/,/g, ''));
+ return Number.isFinite(amount) && amount > 0 ? { amount, currency: SYMBOLS[m[1]] } : { amount: null, currency: null };
+}
+
+/**
+ * End of a submission window such as "Jul 31 - Oct 01, 2026" or
+ * "Sep 01 - 30, 2026", as the last second of that UTC day. Pure.
+ */
+export function parseSubmissionEnd(dates) {
+ const s = String(dates || '').trim();
+ const year = /(\d{4})\s*$/.exec(s)?.[1];
+ if (!year) return null;
+ const [startPart, endPart = startPart] = s.replace(/,\s*\d{4}\s*$/, '').split(/\s+-\s+/);
+ const startMonth = /^([A-Za-z]{3})/.exec(startPart.trim())?.[1];
+ const endMatch = /^(?:([A-Za-z]{3})\s+)?(\d{1,2})$/.exec(endPart.trim());
+ if (!endMatch) return null;
+ const month = MONTHS.indexOf(String(endMatch[1] || startMonth || '').toLowerCase());
+ if (month < 0) return null;
+ const d = new Date(Date.UTC(Number(year), month, Number(endMatch[2]), 23, 59, 59));
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+}
+
+/** Map one hackathon record to a listing. Pure. */
+export function mapHackathon(h) {
+ if (!h?.id || !h.title || !h.url) return null;
+ const url = String(h.url).startsWith('//') ? `https:${h.url}` : String(h.url);
+ const { amount, currency } = parsePrize(h.prize_amount);
+ const themes = (h.themes || []).map((t) => t?.name).filter(Boolean);
+ const where = h.displayed_location?.location || null;
+ const summaryParts = [
+ h.organization_name ? `Hosted by ${h.organization_name}.` : null,
+ where ? `${where}.` : null,
+ themes.length ? `Themes: ${themes.join(', ')}.` : null,
+ h.prizes_counts?.cash ? `${h.prizes_counts.cash} cash prizes.` : null,
+ h.time_left_to_submission ? `${h.time_left_to_submission} to submit.` : null,
+ ].filter(Boolean);
+ return {
+ source: id,
+ externalId: String(h.id),
+ kind: 'hackathon',
+ title: h.title,
+ summary: summaryParts.join(' ') || null,
+ body: summaryParts.join('\n'),
+ url,
+ venue,
+ venueUrl,
+ sponsor: h.organization_name || null,
+ sponsorLogo: h.thumbnail_url ? (String(h.thumbnail_url).startsWith('//') ? `https:${h.thumbnail_url}` : h.thumbnail_url) : null,
+ rewardAmount: amount,
+ rewardCurrency: currency,
+ rewardUsd: currency === 'USD' ? amount : null,
+ deadline: parseSubmissionEnd(h.submission_period_dates),
+ requirements: [
+ 'Register for the hackathon on its page.',
+ 'Build a project inside the submission window and submit it with a demo video and repository link.',
+ ],
+ skills: tagList(themes),
+ agentEligible: h.invite_only ? false : null,
+ submitMode: 'checklist',
+ status: h.open_state === 'open' && !h.invite_only ? 'open' : 'closed',
+ submissionsCount: null,
+ raw: { registrations: h.registrations_count ?? null, dates: h.submission_period_dates || null, gallery: h.submission_gallery_url || null },
+ };
+}
+
+export async function fetchListings() {
+ const out = [];
+ for (let page = 1; page <= PAGES; page++) {
+ const data = await fetchUpstreamJson(
+ `https://devpost.com/api/hackathons?status[]=open&order_by=prize-amount&page=${page}`,
+ { headers: { accept: 'application/json', 'user-agent': 'three.ws-bounty-feed' } },
+ { name: 'bounties-devpost', timeoutMs: 12_000, label: 'hackathon directory' },
+ );
+ const items = Array.isArray(data?.hackathons) ? data.hackathons : [];
+ for (const h of items) {
+ const l = mapHackathon(h);
+ if (l) out.push(l);
+ }
+ if (!items.length) break;
+ }
+ return out;
+}
diff --git a/api/_lib/bounties/sources/github.js b/api/_lib/bounties/sources/github.js
new file mode 100644
index 000000000..6741acc21
--- /dev/null
+++ b/api/_lib/bounties/sources/github.js
@@ -0,0 +1,113 @@
+// Open-source code bounties posted as GitHub issues.
+//
+// Paid bounty platforms for open source (the largest routes payment through a
+// GitHub app) mark a funded issue with a "💎 Bounty" label plus one "$N" label
+// per pledge, and flip a "💰 Rewarded" label on once it is paid. The public
+// issue search exposes all of it, so this adapter reads the label convention
+// directly: no scraping, no account. An optional GITHUB_TOKEN raises the
+// search quota from 10 to 30 requests a minute; the hourly refresh needs two.
+
+import { fetchUpstreamJson } from '../../upstream-fetch.js';
+import { markdownToText, parseUsdLabel, tagList } from '../normalize.js';
+
+export const id = 'github';
+export const label = 'GitHub code bounties';
+export const venue = 'GitHub';
+export const venueUrl = 'https://github.com';
+
+const BOUNTY_LABEL = '💎 Bounty';
+const REWARDED_LABEL = '💰 Rewarded';
+const PAGES = 2;
+const PER_PAGE = 50;
+
+// Labels that describe the work rather than the money or triage state.
+const NOISE_LABELS = new Set(['bounty', 'help wanted', 'good first issue', 'enhancement', 'bug', 'feature', 'documentation']);
+
+function authHeaders() {
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '';
+ const h = { accept: 'application/vnd.github+json', 'user-agent': 'three.ws-bounty-feed' };
+ if (token) h.authorization = `Bearer ${token}`;
+ return h;
+}
+
+/** owner/repo from an issue's repository_url. */
+function repoOf(issue) {
+ const m = /repos\/([^/]+\/[^/]+)$/.exec(String(issue.repository_url || ''));
+ return m ? m[1] : null;
+}
+
+/**
+ * Map one search hit to a listing. Pure.
+ * @param {any} issue
+ */
+export function mapIssue(issue) {
+ const labels = (issue.labels || []).map((l) => (typeof l === 'string' ? l : l?.name)).filter(Boolean);
+ if (!labels.includes(BOUNTY_LABEL)) return null;
+ const pledges = labels.map(parseUsdLabel).filter((n) => n != null);
+ const reward = pledges.length ? Math.max(...pledges) : null;
+ const rewarded = labels.includes(REWARDED_LABEL);
+ const repo = repoOf(issue);
+ const body = markdownToText(issue.body || '');
+ const skills = tagList(
+ labels.filter((l) => l !== BOUNTY_LABEL && l !== REWARDED_LABEL && parseUsdLabel(l) == null && !NOISE_LABELS.has(l.toLowerCase())),
+ );
+ return {
+ source: id,
+ externalId: String(issue.id),
+ kind: 'bounty',
+ title: issue.title,
+ summary: body ? body.slice(0, 400) : null,
+ body,
+ url: issue.html_url,
+ venue,
+ venueUrl: repo ? `https://github.com/${repo}` : venueUrl,
+ sponsor: repo,
+ sponsorLogo: issue.user?.avatar_url || null,
+ rewardAmount: reward,
+ rewardCurrency: reward != null ? 'USD' : null,
+ rewardUsd: reward,
+ deadline: null,
+ requirements: ['Open a pull request that resolves the issue and reference it in the PR description.'],
+ skills,
+ agentEligible: true,
+ submitMode: 'checklist',
+ status: rewarded || issue.state === 'closed' ? 'closed' : 'open',
+ submissionsCount: Number.isFinite(issue.comments) ? issue.comments : null,
+ raw: { repo, number: issue.number, labels, created_at: issue.created_at, updated_at: issue.updated_at },
+ };
+}
+
+export async function fetchListings() {
+ const q = encodeURIComponent(`label:"${BOUNTY_LABEL}" -label:"${REWARDED_LABEL}" state:open is:issue`);
+ const out = [];
+ for (let page = 1; page <= PAGES; page++) {
+ const url = `https://api.github.com/search/issues?q=${q}&sort=updated&order=desc&per_page=${PER_PAGE}&page=${page}`;
+ const data = await fetchUpstreamJson(url, { headers: authHeaders() }, { name: 'bounties-github', timeoutMs: 12_000, label: 'github bounty search' });
+ const items = Array.isArray(data?.items) ? data.items : [];
+ for (const it of items) {
+ const l = mapIssue(it);
+ if (l) out.push(l);
+ }
+ if (items.length < PER_PAGE) break;
+ }
+ return out;
+}
+
+/**
+ * Live payout state of one issue: the venue marks a paid bounty "💰 Rewarded".
+ * @param {{ repo: string, number: number }} ref
+ */
+export async function payoutStatus(ref) {
+ const issue = await fetchUpstreamJson(`https://api.github.com/repos/${ref.repo}/issues/${ref.number}`, { headers: authHeaders() }, {
+ name: 'bounties-github',
+ label: 'github issue',
+ });
+ const labels = (issue.labels || []).map((l) => (typeof l === 'string' ? l : l?.name));
+ return {
+ paid: labels.includes(REWARDED_LABEL),
+ state: issue.state,
+ closed_at: issue.closed_at || null,
+ pledges_usd: labels.map(parseUsdLabel).filter((n) => n != null),
+ url: issue.html_url,
+ };
+}
diff --git a/api/_lib/fixed-launch.js b/api/_lib/fixed-launch.js
index 0870f442d..0973989f9 100644
--- a/api/_lib/fixed-launch.js
+++ b/api/_lib/fixed-launch.js
@@ -266,3 +266,107 @@ export async function fixedEligibility({ network, wallet, connection = null }) {
}
return { eligible: reasons.length === 0, reasons, wallet_lamports: lamports, required_lamports: FIXED_LAUNCH_COST_LAMPORTS };
}
+
+// ── Launch flows ───────────────────────────────────────────────────────────
+//
+// Everything that names the venue's own identifiers stays in this module; the
+// launch service (api/_lib/launch-service.js) and the routes speak only of a
+// "launch account", which is what the venue calls its per-launch state account.
+
+/**
+ * The venue builder's transactions for a creator wallet, inspected: every one
+ * is fee-paid by the creator and together they create the prepared mint.
+ * @returns {Promise<{ transactions_base64: string[], mint: string, launch_account: string, input: object }>}
+ */
+export async function prepareFixedForWallet({ network = 'mainnet', wallet, fundsRecipient = null, launch }) {
+ const prepared = await prepareFixedLaunch({ network, wallet, fundsRecipient, launch });
+ inspectPreparedTransactions(prepared.transactions_base64, { wallet, mint: prepared.mint });
+ return {
+ transactions_base64: prepared.transactions_base64,
+ mint: prepared.mint,
+ launch_account: prepared.genesis_account,
+ input: prepared.input,
+ };
+}
+
+/**
+ * A wallet-signed set must be exactly the prepared set: same count, and each
+ * message byte-identical to what the venue built. A wallet can only add its
+ * signature; any other change is refused before anything is broadcast.
+ */
+export function assertSignedMatchesPrepared(preparedBase64, signedBase64) {
+ if (!Array.isArray(signedBase64) || signedBase64.length !== preparedBase64.length) {
+ throw new FixedLaunchError(400, 'transaction_count_mismatch', `expected ${preparedBase64.length} signed transactions, got ${Array.isArray(signedBase64) ? signedBase64.length : 0}`);
+ }
+ preparedBase64.forEach((b64, i) => {
+ let signed;
+ try {
+ signed = VersionedTransaction.deserialize(Buffer.from(signedBase64[i], 'base64'));
+ } catch {
+ throw new FixedLaunchError(400, 'validation_error', `signed transaction ${i + 1} is not a serialized versioned transaction`);
+ }
+ const prepared = VersionedTransaction.deserialize(Buffer.from(b64, 'base64'));
+ const a = Buffer.from(prepared.message.serialize());
+ const b = Buffer.from(signed.message.serialize());
+ if (!a.equals(b)) throw new FixedLaunchError(422, 'transaction_modified', `signed transaction ${i + 1} differs from the prepared one`);
+ });
+}
+
+/**
+ * Land a signed launch, prove it on-chain, and register it with the venue.
+ * @returns {Promise<{ signatures: string[], venue_url: string|null, registration_error: string|null }>}
+ */
+export async function landFixedLaunch({ network = 'mainnet', signedBase64, mint, launchAccount, wallet, input }) {
+ const signatures = await submitInOrder({ network, signedBase64 });
+ await verifyFixedLaunchOnChain({ network, mint, genesisAccount: launchAccount });
+ const reg = await registerFixedLaunch({ network, wallet, genesisAccount: launchAccount, input });
+ return { signatures, venue_url: reg.venue_url, registration_error: reg.error };
+}
+
+/**
+ * The custodial path: build, sign with a server-held keypair, land, register.
+ * @returns {Promise<{ mint: string, launch_account: string, signatures: string[], venue_url: string|null, registration_error: string|null }>}
+ */
+export async function launchFixedWithKeypair({ network = 'mainnet', keypair, fundsRecipient = null, launch }) {
+ const wallet = keypair.publicKey.toBase58();
+ const prepared = await prepareFixedForWallet({ network, wallet, fundsRecipient, launch });
+ const signed = signPreparedTransactions(prepared.transactions_base64, keypair);
+ const landed = await landFixedLaunch({
+ network,
+ signedBase64: signed,
+ mint: prepared.mint,
+ launchAccount: prepared.launch_account,
+ wallet,
+ input: prepared.input,
+ });
+ return { mint: prepared.mint, launch_account: prepared.launch_account, ...landed };
+}
+
+/** Record a landed fixed-supply launch; the directory and agent profiles read this table. */
+export async function recordFixedLaunch({ userId, agentId = null, network = 'mainnet', mint, launchAccount, launch, creator, signatures, venueUrl = null }) {
+ const [row] = await sql`
+ INSERT INTO fixed_supply_launches
+ (agent_id, user_id, network, mint, genesis_account, name, symbol, image_url, description, creator_address,
+ token_allocation, raise_goal_sol, liquidity_bps, deposit_start_at, deposit_end_at, signatures, venue_url)
+ VALUES
+ (${agentId}, ${userId}, ${network}, ${mint}, ${launchAccount}, ${launch.name}, ${launch.symbol}, ${launch.image_url},
+ ${launch.description || null}, ${creator}, ${launch.token_allocation}, ${launch.raise_goal_sol}, ${launch.liquidity_bps},
+ ${launch.deposit_start_at}, ${launch.deposit_end_at}, ${JSON.stringify(signatures)}::jsonb, ${venueUrl})
+ ON CONFLICT (mint, network) DO NOTHING
+ RETURNING id, mint, network, created_at
+ `;
+ return row || null;
+}
+
+/** One fixed-supply launch by mint, with the launch account under its neutral name. */
+export async function getFixedLaunch({ mint, network = 'mainnet' }) {
+ const [row] = await sql`
+ SELECT f.id, f.agent_id, f.user_id, f.network, f.mint, f.genesis_account AS launch_account, f.name, f.symbol,
+ f.image_url, f.description, f.creator_address, f.token_allocation, f.raise_goal_sol, f.liquidity_bps,
+ f.deposit_start_at, f.deposit_end_at, f.signatures, f.venue_url, f.created_at
+ FROM fixed_supply_launches f
+ WHERE f.mint = ${mint} AND f.network = ${network}
+ LIMIT 1
+ `;
+ return row || null;
+}
diff --git a/api/_lib/inference-billing.js b/api/_lib/inference-billing.js
index 064eee985..349c41d3b 100644
--- a/api/_lib/inference-billing.js
+++ b/api/_lib/inference-billing.js
@@ -160,6 +160,15 @@ export function applyInferenceBudget(meta, budget) {
return next;
}
+/**
+ * Every credit_ledger action that is model spend on behalf of one agent, booked
+ * with ref_type 'agent' and ref_id = the agent id: the flat three-ws/agent rate
+ * (chat completions, the strategy loop) and the metered spend of a v1 run's
+ * paid model lanes. The per-agent budget is judged against all of them, so an
+ * agent cannot outrun its budget by spending through a different surface.
+ */
+export const AGENT_SPEND_ACTIONS = Object.freeze([INFERENCE_ACTION, 'agent_run_step']);
+
/** Inference credits an agent has burned today and this month (UTC). */
export async function agentInferenceSpend(agentId) {
const [row] = await sql`
@@ -172,7 +181,8 @@ export async function agentInferenceSpend(agentId) {
WHERE created_at >= (date_trunc('day', now() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC')
)::int AS calls_today
FROM credit_ledger
- WHERE action = ${INFERENCE_ACTION} AND ref_type = 'agent' AND ref_id = ${String(agentId)}
+ WHERE ref_type = 'agent' AND ref_id = ${String(agentId)}
+ AND action IN (${AGENT_SPEND_ACTIONS[0]}, ${AGENT_SPEND_ACTIONS[1]})
AND created_at >= (date_trunc('month', now() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC')
`;
return {
@@ -221,9 +231,23 @@ export async function assertInferenceAllowed({ userId, agent = null }) {
);
}
if (!agent) return { balanceUsd: acct.balanceUsd, budget: null, spend: null };
+ const { budget, spend } = await assertAgentBudget({ userId, agent });
+ return { balanceUsd: acct.balanceUsd, budget, spend };
+}
- const budget = getInferenceBudget(agent.meta);
- if (!budget) return { balanceUsd: acct.balanceUsd, budget: null, spend: null };
+/**
+ * The per-agent half of the gate, for a caller that meters credits itself (a
+ * v1 run debits its own paid lanes): refuse when the agent's daily or monthly
+ * inference budget is used up, stamping the exhaustion, stopping its
+ * automations and notifying the owner exactly once per window.
+ *
+ * @param {{ userId: string, agent: { id: string, name?: string, meta?: object } }} p
+ * @returns {Promise<{ budget: object|null, spend: object|null }>}
+ * @throws {InferenceBillingError} 402 inference_budget_exhausted
+ */
+export async function assertAgentBudget({ userId, agent }) {
+ const budget = getInferenceBudget(agent?.meta);
+ if (!budget) return { budget: null, spend: null };
const spend = await agentInferenceSpend(agent.id);
const window = exhaustedWindow(budget, spend);
@@ -251,7 +275,7 @@ export async function assertInferenceAllowed({ userId, agent = null }) {
},
);
}
- return { balanceUsd: acct.balanceUsd, budget, spend };
+ return { budget, spend };
}
/** A raised budget that actually readmits calls: double the old one, and never below 1.5x what is already spent. */
@@ -437,7 +461,7 @@ export async function inferenceUsage({ userId, agent = null }) {
SELECT COALESCE(SUM(-amount_usd), 0)::float8 AS spent7,
COUNT(*)::int AS calls7
FROM credit_ledger
- WHERE user_id = ${userId} AND action = ${INFERENCE_ACTION}
+ WHERE user_id = ${userId} AND action IN (${AGENT_SPEND_ACTIONS[0]}, ${AGENT_SPEND_ACTIONS[1]})
AND (${agentId}::text IS NULL OR (ref_type = 'agent' AND ref_id = ${agentId ? String(agentId) : null}))
AND created_at > now() - interval '7 days'
`,
@@ -457,7 +481,7 @@ export async function inferenceUsage({ userId, agent = null }) {
COALESCE(SUM((meta->>'input_tokens')::bigint), 0)::bigint AS input_tokens,
COALESCE(SUM((meta->>'output_tokens')::bigint), 0)::bigint AS output_tokens
FROM credit_ledger
- WHERE user_id = ${userId} AND action = ${INFERENCE_ACTION}
+ WHERE user_id = ${userId} AND action IN (${AGENT_SPEND_ACTIONS[0]}, ${AGENT_SPEND_ACTIONS[1]})
AND (${agentId}::text IS NULL OR (ref_type = 'agent' AND ref_id = ${agentId ? String(agentId) : null}))
AND created_at >= (date_trunc('month', now() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC')
`,
diff --git a/api/_lib/inference-topup.js b/api/_lib/inference-topup.js
index f9b20b5c6..140dbffe3 100644
--- a/api/_lib/inference-topup.js
+++ b/api/_lib/inference-topup.js
@@ -128,13 +128,35 @@ function spendLimitToTopupError(e) {
return new TopupError(403, e.code || 'spend_limit', e.message, e.detail || {});
}
-// ── preview ─────────────────────────────────────────────────────────────────
+async function checkTopupPolicy({ agent, userId, amount, payTo }) {
+ try {
+ await enforceSpendLimit({
+ agentId: agent.id,
+ meta: agent.meta,
+ userId,
+ category: CUSTODY_CATEGORY,
+ usdValue: amount,
+ asset: 'USDC',
+ destination: payTo,
+ });
+ } catch (e) {
+ if (e instanceof SpendLimitError) throw spendLimitToTopupError(e);
+ throw e;
+ }
+}
+
+// ── quote and preview ───────────────────────────────────────────────────────
/**
- * Write a single-use preview of a wallet-funded top-up. Nothing moves.
- * @returns {Promise<object>} the confirmation table the owner must approve
+ * Price a wallet-funded top-up without writing anything: reads the agent
+ * wallet from Solana, runs the owner's spend policy against it, and returns
+ * the confirmation table. previewTopup() is this plus the single-use preview
+ * row; a dry run (scripts/inference-topup-dryrun.mjs) calls it directly.
+ * `checkPolicy: false` skips the spend-policy pass, whose anomaly guard can
+ * record an event or freeze the wallet: a dry run must write nothing.
+ * @returns {Promise<object>} the confirmation table (no preview_id)
*/
-export async function previewTopup({ userId, agentId, amountUsdc, source = 'owner' }) {
+export async function quoteTopup({ userId, agentId, amountUsdc, checkPolicy = true }) {
const amount = normalizeTopupAmount(amountUsdc);
const agent = await loadOwnedAgent(agentId, userId);
const payTo = treasuryAddress();
@@ -155,20 +177,7 @@ export async function previewTopup({ userId, agentId, amountUsdc, source = 'owne
// Fail fast on the owner's own policy (freeze, per-tx cap, English rules)
// so a preview never shows a top-up the guard would refuse. The binding
// check is the atomic reserve at execution time.
- try {
- await enforceSpendLimit({
- agentId: agent.id,
- meta: agent.meta,
- userId,
- category: CUSTODY_CATEGORY,
- usdValue: amount,
- asset: 'USDC',
- destination: payTo,
- });
- } catch (e) {
- if (e instanceof SpendLimitError) throw spendLimitToTopupError(e);
- throw e;
- }
+ if (checkPolicy) await checkTopupPolicy({ agent, userId, amount, payTo });
const sponsor = sponsorOrNull();
if (!sponsor && !(balances.sol > 0.00001)) {
@@ -177,18 +186,7 @@ export async function previewTopup({ userId, agentId, amountUsdc, source = 'owne
const credits = creditsForUsdc(amount);
const acct = await getCreditAccount(userId);
- const [row] = await sql`
- INSERT INTO inference_topups
- (user_id, agent_id, source, status, amount_usdc, credits_usd, payer_address, pay_to, network, expires_at)
- VALUES
- (${userId}, ${agent.id}, ${source}, 'previewed', ${amount.toFixed(6)}, ${credits.toFixed(6)},
- ${agent.meta.solana_address}, ${payTo}, 'mainnet', now() + make_interval(mins => ${PREVIEW_TTL_MINUTES}))
- RETURNING id, expires_at
- `;
-
return {
- preview_id: row.id,
- expires_at: row.expires_at,
confirm_flag: 'confirm_deposit',
agent: { id: agent.id, name: agent.name },
from: agent.meta.solana_address,
@@ -207,9 +205,27 @@ export async function previewTopup({ userId, agentId, amountUsdc, source = 'owne
wallet_usdc_after: Math.round((balances.usdc - amount) * 1e6) / 1e6,
balance_before_usd: acct.balanceUsd,
balance_after_usd: Math.round((acct.balanceUsd + credits) * 1e6) / 1e6,
+ policy_checked: checkPolicy,
};
}
+/**
+ * Write a single-use preview of a wallet-funded top-up. Nothing moves.
+ * @returns {Promise<object>} the confirmation table the owner must approve
+ */
+export async function previewTopup({ userId, agentId, amountUsdc, source = 'owner' }) {
+ const quote = await quoteTopup({ userId, agentId, amountUsdc });
+ const [row] = await sql`
+ INSERT INTO inference_topups
+ (user_id, agent_id, source, status, amount_usdc, credits_usd, payer_address, pay_to, network, expires_at)
+ VALUES
+ (${userId}, ${quote.agent.id}, ${source}, 'previewed', ${quote.amount_usdc.toFixed(6)}, ${quote.credits_usd.toFixed(6)},
+ ${quote.from}, ${quote.to}, 'mainnet', now() + make_interval(mins => ${PREVIEW_TTL_MINUTES}))
+ RETURNING id, expires_at
+ `;
+ return { preview_id: row.id, expires_at: row.expires_at, ...quote };
+}
+
// ── execute ─────────────────────────────────────────────────────────────────
function rowResult(row, extra = {}) {
diff --git a/api/_lib/mcp-connections/catalog.js b/api/_lib/mcp-connections/catalog.js
index 7d5547463..b2c0f1e3c 100644
--- a/api/_lib/mcp-connections/catalog.js
+++ b/api/_lib/mcp-connections/catalog.js
@@ -1,9 +1,9 @@
// The vetted catalog of external MCP servers an agent can be connected to.
//
-// Source of truth: data/mcp-integrations.json. Every remote entry was probed
+// Source of truth: data/mcp-catalog.json. Every remote entry was probed
// live by scripts/vet-mcp-integrations.mjs (initialize, then either tools/list
// for an open server or RFC 9728 / RFC 8414 discovery for a protected one), and
-// `npm run check:mcp-integrations` fails the build on a malformed entry.
+// `npm run check:mcp-catalog` fails the build on a malformed entry.
//
// Not to be confused with public/mcp-catalog.json, which lists the tools
// three.ws itself publishes. This file lists servers other people run.
@@ -11,12 +11,16 @@
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
-export const CATALOG_PATH = fileURLToPath(new URL('../../../data/mcp-integrations.json', import.meta.url));
+export const CATALOG_PATH = fileURLToPath(new URL('../../../data/mcp-catalog.json', import.meta.url));
export const TRANSPORTS = Object.freeze(['streamable-http', 'sse', 'stdio']);
export const AUTH_TYPES = Object.freeze(['oauth', 'bearer', 'none']);
export const REGISTRATIONS = Object.freeze(['dynamic', 'platform']);
const ID_RE = /^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/;
+// The catalog lists general developer and productivity vendors. Crypto
+// projects are out of scope: the platform promotes one coin, and an entry for
+// any other project would be an endorsement shipped to every agent owner.
+const OUT_OF_SCOPE_RE = /\b(blockchain|crypto(currency)?|defi|nfts?|web3|on-?chain|coins?|wallets?|dex)\b/i;
const ENV_RE = /^[A-Z][A-Z0-9_]{2,60}$/;
function isHttps(u) {
@@ -72,6 +76,9 @@ export function validateCatalog(doc) {
if (typeof s[f] !== 'string' || !s[f].trim()) errors.push(`${at}.${f} is required`);
}
if (typeof s.description === 'string' && s.description.length > 200) errors.push(`${at}.description is over 200 characters`);
+ if (OUT_OF_SCOPE_RE.test([s.id, s.name, s.vendor, s.description].join(' '))) {
+ errors.push(`${at} looks like a crypto project; the catalog lists general developer and productivity servers only`);
+ }
if (!categories.has(s.category)) errors.push(`${at}.category ${s.category} is not declared`);
if (!TRANSPORTS.includes(s.transport)) errors.push(`${at}.transport must be one of ${TRANSPORTS.join(', ')}`);
if (!isHttps(s.docs)) errors.push(`${at}.docs must be an https link`);
@@ -111,7 +118,7 @@ export function loadCatalog() {
if (cached) return cached;
const doc = JSON.parse(readFileSync(CATALOG_PATH, 'utf8'));
const errors = validateCatalog(doc);
- if (errors.length) throw new Error(`data/mcp-integrations.json is invalid: ${errors.slice(0, 5).join('; ')}`);
+ if (errors.length) throw new Error(`data/mcp-catalog.json is invalid: ${errors.slice(0, 5).join('; ')}`);
cached = doc;
return doc;
}
diff --git a/api/_lib/mcp-connections/client.js b/api/_lib/mcp-connections/client.js
index ea0dd880a..318715d92 100644
--- a/api/_lib/mcp-connections/client.js
+++ b/api/_lib/mcp-connections/client.js
@@ -135,18 +135,11 @@ export function toolResultToText(result, maxChars = 16_000) {
}
/**
- * Discover how a server wants to be authenticated, without credentials.
- * Returns { auth: 'none', tools } for an open server, { auth: 'oauth',
- * registration } for one that publishes RFC 9728 metadata, or { auth: 'bearer' }
- * for one that answers 401 with no discovery document.
+ * Read a server's OAuth discovery documents (RFC 9728 protected resource, then
+ * RFC 8414 authorization server) without credentials. Returns null when the
+ * server publishes neither.
*/
-export async function probeServer(url, { transport = 'streamable-http' } = {}) {
- try {
- const listed = await fetchTools({ url, transport });
- return { auth: 'none', ...listed };
- } catch (err) {
- if (err.code !== 'needs_auth') throw err;
- }
+export async function discoverAuth(url) {
const fetchFn = createSafeFetch();
let resource = null;
try {
@@ -161,11 +154,28 @@ export async function probeServer(url, { transport = 'streamable-http' } = {}) {
} catch {
metadata = null;
}
- if (!resource && !metadata) return { auth: 'bearer', registration: null, authorizationServer: null };
+ if (!resource && !metadata) return null;
return {
- auth: 'oauth',
registration: metadata?.registration_endpoint ? 'dynamic' : 'platform',
authorizationServer: asUrl,
scopes: resource?.scopes_supported || metadata?.scopes_supported || [],
};
}
+
+/**
+ * Discover how a server wants to be authenticated, without credentials.
+ * Returns { auth: 'none', tools } for an open server, { auth: 'oauth',
+ * registration } for one that publishes RFC 9728 metadata, or { auth: 'bearer' }
+ * for one that answers 401 with no discovery document.
+ */
+export async function probeServer(url, { transport = 'streamable-http' } = {}) {
+ try {
+ const listed = await fetchTools({ url, transport });
+ return { auth: 'none', ...listed };
+ } catch (err) {
+ if (err.code !== 'needs_auth') throw err;
+ }
+ const found = await discoverAuth(url);
+ if (!found) return { auth: 'bearer', registration: null, authorizationServer: null };
+ return { auth: 'oauth', ...found };
+}
diff --git a/api/_lib/migrations/20260925120000_agent_spend_index.sql b/api/_lib/migrations/20260925120000_agent_spend_index.sql
new file mode 100644
index 000000000..1192440f7
--- /dev/null
+++ b/api/_lib/migrations/20260925120000_agent_spend_index.sql
@@ -0,0 +1,9 @@
+-- Per-agent inference budgets are judged against every credit_ledger row booked
+-- as model spend for one agent (ref_type 'agent'): the flat three-ws/agent rate
+-- ('inference.agent') and a v1 run's paid lanes ('agent_run_step'). The older
+-- partial index covers only the first action, so the budget read would scan the
+-- month's ledger once runs are counted too. Additive and idempotent.
+
+CREATE INDEX IF NOT EXISTS credit_ledger_agent_spend
+ ON credit_ledger (ref_id, created_at DESC)
+ WHERE ref_type = 'agent';
diff --git a/api/_lib/pump-callouts.js b/api/_lib/pump-callouts.js
new file mode 100644
index 000000000..83e25d95e
--- /dev/null
+++ b/api/_lib/pump-callouts.js
@@ -0,0 +1,56 @@
+// pump.fun callouts: the live community commentary a coin page renders from
+// frontend-api-v3 `/callout/top/:mint` (the retired `/replies/:mint` route
+// 404s for every mint). Each entry carries the poster's thesis, handle and
+// timestamp. Shared by POST /api/social/sentiment-pulse (lexicon scoring) and
+// the Sentiment Scout (quoted as evidence), so both read the same feed through
+// the shared pump.fun fetch helper (identified user-agent, bounded timeout,
+// one retry on a rate limit or 5xx).
+
+import { PUMP_FRONTEND_BASE, pumpFetchJson } from './pump-feed-fetch.js';
+
+const FETCH_TIMEOUT_MS = 8000;
+
+/**
+ * Map raw pump.fun callout rows into the scorer's post shape, newest first.
+ * Rows with no thesis carry no sentiment and are dropped rather than counted
+ * as neutral, which would drag every score toward zero.
+ *
+ * @param {any[]} callouts
+ * @param {number} limit
+ * @returns {Array<{ id?: string, ts?: string, text: string, author?: string }>}
+ */
+export function calloutsToPosts(callouts, limit) {
+ if (!Array.isArray(callouts)) return [];
+ return callouts
+ .map((c) => {
+ const at = Number(c?.createdAt);
+ const ms = Number.isFinite(at) && at > 0 ? at : null;
+ return {
+ id: c?.calloutId ? String(c.calloutId) : undefined,
+ ts: ms ? new Date(ms).toISOString() : undefined,
+ text: String(c?.thesis || '').trim().slice(0, 2000),
+ author: c?.username ? String(c.username) : undefined,
+ _at: ms ?? 0,
+ };
+ })
+ .filter((p) => p.text)
+ .sort((a, b) => b._at - a._at)
+ .slice(0, limit)
+ .map(({ _at, ...post }) => post);
+}
+
+/**
+ * Fetch a coin's most recent pump.fun callouts. Never throws: an upstream
+ * failure is reported as `{ error, url }` for the handler to surface.
+ */
+export async function fetchPumpFunCallouts(mint, limit, { timeoutMs = FETCH_TIMEOUT_MS } = {}) {
+ const url =
+ `${PUMP_FRONTEND_BASE}/callout/top/${encodeURIComponent(mint)}` +
+ `?limit=${limit}&sortBy=TIMESTAMP&sortOrder=DESC`;
+ const { ok, status, body } = await pumpFetchJson(url, { timeoutMs });
+ if (!ok) {
+ return { error: status ? `pump.fun returned ${status}` : 'pump.fun unreachable', url };
+ }
+ const rows = Array.isArray(body?.callouts) ? body.callouts : Array.isArray(body) ? body : [];
+ return { posts: calloutsToPosts(rows, limit), url };
+}
diff --git a/api/_lib/sandbox/exec-core.js b/api/_lib/sandbox/exec-core.js
index 2eb4124ac..1eaa8c46b 100644
--- a/api/_lib/sandbox/exec-core.js
+++ b/api/_lib/sandbox/exec-core.js
@@ -170,7 +170,8 @@ function sampleProc(pid) {
}
}
-class CappedBuffer {
+/** Keep the first 40% and the last 60% of a stream up to `cap` bytes. */
+export class CappedBuffer {
constructor(cap) {
this.cap = cap;
this.head = [];
@@ -220,8 +221,10 @@ class CappedBuffer {
* @returns {Promise<{ exitCode: number|null, signal: string|null, stdout: object, stderr: object,
* timedOut: boolean, killed: boolean, outputFlood: boolean, wallMs: number, cpuMs: number|null, peakMemoryMb: number|null }>}
*/
-export function runProcess({ argv, cwd, env, limits, language, uid, gid, nproc, signal }) {
- const wrapped = withLimits(argv, { limits, nproc, language });
+export function runProcess({ argv, cwd, env, limits, language, uid, gid, nproc, signal, hostLimits = true, onKill = null }) {
+ // hostLimits=false: the argv is a launcher (the docker CLI) whose own limits
+ // are enforced elsewhere; kernel rlimits on the launcher would only break it.
+ const wrapped = hostLimits ? withLimits(argv, { limits, nproc, language }) : argv;
const started = Date.now();
return new Promise((resolve) => {
const child = spawn(wrapped[0], wrapped.slice(1), {
@@ -242,6 +245,7 @@ export function runProcess({ argv, cwd, env, limits, language, uid, gid, nproc,
let done = false;
const killTree = () => {
+ if (onKill) Promise.resolve().then(onKill).catch(() => {});
try {
process.kill(-child.pid, 'SIGKILL');
} catch {
@@ -310,45 +314,56 @@ export function runProcess({ argv, cwd, env, limits, language, uid, gid, nproc,
}
/**
- * Serve the bridge on a unix socket. One JSON object per line in each
- * direction; requests carry an `id` the response echoes, so a client may keep
- * several calls in flight on one connection.
- * @param {string} socketPath
+ * Speak the bridge protocol on one duplex stream: one JSON object per line in
+ * each direction; requests carry an `id` the response echoes, so a client may
+ * keep several calls in flight on one connection. Used for the local unix
+ * socket and for a socket forwarded over ssh.
+ * @param {import('node:stream').Duplex} conn
* @param {(msg: object) => Promise<object>} handle resolves to the response body
*/
-export async function serveBridge(socketPath, handle) {
- await fs.rm(socketPath, { force: true });
- const server = net.createServer((conn) => {
- let buf = '';
- conn.setEncoding('utf8');
- conn.on('data', (chunk) => {
- buf += chunk;
- if (buf.length > MAX_BRIDGE_LINE) {
- conn.end(`${JSON.stringify({ ok: false, error: { code: 'too_large', message: 'bridge request larger than 8 MB' } })}\n`);
- return;
- }
- let nl;
- while ((nl = buf.indexOf('\n')) >= 0) {
- const line = buf.slice(0, nl);
- buf = buf.slice(nl + 1);
- if (!line.trim()) continue;
- let msg;
- try {
- msg = JSON.parse(line);
- } catch {
- conn.write(`${JSON.stringify({ ok: false, error: { code: 'bad_json', message: 'bridge request is not JSON' } })}\n`);
- continue;
- }
- Promise.resolve()
- .then(() => handle(msg))
- .catch((e) => ({ ok: false, error: { code: e?.code || 'bridge_error', message: String(e?.message || e).slice(0, 500) } }))
- .then((body) => {
- if (!conn.destroyed) conn.write(`${JSON.stringify({ id: msg.id ?? null, ...body })}\n`);
- });
+export function handleBridgeStream(conn, handle) {
+ let buf = '';
+ conn.setEncoding?.('utf8');
+ const send = (obj) => {
+ if (!conn.destroyed) conn.write(`${JSON.stringify(obj)}\n`);
+ };
+ conn.on('data', (chunk) => {
+ buf += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
+ if (buf.length > MAX_BRIDGE_LINE) {
+ buf = '';
+ send({ ok: false, error: { code: 'too_large', message: 'bridge request larger than 8 MB' } });
+ conn.end();
+ return;
+ }
+ let nl;
+ while ((nl = buf.indexOf('\n')) >= 0) {
+ const line = buf.slice(0, nl);
+ buf = buf.slice(nl + 1);
+ if (!line.trim()) continue;
+ let msg;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ send({ ok: false, error: { code: 'bad_json', message: 'bridge request is not JSON' } });
+ continue;
}
- });
- conn.on('error', () => {});
+ Promise.resolve()
+ .then(() => handle(msg))
+ .catch((e) => ({ ok: false, error: { code: e?.code || 'bridge_error', message: String(e?.message || e).slice(0, 500) } }))
+ .then((body) => send({ id: msg.id ?? null, ...body }));
+ }
});
+ conn.on('error', () => {});
+}
+
+/**
+ * Serve the bridge on a unix socket (see handleBridgeStream for the protocol).
+ * @param {string} socketPath
+ * @param {(msg: object) => Promise<object>} handle
+ */
+export async function serveBridge(socketPath, handle) {
+ await fs.rm(socketPath, { force: true });
+ const server = net.createServer((conn) => handleBridgeStream(conn, handle));
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(socketPath, resolve);
diff --git a/api/_lib/token/jupiter.js b/api/_lib/token/jupiter.js
index 3d210a524..e6bd6093b 100644
--- a/api/_lib/token/jupiter.js
+++ b/api/_lib/token/jupiter.js
@@ -72,14 +72,15 @@ export async function fetchJson(url, opts, { timeoutMs = JUP_QUOTE_TIMEOUT_MS, a
/**
* ExactIn quote: how much `outputMint` a given `amount` of `inputMint` buys.
- * `dexes` restricts routing to one or more venue labels (as Jupiter names them,
- * e.g. 'Whirlpool', 'Raydium CLMM', 'Meteora DLMM'), and `onlyDirectRoutes`
- * forbids multi-hop routes: together they price a pair on one venue, which is
- * what a cross-venue comparison needs.
- * @param {{ inputMint: string, outputMint: string, amount: bigint|number|string, slippageBps: number, dexes?: string[]|null, onlyDirectRoutes?: boolean }} args
+ * `dexes` restricts routing to one or more venue labels (the labels the
+ * router itself reports in a quote's routePlan), `excludeDexes` removes venues
+ * from routing, and `onlyDirectRoutes` forbids multi-hop routes: together they
+ * price a pair on one venue at a time, which is what a cross-venue comparison
+ * needs.
+ * @param {{ inputMint: string, outputMint: string, amount: bigint|number|string, slippageBps: number, dexes?: string[]|null, excludeDexes?: string[]|null, onlyDirectRoutes?: boolean }} args
* @returns {Promise<object>} the raw Jupiter quoteResponse
*/
-export async function jupiterQuote({ inputMint, outputMint, amount, slippageBps, dexes = null, onlyDirectRoutes = false }) {
+export async function jupiterQuote({ inputMint, outputMint, amount, slippageBps, dexes = null, excludeDexes = null, onlyDirectRoutes = false }) {
const u = new URL(JUP_QUOTE_URL);
u.searchParams.set('inputMint', inputMint);
u.searchParams.set('outputMint', outputMint);
@@ -87,6 +88,7 @@ export async function jupiterQuote({ inputMint, outputMint, amount, slippageBps,
u.searchParams.set('slippageBps', String(slippageBps));
u.searchParams.set('swapMode', 'ExactIn');
if (Array.isArray(dexes) && dexes.length) u.searchParams.set('dexes', dexes.join(','));
+ if (Array.isArray(excludeDexes) && excludeDexes.length) u.searchParams.set('excludeDexes', excludeDexes.join(','));
if (onlyDirectRoutes) u.searchParams.set('onlyDirectRoutes', 'true');
// A quote is an idempotent GET: retry it through the transient statuses
// (429/5xx/network) so one rate-limited response never fails a paid swap.
diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.js
index ca2da905d..b6fedf40d 100644
--- a/api/_lib/x402/pay.js
+++ b/api/_lib/x402/pay.js
@@ -363,6 +363,12 @@ export async function payX402({
// null/undefined continues the normal flow. Sync or async; a thrown hook is
// treated as an abort (fail-closed), never a crash.
onAccept = null,
+ // Budget for the PAID replay only. The probe stays on FETCH_TIMEOUT_MS: it is
+ // a cheap 402 read. A route that runs its work before settling (the paid Forge
+ // generates the mesh, then settles) can legitimately outlast 20s, and aborting
+ // there does not cancel the server: it still settles, so the buyer pays for a
+ // result it already threw away and books the settlement as a fault.
+ paidTimeoutMs = FETCH_TIMEOUT_MS,
}) {
// ringFeeConfig applies the sponsor-mode price constraint itself (sponsor sits
// exactly at the fee ceiling, so only zero-lamport priority slots are legal),
@@ -502,7 +508,7 @@ export async function payX402({
const paidRes = await fetchWithTimeout(url, {
...reqInit,
headers: { ...reqInit.headers, 'x-payment': xPayment },
- });
+ }, paidTimeoutMs);
return { paidRes, amountAtomic: attemptAmount };
}
diff --git a/api/_lib/x402/pipelines/forge-content.js b/api/_lib/x402/pipelines/forge-content.js
index d4279a566..ad4c38c4f 100644
--- a/api/_lib/x402/pipelines/forge-content.js
+++ b/api/_lib/x402/pipelines/forge-content.js
@@ -56,6 +56,15 @@ const log = logger('x402-forge-content');
const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+// How long the paid generation call may run. /api/x402/forge generates BEFORE it
+// settles, and a standard-tier NIM job finishes 20 to 55s after the request
+// (its submit phase alone may use 30s before the lane falls back). On the shared
+// 20s default the ring aborted first while the server went on to settle: 7 of
+// the 9 ring-paid generations on 2026-09-24/25 were charged, recorded here as
+// `This operation was aborted`, and never reached forge_autonomous_props. 90s
+// clears the observed tail and still leaves the loop tick inside its budget.
+export const FORGE_PAID_TIMEOUT_MS = 90_000;
+
// Vector space tag for the dependency-free fallback embedding. Tagged distinctly
// so it is NEVER compared against real NIM/OpenAI vectors: cosine only ever runs
// within a single embedder space (the rule embeddings.js enforces everywhere).
@@ -404,7 +413,10 @@ export async function run(ctx = {}) {
// so guard it and record the failed call rather than crash the tick.
let result;
try {
- result = await payX402({ url: endpointUrl, method: 'POST', body, buyer, conn, blockhash, mintInfo, remainingCap });
+ result = await payX402({
+ url: endpointUrl, method: 'POST', body, buyer, conn, blockhash, mintInfo, remainingCap,
+ paidTimeoutMs: FORGE_PAID_TIMEOUT_MS,
+ });
} catch (err) {
const errorMsg = err?.message || 'forge_pay_error';
await recordCall(runId, {
diff --git a/api/social/sentiment-pulse.js b/api/social/sentiment-pulse.js
index 66789f6f5..b7f6542e3 100644
--- a/api/social/sentiment-pulse.js
+++ b/api/social/sentiment-pulse.js
@@ -43,10 +43,9 @@
import { z } from 'zod';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { PUMP_FRONTEND_BASE, pumpFetchJson } from '../_lib/pump-feed-fetch.js';
+import { calloutsToPosts, fetchPumpFunCallouts } from '../_lib/pump-callouts.js';
const SOLANA_MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
-const FETCH_TIMEOUT_MS = 8000;
const bodySchema = z.object({
token: z.string().regex(SOLANA_MINT_RE, 'token must be a base58 Solana mint pubkey'),
@@ -54,50 +53,7 @@ const bodySchema = z.object({
extraTexts: z.array(z.string().max(2000)).max(200).optional(),
});
-/**
- * Map raw pump.fun callout rows into the scorer's post shape, newest first.
- * Rows with no thesis carry no sentiment and are dropped rather than counted
- * as neutral, which would drag every score toward zero.
- *
- * @param {any[]} callouts
- * @param {number} limit
- * @returns {Array<{ id?: string, ts?: string, text: string, author?: string }>}
- */
-export function calloutsToPosts(callouts, limit) {
- if (!Array.isArray(callouts)) return [];
- return callouts
- .map((c) => {
- const at = Number(c?.createdAt);
- const ms = Number.isFinite(at) && at > 0 ? at : null;
- return {
- id: c?.calloutId ? String(c.calloutId) : undefined,
- ts: ms ? new Date(ms).toISOString() : undefined,
- text: String(c?.thesis || '').trim().slice(0, 2000),
- author: c?.username ? String(c.username) : undefined,
- _at: ms ?? 0,
- };
- })
- .filter((p) => p.text)
- .sort((a, b) => b._at - a._at)
- .slice(0, limit)
- .map(({ _at, ...post }) => post);
-}
-
-/**
- * Fetch a coin's most recent pump.fun callouts. Never throws: an upstream
- * failure is reported as `{ error, url }` for the handler to surface.
- */
-async function fetchPumpFunCallouts(mint, limit) {
- const url =
- `${PUMP_FRONTEND_BASE}/callout/top/${encodeURIComponent(mint)}` +
- `?limit=${limit}&sortBy=TIMESTAMP&sortOrder=DESC`;
- const { ok, status, body } = await pumpFetchJson(url, { timeoutMs: FETCH_TIMEOUT_MS });
- if (!ok) {
- return { error: status ? `pump.fun returned ${status}` : 'pump.fun unreachable', url };
- }
- const rows = Array.isArray(body?.callouts) ? body.callouts : Array.isArray(body) ? body : [];
- return { posts: calloutsToPosts(rows, limit), url };
-}
+export { calloutsToPosts };
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: false })) return;
diff --git a/data/changelog.json b/data/changelog.json
index 134fa8c58..94c30c6a1 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -11,6 +11,16 @@
],
"link": "/docs/mcp"
},
+ {
+ "date": "2026-09-25",
+ "title": "Props the platform pays Forge to make now land in the /forged gallery",
+ "summary": "Every half hour the platform pays its own Forge to make a new 3D prop for the public /forged gallery. A standard generation takes 20 to 55 seconds, but the paying side gave up after 20. Forge still finished the model and took the payment, so most of those props were paid for, never saved to the gallery, and logged as failed. The paying side now waits up to 90 seconds for a generation. Each paid prop lands in the gallery, and the payment health numbers stop counting these successful payments as failures.",
+ "tags": [
+ "fix",
+ "infra"
+ ],
+ "link": "/forged"
+ },
{
"date": "2026-09-22",
"title": "Claude and other AI clients can now read your three.ws account and follow guided flows",
diff --git a/data/mcp-integrations.json b/data/mcp-catalog.json
similarity index 100%
rename from data/mcp-integrations.json
rename to data/mcp-catalog.json
diff --git a/multiplayer/package.json b/multiplayer/package.json
index a246b3413..652830eb7 100644
--- a/multiplayer/package.json
+++ b/multiplayer/package.json
@@ -26,6 +26,7 @@
"@upstash/redis": "^1.38.0",
"agent0-sdk": "^1.7.1",
"ethers": "^6.16.0",
+ "eventsource": "^5.1.0",
"express": "^5.2.1",
"livepeer": "3.5.0",
"short-uuid": "6.0.3"
diff --git a/package-lock.json b/package-lock.json
index ae677fe86..b229bf525 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -239,6 +239,7 @@
},
"devDependencies": {
"@axe-core/playwright": "^4.13.0",
+ "@electric-sql/pglite": "^0.5.8",
"@joplin/turndown-plugin-gfm": "^1.0.68",
"@playwright/test": "^1.63.0",
"@x402/fetch": "^2.14.0",
@@ -848,6 +849,7 @@
"@upstash/redis": "^1.38.0",
"agent0-sdk": "^1.7.1",
"ethers": "^6.16.0",
+ "eventsource": "^5.1.0",
"express": "^5.2.1",
"livepeer": "3.5.0",
"short-uuid": "6.0.3"
@@ -1053,6 +1055,27 @@
"@types/node": "*"
}
},
+ "multiplayer/node_modules/eventsource": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-5.1.2.tgz",
+ "integrity": "sha512-VJnwqqp+fOT3WDkjnUy49Zuyh48+kH0JdJApZkslrRQyx35zIZJeJYJl0+a+LrTzh5TFv6MdmXnBDv71UXFyWQ==",
+ "license": "MIT",
+ "dependencies": {
+ "eventsource-parser": "^4.1.1"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "multiplayer/node_modules/eventsource-parser": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-4.1.1.tgz",
+ "integrity": "sha512-zaWNqeSLeyzEAAt2Q6aDBRDRk/VnPmsKqvToyGvv6aahvLv71A4Jw7jG93Hckf11zXurbqgsffvpSgKPoeU1Qw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=22.12"
+ }
+ },
"multiplayer/node_modules/multiformats": {
"version": "9.9.0",
"resolved": "https://registry.npmjs.org/multiformats/-/multiformats-9.9.0.tgz",
@@ -6195,6 +6218,13 @@
"node": ">=6"
}
},
+ "node_modules/@electric-sql/pglite": {
+ "version": "0.5.8",
+ "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.5.8.tgz",
+ "integrity": "sha512-n9tsbUOhwx2epK1V0ZG9Ar4SHWUju04dhmzZXiSBXwBoleOvIfals33NAaWgagQVAL4Rbvx/Ptsu3P+pA09f6Q==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/@elevenlabs/elevenlabs-js": {
"version": "2.68.0",
"resolved": "https://registry.npmjs.org/@elevenlabs/elevenlabs-js/-/elevenlabs-js-2.68.0.tgz",
diff --git a/package.json b/package.json
index 2d08d5585..55564534c 100644
--- a/package.json
+++ b/package.json
@@ -248,7 +248,7 @@
"audit:route-shadowing": "node scripts/audit-route-shadowing.mjs",
"audit:handlers": "node scripts/audit-empty-handlers.mjs",
"audit:x402-catalog": "node scripts/audit-x402-catalog.mjs",
- "gate": "npm run check:conflicts && npm run check:claude && npm run check:vendored && npm run check:model-viewer && npm run check:gcloudignore && npm run check:fetch-timeouts && npm run check:tdz-bootstrap && npm run check:event && npm run check:cron-syntax && npm run check:home-matrix && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run audit:mcp-listing && npm run audit:mcp-surfaces && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:links && npm run check:awesome && npm run check:prompt-library && npm run audit:docs && npm run check:docs-freshness && npm run audit:upstreams && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:inline-handlers && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:states && npm run audit:motion-tokens && npm run audit:guards && npm run audit:tour-atlas && npm run check:ios-icons && npm run check:macos-icon && npm run check:apple-widget && npm run check:windows-widget && npm run check:announce && npm run i18n:home && npm run check:skills-seed && npm run check:openai-skills && npm run check:skills-pack && npm run check:skill-repos && npm run check:openai-fields && npm run audit:motion && npm run audit:tour-global && npm run check:doc-media && npm run check:images && npm run audit:route-shadowing",
+ "gate": "npm run check:conflicts && npm run check:claude && npm run check:vendored && npm run check:model-viewer && npm run check:gcloudignore && npm run check:fetch-timeouts && npm run check:tdz-bootstrap && npm run check:event && npm run check:cron-syntax && npm run check:home-matrix && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run check:mcp-catalog && npm run audit:mcp-listing && npm run audit:mcp-surfaces && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:links && npm run check:awesome && npm run check:prompt-library && npm run audit:docs && npm run check:docs-freshness && npm run audit:upstreams && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:inline-handlers && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:states && npm run audit:motion-tokens && npm run audit:guards && npm run audit:tour-atlas && npm run check:ios-icons && npm run check:macos-icon && npm run check:apple-widget && npm run check:windows-widget && npm run check:announce && npm run i18n:home && npm run check:skills-seed && npm run check:openai-skills && npm run check:skills-pack && npm run check:skill-repos && npm run check:openai-fields && npm run audit:motion && npm run audit:tour-global && npm run check:doc-media && npm run check:images && npm run audit:route-shadowing",
"test:gate-3d": "vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js",
"audit:mcp-golden": "node scripts/audit-mcp-golden.mjs",
"audit:mcp-safety": "node scripts/audit-mcp-safety.mjs",
@@ -305,7 +305,7 @@
"triage:gcp:deep": "node scripts/gcp-triage.mjs --deep --since 6h",
"snapshot": "node scripts/page-snapshot.mjs",
"build:news": "node scripts/build-news.mjs",
- "prebuild": "node scripts/copy-three-decoders.mjs && node scripts/copy-voice-models.mjs && (node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & node scripts/build-discovery-cards.mjs & node scripts/build-guards.mjs & node scripts/build-atlas-index.mjs & node scripts/build-mcp-catalog.mjs & node scripts/build-awesome.mjs & node scripts/build-prompt-library.mjs & node scripts/build-community-registry.mjs --check & npm run build:examples & npm run build:docs-search & npm run build:club-assets & npm run build:walk-environments & wait) && node scripts/inject-blog-seo.mjs --write && node scripts/inject-hidden-guard.mjs --write && node scripts/i18n-annotate.mjs --apply --pages=\"public/news/*.html\" && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict && node scripts/audit-empty-handlers.mjs && node scripts/audit-hidden-guard.mjs) && node scripts/inject-seo-meta.mjs --write && node scripts/inject-theme-boot.mjs --write",
+ "prebuild": "node scripts/copy-three-decoders.mjs && node scripts/copy-voice-models.mjs && (node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & node scripts/build-discovery-cards.mjs & node scripts/build-guards.mjs & node scripts/build-atlas-index.mjs & node scripts/build-mcp-catalog.mjs & node scripts/build-awesome.mjs & node scripts/build-prompt-library.mjs & node scripts/build-community-registry.mjs --check & npm run build:examples & npm run build:docs-search & npm run build:club-assets & npm run build:walk-environments & wait) && node scripts/check-mcp-catalog.mjs && node scripts/inject-blog-seo.mjs --write && node scripts/inject-hidden-guard.mjs --write && node scripts/i18n-annotate.mjs --apply --pages=\"public/news/*.html\" && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict && node scripts/audit-empty-handlers.mjs && node scripts/audit-hidden-guard.mjs) && node scripts/inject-seo-meta.mjs --write && node scripts/inject-theme-boot.mjs --write",
"seo:meta": "node scripts/inject-blog-seo.mjs --write && node scripts/build-page-index.mjs && node scripts/inject-seo-meta.mjs --write",
"build": "NODE_OPTIONS='--no-deprecation --max-old-space-size=6144' vite build && node scripts/strip-sw-from-embeds.mjs && node scripts/inject-tour-boot.mjs && node scripts/inject-atlas.mjs && node scripts/inject-inline-behaviors.mjs",
"build:wasm": "node scripts/build-wasm.mjs",
@@ -514,7 +514,9 @@
"check:awesome": "node scripts/build-awesome.mjs --check",
"awesome:links": "node scripts/check-awesome-links.mjs",
"awesome:standalone": "node scripts/build-awesome.mjs --standalone",
- "verify:three-gate": "node scripts/verify-three-gate.mjs"
+ "verify:three-gate": "node scripts/verify-three-gate.mjs",
+ "check:mcp-catalog": "node scripts/check-mcp-catalog.mjs",
+ "vet:mcp-catalog": "node scripts/vet-mcp-integrations.mjs"
},
"dependencies": {
"@0xsplits/splits-sdk": "^6.6.0",
@@ -675,6 +677,7 @@
},
"devDependencies": {
"@axe-core/playwright": "^4.13.0",
+ "@electric-sql/pglite": "^0.5.8",
"@joplin/turndown-plugin-gfm": "^1.0.68",
"@playwright/test": "^1.63.0",
"@x402/fetch": "^2.14.0",
diff --git a/packages/mcp-policy/src/index.js b/packages/mcp-policy/src/index.js
index 4a3dd6841..4a7fe5772 100644
--- a/packages/mcp-policy/src/index.js
+++ b/packages/mcp-policy/src/index.js
@@ -16,6 +16,8 @@ export {
enablementFromTokens,
enablementFromSpec,
enablementFromSelection,
+ selectionToTokens,
+ specFromSelection,
defaultEnablement,
allowListEnablement,
settingsToTokens,
diff --git a/prompts/finish/907-backlog-08-okx-chat-bot-always-on.md b/prompts/finish/907-backlog-08-okx-chat-bot-always-on.md
index 0b3478d57..e6027e964 100644
--- a/prompts/finish/907-backlog-08-okx-chat-bot-always-on.md
+++ b/prompts/finish/907-backlog-08-okx-chat-bot-always-on.md
@@ -73,6 +73,23 @@ host. Build it:
host detect an expired session and emit an actionable alert naming the exact
command, rather than failing chat silently.
+## State on 2026-09-25, re-measured: gcloud is back, the deploy is one approval away
+
+- **Bot host: unchanged.** `/api/healthz` still reports `okx_chat_bot` `degraded` on
+ `cloudrun:okx-chat-bot (okx-chat-bot-00001-926)`, same Vertex `403 Lightning dunning decision is
+ deny`. Live API still `c8f10f437` (`three-ws-api-00458-njs`).
+- **Owner step 0 is done.** `gcloud` is installed and authenticated (project
+ `aerial-vehicle-466722-p5`); `npm run okx:bot:deploy -- --dry-run` passes step [1].
+- **Fresh-clone fix.** This workspace has no `.env.local`, so step [3] died on `DATABASE_URL is not
+ set`. `scripts/okx-bot-llm-gateway.mjs` now falls back to the API service's `DATABASE_URL`
+ (`requireServiceEnvValue`, the same path `rug-signature.mjs` uses). Measured after the change,
+ with no local env: step [3] reads production and reports service account, metering agent, key
+ and secret all `missing`, which is exactly what `--apply` creates. Steps [1] and [4] green.
+- **Why the bot is not deployed yet:** the real run refuses while
+ `scripts/okx-bot-llm-gateway.mjs` has uncommitted edits, and committing a file that names the
+ marketplace needs owner approval (commit gate). Owner: approve the commit of that file plus this
+ order, then run `npm run okx:bot:deploy`, then step 3 below.
+
## State on 2026-09-24, re-measured: the API half has shipped, only the bot deploy is left
- **API deploy: DONE.** Live API `c8f10f437` (`three-ws-api-00458-njs`) contains `53687d994`,
diff --git a/prompts/okx-ai/e2e-evidence/FUNDING-REQUEST.md b/prompts/okx-ai/e2e-evidence/FUNDING-REQUEST.md
index 3940b0462..0a3aa9250 100644
--- a/prompts/okx-ai/e2e-evidence/FUNDING-REQUEST.md
+++ b/prompts/okx-ai/e2e-evidence/FUNDING-REQUEST.md
@@ -1,4 +1,26 @@
-# Work Order 04: funding request (re-verified 2026-09-09)
+# Work Order 04: funding request (current ask re-verified 2026-09-25)
+
+## Current ask, 2026-09-25 (supersedes the 5.0 USD₮0 and 0.10 USDC figures further down)
+
+Re-measured on a fresh host: Step 0 green (health `ok` with `payment-rail` `settleable: true`,
+`relayer_funded: true`; catalog byte-identical module == live == listing; unpaid
+`text-to-3d` 402 with `eip155:196` first at 10000; `okx-3d-services` 36/36;
+`--dry-run` 3/3). `onchainos` v4.6.2 sha256 `ca606d24...c699a` matches the release
+`checksums.txt`. Balances at X Layer block 71544237: buyer 0 USD₮0 / 0 OKB, seller
+2.427731 USD₮0 / 0.839596 OKB. Buyer Solana account `9PirGw9w...fnyc` holds no USDC
+account at all.
+
+| Leg | To | Chain | Token | Amount |
+| --- | --- | --- | --- | --- |
+| Float | `0x75d00a2713565171f33216e5aa2a375e076ecf69` | X Layer (196) | USD₮0 `0x779ded0c9e1022225f8e0630b35a9b54be713736` | **2.16** (1.08 float x 2 for retries) |
+| Case 7 | `9PirGw9wVLLNFgVyjgAt5jvuFQwJ3pYUBWt9n3vZfnyc` | Solana mainnet | USDC `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` | **0.02** |
+
+The payTo wallet cannot fund the buyer from this side: the Cloud Run service holds only its
+address (`X402_PAY_TO_XLAYER`), not its key. The wallet session is logged OUT on this host,
+so the browser login (email OTP for `[email protected]`) is required again.
+
+## Earlier record, 2026-09-09
+
Every leg of the gauntlet that does not move money is finished and green against production.
The paid legs are blocked on one owner action. Amounts below are computed from the live
@@ -178,7 +200,7 @@ Cases 1, 1d, 2, 2b, 3, 3i, 3r, 5a, 5b, 5c, 5d, 6, 7, then case 4 (on-chain settl
verification of every payment the run produced), writing evidence for each into this
directory.
-## The wallet is already logged in
+## Wallet session
-`onchainos wallet status` reads `loggedIn: true` as `[email protected]` (verified 2026-09-09),
-so no OTP is needed for this work order. Funding is the single remaining owner action.
+Logged in on 2026-09-09; logged out on the 2026-09-25 host, so the browser login is needed
+again before any case can sign.
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index f8d2a38e3..08bcb07d4 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,14 +1,36 @@
{
- "generated_at": "2026-09-24T07:08:16.190Z",
+ "generated_at": "2026-09-25T05:37:06.420Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3755,
+ "total": 3757,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
+ {
+ "date": "2026-09-25",
+ "type": "update",
+ "title": "Props the platform pays Forge to make now land in the /forged gallery",
+ "summary": "Every half hour the platform pays its own Forge to make a new 3D prop for the public /forged gallery. A standard generation takes 20 to 55 seconds, but the paying side gave up after 20. Forge still finished the model and took the payment, so most of those props were paid for, never saved to the gallery, and logged as failed. The paying side now waits up to 90 seconds for a generation. Each paid prop lands in the gallery, and the payment health numbers stop counting these successful payments as failures.",
+ "link": "/forged",
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-09-25",
+ "type": "update",
+ "title": "The model catalog AI clients read now shows the real price of every model",
+ "summary": "The three://models resource that Claude and other MCP clients read listed free models with no price and left some paid models blank. Free models now read as costing nothing, and a model served through a partner route is priced at the model that actually answers, so an assistant comparing costs for you works from real numbers.",
+ "link": "/docs/mcp",
+ "tags": [
+ "fix",
+ "sdk"
+ ]
+ },
{
"date": "2026-09-24",
"type": "launch",
@@ -1585,28 +1607,6 @@
"tags": [
"fix"
]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The in-game economy page reads correctly on a phone, and the boutique shows what you are buying",
- "summary": "A full audit of /play/economy, the published reference for every price, prize and gate in the /play world. On a 320px screen the general store and currency panels were wider than the viewport, and because the page suppresses sideways scrolling their right edge was simply cut off: the store's price column was unreachable on the narrowest phones. Those panels now shrink to fit, and the wide tables scroll inside their own labelled box instead. The bar showing how a paid $THREE sale splits used to print its labels inside the coloured segments, where \"50% holder rewards\" was truncated to \"50% holder re...\"; the split now reads from a legend beneath the bar, which stays legible at any ratio. In the boutique, the Stetson and the Shades rendered as blank grey circles while the five colour items showed their colour, because the page ignored the thumbnail the server was already sending; both now show the item, with the colour swatch as the fallback if an image ever goes missing. The wheel's top prize is relabelled \"JACKPOT: 100 Cash\", and a failed load now reads as a proper sentence before the retry hint.",
- "link": "/play/economy",
- "tags": [
- "fix",
- "improvement"
- ]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The Money Pulse now tells you when its stats are down, and retries on the spot",
- "summary": "When the money-intelligence call behind /pulse failed, the three side panels (Top earners, Busiest wallets, Fresh launches) sat on \"Loading...\" forever and the 7-day activity strip went blank, which reads as \"the platform is quiet\" rather than \"we could not fetch this\". Each surface now says what went wrong, notes that the live feed itself is unaffected and that it retries every minute, and offers a Retry button that refetches immediately. First paint uses skeletons shaped like the real counters, bars and rows instead of dashes and a loading label, so nothing shifts when the numbers land. The empty states point somewhere useful now: no tips yet links to the agent directory, no wallet activity links to the agents that are online. Switching between mainnet and devnet shows the skeletons again rather than leaving the previous network's numbers under the new label. The stat cards report their filter state to screen readers, the rail cards are real headings, and the per-row explorer link is a full-size tap target that says where it goes.",
- "link": "/pulse",
- "tags": [
- "fix",
- "improvement"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index b55197fd5..8a1a1f85a 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,33 @@
{
- "generated_at": "2026-09-24T07:08:16.161Z",
+ "generated_at": "2026-09-25T05:37:06.304Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-09-25",
+ "type": "update",
+ "title": "Props the platform pays Forge to make now land in the /forged gallery",
+ "summary": "Every half hour the platform pays its own Forge to make a new 3D prop for the public /forged gallery. A standard generation takes 20 to 55 seconds, but the paying side gave up after 20. Forge still finished the model and took the payment, so most of those props were paid for, never saved to the gallery, and logged as failed. The paying side now waits up to 90 seconds for a generation. Each paid prop lands in the gallery, and the payment health numbers stop counting these successful payments as failures.",
+ "link": "/forged",
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-09-25",
+ "type": "update",
+ "title": "The model catalog AI clients read now shows the real price of every model",
+ "summary": "The three://models resource that Claude and other MCP clients read listed free models with no price and left some paid models blank. Free models now read as costing nothing, and a model served through a partner route is priced at the model that actually answers, so an assistant comparing costs for you works from real numbers.",
+ "link": "/docs/mcp",
+ "tags": [
+ "fix",
+ "sdk"
+ ]
+ },
{
"date": "2026-09-24",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index e9127e42e..33819dee8 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws: features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Props the platform pays Forge to make now land in the /forged gallery</title>
+ <link>https://three.ws/forged</link>
+ <guid isPermaLink="false">2026-09-25:Props the platform pays Forge to make now land in the /forged gallery</guid>
+ <pubDate>Fri, 25 Sep 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Every half hour the platform pays its own Forge to make a new 3D prop for the public /forged gallery. A standard generation takes 20 to 55 seconds, but the paying side gave up after 20. Forge still finished the model and took the payment, so most of those props were paid for, never saved to the gallery, and logged as failed. The paying side now waits up to 90 seconds for a generation. Each paid prop lands in the gallery, and the payment health numbers stop counting these successful payments as failures.</description>
+ </item>
+ <item>
+ <title>The model catalog AI clients read now shows the real price of every model</title>
+ <link>https://three.ws/docs/mcp</link>
+ <guid isPermaLink="false">2026-09-25:The model catalog AI clients read now shows the real price of every model</guid>
+ <pubDate>Fri, 25 Sep 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The three://models resource that Claude and other MCP clients read listed free models with no price and left some paid models blank. Free models now read as costing nothing, and a model served through a partner route is priced at the model that actually answers, so an assistant comparing costs for you works from real numbers.</description>
+ </item>
<item>
<title>Docs · Trade receipts</title>
<link>https://three.ws/docs/trade-receipts</link>
diff --git a/public/features.json b/public/features.json
index c38bca61c..63af6cb7b 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-24T07:08:16.143Z",
+ "generated_at": "2026-09-25T05:37:06.242Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/check-mcp-catalog.mjs b/scripts/check-mcp-catalog.mjs
new file mode 100644
index 000000000..54f9a77f3
--- /dev/null
+++ b/scripts/check-mcp-catalog.mjs
@@ -0,0 +1,56 @@
+#!/usr/bin/env node
+// Offline build check for data/mcp-catalog.json, the vetted list of external
+// MCP servers an agent owner can connect on /integrations/mcp.
+//
+// Runs the same validateCatalog() the API uses at runtime, so a malformed entry
+// fails `npm run build` (it runs from `prebuild`) and `npm run gate` instead of
+// a 500 on /api/integrations/mcp. It also rejects a tier glob listed under two
+// tiers of one entry, since first-match-wins would silently hide the second.
+//
+// Network checks (is the URL live, is the npm package real) live in
+// scripts/vet-mcp-integrations.mjs, which contributors run before a PR.
+//
+// node scripts/check-mcp-catalog.mjs exit 1 on any error
+// node scripts/check-mcp-catalog.mjs --json print the summary as JSON
+
+import { readFileSync } from 'node:fs';
+import { CATALOG_PATH, validateCatalog } from '../api/_lib/mcp-connections/catalog.js';
+
+let doc;
+try {
+ doc = JSON.parse(readFileSync(CATALOG_PATH, 'utf8'));
+} catch (err) {
+ console.error(`check:mcp-catalog: data/mcp-catalog.json is not valid JSON (${err.message})`);
+ process.exit(1);
+}
+
+const errors = validateCatalog(doc);
+for (const s of doc.servers || []) {
+ const seen = new Map();
+ for (const [tier, list] of Object.entries(s.tiers || {})) {
+ for (const glob of list || []) {
+ if (seen.has(glob)) errors.push(`servers (${s.id}).tiers: "${glob}" is listed under both ${seen.get(glob)} and ${tier}`);
+ seen.set(glob, tier);
+ }
+ }
+}
+
+const byCategory = {};
+for (const s of doc.servers || []) byCategory[s.category] = (byCategory[s.category] || 0) + 1;
+const summary = {
+ servers: (doc.servers || []).length,
+ hosted: (doc.servers || []).filter((s) => s.transport !== 'stdio').length,
+ local: (doc.servers || []).filter((s) => s.transport === 'stdio').length,
+ categories: byCategory,
+ errors,
+};
+
+if (process.argv.includes('--json')) console.log(JSON.stringify(summary, null, 2));
+if (errors.length) {
+ console.error(`check:mcp-catalog: ${errors.length} problem(s) in data/mcp-catalog.json`);
+ for (const e of errors) console.error(` ${e}`);
+ process.exit(1);
+}
+if (!process.argv.includes('--json')) {
+ console.log(`check:mcp-catalog: ok, ${summary.servers} servers (${summary.hosted} hosted, ${summary.local} local) in ${Object.keys(byCategory).length} categories`);
+}
diff --git a/scripts/okx-bot-llm-gateway.mjs b/scripts/okx-bot-llm-gateway.mjs
index 9e7f571de..3628e152d 100644
--- a/scripts/okx-bot-llm-gateway.mjs
+++ b/scripts/okx-bot-llm-gateway.mjs
@@ -46,6 +46,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { config as loadEnv } from 'dotenv';
+import { requireServiceEnvValue } from './lib/service-env.mjs';
loadEnv({ path: '.env.local', quiet: true });
loadEnv({ path: '.env', quiet: true });
@@ -130,7 +131,15 @@ function gcloud(argv, { input } = {}) {
}
async function db() {
- if (!process.env.DATABASE_URL) die('DATABASE_URL is not set (it lives in .env.local)');
+ // A fresh clone has no .env.local, so resolve production's copy off the API
+ // service (a Secret Manager reference) rather than stall the deploy on it.
+ if (!process.env.DATABASE_URL) {
+ try {
+ process.env.DATABASE_URL = requireServiceEnvValue('DATABASE_URL');
+ } catch (err) {
+ die(`DATABASE_URL is not set in .env.local and ${err.message}`);
+ }
+ }
const { sql } = await import('../api/_lib/db.js');
return sql;
}
diff --git a/scripts/vet-mcp-integrations.mjs b/scripts/vet-mcp-integrations.mjs
index ccbef3b19..4a3147b51 100644
--- a/scripts/vet-mcp-integrations.mjs
+++ b/scripts/vet-mcp-integrations.mjs
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-// Vet every entry in data/mcp-integrations.json against the live internet.
+// Vet every entry in data/mcp-catalog.json against the live internet.
//
// For each remote server: open an MCP session with no credentials. An open
// server must answer initialize and tools/list (its tool count is recorded); a
@@ -13,11 +13,11 @@
// node scripts/vet-mcp-integrations.mjs --only=github,linear
//
// Network-bound on purpose, so it is not part of the offline build check
-// (scripts/check-mcp-integrations.mjs). Run it before adding or changing entries.
+// (scripts/check-mcp-catalog.mjs). Run it before adding or changing entries.
import { readFileSync, writeFileSync } from 'node:fs';
import { CATALOG_PATH, validateCatalog } from '../api/_lib/mcp-connections/catalog.js';
-import { probeServer } from '../api/_lib/mcp-connections/client.js';
+import { discoverAuth, probeServer } from '../api/_lib/mcp-connections/client.js';
const args = process.argv.slice(2);
const write = args.includes('--write');
@@ -62,7 +62,13 @@ async function vet(entry) {
if (probe.auth === 'none') {
notes.push(`open, ${probe.tools.length} tools`);
if (write) entry.toolCount = probe.tools.length;
- if (entry.auth.type === 'oauth') problems.push('catalog says oauth but the server is open');
+ // Some servers publish their tool list to anyone and demand sign-in only
+ // on tools/call. That is still an OAuth server, as long as it says so.
+ if (entry.auth.type === 'oauth') {
+ const found = await discoverAuth(entry.url);
+ if (found) notes.push(`tool list is public, calls need oauth (${found.registration})`);
+ else problems.push('catalog says oauth but the server is open and publishes no OAuth metadata');
+ }
} else if (probe.auth === 'oauth') {
notes.push(`oauth (${probe.registration})`);
if (entry.auth.type === 'none') problems.push('catalog says no auth but the server demands it');
diff --git a/tests/community-skills-registry.test.js b/tests/community-skills-registry.test.js
new file mode 100644
index 000000000..52beee3aa
--- /dev/null
+++ b/tests/community-skills-registry.test.js
@@ -0,0 +1,192 @@
+// Community skills registry validator (community-skills/tools/registry.mjs).
+//
+// This is the gate a contributor's pull request goes through: the same module
+// runs as `node tools/validate.mjs` in the public mirror and inside
+// `npm run build:pages` here. Each case builds a throwaway registry tree on disk
+// and asserts the verdict, so a malformed skill can never reach
+// /skills/community and a well-formed one always does.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import {
+ buildRegistry,
+ serializeRegistry,
+ parseSkillMarkdown,
+ findTokenReferences,
+ estimateTokens,
+ PROMOTED_COIN,
+ LIMITS,
+} from '../community-skills/tools/registry.mjs';
+
+const BODY = `# Example skill
+
+When the user asks for a position check, read the wallet first, then state the
+three numbers that matter: size, stop and the loss at the stop. Never recommend
+a trade the numbers do not support, and say so plainly when they do not.
+Close with one line naming the next safe action.`;
+
+const GOOD_META = {
+ name: 'Example Skill',
+ description: 'A worked example that reads a wallet and states size, stop and loss at the stop.',
+ author: 'three.ws',
+ tags: ['example', 'risk'],
+ version: '1.0.0',
+ license: 'MIT',
+};
+
+let root;
+
+function addSkill(slug, { meta = GOOD_META, skillMd, files = {} } = {}) {
+ const dir = join(root, 'skills', slug);
+ mkdirSync(dir, { recursive: true });
+ const md = skillMd ?? `---\nname: ${slug}\ndescription: Use when the user asks whether a position is sized safely.\n---\n\n${BODY}\n`;
+ writeFileSync(join(dir, 'SKILL.md'), md);
+ if (meta !== null) writeFileSync(join(dir, 'metadata.json'), typeof meta === 'string' ? meta : JSON.stringify(meta, null, '\t'));
+ for (const [rel, content] of Object.entries(files)) {
+ mkdirSync(join(dir, rel, '..'), { recursive: true });
+ writeFileSync(join(dir, rel), content);
+ }
+}
+
+function messages(result) {
+ return result.errors.map((e) => `${e.slug}: ${e.message}`);
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'community-skills-'));
+ mkdirSync(join(root, 'skills'));
+});
+
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('a well-formed skill', () => {
+ it('passes and becomes a registry entry with a stable hash and token count', () => {
+ addSkill('example-skill', { files: { 'scripts/run.mjs': 'console.log(1);\n', 'references/notes.md': 'Plain notes.\n' } });
+ const result = buildRegistry(root);
+ expect(messages(result)).toEqual([]);
+ expect(result.ok).toBe(true);
+ expect(result.registry.count).toBe(1);
+ const [entry] = result.registry.skills;
+ expect(entry).toMatchObject({
+ slug: 'example-skill',
+ name: 'Example Skill',
+ author: 'three.ws',
+ tags: ['example', 'risk'],
+ version: '1.0.0',
+ path: 'skills/example-skill',
+ files: ['SKILL.md', 'metadata.json', 'references/notes.md', 'scripts/run.mjs'],
+ });
+ expect(entry.sha256).toMatch(/^[0-9a-f]{64}$/);
+ expect(entry.tokens).toBe(estimateTokens(parseSkillMarkdown(readFileSync(join(root, 'skills/example-skill/SKILL.md'), 'utf8')).body));
+ expect(result.registry.tags).toEqual([{ tag: 'example', count: 1 }, { tag: 'risk', count: 1 }]);
+ });
+
+ it('serializes byte-identically on every build, so --check can detect a stale index', () => {
+ addSkill('example-skill');
+ addSkill('second-skill', { meta: { ...GOOD_META, name: 'Second Skill' } });
+ const a = serializeRegistry(buildRegistry(root).registry);
+ const b = serializeRegistry(buildRegistry(root).registry);
+ expect(a).toBe(b);
+ expect(JSON.parse(a).skills.map((s) => s.slug)).toEqual(['example-skill', 'second-skill']);
+ });
+
+ it('allows the promoted coin, the chain rails and shell variables inside code', () => {
+ const md = `---\nname: rails-skill\ndescription: Use when paying for a service with the chain rails.\n---\n\n${BODY}\n\nPay in $USDC, fees in $SOL, hold $THREE (${PROMOTED_COIN.mint}).\n\n\`\`\`sh\necho $HOME $PATH\n\`\`\`\n`;
+ addSkill('rails-skill', { skillMd: md });
+ expect(messages(buildRegistry(root))).toEqual([]);
+ });
+});
+
+describe('a malformed skill fails the build', () => {
+ it('rejects metadata.json with a missing required field', () => {
+ const { author: _drop, ...meta } = GOOD_META;
+ addSkill('no-author', { meta });
+ const result = buildRegistry(root);
+ expect(result.ok).toBe(false);
+ expect(messages(result)).toContain('no-author: metadata.json is missing "author"');
+ expect(result.registry.skills).toEqual([]);
+ });
+
+ it('rejects metadata.json that is not JSON', () => {
+ addSkill('bad-json', { meta: '{ "name": "Bad", ' });
+ expect(messages(buildRegistry(root)).some((m) => m.startsWith('bad-json: metadata.json is not valid JSON'))).toBe(true);
+ });
+
+ it('rejects a missing metadata.json', () => {
+ addSkill('no-meta', { meta: null });
+ expect(messages(buildRegistry(root))).toContain('no-meta: metadata.json is missing');
+ });
+
+ it('rejects unknown metadata fields, bad semver, bad tags and duplicate tags', () => {
+ addSkill('loose-meta', { meta: { ...GOOD_META, version: 'v1', tags: ['Risk', 'risk', 'risk'], homepage: 'x' } });
+ const m = messages(buildRegistry(root));
+ expect(m).toContain('loose-meta: metadata.json has unknown field "homepage" (allowed: name, description, author, tags, version, license)');
+ expect(m).toContain('loose-meta: metadata.json "version" must be semver, e.g. "1.0.0"');
+ expect(m.some((x) => x.includes('tag "Risk" must be lowercase kebab-case'))).toBe(true);
+ expect(m).toContain('loose-meta: tag "risk" is listed twice');
+ });
+
+ it('rejects a directory name that is not a URL-safe slug', () => {
+ addSkill('Bad_Slug', { skillMd: `---\nname: Bad_Slug\ndescription: Use when the user asks whether a position is sized safely.\n---\n\n${BODY}\n` });
+ expect(messages(buildRegistry(root)).some((m) => m.includes('must be a URL-safe slug'))).toBe(true);
+ });
+
+ it('rejects slugs that collide case-insensitively and names used twice', () => {
+ addSkill('one-skill');
+ addSkill('two-skill');
+ const m = messages(buildRegistry(root));
+ expect(m).toContain('two-skill: name "Example Skill" is already used by one-skill');
+ });
+
+ it('rejects SKILL.md without frontmatter, with a mismatched name, or with a thin body', () => {
+ addSkill('no-front', { skillMd: `# Heading\n\n${BODY}\n` });
+ addSkill('wrong-name', { meta: { ...GOOD_META, name: 'Wrong' }, skillMd: `---\nname: other\ndescription: Use when the user asks whether a position is sized safely.\n---\n\n${BODY}\n` });
+ addSkill('thin-body', { meta: { ...GOOD_META, name: 'Thin' }, skillMd: '---\nname: thin-body\ndescription: Use when the user asks whether a position is sized safely.\n---\n\nToo short.\n' });
+ const m = messages(buildRegistry(root));
+ expect(m).toContain('no-front: SKILL.md must open with a --- frontmatter block holding name and description');
+ expect(m).toContain('wrong-name: SKILL.md frontmatter name "other" must equal the directory name "wrong-name"');
+ expect(m.some((x) => x.startsWith('thin-body: SKILL.md body is') && x.includes(`at least ${LIMITS.bodyMinChars}`))).toBe(true);
+ });
+
+ it('rejects a third-party cashtag in prose and an unknown address anywhere', () => {
+ const foreign = 'THREEsynthetic11111111111111111111111111111';
+ addSkill('shill-skill', { skillMd: `---\nname: shill-skill\ndescription: Use when the user asks whether a position is sized safely.\n---\n\n${BODY}\n\nBuy $MOON now.\n` });
+ addSkill('pinned-skill', { meta: { ...GOOD_META, name: 'Pinned' }, files: { 'scripts/pin.mjs': `const MINT = '${foreign}';\nconsole.log(MINT);\n` } });
+ const m = messages(buildRegistry(root));
+ expect(m).toContain('shill-skill: SKILL.md: third-party token reference (cashtag $MOON)');
+ expect(m).toContain(`pinned-skill: scripts/pin.mjs: third-party token reference (address ${foreign})`);
+ });
+
+ it('rejects files outside references/ and scripts/, and scripts that do not parse', () => {
+ addSkill('stray-file', { files: { 'notes.txt': 'x' } });
+ addSkill('broken-script', { meta: { ...GOOD_META, name: 'Broken' }, files: { 'scripts/run.mjs': 'const = ;\n' } });
+ const m = messages(buildRegistry(root));
+ expect(m).toContain('stray-file: notes.txt is not allowed; a skill holds SKILL.md, metadata.json, references/ and scripts/ only');
+ expect(m.some((x) => x.startsWith('broken-script: scripts/run.mjs does not parse'))).toBe(true);
+ });
+});
+
+describe('findTokenReferences', () => {
+ it('flags foreign cashtags in prose only and ignores long all-letter words', () => {
+ expect(findTokenReferences('hold $THREE, pay $USDC')).toEqual([]);
+ expect(findTokenReferences('`$FOO` in code')).toEqual([]);
+ expect(findTokenReferences('ape into $FOO')).toEqual(['cashtag $FOO']);
+ expect(findTokenReferences('Supercalifragilisticexpialidociousness')).toEqual([]);
+ });
+});
+
+describe('the committed registry', () => {
+ it('is valid and up to date with community-skills/skills', () => {
+ const r = spawnSync(process.execPath, ['community-skills/tools/validate.mjs', '--check'], { encoding: 'utf8' });
+ expect(r.stderr).toBe('');
+ expect(r.status).toBe(0);
+ const committed = JSON.parse(readFileSync('community-skills/registry.json', 'utf8'));
+ expect(committed.count).toBeGreaterThanOrEqual(12);
+ expect(committed.skills.map((s) => s.slug)).toContain('risk-manager');
+ });
+});
diff --git a/tests/x402-pay-paid-timeout.test.js b/tests/x402-pay-paid-timeout.test.js
new file mode 100644
index 000000000..3b7a8d54e
--- /dev/null
+++ b/tests/x402-pay-paid-timeout.test.js
@@ -0,0 +1,134 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
+import http from 'node:http';
+import { Keypair } from '@solana/web3.js';
+
+// A paid route that does its work BEFORE it settles (the paid Forge generates the
+// mesh, then settles) keeps running after the buyer gives up: aborting the paid
+// replay does not cancel the server, it still settles, and the buyer books a
+// charged call as `This operation was aborted`. On 2026-09-24/25 that was 7 of
+// the 9 ring-paid forge generations. payX402 therefore takes a budget for the
+// paid replay alone, and the forge pipeline passes one that clears the lane.
+//
+// Driven against a local 402 server: the Solana transfer is genuinely built and
+// signed, but nothing is broadcast and nothing is spent.
+
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+process.env.X402_ASSET_MINT_SOLANA = USDC;
+
+const { payX402, FETCH_TIMEOUT_MS } = await import('../api/_lib/x402/pay.js');
+
+const payTo = Keypair.generate().publicKey.toBase58();
+const feePayer = Keypair.generate().publicKey.toBase58();
+
+// How long the PAID replay takes to answer. The probe always answers at once.
+let paidDelayMs = 0;
+let paidAttempts = 0;
+let server;
+let origin;
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ if (!req.headers['x-payment']) {
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({
+ x402Version: 2,
+ accepts: [{
+ scheme: 'exact',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ asset: USDC,
+ payTo,
+ amount: '1000',
+ extra: { name: 'USDC', decimals: 6, feePayer },
+ }],
+ }));
+ return;
+ }
+ paidAttempts++;
+ setTimeout(() => {
+ if (res.destroyed) return;
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json');
+ res.setHeader(
+ 'x-payment-response',
+ Buffer.from(JSON.stringify({ success: true, transaction: 'SIG_SLOW' })).toString('base64'),
+ );
+ res.end(JSON.stringify({ status: 'done' }));
+ }, paidDelayMs);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ origin = `http://127.0.0.1:${server.address().port}`;
+});
+
+afterAll(() => new Promise((resolve) => {
+ server.closeAllConnections?.();
+ server.close(resolve);
+}));
+
+beforeEach(() => {
+ paidDelayMs = 0;
+ paidAttempts = 0;
+});
+
+const payCtx = {
+ buyer: Keypair.generate(),
+ conn: { getAccountInfo: async () => ({ lamports: 1 }) },
+ blockhash: '11111111111111111111111111111111',
+ mintInfo: { decimals: 6 },
+ selfPay: true,
+ remainingCap: 100_000,
+};
+
+describe('payX402 paid-replay budget', () => {
+ it('aborts a paid replay that outlasts paidTimeoutMs', async () => {
+ paidDelayMs = 3_000;
+ await expect(
+ payX402({ url: `${origin}/slow`, method: 'POST', body: {}, ...payCtx, paidTimeoutMs: 1_000 }),
+ ).rejects.toThrow(/abort/i);
+ expect(paidAttempts).toBe(1);
+ });
+
+ it('waits out a slow paid replay when the budget covers it', async () => {
+ paidDelayMs = 400;
+ const r = await payX402({ url: `${origin}/slow`, method: 'POST', body: {}, ...payCtx, paidTimeoutMs: 5_000 });
+ expect(r.paid).toBe(true);
+ expect(r.txSig).toBe('SIG_SLOW');
+ expect(paidAttempts).toBe(1);
+ });
+
+ it('keeps the shared default for every caller that does not opt in', async () => {
+ const r = await payX402({ url: `${origin}/fast`, method: 'POST', body: {}, ...payCtx });
+ expect(r.paid).toBe(true);
+ expect(FETCH_TIMEOUT_MS).toBe(20_000);
+ });
+});
+
+describe('forge prop pipeline', () => {
+ it('pays the forge with a budget that clears the lane, not the 20s default', async () => {
+ vi.resetModules();
+ const calls = [];
+ vi.doMock('../api/_lib/db.js', () => ({ sql: async () => [] }));
+ vi.doMock('../api/_lib/x402/pay.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ payX402: async (args) => {
+ calls.push(args);
+ return { success: false, paid: false, amountAtomic: 0, txSig: null, status: 503, errorMsg: 'http_503' };
+ },
+ }));
+ const { run, FORGE_PAID_TIMEOUT_MS } = await import('../api/_lib/x402/pipelines/forge-content.js');
+ await run({
+ origin,
+ buyer: payCtx.buyer,
+ conn: payCtx.conn,
+ blockhash: payCtx.blockhash,
+ mintInfo: payCtx.mintInfo,
+ });
+ expect(calls).toHaveLength(1);
+ expect(calls[0].paidTimeoutMs).toBe(FORGE_PAID_TIMEOUT_MS);
+ // Observed server-side completion runs to about 55s; anything under a
+ // minute re-creates the charged-but-aborted class.
+ expect(FORGE_PAID_TIMEOUT_MS).toBeGreaterThanOrEqual(60_000);
+ vi.doUnmock('../api/_lib/db.js');
+ vi.doUnmock('../api/_lib/x402/pay.js');
+ });
+});