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.

Add Agent Sniper documentation and tutorial; implement Mixamo avatar fetching script

nirholas898b8eb9efd2
diff --git a/.gitignore b/.gitignore
index d2f24a942..657e61570 100644
--- a/.gitignore
+++ b/.gitignore
@@ -382,3 +382,6 @@ prompts/robinhood-chain/11-toolkit-cli.md
# archives at repo root are never committed
/*.zip
tests/openai-comarketing-language.test.js
+
+# scratch OTP relay file used by scripts/get-mixamo-token.mjs
+.mixamo-otp
diff --git a/blog/external-autonomous-trading-agent-draft.md b/blog/external-autonomous-trading-agent-draft.md
new file mode 100644
index 000000000..485b02050
--- /dev/null
+++ b/blog/external-autonomous-trading-agent-draft.md
@@ -0,0 +1,65 @@
+# [EXTERNAL SYNDICATION DRAFT] Anatomy of an Autonomous Trading Agent: Gates, Ledgers, and a Firewall That Simulates the Sell Before the Buy
+
+<!--
+ Publication routing (owner action required to post externally):
+ - Target channels, in order of fit: HackerNoon (crypto-native, we have a
+ partnership), AWS Builder Center (we have published there before; frame is
+ architecture, not tokens), a dev.to mirror.
+ - Do NOT post to the IBM Community group. Verified policy in
+ docs/ops/seo-keyword-plan.md: crypto/pump.fun content is off-topic for that
+ audience, is exactly the pattern Google's site-reputation-abuse policy
+ targets, and would put the IBM partnership at risk. IBM Community stays
+ watsonx/Granite tutorials only.
+ - Set the canonical URL on the external platform to:
+ https://three.ws/blog/first-autonomous-trade
+ - This draft is engineering-first: the token is incidental, the architecture
+ is the story. Numbers are real and verifiable on-chain.
+-->
+
+Autonomous agents that hold money are easy to demo and hard to trust. The demo is an LLM with a wallet key. The trust problem is everything else: how do you let software trade unattended against the most adversarial market on the internet (brand-new token launches, where most assets are designed to steal from you) without it getting drained by the first honeypot it meets?
+
+We run a platform (three.ws) where AI agents own Solana wallets and can be armed to trade autonomously. Last week one of them closed its first unattended position: bought a token that was seconds old, sold 30 minutes later, up 42.38%. The trade itself is a rounding error (0.05 SOL committed). The architecture that produced it is the part worth writing down, including the one thing it got right by luck instead of design.
+
+## The core idea: a chain of deterministic gates, and only one file that signs
+
+The agent does not "decide to trade" in any freeform sense. A trade is the output of a pipeline where every stage can veto and no stage can be skipped:
+
+1. **Event-driven trigger.** A long-lived worker holds the token-launch firehose open over a websocket and evaluates each launch the moment it exists. This is deliberately not a cron job: a periodic tick cannot catch a launch window measured in seconds.
+2. **Pure-function entry scoring.** The strategy row (owner-armed policy: market-cap band, socials requirement, creator-history checks, sizing) is evaluated by a side-effect-free scorer that returns `{ pass, score, reasons }`. The `reasons` array is kept for skipped coins too. When your bot mostly does nothing (and a selective one mostly should), the skip log with a reason per rejection is what makes the silence auditable instead of alarming.
+3. **Fleet-wide safety bands.** Operator-level clamps that individual strategies can tighten but never loosen, and that fail closed: a coin whose market cap cannot be determined is rejected, never bought blind.
+4. **Category exclusions read from the chain.** Some launch types are banned outright. The flag we need is not in the feed, so it is read from the on-chain bonding-curve account, cached per mint.
+5. **The trade firewall: simulate the sell before the buy.** This is the load-bearing safety idea. Before broadcasting anything, the executor runs a real on-chain simulation of a buy immediately followed by a sell. A token that cannot be sold back is a honeypot; a round trip with abnormal loss indicates rug mechanics. Either aborts the buy. The scam does not need to be recognized by pattern matching; it is detected by attempting the thing the scam prevents.
+6. **A single signing chokepoint.** Exactly one module can decrypt the agent's key (AES-256-GCM at rest, per-record salts) and sign. Every guardrail (budget ceilings, concurrent-position caps, idempotency locks so a mint is bought at most once per strategy) lives at that chokepoint, so no alternate code path can spend.
+
+## The part most trading bots skip: a hash-chained decision ledger
+
+Every trade appends a record to an append-only ledger: the inputs (trigger, firewall verdict and score, price impact, size), a plain-language rationale, a falsifiable prediction ("realized PnL will be positive"), and a mechanically computed confidence. Each entry carries the hash of the previous one, so history cannot be silently rewritten.
+
+The entry for this trade, verbatim as the agent wrote it:
+
+> "Sniped $BITS on a new_mint trigger with 0.05% price impact; firewall verdict allow (score 100). Committed 0.0500 SOL expecting a profitable exit." (confidence: 0.698)
+
+When we wrote the postmortem, nothing had to be reconstructed from logs or memory. The agent's contemporaneous account of its own reasoning, chained to its prior history and adjacent to the real transaction signatures, was the postmortem. If you are building agents that act in the world, this property is worth more than any single win: the system's story of what it did is checkable, line by line, against what actually happened on-chain.
+
+## What the first live trade taught us
+
+The numbers: entry at 02:26:00 UTC with 0.05 SOL and 0.05% price impact, transaction landed in 1.7 seconds; peak +46.5%; exit at 02:56:04 UTC, full position, +42.38% realized. Exits are decided by a pure function with a strict priority ladder: stop-loss, then trailing stop, then take-profit, then timeout.
+
+The honest finding: the exit reason was `timeout`. The owner had armed stops and a 30-minute maximum hold but no take-profit. So when the position spiked to +46.5%, no rule existed to lock it in; the clock expired and the position happened to still be up 42%. The trade won on luck-shaped policy. One unset field was the difference between "we designed this exit" and "the clock saved us", which is why the take-profit lesson is now the first thing our tutorial teaches.
+
+The other honest finding: nine days of silence preceded the trade. Thousands of launches were evaluated and skipped, each with a logged reason. That is the correct behavior for a selective strategy in a market where most new assets are traps, but it means our sample size is exactly one. We are publishing the trade as an existence proof of the pipeline, not as evidence of an edge.
+
+## Where it goes next: models propose, the pipeline disposes
+
+The strategy that made this trade is frozen policy: constants a human set nine days earlier, unable to react to anything. The next phase, currently in progress, puts an LLM strategist above the same execution stack:
+
+- On a cadence, a reasoning model reads live market state (launch cadence, quality-score distributions from the platform's coin-intelligence engine, the agent's own recent ledger outcomes) and emits a strategy adjustment as structured output: the same typed fields a human tunes, never freeform code.
+- Adjustments land in the same hash-chained ledger with the model's rationale and a falsifiable prediction, so hand-tuned and model-tuned policies are comparable entry by entry.
+- The deterministic layer stays sovereign. The firewall, the fail-closed safety bands, the budget caps, and the signing chokepoint apply to a model-tuned strategy identically. A model can make the policy smarter; it cannot make the system less safe.
+- Competing configurations run head to head with real but capped budgets, and their ledgers decide which policy survives. Results get published either way, because the loss postmortems are where the information is.
+
+The design principle generalizes well beyond trading: give the model the steering wheel, never the brakes. Deterministic gates that fail closed, one signing chokepoint, and an append-only reasoning ledger turn "an LLM with a wallet" into a system you can audit, and eventually, trust.
+
+---
+
+*The full engineering breakdown, the live case-study data, and the tutorial for arming an agent are at [three.ws/docs/agent-sniper](https://three.ws/docs/agent-sniper). Original post: [three.ws/blog/first-autonomous-trade](https://three.ws/blog/first-autonomous-trade).*
diff --git a/blog/first-autonomous-trade.html b/blog/first-autonomous-trade.html
new file mode 100644
index 000000000..59f66602b
--- /dev/null
+++ b/blog/first-autonomous-trade.html
@@ -0,0 +1,130 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Our Agent Made Its First Autonomous Trade. Here Is Every Decision It Took.</title>
+ <meta name="description" content="A three.ws agent sniped a brand-new pump.fun launch and closed it at +42.38%, fully autonomously. The full postmortem: every gate it passed, the on-chain receipts, what was luck, what was design, and the LLM-piloted strategist we are building next.">
+ <meta name="keywords" content="autonomous trading agent, AI agent trading, pump.fun sniper, Solana trading bot, agent wallet, on-chain AI agent, decision ledger, trade firewall, three.ws">
+ <link rel="canonical" href="https://three.ws/blog/first-autonomous-trade">
+
+ <meta property="og:title" content="Our Agent Made Its First Autonomous Trade. Here Is Every Decision It Took.">
+ <meta property="og:description" content="A three.ws agent sniped a new pump.fun launch and closed at +42.38%, autonomously. The full postmortem with on-chain receipts: what was luck, what was design, and what we build next.">
+ <meta property="og:url" content="https://three.ws/blog/first-autonomous-trade">
+ <meta property="og:type" content="article">
+ <meta property="og:image" content="https://three.ws/og-image.png">
+
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:title" content="Our Agent Made Its First Autonomous Trade. Here Is Every Decision It Took.">
+ <meta name="twitter:description" content="A three.ws agent sniped a new pump.fun launch and closed at +42.38%, autonomously. The full postmortem with on-chain receipts.">
+ <meta name="twitter:image" content="https://three.ws/og-image.png">
+
+ <link rel="shortcut icon" href="/favicon.ico">
+ <link rel="stylesheet" href="/nav.css">
+ <link rel="stylesheet" href="/footer.css">
+ <style>
+ :root { color-scheme: dark; }
+ body { margin: 0; background: #060611; color: #e7e7f5; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }
+ .post-wrap { max-width: 720px; margin: 0 auto; padding: 96px 24px 80px; }
+ .post-meta { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; color: #7a85a8; font-size: 13px; margin-bottom: 28px; }
+ .post-date { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
+ .post-tag { padding: 2px 8px; border-radius: 999px; background: rgba(154,212,255,.08); color: #9ad4ff; font-size: 11px; font-weight: 500; letter-spacing: 0.02em; text-transform: uppercase; }
+ h1 { font-size: clamp(26px, 4vw, 40px); font-weight: 700; letter-spacing: -0.02em; line-height: 1.2; margin: 0 0 20px; }
+ h2 { font-size: 20px; font-weight: 600; margin: 40px 0 12px; letter-spacing: -0.01em; }
+ p { color: #c8c8e0; line-height: 1.7; margin: 0 0 18px; font-size: 16px; }
+ ul, ol { color: #c8c8e0; line-height: 1.7; margin: 0 0 18px; padding-left: 24px; font-size: 16px; }
+ li { margin-bottom: 6px; }
+ a { color: #9ad4ff; text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; background: rgba(154,212,255,.07); color: #9ad4ff; padding: 2px 6px; border-radius: 4px; word-break: break-all; }
+ strong { color: #e7e7f5; }
+ blockquote { margin: 0 0 18px; padding: 14px 18px; border-left: 3px solid #9ad4ff; background: rgba(154,212,255,.05); border-radius: 0 8px 8px 0; color: #c8c8e0; font-size: 15px; line-height: 1.7; }
+ .trade-table { width: 100%; border-collapse: collapse; margin: 0 0 18px; font-size: 14px; }
+ .trade-table th, .trade-table td { text-align: left; padding: 8px 10px; border-bottom: 1px solid rgba(255,255,255,.07); color: #c8c8e0; vertical-align: top; }
+ .trade-table th { color: #7a85a8; font-weight: 500; white-space: nowrap; }
+ .table-scroll { overflow-x: auto; }
+ .post-back { display: inline-flex; align-items: center; gap: 6px; color: #7a85a8; font-size: 14px; margin-bottom: 40px; text-decoration: none; }
+ .post-back:hover { color: #9ad4ff; }
+ hr { border: none; border-top: 1px solid rgba(255,255,255,.08); margin: 40px 0; }
+ .post-cta { display: inline-flex; align-items: center; gap: 8px; padding: 12px 22px; border-radius: 10px; background: linear-gradient(120deg, #ffb454, #ff6ad5 60%, #8b5cf6); color: #060611; font-weight: 600; font-size: 15px; text-decoration: none; transition: transform .15s, box-shadow .15s; }
+ .post-cta:hover { text-decoration: none; transform: translateY(-1px); box-shadow: 0 6px 24px rgba(255,106,213,.25); }
+ </style>
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"BlogPosting","headline":"Our Agent Made Its First Autonomous Trade. Here Is Every Decision It Took.","description":"A three.ws agent sniped a brand-new pump.fun launch and closed it at +42.38%, fully autonomously. The full postmortem: every gate it passed, the on-chain receipts, what was luck, what was design, and the LLM-piloted strategist we are building next.","image":"https://three.ws/og-image.png","datePublished":"2026-07-19T12:00:00.000Z","dateModified":"2026-07-19T12:00:00.000Z","author":{"@type":"Organization","name":"three.ws","url":"https://three.ws"},"publisher":{"@type":"Organization","name":"three.ws","url":"https://three.ws","logo":{"@type":"ImageObject","url":"https://three.ws/og-image.png"}},"mainEntityOfPage":{"@type":"WebPage","@id":"https://three.ws/blog/first-autonomous-trade"},"keywords":"autonomous trading agent, AI agent trading, pump.fun sniper, Solana trading bot, agent wallet, on-chain AI agent, decision ledger, trade firewall, three.ws"}</script>
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://three.ws/blog"},{"@type":"ListItem","position":3,"name":"Our Agent Made Its First Autonomous Trade. Here Is Every Decision It Took.","item":"https://three.ws/blog/first-autonomous-trade"}]}</script>
+</head>
+<body>
+ <div id="nav-container"></div>
+ <main class="post-wrap">
+ <a class="post-back" href="/blog">&larr; Blog</a>
+ <div class="post-meta">
+ <span class="post-date">2026-07-19</span>
+ <span class="post-tag">Postmortem</span>
+ <span class="post-tag">Agents</span>
+ <span class="post-tag">Trading</span>
+ </div>
+ <h1>Our Agent Made Its First Autonomous Trade. Here Is Every Decision It Took.</h1>
+
+ <p>At 02:26 UTC on July 19th, an AI agent on three.ws spent 0.05 SOL of its own money on a token that was seconds old. Thirty minutes later it sold, up <strong>42.38%</strong>. No human saw the token, approved the buy, or timed the exit. And because every decision an agent takes here is recorded on a hash-chained ledger next to real on-chain signatures, we can replay the whole thing, gate by gate. This post does exactly that, including the parts that were luck rather than skill.</p>
+
+ <h2>The setup: rules armed nine days earlier</h2>
+ <p>Every three.ws agent has its own custodial Solana wallet. The <a href="/docs/agent-sniper">Agent Sniper</a> lets an owner arm that wallet with a trading policy: which new pump.fun launches qualify, how much to spend, and exactly when to exit. The policy behind this trade was armed on July 10th: 0.05 SOL per trade, 0.2 SOL daily ceiling, one position at a time, only coins in a $5k to $25k market-cap band with real socials, a 30% stop-loss, a 25% trailing stop, and a hard 30-minute maximum hold.</p>
+ <p>Then, for nine days: nothing. The strategy evaluated launch after launch from the live pump.fun firehose and skipped nearly all of them, each skip logged with a reason. That silence is the system working. Most brand-new tokens fail the socials gate, sit outside the band, or fail the safety checks below.</p>
+
+ <h2>The five gates the token passed</h2>
+ <ol>
+ <li><strong>The trigger.</strong> A long-lived worker holds the new-mint feed open and scores coins the second they exist. A launch called $BITS appeared, SOL-quoted, inside the band.</li>
+ <li><strong>The owner's filters.</strong> Socials present, creator had not dumped, market cap in range.</li>
+ <li><strong>The fleet safety band.</strong> Platform-wide market-cap clamps that individual strategies can tighten but never loosen. Unknown market cap fails closed: the sniper never buys what it cannot price.</li>
+ <li><strong>The Mayhem gate.</strong> Pump.fun "Mayhem mode" launches are excluded unconditionally, read straight from the on-chain bonding curve.</li>
+ <li><strong>The trade firewall.</strong> The important one. Before spending anything, the executor ran a <em>real simulated buy-and-sell on-chain</em>. If a token cannot be sold back, it is a honeypot and the buy aborts. The round trip came back clean: verdict <code>allow</code>, score 100.</li>
+ </ol>
+ <p>Only after all five did the agent's key leave its encrypted box to sign. The buy landed in 1.7 seconds with 0.05% price impact, and the agent wrote this to its decision ledger, verbatim:</p>
+ <blockquote>"Sniped $BITS on a new_mint trigger with 0.05% price impact; firewall verdict allow (score 100). Committed 0.0500 SOL expecting a profitable exit." <em>(confidence: 0.698)</em></blockquote>
+
+ <h2>The trade, with receipts</h2>
+ <div class="table-scroll">
+ <table class="trade-table">
+ <tr><th>Entry</th><td>2026-07-19 02:26:00 UTC, 0.05 SOL</td></tr>
+ <tr><th>Peak</th><td>+46.5%</td></tr>
+ <tr><th>Exit</th><td>02:56:04 UTC, full position, reason: <code>timeout</code></td></tr>
+ <tr><th>Realized</th><td><strong>+0.0212 SOL, +42.38%</strong></td></tr>
+ <tr><th>Buy tx</th><td><code>3Y6NqS8CV3K1j5sBZYsuQjpipZeY2wckCz3h99vGA6ZbwJgMpeUjkVm43zffeV52Kc2jWRUn4d4rzcTxoCEGrzRY</code></td></tr>
+ <tr><th>Sell tx</th><td><code>mLmGA7FeHFUEDdQagavVZCH2aExmMssjsVxWiRCSxRZwvbxDS1Xfnvan63ab5FkrKnQ7koEu4yxwgVJYXajeyhH</code></td></tr>
+ </table>
+ </div>
+ <p>Both signatures resolve on any Solana explorer. The position row, the reasoning entry, and the custody events (key recovery, spend, exit) are all in the platform's ledgers, and the wallet's balance is committed into a Merkle attestation every epoch.</p>
+
+ <h2>The honest part: the exit was luck-shaped</h2>
+ <p>Exits run on a strict ladder: stop-loss first, then trailing stop, then take-profit, then timeout. This strategy had <strong>no take-profit configured</strong>. So when the position hit +46.5%, nothing existed to lock that in. The price drifted a few points, the 30-minute clock expired, and the position closed on <code>timeout</code>, still up 42%.</p>
+ <p>It sold because the clock ran out, and it happened to still be winning. A configured take-profit turns that from luck into policy, and that is now the first lesson in <a href="/tutorials/arm-an-agent-sniper">the tutorial</a>. We are publishing the miss along with the win because a 42% first trade teaches nothing if you pretend every part of it was designed.</p>
+ <p>Also worth saying plainly: this is one trade at deliberately tiny size. It is an existence proof that the full pipeline works end to end on mainnet, not a track record. Anyone showing you a single green trade as evidence of an edge is selling something.</p>
+
+ <h2>What we actually learned</h2>
+ <ul>
+ <li><strong>The firewall is the product.</strong> Simulating the sell before the buy is what separates sniping from donating to rug creators. It vetoed quietly for nine days; the one coin it allowed was genuinely sellable.</li>
+ <li><strong>Selectivity feels like silence.</strong> A well-filtered strategy mostly does nothing. The skip log, with a reason per rejected coin, is what makes that trustworthy instead of worrying.</li>
+ <li><strong>Every exit needs a profit rule.</strong> Stops and timeouts protect the downside; only a take-profit or laddered exit converts an upside spike into realized PnL.</li>
+ <li><strong>Auditability changes the conversation.</strong> Because the rationale, confidence, firewall score, and signatures are all on ledgers, this postmortem required zero reconstruction from memory. The agent's story of the trade <em>is</em> the record.</li>
+ </ul>
+
+ <h2>Where this goes: strategies that think</h2>
+ <p>The strategy that made this trade is frozen policy: numbers a human set on July 10th that cannot react to anything. The next phase puts a reasoning model above the same execution stack. An LLM strategist will read live market state (launch cadence, quality-score distributions from our intel engine, the agent's own recent outcomes) and tune the same fields a human tunes today: bands, stops, hold times, sizing. Structured output only, never code.</p>
+ <p>The deterministic layer stays sovereign: the firewall, the safety bands, the budget caps, and the Mayhem exclusion apply to a model-tuned strategy exactly as they do to a hand-tuned one. Models propose; the pipeline disposes. Hand-tuned and LLM-tuned configurations will run head to head with real, capped budgets, and their decision ledgers, win or lose, will be published the same way this one just was.</p>
+
+ <p><a class="post-cta" href="/tutorials/arm-an-agent-sniper">Arm your own agent &rarr;</a></p>
+
+ <h2>Go deeper</h2>
+ <ul>
+ <li>The full engineering breakdown: <a href="/docs/agent-sniper">the Agent Sniper doc</a></li>
+ <li>Watch the intel engine score launches live: <a href="/docs/trading-surfaces">the trading surfaces</a></li>
+ <li>The research policy behind laddered exits: <a href="/docs/trading-experiment">the trading experiment</a></li>
+ </ul>
+
+ <hr>
+ <p><a href="/blog">&larr; All posts</a></p>
+ </main>
+ <div id="footer-container"></div>
+ <script src="/nav.js"></script>
+ <script src="/footer.js"></script>
+</body>
+</html>
diff --git a/blog/index.html b/blog/index.html
index 8f0b6b83a..35c35abce 100644
--- a/blog/index.html
+++ b/blog/index.html
@@ -66,6 +66,19 @@
<ul class="bl-list">
+ <li class="bl-item">
+ <a href="/blog/first-autonomous-trade">
+ <div class="bl-meta">
+ <span class="bl-date">2026-07-19</span>
+ <span class="bl-tag">Postmortem</span>
+ <span class="bl-tag">Agents</span>
+ <span class="bl-tag">Trading</span>
+ </div>
+ <h2 class="bl-title">Our Agent Made Its First Autonomous Trade. Here Is Every Decision It Took.</h2>
+ <p class="bl-summary">A platform agent sniped a brand-new pump.fun launch from its own wallet and exited at +42.38%, fully autonomously. The complete postmortem with on-chain receipts: the five gates the token passed, the firewall that simulates the sell before the buy, the exit that was luck-shaped rather than designed, and the LLM-piloted strategist we build next.</p>
+ </a>
+ </li>
+
<li class="bl-item">
<a href="/blog/concierge-3d-chat-widget">
<div class="bl-meta">
diff --git a/docs/agent-sniper.md b/docs/agent-sniper.md
new file mode 100644
index 000000000..c85025f57
--- /dev/null
+++ b/docs/agent-sniper.md
@@ -0,0 +1,111 @@
+# Agent Sniper: autonomous on-chain trading, fully explained
+
+Every three.ws agent has its own custodial Solana wallet. The Agent Sniper is the subsystem that lets that wallet trade autonomously: it watches the pump.fun launch firehose in real time, scores every new coin against an owner-armed strategy, runs an on-chain safety simulation before committing a single lamport, executes the buy from the agent's own wallet, manages the position through a strict exit ladder, and writes every decision it takes to a hash-chained reasoning ledger you can audit later.
+
+This doc explains the whole system, walks through the first live trade an agent closed on the platform (a real +42.38% exit, receipts included), and lays out where the system goes next.
+
+Related surfaces: [the trading surfaces](./trading-surfaces.md) (Radar, Coin Intelligence, Mission Control), [trading experiment](./trading-experiment.md) (the laddered-exit research policy), [agent wallets](./agent-wallets.md) (how custody works), and the worker itself at `workers/agent-sniper/` (its README is the operator reference).
+
+---
+
+## The pipeline, end to end
+
+A snipe is not one decision. It is a chain of gates, and a coin must pass every one of them:
+
+1. **Trigger.** A long-lived worker holds the PumpPortal new-mint feed open (`trigger: "new_mint"`), or watches for a creator's first-ever fee claim (`trigger: "first_claim"`), or fires from intel/alpha/radar signals. It is deliberately not a cron: a periodic tick cannot snipe a launch.
+2. **Entry scoring** (`workers/agent-sniper/scorer.js`, pure function, no I/O). The coin must be SOL-quoted, inside the strategy's market-cap band, pass creator-history checks, and carry socials if the strategy demands them. Every skip is recorded with a reason string, so you can see why a coin was passed over, not just which ones were bought.
+3. **Fleet safety band.** Worker-level env clamps (`SNIPER_MIN_MC_FLOOR_USD` / `SNIPER_MAX_MC_CEIL_USD`) tighten every strategy at once. A per-strategy bound can only narrow this band, never widen it. Unknown market cap fails closed: the sniper never buys a coin it cannot price.
+4. **Mayhem gate** (`workers/agent-sniper/mayhem-gate.js`). Pump.fun "Mayhem mode" tokens are excluded by owner rule. The flag is not in the firehose, so the worker reads it from the on-chain bonding curve, one cached RPC read per mint.
+5. **Trade firewall** (`api/_lib/trade-firewall.js`). Before broadcasting, the executor runs a real simulated buy-then-sell on-chain. If the token cannot be sold back (honeypot), or the round trip loses abnormally (rug mechanics), the strategy's `firewall_level` decides: `block` aborts the buy, `warn` proceeds with a lowered confidence score.
+6. **Execution** (`workers/agent-sniper/executor.js`, the only file that signs). The agent's key is decrypted from its at-rest AES-256-GCM secret box, the v0 transaction is signed and broadcast with the strategy's slippage and priority-fee settings, and an idempotency lock guarantees one buy per mint per strategy.
+7. **The decision ledger.** Every trade appends an entry to `agent_decisions`: the inputs (trigger, firewall verdict and score, price impact, size), a plain-language rationale, a falsifiable prediction, and a mechanically computed confidence. Entries are hash-chained (`prev_hash` to `entry_hash`), so the reasoning history cannot be silently rewritten.
+8. **Position management** (`workers/agent-sniper/positions.js` + `exit-logic.js`). A sweep re-quotes every open position against the bonding curve (or the AMM after graduation), updates the high-water mark, and decides exits in strict priority order: **stop-loss, then signal-flip, then trailing-stop, then take-profit, then timeout**. The laddered variant recovers initial cost at a configured multiple and lets a moon bag ride the trailing stop.
+9. **Custody audit.** Key recovery, the spend, and the exit each write an `agent_custody_events` row, and the wallet's balance is committed into the platform's custody attestation Merkle tree every epoch.
+
+Nothing in this pipeline is a mock. The firewall simulation is a real on-chain simulation, the buy is a real mainnet transaction, and the ledger rows reference real signatures you can open in any explorer.
+
+## Case study: the first live trade
+
+On 2026-07-19 at 02:26:00 UTC, the platform's own agent ("three", trading from its custodial wallet `3334ZPryymmAuoRx13pBfB2kepL2ULexoirjwqhFKrsc`) sniped a brand-new pump.fun launch on a `new_mint` trigger and closed it 30 minutes later at **+42.38%**.
+
+The full record, straight from the database and the chain:
+
+| Field | Value |
+|---|---|
+| Entry | 2026-07-19 02:26:00 UTC, 0.05 SOL committed |
+| Entry price impact | 0.05% (ceiling was 10%) |
+| Execution | protected route, landed in 1,709 ms, priority fee 1,000 microlamports, no MEV tip |
+| Firewall | simulated buy-and-sell verdict `allow`, score 100 |
+| Ledger confidence | 0.698 |
+| Peak | +46.5% (73,231,688 lamports) |
+| Exit | 2026-07-19 02:56:04 UTC, reason `timeout`, full position |
+| Realized | +21,191,138 lamports = +0.0212 SOL = **+42.38%** |
+| Buy signature | `3Y6NqS8CV3K1j5sBZYsuQjpipZeY2wckCz3h99vGA6ZbwJgMpeUjkVm43zffeV52Kc2jWRUn4d4rzcTxoCEGrzRY` |
+| Sell signature | `mLmGA7FeHFUEDdQagavVZCH2aExmMssjsVxWiRCSxRZwvbxDS1Xfnvan63ab5FkrKnQ7koEu4yxwgVJYXajeyhH` |
+
+The decision-ledger rationale the agent recorded at entry, verbatim:
+
+> "Sniped $BITS on a new_mint trigger with 0.05% price impact; firewall verdict allow (score 100). Committed 0.0500 SOL expecting a profitable exit."
+
+The strategy that produced it was armed on 2026-07-10 with: 0.05 SOL per trade, 0.2 SOL daily budget, one concurrent position, a $5k to $25k market-cap band, socials required, dev-dump avoidance on, firewall on `block`, 30% stop-loss, 25% trailing stop, no take-profit, and a 30-minute maximum hold.
+
+### What the trade actually teaches
+
+Honesty is the point of publishing this, so here is the unvarnished read:
+
+- **The safety stack did its job.** The firewall's simulated round trip is what separates "sniping new launches" from "donating to rug creators". Score 100 meant the token was provably sellable before the buy was broadcast.
+- **The exit was luck-shaped.** The position exited on `timeout`, not on a profit rule. With `take_profit_pct` unset, nothing could lock in the +46.5% peak; the position simply ran out its 30-minute clock while still green. A configured take-profit or a tighter trailing stop converts that from luck into policy.
+- **One trade is not a track record.** This strategy scanned launches for roughly nine days before one coin passed every gate. That selectivity is the system working as designed (most new mints fail the socials gate, the band, or the firewall), but it also means the sample size is one. Treat the 42% as an existence proof of the pipeline, not an expected return.
+- **Small size was correct.** 0.05 SOL per trade meant the whole experiment risked less than a coffee. The pipeline is now proven end to end; size can scale deliberately.
+
+### Audit it yourself
+
+Every layer of the trade above is independently checkable:
+
+- The two transaction signatures resolve on any Solana explorer.
+- The position row lives in `agent_sniper_positions` with entry/exit prices, the peak, and the realized PnL.
+- The reasoning entry lives in `agent_decisions`, hash-chained to the agent's prior history.
+- The spend and key-recovery events live in `agent_custody_events`, and the wallet appears in the epoch custody attestations (`custody_attestation_leaves`).
+
+## Configuration reference
+
+The strategy row (`agent_sniper_strategies`, armed via `POST /api/sniper/strategy`) is the whole policy. The load-bearing fields:
+
+| Field | What it does |
+|---|---|
+| `trigger` | `new_mint`, `first_claim`, `intel_confirmed`, alpha/radar variants |
+| `per_trade_lamports` / `daily_budget_lamports` | Position size and the hard daily spend ceiling |
+| `max_concurrent_positions` | Open-position cap |
+| `min_market_cap_usd` / `max_market_cap_usd` | Entry band; tightened by the fleet-wide safety band |
+| `require_socials` | Reject coins with no Twitter/Telegram/website |
+| `avoid_dev_dump` | Reject coins whose creator already sold (defaults on) |
+| `firewall_level` | `block` (abort on a failed simulation) or `warn` |
+| `slippage_bps` / `max_price_impact_pct` | Execution guards |
+| `stop_loss_pct` | Hard floor below entry, always evaluated first |
+| `trailing_stop_pct` | Percent off the position's high-water mark |
+| `take_profit_pct` | Profit ceiling. **Set this.** Null means winners are only ever closed by the trailing stop or the clock |
+| `max_hold_seconds` | The timeout backstop; closes the position regardless of PnL |
+| `initials_out_multiple` / `moonbag_min_pct` | The laddered exit: recover cost at N times entry, let the rest ride |
+| `kill_switch` / `enabled` | Two independent off switches |
+
+Exit rules are evaluated in a fixed order (stop-loss, signal-flip, trailing-stop, take-profit, timeout) by a pure, unit-tested function (`workers/agent-sniper/exit-logic.js`), so a backtest and the live worker agree on exactly when a position closes.
+
+## Where this goes next
+
+The hard-config sniper is the control group. Its constants (band edges, stop percentages, hold time) are frozen at arm time, which means it cannot react to regime changes: a band that is right at midnight is wrong at noon, and the only fix is a human editing numbers.
+
+The next phase is an **LLM-piloted strategist** running above the same execution stack:
+
+- A reasoning model (via the platform's existing LLM failover chain) periodically reads live market state: launch cadence, graduation rate, intel-engine quality distributions, the agent's own recent ledger outcomes.
+- It emits a strategy adjustment as structured output: the same fields documented above, never freeform code. The deterministic gates (firewall, fleet band, Mayhem exclusion, budget ceilings) stay hard and non-negotiable; the model only tunes what a human owner tunes today.
+- Every adjustment lands in the same hash-chained decision ledger with the model's stated rationale and a falsifiable prediction, so LLM-tuned and hand-tuned strategies are comparable line by line.
+- Configurations run head to head with real, small, capped budgets, and their ledgers decide which policy survives.
+
+The design principle is fixed: **models propose, the deterministic pipeline disposes.** No model output ever bypasses the firewall, the budget caps, or the confirmation gates around irreversible actions.
+
+## Try it
+
+- Arm your first strategy: [the sniper tutorial](/tutorials/arm-an-agent-sniper)
+- Watch the engine think: [Coin Intelligence and the trading surfaces](./trading-surfaces.md)
+- The research policy behind laddered exits: [trading experiment](./trading-experiment.md)
+- The story of the first trade, for non-operators: [the blog post](/blog/first-autonomous-trade)
diff --git a/docs/start-here.md b/docs/start-here.md
index 167e53fe0..42ba50c91 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -80,6 +80,7 @@ Curious what happens between the prompt and the model? [How the Forge works](./h
- **Want a support chat with a face on your own site?** → [Concierge](./concierge.md) — a one-tag chat widget where a rigged 3D avatar lipsyncs streaming answers grounded in your live page, with voice in and out; [the build tutorial](./tutorials/build-a-site-concierge.md) shows how every part works
- **Want a full-body avatar assistant on your site instead?** → [Assistant widget](./assistant-widget.md) — a launcher button opens an animated 3D character standing directly on your page (or a color/gradient), with a free-lane or bring-your-own-key chatbot and a speak mode that says whatever you type, out loud, in a speech bubble
- **Trading?** → [The trading surfaces](./trading-surfaces.md) maps the solo stack (Radar, Coin Intelligence, Live Trade Feed, Watchlist, Mission Control); [trading arenas](./trading-arenas.md) covers tournaments, the theater, vaults, and swarms; [Oracle](./oracle.md) is the conviction engine underneath all of it
+- **Want your agent to trade for you?** → [Agent Sniper](./agent-sniper.md) — the full autonomous-trading pipeline (entry gates, the simulate-the-sell trade firewall, hash-chained decision ledger, exit ladder), with the audited case study of the platform's first live +42% trade; [arm one in minutes](./tutorials/arm-an-agent-sniper.md)
- **Trusting an agent with money?** → [Custody you can verify](./custody.md) — spend limits, freeze, Merkle proof-of-custody, and social recovery; [claim your wallet](./trader-card.md) turns any pump.fun track record into a public, provable Trader Card. Every real-funds feature sits behind the [risk acknowledgment](./risk-acknowledgment.md) — read the [Risk Disclosure](https://three.ws/legal/risk) before committing anything
- **Vetting a counterparty before you pay it?** → [Trust primitives](./trust-primitives.md) — the cross-chain Agent Reputation endpoint scores ANY wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence, in one paid call, before your agent transacts
- **Wondering where the platform's money goes?** → [The autonomous economy](./autonomous-economy.md) — how the on-chain treasury funds itself, the funding-root → engines → sweepback loop, the locks that keep every dollar inside platform-owned wallets, and the two leak scanners that audit every wallet on-chain every minute (so far: 44,122 transactions scanned, zero leaks)
diff --git a/docs/tutorials/arm-an-agent-sniper.md b/docs/tutorials/arm-an-agent-sniper.md
new file mode 100644
index 000000000..8b1c068c7
--- /dev/null
+++ b/docs/tutorials/arm-an-agent-sniper.md
@@ -0,0 +1,105 @@
+# Arm an Autonomous Sniper on Your Agent
+
+By the end of this tutorial your agent trades on its own: it watches every new pump.fun launch the moment it happens, filters them against rules you set, runs a real on-chain safety simulation before spending anything, buys from its own Solana wallet, and manages the position to an exit while you sleep. Every decision it takes is written to an auditable, hash-chained ledger.
+
+This is real trading with real SOL on Solana mainnet. The platform's own agent closed its first autonomous position at +42.38% using exactly this setup, and the same run teaches the most important configuration lesson in this tutorial (Step 4). The full engineering breakdown lives in [the Agent Sniper doc](/docs/agent-sniper).
+
+**What you'll build:**
+
+- An armed sniper strategy on one of your agents (`POST /api/sniper/strategy`)
+- A funded agent wallet that executes trades autonomously
+- A live position ledger you can audit trade by trade
+- Two independent off switches you can flip at any time
+
+**Prerequisites:**
+
+- A three.ws account with at least one saved agent ([first-agent](/tutorials/first-agent) if you have none).
+- Your agent's custodial Solana wallet funded with SOL. Trades come out of this wallet, so fund it with an amount you are fully prepared to lose. 0.3 to 0.5 SOL is plenty for a first run at the sizes below.
+- A session or bearer token for the API calls (sign in at three.ws, or use an API bearer).
+- The mindset for it: sniping brand-new tokens is the highest-risk trading there is. The system's gates exist to filter out provable rugs, not to make bad coins good.
+
+---
+
+## Step 1 — Understand what fires and what blocks
+
+A strategy is a row of policy, and the worker enforces it as a chain of gates. A launch must pass all of them before a single lamport moves:
+
+1. **Trigger**: the worker holds the pump.fun new-mint firehose open and evaluates coins the second they exist.
+2. **Your filters**: market-cap band, socials requirement, creator history, dev-dump avoidance.
+3. **Fleet safety band**: platform-level market-cap clamps that your strategy can tighten but never loosen. An unpriceable coin always fails.
+4. **Mayhem gate**: pump.fun "Mayhem mode" tokens are excluded unconditionally.
+5. **Trade firewall**: a simulated buy-and-sell runs on-chain first. If the token cannot be sold back, the buy aborts. This is the honeypot killer.
+
+Only then does the executor sign. Expect long silences: a well-filtered strategy skips almost everything, and each skip is logged with its reason.
+
+## Step 2 — Arm the strategy
+
+One authenticated call arms it:
+
+```bash
+curl -X POST https://three.ws/api/sniper/strategy \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $THREEWS_TOKEN" \
+ -d '{
+ "agent_id": "YOUR-AGENT-UUID",
+ "network": "mainnet",
+ "enabled": true,
+ "trigger": "new_mint",
+ "per_trade_lamports": 50000000,
+ "daily_budget_lamports": 200000000,
+ "max_concurrent_positions": 1,
+ "min_market_cap_usd": 5000,
+ "max_market_cap_usd": 25000,
+ "require_socials": true,
+ "avoid_dev_dump": true,
+ "firewall_level": "block",
+ "slippage_bps": 500,
+ "max_price_impact_pct": 10,
+ "stop_loss_pct": 30,
+ "trailing_stop_pct": 25,
+ "take_profit_pct": 60,
+ "max_hold_seconds": 1800
+ }'
+```
+
+That is 0.05 SOL per trade, at most 0.2 SOL per day, one position at a time. `GET /api/sniper/strategy` returns your strategies with a live position summary and the agent wallet's SOL balance.
+
+## Step 3 — Know your exit ladder
+
+Exits are decided by a pure function in strict priority order, so behavior is exactly predictable:
+
+1. **Stop-loss** (`stop_loss_pct`): value falls 30% below entry, sell everything, always checked first.
+2. **Trailing stop** (`trailing_stop_pct`): value falls 25% off its peak since entry, sell.
+3. **Take-profit** (`take_profit_pct`): value reaches entry plus 60%, sell.
+4. **Timeout** (`max_hold_seconds`): the clock wins no matter what the PnL is.
+
+There is also a laddered mode (`initials_out_multiple`, `moonbag_min_pct`): recover your initial cost when the position hits a multiple, then let the remaining moon bag ride the trailing stop.
+
+## Step 4 — The lesson from the first live trade: set `take_profit_pct`
+
+The platform's first autonomous position rode to +46.5%, then exited at +42.38% only because its 30-minute timeout expired. Why: the strategy had `take_profit_pct` unset. With no profit rule, a winner is only ever closed by the trailing stop (which gives back 25% from the peak by definition) or by the clock (which exits at whatever the price happens to be).
+
+That trade won anyway. Configuration should not rely on that. Set an explicit `take_profit_pct` (or use the laddered exit) so that locking in a win is policy, not luck.
+
+## Step 5 — Watch it work
+
+- **Positions and PnL**: `GET /api/sniper/strategy` (summary) and the journal at `GET /api/sniper/journal` for the plain-language story of each entry and exit.
+- **Reasoning**: every buy writes a decision-ledger entry with the firewall verdict, price impact, a rationale sentence, and a confidence score, hash-chained to the previous entry.
+- **The market through the engine's eyes**: [Radar and Coin Intelligence](/docs/trading-surfaces) show what the sniper's intel layer is scoring right now, including coins it skipped.
+
+## Step 6 — The off switches
+
+Two independent controls, both instant, both reversible, via the same POST:
+
+- `"kill_switch": true` halts execution but keeps the whole config intact. Use this one first.
+- `"enabled": false` disarms the strategy entirely.
+
+The daily budget is a third, passive backstop: once `daily_budget_lamports` is spent, the strategy cannot buy again until the window resets.
+
+## Where this is going
+
+The hard-config sniper you just armed is the control group. The next phase runs an LLM strategist above the same execution stack: a reasoning model reads live market conditions and the agent's own trade history, then tunes these same fields on a cadence, with every adjustment logged to the same ledger. The deterministic gates (firewall, safety band, budget caps) stay hard no matter what the model says. The design and results log live in [the Agent Sniper doc](/docs/agent-sniper).
+
+---
+
+**Legal note:** the sniper trades real tokens with real money on a public chain, entirely under rules you arm. New-launch tokens are extremely volatile and most go to zero. Nothing on this page is financial advice; fund the agent wallet only with what you can afford to lose.
diff --git a/packages/assistant-mcp/src/index.js b/packages/assistant-mcp/src/index.js
old mode 100644
new mode 100755
diff --git a/public/avatars/mixamo/catalog.json b/public/avatars/mixamo/catalog.json
new file mode 100644
index 000000000..ea67ca08c
--- /dev/null
+++ b/public/avatars/mixamo/catalog.json
@@ -0,0 +1,5 @@
+{
+ "generated_at": "2026-07-19T03:59:37.608Z",
+ "avatars": {},
+ "catalog_size": 106
+}
\ No newline at end of file
diff --git a/scripts/fetch-mixamo-avatars.mjs b/scripts/fetch-mixamo-avatars.mjs
new file mode 100644
index 000000000..0ba0cec04
--- /dev/null
+++ b/scripts/fetch-mixamo-avatars.mjs
@@ -0,0 +1,375 @@
+#!/usr/bin/env node
+// Bulk-download every Mixamo character avatar as FBX (With Skin).
+// Resumable: re-run to pick up where it left off.
+//
+// Listing the catalog needs no auth (Mixamo's /products?type=Character feed is
+// public). Exporting + downloading the actual FBX does need a Mixamo session
+// token, same as the animation fetchers.
+//
+// Usage:
+// node scripts/fetch-mixamo-avatars.mjs # catalog only, no token needed
+// MIXAMO_TOKEN=eyJ... node scripts/fetch-mixamo-avatars.mjs --download
+// # or put MIXAMO_TOKEN=... in .env.local
+//
+// Optional flags:
+// --download run the export+download phase (needs MIXAMO_TOKEN)
+// --concurrency=N parallel export jobs (default 2)
+// --limit=N stop after N successful downloads (default: all)
+// --format=fbx7|fbx6 output format (default fbx7)
+//
+// Prerequisites for --download:
+// node scripts/get-mixamo-token.mjs (first-time login, needs ADOBE_EMAIL/ADOBE_PASSWORD)
+
+import { mkdirSync, writeFileSync, existsSync, readFileSync, renameSync } from 'node:fs';
+import { join } from 'node:path';
+
+// ── Config ────────────────────────────────────────────────────────────────
+const API = 'https://www.mixamo.com/api/v1';
+const PAGE_LIMIT = 96;
+const POLL_INTERVAL_MS = 3000;
+const POLL_MAX_ATTEMPTS = 60;
+
+const args = Object.fromEntries(
+ process.argv.slice(2).map((a) => {
+ const m = a.match(/^--([^=]+)(?:=(.*))?$/);
+ return m ? [m[1], m[2] ?? true] : [a, true];
+ }),
+);
+
+const RUN_DOWNLOAD = !!args.download;
+const CONCURRENCY = Number(args.concurrency) || 2;
+const MAX_DOWNLOADS = args.limit ? Number(args.limit) : Infinity;
+const FORMAT = args.format || 'fbx7';
+
+let globalCooldownUntil = 0;
+const RATE_LIMIT_BASE_MS = 30_000;
+const RATE_LIMIT_MAX_MS = 300_000;
+
+// ── Env loading (.env.local fallback, same convention as the other mixamo scripts) ──
+function loadEnvVar(key) {
+ if (process.env[key]) return process.env[key].trim();
+ const envPath = join(process.cwd(), '.env.local');
+ if (existsSync(envPath)) {
+ const line = readFileSync(envPath, 'utf8').split('\n').find((l) => l.startsWith(`${key}=`));
+ if (line) return line.slice(key.length + 1).trim().replace(/^["']|["']$/g, '');
+ }
+ return null;
+}
+
+const TOKEN = loadEnvVar('MIXAMO_TOKEN');
+
+// ── R2 config — S3_* is the name production (Cloud Run) and mixamo-all.mjs use;
+// R2_* accepted as a fallback for older local setups. ──────────────────────────
+const S3_ENDPOINT = loadEnvVar('S3_ENDPOINT') ||
+ (loadEnvVar('R2_ACCOUNT_ID') ? `https://${loadEnvVar('R2_ACCOUNT_ID')}.r2.cloudflarestorage.com` : null);
+const S3_ACCESS_KEY_ID = loadEnvVar('S3_ACCESS_KEY_ID') || loadEnvVar('R2_ACCESS_KEY_ID');
+const S3_SECRET_ACCESS_KEY = loadEnvVar('S3_SECRET_ACCESS_KEY') || loadEnvVar('R2_SECRET_ACCESS_KEY');
+const S3_BUCKET = loadEnvVar('S3_BUCKET') || loadEnvVar('R2_BUCKET') || 'test';
+const USE_R2 = !!(S3_ENDPOINT && S3_ACCESS_KEY_ID && S3_SECRET_ACCESS_KEY);
+
+let r2 = null;
+async function getR2Client() {
+ if (r2) return r2;
+ const { S3Client } = await import('@aws-sdk/client-s3');
+ r2 = new S3Client({
+ region: 'auto',
+ endpoint: S3_ENDPOINT,
+ credentials: { accessKeyId: S3_ACCESS_KEY_ID, secretAccessKey: S3_SECRET_ACCESS_KEY },
+ });
+ return r2;
+}
+
+async function existsInR2(key) {
+ const { HeadObjectCommand } = await import('@aws-sdk/client-s3');
+ try {
+ await (await getR2Client()).send(new HeadObjectCommand({ Bucket: S3_BUCKET, Key: key }));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function uploadToR2(key, buf) {
+ const { PutObjectCommand } = await import('@aws-sdk/client-s3');
+ await (await getR2Client()).send(
+ new PutObjectCommand({ Bucket: S3_BUCKET, Key: key, Body: buf, ContentType: 'application/octet-stream' }),
+ );
+}
+
+const authHeaders = {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ 'X-Api-Key': 'mixamo2',
+ ...(TOKEN ? { Authorization: `Bearer ${TOKEN}` } : {}),
+};
+
+// ── Output paths ──────────────────────────────────────────────────────────
+const OUT_DIR = join(process.cwd(), 'public', 'avatars', 'mixamo');
+const CATALOG_PATH = join(OUT_DIR, 'catalog.json');
+mkdirSync(OUT_DIR, { recursive: true });
+
+const catalog = existsSync(CATALOG_PATH)
+ ? JSON.parse(readFileSync(CATALOG_PATH, 'utf8'))
+ : { generated_at: null, avatars: {} };
+
+function saveCatalog() {
+ catalog.generated_at = new Date().toISOString();
+ const tmp = `${CATALOG_PATH}.tmp`;
+ writeFileSync(tmp, JSON.stringify(catalog, null, 2));
+ renameSync(tmp, CATALOG_PATH);
+}
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+const slugify = (s) =>
+ s
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 80);
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+async function waitForCooldown() {
+ while (Date.now() < globalCooldownUntil) {
+ await sleep(Math.min(2000, globalCooldownUntil - Date.now()));
+ }
+}
+
+function triggerCooldown(retryAfterSec, attempt) {
+ const explicit = retryAfterSec ? Number(retryAfterSec) * 1000 : 0;
+ const backoff = Math.min(RATE_LIMIT_BASE_MS * 2 ** attempt, RATE_LIMIT_MAX_MS);
+ const wait = Math.max(explicit, backoff);
+ const until = Date.now() + wait;
+ if (until > globalCooldownUntil) {
+ globalCooldownUntil = until;
+ console.log(`Rate limited — pausing ${(wait / 1000).toFixed(0)}s`);
+ }
+}
+
+async function rlFetch(url, init = {}, attempt = 0) {
+ await waitForCooldown();
+ const res = await fetch(url, init);
+ if (res.status === 429) {
+ triggerCooldown(res.headers.get('retry-after'), attempt);
+ if (attempt >= 6) throw new Error('429 (max retries)');
+ return rlFetch(url, init, attempt + 1);
+ }
+ return res;
+}
+
+async function api(path, init = {}) {
+ const res = await rlFetch(`${API}${path}`, { ...init, headers: { ...authHeaders, ...init.headers } });
+ if (!res.ok) {
+ const body = await res.text().catch(() => '');
+ throw new Error(`HTTP ${res.status} ${path} ${body.slice(0, 200)}`);
+ }
+ return res.json();
+}
+
+// ── Step 1: list all Character products — public feed, no auth required ───
+async function listAllCharacters() {
+ const all = [];
+ let page = 1;
+ while (true) {
+ process.stdout.write(`\rListing characters: page ${page} (${all.length} so far)... `);
+ const data = await api(
+ `/products?page=${page}&limit=${PAGE_LIMIT}&type=Character&order=relevance`,
+ );
+ const results = data.results || [];
+ all.push(...results);
+ const totalPages =
+ data.pagination?.num_pages ?? Math.ceil((data.pagination?.num_results ?? 0) / PAGE_LIMIT);
+ if (!totalPages || page >= totalPages || results.length === 0) break;
+ page += 1;
+ await sleep(200);
+ }
+ process.stdout.write('\n');
+ // Dedupe by product id — same pattern as the animation catalog fetchers,
+ // Mixamo's paginated feed can repeat a product across pages.
+ const seen = new Set();
+ const unique = all.filter((a) => (seen.has(a.id) ? false : (seen.add(a.id), true)));
+ return unique;
+}
+
+// ── Step 2: export + poll + download a single character (needs MIXAMO_TOKEN) ──
+async function downloadOne(product) {
+ const slug = slugify(product.description || product.name || product.id);
+ const r2Key = `avatars/mixamo/${slug}.fbx`;
+ const localPath = join(OUT_DIR, `${slug}.fbx`);
+ const existing = catalog.avatars[product.id];
+
+ if (existing?.status === 'completed') {
+ const alreadyExists = USE_R2 ? await existsInR2(r2Key) : existsSync(localPath);
+ if (alreadyExists) return { skipped: true, slug, reason: 'already-downloaded' };
+ }
+ if (existing?.status === 'permanent_fail') {
+ return { skipped: true, slug, reason: 'permanent-fail' };
+ }
+
+ // Fetch product details to get gms_hash
+ const productDetails = await api(`/products/${product.id}`);
+ const gmsHash = productDetails?.details?.gms_hash;
+ if (!gmsHash) {
+ catalog.avatars[product.id] = {
+ id: product.id,
+ name: product.description || product.name,
+ status: 'permanent_fail',
+ reason: 'no_gms_hash',
+ failed_at: new Date().toISOString(),
+ };
+ saveCatalog();
+ throw new Error('no gms_hash');
+ }
+
+ const exportRes = await rlFetch(`${API}/characters/export`, {
+ method: 'POST',
+ headers: authHeaders,
+ body: JSON.stringify({
+ product_id: product.id,
+ product_name: product.description || product.name,
+ type: 'Character',
+ gms_hash: [gmsHash],
+ preferences: { format: FORMAT, skin: 'true', fps: '30', reducekf: '0' },
+ }),
+ });
+
+ if (!exportRes.ok) {
+ const status = exportRes.status;
+ if (status === 400 || status === 404) {
+ catalog.avatars[product.id] = {
+ id: product.id,
+ name: product.description || product.name,
+ status: 'permanent_fail',
+ http: status,
+ failed_at: new Date().toISOString(),
+ };
+ saveCatalog();
+ }
+ throw new Error(`export ${status}`);
+ }
+
+ let downloadUrl = null;
+ for (let i = 0; i < POLL_MAX_ATTEMPTS; i++) {
+ await sleep(POLL_INTERVAL_MS);
+ const status = await api(`/characters/export/${product.id}`);
+ if (status.status === 'completed' && status.result?.url) {
+ downloadUrl = status.result.url;
+ break;
+ }
+ if (status.status === 'failed') throw new Error('export failed');
+ }
+ if (!downloadUrl) throw new Error('poll timeout');
+
+ const fileRes = await rlFetch(downloadUrl);
+ if (!fileRes.ok) throw new Error(`download ${fileRes.status}`);
+ const buf = Buffer.from(await fileRes.arrayBuffer());
+
+ if (USE_R2) {
+ await uploadToR2(r2Key, buf);
+ } else {
+ writeFileSync(localPath, buf);
+ }
+
+ catalog.avatars[product.id] = {
+ id: product.id,
+ name: product.description || product.name,
+ file: USE_R2 ? r2Key : `${slug}.fbx`,
+ bytes: buf.length,
+ downloaded_at: new Date().toISOString(),
+ status: 'completed',
+ storage: USE_R2 ? 'r2' : 'local',
+ };
+ saveCatalog();
+
+ return { slug, bytes: buf.length };
+}
+
+// ── Step 3: concurrency-limited worker pool ─────────────────────────────
+async function runPool(products) {
+ let cursor = 0;
+ let ok = 0;
+ let fail = 0;
+ let skipped = 0;
+
+ async function worker() {
+ while (cursor < products.length && ok + fail < MAX_DOWNLOADS) {
+ const i = cursor++;
+ const product = products[i];
+ const label = `[${i + 1}/${products.length}]`;
+ try {
+ const result = await downloadOne(product);
+ if (result.skipped) {
+ skipped++;
+ console.log(`${label} skip ${result.slug} (${result.reason})`);
+ } else {
+ ok++;
+ console.log(`${label} done ${result.slug} (${(result.bytes / 1024).toFixed(0)} KB)`);
+ await sleep(500);
+ }
+ } catch (err) {
+ fail++;
+ console.warn(`${label} fail ${product.description}: ${err.message}`);
+ if (err.message.includes('HTTP 401') || err.message.includes('HTTP 403')) {
+ console.error('Auth failure — token expired. Refresh MIXAMO_TOKEN and re-run.');
+ process.exit(2);
+ }
+ }
+ }
+ }
+
+ const workers = Array.from({ length: CONCURRENCY }, () => worker());
+ await Promise.all(workers);
+ return { ok, fail, skipped };
+}
+
+// ── Main ──────────────────────────────────────────────────────────────────
+(async () => {
+ console.log(`Mixamo avatar fetcher`);
+ console.log(` Storage: ${USE_R2 ? `R2 -> ${S3_BUCKET}/avatars/mixamo/` : OUT_DIR}`);
+
+ const products = await listAllCharacters();
+ catalog.catalog_size = products.length;
+ saveCatalog();
+ console.log(`Catalog: ${products.length} characters\n`);
+
+ if (products.length === 0) {
+ console.log('No characters found — Mixamo API may be unreachable.');
+ process.exit(1);
+ }
+
+ if (!RUN_DOWNLOAD) {
+ console.log('Catalog-only run (pass --download to export + download FBX files).');
+ if (!TOKEN) {
+ console.log('\nMIXAMO_TOKEN not set — the download phase needs it.');
+ console.log('Get one: node scripts/get-mixamo-token.mjs (needs ADOBE_EMAIL/ADOBE_PASSWORD in .env.local)');
+ }
+ console.log(`\nCatalog saved: ${CATALOG_PATH}`);
+ return;
+ }
+
+ if (!TOKEN) {
+ console.error('MIXAMO_TOKEN not set. Run: node scripts/get-mixamo-token.mjs');
+ process.exit(1);
+ }
+
+ console.log(` Format: ${FORMAT} (with skin)`);
+ console.log(` Concurrency: ${CONCURRENCY}\n`);
+
+ const t0 = Date.now();
+ const { ok, fail, skipped } = await runPool(products);
+ const mins = ((Date.now() - t0) / 60000).toFixed(1);
+
+ console.log(`\n${'='.repeat(43)}`);
+ console.log(`Downloaded: ${ok}`);
+ console.log(`Skipped: ${skipped}`);
+ console.log(`Failed: ${fail}`);
+ console.log(`Time: ${mins} min`);
+ console.log(`Output: ${USE_R2 ? `R2:${S3_BUCKET}/avatars/mixamo/` : OUT_DIR}`);
+ console.log(`\nConvert FBX -> GLB with fbx2gltf:`);
+ console.log(` for f in ${OUT_DIR}/*.fbx; do`);
+ console.log(` fbx2gltf -i "$f" -o "\${f%.fbx}.glb"`);
+ console.log(` done`);
+})().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/scripts/get-mixamo-token.mjs b/scripts/get-mixamo-token.mjs
index 0d9a13619..ba875d90a 100644
--- a/scripts/get-mixamo-token.mjs
+++ b/scripts/get-mixamo-token.mjs
@@ -11,7 +11,7 @@
*/
import { chromium } from 'playwright';
-import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
@@ -40,26 +40,96 @@ function saveToken(token) {
console.log('✅ MIXAMO_TOKEN saved to .env.local');
}
+// Adobe's "Verify your identity" step is two screens: a confirmation screen
+// ("we'll send you a code to n***@g***.com" + Continue button) that must be
+// clicked before the email actually goes out, then the real code-entry screen.
+// Detect which one we're on and only prompt for a code once inputs exist.
+async function handleVerification(page, label) {
+ let bodyText = await page.innerText('body').catch(() => '');
+ if (!/Verify|verification|code/i.test(bodyText)) return bodyText;
+
+ const hasCodeInput = await page
+ .$('input[name="code"], input[aria-label*="code" i], input[placeholder*="code" i], input[type="text"], input[type="number"], input[inputmode="numeric"]')
+ .then(Boolean)
+ .catch(() => false);
+
+ if (!hasCodeInput) {
+ const continueBtn = await page.$('button:has-text("Continue")');
+ if (continueBtn) {
+ console.log(` ${label}: confirmation screen — clicking Continue to trigger the email...`);
+ await continueBtn.click();
+ await page.waitForTimeout(3000);
+ bodyText = await page.innerText('body').catch(() => '');
+ }
+ }
+
+ if (/Verify|verification|code/i.test(bodyText)) {
+ console.log(`\n📧 Adobe sent a verification code to your email (${label}).`);
+ const code = await prompt(' Enter the code: ');
+ await fillOtp(page, code);
+ await page.waitForTimeout(3000);
+ bodyText = await page.innerText('body').catch(() => '');
+ }
+ return bodyText;
+}
+
async function fillOtp(page, code) {
const single = await page.$('input[name="code"], input[aria-label*="code" i], input[placeholder*="code" i]');
if (single) {
await single.fill(code);
} else {
- const inputs = await page.$$('input[type="text"], input[type="number"], input[inputmode="numeric"]');
- for (let i = 0; i < inputs.length && i < code.length; i++) {
- await inputs[i].fill(code[i]);
+ // Split-box OTP (one <input> per digit, type varies: text/tel/number/none).
+ // fill()-ing each box programmatically skips the input events these UIs use
+ // to auto-advance focus, so only the first box ever lands a digit. Instead
+ // click the first box and type the whole code as real keystrokes — the
+ // page's own JS advances focus per keystroke, same as a human typing it.
+ let boxes = await page.$$('input:visible');
+ if (boxes.length === 0) boxes = await page.$$('input');
+ if (boxes.length >= code.length) {
+ await boxes[0].click();
+ await page.keyboard.type(code, { delay: 80 });
+ } else if (boxes.length === 1) {
+ await boxes[0].fill(code);
}
}
+ await page.waitForTimeout(300);
await page.click('button[type="submit"], button:has-text("Continue")').catch(() =>
page.keyboard.press('Enter')
);
}
+const OTP_FILE = join(process.cwd(), '.mixamo-otp');
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
async function prompt(question) {
- const rl = readline.createInterface({ input, output });
- const answer = await rl.question(question);
- rl.close();
- return answer.trim();
+ // A restarted process means a restarted login = a brand-new email that
+ // invalidates whatever code was read from the previous one. So this must
+ // NOT start a fresh process per code — it polls a file for the code while
+ // the SAME browser session (which just sent the one and only email for
+ // this run) stays open. Whoever has the code writes it to .mixamo-otp.
+ if (process.env.ADOBE_OTP) {
+ console.log(`${question}${process.env.ADOBE_OTP} (from ADOBE_OTP)`);
+ return process.env.ADOBE_OTP.trim();
+ }
+ if (process.stdin.isTTY) {
+ const rl = readline.createInterface({ input, output });
+ const answer = await rl.question(question);
+ rl.close();
+ return answer.trim();
+ }
+ console.log(`${question}(waiting up to 4 min — write the code to ${OTP_FILE})`);
+ try { rmSync(OTP_FILE, { force: true }); } catch {}
+ for (let i = 0; i < 120; i++) {
+ await sleep(2000);
+ if (existsSync(OTP_FILE)) {
+ const code = readFileSync(OTP_FILE, 'utf8').trim();
+ if (code) {
+ writeFileSync(OTP_FILE, '');
+ return code;
+ }
+ }
+ }
+ throw new Error('timed out waiting for OTP code');
}
(async () => {
@@ -149,14 +219,8 @@ async function prompt(question) {
console.log(` Page heading: ${bodyText.slice(0, 120).replace(/\n/g, ' ')}`);
// Handle verification screen before password (some accounts see this first)
- if (bodyText.includes('Verify') || bodyText.includes('verification') || bodyText.includes('code')) {
- console.log('\n📧 Adobe sent a verification code to your email.');
- const code = await prompt(' Enter the code: ');
- await fillOtp(loginPage, code);
- await loginPage.waitForTimeout(3000);
- await loginPage.screenshot({ path: 'scripts/debug-step4.png' });
- bodyText = await loginPage.innerText('body').catch(() => '');
- }
+ bodyText = await handleVerification(loginPage, 'before password');
+ await loginPage.screenshot({ path: 'scripts/debug-step4.png' });
// Password step
if (await loginPage.$('input[type="password"]').then(Boolean).catch(() => false)) {
@@ -170,12 +234,7 @@ async function prompt(question) {
}
// Verification after password
- if (bodyText.includes('Verify') || bodyText.includes('verification') || bodyText.includes('code')) {
- console.log('\n📧 Adobe sent a verification code to your email.');
- const code = await prompt(' Enter the code: ');
- await fillOtp(loginPage, code);
- await loginPage.waitForTimeout(3000);
- }
+ bodyText = await handleVerification(loginPage, 'after password');
// Wait for redirect back to mixamo