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.

More SDK package scaffolds and trader stats refinement

nirholasae2db985ba05
diff --git a/api/_lib/trader-stats.js b/api/_lib/trader-stats.js
index ecbeb39fd..1858868da 100644
--- a/api/_lib/trader-stats.js
+++ b/api/_lib/trader-stats.js
@@ -387,7 +387,7 @@ export function shapeOpen(p, network) {
* + open positions. Returns null if the agent has no positions on this network.
*/
export async function getTraderStats({ agentId, network, window = 'all', now = Date.now() }) {
- const [idRows, positions, solUsd, copiers, oracleSummary] = await Promise.all([
+ const [idRows, positions, solUsd, copiers, oracleSummary, projection] = await Promise.all([
sql`
select id, name, description, avatar_url, profile_image_url, is_public
from agent_identities where id = ${agentId} limit 1
@@ -396,6 +396,7 @@ export async function getTraderStats({ agentId, network, window = 'all', now = D
cachedSolUsd(),
copierCountForAgent(agentId, network),
actionsSummary(agentId, network).catch(() => null),
+ latestProjection(agentId, network).catch(() => null),
]);
const identity = idRows[0];
if (!identity) return null;
@@ -424,6 +425,54 @@ export async function getTraderStats({ agentId, network, window = 'all', now = D
closed,
open,
oracle: oracleSummary && oracleSummary.total > 0 ? oracleSummary : null,
+ projection: projection ? buildProjectionComparison(projection, metrics) : null,
+ };
+}
+
+/**
+ * Latest backtest snapshot linked to this agent — the projection the owner armed
+ * against. Read-only; returns null when the table is absent or no snapshot exists.
+ */
+async function latestProjection(agentId, network) {
+ const [row] = await sql`
+ select metrics, sample_size, window_days, ran_at
+ from strategy_backtests
+ where agent_id = ${agentId} and network = ${network}
+ order by ran_at desc limit 1
+ `;
+ return row || null;
+}
+
+/**
+ * Pair the armed projection against what actually happened, so the projection is
+ * accountable — not marketing. Realized numbers come straight from
+ * computeTraderMetrics (chain-proven); projected numbers from the stored backtest.
+ */
+function buildProjectionComparison(snap, metrics) {
+ const m = snap.metrics || {};
+ const bt = m.metrics || {};
+ const projWinRate = typeof bt.win_rate === 'number' ? bt.win_rate : null;
+ const projEv = typeof bt.expected_value_pct === 'number' ? bt.expected_value_pct : null;
+ const projDrawdown = typeof bt.max_drawdown_pct === 'number' ? bt.max_drawdown_pct : null;
+ return {
+ ran_at: snap.ran_at,
+ window_days: snap.window_days,
+ sample_size: snap.sample_size,
+ confidence: m.caveats?.confidence || null,
+ insufficient_data: !!m.insufficient_data,
+ projected: {
+ win_rate: projWinRate,
+ expected_value_pct: projEv,
+ roi_median_pct: typeof bt.roi_median_pct === 'number' ? bt.roi_median_pct : null,
+ max_drawdown_pct: projDrawdown,
+ },
+ realized: {
+ win_rate: metrics.win_rate,
+ avg_pnl_pct: metrics.avg_pnl_pct,
+ roi_pct: metrics.roi_pct,
+ max_drawdown_pct: metrics.max_drawdown_pct,
+ closed_count: metrics.closed_count,
+ },
};
}
diff --git a/packages/agent-guards/README.md b/packages/agent-guards/README.md
new file mode 100644
index 000000000..ad10d2901
--- /dev/null
+++ b/packages/agent-guards/README.md
@@ -0,0 +1,299 @@
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>
+</p>
+
+<h1 align="center">@three-ws/agent-guards</h1>
+
+<p align="center"><strong>Safety rails for autonomous agents — cap what an agent can spend or trade before a transaction is ever signed.</strong></p>
+
+<p align="center">
+ <a href="https://www.npmjs.com/package/@three-ws/agent-guards"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/agent-guards?logo=npm&color=cb3837"></a>
+ <a href="https://www.npmjs.com/package/@three-ws/agent-guards"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/agent-guards?color=cb3837"></a>
+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/agent-guards?color=3b82f6">
+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/agent-guards?color=339933&logo=node.js">
+</p>
+
+<p align="center">
+ <a href="#install">Install</a> ·
+ <a href="#quick-start">Quick start</a> ·
+ <a href="#api">API</a> ·
+ <a href="#how-it-works">How it works</a> ·
+ <a href="https://three.ws">three.ws</a>
+</p>
+
+---
+
+> `@three-ws/agent-guards` is the official client for the three.ws **agent custody
+> guardrails** — the same policy engine that governs every outbound movement of a
+> custodial agent wallet on the platform. It lets an owner set hard spend and trade
+> ceilings on an agent, and lets a caller pre-check a proposed buy/sell against
+> those ceilings *before* signing. One policy is enforced uniformly across all four
+> custody paths — discretionary trade, autonomous snipe, x402 pay, and owner
+> withdraw — so an agent (or a stolen session token) can never drain a wallet past
+> the leash its owner set. It wraps the live `/api/agents/:id/trade` and
+> `/api/agents/:id/trade/limits` endpoints. All trading is SOL-quoted on Solana;
+> the only coin three.ws promotes is [$THREE](https://three.ws).
+
+## Why
+
+An autonomous agent that can sign transactions is a loaded gun pointed at a wallet.
+The moment you hand an LLM a key, you need an answer to one question on *every*
+action: **is this allowed?** Hand-rolling that answer means re-deriving the same
+math in four places — and the day the trade path and the snipe path disagree on
+the daily cap is the day a wallet gets drained.
+
+three.ws solves it once, server-side, as a single policy:
+
+- **Two-tier ceilings.** A per-transaction cap stops one oversized trade; a
+ rolling 24-hour cap stops a thousand small ones. Both are enforced atomically
+ under a per-agent lock, so concurrent spends can't race past the limit.
+- **A real kill switch.** Flip `kill_switch` (trades) or `frozen` (all autonomous
+ paths) and every outbound action is rejected immediately — but the owner's own
+ withdraw stays open, so a freeze locks down a misbehaving agent without trapping
+ its funds.
+- **Circuit breakers, not just caps.** A price-impact breaker and a slippage
+ ceiling reject trades that would execute at a bad price, independent of size.
+- **Owner-set, opt-in.** An unset ceiling means "no global cap" — existing flows
+ keep working. The moment an owner tightens the policy it becomes a hard limit
+ applied everywhere.
+
+This SDK is the programmatic twin of the **Limits & Safety** surface in the
+three.ws agent dashboard — the same policy, exposed as plain functions instead of
+a settings panel.
+
+## Install
+
+```bash
+npm install @three-ws/agent-guards
+```
+
+Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`).
+Setting or reading a policy is an owner-only action and requires the agent owner's
+session cookie or bearer token.
+
+## Quick start
+
+Read an agent's current trade policy, then set a leash:
+
+```js
+import { guards } from '@three-ws/agent-guards';
+
+const a = guards('agent_abc123', { token: process.env.THREE_WS_TOKEN });
+
+// Set the rails: 0.5 SOL per trade, 2 SOL/day, reject >10% price impact.
+await a.setTradeLimits({
+ per_trade_sol: 0.5,
+ daily_budget_sol: 2,
+ max_price_impact_pct: 10,
+ max_slippage_bps: 500,
+});
+```
+
+Pre-check a proposed buy before you commit to signing it. `simulate: true` runs the
+full quote → guard pipeline and returns the decision without moving funds:
+
+```js
+const decision = await a.checkTrade({ side: 'buy', mint, amount: 0.3 });
+
+if (!decision.allowed) {
+ console.log(decision.reason); // e.g. 'per_trade_cap'
+ console.log(decision.message); // human-readable, actionable
+} else {
+ await a.trade({ side: 'buy', mint, amount: 0.3 }); // really executes
+}
+```
+
+The kill switch, in one line:
+
+```js
+await a.setTradeLimits({ kill_switch: true }); // every discretionary trade now rejected
+```
+
+## API
+
+### `guards(agentId, options?) → AgentGuards`
+
+Bind the client to one agent. `options.token` is the owner's bearer token, or pass
+`options.cookie` for a session. `options.baseUrl` overrides the default
+`https://three.ws`.
+
+### `.getTradeLimits() → Promise<TradeLimits & { defaults }>`
+
+`GET /api/agents/:id/trade/limits`. Returns the effective discretionary-trade
+policy plus the platform defaults. Lamport/SOL-denominated knobs that govern the
+agent's own buys:
+
+| Field | Type | Default | Meaning |
+|---|---|---|---|
+| `per_trade_sol` | `number \| null` | `null` | Max SOL on any single buy. `null` = uncapped. |
+| `daily_budget_sol` | `number \| null` | `null` | Rolling-24h SOL buy budget across trade **and** snipe. `null` = uncapped. |
+| `max_price_impact_pct` | `number` | `15` | Circuit breaker — reject a trade over this price impact. |
+| `max_slippage_bps` | `number` | `1000` | Ceiling on client-supplied slippage (basis points). |
+| `max_concurrent` | `number \| null` | `null` | Max open discretionary positions. `null` = unlimited. |
+| `kill_switch` | `boolean` | `false` | When `true`, every discretionary trade is rejected. |
+
+### `.setTradeLimits(patch) → Promise<TradeLimits>`
+
+`PUT /api/agents/:id/trade/limits`. Owner-only, CSRF-gated (bearer callers exempt).
+A **patch** — only the keys you pass change; the rest are preserved. Values are
+normalized and bounded server-side (`max_price_impact_pct` clamps to 0–100,
+`max_slippage_bps` to 0–10000, `max_concurrent` to 1–10000). Returns the new policy.
+
+### `.checkTrade({ side, mint, amount, ... }) → Promise<Decision>`
+
+Pre-flight a trade against every guard without moving funds — wraps the live
+`POST /api/agents/:id/trade` with `simulate: true`. Returns:
+
+| Field | Type | Notes |
+|---|---|---|
+| `allowed` | `boolean` | `true` if the trade clears every guard. |
+| `reason` | `string \| null` | Machine code when blocked — see [reasons](#guard-reasons). |
+| `message` | `string \| null` | Plain-language, actionable explanation. |
+| `detail` | `object` | The numbers behind the decision (amounts, caps, spent-so-far). |
+
+### `.trade({ side, mint, amount, ... }) → Promise<TradeResult>`
+
+`POST /api/agents/:id/trade`. Executes the real trade — runs the identical
+quote → guard → build → custody-claim → sign → confirm pipeline, so it can never
+exceed the policy `checkTrade` reported on.
+
+**Request body**
+
+| Field | Type | Notes |
+|---|---|---|
+| `side` | `'buy' \| 'sell'` | Buys spend SOL; sells move SOL inward. Required. |
+| `mint` | `string` | Base58 Solana mint of the coin to trade. Required. |
+| `amount` | `number \| 'max'` | Buy: SOL to spend. Sell: tokens to sell, or `'max'`. |
+| `slippageBps` | `number` | Slippage in bps. Clamped to `max_slippage_bps`. |
+| `network` | `string` | `mainnet` (default) or `devnet`. |
+| `simulate` | `boolean` | Dry run — never signs or records. `checkTrade` sets this for you. |
+| `idempotency_key` | `string` | De-dupe retries of the same trade. |
+
+Buys are gated on the per-trade cap, daily SOL budget, concurrency ceiling, the
+cross-path USD ceiling, and a SOL fee/rent headroom floor (~0.003 SOL kept above
+the spend). Sells only move SOL inward, so they skip the spend caps but still honor
+the kill switch, the price-impact breaker, and the headroom floor.
+
+### `.getSpendLimits()` / `.setSpendLimits(patch)`
+
+The cross-path USD spend policy (distinct from the SOL trade limits above), stored
+at `meta.spend_limits` and enforced uniformly across trade, snipe, x402 pay, and
+withdraw. Patch semantics are identical to the trade limits.
+
+| Field | Type | Default | Meaning |
+|---|---|---|---|
+| `daily_usd` | `number \| null` | `null` | Rolling-24h USD-equivalent outflow ceiling. |
+| `per_tx_usd` | `number \| null` | `null` | Max USD-equivalent for any single outbound tx. |
+| `withdraw_allowlist` | `string[]` | `[]` | If non-empty, withdraws may only target these addresses (max 50, validated base58). |
+| `frozen` | `boolean` | `false` | Kill switch for **all** autonomous paths. Owner withdraw stays open. |
+
+## How it works
+
+Every outbound movement of an agent wallet runs through one policy. The guards are
+pure, synchronous predicates — the server fetches the live numbers (open count,
+24h spend, wallet balance, quote) and hands them in, so the *same* comparison backs
+both the discretionary trade endpoint and the autonomous sniper. A cap can never
+drift between paths.
+
+```
+ proposed trade (side, mint, amount)
+ │
+ ▼
+ quote the venue ──► price impact, expected out, USD value
+ │
+ ▼
+ ┌──────────────────────── guard pipeline ────────────────────────┐
+ │ kill switch ──► price-impact breaker ──► per-trade SOL cap │
+ │ ──► concurrency ceiling ──► daily SOL budget (rolling 24h)│
+ │ ──► cross-path USD ceiling ──► SOL fee/rent headroom │
+ └─────────────────────────────┬───────────────────────────────────┘
+ clear? ──no──► 4xx { code, message, detail } (never a 500)
+ │ yes
+ ▼
+ reserve in the custody ledger ──► sign ──► confirm ──► finalize
+```
+
+The two caps that matter most — the rolling daily SOL budget and the daily USD
+ceiling — are enforced **atomically under a per-agent advisory lock**. The check
+and the ledger reservation happen in a single statement, so K concurrent spends
+can never all read the same stale 24h total and all pass, turning an $X/day cap
+into $X·K. A reservation that never settles is released, so a failed attempt does
+not permanently consume the agent's budget.
+
+## Guard reasons
+
+A blocked trade is always a structured `4xx` with a machine code and a plain-language
+message — never a thrown 500. `checkTrade` surfaces these on `decision.reason`;
+`trade` rejects with the same shape.
+
+| `reason` | HTTP | Meaning | Recovery |
+|---|---|---|---|
+| `kill_switch` | 403 | Discretionary trading is paused for this agent. | Re-enable trading (`kill_switch: false`). |
+| `wallet_frozen` | 403 | The wallet is frozen; all autonomous spending is paused. | Unfreeze (`frozen: false`). Owner withdraw still works. |
+| `per_trade_cap` | 422 | The buy exceeds `per_trade_sol`. | Lower the amount or raise the cap. |
+| `daily_budget` | 422 | The buy would exceed the rolling-24h SOL budget. | Wait for the window to roll, or raise the budget. |
+| `per_tx_exceeded` | 403 | The tx exceeds `per_tx_usd`. | Lower the amount or raise the per-tx USD limit. |
+| `daily_exceeded` | 403 | The tx would exceed `daily_usd`. | Wait, or raise the daily USD limit. |
+| `max_positions` | 409 | Open trades already at `max_concurrent`. | Close a position before opening another. |
+| `price_impact` | 422 | Price impact above `max_price_impact_pct`. | Lower the trade size or raise the breaker. |
+| `insufficient_sol` | 400 | Wallet can't cover the spend plus fee/rent headroom. | Fund the wallet and retry. |
+| `destination_not_allowed` | 403 | Withdraw target not on `withdraw_allowlist`. | Add the address, or send to an allowed one. |
+
+`detail` carries the raw numbers — e.g. `per_trade_cap` returns
+`{ amount_lamports, cap_lamports }`, `daily_budget` returns
+`{ spent_lamports, amount_lamports, budget_lamports }` — so a UI can render the
+exact overage without re-deriving it.
+
+## Examples
+
+**Provision a new agent with conservative rails** before handing it a key:
+
+```js
+const a = guards(agentId, { token });
+
+await a.setTradeLimits({
+ per_trade_sol: 0.25,
+ daily_budget_sol: 1,
+ max_concurrent: 3,
+ max_price_impact_pct: 8,
+});
+await a.setSpendLimits({ daily_usd: 100, per_tx_usd: 25 });
+```
+
+**Gate an LLM tool call** — let the model propose, but never let it sign past the
+leash:
+
+```js
+async function agentBuy({ mint, sol }) {
+ const check = await a.checkTrade({ side: 'buy', mint, amount: sol });
+ if (!check.allowed) {
+ return { ok: false, reason: check.reason, message: check.message };
+ }
+ return a.trade({ side: 'buy', mint, amount: sol, idempotency_key: crypto.randomUUID() });
+}
+```
+
+**Emergency stop** — freeze every autonomous path while you investigate, without
+locking yourself out of the funds:
+
+```js
+await a.setSpendLimits({ frozen: true }); // trades, snipes, x402 all rejected; withdraw stays open
+```
+
+**Read the policy under the hood** — the raw HTTP this SDK wraps:
+
+```js
+const res = await fetch(`https://three.ws/api/agents/${agentId}/trade/limits`, {
+ headers: { authorization: `Bearer ${token}` },
+});
+const { data } = await res.json(); // { limits, defaults }
+```
+
+## Related
+
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay x402 endpoints; the same spend policy governs every payment.
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — give your guarded agent a 3D body.
+
+---
+
+<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>
diff --git a/packages/irl/README.md b/packages/irl/README.md
new file mode 100644
index 000000000..1a4b87876
--- /dev/null
+++ b/packages/irl/README.md
@@ -0,0 +1,329 @@
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>
+</p>
+
+<h1 align="center">@three-ws/irl</h1>
+
+<p align="center"><strong>Geofenced, real-world presence for agents and avatars — check in at a place, prove you were there, discover who and what is nearby.</strong></p>
+
+<p align="center">
+ <a href="https://www.npmjs.com/package/@three-ws/irl"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/irl?logo=npm&color=cb3837"></a>
+ <a href="https://www.npmjs.com/package/@three-ws/irl"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/irl?color=cb3837"></a>
+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/irl?color=3b82f6">
+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/irl?color=339933&logo=node.js">
+</p>
+
+<p align="center">
+ <a href="#install">Install</a> ·
+ <a href="#quick-start">Quick start</a> ·
+ <a href="#api">API</a> ·
+ <a href="#how-it-works">How it works</a> ·
+ <a href="https://three.ws/irl">three.ws</a>
+</p>
+
+---
+
+> `@three-ws/irl` is the official client for **three.ws IRL** — the layer that
+> drops 3D agents and avatars at real-world GPS coordinates and lets people
+> *stumble onto them in AR by walking up*. You check in at a spot, mint a
+> short-lived proof-of-presence token from your live fix, and read back only the
+> agents within a tight radius of where you actually stand. It wraps the public
+> `/api/irl/*` endpoints: presence minting, GPS pin placement, the geofenced
+> nearby feed, and the real-world interaction log. Presence is the contract —
+> there is no browseable map, no roster, no "query any point on earth." You see
+> what's around you, because you're there. It pairs with
+> [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) (make the
+> avatar) and [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)
+> (render it where you placed it).
+
+## Why
+
+Hand-rolling "agents in the real world" looks easy until you hit the privacy
+math. A naive `GET /pins?lat=&lng=` is a location-harvest API: anyone scripts a
+grid sweep and reconstructs every placement on earth. three.ws IRL closes that
+hole structurally, and this SDK gives you the whole flow as four functions:
+
+- **Presence is proven, not claimed.** Before you can read nearby agents you
+ mint a fix token from your *real* geolocation. The server only answers for the
+ coarse area that token was minted in — "query anywhere" becomes "query where
+ you are." No token banking, no remote scraping.
+- **Tight by default.** The nearby feed is radius-capped at **60 m** (default
+ 40 m), returns at most 50 pins, and is IP rate-limited with sweep detection —
+ large enough to render an agent as you walk up, small enough that one read only
+ ever reveals the handful right where you stand.
+- **Anonymous-friendly.** Place and manage pins from a device token — no login.
+ Authenticated owners get permanent pins; anonymous pins lapse after 7 days.
+- **Coordinates are minimized.** The public feed coarsens lat/lng to ~1.1 m,
+ never returns owner ids, and never logs the caller's position.
+
+This is the SDK twin of the live [/irl](https://three.ws/irl) surface — the same
+endpoints, exposed as plain functions.
+
+## Install
+
+```bash
+npm install @three-ws/irl
+```
+
+Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch` and,
+in the browser, the Geolocation API). To render what you discover, add
+[`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar).
+
+## Quick start
+
+Check in where you stand, then see who's around:
+
+```js
+import { checkIn, nearby } from '@three-ws/irl';
+
+const fix = await checkIn(); // reads the browser's GPS, mints a presence token
+const agents = await nearby(fix); // only answers for the area you checked in at
+
+for (const a of agents) {
+ console.log(a.avatar_name, `${a.distance_m}m away`, a.caption);
+}
+```
+
+Place your own agent at the spot you're standing on:
+
+```js
+import { checkIn, placePin } from '@three-ws/irl';
+
+const fix = await checkIn();
+const { pin } = await placePin({
+ lat: fix.lat,
+ lng: fix.lng,
+ avatarName: 'Scout',
+ avatarUrl: 'https://cdn.three.ws/forge/scout.glb', // from @three-ws/forge
+ caption: 'Say hi — I drop $THREE alpha here',
+});
+
+console.log(pin.id, pin.permanent ? 'permanent' : 'expires in 7 days');
+```
+
+Pass explicit coordinates (Node, or any non-browser fix source):
+
+```js
+const fix = await checkIn({ lat: 40.7411, lng: -73.9897 });
+const agents = await nearby(fix, { radius: 60 });
+```
+
+Log that you met an agent IRL:
+
+```js
+import { interact } from '@three-ws/irl';
+await interact({ pinId: agent.id, type: 'tap', message: 'Found you in Madison Square Park' });
+```
+
+## API
+
+### `checkIn(input?) → Promise<Presence>`
+
+Establish presence at a location. With no argument it reads the browser's
+Geolocation API; pass `{ lat, lng, accuracy? }` to supply a fix yourself. Mints a
+short-lived proof-of-presence token via `POST /api/irl/fix-token` and returns it
+alongside the fix so `nearby()` can prove the read.
+
+**Returns** `Presence`
+
+| Field | Type | Notes |
+|---|---|---|
+| `lat` / `lng` | `number` | The fix used to mint the token. |
+| `token` | `string` | HMAC-signed presence token (header `x-irl-fix` on reads). |
+| `expires_in` | `number` | Token lifetime in seconds — **180** (3 min). Re-`checkIn()` when it lapses. |
+| `cell` | `string` | The precision-7 geohash (~153 m) the fix fell in — the client's "re-mint on cell change" trigger. |
+
+The token anchor is coarsened to ~110 m server-side, so the token itself never
+carries a fine coordinate. A read is authorized only when its claimed point is
+within **250 m** of the anchor and the token is unexpired.
+
+### `nearby(presence, options?) → Promise<Pin[]>`
+
+Read agents within the radius of where you checked in. Wraps
+`GET /api/irl/pins?lat=&lng=&radius=` with the presence token in the `x-irl-fix`
+header.
+
+| Option | Type | Default | Notes |
+|---|---|---|---|
+| `radius` | `number` | `40` | Metres. Clamped server-side to **10–60 m**. |
+
+Each returned `Pin` (allow-list projection — never `user_id` or `device_token`):
+
+| Field | Type | Notes |
+|---|---|---|
+| `id` | `string` | Pin UUID. |
+| `agent_id` | `string \| null` | Linked agent identity, if any. |
+| `lat` / `lng` | `number` | Coarsened to ~1.1 m (5 dp). |
+| `heading` | `number` | Facing, 0–359°. |
+| `distance_m` | `number` | Great-circle metres from your fix. |
+| `avatar_url` | `string` | GLB to load (relative or first-party https). |
+| `avatar_name` / `caption` | `string \| null` | Public display text. |
+| `x402_endpoint` | `string \| null` | First-party pay target for the agent. |
+| `view_count` | `number` | Deduplicated visitor count. |
+| `avatar_version` | `number` | Bumps on a remote outfit re-skin — diff to swap the GLB. |
+| `room_id`, `rel_east_m`, `rel_north_m`, `origin_*` | — | Room frame for shared-anchor clusters (null on standalone pins). |
+| `is_mine` | `boolean` | True for the caller's own pins. |
+
+Pins are sorted nearest-first and filtered to those within `radius`.
+
+### `placePin(input) → Promise<{ pin }>`
+
+Drop a 3D agent at a coordinate. Wraps `POST /api/irl/pins`.
+
+| Field | Type | Notes |
+|---|---|---|
+| `lat` / `lng` | `number` | **Required.** Range-checked. |
+| `heading` | `number` | Initial facing in degrees (default 0). |
+| `avatarUrl` | `string` | GLB URL — relative same-origin or https (no private hosts). |
+| `avatarName` | `string` | ≤ 40 chars. |
+| `caption` | `string` | ≤ 140 chars. Content-gated; may reference only `$THREE`. |
+| `agentId` | `string` | Link the pin to a registered agent. |
+| `x402Endpoint` | `string` | Pay target — must be a first-party three.ws host. |
+| `anchor` | `object` | Optional pose `{ heightM, yawDeg, quat, source }` for AR replay. |
+| `placementKind` | `'precise' \| 'approximate'` | `approximate` blurs the spot by `fuzzRadiusM` (10–500 m). |
+
+Pass the device token (anonymous ownership) via the `deviceToken` field or set a
+default with `configure({ deviceToken })`. Returns `201` with the created pin and
+a `permanent` flag (`true` for signed-in owners, `false` — 7-day expiry — for
+anonymous).
+
+### `myPins(options?) → Promise<Pin[]>`
+
+List the pins you placed. With a device token, wraps `GET /api/irl/pins/mine`
+(the token rides the `x-irl-device` header, never the URL); for a signed-in
+session, `GET /api/irl/pins?mine=1`.
+
+### `interact(input) → Promise<object>`
+
+Log a real-world encounter. Wraps `POST /api/irl/interactions`.
+
+| Field | Type | Notes |
+|---|---|---|
+| `pinId` | `string` | **Required.** The agent you met. |
+| `type` | `'view' \| 'tap' \| 'message' \| 'pay'` | `view` repeats from one device collapse within 5 min. |
+| `message` | `string` | ≤ 280 chars (for `message`). |
+| `deviceToken` | `string` | Anonymous viewer attribution. |
+
+`agent_id` and owner are taken from the pin, never the caller. A `pay` must carry
+a valid on-chain settlement signature and a `$THREE`/USDC mint, and is deduped
+per signature.
+
+### `removePin(id, options?)` · `purgePins(options?)` · `configure(opts)`
+
+`removePin` wraps `DELETE /api/irl/pins?id=`; `purgePins` wraps the bulk
+`DELETE /api/irl/pins?all=1` for a device token. `configure({ baseUrl,
+deviceToken })` sets defaults for the module (base origin defaults to
+`https://three.ws`).
+
+## How it works
+
+Presence is the gate on every read. You can never query a point you aren't at:
+
+```
+ browser GPS / explicit { lat, lng }
+ │
+ ▼ POST /api/irl/fix-token
+ ┌──────────────────────────────────────────┐
+ │ mint: HMAC( anchor≈110m, geohash-7≈153m, │ token (TTL 180s), cell
+ │ issued-at ) │
+ └───────────────────┬──────────────────────┘
+ │ x-irl-fix: <token>
+ ▼ GET /api/irl/pins?lat=&lng=&radius=
+ ┌──────────────────────────────────────────┐
+ │ verify: claimed point within 250m of the │ radius ≤ 60m · ≤ 50 pins
+ │ token anchor · unexpired · unforged │ coords coarsened to ~1.1m
+ └───────────────────┬──────────────────────┘
+ ▼
+ nearby agents (nearest-first)
+```
+
+- **Geohash precision.** The server uses a **precision-7 geohash (~153 m × 153 m
+ cell)** as the spatial key. It's the density unit (≤ 40 pins per cell, so one
+ actor can't carpet-bomb a plaza), the presence token's `cell` (your re-mint
+ trigger as you walk), and the sweep-detection bucket (reading many distinct
+ cells in 120 s fires a coordinate-free ops alert).
+- **Proof-of-presence math.** Token TTL **180 s**, anchor coarsened to **~110 m**
+ (`ANCHOR_DP = 3`), read tolerance **250 m** from the anchor (~one cell plus
+ edge slack, so polling stays seamless across a cell boundary).
+- **No fan-out.** A placement or edit is never broadcast as a roster — it reaches
+ a viewer only on their next proximity poll, and only once they're physically
+ within the radius.
+- **Dev/preview.** Enforcement turns on only when `IRL_FIX_SECRET` (≥ 16 chars)
+ is set. Without it, mint + verify still work self-consistently so local testing
+ isn't gated — but the nearby read does not gate on the token.
+
+## Errors & edge cases
+
+`nearby()` and the write functions reject with a typed `IrlError` carrying a
+`code` mapped from the endpoint's response:
+
+| `code` | HTTP | Meaning | Recovery |
+|---|---|---|---|
+| `fix_required` | 401 | Presence token missing/`expired`/`forged`/`out_of_area`. | Call `checkIn()` again — the fix lapsed or you moved. |
+| `lat_lng_required` | 400 | No coordinates on a read or placement. | Provide `lat`/`lng`. |
+| `invalid_coordinates` | 400 | Out-of-range lat/lng. | Send a real fix. |
+| `area_full` | 429 | The ~150 m cell already holds 40 agents. | Place in another spot. |
+| `pin_limit` | 429 | Active-pin cap reached (20 anon / 60 signed). | Remove an old pin. |
+| `rate` | 429 | Placing too fast (5/min burst, 30/h). | Honour `retryAfter`. |
+| `content` | 422 | Caption/name blocked, or names a coin other than `$THREE`. | Reword. |
+| `endpoint` | 422 | `x402Endpoint` host isn't first-party. | Use a three.ws pay target. |
+| `not_found` | 404 | Pin gone (expired / hidden / not yours). | Refresh your list. |
+| `rate_limiter_unavailable` | 429 | The read limiter couldn't decide — it fails **closed**. | Retry shortly. |
+
+Every state is designed. A lapsed fix returns `fix_required` (not a blank feed),
+a saturated area returns `area_full` (not a silent drop). Surface them the same
+way in your UI — `fix_required` is the "Getting your location…" state, not an
+error toast.
+
+## Examples
+
+**Walk-up discovery loop (browser)** — re-check in when the cell changes:
+
+```js
+import { checkIn, nearby } from '@three-ws/irl';
+
+let presence = await checkIn();
+setInterval(async () => {
+ const next = await checkIn(); // cheap; re-mints on movement
+ if (next.cell !== presence.cell) presence = next;
+ const agents = await nearby(presence);
+ render(agents); // your AR / map layer
+}, 10_000); // ~6 reads/min, well under the 60/min ceiling
+```
+
+**Place a Forge-made avatar where you stand** — full chain:
+
+```js
+import { forge } from '@three-ws/forge';
+import { checkIn, placePin } from '@three-ws/irl';
+
+const model = await forge('a friendly courier robot, full body');
+const fix = await checkIn();
+const { pin } = await placePin({
+ lat: fix.lat, lng: fix.lng,
+ avatarUrl: model.glbUrl,
+ avatarName: 'Courier',
+ caption: 'Tap to trade $THREE',
+});
+```
+
+**Anonymous, no login** — manage pins by device token:
+
+```js
+import { configure, placePin, myPins, purgePins } from '@three-ws/irl';
+
+configure({ deviceToken: crypto.randomUUID() }); // stored client-side, header-only
+await placePin({ lat: 51.5079, lng: -0.0877, avatarName: 'Guide' });
+const mine = await myPins();
+await purgePins(); // wipe every pin from this device
+```
+
+## Related
+
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate the avatar you place.
+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render and animate a discovered pin's GLB.
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — pay an agent's `x402_endpoint` in USDC.
+
+---
+
+<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>
diff --git a/packages/irl/package.json b/packages/irl/package.json
new file mode 100644
index 000000000..41a8d1f5d
--- /dev/null
+++ b/packages/irl/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "@three-ws/irl",
+ "version": "0.1.0",
+ "description": "Geofenced, real-world presence for agents and avatars — check in at a GPS spot with a proof-of-presence fix, discover who's nearby, and log real encounters. The three.ws IRL client.",
+ "keywords": [
+ "irl",
+ "geolocation",
+ "geofence",
+ "geohash",
+ "proof-of-presence",
+ "proximity",
+ "ar",
+ "agents",
+ "avatar",
+ "presence",
+ "three.ws"
+ ],
+ "license": "MIT",
+ "private": true,
+ "type": "module",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nirholas/three.ws"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ }
+}
diff --git a/packages/naming-mcp/src/config.js b/packages/naming-mcp/src/config.js
new file mode 100644
index 000000000..3e5c314ca
--- /dev/null
+++ b/packages/naming-mcp/src/config.js
@@ -0,0 +1,34 @@
+// Centralized env + HTTP base for the naming MCP.
+//
+// This server is a thin, read-only wrapper over the PUBLIC three.ws HTTP API
+// (/api/sns and /api/threews/subdomain). It signs nothing and holds no secret —
+// the only knobs are which deployment to talk to and how long to wait. Nothing
+// about how a name resolves is baked in here; it all comes from the live
+// endpoint backed by Solana / Bonfida SNS.
+
+export function env(key, fallback) {
+ const v = process.env[key];
+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;
+}
+
+// Base URL of the three.ws API that serves /api/sns and /api/threews/subdomain.
+// Override only when self-hosting or pointing at a preview deployment.
+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');
+
+// Per-request timeout (ms). Resolution and availability checks hit a Solana RPC
+// pool, so the default leaves room for a cold lookup; cached reads finish well
+// within it.
+export const HTTP_TIMEOUT_MS = (() => {
+ const raw = env('THREE_WS_TIMEOUT_MS');
+ if (raw === undefined) return 20000;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n <= 0) {
+ throw Object.assign(new Error(`THREE_WS_TIMEOUT_MS must be a positive number (got "${raw}")`), {
+ code: 'bad_config',
+ });
+ }
+ return n;
+})();
+
+// Identifies this client to the API in request logs.
+export const USER_AGENT = '@three-ws/naming-mcp';
diff --git a/packages/naming-mcp/src/lib/api.js b/packages/naming-mcp/src/lib/api.js
new file mode 100644
index 000000000..6eac2451a
--- /dev/null
+++ b/packages/naming-mcp/src/lib/api.js
@@ -0,0 +1,66 @@
+// Real HTTP access to the three.ws API. No mocks, no fixtures — every call is
+// a live request to THREE_WS_BASE. Errors are normalized into a single shape so
+// tool handlers can surface a clean message + status to the MCP client.
+
+import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT } from '../config.js';
+
+/**
+ * Call a three.ws HTTP endpoint and return its parsed JSON body.
+ *
+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/sns`).
+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown }} [opts]
+ * @returns {Promise<any>} Parsed JSON response.
+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error'),
+ * and on upstream errors `.status` + `.body`.
+ */
+export async function apiRequest(path, { method = 'GET', query, body } = {}) {
+ const url = new URL(`${THREE_WS_BASE}${path}`);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null || value === '') continue;
+ url.searchParams.set(key, String(value));
+ }
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);
+
+ let res;
+ try {
+ res = await fetch(url, {
+ method,
+ headers: {
+ accept: 'application/json',
+ 'user-agent': USER_AGENT,
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ signal: controller.signal,
+ });
+ } catch (err) {
+ clearTimeout(timer);
+ if (err?.name === 'AbortError') {
+ throw Object.assign(new Error(`three.ws ${path} timed out after ${HTTP_TIMEOUT_MS}ms`), {
+ code: 'timeout',
+ });
+ }
+ throw Object.assign(new Error(`three.ws ${path} request failed: ${err?.message || err}`), {
+ code: 'network_error',
+ });
+ }
+ clearTimeout(timer);
+
+ const text = await res.text();
+ let data;
+ try {
+ data = text ? JSON.parse(text) : {};
+ } catch {
+ data = { raw: text };
+ }
+
+ if (!res.ok) {
+ const message = data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;
+ throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });
+ }
+ return data;
+}
diff --git a/packages/pose/README.md b/packages/pose/README.md
new file mode 100644
index 000000000..7185ce694
--- /dev/null
+++ b/packages/pose/README.md
@@ -0,0 +1,296 @@
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>
+</p>
+
+<h1 align="center">@three-ws/pose</h1>
+
+<p align="center"><strong>Turn a phrase into a pose — a deterministic seed plus the full joint-rotation map for a rigged 3D avatar.</strong></p>
+
+<p align="center">
+ <a href="https://www.npmjs.com/package/@three-ws/pose"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/pose?logo=npm&color=cb3837"></a>
+ <a href="https://www.npmjs.com/package/@three-ws/pose"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/pose?color=cb3837"></a>
+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/pose?color=3b82f6">
+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/pose?color=339933&logo=node.js">
+</p>
+
+<p align="center">
+ <a href="#install">Install</a> ·
+ <a href="#quick-start">Quick start</a> ·
+ <a href="#api">API</a> ·
+ <a href="#how-it-works">How it works</a> ·
+ <a href="https://three.ws/pose">three.ws</a>
+</p>
+
+---
+
+> `@three-ws/pose` is the official client for the three.ws **Pose Studio** — the
+> engine behind [three.ws/pose](https://three.ws/pose). It maps a natural-language
+> pose description (`"warrior stance"`, `"wave hello"`, `"sitting cross-legged"`)
+> to a **deterministic seed** and the **complete Euler joint-rotation map** for the
+> three.ws humanoid mannequin, picked from an in-repo library of named preset poses.
+> The same prompt always yields the same pose, so it is a perfect way to *seed* or
+> *initialize* a rigged character before you hand off to keyframes or live control.
+> It wraps the public `pose_model` tool on the auth-free `/api/mcp-3d` server — pure,
+> local, deterministic compute, no model inference, no external calls. It pairs with
+> [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) (which *makes & rigs*
+> the avatar) and [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)
+> (which *renders* it).
+
+## Why
+
+You have a rigged humanoid GLB and you want it to *do* something — not a baked clip,
+just a single, named static pose to start from. Hand-authoring Euler rotations per
+joint is tedious and error-prone: which axis bends the elbow, how far does the
+shoulder open, where does the root drop for a crouch? Pose Studio answers that once,
+for a curated library of real poses, and exposes it as a single call:
+
+- **A phrase in, a pose out.** `poseSeed('warrior stance')` resolves to a full
+ `jointName → { x, y, z }` rotation map in radians, ready to apply to your rig.
+- **Deterministic by design.** The result is keyed by `sha256(prompt|presetId)`.
+ Same prompt, same machine, same pose — every time. Reproducible across runs, CI,
+ and clients. No randomness, no drift.
+- **Always a real pose.** Selection scores your prompt against preset labels, ids,
+ and groups; on no match it falls back to a deterministic pick. There is no synthetic
+ or empty-pose codepath — you always get a usable, hand-tuned pose back.
+- **Free and offline-shaped.** The underlying tool is pure local computation — no
+ GPU, no inference, no key. It is one of the cheapest, fastest surfaces on the
+ platform.
+
+This is the SDK twin of the [3D Studio MCP server](https://three.ws/mcp) — the same
+preset engine, exposed as plain functions instead of an MCP tool.
+
+## Install
+
+```bash
+npm install @three-ws/pose
+```
+
+Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`).
+To render or rig the avatar you pose, add
+[`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) and
+[`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge).
+
+## Quick start
+
+No key, no wallet:
+
+```js
+import { poseSeed } from '@three-ws/pose';
+
+const pose = await poseSeed('wave hello');
+
+console.log(pose.presetId); // → 'wave'
+console.log(pose.seed); // → '8c12…e0f9' (stable sha256-derived)
+console.log(pose.parameters); // → { shoulderR: { x: 0, y: 0, z: -2.45 }, elbowR: { x: -1.2, … }, … }
+console.log(pose.previewUrl); // → https://three.ws/pose?seed=8c12…&preset=wave
+```
+
+Apply the rotations straight to a Three.js skeleton:
+
+```js
+import { poseSeed } from '@three-ws/pose';
+
+const { parameters } = await poseSeed('the thinker');
+
+for (const [jointName, euler] of Object.entries(parameters)) {
+ if (jointName === 'rootPosition') {
+ rig.position.set(euler.x, euler.y, euler.z); // optional whole-figure offset
+ continue;
+ }
+ const bone = rig.getObjectByName(jointName);
+ if (bone) bone.rotation.set(euler.x, euler.y, euler.z); // radians
+}
+```
+
+Same prompt, same pose — useful as a fixed initialization seed:
+
+```js
+const a = await poseSeed('crouch');
+const b = await poseSeed('crouch');
+console.log(a.seed === b.seed); // → true, always
+```
+
+## API
+
+### `poseSeed(prompt, options?) → Promise<PoseResult>`
+
+Resolve a natural-language pose description to a deterministic seed and the full
+joint-rotation map. `prompt` is a string, 1–500 characters.
+
+**Options**
+
+| Option | Type | Default | Notes |
+|---|---|---|---|
+| `endpoint` | `string` | `https://three.ws/api/mcp-3d` | Override the Pose Studio MCP endpoint. |
+| `previewBase` | `string` | `https://three.ws/pose` | Base URL for the returned `previewUrl`. |
+| `signal` | `AbortSignal` | — | Cancel an in-flight call. |
+
+**Returns** `PoseResult`
+
+| Field | Type | Notes |
+|---|---|---|
+| `seed` | `string` | 16-hex stable id, `sha256(prompt\|presetId).slice(0,16)`. |
+| `presetId` | `string` | The picked preset's id, e.g. `'wave'`, `'warrior2'`, `'crouch'`. |
+| `presetLabel` | `string` | Human label, e.g. `'Wave hello'`, `'Warrior II (yoga)'`. |
+| `group` | `string` | One of `Standing`, `Action`, `Sitting & Floor`, `Expressive`. |
+| `parameters` | `Record<string, { x, y, z }>` | Joint → Euler rotation **in radians**. May include `rootPosition` (a translation, not a rotation). |
+| `previewUrl` | `string` | Open the result on `three.ws/pose` with `seed` + `preset` params. |
+| `match` | `{ score: number, reason: string }` | `reason` is `token-match` or `no-match-deterministic-pick`. |
+| `groups` | `string[]` | All four preset groups, for building a picker. |
+
+`parameters` follows the mannequin convention: in rest pose every rotation is `0`,
+arms at the sides. `shoulder.z` opens an arm outward, `shoulder.x` is forward(−)/
+back(+), `elbow.x` bends (negative bends the forearm up). Joints not present in a
+pose are at rest (`0`).
+
+### `presetPose(presetId, options?) → Promise<PoseResult>`
+
+Skip selection and resolve a specific preset by id — handy once a user has chosen one
+from a picker. Internally seeds with the preset id as the prompt, so the same preset
+always returns the same seed.
+
+### `listPresetGroups() → string[]`
+
+The four pose groups, returned synchronously for menu scaffolding:
+`['Standing', 'Action', 'Sitting & Floor', 'Expressive']`.
+
+## How it works
+
+`poseSeed()` issues a single `tools/call` to the `pose_model` tool on the Streamable
+HTTP MCP server at `POST /api/mcp-3d`. The tool is **pure local computation** — it
+scores your prompt against an in-repo library of named presets, picks one, derives a
+seed, and returns the preset's pre-authored rotation map. No image model, no GPU, no
+state.
+
+```
+prompt ("warrior stance")
+ │
+ ▼
+ tokenize → score every preset by token overlap
+ (preset id + label + group all contribute vocabulary)
+ │
+ ├─ best score > 0 ──▶ token-match ─────────┐
+ └─ no overlap ──────▶ sha256(prompt) % N ───┤ (deterministic fallback)
+ ▼
+ picked preset { id, label, group, pose }
+ │
+ seed = sha256(prompt | presetId).slice(0,16) ▼
+ { seed, presetId, parameters, previewUrl, … }
+```
+
+The preset library spans four groups — **Standing** (T-pose, A-pose, relaxed,
+contrapposto, arms-up, wave, hands-on-hips), **Action** (walk-step, run, jump, punch,
+archery, superhero-landing), **Sitting & Floor** (chair, floor, kneel, crouch,
+thinker), and **Expressive** (praying, meditate, warrior II, arabesque, flex, point) —
+the same data the public [/pose](https://three.ws/pose) page renders.
+
+### Under the hood — the raw HTTP
+
+The SDK is a thin wrapper. The wire call is a standard MCP `tools/call`:
+
+```js
+const res = await fetch('https://three.ws/api/mcp-3d', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'pose_model', arguments: { prompt: 'warrior stance' } },
+ }),
+});
+
+const { result } = await res.json();
+const pose = result.structuredContent;
+// → { seed, preset_id, preset_label, group, parameters, preview_url, match, groups }
+```
+
+The HTTP tool returns **snake_case** keys (`preset_id`, `preview_url`); the SDK
+normalizes them to the camelCase `PoseResult` shape above. The identical engine is
+also exposed as the paid stdio MCP tool **`get_pose_seed`** ($0.001 USDC), which
+returns the camelCase fields directly — use that when you are already inside an MCP
+agent session.
+
+## Pricing
+
+The deterministic pose computation is **free** on the public `/api/mcp-3d` endpoint —
+no payment, no key, no wallet. It is pure local compute with nothing to meter.
+
+When the same capability is reached through a paid MCP transport, it settles in USDC
+on Solana mainnet over [x402](https://x402.org):
+
+| Surface | Tool | Price | Transport |
+|---|---|---|---|
+| `@three-ws/pose` SDK | `pose_model` | **free** | HTTP (`POST /api/mcp-3d`) |
+| stdio MCP server | `get_pose_seed` | **$0.001 USDC** | stdio (`exact` scheme) |
+
+Prices are authoritative in the server's discovery response — read them at runtime
+rather than hardcoding.
+
+## Errors & edge cases
+
+`poseSeed()` rejects with a typed `PoseError` carrying a `code`:
+
+| `code` | Meaning | Recovery |
+|---|---|---|
+| `invalid_prompt` | Prompt empty or over 500 chars (the tool requires 1–500). | Trim to a short phrase. |
+| `network` | The endpoint was unreachable. | Retry; honour the `signal`. |
+| `tool_error` | The MCP server returned a JSON-RPC error. | Inspect `error.data`; retry. |
+
+Designed states, not crashes:
+
+- **No keyword match** is not an error. The tool falls back to a deterministic pick
+ (`match.reason === 'no-match-deterministic-pick'`) and still returns a real pose.
+ Inspect `match.score === 0` if you want to flag a weak match in your UI.
+- **`rootPosition`** appears in `parameters` for poses that drop or lift the whole
+ figure (crouch, sit, jump). Treat it as a position offset, **not** a bone rotation.
+- **Determinism is per-prompt-string.** `"Wave"` and `"wave hello"` may resolve to
+ the same preset but produce **different seeds** (the seed hashes the exact prompt).
+ Reuse the exact prompt string for a stable seed.
+
+## Examples
+
+**Build a pose picker** from the live groups, then resolve a chosen preset:
+
+```js
+import { poseSeed, listPresetGroups } from '@three-ws/pose';
+
+for (const group of listPresetGroups()) renderGroupHeader(group);
+
+button.onclick = async () => {
+ const pose = await poseSeed(input.value || 'relaxed stand');
+ applyToRig(pose.parameters);
+ shareLink.href = pose.previewUrl;
+};
+```
+
+**Seed a freshly forged avatar** — generate, rig, then drop into a starting pose:
+
+```js
+import { forge, rig } from '@three-ws/forge';
+import { poseSeed } from '@three-ws/pose';
+
+const base = await forge('a cartoon astronaut, full body');
+const rigged = await rig(base.glbUrl); // animation-ready humanoid
+const start = await poseSeed('superhero landing'); // initial pose
+// load rigged.glbUrl, then apply start.parameters to its skeleton
+```
+
+**Agent / MCP** — the same capability is the `pose_model` tool on the 3D Studio
+server, and `get_pose_seed` on the paid stdio server. An agent that already holds an
+MCP session can call either with `{ prompt: 'kneeling' }` and receive the identical
+preset + seed.
+
+## Related
+
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate and auto-rig the humanoid GLB you pose.
+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render and animate the rigged, posed avatar.
+- [`@three-ws/mocap`](https://www.npmjs.com/package/@three-ws/mocap) — go beyond static poses: capture full pose/face/hand clips from webcam or video.
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-settle the paid stdio `get_pose_seed` lane.
+
+---
+
+<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>
diff --git a/packages/pose/package.json b/packages/pose/package.json
new file mode 100644
index 000000000..8241aae86
--- /dev/null
+++ b/packages/pose/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "@three-ws/pose",
+ "version": "0.1.0",
+ "description": "Deterministic, named pose seeds for rigged 3D avatars. Map a natural-language prompt to a stable seed + full Euler joint-rotation map from the three.ws pose-studio preset library.",
+ "keywords": [
+ "3d",
+ "pose",
+ "rig",
+ "skeleton",
+ "joint-rotation",
+ "avatar",
+ "humanoid",
+ "deterministic",
+ "seed",
+ "gltf",
+ "glb",
+ "three.ws"
+ ],
+ "license": "MIT",
+ "private": true,
+ "type": "module",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nirholas/three.ws"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ }
+}
diff --git a/packages/strategies/README.md b/packages/strategies/README.md
new file mode 100644
index 000000000..73d2718f0
--- /dev/null
+++ b/packages/strategies/README.md
@@ -0,0 +1,343 @@
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>
+</p>
+
+<h1 align="center">@three-ws/strategies</h1>
+
+<p align="center"><strong>Automated on-chain trading strategies for agents — DCA, copy-trading, and mirror execution, in one import.</strong></p>
+
+<p align="center">
+ <a href="https://www.npmjs.com/package/@three-ws/strategies"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/strategies?logo=npm&color=cb3837"></a>
+ <a href="https://www.npmjs.com/package/@three-ws/strategies"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/strategies?color=cb3837"></a>
+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/strategies?color=3b82f6">
+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/strategies?color=339933&logo=node.js">
+</p>
+
+<p align="center">
+ <a href="#install">Install</a> ·
+ <a href="#quick-start">Quick start</a> ·
+ <a href="#api">API</a> ·
+ <a href="#how-it-works">How it works</a> ·
+ <a href="https://three.ws">three.ws</a>
+</p>
+
+---
+
+> `@three-ws/strategies` is the official client for the three.ws **strategy
+> engine** — the system that turns a rule set into real, server-signed,
+> fully-leashed trading for an agent. Three strategy families, one import:
+> **DCA** (buy a fixed size on a daily/weekly schedule), **copy-trading**
+> (mirror a public leader's fills into your own wallet, non-custodial), and
+> **mirror execution** (custodial follow that sizes and lands a leader's trades
+> through your agent's wallet). Every order — scheduled, copied, or mirrored —
+> passes through the SAME spend guardrails (per-trade cap, daily budget, USD
+> ceiling, price-impact breaker, rug/honeypot firewall, kill switch) the
+> discretionary trade endpoint uses. A strategy can never bypass a limit. It
+> wraps the public three.ws strategy endpoints; this README documents both the
+> ergonomic SDK surface and the raw HTTP it sits on.
+
+## Why
+
+Automated trading is mostly plumbing nobody wants to write twice: a scheduler
+that survives restarts, a leader-trade detector, position sizing that respects a
+budget, idempotency so a retry never double-spends, MEV-aware broadcast, and an
+honest performance ledger. three.ws built that once, behind a small set of
+endpoints, and clamps every strategy to the agent's spend policy. This SDK is the
+one-line front door:
+
+- **One call per strategy.** `dca({ ... })`, `copy(leaderAgentId, { ... })`,
+ `mirror(agentId, leaderAgentId, { ... })`. No scheduler, no detector, no
+ signing code.
+- **Leashed by construction.** The strategy's own caps (per-trade size, slippage,
+ cooldown, max concurrent) are *additional* constraints on top of the agent's
+ server-side spend policy — never a way around it.
+- **Real performance only.** Rankings and stats come from real closed on-chain
+ positions. A strategy with no closed trades is honestly "unproven" — never a
+ fabricated backtest curve.
+- **Ownable & forkable.** Wrap a rule set as a [Strategy Object](#strategy-objects):
+ publish it, let others fork the *rules* (never wallet access), and rank it on a
+ real-performance leaderboard.
+
+This is the same engine that powers the strategy surfaces on
+[three.ws](https://three.ws), exposed as plain functions.
+
+## Install
+
+```bash
+npm install @three-ws/strategies
+```
+
+Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`).
+Auth is a three.ws session cookie or a bearer token — pass it once when you
+construct the client.
+
+## Quick start
+
+```js
+import { strategies } from '@three-ws/strategies';
+
+const sx = strategies({ token: process.env.THREE_WS_TOKEN }); // bearer or cookie
+
+// 1. DCA — buy a fixed size on a schedule, executed by the platform cron.
+await sx.dca({
+ agentId: 'THREEsynthetic-agent-uuid',
+ delegationId: 'THREEsynthetic-delegation-uuid',
+ tokenIn: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',
+ tokenOut: '0x0000000000000000000000000000000000000000',
+ tokenOutSymbol: 'THREE',
+ amountPerExecution: '1000000000000000000', // wei
+ interval: 'daily', // daily | weekly
+ slippageBps: 50,
+});
+
+// 2. Copy a public leader's fills into your own wallet (non-custodial).
+await sx.copy('THREEsynthetic-leader-uuid', {
+ copierWallet: 'THREEsynthetic1111111111111111111111111111',
+ fixedSol: 0.25,
+ perTradeCapSol: 0.5,
+ dailyBudgetSol: 2,
+});
+
+// 3. Mirror a leader through your agent's wallet (custodial, sized + landed).
+await sx.mirror('THREEsynthetic-agent-uuid', 'THREEsynthetic-leader-uuid', {
+ sizingMode: 'proportional',
+ proportionPct: 50,
+ maxPerTradeSol: 0.3,
+ dailyBudgetSol: 1.5,
+});
+```
+
+Every example uses `$THREE` (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`)
+or a clearly-synthetic placeholder. The engine is generic plumbing: the token to
+trade is always supplied at runtime — it never hardcodes a coin.
+
+## API
+
+### `strategies(options) → Client`
+
+| Option | Type | Default | Notes |
+|---|---|---|---|
+| `token` | `string` | — | Bearer token. Omit to rely on the three.ws session cookie. |
+| `baseUrl` | `string` | `https://three.ws` | Override for self-hosted / preview deploys. |
+| `network` | `'mainnet' \| 'devnet'` | `'mainnet'` | Default network for copy/mirror calls. |
+| `csrfToken` | `string` | — | Required for cookie-session writes (bearer clients are exempt). |
+
+### `dca(input) → Promise<DcaStrategy>`
+
+Create a dollar-cost-averaging strategy. The platform cron executes it on the
+chosen interval. Wraps `POST /api/dca-strategies`.
+
+| Field | Type | Notes |
+|---|---|---|
+| `agentId` | `string` (uuid) | The agent that owns the strategy. |
+| `delegationId` | `string` (uuid) | An **active**, unexpired delegation for that agent. |
+| `tokenIn` / `tokenOut` | `string` | `0x`-prefixed 40-char hex addresses. |
+| `tokenOutSymbol` | `string` | Must be on the operator's `DCA_ALLOWED_TOKEN_OUT` whitelist. |
+| `amountPerExecution` | `string` | Amount in wei (decimal integer string). |
+| `interval` | `'daily' \| 'weekly'` | Maps to `period_seconds` `86400` / `604800`. |
+| `chainId` | `number?` | Optional; falls back to the operator's `DCA_CHAIN_ID`. |
+| `slippageBps` | `number` | 1–500, default 50. Capped server-side at 500. |
+
+Returns `{ id, status, next_execution_at, created_at }`. Companion reads:
+`listDca(agentId)` (`GET /api/dca-strategies?agent_id=`, each row carries its
+`last_execution`) and `cancelDca(id)` (`DELETE /api/dca-strategies/:id`).
+
+### `copy(leaderAgentId, input) → Promise<Subscription>`
+
+Subscribe to a public leader. The copy engine sizes each of the leader's fills
+against your rules and drops a **copy intent** into your inbox — non-custodial,
+so you (or your agent) execute it from your own wallet. Wraps
+`POST /api/copy/subscriptions`.
+
+| Field | Type | Default | Notes |
+|---|---|---|---|
+| `copierWallet` | `string` | — | Your Solana address (base58). Required. |
+| `sizingRule` | `'fixed' \| 'multiplier' \| 'pct_balance'` | `'fixed'` | How each copy is sized. |
+| `fixedSol` | `number` | — | SOL per copy when `sizingRule: 'fixed'`. |
+| `multiplier` | `number` | — | × the leader's entry when `'multiplier'`. |
+| `pctBalance` | `number` | — | 0–100 % of your balance when `'pct_balance'`. |
+| `perTradeCapSol` | `number` | — | Hard cap per copy. Required, > 0. |
+| `minOrderSol` | `number` | `0` | Skip copies sized below this. |
+| `dailyBudgetSol` | `number` | — | Daily fan-out cap. Required, > 0. |
+| `maxOpenCopies` | `number` | `5` | Cap on pending intents (1–100). |
+| `mcapFloorUsd` / `mcapCeilingUsd` | `number?` | — | Skip coins outside this market-cap band. |
+| `copySells` | `boolean` | `true` | Mirror the leader's exits, not just entries. |
+| `requireSafetyPass` | `boolean` | `false` | Skip when coin safety can't be confirmed. |
+| `minOracleScore` | `number?` | — | 0–100 conviction gate. |
+| `perfFeeBps` | `number` | `1000` | Performance fee to the leader (0–3000 bps). |
+
+Reads: `listSubscriptions()`, `copyExecutions({ status })` (your intent inbox —
+`pending` by default), `pauseCopy(id)` / `stopCopy(id)`.
+
+### `mirror(agentId, leaderAgentId, input) → Promise<Follow>`
+
+**Custodial** follow: your agent's wallet sizes and lands the leader's trades
+automatically through the leashed runtime. Wraps the agent strategy surface
+(`POST /api/agents/:id/strategies` family).
+
+| Field | Type | Default | Notes |
+|---|---|---|---|
+| `sizingMode` | `'fixed' \| 'proportional' \| 'pct_balance'` | `'proportional'` | How each mirror is sized. |
+| `fixedSol` | `number` | — | SOL per mirror when `'fixed'`. |
+| `proportionPct` | `number` | `100` | % of the leader's size when `'proportional'`. |
+| `pctBalance` | `number` | — | 0–100 % of your balance when `'pct_balance'`. |
+| `maxPerTradeSol` | `number?` | — | Per-mirror cap (the agent's own cap is the hard backstop). |
+| `dailyBudgetSol` | `number?` | — | Per-follow daily cap (stacks under the agent's budget). |
+| `minLeaderSol` | `number` | `0` | Ignore leader buys below this. |
+| `copySells` | `boolean` | `true` | Mirror exits. |
+| `mintAllowlist` / `mintDenylist` | `string[]` | `[]` | Restrict / block specific mints. |
+
+Mirror controls: `killSwitch(agentId, engaged)` (per-owner global halt),
+`sweep(agentId)` ("run now"), and `equipped(agentId)` (live equips + open
+positions + kill state).
+
+### Strategy Objects
+
+A reusable, publishable, forkable rule set — ranked by **real** performance.
+
+| Method | Wraps | Purpose |
+|---|---|---|
+| `createStrategy({ name, config })` | `POST /api/strategies` | Author a rule set (validated before it persists). |
+| `listStrategies({ scope, sort, q })` | `GET /api/strategies` | `scope=mine\|published`; `sort=performance\|recent\|forks\|equips`. |
+| `getStrategy(id)` | `GET /api/strategies/:id` | One strategy + live performance + equip count. |
+| `leaderboard({ limit })` | `GET /api/strategies/leaderboard` | Proven strategies ranked by real ROI. |
+| `forkStrategy(id)` | `POST /api/strategies/:id/fork` | Clone the **rules** into your library (no wallet access transferred). |
+| `publishStrategy(id, published)` | `POST /api/strategies/:id/publish` | Toggle marketplace visibility. |
+| `updateStrategy(id, patch)` | `PATCH /api/strategies/:id` | Edit name/description/config (bumps version). |
+
+The `config` is a structured plan — `entry` (trigger, age, market-cap, liquidity,
+creator history), `sizing` (`amount_sol`, `max_slippage_bps`), `exits`
+(`take_profit_pct`, `stop_loss_pct`, `trailing_stop_pct`, `max_hold_minutes`),
+and `risk` (`max_concurrent_positions`, `cooldown_minutes`). It is normalized and
+bounds-checked server-side, so a malformed rule set can never be saved or run.
+
+## How it works
+
+```
+ DCA copy mirror
+ ┌──────────────┐ ┌───────────────────┐ ┌──────────────────┐
+ │ schedule + │ │ leader fills → │ │ leader fills → │
+ │ delegation │ │ planCopyOrder() │ │ planMirror() │
+ └──────┬───────┘ └─────────┬─────────┘ └────────┬─────────┘
+ │ cron tick │ sized INTENT │ sized order
+ ▼ ▼ (you execute) ▼
+ run-dca executor copy_executions inbox runStrategyTrade()
+ │ (non-custodial) │ (custodial)
+ └──────────────┬──────────────────────────────────┘
+ ▼
+ ┌──────────────────────────────────────────────┐
+ │ shared spend guardrails — kill switch, │
+ │ per-trade cap, daily budget, USD ceiling, │
+ │ price-impact breaker, rug/honeypot firewall, │
+ │ SOL headroom, custody idempotency │
+ └───────────────────────┬──────────────────────┘
+ ▼
+ MEV-aware execution (Jito-aware broadcast)
+ ▼
+ real on-chain fill → custody + position ledger
+```
+
+- **DCA** records a strategy bound to a delegation; the platform cron
+ (`run-dca`) executes it each interval and writes a `dca_executions` row per
+ fill (`tx_hash`, `amount_in`, `amount_out`, `status`).
+- **Copy** is non-custodial. The pure `planCopyOrder` engine sizes each leader
+ fill against your subscription, clamps it to your per-trade cap and remaining
+ daily budget, and emits a copy intent. You act on it from your own wallet — the
+ platform never signs.
+- **Mirror** is custodial. The pure `planMirror` engine sizes the leader's trade,
+ then `runStrategyTrade` runs it through the full guard + custody path and the
+ MEV-aware execution engine. Sizing is the *first* clamp; the agent's spend
+ policy is the hard backstop.
+- **Strategy Objects** drive the same custodial runtime from rules instead of a
+ leader: real pump.fun launches are matched against `entry`; open positions are
+ marked-to-market with real sell re-quotes and closed on TP / SL / trailing /
+ timeout.
+
+Every custodial fill is idempotency-keyed in the custody ledger, so a retried
+order replays instead of double-spending.
+
+## Errors & edge cases
+
+The SDK surfaces the endpoints' error codes as a typed `StrategyError` with a
+`code` and the HTTP `status`:
+
+| `code` | HTTP | Meaning | Recovery |
+|---|---|---|---|
+| `unauthorized` | 401 | No valid session/bearer. | Pass a `token` or sign in. |
+| `not_configured` | 400 | DCA whitelist or chain not set by the operator. | Set `DCA_ALLOWED_TOKEN_OUT` / `DCA_CHAIN_ID`, or pass `chainId`. |
+| `validation_error` | 400 | Bad field, off-whitelist symbol, or invalid rule set. | Read `errors`; fix the offending field. |
+| `delegation_expired` | 409 | The DCA delegation has lapsed. | Re-authorize a fresh delegation. |
+| `conflict` | 409 | An active DCA strategy already exists for this token pair. | Cancel the existing one first. |
+| `invalid_wallet` | 400 | `copierWallet` isn't a valid Solana address. | Provide a base58 address. |
+| `leader_not_found` | 404 | Leader isn't a public agent. | Use a public leader's agent id. |
+| `forbidden` | 403 | Not the owner of the agent/strategy. | Operate on your own resources. |
+| `not_found` | 404 | Unknown strategy / agent / subscription. | Check the id. |
+| `rate_limited` | 429 | Too many requests. | Honour `retryAfter` on the error. |
+
+Strategy runtime "skips" are designed states, not errors — every custodial skip
+carries a machine + human reason (`per_trade_cap`, `daily_budget`,
+`firewall_blocked`, `cooldown`, `max_concurrent`, `insufficient_sol`, …) so the
+owner's activity feed always explains why an order didn't fire. The copy and
+mirror engines do the same (`below_min_order`, `daily_budget_spent`,
+`mint_denylisted`, `mirror_killed`, …). Surface these — don't treat a leashed
+skip as a failure.
+
+## Examples
+
+**Schedule a weekly DCA into $THREE**
+
+```js
+await sx.dca({
+ agentId, delegationId,
+ tokenIn: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',
+ tokenOut: '0x0000000000000000000000000000000000000000',
+ tokenOutSymbol: 'THREE',
+ amountPerExecution: '500000000000000000',
+ interval: 'weekly',
+});
+```
+
+**Copy a leader, but only safe coins above a market-cap floor**
+
+```js
+await sx.copy(leaderAgentId, {
+ copierWallet: 'THREEsynthetic1111111111111111111111111111',
+ sizingRule: 'multiplier',
+ multiplier: 0.5,
+ perTradeCapSol: 0.4,
+ dailyBudgetSol: 3,
+ requireSafetyPass: true,
+ mcapFloorUsd: 50_000,
+});
+
+// Poll the non-custodial intent inbox and act from your own wallet.
+const { executions } = await sx.copyExecutions({ status: 'pending' });
+```
+
+**Publish a Strategy Object and rank it honestly**
+
+```js
+const { data } = await sx.createStrategy({
+ name: 'Fresh-launch momentum',
+ config: {
+ entry: { trigger: 'new_launch', max_age_minutes: 30, require_socials: true },
+ sizing: { amount_sol: 0.1, max_slippage_bps: 500 },
+ exits: { take_profit_pct: 150, stop_loss_pct: 40, trailing_stop_pct: 25 },
+ risk: { max_concurrent_positions: 3, cooldown_minutes: 10 },
+ },
+});
+await sx.publishStrategy(data.id, true);
+
+const { data: board } = await sx.leaderboard({ limit: 10 }); // proven, real-ROI ranked
+```
+
+## Related
+
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay any x402-gated three.ws endpoint.
+- [`@three-ws/agenc`](https://www.npmjs.com/package/@three-ws/agenc) — agent coordination + delegation primitives.
+- [`@three-ws/reputation`](https://www.npmjs.com/package/@three-ws/reputation) — ERC-8004 reputation behind leader discovery.
+- [`@three-ws/intel`](https://www.npmjs.com/package/@three-ws/intel) — market intel to feed strategy entry rules.
+
+---
+
+<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>
diff --git a/packages/vanity-mcp/src/config.js b/packages/vanity-mcp/src/config.js
new file mode 100644
index 000000000..9af81521e
--- /dev/null
+++ b/packages/vanity-mcp/src/config.js
@@ -0,0 +1,34 @@
+// Centralized env + HTTP base for the vanity MCP.
+//
+// This server is a thin, read-only wrapper over the PUBLIC three.ws HTTP API
+// (/api/vanity). It signs nothing and holds no secret — the only knobs are which
+// deployment to talk to and how long to wait. Nothing about how a bounty is
+// priced or an address is appraised is baked in here; it all comes from the live
+// endpoint.
+
+export function env(key, fallback) {
+ const v = process.env[key];
+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;
+}
+
+// Base URL of the three.ws API that serves /api/vanity. Override only when
+// self-hosting or pointing at a preview deployment.
+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');
+
+// Per-request timeout (ms). These are all read endpoints — quote runs an honest
+// difficulty oracle and the board/gallery hit a store — so the default is brisk
+// but leaves headroom for a cold cache.
+export const HTTP_TIMEOUT_MS = (() => {
+ const raw = env('THREE_WS_TIMEOUT_MS');
+ if (raw === undefined) return 20000;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n <= 0) {
+ throw Object.assign(new Error(`THREE_WS_TIMEOUT_MS must be a positive number (got "${raw}")`), {
+ code: 'bad_config',
+ });
+ }
+ return n;
+})();
+
+// Identifies this client to the API in request logs.
+export const USER_AGENT = '@three-ws/vanity-mcp';
diff --git a/packages/vanity-mcp/src/lib/api.js b/packages/vanity-mcp/src/lib/api.js
new file mode 100644
index 000000000..0aae62985
--- /dev/null
+++ b/packages/vanity-mcp/src/lib/api.js
@@ -0,0 +1,66 @@
+// Real HTTP access to the three.ws API. No mocks, no fixtures — every call is
+// a live request to THREE_WS_BASE. Errors are normalized into a single shape so
+// tool handlers can surface a clean message + status to the MCP client.
+
+import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT } from '../config.js';
+
+/**
+ * Call a three.ws HTTP endpoint and return its parsed JSON body.
+ *
+ * @param {string} path Endpoint path beginning with `/` (e.g. `/api/vanity/bounties`).
+ * @param {{ method?: string, query?: Record<string, unknown>, body?: unknown }} [opts]
+ * @returns {Promise<any>} Parsed JSON response.
+ * @throws {Error} with `.code` ('timeout' | 'network_error' | 'upstream_error'),
+ * and on upstream errors `.status` + `.body`.
+ */
+export async function apiRequest(path, { method = 'GET', query, body } = {}) {
+ const url = new URL(`${THREE_WS_BASE}${path}`);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null || value === '') continue;
+ url.searchParams.set(key, String(value));
+ }
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);
+
+ let res;
+ try {
+ res = await fetch(url, {
+ method,
+ headers: {
+ accept: 'application/json',
+ 'user-agent': USER_AGENT,
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ signal: controller.signal,
+ });
+ } catch (err) {
+ clearTimeout(timer);
+ if (err?.name === 'AbortError') {
+ throw Object.assign(new Error(`three.ws ${path} timed out after ${HTTP_TIMEOUT_MS}ms`), {
+ code: 'timeout',
+ });
+ }
+ throw Object.assign(new Error(`three.ws ${path} request failed: ${err?.message || err}`), {
+ code: 'network_error',
+ });
+ }
+ clearTimeout(timer);
+
+ const text = await res.text();
+ let data;
+ try {
+ data = text ? JSON.parse(text) : {};
+ } catch {
+ data = { raw: text };
+ }
+
+ if (!res.ok) {
+ const message = data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;
+ throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });
+ }
+ return data;
+}
diff --git a/packages/vanity-mcp/src/tools/vanity-quote.js b/packages/vanity-mcp/src/tools/vanity-quote.js
new file mode 100644
index 000000000..dc9f4bd6d
--- /dev/null
+++ b/packages/vanity-mcp/src/tools/vanity-quote.js
@@ -0,0 +1,44 @@
+// `vanity_quote` — honest difficulty→price oracle for a vanity pattern. Read-only.
+//
+// Wraps GET /api/vanity/bounties?view=quote. Pure function of the pattern: the
+// same prefix/suffix/ignoreCase always yields the same difficulty + suggested
+// USDC bounty, so this is idempotent.
+
+import { z } from 'zod';
+
+import { apiRequest } from '../lib/api.js';
+
+export const def = {
+ name: 'vanity_quote',
+ title: 'Quote the bounty price for a vanity pattern',
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Quote how hard a Solana vanity address is and what to escrow for it. Give a Base58 prefix and/or suffix and get the expected attempts, rarity tier, and an honest suggested USDC bounty (atomic units) from the difficulty→price oracle. Pure function of the pattern — no wallet, no payment, fully read-only. Use this before posting a grind-bounty so you escrow a fair amount.',
+ inputSchema: {
+ prefix: z.string().optional().describe('Base58 prefix the address must start with (e.g. "THREE").'),
+ suffix: z.string().optional().describe('Base58 suffix the address must end with.'),
+ ignoreCase: z.boolean().optional().describe('Match the pattern case-insensitively (cheaper, less rare). Default false.'),
+ },
+ async handler(args) {
+ const prefix = String(args?.prefix ?? '').trim();
+ const suffix = String(args?.suffix ?? '').trim();
+ if (!prefix && !suffix) {
+ throw Object.assign(new Error('Provide a prefix and/or suffix to quote.'), { code: 'validation_error', status: 400 });
+ }
+ const data = await apiRequest('/api/vanity/bounties', {
+ query: {
+ view: 'quote',
+ prefix: prefix || undefined,
+ suffix: suffix || undefined,
+ ignoreCase: args?.ignoreCase ? '1' : undefined,
+ },
+ });
+ return {
+ ok: true,
+ pattern: data?.pattern,
+ difficulty: data?.difficulty,
+ oracle: data?.oracle,
+ band: data?.band,
+ };
+ },
+};
diff --git a/src/trader.js b/src/trader.js
index b49a40563..078c53abd 100644
--- a/src/trader.js
+++ b/src/trader.js
@@ -158,6 +158,49 @@ function oracleBlock(oracle, agentId) {
</div>`;
}
+// --- Projected-vs-realized block ---------------------------------------------
+// The strategy was backtested over real captured history before it was armed.
+// Showing the projection NEXT TO what actually happened keeps it accountable —
+// a projection nobody checks is just marketing.
+function projectionBlock(p) {
+ const proj = p.projected || {};
+ const real = p.realized || {};
+ const traded = (real.closed_count || 0) > 0;
+ const pct = (v) => (v == null ? '—' : `${(v * 100).toFixed(0)}%`);
+ const signed = (v) => (v == null ? '—' : `<span class="${v >= 0 ? 'lb-pos' : 'lb-neg'}">${v > 0 ? '+' : ''}${Number(v).toFixed(1)}%</span>`);
+ const dd = (v) => (v == null ? '—' : `<span class="${v > 0 ? 'lb-neg' : 'lb-muted'}">${v > 0 ? '−' : ''}${Number(v).toFixed(1)}%</span>`);
+
+ const ran = p.ran_at ? relTime(p.ran_at) : null;
+ const conf = p.confidence ? `<span class="tp-proj-conf tp-proj-${escapeHtml(p.confidence)}">${escapeHtml(p.confidence)} confidence</span>` : '';
+
+ const row = (label, projVal, realVal) => `
+ <div class="tp-proj-row">
+ <span class="tp-proj-k">${escapeHtml(label)}</span>
+ <b class="tp-proj-proj">${projVal}</b>
+ <b class="tp-proj-real">${traded ? realVal : '<span class="lb-muted">no trades yet</span>'}</b>
+ </div>`;
+
+ return `
+ <div class="tp-oracle-block tp-proj-block">
+ <div class="tp-oracle-head">
+ <span class="tp-oracle-label">Projected vs realized</span>
+ ${conf}
+ </div>
+ <div class="tp-proj-grid">
+ <div class="tp-proj-row tp-proj-head">
+ <span class="tp-proj-k"></span>
+ <b class="tp-proj-proj">Backtested${p.window_days ? ` · ${p.window_days}d` : ''}</b>
+ <b class="tp-proj-real">Realized</b>
+ </div>
+ ${row('Win rate', pct(proj.win_rate), pct(real.win_rate))}
+ ${row('Avg / EV per trade', signed(proj.expected_value_pct), signed(real.avg_pnl_pct))}
+ ${row('Median ROI', signed(proj.roi_median_pct), signed(real.roi_pct))}
+ ${row('Max drawdown', dd(proj.max_drawdown_pct), dd(real.max_drawdown_pct))}
+ </div>
+ <p class="tp-oracle-note">Projection from a replay over ${p.sample_size || 0} real historical launches${ran ? `, run ${ran}` : ''}. ${p.insufficient_data ? 'Sample was thin — treat as directional only. ' : ''}Realized numbers are chain-proven once this agent starts trading. A strategy that beats its own backtest earns trust; one that misses it is held honest.</p>
+ </div>`;
+}
+
// --- Trade tables ------------------------------------------------------------
function closedRows(closed) {
if (!closed.length) return '<tr><td colspan="6" style="text-align:center;color:var(--ink-faint)">No closed trades in this window.</td></tr>';
@@ -250,6 +293,8 @@ function render(data) {
<div class="tp-metrics">${metricsGrid(m)}</div>
+ ${data.projection ? projectionBlock(data.projection) : ''}
+
${data.oracle ? oracleBlock(data.oracle, a.id) : ''}
<div class="tp-curve-wrap">