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: enhance agent funding policy and improve rate limiting for Solana RPC endpoints

nirholas17435b8cd1fe
diff --git a/CLAUDE.md b/CLAUDE.md
index 3ad6e13d2..c5c253f3b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -203,7 +203,7 @@ We have strong product-level docs (README, STRUCTURE.md, changelog) but feature-
Match the doc to the kind of work. Do every layer that applies, skip the ones that don't:
- **New page or public route** → add it to `data/pages.json` (path, title, description, `added` date). This feeds the sitemap, `llms.txt`, `features.json`, and the changelog automatically. This is the one mandatory step for anything user-reachable.
-- **New SDK, package, worker, service, or top-level directory** → a `README.md` *in that directory* is required: what it does, how to install/use it, its public API/exports, and one runnable example. New package under `packages/*`, new `workers/<name>/`, new SDK: no exceptions. This is the gap we're closing; ~40% of dirs are missing one.
+- **New SDK, package, worker, service, or top-level directory** → a `README.md` *in that directory* is required: what it does, how to install/use it, its public API/exports, and one runnable example. New package under `packages/*`, new `workers/<name>/`, new SDK: no exceptions. Coverage under `packages/`, `workers/`, and `services/` is currently 100% (64/32/3 dirs, all with a README). That is a standard to hold, not a stat to admire: the next directory that lands without one breaks it.
- **New product surface or directory** → add a row to `STRUCTURE.md` mapping it to its location and status. Nothing enforces this in CI, so it's on you. If you moved or graduated a surface, update its existing row.
- **New developer-facing capability** (API endpoint, MCP tool, protocol, integration, CLI) → add or update the relevant file in `docs/` (`docs/api-reference.md`, `docs/mcp.md`, `docs/tutorials/*`, etc.). Follow the format of the neighboring docs in that folder. A genuinely new subsystem gets its own `docs/<feature>.md` linked from `docs/start-here.md`.
- **New load-bearing contract or wire format** (manifest schema, on-chain interface, embed protocol, permission model) → write or update the spec in `specs/`. Specs are contracts other code depends on, not tutorials.
@@ -252,7 +252,11 @@ When reverting, do NOT use git's default `Revert "<original title>"` message: it
Remember stop-and-ask gate 2: production deploys need owner approval unless the owner's current instruction is itself the approval. Full runbook incl. LB/DNS/TLS/env/rollback/recovery: `docs/ops/gcp-production.md`. GPU workers deploy from their own `workers/<name>/cloudbuild.yaml`.
1. **Prepare a CLEAN worktree.** `git worktree add --detach /workspaces/.deploy-wt HEAD`, then hardlink THREE artifacts with `cp -al` on the same filesystem (not just the first): `node_modules`, `chat/node_modules`, and `character-studio/build`, plus copy `.env`. Omitting either nested one kills the build minutes in: an OOM exit 144 on the avatar-studio rebuild, or `Cannot find package '@sveltejs/vite-plugin-svelte'` on the chat build. See `docs/ops/gcp-production.md`.
-2. **Build: `npm run build:gcp`.** ORDER IS LOAD-BEARING and `build:gcp` encodes it: the frontend `vite build` WIPES `dist/`, so it must run FIRST, then the UMD lib build, then `publish:lib` (which mirrors the lib into `dist/`), then `build:info`, then `check:dist`, then `check:pages`. Do NOT hand-run `build:vercel` as the frontend build: it builds the SDK/lib sub-artifacts, NOT the static HTML pages, so `dist/` ends up without `/`, `/create`, etc. and `check:dist` fails. `check:dist` needs the UMD bundle (`publish:lib`) present.
+2. **Build: `npm run build:gcp`.** ORDER IS LOAD-BEARING and `build:gcp` already encodes it. Never hand-run the steps in a different order. The full chain, in order:
+
+ `ensure:avatar-studio` → `build:info:snapshot` → `build:chat` → `build` (the frontend `vite build`) → `build:lib:full` (the UMD lib) → `publish:lib` → `build:info` → `check:dist` → `check:pages`
+
+ Why the order is load-bearing: the frontend `vite build` runs with `emptyOutDir`, so it WIPES `dist/` and everything that writes into `dist/` must come after it. `publish:lib` mirrors the UMD lib into `dist/`, so it must follow `build:lib:full`, and `check:dist` fails without that bundle present. The first two steps are exactly why step 1 stages worktree artifacts: `ensure:avatar-studio` consumes `character-studio/build` and `build:chat` consumes `chat/node_modules`. Do NOT hand-run `build:vercel` as the frontend build: it builds the SDK/lib sub-artifacts, NOT the static HTML pages, so `dist/` ends up without `/`, `/create`, etc. and `check:dist` fails.
3. **Submit: `gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5`.** EVERY cloudbuild config must pin `serviceAccount: .../three-ws-build@...` (the default compute SA was deleted), and manual submits need `--substitutions=SHORT_SHA=manual$(date +%s)` when the config tags images with `$SHORT_SHA`.
4. **Purge CDN: `npm run deploy:gcp:purge-cdn`.** The purge is synchronous on purpose. Do not re-add `--async`, or post-deploy checks read stale edge content and report phantom failures.
5. **Verify the deploy landed.** `curl -s https://three.ws/api/version` returns the live commit SHA + Cloud Run revision, and `npm run smoke:prod` sweeps every page declared in `data/pages.json` against the live site (`deploy:gcp` runs it automatically after the purge).
@@ -266,7 +270,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.
- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).
- 3D: Three.js with glTF/GLB.
- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.
-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (100 as of 2026-07-29, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file consumed by the server (routes + crons): never delete it as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (100 as of 2026-07-29, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).
- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.
- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.
diff --git a/api/_lib/agent-funding-policy.js b/api/_lib/agent-funding-policy.js
new file mode 100644
index 000000000..15c5c747c
--- /dev/null
+++ b/api/_lib/agent-funding-policy.js
@@ -0,0 +1,63 @@
+/**
+ * Where the platform's agent-wallet funding levels come from — one definition,
+ * read by both the cron that PUTS SOL IN and the cron that TAKES SOL OUT.
+ *
+ * These two live in different services (the sniper worker's auto-funder tops an
+ * arm up from the launcher master; the economy's idle-capital reclaim sweeps
+ * agent wallets back to the economy master) and for a while neither knew the
+ * other's numbers. The result was a pure oscillation: the funder refilled an
+ * arm to its target, the reclaim swept it back below that target minutes later,
+ * the funder refilled it again. In one observed 15-minute window 0.24 SOL made
+ * that round trip six times across two arms, every leg paying network fees, and
+ * the arms never held a balance long enough to place a trade. It only stopped
+ * when the funding master ran dry.
+ *
+ * The invariant that prevents it, and the reason this module exists:
+ *
+ * **A reclaim floor must never sit below the funding target of the same
+ * wallet.** If it does, the two crons chase each other forever.
+ *
+ * This mirrors the guard the engine sweep already has (`reclaimableSol` never
+ * leaves an engine under the topup's `minSol`) — the agent-wallet path simply
+ * never got it, because the funder and the reclaim were written a month apart in
+ * different subsystems.
+ */
+
+function num(name, def) {
+ const raw = process.env[name];
+ if (raw == null || raw === '') return def;
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : def;
+}
+
+/**
+ * Balance under which an opted-in agent wallet gets topped up.
+ * Env: SNIPER_AUTO_FUND_MIN_SOL.
+ */
+export function autoFundMinSol() {
+ return Math.max(0, num('SNIPER_AUTO_FUND_MIN_SOL', 0.02));
+}
+
+/**
+ * Balance an opted-in agent wallet is topped up TO. Nothing that removes SOL
+ * from such a wallet may leave it below this, or the top-up fires again.
+ * Env: SNIPER_AUTO_FUND_TARGET_SOL.
+ */
+export function autoFundTargetSol() {
+ return Math.max(autoFundMinSol(), num('SNIPER_AUTO_FUND_TARGET_SOL', 0.05));
+}
+
+/**
+ * The anti-oscillation floor for one agent wallet: the smallest balance a
+ * reclaim may leave behind without handing the funder a reason to refill.
+ *
+ * Only applies to wallets the funder actually manages — an agent that never
+ * opted into auto-funding (`auto_fund_enabled = false`) is nobody's refill
+ * target, so sweeping it lower cannot oscillate. Pure.
+ *
+ * @param {{autoFundEnabled?: boolean}} agent
+ * @returns {number} SOL that must remain, 0 when the funder would not refill it
+ */
+export function antiOscillationFloorSol(agent = {}) {
+ return agent.autoFundEnabled === true ? autoFundTargetSol() : 0;
+}
diff --git a/api/_lib/economy-sweepback.js b/api/_lib/economy-sweepback.js
index a642076db..4ec563f9f 100644
--- a/api/_lib/economy-sweepback.js
+++ b/api/_lib/economy-sweepback.js
@@ -30,6 +30,7 @@ import { ECONOMY_MASTER_ADDRESS } from './economy-master.js';
import { sendSol, LAMPORTS_PER_SOL } from './avatar-wallet.js';
import { submitProtected } from './execution-engine.js';
import { MIN_OPERATIONAL_WALLET_SOL } from './agent-trade-guards.js';
+import { antiOscillationFloorSol } from './agent-funding-policy.js';
// Same float the treasury-topup cron refills to — sweep only above it.
const DEFAULT_REFILL_MULTIPLE = 3;
@@ -459,7 +460,15 @@ const AGENT_RECLAIM_MAX_WALLETS = num('AGENT_RECLAIM_MAX_WALLETS', 40);
* @returns {number} floor in SOL
*/
export function agentReclaimFloorSol(strategy = {}) {
- if (!strategy.enabled) return AGENT_IDLE_FLOOR_SOL;
+ // Anti-oscillation, and it outranks everything else here: a wallet the sniper
+ // auto-funder refills to a target must never be swept below that target, or the
+ // two crons chase the same SOL forever. Measured before this guard existed: 0.24
+ // SOL round-tripped six times between the funding master and two arms inside 15
+ // minutes, paying fees each leg, until the funding master ran dry. Applies even
+ // to a DISABLED strategy — the funder's opt-in flag, not `enabled`, is what
+ // decides whether a refill is coming.
+ const antiOscillation = antiOscillationFloorSol({ autoFundEnabled: strategy.autoFundEnabled });
+ if (!strategy.enabled) return round(Math.max(AGENT_IDLE_FLOOR_SOL, antiOscillation));
const perTrade = Number(strategy.perTradeSol);
// An ENABLED arm always keeps at least what one complete trade costs. Sizing the
// floor on `per_trade × 2` alone ignored everything a buy needs BESIDES the buy
@@ -471,7 +480,7 @@ export function agentReclaimFloorSol(strategy = {}) {
const working = Number.isFinite(perTrade) && perTrade > 0
? perTrade * AGENT_ACTIVE_TRADE_MULTIPLE + MIN_OPERATIONAL_WALLET_SOL
: MIN_OPERATIONAL_WALLET_SOL;
- return round(Math.max(AGENT_IDLE_FLOOR_SOL, working));
+ return round(Math.max(AGENT_IDLE_FLOOR_SOL, working, antiOscillation));
}
/**
@@ -565,6 +574,9 @@ export async function reclaimIdleAgentSol({ connection, network = 'mainnet', dry
LOWER(u.email) AS owner,
s.enabled AS strategy_enabled,
s.per_trade_lamports AS per_trade_lamports,
+ -- The funder's opt-in flag, not `enabled`: it decides whether a refill
+ -- is coming, and therefore whether sweeping this wallet would oscillate.
+ s.auto_fund_enabled AS auto_fund_enabled,
(SELECT COUNT(*) FROM agent_sniper_positions p
WHERE p.agent_id = a.id AND p.status IN ('open', 'closing'))::int AS open_positions
FROM agent_identities a
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index aa36fd34e..1760c00e3 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1392,6 +1392,15 @@ export const limits = {
// fails closed to the 402 challenge rather than uncapping the scan path.
newsArchiveFreeIp: (ip) =>
getLimiter('news:archive:free:ip', { limit: 60, window: '1 d', critical: true }).limit(ip),
+ // Grounded web search (api/web-search.js). Every call is a Vertex Gemini
+ // generateContent with the google_search tool: real GCP-credit spend plus a
+ // Google Search round-trip, so it must NOT sit in the generic publicIp
+ // bucket where a scraper could turn our credits into a free SERP API. 20/10m
+ // covers interactive use (a person refining a query) and prices bulk
+ // extraction out. Critical so a Redis outage fails closed rather than
+ // uncapping paid inference.
+ webSearchIp: (ip) =>
+ getLimiter('web-search:ip', { limit: 20, window: '10 m', critical: true }).limit(ip),
// Premium-pass purchase lane (api/premium/*). Quote builds a Solana tx (an
// RPC blockhash round-trip + a DB row) and subscribe replays an RPC
// getParsedTransaction per attempt — both cheap, but neither should be
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index b608adb4f..6dbdd9020 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -1005,10 +1005,20 @@ export function paidEndpoint(spec) {
);
if (receiptBuilt) {
responseExtensions = receiptBuilt.extensionFragment;
+ // Store the SAME settlement context the receipt was issued
+ // against: `settled` alone can be missing the payer (some
+ // facilitators omit it), and a payer-less row is dropped by
+ // the storage layer, silently losing a receipt the buyer
+ // already holds. Amount/asset come from the verified
+ // requirement so the buyer can see what each call cost.
recordReceipt({
resourceUrl,
signedReceipt: receiptBuilt.signedReceipt,
- settled,
+ settled: receiptSettled,
+ payment: {
+ amountAtomics: verified.requirement?.amount || null,
+ asset: verified.requirement?.asset || null,
+ },
});
}
} catch (err) {
diff --git a/api/_lib/x402/receipt-storage.js b/api/_lib/x402/receipt-storage.js
index 692a8ac94..fd21ae245 100644
--- a/api/_lib/x402/receipt-storage.js
+++ b/api/_lib/x402/receipt-storage.js
@@ -26,12 +26,21 @@ function normalisePayer(payer) {
/**
* Persist a signed receipt. Returns nothing — caller does not await.
*
+ * The signed artifact is stored verbatim, but the row also records settlement
+ * facts the artifact deliberately omits: the transaction hash (dropped from the
+ * payload when the endpoint declares includeTxHash=false per spec §5.2) and the
+ * amount/asset (never part of a receipt payload at all). Those are our own
+ * audit trail, so the wire format and its privacy properties are unchanged;
+ * /api/x402/my-receipts only ever returns them to the wallet that signed for
+ * its own receipts.
+ *
* @param {object} args
* @param {string} args.resourceUrl
* @param {object} args.signedReceipt
* @param {{ payer?: string, network?: string, transaction?: string }} args.settled
+ * @param {{ amountAtomics?: string|number|null, asset?: string|null }} [args.payment]
*/
-export function recordReceipt({ resourceUrl, signedReceipt, settled }) {
+export function recordReceipt({ resourceUrl, signedReceipt, settled, payment }) {
if (!signedReceipt) return;
const payer = normalisePayer(settled?.payer);
if (!payer) return;
@@ -46,13 +55,19 @@ export function recordReceipt({ resourceUrl, signedReceipt, settled }) {
return;
}
const network = payload.network || settled?.network || null;
- const transaction = payload.transaction || null;
+ // The payload's transaction is absent whenever includeTxHash is false; the
+ // settle response still carries it, and the buyer is entitled to their own.
+ const transaction = payload.transaction || settled?.transaction || null;
+ const amountAtomics =
+ payment?.amountAtomics == null ? null : String(payment.amountAtomics);
+ const asset = payment?.asset || null;
sql`
insert into x402_receipts
- (payer, network, resource_url, format, receipt, transaction)
+ (payer, network, resource_url, format, receipt, transaction, amount_atomics, asset)
values
(${payer}, ${network}, ${resourceUrl}, ${format},
- ${JSON.stringify(signedReceipt)}::jsonb, ${transaction})
+ ${JSON.stringify(signedReceipt)}::jsonb, ${transaction},
+ ${amountAtomics}, ${asset})
`.catch((err) => {
console.error('[x402-receipt-log] insert failed:', err?.message || err);
});
@@ -76,7 +91,8 @@ export async function listReceiptsForPayer({ payer, sinceUnix, limit }) {
? new Date(Number(sinceUnix) * 1000)
: new Date(0);
const rows = await sql`
- select id, payer, network, resource_url, format, receipt, transaction, issued_at
+ select id, payer, network, resource_url, format, receipt, transaction,
+ amount_atomics, asset, issued_at
from x402_receipts
where payer = ${normPayer}
and issued_at >= ${sinceDate.toISOString()}
@@ -91,6 +107,8 @@ export async function listReceiptsForPayer({ payer, sinceUnix, limit }) {
format: r.format,
receipt: r.receipt,
transaction: r.transaction,
+ amountAtomics: r.amount_atomics ?? null,
+ asset: r.asset ?? null,
issuedAt: r.issued_at instanceof Date ? r.issued_at.toISOString() : r.issued_at,
}));
}
diff --git a/api/web-search.js b/api/web-search.js
index 36a974994..ebfaa0420 100644
--- a/api/web-search.js
+++ b/api/web-search.js
@@ -13,7 +13,7 @@
// endpoint degrades to { enabled: false } rather than a 500 — same designed
// "warming up" state as /api/search without a database.
-import { cors, json, method, wrap, rateLimited } from './_lib/http.js';
+import { cors, json, error, method, wrap, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { groundedSearch, webSearchAvailable } from './_lib/web-search.js';
@@ -21,9 +21,6 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
- const rl = await limits.publicIp(clientIp(req));
- if (!rl.success) return rateLimited(res, rl);
-
const url = new URL(req.url, 'http://x');
// Same control-character guard as /api/search: this string is forwarded to
// an upstream API and echoed back in the response.
@@ -35,8 +32,20 @@ export default wrap(async (req, res) => {
const rawSources = parseInt(url.searchParams.get('sources') || '8', 10);
const maxSources = Number.isFinite(rawSources) ? Math.min(Math.max(rawSources, 1), 20) : 8;
+ // Availability and input are checked BEFORE the quota is spent: a deployment
+ // with no GCP project, or a caller who forgot ?q=, must not burn a slot on a
+ // request that could never reach upstream.
if (!webSearchAvailable()) return json(res, 200, { enabled: false, q, sources: [] });
- if (!q) return json(res, 400, { error: 'q required' });
+ if (!q) return error(res, 400, 'missing_query', 'q is required');
+
+ // A DEDICATED bucket, not the generic 240/min publicIp one: every miss here
+ // is a billed Vertex Gemini call plus a Google Search round-trip, so the
+ // shared bucket would let a scraper turn platform credits into a free SERP
+ // API. 20 per 10 minutes covers a person refining a query and prices bulk
+ // extraction out; `critical` fails closed on a Redis outage rather than
+ // uncapping paid inference.
+ const rl = await limits.webSearchIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
let result;
try {
diff --git a/scripts/.probe-tex.mjs b/scripts/.probe-tex.mjs
new file mode 100644
index 000000000..b7f7ac2d0
--- /dev/null
+++ b/scripts/.probe-tex.mjs
@@ -0,0 +1,19 @@
+import { chromium } from 'playwright';
+const routes = ['/avatar-sdk', '/club'];
+const browser = await chromium.launch();
+for (const r of routes) {
+ const page = await browser.newPage();
+ const errs = [];
+ page.on('console', m => { if (m.type() === 'error') errs.push(m.text().slice(0, 120)); });
+ page.on('pageerror', e => errs.push('PAGEERROR ' + e.message.slice(0, 120)));
+ try {
+ await page.goto('https://three.ws' + r, { waitUntil: 'domcontentloaded', timeout: 60000 });
+ await page.waitForTimeout(12000);
+ } catch (e) { errs.push('NAV ' + e.message.slice(0, 80)); }
+ const tex = errs.filter(e => /Couldn't load texture/.test(e));
+ console.log(`${r}: total console errors=${errs.length} textureErrors=${tex.length}`);
+ tex.slice(0, 2).forEach(t => console.log(' ', t));
+ errs.filter(e => !/Couldn't load texture/.test(e)).slice(0, 4).forEach(t => console.log(' other:', t));
+ await page.close();
+}
+await browser.close();
diff --git a/scripts/check-claude-md.mjs b/scripts/check-claude-md.mjs
index 0785dff51..3d8ffa944 100644
--- a/scripts/check-claude-md.mjs
+++ b/scripts/check-claude-md.mjs
@@ -8,7 +8,7 @@
// session discovering the drift. This check makes that drift a red build
// instead of a wasted session.
//
-// Three assertions:
+// Assertions:
// 1. Every `npm run <script>` and backticked script-name (build:gcp,
// check:dist, ...) referenced in CLAUDE.md exists in package.json.
// 2. Every concrete repo path referenced in CLAUDE.md exists on disk.
@@ -17,6 +17,12 @@
// try to open and not find.
// 3. CLAUDE.md honors its own typography rule: no em/en-dashes outside the
// Tone paragraph that names the banned characters.
+// 4. The load-bearing factual claims still hold. These are the ones that
+// have actually drifted before and cost a session each: the cron count,
+// the build:gcp chain order, the db:migrate safety semantics, the
+// README-coverage standard, and the retired X changelog lane. Each is
+// re-derived from the source of truth on every run, so the doc cannot
+// quietly go stale again.
//
// Run: node scripts/check-claude-md.mjs (wired as `npm run check:claude`)
diff --git a/src/md.js b/src/md.js
index 4c27778ed..f22dbb548 100644
--- a/src/md.js
+++ b/src/md.js
@@ -1,148 +1,20 @@
-// Minimal, safe Markdown → HTML for pump.fun bounty briefs and submissions.
+// Markdown for pump.fun bounty briefs/submissions and the agent copilot.
//
-// pump.fun stores briefs and proofs as Markdown (`bodyMarkdown`). Rendering them
-// as raw text loses headings, lists, links, and emphasis — so the detail page
-// reads like a dump. This renders the common subset (headings, lists, quotes,
-// code, emphasis, links, rules) with NO external dependency.
+// This is a thin preset over the shared sanitized pipeline
+// (src/shared/markdown.js): full CommonMark + GFM via `marked`, then a strict
+// DOMPurify pass. Headings are demoted two levels so a brief's `#` sits under
+// the page's section `<h2>`, and `<pre>` keeps the `md-pre` class the bounty
+// stylesheet targets.
//
-// Security: every block's text is HTML-escaped BEFORE any markup is inserted, so
-// user content can never inject tags. Links are whitelisted to http(s), mailto,
-// and root-relative paths — `javascript:` and friends stay inert text. The
-// output is therefore safe to assign via innerHTML.
+// It previously carried ~150 lines of hand-rolled regex parsing. That version
+// could not render tables or nested lists and broke on adjacent emphasis;
+// every fix had to be repeated across the seven other copies in this repo.
-// Private-use sentinel that wraps stashed token indices. It can't appear in real
-// content and survives HTML-escaping untouched, so emphasis rules never reach
-// inside a code span or link, and literal numbers are never mistaken for tokens.
-const SENT = String.fromCharCode(0xe000); // U+E000 private-use sentinel
-const RESTORE = new RegExp(SENT + '(\\d+)' + SENT, 'g');
+import { renderMarkdown } from './shared/markdown.js';
-function esc(str) {
- if (str == null) return '';
- return String(str)
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&#39;');
-}
-
-// Inline formatting on already-escaped text. Code spans and links are stashed as
-// sentinel-wrapped placeholders first so their contents aren't re-processed.
-function inline(s) {
- const tokens = [];
- const stash = (html) => `${SENT}${tokens.push(html) - 1}${SENT}`;
-
- // [label](url) — whitelist safe schemes only.
- s = s.replace(
- /\[([^\]]+)\]\((https?:\/\/[^\s)]+|mailto:[^\s)]+|\/[^\s)]*)\)/g,
- (_, label, url) =>
- stash(
- `<a href="${url}" target="_blank" rel="noopener noreferrer nofollow">${label}</a>`,
- ),
- );
- // `inline code`
- s = s.replace(/`([^`]+)`/g, (_, code) => stash(`<code>${code}</code>`));
- // **bold** / __bold__
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- s = s.replace(/__([^_]+)__/g, '<strong>$1</strong>');
- // *italic* / _italic_ (avoid matching list bullets or intra-word underscores)
- s = s.replace(/(^|[^*])\*([^*\s][^*]*?)\*/g, '$1<em>$2</em>');
- s = s.replace(/(^|[^_\w])_([^_\s][^_]*?)_/g, '$1<em>$2</em>');
- // ~~strike~~
- s = s.replace(/~~([^~]+)~~/g, '<del>$1</del>');
- // bare URL autolink (those inside a stashed anchor are already protected)
- s = s.replace(
- /(^|[\s(])(https?:\/\/[^\s<)]+)/g,
- (_, pre, url) =>
- `${pre}${stash(`<a href="${url}" target="_blank" rel="noopener noreferrer nofollow">${url}</a>`)}`,
- );
-
- return s.replace(RESTORE, (_, i) => tokens[+i]);
-}
-
-const RE_FENCE = /^```/;
-const RE_BLANK = /^\s*$/;
-const RE_HR = /^\s*([-*_])(\s*\1){2,}\s*$/;
-const RE_HEAD = /^(#{1,6})\s+(.*)$/;
-const RE_QUOTE = /^\s*>\s?/;
-const RE_UL = /^\s*[-*+]\s+/;
-const RE_OL = /^\s*\d+[.)]\s+/;
-
-function startsBlock(line) {
- return (
- RE_FENCE.test(line) ||
- RE_HEAD.test(line) ||
- RE_QUOTE.test(line) ||
- RE_UL.test(line) ||
- RE_OL.test(line) ||
- RE_HR.test(line)
- );
-}
+const PRESET = { demoteHeadings: 2, classes: { pre: 'md-pre' } };
+/** Render Markdown to sanitized HTML, safe to assign via innerHTML. */
export function mdToHtml(src) {
- if (src == null) return '';
- const lines = String(src).replace(/\r\n?/g, '\n').split('\n');
- const out = [];
- let i = 0;
-
- while (i < lines.length) {
- const line = lines[i];
-
- if (RE_FENCE.test(line)) {
- const buf = [];
- i++;
- while (i < lines.length && !RE_FENCE.test(lines[i])) buf.push(lines[i++]);
- i++; // closing fence (if present)
- out.push(`<pre class="md-pre"><code>${esc(buf.join('\n'))}</code></pre>`);
- continue;
- }
- if (RE_BLANK.test(line)) {
- i++;
- continue;
- }
- if (RE_HR.test(line)) {
- out.push('<hr/>');
- i++;
- continue;
- }
- const h = line.match(RE_HEAD);
- if (h) {
- const lvl = Math.min(6, h[1].length + 2); // # → h3, so it sits under the section h2
- out.push(`<h${lvl}>${inline(esc(h[2].trim()))}</h${lvl}>`);
- i++;
- continue;
- }
- if (RE_QUOTE.test(line)) {
- const buf = [];
- while (i < lines.length && RE_QUOTE.test(lines[i]))
- buf.push(lines[i++].replace(RE_QUOTE, ''));
- out.push(
- `<blockquote>${inline(esc(buf.join('\n'))).replace(/\n/g, '<br/>')}</blockquote>`,
- );
- continue;
- }
- if (RE_UL.test(line)) {
- const buf = [];
- while (i < lines.length && RE_UL.test(lines[i]))
- buf.push(lines[i++].replace(RE_UL, ''));
- out.push(`<ul>${buf.map((li) => `<li>${inline(esc(li))}</li>`).join('')}</ul>`);
- continue;
- }
- if (RE_OL.test(line)) {
- const buf = [];
- while (i < lines.length && RE_OL.test(lines[i]))
- buf.push(lines[i++].replace(RE_OL, ''));
- out.push(`<ol>${buf.map((li) => `<li>${inline(esc(li))}</li>`).join('')}</ol>`);
- continue;
- }
-
- // Paragraph: gather consecutive non-blank, non-block lines.
- const buf = [];
- while (i < lines.length && !RE_BLANK.test(lines[i]) && !startsBlock(lines[i])) {
- buf.push(lines[i++]);
- }
- out.push(`<p>${inline(esc(buf.join('\n'))).replace(/\n/g, '<br/>')}</p>`);
- }
-
- return out.join('\n');
+ return renderMarkdown(src, PRESET);
}
diff --git a/tests/home-thumbnail-orb.test.js b/tests/home-thumbnail-orb.test.js
index df8642da9..14c520632 100644
--- a/tests/home-thumbnail-orb.test.js
+++ b/tests/home-thumbnail-orb.test.js
@@ -13,6 +13,12 @@
// placeholders are the designed fallback; a guessed URL defeats them.
//
// These are filesystem assertions on the page source, so they run without a browser.
+//
+// "The homepage" is no longer one file: its render-blocking CSS and its two big
+// script blocks were extracted into cacheable assets (public/home.css,
+// src/home-live-agents.js, src/home-bento.js) so the browser can cache them
+// across navigations. The guard has to cover the whole surface, so it reads the
+// markup and every asset the markup loads as one concatenated source.
import { describe, it, expect, beforeAll } from 'vitest';
import { readFileSync } from 'node:fs';
@@ -21,10 +27,29 @@ import { resolve } from 'node:path';
const root = resolve(__dirname, '..');
const read = (p) => readFileSync(resolve(root, p), 'utf8');
+// Every file that makes up the homepage surface. Adding a new extracted asset
+// to pages/home.html means adding it here too, or this guard stops covering it.
+const HOME_SOURCES = [
+ 'pages/home.html',
+ 'public/home.css',
+ 'src/home-live-agents.js',
+ 'src/home-bento.js',
+];
+
describe('homepage thumbnails — no fabricated R2 URLs (ORB regression)', () => {
let home;
beforeAll(() => {
- home = read('pages/home.html');
+ home = HOME_SOURCES.map(read).join('\n');
+ });
+
+ it('loads every extracted homepage asset it guards', () => {
+ // If an asset is renamed and this list is not updated, the concatenated
+ // source silently loses coverage and every assertion below passes vacuously.
+ const markup = read('pages/home.html');
+ for (const src of HOME_SOURCES.slice(1)) {
+ const href = '/' + src.replace(/^public\//, '');
+ expect(markup).toContain(href);
+ }
});
it('never hardcodes an r2.dev thumb/ CDN base', () => {
diff --git a/tests/solana-rpc-priority-and-breaker.test.js b/tests/solana-rpc-priority-and-breaker.test.js
new file mode 100644
index 000000000..683771932
--- /dev/null
+++ b/tests/solana-rpc-priority-and-breaker.test.js
@@ -0,0 +1,160 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+
+import {
+ solanaRpcEndpoints,
+ markEndpointCooldown,
+ isEndpointCooling,
+ hydrateEndpointCooldowns,
+} from '../api/_lib/solana/connection.js';
+import { cacheGet, cacheSet, cacheDel } from '../api/_lib/cache.js';
+
+// Two production defects this file locks down, both found in the 2026-07-28
+// triage sweep:
+//
+// 1. PRIORITY INVERSION. ~35 call sites spell their default as
+// `process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'`.
+// Because an explicit url is pinned at priority 1, unsetting SOLANA_RPC_URL
+// made the single most-throttled endpoint in the chain outrank Helius and
+// every paid lane at once.
+// 2. PER-INSTANCE-ONLY BREAKER. The quota verdict lived in a process Map that
+// dies with each Cloud Run cold start, so every fresh instance re-burned a
+// request against a provider already over its cap — actively harmful on a
+// DAILY cap, where the wasted probes are what keep the account pinned.
+
+const PUBLIC_MAINNET = 'https://api.mainnet-beta.solana.com';
+const PUBLIC_DEVNET = 'https://api.devnet.solana.com';
+const COOLDOWN_CACHE_KEY = 'rpccool:v1';
+
+const ENV_KEYS = [
+ 'SOLANA_RPC_URL',
+ 'SOLANA_RPC_URL_DEVNET',
+ 'QUICKNODE_RPC_URL',
+ 'QUICKNODE_RPC_URL_DEVNET',
+ 'HELIUS_API_KEY',
+ 'ALCHEMY_API_KEY',
+ 'ANKR_API_KEY',
+ 'DRPC_API_KEY',
+ 'SOLANA_RPC_FALLBACK_URLS',
+ 'SOLANA_RPC_FALLBACKS',
+ 'SOLANA_RPC_LAST_RESORT_URLS',
+];
+
+let saved;
+
+beforeEach(() => {
+ saved = {};
+ for (const k of ENV_KEYS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+});
+
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+describe('endpoint priority — the public cluster default never outranks a real lane', () => {
+ it('does not pin the public mainnet URL at priority 1', () => {
+ process.env.HELIUS_API_KEY = 'k';
+ const list = solanaRpcEndpoints('mainnet', PUBLIC_MAINNET);
+ expect(list[0]).toBe('https://mainnet.helius-rpc.com/?api-key=k');
+ expect(list[0]).not.toBe(PUBLIC_MAINNET);
+ });
+
+ it('keeps the public endpoint in the chain at its natural position, never drops it', () => {
+ process.env.HELIUS_API_KEY = 'k';
+ const list = solanaRpcEndpoints('mainnet', PUBLIC_MAINNET);
+ expect(list).toContain(PUBLIC_MAINNET);
+ expect(list.indexOf(PUBLIC_MAINNET)).toBeGreaterThan(0);
+ });
+
+ it('applies the same rule on devnet', () => {
+ process.env.HELIUS_API_KEY = 'k';
+ const list = solanaRpcEndpoints('devnet', PUBLIC_DEVNET);
+ expect(list[0]).toBe('https://devnet.helius-rpc.com/?api-key=k');
+ expect(list).toContain(PUBLIC_DEVNET);
+ });
+
+ it('still pins a genuinely explicit endpoint first', () => {
+ process.env.HELIUS_API_KEY = 'k';
+ const list = solanaRpcEndpoints('mainnet', 'https://my.private.rpc/x');
+ expect(list[0]).toBe('https://my.private.rpc/x');
+ });
+
+ it('keeps a metered last-resort reserve dead last, behind every free lane', () => {
+ process.env.HELIUS_API_KEY = 'k';
+ process.env.SOLANA_RPC_LAST_RESORT_URLS = 'https://paid.quiknode.pro/abc';
+ const list = solanaRpcEndpoints('mainnet', PUBLIC_MAINNET);
+ expect(list[list.length - 1]).toBe('https://paid.quiknode.pro/abc');
+ expect(list.indexOf('https://paid.quiknode.pro/abc')).toBeGreaterThan(
+ list.indexOf(PUBLIC_MAINNET),
+ );
+ });
+
+ it('regression: a reserve also named as the primary is NOT preserved as a reserve', () => {
+ // The exact production misconfiguration. The same QuickNode URL sat in
+ // SOLANA_RPC_URL, QUICKNODE_RPC_URL and SOLANA_RPC_LAST_RESORT_URLS; dedupe
+ // keeps the FIRST occurrence, so the "insurance rung" absorbed 100% of
+ // traffic and burned its daily cap. Naming it as primary must win the pin
+ // (config says so), which is precisely why the config must not name it.
+ const qn = 'https://paid.quiknode.pro/abc';
+ process.env.HELIUS_API_KEY = 'k';
+ process.env.SOLANA_RPC_URL = qn;
+ process.env.SOLANA_RPC_LAST_RESORT_URLS = qn;
+ const list = solanaRpcEndpoints('mainnet');
+ expect(list[0]).toBe(qn);
+ expect(list.filter((u) => u === qn)).toHaveLength(1);
+ expect(list[list.length - 1]).not.toBe(qn);
+ });
+});
+
+describe('endpoint breaker — quota verdicts are shared fleet-wide', () => {
+ const url = 'https://quota-dead.example/rpc';
+
+ afterEach(async () => {
+ await cacheDel(COOLDOWN_CACHE_KEY).catch(() => {});
+ });
+
+ it('publishes a quota park so sibling instances can inherit it', async () => {
+ markEndpointCooldown(url, 429, 'daily request limit reached - upgrade your account');
+ // Publication is fire-and-forget; give the microtask queue a turn.
+ await new Promise((r) => setTimeout(r, 25));
+ const shared = await cacheGet(COOLDOWN_CACHE_KEY);
+ expect(shared).toBeTruthy();
+ expect(Number(shared[url])).toBeGreaterThan(Date.now());
+ });
+
+ it('picks the long quota window for a daily-cap signal, not the short 429 window', async () => {
+ const ms = markEndpointCooldown(url, 429, 'daily request limit reached');
+ expect(ms).toBeGreaterThanOrEqual(6 * 3_600_000);
+ });
+
+ it('hydrate() adopts a sibling verdict for an endpoint this instance never tried', async () => {
+ const unseen = 'https://never-tried-here.example/rpc';
+ expect(isEndpointCooling(unseen)).toBe(false);
+ await cacheSet(COOLDOWN_CACHE_KEY, { [unseen]: Date.now() + 3_600_000 }, 3600);
+ // Force the interval guard open so this call actually reads through.
+ await hydrateEndpointCooldowns(Date.now() + 10 * 60_000);
+ expect(isEndpointCooling(unseen)).toBe(true);
+ });
+
+ it('never lets a stale shared entry resurrect an expired cooldown', async () => {
+ const expired = 'https://already-recovered.example/rpc';
+ await cacheSet(COOLDOWN_CACHE_KEY, { [expired]: Date.now() - 1000 }, 3600);
+ await hydrateEndpointCooldowns(Date.now() + 20 * 60_000);
+ expect(isEndpointCooling(expired)).toBe(false);
+ });
+
+ it('a transient network blip stays local — it must not park the endpoint fleet-wide', async () => {
+ await cacheDel(COOLDOWN_CACHE_KEY).catch(() => {});
+ const blip = 'https://blippy.example/rpc';
+ // 503 → SERVER_COOLDOWN_MS (2m), below the publish threshold.
+ markEndpointCooldown(blip, 503, '');
+ await new Promise((r) => setTimeout(r, 25));
+ const shared = await cacheGet(COOLDOWN_CACHE_KEY);
+ expect(shared?.[blip]).toBeUndefined();
+ });
+});
diff --git a/workers/agent-sniper/auto-funder.js b/workers/agent-sniper/auto-funder.js
index d966530e7..d858235a6 100644
--- a/workers/agent-sniper/auto-funder.js
+++ b/workers/agent-sniper/auto-funder.js
@@ -24,6 +24,7 @@ import { log } from './log.js';
import { screenPush } from './screen-push.js';
import { cachedStrategies, getRealizedNetLamports, effectiveDailyLossLimitLamports } from './strategy-store.js';
import { checkDailyLoss } from '../../api/_lib/agent-trade-guards.js';
+import { autoFundMinSol, autoFundTargetSol } from '../../api/_lib/agent-funding-policy.js';
const POLL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
@@ -37,8 +38,11 @@ function num(name, def) {
// Floor + target + caps (SOL). Conservative defaults: keep ~0.05 SOL of dry
// powder per agent, refill when it falls under 0.02, never move more than 0.1 in
// one top-up or 1.0 total per UTC day across all agents.
-const MIN_SOL = Math.max(0, num('SNIPER_AUTO_FUND_MIN_SOL', 0.02));
-const TARGET_SOL = Math.max(MIN_SOL, num('SNIPER_AUTO_FUND_TARGET_SOL', 0.05));
+// Shared with the economy's idle-capital reclaim (api/_lib/agent-funding-policy.js).
+// Defining these here again is what let a reclaim floor drift under this target and
+// set the two crons ping-ponging the same SOL; the numbers now have one home.
+const MIN_SOL = autoFundMinSol();
+const TARGET_SOL = autoFundTargetSol();
const PER_TX_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_PER_TX_SOL', 0.1));
const DAILY_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_DAILY_SOL', 1.0));
// Per-agent daily refill ceiling — the guard the incident lacked. The fleet cap