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.

Bypass per-IP rate limit for internal forge-seed-cron calls

nirholasa32978b2fae2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8d19ca488..93b1d503f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Agents and items are now clearly separate — a teapot won't get a brain** — Every 3D model you create is now clearly one of two things: an Agent (a character that thinks, talks, remembers, and can go on-chain) or an Item (a 3D object or prop for scenes and trading). On the review screen the choice is spelled out with a short description of each, and we pick a smart default — models from the selfie, studio, and character tools start as agents, while anything you type into existence with prompt-to-3D starts as an item, so a teapot is never pre-loaded with a brain. Pick Item and the agent-only capabilities (voice, persona, on-chain identity) step aside for a gentle note — with a one-click "made a character? make it an agent" escape hatch if the guess was wrong. The Forge tagger now groups its labels the same way, calling out that only avatars and creatures can become agents. (`/create`) `[improvement]`
- **Agents can autonomously trade USDC-paired coins** — An agent's own wallet can now buy and sell USDC-paired coins on its own — not just SOL ones. Until now the autonomous lanes (an agent's buy/sell endpoints, scheduled buybacks, and creator-fee distributions) assumed every coin priced in SOL, so on a USDC coin they would have built a SOL trade the market refuses. Now the agent reads each coin's real pairing straight from the chain and trades in the matching currency: a USDC coin is bought and sold in USDC, with the agent's USDC account opened automatically and its balance checked up front so a trade fails clearly instead of reverting on-chain. Buybacks and fee distributions follow the same rule — they run in the coin's own currency, and if a coin's setup genuinely can't support a run, it's recorded with the reason rather than silently skipped. Every trade is now logged with the exact quote asset and amount, so prices and volumes stay correct for USDC and SOL coins alike. SOL coins behave exactly as before. (`/pump-dashboard`) `[feature]`
- **Autonomous coin buybacks and creator-fee distributions now run on schedule** — Coins launched through three.ws with autopilot enabled now have their buybacks and creator-fee distributions executed automatically on an hourly schedule, instead of waiting for a manual trigger. A new balance watchdog checks every Solana signer the platform uses to pay on-chain fees and alerts the team the moment one runs low, so autopilot never silently stalls for lack of gas. No action needed from coin owners — it just works in the background. `[improvement, infra]`
+- **Avatars come to life — animations now play on the avatar page** — Every avatar page now plays its built-in animation the moment it loads, so a rigged avatar stands, breathes, or performs its motion instead of freezing in a static pose. A new floating control sits over the 3D stage: a play/pause button, plus a clip switcher when an avatar carries more than one take so you can jump between them. Avatars with no embedded motion are unaffected — the control only appears when there's something to play. `[feature]`
- **Browse every community avatar from your dashboard** — The dashboard Avatars page now has a Community tab alongside My avatars. It shows every public 3D avatar the whole community has built — with live spinning previews, a running count and total views, search, tag filters, and infinite scroll. Open any one as a live page, remix it in the 3D studio, or copy its share link, embed snippet, or GLB URL in a click. (`/dashboard/avatars`) `[feature]`
- **Buy and sell USDC-paired coins straight from the trade widget** — The in-world trade widget now speaks both currencies. Open Buy on a coin and the widget reads its real pairing from the chain: a SOL coin asks for SOL exactly as before, while a USDC-paired coin denominates the amount in USDC, shows your wallet's USDC balance, and prices and settles the trade in USDC. A new Sell tab lets you sell a coin you hold back to its quote asset — pick 25%, 50%, or Max of your balance, see the live payout, and sign once; for USDC coins the payout account is opened for you automatically in the same transaction. Every state is handled: not enough USDC offers a one-tap Add-funds flow, a moved price explains your slippage, and a cancelled signature is quietly acknowledged. The whole flow is your own wallet, signed in your browser, with a Solscan link the moment it lands. (`/play`) `[feature]`
- **Chat never stalls on a down AI model — instant, quiet failover** — If you pick a specific AI model for the agent (say Claude) and our key for that provider is temporarily unavailable, chat now hands you an answer instantly from a healthy free model instead of pausing on the dead provider. Previously the app re-tried the unavailable provider on the very first attempt of every single message — adding a little delay each time and filling our logs with repeat warnings. Now a provider with a key or billing problem is set aside for a few minutes after the first failure and skipped up front, even when it was the one you explicitly chose, so the next message goes straight to a model that works. Free-first, always a working fallback. (`/chat`) `[improvement]`
@@ -19,6 +20,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Launchpad Studio: pick your avatar from your own agents and the gallery** — Building a launchpad in Launchpad Studio (three.ws/launchpad) no longer means hunting down a model URL by hand. The avatar picker now shows three sections: your own three.ws agents (when you're signed in), the platform avatar gallery with a Show more button to browse deeper, and a collapsed Or enter a URL field for power users who want to paste a custom .glb. Thumbnails load lazily, the selected avatar updates the live 3D preview instantly, and your choice is saved with the published page. (`/launchpad`) `[feature, improvement]`
- **Live coin status — price, market cap and graduation — now unified across the platform** — The launches feed, agent profile token panels, and the in-world agent coin card now share one live coin-status display, so every place that shows a coin reads the same numbers from the same source. Launch cards now stream the coin's real logo, USD price, market cap, a graduation progress ring and time since launch — not just market cap — with the orbital fingerprint as a placeholder until the logo loads. Agent profiles show a live price-and-graduation chip in the token panel and per-coin market caps in the launch history, and the agent home card's market readout is now consistent with the rest of the platform. Each card refreshes on its own and degrades gracefully to a Retry if pump.fun is briefly unreachable. (`/launches`) `[improvement]`
- **On-chain model validation for Solana agents** — Solana agents now get the same verifiable, on-chain glTF/model validation that EVM agents get from the ValidationRegistry — no contract to deploy. When you register an agent on Solana, the platform validator fetches your avatar's GLB, runs it through the same Khronos glTF validator behind the model checker, and records the pass/fail result as a signed on-chain attestation (an SPL Memo carrying a SHA-256 proof of the full report and a link to it). The result shows up as a 'model verified' badge on the agent passport, rides on the agent card, and is queryable at /api/agents/solana-validation. Anyone can independently recompute the proof hash from the same GLB to confirm the verdict, and you can re-validate on demand after updating your model. Re-attesting an identical report is idempotent, so no duplicate transactions. `[feature, security]`
+- **Pose any avatar — a full motion library on the avatar page** — Every avatar page has a new Pose tab. Open it and the avatar steps onto a live 3D stage you can orbit, with a searchable library of 100+ motions — idle, wave, dance, jump, flex, facepalm and more. Click one and it plays on the avatar instantly, even when the model itself ships no built-in animation: the clips retarget onto its skeleton in your browser. A speed slider and a reset-to-idle control round out the transport. Avatars without a standard humanoid rig get a clear message instead of a broken stage. `[feature]`
- **Pump dashboard alerts now run server-side — fire across devices even with the tab closed** — Alert rules moved from your browser to our servers, so they fire whether or not a dashboard tab is open and follow you across every device you sign in on. Build as many rules as you need: get notified when any token (or a specific mint, or one of your agents' coins) graduates to an AMM, when a coin's market cap rises above or falls below a price you set, when someone places a whale-sized buy, or when one of your agents launches a new coin. Each rule delivers however you want — an in-app notification, a signed webhook POST to your own server, and Telegram — with each channel handled independently so one failing never blocks the others. Per-rule cooldowns and de-duplication prevent alert storms, the dashboard shows when a rule last fired and surfaces any delivery failures, and existing graduation alerts were migrated over automatically. (`/pump-dashboard`) `[feature]`
- **Pump Live: real token art, live market caps, and a feed that heals itself** — The Pump Live showcase (three.ws/pump-live) — where a 3D agent reacts to brand-new pump.fun launches in real time — is now fully wired. Every new coin appears with its real artwork and a live USD market cap, instead of a generic avatar and a rough estimate. A new stats bar tracks tokens launched, initial-buy volume, and time since the last launch as events stream in. Before the first launch arrives you get a tidy loading skeleton instead of a blank panel; if the upstream stream drops, the feed reconnects on its own with a backoff and, if it stays down, shows a clear message with a Retry button. Token images are resolved and served through three.ws, so they always load cleanly and never trip browser security errors, and the page keeps streaming even on devices that can't run the 3D view. (`/pump-live`) `[improvement, fix]`
- **Pump Visualizer’s Trending view fixed — spheres now sized by real market cap** — The Trending mode of the 3D Pump Visualizer (three.ws/pump-visualizer) now renders correctly: every coin appears as a sphere sized by its real USD market cap, textured with its actual logo, with a full detail panel showing market cap, all-time-high, replies, age, and socials. Previously Trending failed to load because the market data it relied on wasn’t reaching the scene. Click a sphere to inspect it, or double-click to open the full 3D coin page. The live Firehose and Migrations modes are unchanged. (`/pump-visualizer`) `[fix, improvement]`
@@ -28,6 +30,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Strategy Lab now catches broken trading strategies before they run** — Validation in the Strategy Lab (three.ws/strategy-lab) went from a basic syntax check to a real soundness check, so a strategy can't quietly pass review and then misbehave with live funds. It now flags the mistakes that used to slip through: a misspelled metric that silently never matches, a threshold that can never be true (like a percentage above 100), filters that contradict each other so the strategy would never buy, a position rule placed where no position exists yet, a per-trade size larger than the session budget, and later exit rules that an earlier rule always triggers first. When you point a strategy at specific coins, it confirms each one actually exists and warns if a SOL-denominated strategy targets a USDC-paired coin. Problems are shown inline, field by field, with a plain-language reason and exactly where to fix them — and the same checks now guard Backtest and Run, so what validates is what executes. (`/strategy-lab`) `[improvement]`
- **The Forge always returns a model — the default never dead-ends** — Typing a prompt into the Forge on the default Standard setting now always produces a 3D model, even when our paid reconstruction provider is throttled or over its quota. Previously a busy upstream could leave the default flow stuck on a "generator is busy, try again" message that never cleared. Now, if the paid engine is unavailable, a text prompt transparently falls back to the free NVIDIA lane and still hands you a finished model — and the result clearly shows which engine produced it, so the change is never hidden. Free-first, always a working fallback. (`/forge`) `[fix]`
- **The Forge grows itself — a new avatar or accessory every minute, tied to real accounts** — A new auto-generation system creates a fresh 3D avatar or accessory every minute using the free NVIDIA lane and adds it to the community gallery. Each model is attributed to a new user account with an OG single-word username — wolf, raven, iron, frost — so the gallery reads like a real creator community. The system cycles through 200+ curated prompts covering fantasy warriors, sci-fi soldiers, mythological creatures, and matching weapons, armor, and accessories, cycling through the full library before repeating. Every model is a permanent GLB stored in our own CDN. (`/forge`) `[feature]`
+- **The IRL page loads again** — Opening three.ws/irl returned a Not Found error even though the page was fully built and linked from the navigation. The page wasn't mapped in our routing rules, so the server never served it. We added the route — the IRL experience (walk a 3D avatar in your real space with camera passthrough, an on-screen joystick, and tap-to-place objects) now opens directly from the link in the menu. (`/irl`) `[fix]`
- **The pump.fun graduations feed stays fresh around the clock** — The recent-graduations feed and the graduation data behind pump.fun signals and MCP tools now refresh continuously in the background, instead of only updating while someone had the live feed open. A new scheduled job listens to the real pump.fun migration stream and records graduations as they happen, so the feed shows up-to-date tokens even after quiet periods. Graduation data is also served straight from our own live records, so it never silently falls back to an empty list. `[infra, improvement]`
- **The site footer and top pages are now polished on phones** — On mobile the footer's link columns ran off the right edge and got cut off — the contract address and legal links were unreachable — because an old style rule for the 3D viewer's corner credit was hijacking the main footer's layout. The footer now stacks into clean, tappable columns on every page. We also did a mobile pass across the most-used pages — Home, Discover, Create, Forge, Marketplace, Gallery, and Pay — eliminating sideways scrolling, enlarging tap targets to a comfortable size, and stopping form fields from zooming the page when you tap them. `[fix, improvement]`
- **The top navigation is back on every page** — The site header was being clipped to a sliver on most pages — the menu, search, and account controls were cut off and the dropdowns wouldn't open. An old style rule meant for the standalone 3D viewer's compact toolbar was leaking onto the shared navigation, forcing it to a fixed height and hiding everything below it. The viewer rule is now scoped to only the viewer, so the full navigation renders at its natural height across the whole site. `[fix]`
diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.js
index 34c96b6b6..1feab3abc 100644
--- a/api/cron/forge-seed-cron.js
+++ b/api/cron/forge-seed-cron.js
@@ -55,6 +55,39 @@ async function fetchJson(url, options = {}) {
return { status: res.status, body };
}
+// Insert a public avatar row for a finished seed creation, attributed to the
+// synthetic user. Reads the stored GLB straight from forge_creations and is
+// idempotent (`on conflict do nothing`) so a re-poll never double-inserts.
+// Bypasses plan quota — this is platform-seeded content, not a user upload.
+async function insertSeedAvatar({ userId, prompt, modelCategory, creationId }) {
+ if (!creationId) return;
+ await sql`
+ insert into avatars
+ (owner_id, slug, name, description, storage_key, size_bytes,
+ content_type, source, source_meta, visibility, tags,
+ model_category, created_at, updated_at)
+ select
+ ${userId},
+ ${toSlug(prompt)},
+ ${toTitle(prompt)},
+ ${'AI-generated ' + modelCategory + ' — forged on three.ws'},
+ fc.glb_key,
+ coalesce(fc.size_bytes, 0),
+ 'model/gltf-binary',
+ 'forge',
+ ${JSON.stringify({ forge_creation_id: creationId, prompt, seed: true })}::jsonb,
+ 'public',
+ array[${modelCategory}]::text[],
+ ${modelCategory},
+ now(), now()
+ from forge_creations fc
+ where fc.id = ${creationId}
+ and fc.glb_key is not null
+ and fc.status = 'done'
+ on conflict do nothing
+ `;
+}
+
// ── Phase 1: poll pending jobs ────────────────────────────────────────────────
async function pollPending(origin) {
@@ -71,43 +104,20 @@ async function pollPending(origin) {
const results = [];
await Promise.all(rows.map(async (job) => {
try {
+ const cronSecret = process.env.CRON_SECRET || env.CRON_SECRET || '';
const poll = await fetchJson(
`${origin}/api/forge?job=${encodeURIComponent(job.job_id)}`,
- { headers: { 'x-forge-client': job.raw_client_id } },
+ { headers: { 'x-forge-client': job.raw_client_id, 'x-forge-seed': cronSecret } },
);
if (poll.body?.status === 'done' && poll.body.glb_url) {
const creationId = poll.body.creation_id ?? null;
-
- // Insert directly into avatars (bypasses plan quota — this is
- // platform-seeded content, not a user upload against their limit).
- if (creationId) {
- await sql`
- insert into avatars
- (owner_id, slug, name, description, storage_key, size_bytes,
- content_type, source, source_meta, visibility, tags,
- model_category, created_at, updated_at)
- select
- ${job.user_id},
- ${toSlug(job.prompt)},
- ${toTitle(job.prompt)},
- ${'AI-generated ' + job.model_category + ' — forged on three.ws'},
- fc.glb_key,
- coalesce(fc.size_bytes, 0),
- 'model/gltf-binary',
- 'forge',
- ${JSON.stringify({ forge_creation_id: creationId, prompt: job.prompt, seed: true })}::jsonb,
- 'public',
- array[${job.model_category}]::text[],
- ${job.model_category},
- now(), now()
- from forge_creations fc
- where fc.id = ${creationId}
- and fc.glb_key is not null
- and fc.status = 'done'
- on conflict do nothing
- `;
- }
+ await insertSeedAvatar({
+ userId: job.user_id,
+ prompt: job.prompt,
+ modelCategory: job.model_category,
+ creationId,
+ });
await sql`
update forge_seed_jobs
@@ -182,16 +192,18 @@ async function startNextJob(origin) {
return { skipped: true, reason: 'user insert conflict — will retry next tick' };
}
+ const cronSecret = process.env.CRON_SECRET || env.CRON_SECRET || '';
const submit = await fetchJson(`${origin}/api/forge`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-forge-client': rawClientId,
+ 'x-forge-seed': cronSecret,
},
body: JSON.stringify({ prompt: chosen.prompt, tier: 'draft', path: 'image' }),
});
- if (submit.status !== 200 || !submit.body?.job_id) {
+ if (submit.status !== 200) {
await sql`delete from users where id = ${user.id}`.catch(() => {});
return {
ok: false,
@@ -199,18 +211,58 @@ async function startNextJob(origin) {
};
}
- await sql`
- insert into forge_seed_jobs (user_id, raw_client_id, job_id, prompt, model_category)
- values (${user.id}, ${rawClientId}, ${submit.body.job_id}, ${chosen.prompt}, ${chosen.category})
- `;
+ const creationId = submit.body?.creation_id ?? null;
+
+ // The free NVIDIA draft lane finishes inline (~13–22 s) and returns the
+ // finished model in the submit response with job_id:null — there is nothing
+ // to poll. Attribute it to the synthetic user right now.
+ if (submit.body?.status === 'done' && submit.body?.glb_url) {
+ await insertSeedAvatar({
+ userId: user.id,
+ prompt: chosen.prompt,
+ modelCategory: chosen.category,
+ creationId,
+ });
+ await sql`
+ insert into forge_seed_jobs
+ (user_id, raw_client_id, job_id, prompt, model_category,
+ status, creation_id, glb_url, finished_at)
+ values (${user.id}, ${rawClientId}, ${submit.body.job_id || 'sync-' + (creationId || randomUUID())},
+ ${chosen.prompt}, ${chosen.category}, 'done', ${creationId}, ${submit.body.glb_url}, now())
+ `;
+ return {
+ ok: true,
+ sync: true,
+ creation_id: creationId,
+ glb_url: submit.body.glb_url,
+ prompt: chosen.prompt,
+ category: chosen.category,
+ username,
+ user_id: user.id,
+ };
+ }
+
+ // Otherwise the lane is asynchronous — record the job so the next tick polls it.
+ if (submit.body?.job_id) {
+ await sql`
+ insert into forge_seed_jobs (user_id, raw_client_id, job_id, prompt, model_category)
+ values (${user.id}, ${rawClientId}, ${submit.body.job_id}, ${chosen.prompt}, ${chosen.category})
+ `;
+ return {
+ ok: true,
+ job_id: submit.body.job_id,
+ prompt: chosen.prompt,
+ category: chosen.category,
+ username,
+ user_id: user.id,
+ };
+ }
+ // Neither a finished model nor a poll token — a genuine failure.
+ await sql`delete from users where id = ${user.id}`.catch(() => {});
return {
- ok: true,
- job_id: submit.body.job_id,
- prompt: chosen.prompt,
- category: chosen.category,
- username,
- user_id: user.id,
+ ok: false,
+ reason: `forge submit returned no job_id and status=${submit.body?.status || 'unknown'}`,
};
}
diff --git a/api/forge.js b/api/forge.js
index 4effb5304..d6e890f62 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -59,6 +59,18 @@ import {
markFailed,
findByJob,
} from './_lib/forge-store.js';
+import { constantTimeEquals } from './_lib/crypto.js';
+import { env as _env } from './_lib/env.js';
+
+// Returns true when the request carries the internal cron seed token, meaning
+// the call comes from forge-seed-cron (server→server). These bypass the per-IP
+// rate limit — they're metered by MAX_CONCURRENT_PENDING in the cron instead.
+function isInternalSeedRequest(req) {
+ const token = req.headers['x-forge-seed'];
+ if (!token) return false;
+ const secret = _env.CRON_SECRET;
+ return !!secret && constantTimeEquals(token, secret);
+}
// The free NVIDIA NIM (TRELLIS) provider is loaded lazily and dynamically: it
// ships in T1.1, so importing it statically would couple this whole endpoint to
@@ -146,6 +158,21 @@ function unconfigured(res) {
});
}
+// Whether a thrown provider error means the upstream itself is unavailable —
+// throttled, over-quota, unreachable, or 5xx — as opposed to a client/config
+// fault. Both never-dead-end fallbacks (image→3D to the self-hosted Hunyuan3D
+// worker, text→3D to the free NVIDIA NIM lane) degrade on exactly these so a
+// generation rides out a transient upstream outage instead of failing the user.
+function isUpstreamUnavailable(err) {
+ return (
+ err?.code === 'rate_limited' ||
+ err?.providerStatus === 429 ||
+ err?.code === 'provider_error' ||
+ err?.code === 'provider_unreachable' ||
+ (typeof err?.providerStatus === 'number' && err.providerStatus >= 500)
+ );
+}
+
// Free NVIDIA NIM TRELLIS text→3D lane, extracted so it serves two callers:
// 1. the draft default (backendId === 'nvidia'), and
// 2. the never-dead-end fallback the paid image-intermediate TRELLIS lane
@@ -289,9 +316,11 @@ async function startJob(req, res) {
}
const isFreeLane = BACKENDS[backendId]?.free === true;
- const rl = isFreeLane ? await limits.mcp3dGenerateFree(ip) : await limits.mcp3dGenerate(ip);
- if (!rl.success) {
- return rateLimited(res, rl, 'Generation limit reached. Try again shortly.');
+ if (!isInternalSeedRequest(req)) {
+ const rl = isFreeLane ? await limits.mcp3dGenerateFree(ip) : await limits.mcp3dGenerate(ip);
+ if (!rl.success) {
+ return rateLimited(res, rl, 'Generation limit reached. Try again shortly.');
+ }
}
if (isImageMode) {
@@ -680,11 +709,46 @@ async function startJob(req, res) {
reconstructParams.path = path;
}
- const job = await provider.submit({
- mode: 'reconstruct',
- sourceUrl: referenceImageUrl,
- params: reconstructParams,
- });
+ let job;
+ try {
+ job = await provider.submit({
+ mode: 'reconstruct',
+ sourceUrl: referenceImageUrl,
+ params: reconstructParams,
+ });
+ } catch (submitErr) {
+ // Image→3D free fallback: when the standing platform TRELLIS lane
+ // (Replicate) is over-quota or unreachable, retry on the self-hosted
+ // Hunyuan3D Cloud Run worker if it's wired — so a photo upload never
+ // dead-ends. The text→3D fallback (free NVIDIA NIM, in the outer catch)
+ // can't take photos, so image mode would otherwise have no escape. Scoped
+ // to the default trellis lane: a text prompt prefers the genuinely-free
+ // NVIDIA lane over paid GPU compute, and an explicitly chosen Hunyuan3D /
+ // BYOK backend that fails surfaces its own error. Provenance reports
+ // backend:hunyuan3d so the downgrade stays visible.
+ const hunyuanUrl = process.env.GCP_HUNYUAN3D_URL;
+ const canFallbackToHunyuan =
+ isImageMode &&
+ backendId === 'trellis' &&
+ hunyuanUrl &&
+ process.env.GCP_RECONSTRUCTION_KEY &&
+ isUpstreamUnavailable(submitErr);
+ if (!canFallbackToHunyuan) throw submitErr;
+ console.warn(
+ `[forge] platform TRELLIS lane unavailable (${submitErr?.providerStatus || submitErr?.code}); degrading image→3D to self-hosted Hunyuan3D`,
+ );
+ backendId = 'hunyuan3d';
+ provider = createGcpProvider({ reconstructUrl: hunyuanUrl });
+ // Hunyuan3D is poly-aware — supply the tier budget the TRELLIS params omit.
+ reconstructParams.target_polycount = tier.polycount;
+ reconstructParams.tier = tier.id;
+ reconstructParams.path = path;
+ job = await provider.submit({
+ mode: 'reconstruct',
+ sourceUrl: referenceImageUrl,
+ params: reconstructParams,
+ });
+ }
// How the job was actually conditioned. The provider reports back which
// backend handled it and how many views it fused — these can differ from
@@ -767,13 +831,7 @@ async function startJob(req, res) {
// reconstruct fallback (NVCF is text-only), so they fall through to the
// designed states below. `nvidiaTried` guards against re-running a lane that
// already failed this request (the draft nvidia→trellis→nvidia loop).
- const upstreamUnavailable =
- err?.code === 'rate_limited' ||
- err?.providerStatus === 429 ||
- err?.code === 'provider_error' ||
- err?.code === 'provider_unreachable' ||
- (typeof err?.providerStatus === 'number' && err.providerStatus >= 500);
- if (upstreamUnavailable && !isImageMode && !nvidiaTried && prompt) {
+ if (isUpstreamUnavailable(err) && !isImageMode && !nvidiaTried && prompt) {
nvidiaTried = true;
console.warn(
`[forge] paid TRELLIS lane unavailable (${err?.providerStatus || err?.code}); degrading text→3D to free NVIDIA NIM`,
diff --git a/api/sniper/leaderboard.js b/api/sniper/leaderboard.js
new file mode 100644
index 000000000..8b12a3ec6
--- /dev/null
+++ b/api/sniper/leaderboard.js
@@ -0,0 +1,125 @@
+/**
+ * Agent Sniper — public leaderboard + recent trades.
+ *
+ * GET /api/sniper/leaderboard?network=mainnet
+ *
+ * Ranks agents by realized P&L from agent_sniper_positions and returns the most
+ * recent closed trades + currently-open positions for the /play arena's initial
+ * render. Public + IP rate-limited — the on-chain tx signatures are the proof,
+ * so the whole point is that anyone can watch.
+ */
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+function solscan(sig, network) {
+ if (!sig || sig === 'SIMULATED') return null;
+ return network === 'devnet'
+ ? `https://solscan.io/tx/${sig}?cluster=devnet`
+ : `https://solscan.io/tx/${sig}`;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+
+ const [board, recent, open] = await Promise.all([
+ sql`
+ select p.agent_id, p.wallet,
+ a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image,
+ count(*) filter (where p.status = 'closed') as closed,
+ count(*) filter (where p.status in ('open','opening','closing')) as open_positions,
+ count(*) filter (where p.exit_reason = 'take_profit') as wins,
+ coalesce(sum(p.realized_pnl_lamports),0)::text as realized_pnl_lamports,
+ coalesce(avg(p.realized_pnl_pct) filter (where p.status = 'closed'),0)::float as avg_pnl_pct,
+ max(p.realized_pnl_pct) filter (where p.status = 'closed')::float as best_pnl_pct
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id
+ where p.network = ${network}
+ group by p.agent_id, p.wallet, a.name, a.avatar_url, a.profile_image_url
+ order by sum(p.realized_pnl_lamports) desc nulls last
+ limit 100
+ `,
+ sql`
+ select p.id, p.agent_id, a.name as agent_name, p.mint, p.symbol, p.name,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.realized_pnl_lamports,
+ p.realized_pnl_pct, p.exit_reason, p.buy_sig, p.sell_sig, p.closed_at
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id
+ where p.network = ${network} and p.status = 'closed'
+ order by p.closed_at desc
+ limit 30
+ `,
+ sql`
+ select p.id, p.agent_id, a.name as agent_name, p.mint, p.symbol, p.name,
+ p.entry_quote_lamports, p.last_value_lamports, p.peak_value_lamports,
+ p.buy_sig, p.opened_at
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id
+ where p.network = ${network} and p.status = 'open'
+ order by p.opened_at desc
+ limit 50
+ `,
+ ]);
+
+ const leaderboard = board.map((r, i) => ({
+ rank: i + 1,
+ agent_id: r.agent_id,
+ agent_name: r.agent_name,
+ image: r.agent_image || r.agent_avatar || null,
+ wallet: r.wallet,
+ closed: Number(r.closed),
+ open_positions: Number(r.open_positions),
+ wins: Number(r.wins),
+ realized_pnl_lamports: r.realized_pnl_lamports,
+ realized_pnl_sol: Number(BigInt(r.realized_pnl_lamports)) / 1e9,
+ avg_pnl_pct: r.avg_pnl_pct != null ? Number(r.avg_pnl_pct) : 0,
+ best_pnl_pct: r.best_pnl_pct != null ? Number(r.best_pnl_pct) : null,
+ }));
+
+ const trades = recent.map((t) => ({
+ id: t.id,
+ agent_id: t.agent_id,
+ agent_name: t.agent_name,
+ mint: t.mint,
+ symbol: t.symbol,
+ name: t.name,
+ entry_sol: t.entry_quote_lamports != null ? Number(BigInt(t.entry_quote_lamports)) / 1e9 : null,
+ exit_sol: t.exit_quote_lamports != null ? Number(BigInt(t.exit_quote_lamports)) / 1e9 : null,
+ pnl_sol: t.realized_pnl_lamports != null ? Number(BigInt(t.realized_pnl_lamports)) / 1e9 : null,
+ pnl_pct: t.realized_pnl_pct != null ? Number(t.realized_pnl_pct) : null,
+ exit_reason: t.exit_reason,
+ buy_url: solscan(t.buy_sig, network),
+ sell_url: solscan(t.sell_sig, network),
+ at: t.closed_at,
+ }));
+
+ const positions = open.map((o) => {
+ const entry = o.entry_quote_lamports != null ? Number(BigInt(o.entry_quote_lamports)) : 0;
+ const last = o.last_value_lamports != null ? Number(BigInt(o.last_value_lamports)) : entry;
+ return {
+ id: o.id,
+ agent_id: o.agent_id,
+ agent_name: o.agent_name,
+ mint: o.mint,
+ symbol: o.symbol,
+ name: o.name,
+ entry_sol: entry / 1e9,
+ current_sol: last / 1e9,
+ unrealized_pct: entry > 0 ? ((last - entry) / entry) * 100 : 0,
+ buy_url: solscan(o.buy_sig, network),
+ at: o.opened_at,
+ };
+ });
+
+ return json(res, 200, { network, leaderboard, trades, positions, t: Date.now() });
+});
diff --git a/api/sniper/strategy.js b/api/sniper/strategy.js
new file mode 100644
index 000000000..7b4467e0e
--- /dev/null
+++ b/api/sniper/strategy.js
@@ -0,0 +1,289 @@
+/**
+ * Agent Sniper — strategy (arm/config) API.
+ *
+ * GET /api/sniper/strategy → the caller's sniper strategies + each
+ * agent's live position summary.
+ * POST /api/sniper/strategy → upsert/arm the strategy for one owned agent.
+ *
+ * Strategy rows (agent_sniper_strategies) are read by the agent-sniper worker
+ * (workers/agent-sniper). Arming is an explicit, owner-only opt-in: the agent
+ * trades from its OWN wallet with real funds, so a strategy is disabled until
+ * the owner sets a budget, a per-trade size, and confirms the risk.
+ *
+ * Auth: session cookie OR bearer token. Every read/write is scoped to agents
+ * the caller owns (agent_identities.user_id).
+ */
+
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { z } from 'zod';
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+const lamports = z.union([z.string(), z.number()]);
+const optPct = z.union([z.string(), z.number()]).nullable().optional();
+const optInt = z.union([z.string(), z.number()]).nullable().optional();
+
+const STRATEGY_SCHEMA = z.object({
+ agent_id: z.string().uuid(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ enabled: z.boolean().optional(),
+ kill_switch: z.boolean().optional(),
+ // sizing
+ daily_budget_lamports: lamports.optional(),
+ per_trade_lamports: lamports.optional(),
+ max_concurrent_positions: z.union([z.string(), z.number()]).optional(),
+ slippage_bps: z.union([z.string(), z.number()]).optional(),
+ max_price_impact_pct: z.union([z.string(), z.number()]).optional(),
+ // entry filters (null clears)
+ min_market_cap_usd: optPct,
+ max_market_cap_usd: optPct,
+ min_creator_graduated: optInt,
+ max_creator_launches: optInt,
+ require_socials: z.boolean().optional(),
+ require_sol_quote: z.boolean().optional(),
+ // exits
+ take_profit_pct: optPct,
+ stop_loss_pct: z.union([z.string(), z.number()]).optional(),
+ trailing_stop_pct: optPct,
+ max_hold_seconds: z.union([z.string(), z.number()]).optional(),
+});
+
+const atomicStr = (v, fallback = '0') => {
+ if (v == null) return fallback;
+ let s = String(v).trim();
+ if (!/^\d+$/.test(s)) {
+ const n = Number(s);
+ if (!Number.isFinite(n) || n < 0) return fallback;
+ s = String(Math.floor(n));
+ }
+ return s;
+};
+const intOrNull = (v) => {
+ if (v == null || v === '') return null;
+ const n = Math.floor(Number(v));
+ return Number.isFinite(n) ? n : null;
+};
+const numOrNull = (v) => {
+ if (v == null || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+};
+const clampInt = (v, min, max, def) => {
+ const n = Math.floor(Number(v));
+ if (!Number.isFinite(n)) return def;
+ return Math.min(max, Math.max(min, n));
+};
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in to manage the sniper');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (req.method === 'POST') return upsertStrategy(req, res, userId);
+ return listStrategies(req, res, userId);
+});
+
+// ── GET — strategies + live position summary ─────────────────────────────────
+
+async function listStrategies(req, res, userId) {
+ const rows = await sql`
+ select s.*, a.name as agent_name,
+ a.avatar_url as agent_avatar, a.profile_image_url as agent_image
+ from agent_sniper_strategies s
+ join agent_identities a on a.id = s.agent_id
+ where s.user_id = ${userId}
+ order by s.updated_at desc
+ limit 100
+ `;
+
+ const summary = rows.length
+ ? await sql`
+ select agent_id,
+ count(*) filter (where status in ('opening','open','closing')) as open_positions,
+ count(*) filter (where status = 'closed') as closed_positions,
+ coalesce(sum(realized_pnl_lamports),0)::text as realized_pnl_lamports,
+ count(*) filter (where exit_reason = 'take_profit') as wins
+ from agent_sniper_positions
+ where user_id = ${userId}
+ group by agent_id
+ `
+ : [];
+ const byAgent = new Map(summary.map((s) => [s.agent_id, s]));
+
+ const strategies = rows.map((s) => {
+ const sum = byAgent.get(s.agent_id);
+ return {
+ agent_id: s.agent_id,
+ agent_name: s.agent_name,
+ image: s.agent_image || s.agent_avatar || null,
+ network: s.network,
+ enabled: s.enabled,
+ kill_switch: s.kill_switch,
+ daily_budget_lamports: String(s.daily_budget_lamports),
+ per_trade_lamports: String(s.per_trade_lamports),
+ max_concurrent_positions: s.max_concurrent_positions,
+ slippage_bps: s.slippage_bps,
+ max_price_impact_pct: Number(s.max_price_impact_pct),
+ min_market_cap_usd: s.min_market_cap_usd != null ? Number(s.min_market_cap_usd) : null,
+ max_market_cap_usd: s.max_market_cap_usd != null ? Number(s.max_market_cap_usd) : null,
+ min_creator_graduated: s.min_creator_graduated,
+ max_creator_launches: s.max_creator_launches,
+ require_socials: s.require_socials,
+ require_sol_quote: s.require_sol_quote,
+ take_profit_pct: s.take_profit_pct != null ? Number(s.take_profit_pct) : null,
+ stop_loss_pct: Number(s.stop_loss_pct),
+ trailing_stop_pct: s.trailing_stop_pct != null ? Number(s.trailing_stop_pct) : null,
+ max_hold_seconds: s.max_hold_seconds,
+ summary: {
+ open_positions: sum ? Number(sum.open_positions) : 0,
+ closed_positions: sum ? Number(sum.closed_positions) : 0,
+ realized_pnl_lamports: sum ? sum.realized_pnl_lamports : '0',
+ wins: sum ? Number(sum.wins) : 0,
+ },
+ };
+ });
+
+ return json(res, 200, { strategies });
+}
+
+// ── POST — upsert/arm strategy ───────────────────────────────────────────────
+
+async function upsertStrategy(req, res, userId) {
+ const body = await readJson(req);
+ const parsed = STRATEGY_SCHEMA.safeParse(body);
+ if (!parsed.success) {
+ return error(res, 400, 'bad_request', parsed.error.issues[0]?.message || 'invalid strategy');
+ }
+ const p = parsed.data;
+
+ // Ownership: the agent must belong to the caller.
+ const [agent] = await sql`
+ select id from agent_identities
+ where id = ${p.agent_id} and user_id = ${userId} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found or not owned by you');
+
+ const [existing] = await sql`
+ select * from agent_sniper_strategies
+ where agent_id = ${p.agent_id} and network = ${p.network} limit 1
+ `;
+ const cur = existing || {
+ enabled: false, kill_switch: false,
+ daily_budget_lamports: '0', per_trade_lamports: '0',
+ max_concurrent_positions: 1, slippage_bps: 500, max_price_impact_pct: 10,
+ min_market_cap_usd: null, max_market_cap_usd: null,
+ min_creator_graduated: null, max_creator_launches: null,
+ require_socials: false, require_sol_quote: true,
+ take_profit_pct: null, stop_loss_pct: 30, trailing_stop_pct: null,
+ max_hold_seconds: 1800,
+ };
+
+ const next = {
+ enabled: p.enabled ?? cur.enabled,
+ kill_switch: p.kill_switch ?? cur.kill_switch,
+ daily_budget_lamports: p.daily_budget_lamports != null ? atomicStr(p.daily_budget_lamports) : String(cur.daily_budget_lamports),
+ per_trade_lamports: p.per_trade_lamports != null ? atomicStr(p.per_trade_lamports) : String(cur.per_trade_lamports),
+ max_concurrent_positions: p.max_concurrent_positions != null ? clampInt(p.max_concurrent_positions, 1, 50, 1) : cur.max_concurrent_positions,
+ slippage_bps: p.slippage_bps != null ? clampInt(p.slippage_bps, 0, 5000, 500) : cur.slippage_bps,
+ max_price_impact_pct: p.max_price_impact_pct != null ? Math.min(100, Math.max(0, Number(p.max_price_impact_pct))) : Number(cur.max_price_impact_pct),
+ min_market_cap_usd: 'min_market_cap_usd' in p ? numOrNull(p.min_market_cap_usd) : (cur.min_market_cap_usd != null ? Number(cur.min_market_cap_usd) : null),
+ max_market_cap_usd: 'max_market_cap_usd' in p ? numOrNull(p.max_market_cap_usd) : (cur.max_market_cap_usd != null ? Number(cur.max_market_cap_usd) : null),
+ min_creator_graduated: 'min_creator_graduated' in p ? intOrNull(p.min_creator_graduated) : cur.min_creator_graduated,
+ max_creator_launches: 'max_creator_launches' in p ? intOrNull(p.max_creator_launches) : cur.max_creator_launches,
+ require_socials: p.require_socials ?? cur.require_socials,
+ require_sol_quote: p.require_sol_quote ?? cur.require_sol_quote,
+ take_profit_pct: 'take_profit_pct' in p ? numOrNull(p.take_profit_pct) : (cur.take_profit_pct != null ? Number(cur.take_profit_pct) : null),
+ stop_loss_pct: p.stop_loss_pct != null ? Number(p.stop_loss_pct) : Number(cur.stop_loss_pct),
+ trailing_stop_pct: 'trailing_stop_pct' in p ? numOrNull(p.trailing_stop_pct) : (cur.trailing_stop_pct != null ? Number(cur.trailing_stop_pct) : null),
+ max_hold_seconds: p.max_hold_seconds != null ? clampInt(p.max_hold_seconds, 30, 86400, 1800) : cur.max_hold_seconds,
+ };
+
+ // Mandatory stop-loss — never let the DB constraint be the first line of defense.
+ if (!(next.stop_loss_pct > 0)) {
+ return error(res, 400, 'bad_request', 'stop_loss_pct must be greater than 0');
+ }
+ // A live, armed strategy with no real money makes no sense; guide the owner.
+ if (next.enabled && (BigInt(next.daily_budget_lamports) <= 0n || BigInt(next.per_trade_lamports) <= 0n)) {
+ return error(res, 400, 'bad_request', 'set a daily_budget_lamports and per_trade_lamports before enabling');
+ }
+ if (next.enabled && BigInt(next.per_trade_lamports) > BigInt(next.daily_budget_lamports)) {
+ return error(res, 400, 'bad_request', 'per_trade_lamports cannot exceed daily_budget_lamports');
+ }
+
+ const [row] = await sql`
+ insert into agent_sniper_strategies
+ (agent_id, user_id, network, enabled, kill_switch,
+ daily_budget_lamports, per_trade_lamports, max_concurrent_positions,
+ slippage_bps, max_price_impact_pct,
+ min_market_cap_usd, max_market_cap_usd, min_creator_graduated, max_creator_launches,
+ require_socials, require_sol_quote,
+ take_profit_pct, stop_loss_pct, trailing_stop_pct, max_hold_seconds, updated_at)
+ values
+ (${p.agent_id}, ${userId}, ${p.network}, ${next.enabled}, ${next.kill_switch},
+ ${next.daily_budget_lamports}, ${next.per_trade_lamports}, ${next.max_concurrent_positions},
+ ${next.slippage_bps}, ${next.max_price_impact_pct},
+ ${next.min_market_cap_usd}, ${next.max_market_cap_usd}, ${next.min_creator_graduated}, ${next.max_creator_launches},
+ ${next.require_socials}, ${next.require_sol_quote},
+ ${next.take_profit_pct}, ${next.stop_loss_pct}, ${next.trailing_stop_pct}, ${next.max_hold_seconds}, now())
+ on conflict (agent_id, network) do update set
+ enabled = excluded.enabled,
+ kill_switch = excluded.kill_switch,
+ daily_budget_lamports = excluded.daily_budget_lamports,
+ per_trade_lamports = excluded.per_trade_lamports,
+ max_concurrent_positions = excluded.max_concurrent_positions,
+ slippage_bps = excluded.slippage_bps,
+ max_price_impact_pct = excluded.max_price_impact_pct,
+ min_market_cap_usd = excluded.min_market_cap_usd,
+ max_market_cap_usd = excluded.max_market_cap_usd,
+ min_creator_graduated = excluded.min_creator_graduated,
+ max_creator_launches = excluded.max_creator_launches,
+ require_socials = excluded.require_socials,
+ require_sol_quote = excluded.require_sol_quote,
+ take_profit_pct = excluded.take_profit_pct,
+ stop_loss_pct = excluded.stop_loss_pct,
+ trailing_stop_pct = excluded.trailing_stop_pct,
+ max_hold_seconds = excluded.max_hold_seconds,
+ updated_at = now()
+ returning *
+ `;
+
+ return json(res, 200, {
+ ok: true,
+ strategy: {
+ agent_id: row.agent_id,
+ network: row.network,
+ enabled: row.enabled,
+ kill_switch: row.kill_switch,
+ daily_budget_lamports: String(row.daily_budget_lamports),
+ per_trade_lamports: String(row.per_trade_lamports),
+ max_concurrent_positions: row.max_concurrent_positions,
+ slippage_bps: row.slippage_bps,
+ max_price_impact_pct: Number(row.max_price_impact_pct),
+ min_market_cap_usd: row.min_market_cap_usd != null ? Number(row.min_market_cap_usd) : null,
+ max_market_cap_usd: row.max_market_cap_usd != null ? Number(row.max_market_cap_usd) : null,
+ min_creator_graduated: row.min_creator_graduated,
+ max_creator_launches: row.max_creator_launches,
+ require_socials: row.require_socials,
+ require_sol_quote: row.require_sol_quote,
+ take_profit_pct: row.take_profit_pct != null ? Number(row.take_profit_pct) : null,
+ stop_loss_pct: Number(row.stop_loss_pct),
+ trailing_stop_pct: row.trailing_stop_pct != null ? Number(row.trailing_stop_pct) : null,
+ max_hold_seconds: row.max_hold_seconds,
+ },
+ });
+}
diff --git a/api/sniper/stream.js b/api/sniper/stream.js
new file mode 100644
index 000000000..bb82181c2
--- /dev/null
+++ b/api/sniper/stream.js
@@ -0,0 +1,135 @@
+/**
+ * Agent Sniper — live SSE stream for the /play arena.
+ *
+ * GET /api/sniper/stream?network=mainnet
+ *
+ * The sniper worker is a SEPARATE process, so this endpoint can't read its
+ * in-memory state — it DB-polls agent_sniper_positions for rows changed since a
+ * cursor (~1.5s) and emits diffs. Postgres LISTEN/NOTIFY is not an option: Neon
+ * serverless HTTP can't hold a LISTEN connection.
+ *
+ * Events: open, buy, sell, update, ping, close.
+ */
+
+import { cors, method, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const MAX_DURATION_MS = 90_000;
+const PING_INTERVAL_MS = 15_000;
+const POLL_INTERVAL_MS = 1_500;
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+function solscan(sig, network) {
+ if (!sig || sig === 'SIMULATED') return null;
+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;
+}
+const sol = (l) => (l != null ? Number(BigInt(l)) / 1e9 : null);
+
+function shape(r, network) {
+ const entry = r.entry_quote_lamports != null ? Number(BigInt(r.entry_quote_lamports)) : 0;
+ const last = r.last_value_lamports != null ? Number(BigInt(r.last_value_lamports)) : entry;
+ return {
+ id: r.id,
+ agent_id: r.agent_id,
+ agent_name: r.agent_name,
+ mint: r.mint,
+ symbol: r.symbol,
+ name: r.name,
+ status: r.status,
+ exit_reason: r.exit_reason,
+ entry_sol: sol(r.entry_quote_lamports),
+ current_sol: entry > 0 ? last / 1e9 : sol(r.last_value_lamports),
+ exit_sol: sol(r.exit_quote_lamports),
+ pnl_sol: sol(r.realized_pnl_lamports),
+ pnl_pct: r.realized_pnl_pct != null ? Number(r.realized_pnl_pct) : (entry > 0 ? ((last - entry) / entry) * 100 : null),
+ buy_url: solscan(r.buy_sig, network),
+ sell_url: solscan(r.sell_sig, network),
+ at: r.changed_at,
+ };
+}
+
+export default async function handleSniperStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active) return;
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ };
+
+ // Start from "now" so we stream only fresh activity; the leaderboard endpoint
+ // supplies the initial backlog the page renders on load.
+ let cursor = new Date().toISOString();
+
+ const poll = async () => {
+ if (!active) return;
+ try {
+ const rows = await sql`
+ select p.id, p.agent_id, a.name as agent_name, p.mint, p.symbol, p.name,
+ p.status, p.exit_reason, p.entry_quote_lamports, p.last_value_lamports,
+ p.exit_quote_lamports, p.realized_pnl_lamports, p.realized_pnl_pct,
+ p.buy_sig, p.sell_sig, p.opened_at, p.closed_at,
+ greatest(p.opened_at, coalesce(p.closed_at, p.opened_at),
+ coalesce(p.last_quoted_at, p.opened_at)) as changed_at
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id
+ where p.network = ${network}
+ and greatest(p.opened_at, coalesce(p.closed_at, p.opened_at),
+ coalesce(p.last_quoted_at, p.opened_at)) > ${cursor}
+ order by changed_at asc
+ limit 100
+ `;
+ for (const r of rows) {
+ const payload = shape(r, network);
+ // Classify the transition for the ticker: a row whose newest timestamp
+ // is its close is a sell; one whose newest is its open is a buy; the
+ // rest are live re-quote updates.
+ const closedTs = r.closed_at ? new Date(r.closed_at).getTime() : 0;
+ const openedTs = new Date(r.opened_at).getTime();
+ const changedTs = new Date(r.changed_at).getTime();
+ const event = r.status === 'closed' && closedTs === changedTs ? 'sell'
+ : openedTs === changedTs && r.buy_sig ? 'buy'
+ : 'update';
+ send(event, payload);
+ if (r.changed_at > cursor) cursor = r.changed_at;
+ }
+ } catch (err) {
+ send('error', { message: 'poll_failed' });
+ }
+ };
+
+ send('open', { network, source: 'agent-sniper' });
+ const pollTimer = setInterval(poll, POLL_INTERVAL_MS);
+ const ping = setInterval(() => send('ping', { t: Date.now() }), PING_INTERVAL_MS);
+
+ const teardown = () => {
+ if (!active) return;
+ active = false;
+ clearInterval(pollTimer);
+ clearInterval(ping);
+ clearTimeout(durationTimer);
+ try { res.end(); } catch {}
+ };
+ const durationTimer = setTimeout(() => {
+ send('close', { reason: 'duration_limit' });
+ teardown();
+ }, MAX_DURATION_MS);
+
+ req.on('close', teardown);
+}
diff --git a/data/changelog.json b/data/changelog.json
index 1a93a575b..fd7fb58a2 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-15",
+ "title": "Pose any avatar — a full motion library on the avatar page",
+ "summary": "Every avatar page has a new Pose tab. Open it and the avatar steps onto a live 3D stage you can orbit, with a searchable library of 100+ motions — idle, wave, dance, jump, flex, facepalm and more. Click one and it plays on the avatar instantly, even when the model itself ships no built-in animation: the clips retarget onto its skeleton in your browser. A speed slider and a reset-to-idle control round out the transport. Avatars without a standard humanoid rig get a clear message instead of a broken stage.",
+ "tags": ["feature"]
+ },
+ {
+ "date": "2026-06-15",
+ "title": "Avatars come to life — animations now play on the avatar page",
+ "summary": "Every avatar page now plays its built-in animation the moment it loads, so a rigged avatar stands, breathes, or performs its motion instead of freezing in a static pose. A new floating control sits over the 3D stage: a play/pause button, plus a clip switcher when an avatar carries more than one take so you can jump between them. Avatars with no embedded motion are unaffected — the control only appears when there's something to play.",
+ "tags": ["feature"]
+ },
+ {
+ "date": "2026-06-15",
+ "title": "The IRL page loads again",
+ "summary": "Opening three.ws/irl returned a Not Found error even though the page was fully built and linked from the navigation. The page wasn't mapped in our routing rules, so the server never served it. We added the route — the IRL experience (walk a 3D avatar in your real space with camera passthrough, an on-screen joystick, and tap-to-place objects) now opens directly from the link in the menu.",
+ "tags": ["fix"],
+ "link": "/irl"
+ },
{
"date": "2026-06-15",
"title": "Browse every community avatar from your dashboard",
diff --git a/public/bazaar.html b/public/bazaar.html
index 28625f7f6..9957fabcd 100644
--- a/public/bazaar.html
+++ b/public/bazaar.html
@@ -245,7 +245,10 @@
.cards {
display: grid;
- grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
+ /* min(100%, 320px) lets the track collapse to the container width on
+ phones narrower than 320px so a single card never forces sideways
+ scroll; on wider screens it keeps the 320px comfortable minimum. */
+ grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr));
gap: 14px;
}
.card {
diff --git a/public/changelog.json b/public/changelog.json
index d045e1eaa..5871e9fb2 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T10:14:40.135Z",
+ "generated_at": "2026-06-15T15:13:26.566Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -58,6 +58,16 @@
"infra"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Avatars come to life — animations now play on the avatar page",
+ "summary": "Every avatar page now plays its built-in animation the moment it loads, so a rigged avatar stands, breathes, or performs its motion instead of freezing in a static pose. A new floating control sits over the 3D stage: a play/pause button, plus a clip switcher when an avatar carries more than one take so you can jump between them. Avatars with no embedded motion are unaffected — the control only appears when there's something to play.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
@@ -140,6 +150,16 @@
"security"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Pose any avatar — a full motion library on the avatar page",
+ "summary": "Every avatar page has a new Pose tab. Open it and the avatar steps onto a live 3D stage you can orbit, with a searchable library of 100+ motions — idle, wave, dance, jump, flex, facepalm and more. Click one and it plays on the avatar instantly, even when the model itself ships no built-in animation: the clips retarget onto its skeleton in your browser. A speed slider and a reset-to-idle control round out the transport. Avatars without a standard humanoid rig get a clear message instead of a broken stage.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
@@ -233,6 +253,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "The IRL page loads again",
+ "summary": "Opening three.ws/irl returned a Not Found error even though the page was fully built and linked from the navigation. The page wasn't mapped in our routing rules, so the server never served it. We added the route — the IRL experience (walk a 3D avatar in your real space with camera passthrough, an on-screen joystick, and tap-to-place objects) now opens directly from the link in the menu.",
+ "link": "/irl",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 0d5f402b6..3ecce52c8 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -46,6 +46,14 @@
<category>improvement</category>
<description>Coins launched through three.ws with autopilot enabled now have their buybacks and creator-fee distributions executed automatically on an hourly schedule, instead of waiting for a manual trigger. A new balance watchdog checks every Solana signer the platform uses to pay on-chain fees and alerts the team the moment one runs low, so autopilot never silently stalls for lack of gas. No action needed from coin owners — it just works in the background.</description>
</item>
+ <item>
+ <title>Avatars come to life — animations now play on the avatar page</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-15:Avatars come to life — animations now play on the avatar page</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every avatar page now plays its built-in animation the moment it loads, so a rigged avatar stands, breathes, or performs its motion instead of freezing in a static pose. A new floating control sits over the 3D stage: a play/pause button, plus a clip switcher when an avatar carries more than one take so you can jump between them. Avatars with no embedded motion are unaffected — the control only appears when there's something to play.</description>
+ </item>
<item>
<title>Browse every community avatar from your dashboard</title>
<link>https://three.ws/dashboard/avatars</link>
@@ -110,6 +118,14 @@
<category>feature</category>
<description>Solana agents now get the same verifiable, on-chain glTF/model validation that EVM agents get from the ValidationRegistry — no contract to deploy. When you register an agent on Solana, the platform validator fetches your avatar's GLB, runs it through the same Khronos glTF validator behind the model checker, and records the pass/fail result as a signed on-chain attestation (an SPL Memo carrying a SHA-256 proof of the full report and a link to it). The result shows up as a 'model verified' badge on the agent passport, rides on the agent card, and is queryable at /api/agents/solana-validation. Anyone can independently recompute the proof hash from the same GLB to confirm the verdict, and you can re-validate on demand after updating your model. Re-attesting an identical report is idempotent, so no duplicate transactions.</description>
</item>
+ <item>
+ <title>Pose any avatar — a full motion library on the avatar page</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-15:Pose any avatar — a full motion library on the avatar page</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every avatar page has a new Pose tab. Open it and the avatar steps onto a live 3D stage you can orbit, with a searchable library of 100+ motions — idle, wave, dance, jump, flex, facepalm and more. Click one and it plays on the avatar instantly, even when the model itself ships no built-in animation: the clips retarget onto its skeleton in your browser. A speed slider and a reset-to-idle control round out the transport. Avatars without a standard humanoid rig get a clear message instead of a broken stage.</description>
+ </item>
<item>
<title>Pump dashboard alerts now run server-side — fire across devices even with the tab closed</title>
<link>https://three.ws/pump-dashboard</link>
@@ -182,6 +198,14 @@
<category>feature</category>
<description>A new auto-generation system creates a fresh 3D avatar or accessory every minute using the free NVIDIA lane and adds it to the community gallery. Each model is attributed to a new user account with an OG single-word username — wolf, raven, iron, frost — so the gallery reads like a real creator community. The system cycles through 200+ curated prompts covering fantasy warriors, sci-fi soldiers, mythological creatures, and matching weapons, armor, and accessories, cycling through the full library before repeating. Every model is a permanent GLB stored in our own CDN.</description>
</item>
+ <item>
+ <title>The IRL page loads again</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-15:The IRL page loads again</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Opening three.ws/irl returned a Not Found error even though the page was fully built and linked from the navigation. The page wasn't mapped in our routing rules, so the server never served it. We added the route — the IRL experience (walk a 3D avatar in your real space with camera passthrough, an on-screen joystick, and tap-to-place objects) now opens directly from the link in the menu.</description>
+ </item>
<item>
<title>The pump.fun graduations feed stays fresh around the clock</title>
<link>https://three.ws/changelog</link>
diff --git a/public/discover/discover.js b/public/discover/discover.js
index c6f8e71f6..1fbcd55cf 100644
--- a/public/discover/discover.js
+++ b/public/discover/discover.js
@@ -553,7 +553,7 @@ function renderAvatarCard(item) {
${tagChips ? `<div class="explore-card-svcs">${tagChips}</div>` : ''}
<div class="explore-card-foot">
<span class="explore-card-owner" title="Avatar made public by its creator">
- ${item.viewCount ? `<span class="explore-card-views">${escapeHtml(formatCompact(item.viewCount))} views</span>` : `@${escapeHtml(item.slug || 'avatar')}`}
+ @${escapeHtml(item.slug || 'avatar')}
</span>
<div class="explore-card-actions">
<a class="explore-card-link" href="${escapeAttr(detailUrl)}">View avatar</a>
@@ -617,12 +617,6 @@ function renderSolanaCard(item) {
return card;
}
-function formatCompact(n) {
- if (n < 1000) return String(n);
- if (n < 1_000_000) return (n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '') + 'k';
- return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
-}
-
function escapeHtml(s) {
return String(s ?? '')
.replace(/&/g, '&amp;')
diff --git a/public/features.json b/public/features.json
index 7f7576438..2bb81993a 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T10:14:40.116Z",
+ "generated_at": "2026-06-15T15:13:26.376Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/home-live.js b/public/home-live.js
index ca5cd90b7..1dca819f3 100644
--- a/public/home-live.js
+++ b/public/home-live.js
@@ -91,8 +91,6 @@
if (item.source && item.source !== 'upload')
bits.push(item.source);
else bits.push('GLB');
- if (item.viewCount && item.viewCount > 0)
- bits.push(`${item.viewCount} view${item.viewCount === 1 ? '' : 's'}`);
return bits;
}
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 97ca39752..9f7fd6be1 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -227,6 +227,8 @@ function renderShell(glbUrl) {
tone-mapping="aces"
environment-image="neutral"
reveal="auto"
+ autoplay
+ animation-crossfade-duration="300"
ar
ar-modes="webxr scene-viewer quick-look"
ar-scale="auto"
@@ -237,6 +239,12 @@ function renderShell(glbUrl) {
</div>
</div>
</model-viewer>
+ <div class="av-anim-bar" id="av-anim-bar" role="group" aria-label="Animation playback">
+ <button class="av-anim-toggle" id="av-anim-toggle" type="button" aria-label="Pause animation" aria-pressed="true">
+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
+ </button>
+ <div class="av-anim-clips" id="av-anim-clips"></div>
+ </div>
</div>
<div class="av-meta-strip" id="av-meta-strip">
<div class="av-meta-item"><span class="av-meta-key">Format</span><span class="av-meta-val">glTF 2.0</span></div>
@@ -394,6 +402,7 @@ function renderShell(glbUrl) {
viewer?.addEventListener('load', () => {
$('av-stage-loading')?.remove();
positionThoughtHotspot(viewer);
+ setupAnimationControls(viewer);
});
viewer?.addEventListener('error', () => {
const ld = $('av-stage-loading');
@@ -1154,11 +1163,117 @@ function playClipByHint(hints, { loop = false } = {}) {
if (idx !== -1) break;
}
if (idx === -1) return;
- viewer.animationName = clips[idx];
- viewer.autoplay = true;
+ playClip(viewer, clips[idx], { loop });
+}
+
+// Build the floating play/pause + clip-switcher bar once the model is loaded.
+// Visible only when the GLB actually carries animation clips. A rigged avatar
+// with a single embedded mocap take gets an autoplaying idle + a pause toggle;
+// a model with several takes gets a pill switcher to jump between them.
+function setupAnimationControls(viewer) {
+ const bar = $('av-anim-bar');
+ const clipsHost = $('av-anim-clips');
+ const toggle = $('av-anim-toggle');
+ if (!bar || !clipsHost || !toggle) return;
+
+ const clips = (viewer.availableAnimations || []).slice();
+ if (!clips.length) {
+ bar.removeAttribute('data-visible');
+ return;
+ }
+
+ // Mirror into the skills-panel detection set so wave/idle skills light up
+ // even before the byte-range stats probe resolves.
+ availableAnimations = new Set(clips.map((n) => n.toLowerCase()));
+
+ // Pick a sensible default: prefer a calm idle/breathing take, then a wave,
+ // then whatever ships first.
+ const lower = clips.map((n) => n.toLowerCase());
+ const preferred = ['idle', 'breath', 'stand', 'wave', 'dance'];
+ let defaultIdx = -1;
+ for (const hint of preferred) {
+ defaultIdx = lower.findIndex((n) => n.includes(hint));
+ if (defaultIdx !== -1) break;
+ }
+ if (defaultIdx === -1) defaultIdx = 0;
+
+ if (clips.length === 1) {
+ // One take — no switcher, just a label so the control reads clearly.
+ const label = document.createElement('span');
+ label.className = 'av-anim-label';
+ label.textContent = prettyClipName(clips[0], 0, 1);
+ clipsHost.replaceChildren(label);
+ } else {
+ const frag = document.createDocumentFragment();
+ clips.forEach((name, i) => {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'av-anim-clip';
+ btn.dataset.clip = name;
+ btn.textContent = prettyClipName(name, i, clips.length);
+ btn.addEventListener('click', () => playClip(viewer, name, { loop: true }));
+ frag.appendChild(btn);
+ });
+ clipsHost.replaceChildren(frag);
+ }
+
+ toggle.addEventListener('click', () => {
+ if (animPlaying) {
+ viewer.pause();
+ setAnimPlaying(false);
+ } else {
+ if (typeof viewer.play === 'function') viewer.play({ repetitions: Infinity });
+ setAnimPlaying(true);
+ }
+ });
+
+ playClip(viewer, clips[defaultIdx], { loop: true });
+ bar.setAttribute('data-visible', '1');
+}
+
+// Play a named clip via model-viewer's public API and sync the control bar.
+function playClip(viewer, name, { loop = true } = {}) {
+ if (!viewer || !name) return;
+ viewer.animationName = name;
+ viewer.currentTime = 0;
if (typeof viewer.play === 'function') viewer.play({ repetitions: loop ? Infinity : 1 });
+ setAnimPlaying(true);
+ const clipsHost = $('av-anim-clips');
+ clipsHost?.querySelectorAll('.av-anim-clip').forEach((btn) => {
+ btn.classList.toggle('is-active', btn.dataset.clip === name);
+ });
}
+// Toggle the play/pause button's icon + ARIA state.
+function setAnimPlaying(playing) {
+ animPlaying = playing;
+ const toggle = $('av-anim-toggle');
+ if (!toggle) return;
+ toggle.setAttribute('aria-pressed', String(playing));
+ toggle.setAttribute('aria-label', playing ? 'Pause animation' : 'Play animation');
+ toggle.innerHTML = playing
+ ? '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>'
+ : '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>';
+}
+
+// Humanize a raw glTF clip name for the switcher. Mocap exporters leave noise
+// like "mixamo.com" or "Armature|Take 001" — collapse those to a clean label.
+function prettyClipName(name, i, total) {
+ const raw = (name || '').trim();
+ if (!raw || /^mixamo\.com$/i.test(raw) || /\.(glb|gltf|fbx|com)$/i.test(raw)) {
+ return total > 1 ? `Clip ${i + 1}` : 'Animation';
+ }
+ const cleaned = raw
+ .replace(/^armature[|/_-]*/i, '')
+ .replace(/\|/g, ' ')
+ .replace(/[_-]+/g, ' ')
+ .trim();
+ if (!cleaned) return total > 1 ? `Clip ${i + 1}` : 'Animation';
+ return cleaned.replace(/\b\w/g, (c) => c.toUpperCase());
+}
+
+let animPlaying = false;
+
// ── Plugins panel ─────────────────────────────────────────────────────
async function loadPlugins() {
diff --git a/src/characters.css b/src/characters.css
index a885f18f6..4b696a985 100644
--- a/src/characters.css
+++ b/src/characters.css
@@ -33,6 +33,7 @@ body {
.chs-search {
flex: 1;
+ min-width: 0;
background: rgba(255, 255, 255, 0.7);
border: 1.5px solid rgba(0,0,0,0.1);
border-radius: 32px;
@@ -77,7 +78,10 @@ body {
/* ── Grid ─────────────────────────────────────────────── */
.chs-grid {
display: grid;
- grid-template-columns: 1fr 1fr;
+ /* Mobile-first: one full-width column. minmax(0, 1fr) lets the track
+ shrink below the cards' content min-width so token/stat rows never
+ force horizontal scroll on narrow phones. */
+ grid-template-columns: minmax(0, 1fr);
gap: 12px;
padding: 16px 20px;
max-width: 640px;
@@ -85,7 +89,7 @@ body {
}
@media (min-width: 480px) {
- .chs-grid { grid-template-columns: 1fr 1fr; }
+ .chs-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
/* ── Character card ───────────────────────────────────── */
diff --git a/tests/api/forge-fallback.test.js b/tests/api/forge-fallback.test.js
index a6f77ee58..17ad3590b 100644
--- a/tests/api/forge-fallback.test.js
+++ b/tests/api/forge-fallback.test.js
@@ -17,9 +17,19 @@ beforeAll(() => {
APP_ORIGIN: 'https://three.ws',
REPLICATE_API_TOKEN: 'test-token',
NVIDIA_API_KEY: 'test-nvidia-key',
+ // Self-hosted Hunyuan3D worker wired → image→3D has a fallback target.
+ GCP_HUNYUAN3D_URL: 'https://hunyuan3d.example.run.app',
+ GCP_RECONSTRUCTION_KEY: 'test-gcp-key',
});
});
+// Self-hosted Hunyuan3D Cloud Run worker (the image→3D fallback) accepts the job
+// and returns a poll handle, exactly like api/_providers/gcp.js.
+const gcpSubmit = vi.fn(async () => ({ extJobId: 'gcpjob1234567890', viewsUsed: 1, multiview: false }));
+vi.mock('../../api/_providers/gcp.js', () => ({
+ createRegenProvider: () => ({ submit: gcpSubmit }),
+}));
+
// Replicate (paid TRELLIS lane) is over-quota — every submit throws a 429 the
// same way api/_providers/replicate.js does on a non-ok response.
vi.mock('../../api/_providers/replicate.js', () => ({
@@ -117,8 +127,9 @@ describe('forge free-first fallback when the paid lane is over-quota', () => {
expect(nvidiaTextTo3d).toHaveBeenCalled();
});
- it('still surfaces a busy state for an image upload (no free reconstruct fallback)', async () => {
+ it('degrades an image upload to the self-hosted Hunyuan3D worker (not NVIDIA — it is text-only)', async () => {
nvidiaTextTo3d.mockClear();
+ gcpSubmit.mockClear();
const req = makeReq({
image_urls: ['https://cdn.example/photo.png'],
prompt: 'a mug',
@@ -129,10 +140,38 @@ describe('forge free-first fallback when the paid lane is over-quota', () => {
const res = makeRes();
await handler(req, res);
- // Image→3D has no free fallback (NVCF is text-only), so it does NOT silently
- // produce an unrelated prompt-based model — it returns the honest busy state.
- expect(res.statusCode).toBe(429);
- expect(res.body.error).toBe('rate_limited');
+ expect(res.statusCode).toBe(200);
+ expect(res.body.status).toBe('queued');
+ expect(res.body.backend).toBe('hunyuan3d');
+ expect(gcpSubmit).toHaveBeenCalled();
+ // NVIDIA is text-only — it must never be invoked for a photo upload.
expect(nvidiaTextTo3d).not.toHaveBeenCalled();
+ // Hunyuan3D is poly-aware: the tier budget the TRELLIS params omit is supplied.
+ expect(gcpSubmit.mock.calls[0][0].params.target_polycount).toBeGreaterThan(0);
+ });
+
+ it('surfaces the honest busy state for an image upload when no Hunyuan3D worker is wired', async () => {
+ const savedUrl = process.env.GCP_HUNYUAN3D_URL;
+ delete process.env.GCP_HUNYUAN3D_URL;
+ gcpSubmit.mockClear();
+ try {
+ const req = makeReq({
+ image_urls: ['https://cdn.example/photo.png'],
+ prompt: 'a mug',
+ tier: 'standard',
+ path: 'image',
+ skip_validation: true,
+ });
+ const res = makeRes();
+ await handler(req, res);
+
+ // No free reconstruct fallback exists → it does NOT fabricate a model; it
+ // returns the honest busy state so the page can prompt a retry or Draft.
+ expect(res.statusCode).toBe(429);
+ expect(res.body.error).toBe('rate_limited');
+ expect(gcpSubmit).not.toHaveBeenCalled();
+ } finally {
+ process.env.GCP_HUNYUAN3D_URL = savedUrl;
+ }
});
});
diff --git a/vercel.json b/vercel.json
index 0b516944e..90550d08a 100644
--- a/vercel.json
+++ b/vercel.json
@@ -593,6 +593,10 @@
"src": "/walk/?",
"dest": "/walk.html"
},
+ {
+ "src": "/irl/?",
+ "dest": "/irl.html"
+ },
{
"src": "/communities/?",
"dest": "/communities.html"
diff --git a/workers/agent-sniper/Dockerfile b/workers/agent-sniper/Dockerfile
new file mode 100644
index 000000000..572df7b76
--- /dev/null
+++ b/workers/agent-sniper/Dockerfile
@@ -0,0 +1,32 @@
+# agent-sniper — long-lived Node worker.
+#
+# Build from the REPO ROOT (it imports api/_lib/* and the @three-ws/agent-payments
+# workspace, so it needs the full install):
+#
+# docker build -f workers/agent-sniper/Dockerfile -t agent-sniper .
+# docker run --env-file .env agent-sniper
+#
+# Deploy target is Cloud Run (no HTTP port — it's a background worker; deploy
+# with --no-cpu-throttling so the feed stays connected between requests).
+
+FROM node:24-slim
+
+WORKDIR /app
+
+# Install deps first for layer caching. postinstall builds the agent-payments
+# SDK (dist/) that the trade client imports.
+COPY package.json package-lock.json* ./
+COPY agent-payments-sdk/package.json ./agent-payments-sdk/
+RUN npm ci --omit=dev --ignore-scripts || npm install --omit=dev --ignore-scripts
+
+# Bring in source needed at runtime, then build the SDK explicitly (ignore-scripts
+# skipped the postinstall build above).
+COPY agent-payments-sdk ./agent-payments-sdk
+COPY api ./api
+COPY workers/agent-sniper ./workers/agent-sniper
+RUN npm run build --prefix agent-payments-sdk
+
+ENV NODE_ENV=production \
+ SNIPER_MODE=simulate
+
+CMD ["node", "workers/agent-sniper/index.js"]
diff --git a/workers/agent-sniper/README.md b/workers/agent-sniper/README.md
new file mode 100644
index 000000000..771dd66b1
--- /dev/null
+++ b/workers/agent-sniper/README.md
@@ -0,0 +1,75 @@
+# agent-sniper
+
+Autonomous pump.fun sniper. A long-lived Node worker that holds the PumpPortal
+new-mint feed open, scores each launch against every armed agent strategy, and
+snipes from the **agent's own** Solana wallet — then manages each position to a
+stop-loss / take-profit / trailing-stop / timeout exit.
+
+It is deliberately **not** a Vercel cron: hourly ticks can't snipe a launch.
+
+## Architecture
+
+| File | Role |
+|------|------|
+| `index.js` | Entrypoint. Feed subscription, buy queue, position sweep, feed watchdog, graceful shutdown. |
+| `config.js` | Validated env (`loadConfig`). Throws on missing `DATABASE_URL`/`JWT_SECRET`; refuses live mode without a real RPC. |
+| `strategy-store.js` | Cached active-strategy list + `countOpenPositions` / `getDailySpend` / `getOpenPositions`. |
+| `scorer.js` | Pure `scoreMint(mint, strategy)` entry filter (mc band, creator history, socials, SOL-quote). |
+| `keys.js` | `loadAgentKeypair` — decrypts the agent secret via `recoverSolanaAgentKeypair`, TTL-cached, audited. |
+| `trade-client.js` | Wraps `PumpTradeClient`; `signAndSend` assembles a v0 tx, signs with the agent keypair, broadcasts, confirms. |
+| `executor.js` | `executeBuy` / `executeSell` — every guardrail, the idempotency lock, the only place that signs. |
+| `positions.js` | `runPositionSweep` — re-quotes open positions and triggers exits. |
+
+State lives in two tables (migration `api/_lib/migrations/20260615020000_agent_sniper.sql`):
+`agent_sniper_strategies` (owner-armed policy) and `agent_sniper_positions` (the
+sniper's own trade ledger — *not* `pump_agent_trades`, whose `mint_id` FK can't
+hold a stranger-launched mint).
+
+## Guardrails
+
+Enforced in `executeBuy`, short-circuiting before any transaction:
+
+1. **Global kill** — `SNIPER_GLOBAL_KILL=1` halts new buys (positions still managed).
+2. **Per-agent kill** — `kill_switch` column; killed agents drop out of the active set and any open position exits at market.
+3. **Daily budget cap** — `daily_budget_lamports` vs today's committed spend.
+4. **Max concurrent positions** — `max_concurrent_positions`.
+5. **Mandatory stop-loss** — DB `CHECK (stop_loss_pct > 0)` + runtime filter.
+6. **Price-impact circuit breaker** — `max_price_impact_pct` checked against a fresh `quoteForBuy`.
+7. **Idempotency** — `INSERT … ON CONFLICT (agent_id, mint, network) DO NOTHING` claims the slot before the tx; one shot per mint per agent.
+
+> **Single-worker assumption.** Budget/concurrency races are prevented by an
+> in-process per-agent lock. Run exactly ONE instance. Scaling out requires an
+> atomic DB spend reservation instead.
+
+## Environment
+
+| Var | Required | Default | Notes |
+|-----|----------|---------|-------|
+| `DATABASE_URL` | ✅ | — | Neon Postgres. |
+| `JWT_SECRET` | ✅ | — | Decrypts agent Solana secrets. |
+| `SOLANA_RPC_URL` / `HELIUS_API_KEY` | live only | — | Public RPC 429s under the firehose; required for `live`. |
+| `SNIPER_MODE` | | `simulate` | `simulate` = real quotes, no broadcast; `live` = real trades. |
+| `SNIPER_NETWORK` | | `mainnet` | `mainnet`/`devnet`. |
+| `SNIPER_GLOBAL_KILL` | | `0` | `1` halts new buys. |
+| `SNIPER_POLL_MS` | | `5000` | Position re-quote cadence. |
+| `SNIPER_MAX_GLOBAL_BUYS_PER_MIN` | | `10` | Platform-wide buy throttle backstop. |
+| `SNIPER_CONFIRM_TIMEOUT_MS` | | `60000` | Per-trade confirmation wait. |
+
+## Run locally
+
+```bash
+# from repo root, with env exported (DATABASE_URL, JWT_SECRET, HELIUS_API_KEY)
+npm run db:migrate # once — creates the two tables
+SNIPER_MODE=simulate node workers/agent-sniper/index.js
+```
+
+Arm a test agent (owned by you, wallet funded with a little SOL) by inserting a
+strategy row, then watch it score → open → exit. Flip to `SNIPER_MODE=live`
+with tiny caps to land one real trade. `Ctrl-C` drains in-flight buys and exits.
+
+## Known gap (fast-follow)
+
+Bonding-curve exits only. A position that **graduates** mid-hold can't be sold on
+the curve — it's flagged `exit_reason='graduated'` and parked for the AMM-exit
+follow-up (via `buildPumpSwapInnerIx`). Short `max_hold_seconds` / take-profit
+keep most positions exiting before graduation in the meantime.
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
new file mode 100644
index 000000000..314fea0b1
--- /dev/null
+++ b/workers/agent-sniper/executor.js
@@ -0,0 +1,221 @@
+// agent-sniper — the only module that signs and broadcasts.
+//
+// executeBuy / executeSell own every guardrail, the idempotency lock, the trade
+// build, the broadcast, and the agent_sniper_positions writes. In `simulate`
+// mode the full path runs against REAL on-chain quotes but the broadcast is
+// skipped (sig = 'SIMULATED') — an ops safety toggle, never the default.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+import { loadAgentKeypair } from './keys.js';
+import { getTradeCtx, signAndSend } from './trade-client.js';
+import { countOpenPositions, getDailySpend } from './strategy-store.js';
+
+// Fee + rent headroom we keep above the trade size so a buy doesn't fail for
+// lack of lamports to pay fees / open the token ATA.
+const SOL_HEADROOM_LAMPORTS = 3_000_000n; // ~0.003 SOL
+
+// ── per-agent serialization ────────────────────────────────────────────────
+// Single-worker assumption: a per-agent in-process lock makes the budget +
+// concurrency checks race-free without a DB reservation. (Scaling to N workers
+// would require an atomic spend reservation instead — documented in README.)
+const _locks = new Map();
+async function withAgentLock(agentId, fn) {
+ const prev = _locks.get(agentId) || Promise.resolve();
+ let release;
+ const next = new Promise((r) => (release = r));
+ _locks.set(agentId, prev.then(() => next));
+ await prev;
+ try {
+ return await fn();
+ } finally {
+ release();
+ if (_locks.get(agentId) === next) _locks.delete(agentId);
+ }
+}
+
+function bn(ctx, v) {
+ return new ctx.BN(BigInt(v).toString());
+}
+
+/**
+ * Attempt to snipe `mint` for `strat`. All checks short-circuit before any tx.
+ * @returns {Promise<{ status: string, reason?: string, sig?: string }>}
+ */
+export async function executeBuy({ cfg, strat, mint, throttle }) {
+ return withAgentLock(strat.agent_id, async () => {
+ const perTrade = BigInt(strat.per_trade_lamports);
+ const tag = { agent: strat.agent_id, mint: mint.mint, symbol: mint.symbol };
+
+ // 1. global throttle (platform-wide backstop)
+ if (!throttle.tryConsume()) return skip(tag, 'global_throttle');
+
+ // 2. concurrency cap
+ const open = await countOpenPositions(strat.agent_id, cfg.network);
+ if (open >= strat.max_concurrent_positions) return skip(tag, 'max_positions');
+
+ // 3. daily budget cap
+ const spent = await getDailySpend(strat.agent_id, cfg.network);
+ if (spent + perTrade > BigInt(strat.daily_budget_lamports)) return skip(tag, 'daily_budget');
+
+ // 4. idempotency lock — claim the (agent,mint,network) slot BEFORE the tx.
+ const claimed = await sql`
+ INSERT INTO agent_sniper_positions
+ (strategy_id, agent_id, user_id, wallet, network, mint, symbol, name, status)
+ VALUES (${strat.id}, ${strat.agent_id}, ${strat.user_id}, ${'pending'}, ${cfg.network},
+ ${mint.mint}, ${mint.symbol || null}, ${mint.name || null}, 'opening')
+ ON CONFLICT (agent_id, mint, network) DO NOTHING
+ RETURNING id
+ `;
+ if (!claimed.length) return skip(tag, 'already_held');
+ const posId = claimed[0].id;
+
+ try {
+ // 5. agent wallet + funds
+ const loaded = await loadAgentKeypair(strat.agent_id, strat.user_id, 'sniper_buy');
+ if (!loaded) return await fail(posId, tag, 'no_wallet');
+ const { keypair, address } = loaded;
+ await sql`UPDATE agent_sniper_positions SET wallet = ${address} WHERE id = ${posId}`;
+
+ const ctx = await getTradeCtx(cfg.network);
+ const lamports = BigInt(await ctx.connection.getBalance(keypair.publicKey, 'confirmed'));
+ if (lamports < perTrade + SOL_HEADROOM_LAMPORTS) {
+ return await fail(posId, tag, 'insufficient_sol');
+ }
+
+ const mintPk = new ctx.web3.PublicKey(mint.mint);
+ const slippagePct = strat.slippage_bps / 100;
+
+ // 6. quote + price-impact circuit breaker
+ const quote = await ctx.client.quoteForBuy({ mint: mintPk, quoteAmount: bn(ctx, perTrade), slippagePct });
+ if (strat.require_sol_quote && !quote.quoteMint.equals(ctx.web3.PublicKey.default) && quote.quoteMint.toBase58() !== 'So11111111111111111111111111111111111111112') {
+ return await fail(posId, tag, 'quote_not_sol');
+ }
+ if (Number(quote.priceImpactPct) > Number(strat.max_price_impact_pct)) {
+ return await fail(posId, tag, 'price_impact');
+ }
+
+ // 7. build + (live) broadcast
+ const built = await ctx.client.buildBuyInstructions({
+ mint: mintPk, user: keypair.publicKey, quoteAmount: bn(ctx, perTrade), slippagePct,
+ });
+ const baseAmount = BigInt(built.expectedBaseTokens.toString());
+ if (baseAmount <= 0n) return await fail(posId, tag, 'zero_tokens');
+
+ let sig = 'SIMULATED';
+ if (cfg.mode === 'live') {
+ sig = await signAndSend(ctx, keypair, built.instructions, cfg.confirmTimeoutMs);
+ }
+
+ const pricePerToken = Number(perTrade) / Number(baseAmount);
+ await sql`
+ UPDATE agent_sniper_positions SET
+ status = 'open', buy_sig = ${sig},
+ entry_quote_lamports = ${perTrade.toString()},
+ base_amount = ${baseAmount.toString()},
+ entry_price_lamports_per_token = ${pricePerToken},
+ entry_price_impact_pct = ${Number(quote.priceImpactPct)},
+ peak_value_lamports = ${perTrade.toString()},
+ last_value_lamports = ${perTrade.toString()},
+ last_quoted_at = now()
+ WHERE id = ${posId}
+ `;
+ log.trade('buy', { ...tag, mode: cfg.mode, sig, sol: lamportsToSol(perTrade), base: baseAmount.toString(), impact: Number(quote.priceImpactPct).toFixed(2) });
+ return { status: 'open', sig };
+ } catch (err) {
+ return await fail(posId, tag, errCode(err), err);
+ }
+ });
+}
+
+/**
+ * Close `position` for `reason`. Re-quotes fresh for slippage, builds the sell,
+ * broadcasts (live), records realized P&L.
+ */
+export async function executeSell({ cfg, position, reason }) {
+ return withAgentLock(position.agent_id, async () => {
+ const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol, reason };
+ await sql`UPDATE agent_sniper_positions SET status = 'closing' WHERE id = ${position.id} AND status = 'open'`;
+
+ try {
+ const loaded = await loadAgentKeypair(position.agent_id, position.user_id, 'sniper_sell');
+ if (!loaded) return await fail(position.id, tag, 'no_wallet');
+ const { keypair } = loaded;
+
+ const ctx = await getTradeCtx(cfg.network);
+ const mintPk = new ctx.web3.PublicKey(position.mint);
+ const baseAmount = bn(ctx, BigInt(position.base_amount));
+ const slippagePct = (position.slippage_bps ?? 500) / 100;
+
+ let expectedOut;
+ let built;
+ try {
+ const quote = await ctx.client.quoteForSell({ mint: mintPk, baseAmount, slippagePct });
+ expectedOut = BigInt(quote.expectedQuoteOut.toString());
+ built = await ctx.client.buildSellInstructions({ mint: mintPk, user: keypair.publicKey, baseAmount, slippagePct });
+ } catch (err) {
+ if (err?.name === 'CoinGraduatedError') return await markGraduated(position.id, tag);
+ throw err;
+ }
+
+ let sig = 'SIMULATED';
+ if (cfg.mode === 'live') {
+ sig = await signAndSend(ctx, keypair, built.instructions, cfg.confirmTimeoutMs);
+ } else {
+ expectedOut = BigInt(built.expectedQuoteOut.toString());
+ }
+
+ const entry = BigInt(position.entry_quote_lamports || '0');
+ const pnl = expectedOut - entry;
+ const pnlPct = entry > 0n ? (Number(pnl) / Number(entry)) * 100 : 0;
+ await sql`
+ UPDATE agent_sniper_positions SET
+ status = 'closed', exit_reason = ${reason}, sell_sig = ${sig},
+ exit_quote_lamports = ${expectedOut.toString()},
+ realized_pnl_lamports = ${pnl.toString()},
+ realized_pnl_pct = ${pnlPct},
+ closed_at = now()
+ WHERE id = ${position.id}
+ `;
+ log.trade('sell', { ...tag, mode: cfg.mode, sig, pnl_sol: lamportsToSol(pnl), pnl_pct: pnlPct.toFixed(1) });
+ return { status: 'closed', sig, pnl: pnl.toString() };
+ } catch (err) {
+ // A failed sell must NOT terminate the position — leave it 'open' so the
+ // next tick retries the exit rather than stranding the bag as 'failed'.
+ await sql`UPDATE agent_sniper_positions SET status = 'open', error = ${errCode(err)}, last_quoted_at = now() WHERE id = ${position.id}`;
+ log.warn('sell failed (will retry)', { ...tag, code: errCode(err), err: err?.message });
+ return { status: 'retry', reason: errCode(err) };
+ }
+ });
+}
+
+async function markGraduated(posId, tag) {
+ // Bonding-curve sell is impossible post-graduation. Flag for the AMM-exit
+ // fast-follow and stop re-quoting (getOpenPositions excludes 'graduated%').
+ await sql`
+ UPDATE agent_sniper_positions
+ SET error = 'graduated:awaiting_amm_exit', exit_reason = 'graduated', last_quoted_at = now()
+ WHERE id = ${posId}
+ `;
+ log.warn('position graduated — needs AMM exit', tag);
+ return { status: 'graduated' };
+}
+
+function skip(tag, reason) {
+ log.info('skip', { ...tag, reason });
+ return { status: 'skip', reason };
+}
+
+async function fail(posId, tag, reason, err) {
+ await sql`UPDATE agent_sniper_positions SET status = 'failed', error = ${reason}, closed_at = now() WHERE id = ${posId}`;
+ log.warn('buy aborted', { ...tag, reason, err: err?.message });
+ return { status: 'failed', reason };
+}
+
+function errCode(err) {
+ return err?.code || err?.name || 'error';
+}
+
+function lamportsToSol(l) {
+ return Number(BigInt(l)) / 1e9;
+}
diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.js
new file mode 100644
index 000000000..665a58883
--- /dev/null
+++ b/workers/agent-sniper/index.js
@@ -0,0 +1,144 @@
+// agent-sniper — autonomous pump.fun sniper worker (entrypoint).
+//
+// Holds the PumpPortal new-mint feed open, scores each launch against every
+// armed agent strategy, and snipes from the agent's own wallet. A second loop
+// manages open positions to their exit. This is a long-lived process — NOT a
+// Vercel cron (hourly is far too slow to snipe). Run: node workers/agent-sniper.
+//
+// SNIPER_MODE=simulate — real quotes, no broadcast (default, safe)
+// SNIPER_MODE=live — real trades from agent wallets
+// SNIPER_GLOBAL_KILL=1 — halt new buys; positions still managed/exited
+
+import { connectPumpFunFeed } from '../../api/_lib/pumpfun-ws-feed.js';
+import { loadConfig } from './config.js';
+import { log } from './log.js';
+import { refreshStrategies, cachedStrategies, logStrategyLoad } from './strategy-store.js';
+import { scoreMint } from './scorer.js';
+import { executeBuy } from './executor.js';
+import { runPositionSweep } from './positions.js';
+
+// ── global buy throttle (sliding 60s window) ─────────────────────────────────
+function makeThrottle(maxPerMin) {
+ const hits = [];
+ return {
+ tryConsume() {
+ if (maxPerMin <= 0) return true;
+ const now = Date.now();
+ while (hits.length && now - hits[0] > 60_000) hits.shift();
+ if (hits.length >= maxPerMin) return false;
+ hits.push(now);
+ return true;
+ },
+ };
+}
+
+// ── bounded buy queue (cap concurrent snipe attempts → bounded RPC) ──────────
+function makeQueue(concurrency, maxDepth) {
+ let active = 0;
+ const q = [];
+ const pump = () => {
+ while (active < concurrency && q.length) {
+ const job = q.shift();
+ active++;
+ Promise.resolve()
+ .then(job)
+ .catch((err) => log.error('buy job crashed', { err: err?.message }))
+ .finally(() => { active--; pump(); });
+ }
+ };
+ return {
+ push(job) {
+ if (q.length >= maxDepth) { log.warn('buy queue full — dropping snipe', { depth: q.length }); return; }
+ q.push(job);
+ pump();
+ },
+ get inFlight() { return active + q.length; },
+ };
+}
+
+async function main() {
+ const cfg = loadConfig();
+ log.info('boot', { network: cfg.network, mode: cfg.mode, globalKill: cfg.globalKill, pollMs: cfg.pollMs });
+
+ const throttle = makeThrottle(cfg.maxGlobalBuysPerMin);
+ const queue = makeQueue(3, 50);
+ let draining = false;
+ let lastEventAt = Date.now();
+
+ await refreshStrategies(cfg.network, 0).then(() => logStrategyLoad(cfg.network)).catch((err) =>
+ log.error('initial strategy load failed', { err: err?.message }),
+ );
+
+ const onEvent = ({ kind, data }) => {
+ lastEventAt = Date.now();
+ if (kind !== 'mint' || draining || cfg.globalKill) return;
+ const strategies = cachedStrategies();
+ for (const strat of strategies) {
+ const { pass, reasons } = scoreMint(data, strat);
+ if (!pass) continue;
+ log.info('candidate', { agent: strat.agent_id, mint: data.mint, symbol: data.symbol, reasons });
+ queue.push(() => executeBuy({ cfg, strat, mint: data, throttle }));
+ }
+ };
+
+ const abort = new AbortController();
+ let stopFeed = connectPumpFunFeed({ kind: 'mint', signal: abort.signal, onEvent });
+ log.info('feed connected', {});
+
+ // Strategy cache refresh.
+ const strategyTimer = setInterval(() => {
+ refreshStrategies(cfg.network, cfg.strategyRefreshMs)
+ .then(() => logStrategyLoad(cfg.network))
+ .catch((err) => log.error('strategy refresh failed', { err: err?.message }));
+ }, cfg.strategyRefreshMs);
+
+ // Position lifecycle sweep — overlap-guarded so a slow sweep can't stack.
+ let sweeping = false;
+ const positionTimer = setInterval(async () => {
+ if (sweeping || draining) return;
+ sweeping = true;
+ try { await runPositionSweep(cfg); } finally { sweeping = false; }
+ }, cfg.pollMs);
+
+ // Feed watchdog: connectPumpFunFeed stops after 5 drops; if the feed goes
+ // quiet past the threshold, tear down and re-subscribe so the brain never
+ // silently goes deaf.
+ const watchdogTimer = setInterval(() => {
+ if (draining) return;
+ if (Date.now() - lastEventAt > cfg.feedWatchdogMs) {
+ log.warn('feed silent — re-subscribing', { silentMs: Date.now() - lastEventAt });
+ try { stopFeed?.(); } catch {}
+ lastEventAt = Date.now();
+ const a2 = new AbortController();
+ abort.signal.addEventListener('abort', () => a2.abort());
+ stopFeed = connectPumpFunFeed({ kind: 'mint', signal: a2.signal, onEvent });
+ }
+ }, Math.min(cfg.feedWatchdogMs, 60_000));
+
+ const shutdown = async (signal) => {
+ if (draining) return;
+ draining = true;
+ log.info('shutdown', { signal, inFlight: queue.inFlight });
+ clearInterval(strategyTimer);
+ clearInterval(positionTimer);
+ clearInterval(watchdogTimer);
+ try { stopFeed?.(); } catch {}
+ abort.abort();
+ // Give in-flight buys a moment to settle (Neon HTTP is stateless — nothing
+ // else to close).
+ const deadline = Date.now() + 10_000;
+ while (queue.inFlight > 0 && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 200));
+ }
+ log.info('bye', { inFlight: queue.inFlight });
+ process.exit(0);
+ };
+ process.on('SIGINT', () => shutdown('SIGINT'));
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
+ process.on('unhandledRejection', (err) => log.error('unhandledRejection', { err: err?.message }));
+}
+
+main().catch((err) => {
+ log.error('fatal', { err: err?.message, stack: err?.stack });
+ process.exit(1);
+});
diff --git a/workers/agent-sniper/keys.js b/workers/agent-sniper/keys.js
new file mode 100644
index 000000000..beb53a337
--- /dev/null
+++ b/workers/agent-sniper/keys.js
@@ -0,0 +1,49 @@
+// agent-sniper — agent keypair loading with an in-process TTL cache.
+//
+// A long-lived worker would otherwise re-decrypt an agent's Solana secret on
+// every trade. We cache the decrypted Keypair for a short TTL keyed by agentId.
+// Each *decrypt* still writes a usage_events audit row (via the audit arg to
+// recoverSolanaAgentKeypair); cache hits do not, which is correct — no key
+// material left the process on a hit. Keypairs are never logged.
+
+import { sql } from '../../api/_lib/db.js';
+import { recoverSolanaAgentKeypair } from '../../api/_lib/agent-wallet.js';
+
+const TTL_MS = 5 * 60_000;
+const _cache = new Map(); // agentId → { keypair, at }
+
+/**
+ * Load the signing Keypair for an agent the sniper already owns a strategy for.
+ * Returns null if the agent has no provisioned Solana wallet (the sniper never
+ * auto-provisions — an unfunded fresh wallet can't trade anyway).
+ *
+ * @param {string} agentId
+ * @param {string} userId the strategy owner (for the audit trail)
+ * @param {string} reason
+ * @returns {Promise<{ keypair: import('@solana/web3.js').Keypair, address: string } | null>}
+ */
+export async function loadAgentKeypair(agentId, userId, reason = 'sniper_trade') {
+ const hit = _cache.get(agentId);
+ if (hit && Date.now() - hit.at < TTL_MS) {
+ return { keypair: hit.keypair, address: hit.keypair.publicKey.toBase58() };
+ }
+
+ const [row] = await sql`
+ SELECT meta FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ const meta = row?.meta || null;
+ if (!meta?.encrypted_solana_secret || !meta?.solana_address) return null;
+
+ const keypair = await recoverSolanaAgentKeypair(meta.encrypted_solana_secret, {
+ agentId,
+ userId,
+ reason,
+ });
+ _cache.set(agentId, { keypair, at: Date.now() });
+ return { keypair, address: keypair.publicKey.toBase58() };
+}
+
+export function clearKeyCache() {
+ _cache.clear();
+}
diff --git a/workers/agent-sniper/package.json b/workers/agent-sniper/package.json
new file mode 100644
index 000000000..280de68a8
--- /dev/null
+++ b/workers/agent-sniper/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "@three-ws/agent-sniper",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "description": "Autonomous pump.fun sniper worker — watches the live feed, snipes from agent wallets, manages exits.",
+ "main": "index.js",
+ "scripts": {
+ "start": "node index.js",
+ "simulate": "SNIPER_MODE=simulate node index.js",
+ "live": "SNIPER_MODE=live node index.js"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+}
diff --git a/workers/agent-sniper/positions.js b/workers/agent-sniper/positions.js
new file mode 100644
index 000000000..030c1d8be
--- /dev/null
+++ b/workers/agent-sniper/positions.js
@@ -0,0 +1,95 @@
+// agent-sniper — position lifecycle loop.
+//
+// Every cfg.pollMs: re-quote each open position's current SOL value off the
+// bonding curve, update the high-water mark, and exit on stop-loss / trailing
+// stop / take-profit / timeout (evaluated in that priority order). Pricing is
+// authoritative on-chain (quoteForSell), so it needs no per-mint trade feed.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+import { getTradeCtx } from './trade-client.js';
+import { getOpenPositions } from './strategy-store.js';
+import { executeSell } from './executor.js';
+
+function pct(n) {
+ const x = Number(n);
+ return Number.isFinite(x) ? x : null;
+}
+
+/** Decide the exit reason for a position, or null to hold. */
+function decideExit(pos, value, peak) {
+ const entry = BigInt(pos.entry_quote_lamports || '0');
+ if (entry <= 0n) return null;
+ const ev = Number(entry);
+ const sl = pct(pos.stop_loss_pct);
+ const ts = pct(pos.trailing_stop_pct);
+ const tp = pct(pos.take_profit_pct);
+
+ if (sl != null && value <= ev * (1 - sl / 100)) return 'stop_loss';
+ if (ts != null && peak > 0 && value <= peak * (1 - ts / 100)) return 'trailing_stop';
+ if (tp != null && value >= ev * (1 + tp / 100)) return 'take_profit';
+
+ const heldS = (Date.now() - new Date(pos.opened_at).getTime()) / 1000;
+ if (pos.max_hold_seconds != null && heldS >= pos.max_hold_seconds) return 'timeout';
+ return null;
+}
+
+async function tickPosition(cfg, pos) {
+ // Kill-switch flipped while holding → exit at market now.
+ if (pos.kill_switch) {
+ await executeSell({ cfg, position: pos, reason: 'kill_switch' });
+ return;
+ }
+
+ const ctx = await getTradeCtx(cfg.network);
+ const mintPk = new ctx.web3.PublicKey(pos.mint);
+ const baseAmount = new ctx.BN(BigInt(pos.base_amount).toString());
+ const slippagePct = (pos.slippage_bps ?? 500) / 100;
+
+ let value;
+ try {
+ const quote = await ctx.client.quoteForSell({ mint: mintPk, baseAmount, slippagePct });
+ value = Number(quote.expectedQuoteOut.toString());
+ } catch (err) {
+ if (err?.name === 'CoinGraduatedError') {
+ await sql`
+ UPDATE agent_sniper_positions
+ SET error = 'graduated:awaiting_amm_exit', exit_reason = 'graduated', last_quoted_at = now()
+ WHERE id = ${pos.id}
+ `;
+ log.warn('position graduated — needs AMM exit', { agent: pos.agent_id, mint: pos.mint });
+ return;
+ }
+ log.warn('position re-quote failed', { mint: pos.mint, err: err?.message });
+ return;
+ }
+
+ const prevPeak = Number(pos.peak_value_lamports || pos.entry_quote_lamports || 0);
+ const peak = Math.max(prevPeak, value);
+ await sql`
+ UPDATE agent_sniper_positions
+ SET last_value_lamports = ${Math.round(value)}, peak_value_lamports = ${Math.round(peak)}, last_quoted_at = now()
+ WHERE id = ${pos.id}
+ `;
+
+ const reason = decideExit(pos, value, peak);
+ if (reason) await executeSell({ cfg, position: pos, reason });
+}
+
+/** Run one sweep over all open positions. Errors on one position never abort the rest. */
+export async function runPositionSweep(cfg) {
+ let positions;
+ try {
+ positions = await getOpenPositions(cfg.network);
+ } catch (err) {
+ log.error('open-position query failed', { err: err?.message });
+ return;
+ }
+ for (const pos of positions) {
+ try {
+ await tickPosition(cfg, pos);
+ } catch (err) {
+ log.error('position tick failed', { mint: pos.mint, err: err?.message });
+ }
+ }
+}
diff --git a/workers/agent-sniper/scorer.js b/workers/agent-sniper/scorer.js
new file mode 100644
index 000000000..77842119b
--- /dev/null
+++ b/workers/agent-sniper/scorer.js
@@ -0,0 +1,63 @@
+// agent-sniper — entry scoring. Pure, no I/O.
+//
+// Given an enriched mint event (from connectPumpFunFeed) and a strategy row,
+// decide whether the agent should snipe it. Returns { pass, score, reasons }.
+// `reasons` always explains the verdict — kept on skipped events too so the
+// logs show WHY a mint was passed over, which is what you stare at when tuning.
+
+function n(v) {
+ if (v == null) return null;
+ const x = Number(v);
+ return Number.isFinite(x) ? x : null;
+}
+
+/**
+ * @param {object} mint enriched PumpPortal mint event
+ * @param {object} strat agent_sniper_strategies row
+ * @returns {{ pass: boolean, score: number, reasons: string[] }}
+ */
+export function scoreMint(mint, strat) {
+ const reasons = [];
+ let score = 0;
+
+ // ── hard filters (any failure → skip) ────────────────────────────────────
+ if (strat.require_sol_quote && mint.is_usdc_pair) {
+ return { pass: false, score: 0, reasons: ['quote_not_sol'] };
+ }
+
+ const mcUsd = n(mint.market_cap_usd);
+ const minMc = n(strat.min_market_cap_usd);
+ const maxMc = n(strat.max_market_cap_usd);
+ if (minMc != null && (mcUsd == null || mcUsd < minMc)) {
+ return { pass: false, score: 0, reasons: ['mc_below_min'] };
+ }
+ if (maxMc != null && mcUsd != null && mcUsd > maxMc) {
+ return { pass: false, score: 0, reasons: ['mc_above_max'] };
+ }
+
+ const launches = n(mint.creator_launches);
+ const graduated = n(mint.creator_graduated);
+ const maxLaunches = n(strat.max_creator_launches);
+ const minGrad = n(strat.min_creator_graduated);
+ // Serial-rugger guard: many launches, none graduated.
+ if (maxLaunches != null && launches != null && launches > maxLaunches) {
+ return { pass: false, score: 0, reasons: ['creator_too_many_launches'] };
+ }
+ if (minGrad != null && (graduated == null || graduated < minGrad)) {
+ return { pass: false, score: 0, reasons: ['creator_too_few_graduated'] };
+ }
+
+ const hasSocials = !!(mint.twitter || mint.telegram || mint.website);
+ if (strat.require_socials && !hasSocials) {
+ return { pass: false, score: 0, reasons: ['no_socials'] };
+ }
+
+ // ── soft signals (contribute to score; tie-break / future ranking) ───────
+ if (hasSocials) { score += 1; reasons.push('has_socials'); }
+ if (graduated != null && graduated > 0) { score += graduated; reasons.push(`creator_graduated:${graduated}`); }
+ const initBuy = n(mint.initial_buy_sol);
+ if (initBuy != null && initBuy >= 1) { score += 1; reasons.push(`initial_buy:${initBuy.toFixed(2)}sol`); }
+ if (mcUsd != null) reasons.push(`mc_usd:${Math.round(mcUsd)}`);
+
+ return { pass: true, score, reasons };
+}
diff --git a/workers/agent-sniper/strategy-store.js b/workers/agent-sniper/strategy-store.js
new file mode 100644
index 000000000..7519a52c0
--- /dev/null
+++ b/workers/agent-sniper/strategy-store.js
@@ -0,0 +1,75 @@
+// agent-sniper — strategy + position reads (cached strategy list, position counts).
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+
+let _strategies = [];
+let _loadedAt = 0;
+
+/**
+ * Active strategies for the worker's network: enabled, not killed, with a real
+ * budget and a positive stop-loss. The stop-loss filter is the runtime half of
+ * the mandatory-SL guarantee (the DB constraint is the other half) — a strategy
+ * that somehow has a null/zero SL is dropped here rather than trusted.
+ */
+export async function refreshStrategies(network, maxAgeMs) {
+ if (Date.now() - _loadedAt < maxAgeMs && _strategies.length) return _strategies;
+ const rows = await sql`
+ SELECT * FROM agent_sniper_strategies
+ WHERE network = ${network}
+ AND enabled = true
+ AND kill_switch = false
+ AND daily_budget_lamports > 0
+ AND per_trade_lamports > 0
+ AND stop_loss_pct > 0
+ `;
+ _strategies = rows;
+ _loadedAt = Date.now();
+ return _strategies;
+}
+
+export function cachedStrategies() {
+ return _strategies;
+}
+
+/** Count an agent's positions that still hold (or are mid-open) on this network. */
+export async function countOpenPositions(agentId, network) {
+ const [r] = await sql`
+ SELECT count(*)::int AS n FROM agent_sniper_positions
+ WHERE agent_id = ${agentId} AND network = ${network}
+ AND status IN ('opening','open','closing')
+ `;
+ return r?.n ?? 0;
+}
+
+/** Lamports committed by an agent today (UTC) — the daily-budget denominator. */
+export async function getDailySpend(agentId, network) {
+ const [r] = await sql`
+ SELECT coalesce(sum(entry_quote_lamports), 0)::text AS spent
+ FROM agent_sniper_positions
+ WHERE agent_id = ${agentId} AND network = ${network}
+ AND opened_at >= date_trunc('day', now())
+ AND status <> 'failed'
+ `;
+ return BigInt(r?.spent ?? '0');
+}
+
+/** Open positions across all agents — the position-loop work set. */
+export async function getOpenPositions(network) {
+ return sql`
+ SELECT p.*, s.take_profit_pct, s.stop_loss_pct, s.trailing_stop_pct,
+ s.max_hold_seconds, s.slippage_bps, s.user_id AS strat_user_id,
+ s.kill_switch
+ FROM agent_sniper_positions p
+ JOIN agent_sniper_strategies s ON s.id = p.strategy_id
+ WHERE p.network = ${network}
+ AND p.status = 'open'
+ AND (p.error IS NULL OR p.error NOT LIKE 'graduated%')
+ ORDER BY p.opened_at ASC
+ LIMIT 200
+ `;
+}
+
+export function logStrategyLoad(network) {
+ log.info('strategies refreshed', { network, count: _strategies.length });
+}
diff --git a/workers/agent-sniper/trade-client.js b/workers/agent-sniper/trade-client.js
new file mode 100644
index 000000000..3cdc7d148
--- /dev/null
+++ b/workers/agent-sniper/trade-client.js
@@ -0,0 +1,60 @@
+// agent-sniper — pump.fun trade client + transaction broadcast.
+//
+// Thin wrapper over the platform's PumpTradeClient (api/_lib/pump.js, which
+// resolves the right RPC and the @three-ws/agent-payments build) plus a single
+// place that assembles, signs with the AGENT's keypair, and broadcasts a v0 tx.
+// Mirrors the sign+send flow used by handleRunBuyback in api/cron/[name].js.
+
+import { getPumpTradeClient } from '../../api/_lib/pump.js';
+
+let _ctx = null;
+
+/** Lazily build (and reuse) the trade client + connection for a network. */
+export async function getTradeCtx(network) {
+ if (_ctx && _ctx.network === network) return _ctx;
+ const { client, connection, BN, web3 } = await getPumpTradeClient({ network });
+ _ctx = { network, client, connection, BN, web3 };
+ return _ctx;
+}
+
+/**
+ * Assemble a v0 transaction from instructions, sign with `payer`, broadcast,
+ * and wait for confirmation. Returns the signature.
+ *
+ * @param {object} ctx result of getTradeCtx
+ * @param {import('@solana/web3.js').Keypair} payer
+ * @param {import('@solana/web3.js').TransactionInstruction[]} instructions
+ * @param {number} confirmTimeoutMs
+ */
+export async function signAndSend(ctx, payer, instructions, confirmTimeoutMs) {
+ const { connection, web3 } = ctx;
+ const { TransactionMessage, VersionedTransaction } = web3;
+
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ const msg = new TransactionMessage({
+ payerKey: payer.publicKey,
+ recentBlockhash: blockhash,
+ instructions,
+ }).compileToV0Message();
+ const tx = new VersionedTransaction(msg);
+ tx.sign([payer]);
+
+ const sig = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ maxRetries: 3,
+ });
+
+ // Bound the confirmation wait so a stuck tx can't pin the loop forever.
+ const confirmPromise = connection.confirmTransaction(
+ { signature: sig, blockhash, lastValidBlockHeight },
+ 'confirmed',
+ );
+ const timeout = new Promise((_, rej) =>
+ setTimeout(() => rej(Object.assign(new Error('confirm timeout'), { code: 'CONFIRM_TIMEOUT', sig })), confirmTimeoutMs),
+ );
+ const result = await Promise.race([confirmPromise, timeout]);
+ if (result?.value?.err) {
+ throw Object.assign(new Error(`tx failed on-chain: ${JSON.stringify(result.value.err)}`), { code: 'TX_ERR', sig });
+ }
+ return sig;
+}