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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Market-maker engine, agent-mm worker, and SDK package sources
nirholas14540517f978
diff --git a/api/_lib/market-maker.js b/api/_lib/market-maker.jsnew file mode 100644index 000000000..030bd5340--- /dev/null+++ b/api/_lib/market-maker.js@@ -0,0 +1,547 @@+// Launch Copilot — autonomous fair-launch market-maker model + service layer.+//+// Single source of truth for the `market_maker_policies` model: presets,+// validation, the HARD anti-manipulation caps, ownership checks, the action+// ledger, and the derived live state. Shared by the API (api/launch/mm.js), the+// launch-time attach (api/pump/[action].js), and the engine worker+// (workers/agent-mm). The engine adds NO new way to move funds — it routes every+// fill through executeAgentTrade, the same firewall + spend-guard + custody path+// a manual trade uses. This module owns the rulebook; the worker owns the timing.+//+// Non-manipulation is a property of the policy, not a hope: a policy that would+// let the MM wash-trade, dominate volume, or round-trip in seconds is REFUSED at+// create time (assertPolicySafe), and the same caps are re-checked in the engine.++import { sql } from './db.js';++export const SOL = 1_000_000_000; // lamports per SOL++// ── anti-manipulation hard caps (the line the MM must never cross) ────────────+// These are enforced in BOTH directions: a create/update request outside them is+// refused with a plain-language reason, and the engine re-clamps at execution.+export const GUARDS = {+ // No two actions — and never a side flip — inside this window. The core+ // anti-wash-trade gate: you cannot buy then sell (or sell then buy) rapidly.+ MIN_ACTION_INTERVAL_SECONDS: 30,+ // A side flip (buy→sell / sell→buy) needs this multiple of the interval on top,+ // so the MM physically cannot round-trip to fake two-sided volume.+ SIDE_FLIP_INTERVAL_MULTIPLE: 2,+ // A single action may never exceed this share of live market volume.+ MAX_VOLUME_PCT_CEILING: 33,+ // Recycling can never be a dump: never sell more than this share of inventory+ // in one action, and a policy can't be configured above it.+ MAX_RECYCLE_PCT: 90,+ // When live volume can't be read, the engine refuses to act on anything larger+ // than this absolute SOL slice — so the MM never paints a no-volume tape.+ NO_VOLUME_FALLBACK_LAMPORTS: 50_000_000, // 0.05 SOL+ // Dust floor — below this an action is skipped (not worth a tx / fee).+ MIN_TRADE_LAMPORTS: 2_000_000, // 0.002 SOL+ // Default rolling window over which "live volume" is measured for the cap.+ VOLUME_WINDOW_SECONDS: 300,+};++// Plain-language preset rulebooks. The UI offers these; "custom" keeps whatever+// the owner set. Floor price is always supplied at attach time (it's coin-+// specific), so presets only carry the behavioral shape.+export const PRESETS = {+ gentle: {+ label: 'Gentle floor defense',+ description:+ 'Quietly defends a tight floor and only trims into strong rallies. Small, infrequent, conservative.',+ floor_band_pct: 3,+ take_profit_band_pct: 40,+ recycle_pct: 12,+ slippage_bps: 300,+ max_price_impact_pct: 5,+ min_action_interval_seconds: 120,+ max_volume_pct: 8,+ graduation_action: 'hold',+ },+ balanced: {+ label: 'Balanced market-maker',+ description:+ 'Two-sided support: defends the floor and recycles measured profit into rallies. The default.',+ floor_band_pct: 5,+ take_profit_band_pct: 25,+ recycle_pct: 20,+ slippage_bps: 500,+ max_price_impact_pct: 8,+ min_action_interval_seconds: 60,+ max_volume_pct: 15,+ graduation_action: 'provide_lp',+ },+ aggressive: {+ label: 'Aggressive recycle',+ description:+ 'Defends a wider band and recycles harder into spikes to keep liquidity turning. Still volume-capped.',+ floor_band_pct: 8,+ take_profit_band_pct: 15,+ recycle_pct: 35,+ slippage_bps: 800,+ max_price_impact_pct: 12,+ min_action_interval_seconds: 45,+ max_volume_pct: 25,+ graduation_action: 'provide_lp',+ },+};++export const GRADUATION_ACTIONS = ['provide_lp', 'hold', 'distribute'];++/** A requested policy that would cross the anti-manipulation line. */+export class PolicyError extends Error {+ constructor(code, message, detail = {}) {+ super(message);+ this.name = 'PolicyError';+ this.code = code;+ this.detail = detail;+ this.status = code === 'manipulation_guard' ? 422 : 400;+ }+}++// ── coercion helpers (Neon returns numeric/bigint columns as strings) ─────────+function num(v, def = null) {+ if (v == null || v === '') return def;+ const n = Number(v);+ return Number.isFinite(n) ? n : def;+}+function bigintStr(v, def = 0n) {+ try {+ if (v == null || v === '') return def;+ return BigInt(typeof v === 'number' ? Math.round(v) : String(v).split('.')[0]);+ } catch {+ return def;+ }+}+function clamp(n, lo, hi) {+ return Math.max(lo, Math.min(hi, n));+}++/**+ * Normalize + validate a create/update patch into the column shape. Throws a+ * PolicyError on anything malformed or outside the anti-manipulation caps. Only+ * keys present in `raw` are returned (so an update touches just those columns),+ * EXCEPT when `withPreset` seeds a full behavioral shape.+ *+ * @param {object} raw caller-supplied fields (snake or camel tolerated)+ * @param {object} [opts]+ * @param {boolean} [opts.isCreate] require floor price + full shape+ * @returns {object} validated column patch+ */+export function normalizePolicyPatch(raw = {}, { isCreate = false } = {}) {+ const get = (...keys) => {+ for (const k of keys) if (raw[k] != null) return raw[k];+ return undefined;+ };+ const patch = {};++ // Preset seeds the behavioral shape first; explicit fields then override it.+ const preset = get('preset');+ if (preset != null) {+ if (!['gentle', 'balanced', 'aggressive', 'custom'].includes(preset)) {+ throw new PolicyError('invalid_preset', 'preset must be gentle, balanced, aggressive, or custom');+ }+ patch.preset = preset;+ if (preset !== 'custom') Object.assign(patch, PRESETS[preset]);+ }++ const mode = get('mode');+ if (mode != null) {+ if (mode !== 'simulate' && mode !== 'live') throw new PolicyError('invalid_mode', 'mode must be simulate or live');+ patch.mode = mode;+ }++ const floor = get('floor_price_sol', 'floorPriceSol');+ if (floor != null) {+ const f = num(floor);+ if (f == null || f < 0) throw new PolicyError('invalid_floor', 'floor_price_sol must be a non-negative number (SOL per token)');+ patch.floor_price_sol = f;+ } else if (isCreate) {+ throw new PolicyError('missing_floor', 'floor_price_sol is required (the SOL-per-token price to defend)');+ }++ const numField = (keys, col, { min, max, label }) => {+ const v = get(...keys);+ if (v == null) return;+ const n = num(v);+ if (n == null || n < min || n > max) {+ throw new PolicyError(`invalid_${col}`, `${label} must be between ${min} and ${max}`);+ }+ patch[col] = n;+ };++ numField(['floor_band_pct', 'floorBandPct'], 'floor_band_pct', { min: 0, max: 90, label: 'floor band %' });+ numField(['take_profit_band_pct', 'takeProfitBandPct'], 'take_profit_band_pct', { min: 0, max: 10_000, label: 'take-profit band %' });+ numField(['recycle_pct', 'recyclePct'], 'recycle_pct', { min: 0.1, max: GUARDS.MAX_RECYCLE_PCT, label: 'recycle %' });+ numField(['max_inventory_tokens', 'maxInventoryTokens'], 'max_inventory_tokens', { min: 0, max: 1_000_000_000, label: 'max inventory (tokens)' });+ numField(['slippage_bps', 'slippageBps'], 'slippage_bps', { min: 0, max: 5_000, label: 'slippage (bps)' });+ numField(['max_price_impact_pct', 'maxPriceImpactPct'], 'max_price_impact_pct', { min: 0, max: 100, label: 'max price impact %' });++ // SOL budgets supplied in SOL → store lamports.+ const lamportsField = (keys, col, { maxSol, label }) => {+ const v = get(...keys);+ if (v == null) return;+ const sol = num(v);+ if (sol == null || sol < 0 || sol > maxSol) throw new PolicyError(`invalid_${col}`, `${label} must be between 0 and ${maxSol} SOL`);+ patch[col] = String(BigInt(Math.round(sol * SOL)));+ };+ lamportsField(['dip_buy_budget_sol', 'dipBuyBudgetSol'], 'dip_buy_budget_lamports', { maxSol: 1_000, label: 'dip-buy budget' });+ lamportsField(['daily_budget_sol', 'dailyBudgetSol'], 'daily_budget_lamports', { maxSol: 1_000, label: 'daily budget' });+ lamportsField(['seed_sol', 'seedSol'], 'seed_lamports', { maxSol: 50, label: 'seed buy' });++ const grad = get('graduation_action', 'graduationAction');+ if (grad != null) {+ if (!GRADUATION_ACTIONS.includes(grad)) throw new PolicyError('invalid_graduation_action', `graduation_action must be one of ${GRADUATION_ACTIONS.join(', ')}`);+ patch.graduation_action = grad;+ }++ // Anti-manipulation caps — clamped to the platform ceilings, never beyond.+ const interval = get('min_action_interval_seconds', 'minActionIntervalSeconds');+ if (interval != null) {+ const s = num(interval);+ if (s == null || s < GUARDS.MIN_ACTION_INTERVAL_SECONDS) {+ throw new PolicyError(+ 'manipulation_guard',+ `min_action_interval_seconds must be at least ${GUARDS.MIN_ACTION_INTERVAL_SECONDS}s — a faster cadence would allow wash-trading, which the platform does not permit`,+ { min: GUARDS.MIN_ACTION_INTERVAL_SECONDS },+ );+ }+ patch.min_action_interval_seconds = Math.round(clamp(s, GUARDS.MIN_ACTION_INTERVAL_SECONDS, 86_400));+ }+ const volPct = get('max_volume_pct', 'maxVolumePct');+ if (volPct != null) {+ const v = num(volPct);+ if (v == null || v <= 0) throw new PolicyError('invalid_max_volume_pct', 'max_volume_pct must be a positive number');+ if (v > GUARDS.MAX_VOLUME_PCT_CEILING) {+ throw new PolicyError(+ 'manipulation_guard',+ `max_volume_pct cannot exceed ${GUARDS.MAX_VOLUME_PCT_CEILING}% — a market-maker that dominated more of the volume would be painting the tape, which the platform does not permit`,+ { ceiling: GUARDS.MAX_VOLUME_PCT_CEILING },+ );+ }+ patch.max_volume_pct = v;+ }++ const enabled = get('enabled');+ if (enabled != null) patch.enabled = enabled === true || enabled === 'true';+ const kill = get('kill_switch', 'killSwitch');+ if (kill != null) patch.kill_switch = kill === true || kill === 'true';++ return patch;+}++/**+ * Final safety gate on a fully-resolved policy (post-merge). Throws PolicyError+ * if any combination would cross the anti-manipulation line. Called before a+ * policy is enabled — refusing rather than silently neutering, with a reason the+ * UI surfaces verbatim.+ */+export function assertPolicySafe(policy) {+ const interval = num(policy.min_action_interval_seconds);+ if (interval == null || interval < GUARDS.MIN_ACTION_INTERVAL_SECONDS) {+ throw new PolicyError('manipulation_guard', `Action interval must be at least ${GUARDS.MIN_ACTION_INTERVAL_SECONDS}s to prevent wash-trading.`);+ }+ const volPct = num(policy.max_volume_pct);+ if (volPct == null || volPct <= 0 || volPct > GUARDS.MAX_VOLUME_PCT_CEILING) {+ throw new PolicyError('manipulation_guard', `Max volume share must be between 0 and ${GUARDS.MAX_VOLUME_PCT_CEILING}% so the maker can't dominate the tape.`);+ }+ const recycle = num(policy.recycle_pct);+ if (recycle == null || recycle <= 0 || recycle > GUARDS.MAX_RECYCLE_PCT) {+ throw new PolicyError('manipulation_guard', `Recycle share must be between 0 and ${GUARDS.MAX_RECYCLE_PCT}% — recycling is measured profit-taking, not a dump.`);+ }+ if (num(policy.floor_price_sol) == null || num(policy.floor_price_sol) < 0) {+ throw new PolicyError('invalid_floor', 'A valid floor price is required to enable the market-maker.');+ }+ // Enabling LIVE requires a real spend budget — otherwise it's a no-op that+ // looks armed. Refuse the misleading state.+ if (policy.enabled && policy.mode === 'live') {+ const dip = bigintStr(policy.dip_buy_budget_lamports);+ const daily = bigintStr(policy.daily_budget_lamports);+ const seed = bigintStr(policy.seed_lamports);+ if (dip <= 0n && daily <= 0n && seed <= 0n) {+ throw new PolicyError('no_budget', 'Set a dip-buy, daily, or seed budget before enabling live — a live maker with no budget can never act.');+ }+ }+ return true;+}++// ── ownership ─────────────────────────────────────────────────────────────────++/**+ * Resolve the launched coin the owner controls. The MM can only be attached to a+ * coin launched THROUGH three.ws (a row in pump_agent_mints) by its owner — the+ * agent that owns it also owns the wallet the MM trades from. Returns the mint+ * row { agent_id, user_id, name, symbol } or null.+ */+export async function resolveOwnedLaunch({ userId, mint, network }) {+ const [row] = await sql`+ SELECT agent_id, user_id, name, symbol, network+ FROM pump_agent_mints+ WHERE mint = ${mint} AND network = ${network} AND user_id = ${userId}+ LIMIT 1+ `;+ return row || null;+}++// ── policy reads ──────────────────────────────────────────────────────────────++export async function getPolicyByMint(mint, network) {+ const [row] = await sql`SELECT * FROM market_maker_policies WHERE mint = ${mint} AND network = ${network} LIMIT 1`;+ return row || null;+}+export async function getPolicyById(id) {+ const [row] = await sql`SELECT * FROM market_maker_policies WHERE id = ${id} LIMIT 1`;+ return row || null;+}+export async function listOwnerPolicies(userId, { limit = 100 } = {}) {+ return sql`+ SELECT * FROM market_maker_policies+ WHERE user_id = ${userId}+ ORDER BY created_at DESC+ LIMIT ${Math.min(limit, 200)}+ `;+}++/** Active policies on a network for the engine worker (enabled, not killed). */+export async function getActivePolicies(network, limit = 500) {+ return sql`+ SELECT * FROM market_maker_policies+ WHERE network = ${network} AND enabled = true AND kill_switch = false+ AND status NOT IN ('killed')+ ORDER BY last_eval_at ASC NULLS FIRST, created_at ASC+ LIMIT ${limit}+ `;+}++// ── create / update ─────────────────────────────────────────────────────────++/**+ * Create or update the (one) policy for a launched coin. Merges the validated+ * patch over the current row (or preset defaults on create), runs the final+ * safety gate, and writes. Returns the persisted row.+ */+export async function upsertPolicy({ mint, network, agentId, userId, patch }) {+ const existing = await getPolicyByMint(mint, network);++ // Resolved view used for the safety gate (merge patch over existing/defaults).+ const base = existing || {+ preset: 'balanced',+ mode: 'simulate',+ ...PRESETS.balanced,+ dip_buy_budget_lamports: '0',+ daily_budget_lamports: '0',+ seed_lamports: '0',+ max_inventory_tokens: 0,+ enabled: false,+ kill_switch: false,+ };+ const resolved = { ...base, ...patch };+ if (resolved.enabled) assertPolicySafe(resolved);++ if (!existing) {+ // Create — fill every column from resolved (preset defaults already merged).+ const [row] = await sql`+ INSERT INTO market_maker_policies (+ mint, network, agent_id, user_id, enabled, mode, preset,+ floor_price_sol, floor_band_pct, dip_buy_budget_lamports,+ take_profit_band_pct, recycle_pct, max_inventory_tokens,+ seed_lamports, graduation_action,+ daily_budget_lamports, slippage_bps, max_price_impact_pct,+ min_action_interval_seconds, max_volume_pct, kill_switch, status+ ) VALUES (+ ${mint}, ${network}, ${agentId}, ${userId},+ ${resolved.enabled === true}, ${resolved.mode || 'simulate'}, ${resolved.preset || 'balanced'},+ ${num(resolved.floor_price_sol, 0)}, ${num(resolved.floor_band_pct, 5)}, ${String(bigintStr(resolved.dip_buy_budget_lamports))},+ ${num(resolved.take_profit_band_pct, 25)}, ${num(resolved.recycle_pct, 20)}, ${num(resolved.max_inventory_tokens, 0)},+ ${String(bigintStr(resolved.seed_lamports))}, ${resolved.graduation_action || 'hold'},+ ${String(bigintStr(resolved.daily_budget_lamports))}, ${Math.round(num(resolved.slippage_bps, 500))}, ${num(resolved.max_price_impact_pct, 8)},+ ${Math.round(num(resolved.min_action_interval_seconds, 60))}, ${num(resolved.max_volume_pct, 15)},+ ${resolved.kill_switch === true}, ${resolved.enabled === true ? 'active' : 'idle'}+ )+ RETURNING *+ `;+ return row;+ }++ // Update — only the columns present in patch. Build a dynamic SET safely.+ const cols = [];+ const setEnabledStatus = patch.enabled != null || patch.kill_switch != null;+ const colMap = {+ mode: patch.mode,+ preset: patch.preset,+ floor_price_sol: patch.floor_price_sol != null ? num(patch.floor_price_sol) : undefined,+ floor_band_pct: patch.floor_band_pct,+ dip_buy_budget_lamports: patch.dip_buy_budget_lamports,+ take_profit_band_pct: patch.take_profit_band_pct,+ recycle_pct: patch.recycle_pct,+ max_inventory_tokens: patch.max_inventory_tokens,+ seed_lamports: patch.seed_lamports,+ graduation_action: patch.graduation_action,+ daily_budget_lamports: patch.daily_budget_lamports,+ slippage_bps: patch.slippage_bps,+ max_price_impact_pct: patch.max_price_impact_pct,+ min_action_interval_seconds: patch.min_action_interval_seconds,+ max_volume_pct: patch.max_volume_pct,+ enabled: patch.enabled,+ kill_switch: patch.kill_switch,+ };+ for (const [k, v] of Object.entries(colMap)) if (v !== undefined) cols.push([k, v]);+ if (setEnabledStatus) {+ // Recompute the lifecycle status from the new enabled/kill flags, without+ // clobbering a 'graduated' terminal state.+ const killed = patch.kill_switch === true;+ const enabled = patch.enabled != null ? patch.enabled === true : existing.enabled;+ const nextStatus = killed ? 'killed' : enabled ? (existing.status === 'graduated' ? 'graduated' : 'active') : 'paused';+ cols.push(['status', nextStatus]);+ }+ if (!cols.length) return existing;++ // Neon's tagged template can't take a dynamic column list directly; assemble a+ // parameterized statement with sql.unsafe-free interpolation via a fragment.+ const assignments = cols.map(([k], i) => `${k} = $${i + 1}`).join(', ');+ const values = cols.map(([, v]) => v);+ const [row] = await sql(+ `UPDATE market_maker_policies SET ${assignments}, updated_at = now() WHERE id = $${values.length + 1} RETURNING *`,+ [...values, existing.id],+ );+ return row;+}++// ── action ledger ─────────────────────────────────────────────────────────────++/**+ * Append an action to the transparent ledger. Returns the new row id. Every+ * decision (executed, simulated, skipped, blocked, failed) is recorded — the+ * skips included, so the live feed honestly shows "held, nothing to do".+ */+export async function recordAction(a) {+ const [row] = await sql`+ INSERT INTO market_maker_actions+ (policy_id, mint, network, kind, side, trigger_reason, price_sol,+ sol_lamports, token_amount, price_impact_pct, venue, signature,+ custody_event_id, status, detail, meta)+ VALUES (+ ${a.policyId}, ${a.mint}, ${a.network}, ${a.kind}, ${a.side ?? null},+ ${a.triggerReason ?? null}, ${a.priceSol ?? null},+ ${a.solLamports != null ? String(bigintStr(a.solLamports)) : null},+ ${a.tokenAmount ?? null}, ${a.priceImpactPct ?? null}, ${a.venue ?? null},+ ${a.signature ?? null}, ${a.custodyEventId ?? null}, ${a.status ?? 'executed'},+ ${a.detail ?? null}, ${JSON.stringify(a.meta ?? {})}::jsonb+ )+ RETURNING id, created_at+ `;+ return row;+}++export async function listActions(policyId, { limit = 50, sinceId = null, includeSkips = true } = {}) {+ const lim = Math.min(limit, 200);+ if (sinceId != null) {+ return includeSkips+ ? sql`SELECT * FROM market_maker_actions WHERE policy_id = ${policyId} AND id > ${sinceId} ORDER BY id ASC LIMIT ${lim}`+ : sql`SELECT * FROM market_maker_actions WHERE policy_id = ${policyId} AND id > ${sinceId} AND kind <> 'skip' ORDER BY id ASC LIMIT ${lim}`;+ }+ return includeSkips+ ? sql`SELECT * FROM market_maker_actions WHERE policy_id = ${policyId} ORDER BY id DESC LIMIT ${lim}`+ : sql`SELECT * FROM market_maker_actions WHERE policy_id = ${policyId} AND kind <> 'skip' ORDER BY id DESC LIMIT ${lim}`;+}++// ── rolling spend (24h, from the action ledger) ───────────────────────────────++/** Lamports the MM deployed (seed + defend buys) for a policy in the last 24h. */+export async function getDeployedLamports24h(policyId) {+ const [r] = await sql`+ SELECT COALESCE(SUM(sol_lamports), 0)::numeric AS s+ FROM market_maker_actions+ WHERE policy_id = ${policyId} AND side = 'buy'+ AND status IN ('executed','simulated')+ AND created_at > now() - interval '24 hours'+ `;+ return bigintStr(r?.s);+}++/** Lamports the MM spent ONLY on dip-defense in the last 24h (for the dip budget). */+export async function getDefenseLamports24h(policyId) {+ const [r] = await sql`+ SELECT COALESCE(SUM(sol_lamports), 0)::numeric AS s+ FROM market_maker_actions+ WHERE policy_id = ${policyId} AND kind = 'defend_buy'+ AND status IN ('executed','simulated')+ AND created_at > now() - interval '24 hours'+ `;+ return bigintStr(r?.s);+}++// ── derived view (for API + UI) ───────────────────────────────────────────────++/** A clean, typed, public-safe view of a policy row + its budgets/PnL. */+export function toPublicPolicy(p) {+ if (!p) return null;+ const lamToSol = (v) => Number(bigintStr(v)) / SOL;+ return {+ id: p.id,+ mint: p.mint,+ network: p.network,+ agent_id: p.agent_id,+ enabled: p.enabled === true,+ mode: p.mode,+ preset: p.preset,+ status: p.status,+ kill_switch: p.kill_switch === true,+ floor_price_sol: num(p.floor_price_sol, 0),+ floor_band_pct: num(p.floor_band_pct, 0),+ take_profit_band_pct: num(p.take_profit_band_pct, 0),+ recycle_pct: num(p.recycle_pct, 0),+ max_inventory_tokens: num(p.max_inventory_tokens, 0),+ graduation_action: p.graduation_action,+ graduation_status: p.graduation_status,+ graduation_signature: p.graduation_signature,+ slippage_bps: num(p.slippage_bps, 0),+ max_price_impact_pct: num(p.max_price_impact_pct, 0),+ min_action_interval_seconds: num(p.min_action_interval_seconds, 0),+ max_volume_pct: num(p.max_volume_pct, 0),+ budgets: {+ dip_buy_sol: lamToSol(p.dip_buy_budget_lamports),+ daily_sol: lamToSol(p.daily_budget_lamports),+ seed_sol: lamToSol(p.seed_lamports),+ seed_done: p.seed_done_at != null,+ },+ realized: {+ pnl_sol: lamToSol(p.realized_pnl_lamports),+ sol_deployed: lamToSol(p.sol_deployed_lamports),+ sol_recovered: lamToSol(p.sol_recovered_lamports),+ inventory_tokens: num(p.inventory_tokens, null),+ inventory_value_sol: p.inventory_value_lamports != null ? lamToSol(p.inventory_value_lamports) : null,+ last_price_sol: num(p.last_price_sol, null),+ },+ last_action_at: p.last_action_at,+ last_action_side: p.last_action_side,+ last_eval_at: p.last_eval_at,+ last_error: p.last_error,+ created_at: p.created_at,+ updated_at: p.updated_at,+ // The disclosed guarantee, surfaced so the UI can show it verbatim.+ disclosure:+ 'This market-maker is rules-based and non-manipulative. It cannot wash-trade ' ++ `(no action and no side flip within ${num(p.min_action_interval_seconds, 60)}s), ` ++ `cannot exceed ${num(p.max_volume_pct, 15)}% of live volume in one action, ` ++ 'and operates from the agent’s own audited wallet. The owner can pause, kill, or withdraw at any time.',+ };+}++export function toPublicAction(a) {+ if (!a) return null;+ return {+ id: Number(a.id),+ kind: a.kind,+ side: a.side,+ trigger_reason: a.trigger_reason,+ price_sol: num(a.price_sol, null),+ sol: a.sol_lamports != null ? Number(bigintStr(a.sol_lamports)) / SOL : null,+ token_amount: num(a.token_amount, null),+ price_impact_pct: num(a.price_impact_pct, null),+ venue: a.venue,+ signature: a.signature,+ status: a.status,+ detail: a.detail,+ created_at: a.created_at,+ };+}diff --git a/api/_lib/migrations/20260626130000_market_maker_policies.sql b/api/_lib/migrations/20260626130000_market_maker_policies.sqlnew file mode 100644index 000000000..b7e876b0b--- /dev/null+++ b/api/_lib/migrations/20260626130000_market_maker_policies.sql@@ -0,0 +1,128 @@+-- Launch Copilot — autonomous fair-launch market-maker.+--+-- A coin launched via three.ws can attach a rules-based, NON-MANIPULATIVE+-- market-maker that runs from the launching agent's own audited wallet. The+-- policy is the published rulebook: a defended floor band, measured profit+-- recycling into strength, an inventory ceiling, a graduation action, hard+-- anti-manipulation caps (min interval between actions, max % of live volume),+-- and budgets. The engine (workers/agent-mm) only decides WHEN/HOW MUCH within+-- these limits, then routes every fill through the SAME firewall + spend-guard ++-- custody-audited path (executeAgentTrade) a manual trade uses — it adds no new+-- way to move funds. One policy per (mint, network).++begin;++create table if not exists market_maker_policies (+ id uuid primary key default gen_random_uuid(),+ mint text not null,+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ enabled boolean not null default false,+ -- A policy runs LIVE only when both the worker AND this flag are live; otherwise+ -- the full decision logic runs against real quotes but never signs/spends.+ mode text not null default 'simulate' check (mode in ('simulate','live')),+ preset text not null default 'custom' check (preset in ('gentle','balanced','aggressive','custom')),++ -- ── floor defense ─────────────────────────────────────────────────────────+ -- floor_price_sol is SOL per WHOLE token. Defend when the live price falls+ -- through floor_price_sol * (1 - floor_band_pct/100), buying a bounded slice.+ floor_price_sol numeric(40, 18) not null check (floor_price_sol >= 0),+ floor_band_pct numeric(6, 3) not null default 5 check (floor_band_pct >= 0 and floor_band_pct <= 90),+ dip_buy_budget_lamports numeric(40, 0) not null default 0 check (dip_buy_budget_lamports >= 0),++ -- ── profit recycling ──────────────────────────────────────────────────────+ -- Sell recycle_pct of managed inventory into a spike above+ -- floor_price_sol * (1 + take_profit_band_pct/100), locking realized SOL.+ take_profit_band_pct numeric(7, 3) not null default 25 check (take_profit_band_pct >= 0),+ recycle_pct numeric(6, 3) not null default 20 check (recycle_pct > 0 and recycle_pct <= 90),+ -- Token inventory ceiling (whole tokens). 0 = no cap. Above it the engine trims.+ max_inventory_tokens numeric(40, 6) not null default 0 check (max_inventory_tokens >= 0),++ -- ── seed (one-time initial buy from the agent wallet) ─────────────────────+ seed_lamports numeric(40, 0) not null default 0 check (seed_lamports >= 0),+ seed_done_at timestamptz,++ -- ── graduation transition (curve → AMM) ──────────────────────────────────+ graduation_action text not null default 'hold' check (graduation_action in ('provide_lp','hold','distribute')),+ graduation_done_at timestamptz,+ graduation_status text, -- pending | done | failed:<reason>+ graduation_signature text,++ -- ── budgets + execution ──────────────────────────────────────────────────+ daily_budget_lamports numeric(40, 0) not null default 0 check (daily_budget_lamports >= 0),+ slippage_bps int not null default 500 check (slippage_bps between 0 and 5000),+ max_price_impact_pct numeric(6, 3) not null default 8 check (max_price_impact_pct >= 0),++ -- ── anti-manipulation hard caps (codified + publicly disclosed) ───────────+ -- min_action_interval_seconds: the engine cannot act twice (and CANNOT cross+ -- sides) inside this window — the core anti-wash-trade gate. max_volume_pct:+ -- a single action is capped to this share of live market volume, so the MM can+ -- never dominate / paint the tape. Bounds are enforced again in code; a policy+ -- that requests values outside them is refused at create time.+ min_action_interval_seconds int not null default 60 check (min_action_interval_seconds >= 30),+ max_volume_pct numeric(6, 3) not null default 15 check (max_volume_pct > 0 and max_volume_pct <= 33),+ kill_switch boolean not null default false,++ -- ── engine-maintained runtime state ──────────────────────────────────────+ status text not null default 'idle'+ check (status in ('idle','active','paused','killed','graduated','error')),+ realized_pnl_lamports numeric(40, 0) not null default 0,+ sol_deployed_lamports numeric(40, 0) not null default 0, -- gross SOL spent (seed + defense)+ sol_recovered_lamports numeric(40, 0) not null default 0, -- gross SOL recovered (recycle + distribute)+ inventory_tokens numeric(40, 6), -- last observed managed inventory (whole tokens)+ inventory_value_lamports numeric(40, 0), -- last observed inventory SOL value+ last_price_sol numeric(40, 18),+ last_action_at timestamptz,+ last_action_side text check (last_action_side in ('buy','sell')),+ last_eval_at timestamptz,+ last_error text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),++ unique (mint, network)+);++-- The worker's active work set: enabled policies on a network, not killed.+create index if not exists mm_policies_active_idx+ on market_maker_policies (network, status)+ where enabled = true and kill_switch = false;+create index if not exists mm_policies_owner_idx on market_maker_policies (user_id, created_at desc);+create index if not exists mm_policies_agent_idx on market_maker_policies (agent_id);++-- Transparent, append-only action log — every decision the engine took (or+-- skipped, and why). Drives the live action feed in the Launch Copilot UI and is+-- the honest record that the MM defended/recycled within its disclosed policy.+create table if not exists market_maker_actions (+ id bigserial primary key,+ policy_id uuid not null references market_maker_policies(id) on delete cascade,+ mint text not null,+ network text not null default 'mainnet',+ -- seed | defend_buy | recycle_sell | rebalance_trim+ -- | graduation_lp | graduation_distribute | graduation_hold | skip+ kind text not null,+ side text check (side in ('buy','sell')),+ trigger_reason text,+ price_sol numeric(40, 18),+ sol_lamports numeric(40, 0),+ token_amount numeric(40, 6),+ price_impact_pct numeric(7, 3),+ venue text, -- bonding_curve | amm | lp+ signature text,+ custody_event_id bigint,+ status text not null default 'executed'+ check (status in ('executed','simulated','skipped','failed','blocked')),+ detail text,+ meta jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+);++create index if not exists mm_actions_policy_time_idx on market_maker_actions (policy_id, created_at desc);+create index if not exists mm_actions_mint_time_idx on market_maker_actions (mint, network, created_at desc);+-- Material (non-skip) actions only — the audit/realized view skips the noisy+-- "held, nothing to do" rows the live feed shows.+create index if not exists mm_actions_material_idx+ on market_maker_actions (policy_id, created_at desc)+ where kind <> 'skip';++commit;diff --git a/packages/agenc/LICENSE b/packages/agenc/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/agenc/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/agenc/src/http.js b/packages/agenc/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/agenc/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/agenc/src/index.d.ts b/packages/agenc/src/index.d.tsnew file mode 100644index 000000000..ab9e95a9d--- /dev/null+++ b/packages/agenc/src/index.d.ts@@ -0,0 +1,161 @@+// Type definitions for @three-ws/agenc++export declare class ThreeWsError extends Error {+ name: string;+ code: string;+ status: number | null;+ detail?: string;+ retryAfter?: number;+ body: unknown;+}++export declare class PaymentRequiredError extends ThreeWsError {+ accepts: unknown | null;+}++export declare const DEFAULT_BASE_URL: string;++export type Cluster = 'mainnet' | 'devnet';++/** Lifecycle state of a task, decoded from the on-chain enum by the bridge. */+export type TaskState = 'Open' | 'Claimed' | 'Completed' | 'Cancelled' | 'Disputed' | 'Expired';++/** Registry status of an agent, decoded from the on-chain enum by the bridge. */+export type AgentStatus = 'Inactive' | 'Active' | 'Busy' | 'Suspended';++export interface AgencClientOptions {+ /** API origin. Defaults to https://three.ws (or THREE_WS_BASE_URL). */+ baseUrl?: string;+ /** fetch implementation (default globalThis.fetch). */+ fetch?: typeof fetch;+ /** Bearer token attached as Authorization (reads are public; rarely needed). */+ apiKey?: string;+ /** Default headers on every request. */+ headers?: Record<string, string>;+}++export interface CommonOptions {+ /** Target cluster. Default 'mainnet'. */+ cluster?: Cluster;+ /** Abort an in-flight read. */+ signal?: AbortSignal;+}++export interface ListTasksOptions extends CommonOptions {}++export interface GetTaskOptions extends CommonOptions {+ /** Include the event timeline (?lifecycle=1). Default false. */+ lifecycle?: boolean;+}++export interface GetAgentOptions extends CommonOptions {}++export interface TaskSummary {+ /** 32-byte task id, hex. */+ taskId: string | null;+ /** Derived task account address (base58). */+ taskPda: string | null;+ /** Lifecycle state label. */+ state: TaskState | string | null;+ /** Raw enum ordinal when numeric. */+ stateRaw: number | null;+ /** Escrowed reward (atomic units, stringified). */+ rewardAmount: string | null;+ /** SPL mint of the reward; null for native SOL. */+ rewardMint: string | null;+ /** Unix deadline (stringified). */+ deadline: string | null;+ currentWorkers: number | null;+ maxWorkers: number | null;+ /** Completion timestamp, if any. */+ completedAt: string | null;+ /** true when the task carries a constraint hash (ZK lane). */+ private: boolean;+}++export interface TaskList {+ cluster: string | null;+ programId: string | null;+ creator: string | null;+ count: number;+ tasks: TaskSummary[];+ fetchedAt: string | null;+ raw: unknown;+}++export interface LifecycleEvent {+ eventName: string | null;+ timestamp: string | number | null;+ txSignature: string | null;+ actor: string | null;+}++export interface TaskLifecycle {+ currentState: TaskState | string | null;+ createdAt: string | number | null;+ currentWorkers: number | null;+ maxWorkers: number | null;+ timeline: LifecycleEvent[];+}++export interface TaskRecord extends TaskSummary {+ /** Creator wallet (base58). */+ creator: string | null;+ /** Constraint hash (hex) for private/ZK tasks; null otherwise. */+ constraintHash: string | null;+}++export interface TaskDetail {+ cluster: string | null;+ programId: string | null;+ taskPda: string | null;+ task: TaskRecord;+ /** Present (non-null) only when `{ lifecycle: true }` was requested. */+ lifecycle: TaskLifecycle | null;+ fetchedAt: string | null;+ raw: unknown;+}++export interface AgentRecord {+ /** 32-byte agent id, hex. */+ agentId: string | null;+ /** Controlling wallet (base58). */+ authority: string | null;+ /** Freeform u64 capability bitmap (stringified). */+ capabilities: string | null;+ status: AgentStatus | string | null;+ statusRaw: number | null;+ endpoint: string | null;+ metadataUri: string | null;+ /** Staked lamports (stringified). */+ stakeAmount: string | null;+ activeTasks: number | null;+ reputation: number | null;+ registeredAt: string | number | null;+}++export interface AgentDetail {+ cluster: string | null;+ programId: string | null;+ agentPda: string | null;+ agent: AgentRecord;+ fetchedAt: string | null;+ raw: unknown;+}++/** Resolve a task by PDA string, explicit PDA, or a (creator, taskId) pair. */+export type TaskSelector = string | { taskPda?: string } | { creator: string; taskId: string };++/** Resolve an agent by PDA string, or by PDA / id label object, or a bare id label. */+export type AgentSelector = string | { agentPda?: string; agentId?: string };++export interface AgencClient {+ listTasks(creator: string, opts?: ListTasksOptions): Promise<TaskList>;+ getTask(idOrPda: TaskSelector, opts?: GetTaskOptions): Promise<TaskDetail>;+ getAgent(idOrPda: AgentSelector, opts?: GetAgentOptions): Promise<AgentDetail>;+}++export declare function createAgenc(options?: AgencClientOptions): AgencClient;+export declare function listTasks(creator: string, opts?: ListTasksOptions): Promise<TaskList>;+export declare function getTask(idOrPda: TaskSelector, opts?: GetTaskOptions): Promise<TaskDetail>;+export declare function getAgent(idOrPda: AgentSelector, opts?: GetAgentOptions): Promise<AgentDetail>;diff --git a/packages/agenc/src/index.js b/packages/agenc/src/index.jsnew file mode 100644index 000000000..f40bbc028--- /dev/null+++ b/packages/agenc/src/index.js@@ -0,0 +1,255 @@+// @three-ws/agenc — read client for the AgenC agent-coordination protocol on+// Solana (agenc.tech, by Tetsuo Corp). Thin, auth-free client over the public+// three.ws AgenC bridge (/api/agenc/*): discover a creator's tasks, read a+// single task's on-chain state + lifecycle timeline, and resolve the agent+// registry — no Anchor, IDL, or wallet. See README.md for the full reference.++import { createHttp, ThreeWsError } from './http.js';++export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';++const CLUSTERS = ['mainnet', 'devnet'];++// Base58 alphabet (no 0, O, I, l). The bridge ultimately validates pubkeys, but+// catching an obviously-malformed creator before the round-trip turns a 400 into+// a local `invalid_input` with a clear message.+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++/**+ * Create an AgenC read client bound to a base URL, fetch, and optional auth.+ * For most callers the zero-config defaults `listTasks()` / `getTask()` /+ * `getAgent()` are enough; use this to reuse a custom origin (a self-hosted+ * bridge), a custom fetch, or default headers across many reads.+ */+export function createAgenc(options = {}) {+ const request = createHttp(options);++ /** Every task a creator wallet posted. Wraps GET /api/agenc/list-tasks. */+ async function listTasks(creator, opts = {}) {+ const wallet = typeof creator === 'string' ? creator.trim() : '';+ if (!wallet) {+ throw new ThreeWsError('listTasks() needs a base58 creator wallet.', { code: 'invalid_input' });+ }+ if (!BASE58_RE.test(wallet)) {+ throw new ThreeWsError(`"${wallet}" is not a valid base58 creator wallet.`, { code: 'invalid_input' });+ }+ const res = await request('/api/agenc/list-tasks', {+ query: { action: 'list-tasks', creator: wallet, cluster: cluster(opts) },+ signal: opts.signal,+ });+ return shapeTaskList(res);+ }++ /**+ * A single task's on-chain state and, with `{ lifecycle: true }`, its event+ * timeline. Wraps GET /api/agenc/get-task. Resolve a task three ways:+ * getTask('TASK_PDA') // by PDA+ * getTask({ taskPda: 'TASK_PDA' }) // explicit+ * getTask({ creator: 'C', taskId: 'label' }) // derive the PDA+ */+ async function getTask(idOrPda, opts = {}) {+ const query = { action: 'get-task', cluster: cluster(opts) };+ const sel = taskSelector(idOrPda);+ if (sel.taskPda) {+ query.taskPda = sel.taskPda;+ } else if (sel.creator && sel.taskId != null) {+ query.creator = sel.creator;+ query.taskId = sel.taskId;+ } else {+ throw new ThreeWsError('getTask() needs a taskPda, or a { creator, taskId } pair.', { code: 'invalid_input' });+ }+ if (opts.lifecycle) query.lifecycle = '1';++ const res = await request('/api/agenc/get-task', { query, signal: opts.signal });+ return shapeTaskDetail(res);+ }++ /**+ * An agent's registry entry. Wraps GET /api/agenc/get-agent. Resolve by PDA+ * or by id (hex, 0x-hex, or a UTF-8 label SHA-256 hashed by the bridge):+ * getAgent('AGENT_PDA') // by PDA+ * getAgent({ agentPda: 'AGENT_PDA' }) // explicit+ * getAgent({ agentId: 'my-label' }) // derive the PDA+ * getAgent('my-label') // bare string → agentId+ */+ async function getAgent(idOrPda, opts = {}) {+ const query = { action: 'get-agent', cluster: cluster(opts) };+ const sel = agentSelector(idOrPda);+ if (sel.agentPda) {+ query.agentPda = sel.agentPda;+ } else if (sel.agentId) {+ query.agentId = sel.agentId;+ } else {+ throw new ThreeWsError('getAgent() needs an agentPda or agentId.', { code: 'invalid_input' });+ }++ const res = await request('/api/agenc/get-agent', { query, signal: opts.signal });+ return shapeAgentDetail(res);+ }++ return { listTasks, getTask, getAgent };+}++// A module-level default client for the zero-config path: `import { listTasks }`.+let shared = null;+function defaultClient() {+ return (shared ||= createAgenc());+}++/** Every task a creator wallet posted (mainnet by default). */+export function listTasks(creator, opts) {+ return defaultClient().listTasks(creator, opts);+}+/** A single task's state and (optionally) lifecycle timeline. */+export function getTask(idOrPda, opts) {+ return defaultClient().getTask(idOrPda, opts);+}+/** An agent's registry entry, resolved from a label, hex id, or PDA. */+export function getAgent(idOrPda, opts) {+ return defaultClient().getAgent(idOrPda, opts);+}++// ── input normalization ──────────────────────────────────────────────────────++// Resolve a target cluster: explicit option → default mainnet. Reject anything+// the bridge doesn't speak before spending a round-trip on it.+function cluster(opts) {+ const c = opts.cluster;+ if (c === undefined || c === null) return 'mainnet';+ if (!CLUSTERS.includes(c)) {+ throw new ThreeWsError(`Invalid cluster "${c}". Expected one of: ${CLUSTERS.join(', ')}.`, { code: 'invalid_input' });+ }+ return c;+}++// A bare string is a task PDA; an object names the PDA or a (creator, taskId)+// pair. taskId may be hex, 0x-hex, or any UTF-8 label — the bridge hashes it.+function taskSelector(idOrPda) {+ if (typeof idOrPda === 'string') return { taskPda: idOrPda.trim() || null };+ const o = idOrPda || {};+ return {+ taskPda: trimOrNull(o.taskPda),+ creator: trimOrNull(o.creator),+ taskId: o.taskId == null ? null : String(o.taskId).trim(),+ };+}++// A bare string is treated as an agentId label (the README's ergonomic default);+// an object names the PDA or the id explicitly.+function agentSelector(idOrPda) {+ if (typeof idOrPda === 'string') return { agentId: idOrPda.trim() || null };+ const o = idOrPda || {};+ return {+ agentPda: trimOrNull(o.agentPda),+ agentId: trimOrNull(o.agentId),+ };+}++function trimOrNull(v) {+ if (v == null) return null;+ const s = String(v).trim();+ return s || null;+}++// ── response shaping ─────────────────────────────────────────────────────────+// The bridge already returns decoded, camelCase fields (taskId, rewardAmount,+// state labels). We pass them through with stable defaults and a `.raw` escape+// hatch, normalizing the bridge's `programId` (a base58 string after serialize)+// and omitting the internal `ok` flag.++function ensureObject(res, what) {+ if (!res || typeof res !== 'object') {+ throw new ThreeWsError(`Unexpected empty response from the AgenC bridge (${what}).`, { code: 'bad_response' });+ }+ return res;+}++function shapeTaskList(res) {+ ensureObject(res, 'list-tasks');+ return {+ cluster: res.cluster ?? null,+ programId: res.programId ?? null,+ creator: res.creator ?? null,+ count: typeof res.count === 'number' ? res.count : (res.tasks?.length ?? 0),+ tasks: Array.isArray(res.tasks) ? res.tasks.map(shapeTaskSummary) : [],+ fetchedAt: res.fetchedAt ?? null,+ raw: res,+ };+}++function shapeTaskSummary(t) {+ return {+ taskId: t.taskId ?? null,+ taskPda: t.taskPda ?? null,+ state: t.state ?? null,+ stateRaw: t.stateRaw ?? null,+ rewardAmount: t.rewardAmount ?? null,+ rewardMint: t.rewardMint ?? null,+ deadline: t.deadline ?? null,+ currentWorkers: t.currentWorkers ?? null,+ maxWorkers: t.maxWorkers ?? null,+ completedAt: t.completedAt ?? null,+ private: Boolean(t.private),+ };+}++function shapeTaskDetail(res) {+ ensureObject(res, 'get-task');+ const t = res.task || {};+ return {+ cluster: res.cluster ?? null,+ programId: res.programId ?? null,+ taskPda: res.taskPda ?? null,+ task: {+ ...shapeTaskSummary(t),+ creator: t.creator ?? null,+ constraintHash: t.constraintHash ?? null,+ },+ lifecycle: shapeLifecycle(res.lifecycle),+ fetchedAt: res.fetchedAt ?? null,+ raw: res,+ };+}++function shapeLifecycle(lc) {+ if (!lc || typeof lc !== 'object') return null;+ return {+ currentState: lc.currentState ?? null,+ createdAt: lc.createdAt ?? null,+ currentWorkers: lc.currentWorkers ?? null,+ maxWorkers: lc.maxWorkers ?? null,+ timeline: Array.isArray(lc.timeline)+ ? lc.timeline.map((e) => ({+ eventName: e.eventName ?? null,+ timestamp: e.timestamp ?? null,+ txSignature: e.txSignature ?? null,+ actor: e.actor ?? null,+ }))+ : [],+ };+}++function shapeAgentDetail(res) {+ ensureObject(res, 'get-agent');+ const a = res.agent || {};+ return {+ cluster: res.cluster ?? null,+ programId: res.programId ?? null,+ agentPda: res.agentPda ?? null,+ agent: {+ agentId: a.agentId ?? null,+ authority: a.authority ?? null,+ capabilities: a.capabilities ?? null,+ status: a.status ?? null,+ statusRaw: a.statusRaw ?? null,+ endpoint: a.endpoint ?? null,+ metadataUri: a.metadataUri ?? null,+ stakeAmount: a.stakeAmount ?? null,+ activeTasks: a.activeTasks ?? null,+ reputation: a.reputation ?? null,+ registeredAt: a.registeredAt ?? null,+ },+ fetchedAt: res.fetchedAt ?? null,+ raw: res,+ };+}diff --git a/packages/agent-guards/LICENSE b/packages/agent-guards/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/agent-guards/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/agent-guards/package.json b/packages/agent-guards/package.jsonindex 8b45ea0c4..2a50b2fa6 100644--- a/packages/agent-guards/package.json+++ b/packages/agent-guards/package.json@@ -2,6 +2,26 @@"name": "@three-ws/agent-guards","version": "0.1.0","description": "Safety rails for autonomous agents — per-agent spend policies and trade guards that cap what an agent can spend or trade before a transaction is signed. The three.ws agent custody SDK.",+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "types": "./src/index.d.ts",+ "exports": {+ ".": {+ "types": "./src/index.d.ts",+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test test/*.test.js"+ },"keywords": ["agent","autonomous",@@ -14,15 +34,22 @@"guardrails","three.ws"],+ "author": "nirholas <[email protected]>","license": "MIT",- "private": true,- "type": "module","homepage": "https://three.ws","repository": {"type": "git",- "url": "https://github.com/nirholas/three.ws"+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/agent-guards"},"bugs": {"url": "https://github.com/nirholas/three.ws/issues"+ },+ "engines": {+ "node": ">=18"+ },+ "dependencies": {},+ "publishConfig": {+ "access": "public"}}diff --git a/packages/agent-guards/src/http.js b/packages/agent-guards/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/agent-guards/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/agent-memory/LICENSE b/packages/agent-memory/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/agent-memory/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/agent-memory/package.json b/packages/agent-memory/package.jsonindex 39f64b2b2..508d9fd3b 100644--- a/packages/agent-memory/package.json+++ b/packages/agent-memory/package.json@@ -2,6 +2,26 @@"name": "@three-ws/agent-memory","version": "0.1.0","description": "Persistent, embeddings-backed memory for agents. Store facts and entities, recall them semantically, and surface a working context — over the three.ws Memory engine.",+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "types": "./src/index.d.ts",+ "exports": {+ ".": {+ "types": "./src/index.d.ts",+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test test/*.test.js"+ },"keywords": ["agent-memory","memory",@@ -16,15 +36,22 @@"letta","three.ws"],+ "author": "nirholas <[email protected]>","license": "MIT",- "private": true,- "type": "module","homepage": "https://three.ws","repository": {"type": "git",- "url": "https://github.com/nirholas/three.ws"+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/agent-memory"},"bugs": {"url": "https://github.com/nirholas/three.ws/issues"+ },+ "engines": {+ "node": ">=18"+ },+ "dependencies": {},+ "publishConfig": {+ "access": "public"}}diff --git a/packages/agent-memory/src/http.js b/packages/agent-memory/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/agent-memory/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/agent-memory/src/index.d.ts b/packages/agent-memory/src/index.d.tsnew file mode 100644index 000000000..7936c046c--- /dev/null+++ b/packages/agent-memory/src/index.d.ts@@ -0,0 +1,179 @@+// Type definitions for @three-ws/agent-memory++export declare class ThreeWsError extends Error {+ name: string;+ code: string;+ status: number | null;+ detail?: string;+ retryAfter?: number;+ body: unknown;+}++/** The README's ergonomic alias for the thrown auth/validation error — same class as `ThreeWsError`. */+export declare class MemoryError extends ThreeWsError {}++export declare class PaymentRequiredError extends ThreeWsError {+ accepts: unknown | null;+}++export declare const DEFAULT_BASE_URL: string;++export type MemoryType = 'user' | 'feedback' | 'project' | 'reference';+export type MemoryTier = 'working' | 'recall' | 'archival';+export type EntityKind = 'mint' | 'ticker' | 'wallet' | 'person' | 'strategy' | 'topic';+export type RecallMatch = 'semantic' | 'lexical';++export interface Memory {+ id: string;+ agentId: string | null;+ type: MemoryType;+ content: string;+ tags: string[];+ context: Record<string, unknown>;+ salience: number;+ tier: MemoryTier;+ pinned: boolean;+ embedder: string | null;+ hasEmbedding: boolean;+ accessCount: number;+ isPublic: boolean;+ tokens: number;+ createdAt: number | null;+ updatedAt: number | null;+ lastAccessedAt: number | null;+ expiresAt: number | null;+ /** recall() only: cosine similarity (4-dp), or null for a lexical hit. */+ score?: number | null;+ /** recall() only: how the hit was found. */+ match?: RecallMatch;+ /** The raw server payload. */+ raw: unknown;+}++export interface Entity {+ id: string;+ kind: EntityKind;+ label: string;+ salience: number | null;+ mentions: number;+ firstSeenAt: number | null;+ lastSeenAt: number | null;+ meta: Record<string, unknown>;+ raw: unknown;+}++export interface GraphEdge {+ source: string;+ target: string;+ weight: number;+}++export interface MemoryGraph {+ nodes: Entity[];+ edges: GraphEdge[];+ stats: { entities: number; edges: number };+}++export interface Context {+ entries: Memory[];+ /** Estimated tokens in the working core. */+ tokens: number;+ /** The working-core token budget (2000). */+ budget: number;+ /** tokens > budget. */+ overBudget: boolean;+ counts: { total: number; working: number; recall: number; archival: number; embedded: number };+ raw: unknown;+}++export interface RememberOptions {+ type?: MemoryType;+ tags?: string[];+ context?: Record<string, unknown>;+ salience?: number;+ pinned?: boolean;+ tier?: MemoryTier;+ /** Pass to upsert an existing memory idempotently. */+ id?: string;+ createdAt?: number | string;+ updatedAt?: number | string;+ expiresAt?: number | string;+ signal?: AbortSignal;+}++export interface RecallOptions {+ /** Max results, clamped 1..50. Default 8. */+ topK?: number;+ /** Min cosine similarity, 0..1. Default 0.25. */+ minScore?: number;+ /** Restrict to tiers, e.g. ['working', 'recall']. */+ tiers?: MemoryTier[];+ /** Restrict to one memory type. */+ type?: MemoryType;+ signal?: AbortSignal;+}++export interface ListOptions {+ type?: MemoryType;+ /** Only memories created after this epoch-ms timestamp. */+ since?: number;+ /** Max rows, <= 500. Default 200. */+ limit?: number;+ signal?: AbortSignal;+}++export interface EditChanges {+ content?: string;+ tags?: string[];+}++export interface AgentMemoryOptions {+ /** The agent these memories belong to. Required. */+ agentId: string;+ /** Bearer token for writes (server-to-server). */+ token?: string;+ /** Alias for `token`. */+ apiKey?: string;+ baseUrl?: string;+ fetch?: typeof fetch;+ headers?: Record<string, string>;+}++export interface AgentMemoryClient {+ readonly agentId: string;+ remember(content: string | (RememberOptions & { content: string }), opts?: RememberOptions): Promise<Memory>;+ recall(query: string, opts?: RecallOptions): Promise<Memory[]>;+ list(opts?: ListOptions): Promise<Memory[]>;+ graph(opts?: { signal?: AbortSignal }): Promise<MemoryGraph>;+ entities(opts?: { signal?: AbortSignal }): Promise<Entity[]>;+ memoriesFor(entityId: string, opts?: { signal?: AbortSignal }): Promise<Memory[]>;+ context(opts?: { signal?: AbortSignal }): Promise<Context>;+ pin(id: string, opts?: { signal?: AbortSignal }): Promise<Memory>;+ unpin(id: string, opts?: { signal?: AbortSignal }): Promise<Memory>;+ retier(id: string, tier: MemoryTier, opts?: { signal?: AbortSignal }): Promise<Memory>;+ setSalience(id: string, salience: number, opts?: { signal?: AbortSignal }): Promise<Memory>;+ edit(id: string, changes: EditChanges, opts?: { signal?: AbortSignal }): Promise<Memory>;+ merge(memoryIds: string[], opts?: { signal?: AbortSignal }): Promise<{ entry: Memory | null; merged: number }>;+ forget(id: string, opts?: { signal?: AbortSignal }): Promise<{ ok: boolean; id: string }>;+}++export declare function createAgentMemory(options: AgentMemoryOptions): AgentMemoryClient;++export declare class AgentMemory implements AgentMemoryClient {+ constructor(options: AgentMemoryOptions);+ readonly agentId: string;+ remember(content: string | (RememberOptions & { content: string }), opts?: RememberOptions): Promise<Memory>;+ recall(query: string, opts?: RecallOptions): Promise<Memory[]>;+ list(opts?: ListOptions): Promise<Memory[]>;+ graph(opts?: { signal?: AbortSignal }): Promise<MemoryGraph>;+ entities(opts?: { signal?: AbortSignal }): Promise<Entity[]>;+ memoriesFor(entityId: string, opts?: { signal?: AbortSignal }): Promise<Memory[]>;+ context(opts?: { signal?: AbortSignal }): Promise<Context>;+ pin(id: string, opts?: { signal?: AbortSignal }): Promise<Memory>;+ unpin(id: string, opts?: { signal?: AbortSignal }): Promise<Memory>;+ retier(id: string, tier: MemoryTier, opts?: { signal?: AbortSignal }): Promise<Memory>;+ setSalience(id: string, salience: number, opts?: { signal?: AbortSignal }): Promise<Memory>;+ edit(id: string, changes: EditChanges, opts?: { signal?: AbortSignal }): Promise<Memory>;+ merge(memoryIds: string[], opts?: { signal?: AbortSignal }): Promise<{ entry: Memory | null; merged: number }>;+ forget(id: string, opts?: { signal?: AbortSignal }): Promise<{ ok: boolean; id: string }>;+}diff --git a/packages/agent-memory/src/index.js b/packages/agent-memory/src/index.jsnew file mode 100644index 000000000..b46ab2021--- /dev/null+++ b/packages/agent-memory/src/index.js@@ -0,0 +1,328 @@+// @three-ws/agent-memory — persistent, embeddings-backed memory for agents.+// Thin client over the live /api/agent-memory and /api/memory/* endpoints (the+// SDK twin of the three.ws Memory Studio). One agent's memories per client:+// remember() a fact, recall() it by meaning, walk the auto-mined entity graph,+// and curate the working core. See README.md for the full reference.++import { createHttp, ThreeWsError } from './http.js';++export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';++// The README documents writes that throw a `MemoryError` with a `.code`. That+// is the platform's shared ThreeWsError under an ergonomic name — re-exported so+// `instanceof MemoryError` and `instanceof ThreeWsError` both hold.+export { ThreeWsError as MemoryError } from './http.js';++const MEMORY_TYPES = ['user', 'feedback', 'project', 'reference'];+const MEMORY_TIERS = ['working', 'recall', 'archival'];++/**+ * Create an AgentMemory client bound to one agent, a base URL, a fetch, and an+ * optional bearer token. The default exports (`remember`, `recall`, …) need an+ * `agentId` per call; this factory (and the `AgentMemory` class) bind it once so+ * every method targets the same agent.+ *+ * @param {object} options+ * @param {string} options.agentId The agent these memories belong to.+ * @param {string} [options.token] Bearer token for writes (server-to-server).+ * @param {string} [options.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [options.fetch] fetch implementation (e.g. an x402 payer).+ * @param {Record<string,string>} [options.headers]+ */+export function createAgentMemory(options = {}) {+ const agentId = options.agentId;+ if (!agentId || typeof agentId !== 'string') {+ throw new ThreeWsError('createAgentMemory() needs an `agentId` string.', { code: 'invalid_input' });+ }+ // `token` is the README's name for the platform's bearer auth — createHttp+ // attaches whatever it gets as `apiKey` to the Authorization header.+ const request = createHttp({ ...options, apiKey: options.apiKey || options.token });++ /** Store (or upsert) a memory. Wraps `POST /api/agent-memory`. */+ async function remember(content, opts = {}) {+ const input = typeof content === 'string' ? { content } : { ...(content || {}) };+ const text = input.content;+ if (!text || typeof text !== 'string') {+ throw new ThreeWsError('remember() needs `content` text.', { code: 'invalid_input' });+ }+ const merged = { ...input, ...opts };++ const type = normalizeEnum(merged.type, MEMORY_TYPES, 'type', true); // soft: server falls back to 'project'+ const tier = normalizeEnum(merged.tier, MEMORY_TIERS, 'tier');+ if (merged.salience !== undefined) assertUnit(merged.salience, 'salience');++ const entry = prune({+ id: merged.id,+ type,+ content: text,+ tags: merged.tags,+ context: merged.context,+ salience: merged.salience,+ pinned: merged.pinned === true ? true : undefined,+ tier,+ createdAt: merged.createdAt,+ updatedAt: merged.updatedAt,+ expiresAt: merged.expiresAt,+ });++ const res = await request('/api/agent-memory', {+ method: 'POST',+ body: { agentId, entry },+ signal: merged.signal,+ });+ return shapeMemory(res?.entry);+ }++ /** Semantic search over the agent's memories. Wraps `POST /api/memory/search`. */+ async function recall(query, opts = {}) {+ const q = String(query || '').trim();+ if (!q) throw new ThreeWsError('recall() needs a non-empty query.', { code: 'invalid_input' });+ if (opts.minScore !== undefined) assertUnit(opts.minScore, 'minScore');++ const res = await request('/api/memory/search', {+ method: 'POST',+ body: prune({+ agentId,+ query: q,+ topK: opts.topK,+ minScore: opts.minScore,+ tiers: cleanTiers(opts.tiers),+ type: normalizeEnum(opts.type, MEMORY_TYPES, 'type'),+ }),+ signal: opts.signal,+ });+ return (res?.results || []).map(shapeMemory);+ }++ /** Every memory for the agent (newest, salience-first). Wraps `GET /api/agent-memory`. */+ async function list(opts = {}) {+ const res = await request('/api/agent-memory', {+ query: prune({+ agentId,+ type: normalizeEnum(opts.type, MEMORY_TYPES, 'type'),+ since: opts.since,+ limit: opts.limit,+ }),+ signal: opts.signal,+ });+ return (res?.entries || []).map(shapeMemory);+ }++ /** The full temporal knowledge graph. Wraps `GET /api/memory/graph`. */+ async function graph(opts = {}) {+ const res = await request('/api/memory/graph', { query: { agentId }, signal: opts.signal });+ return {+ nodes: (res?.nodes || []).map(shapeEntity),+ edges: (res?.edges || []).map((e) => ({ source: e.source, target: e.target, weight: e.weight ?? 1 })),+ stats: res?.stats || { entities: 0, edges: 0 },+ };+ }++ /** Knowledge-graph nodes ranked by mention count — convenience over `graph()`. */+ async function entities(opts = {}) {+ const { nodes } = await graph(opts);+ return [...nodes].sort((a, b) => (b.mentions || 0) - (a.mentions || 0));+ }++ /** Memories that mention a given entity node. Wraps `GET /api/memory/graph?entityId=`. */+ async function memoriesFor(entityId, opts = {}) {+ if (!entityId || typeof entityId !== 'string') {+ throw new ThreeWsError('memoriesFor() needs an `entityId` string.', { code: 'invalid_input' });+ }+ const res = await request('/api/memory/graph', { query: { agentId, entityId }, signal: opts.signal });+ return (res?.memories || []).map(shapeMemory);+ }++ /** The always-in-context working set + live token budget. Wraps `GET /api/memory/context`. */+ async function context(opts = {}) {+ const res = await request('/api/memory/context', { query: { agentId }, signal: opts.signal });+ return {+ entries: (res?.entries || []).map(shapeMemory),+ tokens: res?.tokens ?? 0,+ budget: res?.budget ?? 2000,+ overBudget: Boolean(res?.overBudget),+ counts: res?.counts || { total: 0, working: 0, recall: 0, archival: 0, embedded: 0 },+ raw: res,+ };+ }++ // ── Curation (owner-only, POST /api/memory/curate) ───────────────────────────++ async function curate(op, payload = {}, opts = {}) {+ const res = await request('/api/memory/curate', {+ method: 'POST',+ body: { agentId, op, ...payload },+ signal: opts.signal,+ });+ return res;+ }++ function requireId(id, label) {+ if (!id || typeof id !== 'string') {+ throw new ThreeWsError(`${label} needs a memory id string.`, { code: 'invalid_input' });+ }+ }++ /** Pin a memory to the working core (tier → working, pinned → true). */+ async function pin(id, opts) {+ requireId(id, 'pin()');+ return shapeMemory((await curate('pin', { memoryId: id }, opts))?.entry);+ }+ /** Unpin a memory (pinned → false, tier → recall). */+ async function unpin(id, opts) {+ requireId(id, 'unpin()');+ return shapeMemory((await curate('unpin', { memoryId: id }, opts))?.entry);+ }+ /** Move a memory to a tier (`working | recall | archival`). */+ async function retier(id, tier, opts) {+ requireId(id, 'retier()');+ normalizeEnum(tier, MEMORY_TIERS, 'tier'); // throws if invalid; required here+ if (!tier) throw new ThreeWsError('retier() needs a `tier`.', { code: 'invalid_input' });+ return shapeMemory((await curate('tier', { memoryId: id, tier }, opts))?.entry);+ }+ /** Set a memory's importance, `0..1`. */+ async function setSalience(id, salience, opts) {+ requireId(id, 'setSalience()');+ assertUnit(salience, 'salience');+ return shapeMemory((await curate('salience', { memoryId: id, salience }, opts))?.entry);+ }+ /** Edit a memory's content/tags — re-embeds + re-mines on content change. */+ async function edit(id, changes = {}, opts) {+ requireId(id, 'edit()');+ const hasContent = typeof changes.content === 'string';+ const hasTags = Array.isArray(changes.tags);+ if (!hasContent && !hasTags) {+ throw new ThreeWsError('edit() needs `content` or `tags` to change.', { code: 'invalid_input' });+ }+ return shapeMemory((await curate('edit', prune({ memoryId: id, content: changes.content, tags: changes.tags }), opts))?.entry);+ }+ /** Fold duplicate memories into the first id; re-indexes the survivor. */+ async function merge(memoryIds, opts) {+ const ids = Array.isArray(memoryIds) ? memoryIds.filter(Boolean) : [];+ if (ids.length < 2) {+ throw new ThreeWsError('merge() needs at least 2 memory ids: [target, ...dupes].', { code: 'invalid_input' });+ }+ const res = await curate('merge', { memoryIds: ids }, opts);+ return { entry: shapeMemory(res?.entry), merged: res?.merged ?? 0 };+ }+ /** Delete a memory. Returns `{ ok, id }`. */+ async function forget(id, opts) {+ requireId(id, 'forget()');+ const res = await curate('forget', { memoryId: id }, opts);+ return { ok: Boolean(res?.ok), id: res?.forgot ?? id };+ }++ return {+ agentId,+ remember, recall, list,+ graph, entities, memoriesFor, context,+ pin, unpin, retier, setSalience, edit, merge, forget,+ };+}++/**+ * The README's headline ergonomic surface: `new AgentMemory({ agentId, token })`.+ * A thin class wrapper over `createAgentMemory` so methods read like an object+ * the agent owns.+ */+export class AgentMemory {+ constructor(options = {}) {+ const client = createAgentMemory(options);+ this.agentId = client.agentId;+ this.remember = client.remember;+ this.recall = client.recall;+ this.list = client.list;+ this.graph = client.graph;+ this.entities = client.entities;+ this.memoriesFor = client.memoriesFor;+ this.context = client.context;+ this.pin = client.pin;+ this.unpin = client.unpin;+ this.retier = client.retier;+ this.setSalience = client.setSalience;+ this.edit = client.edit;+ this.merge = client.merge;+ this.forget = client.forget;+ }+}++// ── Shaping ─────────────────────────────────────────────────────────────────++// The store's decorateMemory() already emits a mostly-camelCase memory (with a+// snake_case `agent_id`). Normalize that one stray field and keep a `.raw`+// escape hatch; pass score/match through untouched for recall() hits.+function shapeMemory(row) {+ if (!row || typeof row !== 'object') return null;+ const memory = {+ id: row.id,+ agentId: row.agentId ?? row.agent_id ?? null,+ type: row.type,+ content: row.content,+ tags: row.tags || [],+ context: row.context || {},+ salience: row.salience,+ tier: row.tier || 'recall',+ pinned: Boolean(row.pinned),+ embedder: row.embedder ?? null,+ hasEmbedding: Boolean(row.hasEmbedding),+ accessCount: row.accessCount ?? 0,+ isPublic: Boolean(row.isPublic),+ tokens: row.tokens ?? 0,+ createdAt: row.createdAt ?? null,+ updatedAt: row.updatedAt ?? null,+ lastAccessedAt: row.lastAccessedAt ?? null,+ expiresAt: row.expiresAt ?? null,+ raw: row,+ };+ if ('score' in row) memory.score = row.score;+ if ('match' in row) memory.match = row.match;+ return memory;+}++function shapeEntity(node) {+ return {+ id: node.id,+ kind: node.kind,+ label: node.label,+ salience: node.salience ?? null,+ mentions: node.mentions ?? 0,+ firstSeenAt: node.firstSeenAt ?? null,+ lastSeenAt: node.lastSeenAt ?? null,+ meta: node.meta || {},+ raw: node,+ };+}++// ── Validation helpers (mirror forge's enum/unit checks; throw before network) ──++function normalizeEnum(value, allowed, label, soft = false) {+ if (value === undefined || value === null) return undefined;+ if (!allowed.includes(value)) {+ if (soft) return undefined; // server clamps invalid values to a default+ throw new ThreeWsError(`Invalid ${label} "${value}". Expected one of: ${allowed.join(', ')}.`, { code: 'invalid_input' });+ }+ return value;+}++function assertUnit(value, label) {+ const n = Number(value);+ if (!Number.isFinite(n) || n < 0 || n > 1) {+ throw new ThreeWsError(`${label} must be a number in 0..1.`, { code: 'invalid_input' });+ }+}++function cleanTiers(tiers) {+ if (!Array.isArray(tiers)) return undefined;+ const list = tiers.map((t) => String(t).trim()).filter((t) => MEMORY_TIERS.includes(t));+ return list.length ? list : undefined;+}++function prune(obj) {+ const out = {};+ for (const [k, v] of Object.entries(obj)) {+ if (v === undefined || v === null) continue;+ if (Array.isArray(v) && v.length === 0) continue;+ out[k] = v;+ }+ return out;+}diff --git a/packages/forge/LICENSE b/packages/forge/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/forge/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/forge/package.json b/packages/forge/package.jsonindex dee46818a..16e1e8258 100644--- a/packages/forge/package.json+++ b/packages/forge/package.json@@ -2,6 +2,26 @@"name": "@three-ws/forge","version": "0.1.0","description": "Text/image/sketch → textured, rig-ready 3D GLB in one call. The three.ws Forge generation SDK — free TRELLIS lane, paid high-detail tiers, and auto-rigging.",+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "types": "./src/index.d.ts",+ "exports": {+ ".": {+ "types": "./src/index.d.ts",+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test test/*.test.js"+ },"keywords": ["3d","text-to-3d",@@ -14,15 +34,22 @@"rigging","three.ws"],+ "author": "nirholas <[email protected]>","license": "MIT",- "private": true,- "type": "module","homepage": "https://three.ws/forge","repository": {"type": "git",- "url": "https://github.com/nirholas/three.ws"+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/forge"},"bugs": {"url": "https://github.com/nirholas/three.ws/issues"+ },+ "engines": {+ "node": ">=18"+ },+ "dependencies": {},+ "publishConfig": {+ "access": "public"}}diff --git a/packages/forge/src/http.js b/packages/forge/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/forge/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/forge/src/index.d.ts b/packages/forge/src/index.d.tsnew file mode 100644index 000000000..23bd33033--- /dev/null+++ b/packages/forge/src/index.d.ts@@ -0,0 +1,87 @@+// Type definitions for @three-ws/forge++export declare class ThreeWsError extends Error {+ name: string;+ code: string;+ status: number | null;+ detail?: string;+ retryAfter?: number;+ body: unknown;+}++export declare class PaymentRequiredError extends ThreeWsError {+ accepts: unknown | null;+}++export declare const DEFAULT_BASE_URL: string;++export type ForgePath = 'image' | 'geometry' | 'sketch';+export type ForgeTier = 'draft' | 'standard' | 'high';+export type ForgeStatus = 'queued' | 'running' | 'done' | 'failed';++export interface ForgeInput {+ /** Text description. Required for the text and sketch paths. */+ prompt?: string;+ /** One or more image URLs / data URIs. Switches to image→3D. */+ images?: string[];+ /** Reference-image aspect for the `image` path, e.g. "1:1". */+ aspectRatio?: string;+}++export interface ForgeOptions {+ path?: ForgePath;+ tier?: ForgeTier;+ /** Force a generation backend (`nvidia`, `huggingface`, `meshy`, `tripo`). */+ backend?: string;+ /** Billing lane for paid tiers. */+ payWith?: 'x402' | 'credits';+ /** Called on each poll tick with the latest job state. */+ onProgress?: (job: ForgeResult) => void;+ pollIntervalMs?: number;+ timeoutMs?: number;+ headers?: Record<string, string>;+ signal?: AbortSignal;+}++export interface ForgeResult {+ jobId: string | null;+ creationId: string | null;+ status: ForgeStatus;+ glbUrl: string | null;+ viewerUrl: string | null;+ path: string | null;+ tier: string | null;+ backend: string | null;+ etaSeconds: number | null;+ estimatedCredits: number | null;+ durable: boolean;+ raw: unknown;+}++export interface Catalog {+ tiers: unknown[];+ backends: unknown[];+ paths: unknown[];+ [key: string]: unknown;+}++export interface ForgeClientOptions {+ baseUrl?: string;+ fetch?: typeof fetch;+ apiKey?: string;+ /** BYOK Meshy/Tripo key for the geometry path. */+ providerKey?: string;+ headers?: Record<string, string>;+}++export interface ForgeClient {+ forge(promptOrInput: string | ForgeInput, opts?: ForgeOptions): Promise<ForgeResult>;+ rig(glbUrl: string, opts?: ForgeOptions): Promise<ForgeResult>;+ catalog(opts?: { signal?: AbortSignal }): Promise<Catalog>;+ getJob(jobId: string, opts?: { signal?: AbortSignal }): Promise<ForgeResult>;+}++export declare function createForge(options?: ForgeClientOptions): ForgeClient;+export declare function forge(promptOrInput: string | ForgeInput, opts?: ForgeOptions): Promise<ForgeResult>;+export declare function rig(glbUrl: string, opts?: ForgeOptions): Promise<ForgeResult>;+export declare function catalog(opts?: { signal?: AbortSignal }): Promise<Catalog>;diff --git a/packages/forge/src/index.js b/packages/forge/src/index.jsnew file mode 100644index 000000000..f98f0e7bf--- /dev/null+++ b/packages/forge/src/index.js@@ -0,0 +1,181 @@+// @three-ws/forge — text/image/sketch → textured, rig-ready 3D GLB.+// Thin client over the public, auth-free /api/forge endpoint (the SDK twin of+// the 3D Studio MCP server). See README.md for the full reference.++import { createHttp, delay, ThreeWsError } from './http.js';++export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';++const TIERS = ['draft', 'standard', 'high'];+const PATHS = ['image', 'geometry', 'sketch'];++/**+ * Create a Forge client bound to a base URL, fetch, and optional auth/provider key.+ * For most callers the default export `forge()` / `rig()` is enough; use this+ * when you want to reuse configuration (a payment-aware fetch, a custom origin,+ * a BYOK provider key) across many calls.+ */+export function createForge(options = {}) {+ const request = createHttp(options);+ const providerKey = options.providerKey || null;++ function providerHeaders(extra) {+ const h = { ...(extra || {}) };+ if (providerKey) h['x-forge-provider-key'] = providerKey;+ return h;+ }++ /** Submit a generation and resolve once the GLB is ready. */+ async function forge(promptOrInput, opts = {}) {+ const input = typeof promptOrInput === 'string' ? { prompt: promptOrInput } : { ...(promptOrInput || {}) };+ const path = normalizeEnum(opts.path, PATHS, 'path');+ const tier = normalizeEnum(opts.tier, TIERS, 'tier');++ if (!input.prompt && !(input.images && input.images.length)) {+ throw new ThreeWsError('forge() needs a `prompt` or at least one image.', { code: 'invalid_input' });+ }+ if (path === 'sketch' && !input.prompt) {+ throw new ThreeWsError('The sketch path needs a `prompt` naming what the drawing depicts.', { code: 'invalid_input' });+ }++ const body = {+ prompt: input.prompt,+ image_urls: input.images,+ aspect_ratio: input.aspectRatio,+ path,+ tier,+ backend: opts.backend,+ pay_with: opts.payWith,+ };++ const submitted = await request('/api/forge', {+ method: 'POST',+ body: prune(body),+ headers: providerHeaders(opts.headers),+ signal: opts.signal,+ });++ return resolveJob(submitted, opts);+ }++ /** Auto-rig an existing GLB into an animation-ready humanoid. */+ async function rig(glbUrl, opts = {}) {+ if (!glbUrl || typeof glbUrl !== 'string') {+ throw new ThreeWsError('rig() needs a GLB url string.', { code: 'invalid_input' });+ }+ const submitted = await request('/api/forge', {+ method: 'POST',+ query: { action: 'rig' },+ body: { glb_url: glbUrl },+ headers: providerHeaders(opts.headers),+ signal: opts.signal,+ });+ return resolveJob(submitted, opts);+ }++ /** Fetch the live tier / backend / cost matrix. */+ async function catalog(opts = {}) {+ return request('/api/forge', { query: { catalog: '1' }, signal: opts.signal });+ }++ /** Poll a single job once. */+ async function getJob(jobId, opts = {}) {+ return shape(await request('/api/forge', { query: { job: jobId }, signal: opts.signal }), options.baseUrl);+ }++ // Poll a submitted job to completion (sync backends return done immediately).+ async function resolveJob(submitted, opts) {+ let job = shape(submitted, options.baseUrl);+ opts.onProgress?.(job);+ if (job.status === 'done' || !job.jobId) {+ if (job.status === 'failed') throw failed(job);+ return job;+ }+ const intervalMs = opts.pollIntervalMs ?? 2500;+ const timeoutMs = opts.timeoutMs ?? 180_000;+ const start = now();+ while (job.status !== 'done') {+ if (now() - start > timeoutMs) {+ throw new ThreeWsError(`Forge job ${job.jobId} did not finish within ${Math.round(timeoutMs / 1000)}s.`, { code: 'timeout' });+ }+ await delay(intervalMs, opts.signal);+ job = shape(await request('/api/forge', { query: { job: job.jobId }, signal: opts.signal }), options.baseUrl);+ opts.onProgress?.(job);+ if (job.status === 'failed') throw failed(job);+ }+ return job;+ }++ return { forge, rig, catalog, getJob };+}++// A module-level default client for the zero-config path: `import { forge }`.+let shared = null;+function defaultClient() {+ return (shared ||= createForge());+}++/** Generate a GLB from text, image(s), or a sketch. */+export function forge(promptOrInput, opts) {+ return defaultClient().forge(promptOrInput, opts);+}+/** Auto-rig a GLB into an animation-ready humanoid. */+export function rig(glbUrl, opts) {+ return defaultClient().rig(glbUrl, opts);+}+/** Fetch the live tier / backend / cost matrix. */+export function catalog(opts) {+ return defaultClient().catalog(opts);+}++function shape(res, baseUrl) {+ if (!res || typeof res !== 'object') {+ throw new ThreeWsError('Unexpected empty response from /api/forge.', { code: 'bad_response' });+ }+ const origin = String(baseUrl || 'https://three.ws').replace(/\/+$/, '');+ const creationId = res.creation_id ?? null;+ return {+ jobId: res.job_id ?? null,+ creationId,+ status: res.status || (res.glb_url ? 'done' : 'queued'),+ glbUrl: res.glb_url ?? null,+ viewerUrl: creationId ? `${origin}/forge?share=${creationId}` : null,+ path: res.path ?? null,+ tier: res.tier ?? null,+ backend: res.backend ?? null,+ etaSeconds: res.eta_seconds ?? null,+ estimatedCredits: res.estimated_credits ?? null,+ durable: Boolean(res.durable),+ raw: res,+ };+}++function failed(job) {+ return new ThreeWsError(job.raw?.message || 'Forge generation failed to produce a usable mesh.', {+ code: job.raw?.error || 'generation_failed',+ body: job.raw,+ });+}++function normalizeEnum(value, allowed, label) {+ if (value === undefined || value === null) return undefined;+ if (!allowed.includes(value)) {+ throw new ThreeWsError(`Invalid ${label} "${value}". Expected one of: ${allowed.join(', ')}.`, { code: 'invalid_input' });+ }+ return value;+}++function prune(obj) {+ const out = {};+ for (const [k, v] of Object.entries(obj)) {+ if (v === undefined || v === null) continue;+ if (Array.isArray(v) && v.length === 0) continue;+ out[k] = v;+ }+ return out;+}++function now() {+ // Date.now via getTime keeps this testable without relying on a frozen clock.+ return new Date().getTime();+}diff --git a/packages/forge/test/forge.test.js b/packages/forge/test/forge.test.jsnew file mode 100644index 000000000..5d60e26dd--- /dev/null+++ b/packages/forge/test/forge.test.js@@ -0,0 +1,115 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createForge, ThreeWsError, PaymentRequiredError } from '../src/index.js';++// A scripted fetch double: each call shifts the next queued response and records+// the request. No network, no real endpoints — we assert on request shaping and+// response parsing, which is all the SDK is responsible for.+function stubFetch(responses) {+ const calls = [];+ const queue = [...responses];+ const fetch = async (url, init) => {+ calls.push({ url: new URL(url), init });+ const next = queue.shift();+ if (!next) throw new Error('stubFetch: no more queued responses');+ const { status = 200, body = {}, headers = {} } = next;+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: { get: (k) => headers[k.toLowerCase()] ?? null },+ text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),+ };+ };+ return { fetch, calls };+}++test('forge() posts the prompt and shapes a synchronous done job', async () => {+ const { fetch, calls } = stubFetch([+ { body: { job_id: null, creation_id: 'c1', status: 'done', glb_url: 'https://cdn.three.ws/a.glb', backend: 'nvidia', tier: 'standard', path: 'image', durable: true } },+ ]);+ const client = createForge({ fetch, baseUrl: 'https://three.ws' });+ const res = await client.forge('a chrome robot');++ assert.equal(calls[0].url.pathname, '/api/forge');+ assert.equal(calls[0].init.method, 'POST');+ const sent = JSON.parse(calls[0].init.body);+ assert.equal(sent.prompt, 'a chrome robot');+ assert.ok(!('path' in sent), 'unset options are pruned from the body');+ assert.equal(res.status, 'done');+ assert.equal(res.glbUrl, 'https://cdn.three.ws/a.glb');+ assert.equal(res.viewerUrl, 'https://three.ws/forge?share=c1');+ assert.equal(res.backend, 'nvidia');+});++test('forge() polls a queued job until done', async () => {+ const { fetch, calls } = stubFetch([+ { body: { job_id: 'j1', creation_id: 'c2', status: 'queued' } },+ { body: { job_id: 'j1', status: 'running' } },+ { body: { job_id: 'j1', creation_id: 'c2', status: 'done', glb_url: 'https://cdn.three.ws/b.glb' } },+ ]);+ const ticks = [];+ const client = createForge({ fetch });+ const res = await client.forge('a fox', { pollIntervalMs: 1, onProgress: (j) => ticks.push(j.status) });++ assert.equal(res.glbUrl, 'https://cdn.three.ws/b.glb');+ assert.equal(calls[1].url.searchParams.get('job'), 'j1');+ assert.ok(ticks.includes('queued'));+ assert.ok(ticks.includes('done'));+});++test('rig() targets action=rig with the glb_url', async () => {+ const { fetch, calls } = stubFetch([+ { body: { job_id: null, creation_id: 'c3', status: 'done', glb_url: 'https://cdn.three.ws/rigged.glb' } },+ ]);+ const client = createForge({ fetch });+ const res = await client.rig('https://cdn.three.ws/raw.glb');+ assert.equal(calls[0].url.searchParams.get('action'), 'rig');+ assert.equal(JSON.parse(calls[0].init.body).glb_url, 'https://cdn.three.ws/raw.glb');+ assert.equal(res.glbUrl, 'https://cdn.three.ws/rigged.glb');+});++test('the geometry path attaches the BYOK provider key header', async () => {+ const { fetch, calls } = stubFetch([{ body: { status: 'done', glb_url: 'x' } }]);+ const client = createForge({ fetch, providerKey: 'meshy_test_key' });+ await client.forge('a sword', { path: 'geometry' });+ assert.equal(calls[0].init.headers['x-forge-provider-key'], 'meshy_test_key');+});++test('needs_key (501) surfaces as a typed ThreeWsError', async () => {+ const { fetch } = stubFetch([{ status: 501, body: { error: 'needs_key', message: 'Add a Meshy key.' } }]);+ const client = createForge({ fetch });+ await assert.rejects(() => client.forge('x', { path: 'geometry' }), (e) => {+ assert.ok(e instanceof ThreeWsError);+ assert.equal(e.code, 'needs_key');+ assert.equal(e.status, 501);+ return true;+ });+});++test('402 surfaces as PaymentRequiredError carrying the x402 challenge', async () => {+ const accepts = [{ scheme: 'exact', asset: 'USDC', network: 'eip155:8453', maxAmountRequired: '150000' }];+ const { fetch } = stubFetch([{ status: 402, body: { error: 'payment_required', message: 'pay', accepts } }]);+ const client = createForge({ fetch });+ await assert.rejects(() => client.forge('x', { tier: 'high' }), (e) => {+ assert.ok(e instanceof PaymentRequiredError);+ assert.deepEqual(e.accepts, accepts);+ return true;+ });+});++test('invalid tier/path are rejected before any network call', async () => {+ const { fetch, calls } = stubFetch([]);+ const client = createForge({ fetch });+ await assert.rejects(() => client.forge('x', { tier: 'ultra' }), /Invalid tier/);+ await assert.rejects(() => client.forge('x', { path: 'voxel' }), /Invalid path/);+ await assert.rejects(() => client.forge({}), /needs a `prompt`/);+ assert.equal(calls.length, 0);+});++test('catalog() reads the matrix endpoint', async () => {+ const { fetch, calls } = stubFetch([{ body: { tiers: [{ id: 'draft' }], backends: [], paths: [] } }]);+ const client = createForge({ fetch });+ const cat = await client.catalog();+ assert.equal(calls[0].url.searchParams.get('catalog'), '1');+ assert.equal(cat.tiers[0].id, 'draft');+});diff --git a/packages/glb-tools/LICENSE b/packages/glb-tools/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/glb-tools/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/glb-tools/src/http.js b/packages/glb-tools/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/glb-tools/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/guardian/LICENSE b/packages/guardian/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/guardian/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/guardian/src/http.js b/packages/guardian/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/guardian/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/mocap/LICENSE b/packages/mocap/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/mocap/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/mocap/src/http.js b/packages/mocap/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/mocap/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/mocap/src/index.d.ts b/packages/mocap/src/index.d.tsnew file mode 100644index 000000000..64aecba28--- /dev/null+++ b/packages/mocap/src/index.d.ts@@ -0,0 +1,149 @@+// Type definitions for @three-ws/mocap++export declare class ThreeWsError extends Error {+ name: string;+ code: string;+ status: number | null;+ detail?: string;+ retryAfter?: number;+ body: unknown;+}++export declare class PaymentRequiredError extends ThreeWsError {+ accepts: unknown | null;+}++export declare const DEFAULT_BASE_URL: string;++export type ClipKind = 'face' | 'pose' | 'hand' | 'vmc';+export type Visibility = 'private' | 'unlisted' | 'public';+export type ClipOwner = 'self' | 'other';++/** One captured frame. `t` is seconds from clip start. */+export interface Frame {+ t: number;+ shapes: Record<string, number>;+ mat?: number[] | null;+}++/** The object the capture runtime's `getRecording()` returns. */+export interface Recording {+ format: string;+ duration: number;+ frames: Frame[];+}++export interface Price {+ amount: string;+ currency: string;+}++/** Per-call authentication. Pass a bearer token, or rely on a session cookie. */+export interface Auth {+ /** Bearer token attached as `Authorization` for this call. */+ token?: string;+ /** Extra headers merged into the request. */+ headers?: Record<string, string>;+ signal?: AbortSignal;+}++export interface SaveMeta {+ /** Required. 1–120 chars. */+ name: string;+ /** `^[a-z0-9][a-z0-9-]{0,79}$`, unique per owner. Auto-derived from `name` if omitted. */+ slug?: string;+ description?: string;+ /** Up to 20 tags, ≤40 chars each. */+ tags?: string[];+ visibility?: Visibility;+ /** Bind the clip to one of your avatars (must be owned by you). */+ avatarId?: string;+ /** Snake-case alias for `avatarId`. */+ avatar_id?: string;+ signal?: AbortSignal;+}++export interface ListOptions {+ /** Clamped to 1–100. Default 50. */+ limit?: number;+ /** `nextCursor` from the previous page. */+ cursor?: string;+ kind?: ClipKind;+ /** Authed: union your clips with the public pool. */+ includePublic?: boolean;+ signal?: AbortSignal;+}++export interface UpdatePatch {+ name?: string;+ description?: string;+ tags?: string[];+ visibility?: Visibility;+ /** Bind/unbind an avatar; `null` unbinds. */+ avatarId?: string | null;+ avatar_id?: string | null;+ /** Set a sale price, or `null` to make the clip free again. */+ price?: Price | null;+ signal?: AbortSignal;+}++/** A mocap clip. `frames` is populated only by `getClip`. */+export interface Clip {+ id: string | null;+ slug: string | null;+ name: string | null;+ description: string | null;+ kind: ClipKind | null;+ format: string | null;+ durationMs: number | null;+ duration: number | null;+ frameCount: number | null;+ /** Present only on `getClip`; `null` from list/save/update. */+ frames: Frame[] | null;+ tags: string[];+ visibility: Visibility | null;+ avatarId: string | null;+ playCount: number | null;+ price: Price | null;+ owner: ClipOwner | null;+ createdAt: string | null;+ updatedAt: string | null;+ /** Raw endpoint payload, for fields not surfaced above. */+ raw: unknown;+}++export interface ClipPage {+ items: Clip[];+ nextCursor: string | null;+ raw: unknown;+}++export interface MocapClientOptions {+ baseUrl?: string;+ fetch?: typeof fetch;+ /** Default bearer token for every call. */+ apiKey?: string;+ /** Alias for `apiKey` (matches the README's `auth.token`). */+ token?: string;+ headers?: Record<string, string>;+}++export interface MocapClient {+ saveClip(recording: Recording, meta: SaveMeta, auth?: Auth | string): Promise<Clip>;+ getClip(idOrSlug: string, auth?: Auth | string): Promise<Clip>;+ listClips(auth?: Auth | string, opts?: ListOptions): Promise<ClipPage>;+ updateClip(idOrSlug: string, patch: UpdatePatch, auth?: Auth | string): Promise<Clip>;+ deleteClip(idOrSlug: string, auth?: Auth | string): Promise<{ ok: boolean }>;+}++export declare function createMocap(options?: MocapClientOptions): MocapClient;+export declare function saveClip(recording: Recording, meta: SaveMeta, auth?: Auth | string): Promise<Clip>;+export declare function getClip(idOrSlug: string, auth?: Auth | string): Promise<Clip>;+export declare function listClips(auth?: Auth | string, opts?: ListOptions): Promise<ClipPage>;+export declare function updateClip(idOrSlug: string, patch: UpdatePatch, auth?: Auth | string): Promise<Clip>;+export declare function deleteClip(idOrSlug: string, auth?: Auth | string): Promise<{ ok: boolean }>;++/** The wire-format strings the store accepts. */+export declare const supportedFormats: string[];+/** Map a format string to its clip kind, or `null` if unknown. */+export declare function formatKind(format: string): ClipKind | null;diff --git a/packages/mocap/src/index.js b/packages/mocap/src/index.jsnew file mode 100644index 000000000..17240d372--- /dev/null+++ b/packages/mocap/src/index.js@@ -0,0 +1,279 @@+// @three-ws/mocap — save, list, share, and replay motion-capture clips.+// Thin client over the auth'd /api/mocap/clips endpoints (the durable half of+// the in-browser mocap studio). Recording happens client-side; this SDK is the+// persistence layer. See README.md for the full reference.++import { createHttp, ThreeWsError } from './http.js';++export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';++// The wire-format strings the store accepts, and the clip `kind` each maps to.+// Mirrors SUPPORTED_FORMATS / FORMAT_KIND in api/mocap/clips.js.+const FORMAT_KIND = {+ 'three.ws.face-mocap.v1': 'face',+ 'three.ws.pose-mocap.v1': 'pose',+ 'three.ws.hand-mocap.v1': 'hand',+ 'three.ws.vmc.v1': 'vmc',+};+const SUPPORTED_FORMATS = Object.keys(FORMAT_KIND);+const VISIBILITIES = ['private', 'unlisted', 'public'];+const KINDS = ['face', 'pose', 'hand', 'vmc'];++const MAX_FRAMES = 18_000; // matches MAX_FRAMES_INLINE server-side+const MAX_NAME = 120;++/**+ * Create a Mocap client bound to a base URL, fetch, and optional auth.+ * For most callers the default exports `saveClip()` / `getClip()` / `listClips()`+ * are enough; use this to reuse configuration (a session-aware fetch, a custom+ * origin, a default bearer token) across many calls.+ *+ * @param {object} [options]+ * @param {string} [options.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [options.fetch] fetch implementation (default global).+ * @param {string} [options.apiKey] default bearer token for every call.+ * @param {string} [options.token] alias for apiKey (matches the README's `auth.token`).+ * @param {Record<string,string>} [options.headers] default headers on every call.+ */+export function createMocap(options = {}) {+ const request = createHttp({ ...options, apiKey: options.apiKey || options.token });++ /** Persist a browser recording. Wraps POST /api/mocap/clips. */+ async function saveClip(recording, meta = {}, auth) {+ const clip = normalizeRecording(recording);+ if (!meta || typeof meta.name !== 'string' || !meta.name.trim()) {+ throw new ThreeWsError('saveClip() needs `meta.name` (1–120 chars).', { code: 'invalid_input' });+ }+ if (meta.name.length > MAX_NAME) {+ throw new ThreeWsError(`meta.name must be ≤ ${MAX_NAME} chars.`, { code: 'invalid_input' });+ }+ const visibility = normalizeEnum(meta.visibility, VISIBILITIES, 'visibility');++ const body = prune({+ name: meta.name,+ slug: meta.slug,+ description: meta.description,+ avatar_id: meta.avatarId ?? meta.avatar_id,+ tags: meta.tags,+ visibility,+ clip,+ });++ const out = await request('/api/mocap/clips', {+ method: 'POST',+ body,+ headers: authHeaders(auth),+ signal: optSignal(auth, meta),+ });+ return shapeClip(out?.clip ?? out);+ }++ /** Fetch one clip with its full `frames` array. Wraps GET /api/mocap/clips/:id. */+ async function getClip(idOrSlug, auth) {+ const id = requireId(idOrSlug, 'getClip');+ const out = await request(`/api/mocap/clips/${encodeURIComponent(id)}`, {+ headers: authHeaders(auth),+ signal: optSignal(auth),+ });+ return shapeClip(out?.clip ?? out);+ }++ /** List clips without frames (metadata only). Wraps GET /api/mocap/clips. */+ async function listClips(auth, opts = {}) {+ const kind = normalizeEnum(opts.kind, KINDS, 'kind');+ const query = prune({+ limit: opts.limit != null ? clamp(opts.limit, 1, 100) : undefined,+ cursor: opts.cursor,+ kind,+ include_public: opts.includePublic ? 'true' : undefined,+ });+ const out = await request('/api/mocap/clips', {+ query,+ headers: authHeaders(auth),+ signal: optSignal(auth, opts),+ });+ return {+ items: (out?.items || []).map(shapeClip),+ nextCursor: out?.next_cursor ?? null,+ raw: out,+ };+ }++ /** Edit clip metadata (owner only). Wraps PATCH /api/mocap/clips/:id. */+ async function updateClip(idOrSlug, patch = {}, auth) {+ const id = requireId(idOrSlug, 'updateClip');+ const visibility = normalizeEnum(patch.visibility, VISIBILITIES, 'visibility');+ const body = prune({+ name: patch.name,+ description: patch.description,+ tags: patch.tags,+ visibility,+ avatar_id: 'avatarId' in patch ? patch.avatarId : patch.avatar_id,+ price: patch.price,+ }, { keepNull: ['avatar_id', 'price'] });++ if (Object.keys(body).length === 0) {+ throw new ThreeWsError('updateClip() needs at least one field to patch.', { code: 'invalid_input' });+ }+ const out = await request(`/api/mocap/clips/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body,+ headers: authHeaders(auth),+ signal: optSignal(auth, patch),+ });+ return shapeClip(out?.clip ?? out);+ }++ /** Soft-delete a clip you own. Wraps DELETE /api/mocap/clips/:id. */+ async function deleteClip(idOrSlug, auth) {+ const id = requireId(idOrSlug, 'deleteClip');+ const out = await request(`/api/mocap/clips/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ headers: authHeaders(auth),+ signal: optSignal(auth),+ });+ return { ok: out?.ok === true };+ }++ return { saveClip, getClip, listClips, updateClip, deleteClip };+}++// A module-level default client for the zero-config path: `import { saveClip }`.+let shared = null;+function defaultClient() {+ return (shared ||= createMocap());+}++/** Persist a browser recording to your library. */+export function saveClip(recording, meta, auth) {+ return defaultClient().saveClip(recording, meta, auth);+}+/** Fetch one clip with its full frames array, ready to replay. */+export function getClip(idOrSlug, auth) {+ return defaultClient().getClip(idOrSlug, auth);+}+/** List clips (metadata only), cursor-paginated, newest first. */+export function listClips(auth, opts) {+ return defaultClient().listClips(auth, opts);+}+/** Edit a clip's metadata (name, description, tags, visibility, avatar, price). */+export function updateClip(idOrSlug, patch, auth) {+ return defaultClient().updateClip(idOrSlug, patch, auth);+}+/** Soft-delete a clip you own. */+export function deleteClip(idOrSlug, auth) {+ return defaultClient().deleteClip(idOrSlug, auth);+}++/** The wire-format strings the store accepts. */+export const supportedFormats = SUPPORTED_FORMATS.slice();+/** Map a format string to its clip kind (`face` / `pose` / `hand` / `vmc`). */+export function formatKind(format) {+ return FORMAT_KIND[format] ?? null;+}++// ---- internals --------------------------------------------------------------++// Validate the recording the capture runtime handed us before any network call.+function normalizeRecording(recording) {+ if (!recording || typeof recording !== 'object') {+ throw new ThreeWsError('saveClip() needs the recording object from getRecording().', { code: 'invalid_input' });+ }+ const { format, duration, frames } = recording;+ if (typeof format !== 'string' || !FORMAT_KIND[format]) {+ throw new ThreeWsError(+ `Unsupported recording format "${format}". Expected one of: ${SUPPORTED_FORMATS.join(', ')}.`,+ { code: 'unsupported_format' },+ );+ }+ if (typeof duration !== 'number' || !Number.isFinite(duration) || duration < 0 || duration > 3600) {+ throw new ThreeWsError('recording.duration must be a number in seconds, 0–3600.', { code: 'invalid_input' });+ }+ if (!Array.isArray(frames) || frames.length === 0) {+ throw new ThreeWsError('recording.frames must be a non-empty array.', { code: 'invalid_input' });+ }+ if (frames.length > MAX_FRAMES) {+ throw new ThreeWsError(`recording.frames exceeds ${MAX_FRAMES} — split the capture.`, { code: 'invalid_input' });+ }+ // Pass frames through as-is (server re-validates each); just assert the+ // outer shape so a malformed buffer fails fast with a clear message.+ return { format, duration, frames };+}++// Per-call auth: `{ token }` → Authorization bearer that overrides the client default.+function authHeaders(auth) {+ const token = typeof auth === 'string' ? auth : auth?.token;+ const headers = { ...(auth?.headers || {}) };+ if (token) headers.authorization = `Bearer ${token}`;+ return Object.keys(headers).length ? headers : undefined;+}++function optSignal(auth, opts) {+ return auth?.signal ?? opts?.signal;+}++function shapeClip(row) {+ if (!row || typeof row !== 'object') {+ throw new ThreeWsError('Unexpected empty response from /api/mocap/clips.', { code: 'bad_response' });+ }+ const durationMs = row.duration_ms ?? null;+ return {+ id: row.id ?? null,+ slug: row.slug ?? null,+ name: row.name ?? null,+ description: row.description ?? null,+ kind: row.kind ?? null,+ format: row.format ?? null,+ durationMs,+ duration: row.duration ?? (durationMs != null ? durationMs / 1000 : null),+ frameCount: row.frame_count ?? null,+ frames: row.frames ?? null,+ tags: row.tags ?? [],+ visibility: row.visibility ?? null,+ avatarId: row.avatar_id ?? null,+ playCount: row.play_count != null ? Number(row.play_count) : null,+ price: row.price ?? null,+ owner: row.owner ?? null,+ createdAt: row.created_at ?? null,+ updatedAt: row.updated_at ?? null,+ raw: row,+ };+}++function requireId(idOrSlug, fn) {+ if (typeof idOrSlug !== 'string' || !idOrSlug.trim()) {+ throw new ThreeWsError(`${fn}() needs a clip id or slug.`, { code: 'invalid_input' });+ }+ return idOrSlug.trim();+}++function normalizeEnum(value, allowed, label) {+ if (value === undefined || value === null) return undefined;+ if (!allowed.includes(value)) {+ throw new ThreeWsError(`Invalid ${label} "${value}". Expected one of: ${allowed.join(', ')}.`, { code: 'invalid_input' });+ }+ return value;+}++function clamp(n, lo, hi) {+ const v = Math.trunc(Number(n));+ if (!Number.isFinite(v)) return lo;+ return Math.min(Math.max(v, lo), hi);+}++// Drop undefined / empty-array fields. `keepNull` lists keys whose explicit+// null is meaningful to the endpoint (price: null clears a price; avatar_id:+// null unbinds an avatar) and must survive pruning.+function prune(obj, { keepNull = [] } = {}) {+ const out = {};+ for (const [k, v] of Object.entries(obj)) {+ if (v === undefined) continue;+ if (v === null) {+ if (keepNull.includes(k)) out[k] = null;+ continue;+ }+ if (Array.isArray(v) && v.length === 0) continue;+ out[k] = v;+ }+ return out;+}diff --git a/packages/names/LICENSE b/packages/names/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/names/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/names/package.json b/packages/names/package.jsonindex 97103a1d3..51aab747b 100644--- a/packages/names/package.json+++ b/packages/names/package.json@@ -2,6 +2,26 @@"name": "@three-ws/names","version": "0.1.0","description": "ENS + SNS name resolution, *.threews.sol subdomain minting, and pay-by-name in one import. The three.ws agent-identity SDK.",+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "types": "./src/index.d.ts",+ "exports": {+ ".": {+ "types": "./src/index.d.ts",+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test test/*.test.js"+ },"keywords": ["ens","sns",@@ -15,15 +35,22 @@"agent-identity","three.ws"],+ "author": "nirholas <[email protected]>","license": "MIT",- "private": true,- "type": "module",- "homepage": "https://three.ws",+ "homepage": "https://three.ws/names","repository": {"type": "git",- "url": "https://github.com/nirholas/three.ws"+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/names"},"bugs": {"url": "https://github.com/nirholas/three.ws/issues"+ },+ "engines": {+ "node": ">=18"+ },+ "dependencies": {},+ "publishConfig": {+ "access": "public"}}diff --git a/packages/names/src/http.js b/packages/names/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/names/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/names/src/index.d.ts b/packages/names/src/index.d.tsnew file mode 100644index 000000000..a84cae197--- /dev/null+++ b/packages/names/src/index.d.ts@@ -0,0 +1,191 @@+// Type definitions for @three-ws/names++export declare class ThreeWsError extends Error {+ name: string;+ code: string;+ status: number | null;+ detail?: string;+ retryAfter?: number;+ body: unknown;+}++export declare class PaymentRequiredError extends ThreeWsError {+ accepts: unknown | null;+}++export declare const DEFAULT_BASE_URL: string;++export type Network = 'solana' | 'ethereum';+export type PayMode = 'prep' | 'send';+export type PayeeSource = 'address' | 'sns' | 'username';++export interface NamesClientOptions {+ baseUrl?: string;+ fetch?: typeof fetch;+ /** Bearer token attached to every authenticated call. */+ apiKey?: string;+ /** Alias for `apiKey`. */+ token?: string;+ headers?: Record<string, string>;+}++export interface CallOptions {+ signal?: AbortSignal;+ headers?: Record<string, string>;+ /** Per-call bearer token; overrides the client default. */+ token?: string;+}++export interface ResolveResult {+ /** The resolved name, e.g. `alice.sol` or `vitalik.eth`. Null on a miss. */+ name: string | null;+ /** Owner wallet (base58 for SNS, 0x for ENS). Null when `resolved` is false. */+ address: string | null;+ /** Which registry answered. */+ network: Network;+ /** `false` is a routine "no such name", not an error (SNS only). */+ resolved: boolean;+ /** (SNS) other `.sol` domains the owner holds. */+ allDomains: string[];+ /** (SNS) the owner's primary `.sol`, if set. */+ favoriteDomain: string | null;+ /** (ENS) agents registered to the resolved address. */+ agents?: unknown[];+ raw: unknown;+}++export interface Availability {+ label: string | null;+ parent: string | null;+ fullName: string | null;+ available: boolean;+ owner: string | null;+ raw: unknown;+}++export interface MintInput {+ /** Required. The agent the subdomain attaches to. */+ agentId: string;+ /** Optional. Defaults to the agent's slugified name. 1–63 chars `[a-z0-9-]`. */+ label?: string;+ /** Optional base58 wallet to receive ownership. Must be linked to your account. */+ ownerAddress?: string;+ /** Optional, 1000–10000. Registry bytes reserved. Default 2000. */+ space?: number;+ /** Bearer token (or rely on a session cookie). */+ token?: string;+ headers?: Record<string, string>;+ signal?: AbortSignal;+}++export interface MintResult {+ ok: boolean;+ agentId: string | null;+ fullName: string | null;+ parent: string | null;+ owner: string | null;+ signature: string | null;+ explorer: string | null;+ urlRecord: string | null;+ agentUrl: string | null;+ raw: unknown;+}++export interface ClaimInput {+ /** Required. Must equal your account username. */+ label: string;+ /** Optional base58 wallet (linked to your account) to receive ownership. */+ ownerWallet?: string;+ token?: string;+ headers?: Record<string, string>;+ signal?: AbortSignal;+}++export interface ClaimResult {+ id: string | null;+ label: string | null;+ parent: string | null;+ ownerWallet: string | null;+ urlRecord: string | null;+ signature: string | null;+ fullName: string | null;+ showcaseUrl: string | null;+ explorer: string | null;+ createdAt: string | null;+ raw: unknown;+}++export interface PayeeClaim {+ user_id: string;+ username: string;+ display_name: string | null;+}++export interface Payee {+ name: string | null;+ address: string | null;+ source: PayeeSource | null;+ resolved: string | null;+ claim?: PayeeClaim | null;+ raw: unknown;+}++export interface PayOptions {+ /** `prep` returns an unsigned tx; `send` has the agent sign and broadcast. Default `prep`. */+ mode?: PayMode;+ /** Required for `prep`. Base58 fee-payer + source. */+ payerWallet?: string;+ /** Required for `send`. The agent that signs (must be yours). */+ agentId?: string;+ /** (`send`) the address you previewed; rejects with `recipient_changed` if the name re-points. */+ expectedAddress?: string;+ /** Optional memo. */+ message?: string;+ /** Bearer token for `send`. */+ token?: string;+ headers?: Record<string, string>;+ signal?: AbortSignal;+}++export interface PayPrepResult {+ mode: 'prep';+ recipient: Payee;+ amountUsdc: number | null;+ txBase64: string | null;+ blockhash: string | null;+ lastValidBlockHeight: number | null;+ mint: string | null;+ raw: unknown;+}++export interface PaySendResult {+ mode: 'send';+ recipient: Payee;+ payer: string | null;+ amountUsdc: number | null;+ signature: string | null;+ raw: unknown;+}++export type PayResult = PayPrepResult | PaySendResult;++export interface NamesClient {+ resolve(name: string, opts?: CallOptions): Promise<ResolveResult>;+ reverseLookup(address: string, opts?: CallOptions): Promise<ResolveResult>;+ checkSubdomain(label: string, opts?: CallOptions): Promise<Availability>;+ mintSubdomain(input: MintInput): Promise<MintResult>;+ claimSubdomain(input: ClaimInput): Promise<ClaimResult>;+ releaseSubdomain(label: string, opts?: CallOptions): Promise<unknown>;+ resolvePayee(name: string, opts?: CallOptions): Promise<Payee>;+ payByName(name: string, amountUsdc: string | number, opts?: PayOptions): Promise<PayResult>;+}++export declare function createNames(options?: NamesClientOptions): NamesClient;+export declare function resolve(name: string, opts?: CallOptions): Promise<ResolveResult>;+export declare function reverseLookup(address: string, opts?: CallOptions): Promise<ResolveResult>;+export declare function checkSubdomain(label: string, opts?: CallOptions): Promise<Availability>;+export declare function mintSubdomain(input: MintInput): Promise<MintResult>;+export declare function claimSubdomain(input: ClaimInput): Promise<ClaimResult>;+export declare function releaseSubdomain(label: string, opts?: CallOptions): Promise<unknown>;+export declare function resolvePayee(name: string, opts?: CallOptions): Promise<Payee>;+export declare function payByName(name: string, amountUsdc: string | number, opts?: PayOptions): Promise<PayResult>;diff --git a/packages/names/src/index.js b/packages/names/src/index.jsnew file mode 100644index 000000000..82b4ec891--- /dev/null+++ b/packages/names/src/index.js@@ -0,0 +1,374 @@+// @three-ws/names — ENS + SNS resolution, *.threews.sol subdomain minting, and+// pay-by-name. A thin client over the public /api/sns, /api/sns-subdomain,+// /api/threews/subdomain, /api/x402/pay-by-name, and /api/agents/ens endpoints.+// See README.md for the full reference.++import { createHttp, ThreeWsError } from './http.js';++export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';++// Matches the platform's name validators. `.eth` routes to the ENS resolver,+// everything else (a `.sol` domain or a bare label) routes to the .sol registry.+const ETH_RE = /^(?:[a-z0-9-]+\.)+eth$/i;+const SOL_NAME_RE = /^[a-z0-9-]{1,63}(?:\.[a-z0-9-]{1,63})*(?:\.sol)?$/i;+const ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const PAY_MODES = ['prep', 'send'];++/**+ * Create a Names client bound to a base URL, fetch, and optional auth.+ * For most callers the default exports (`resolve()`, `payByName()`, …) are+ * enough; use this to reuse configuration — a payment-aware fetch, a custom+ * origin, or a bearer token — across many calls.+ */+export function createNames(options = {}) {+ const request = createHttp(options);+ const defaultToken = options.apiKey || options.token || null;++ // A per-call bearer token overrides the client default. Both land in the+ // Authorization header the http core already understands.+ function authHeaders(token, extra) {+ const h = { ...(extra || {}) };+ const bearer = token || defaultToken;+ if (bearer) h.authorization = `Bearer ${bearer}`;+ return h;+ }++ /** Resolve a name to an address. `.eth` → ENS, `.sol`/bare label → SNS. */+ async function resolve(name, opts = {}) {+ const trimmed = String(name || '').trim();+ if (!trimmed) {+ throw new ThreeWsError('resolve() needs a non-empty name.', { code: 'invalid_input' });+ }+ if (ETH_RE.test(trimmed)) {+ const res = await request(`/api/agents/ens/${encodeURIComponent(trimmed.toLowerCase())}`, {+ signal: opts.signal,+ });+ return shapeEns(res);+ }+ if (!SOL_NAME_RE.test(trimmed)) {+ throw new ThreeWsError(+ `Invalid name "${trimmed}". Expected a .eth name, a .sol domain, or a bare [a-z0-9-] label.`,+ { code: 'invalid_input' },+ );+ }+ const res = await request('/api/sns', { query: { name: trimmed }, signal: opts.signal });+ return shapeSns(res);+ }++ /** Find the primary `.sol` for a wallet. Wraps GET /api/sns?address=. */+ async function reverseLookup(address, opts = {}) {+ const addr = String(address || '').trim();+ if (!ADDR_RE.test(addr)) {+ throw new ThreeWsError('reverseLookup() needs a base58 Solana address.', { code: 'invalid_input' });+ }+ const res = await request('/api/sns', { query: { address: addr }, signal: opts.signal });+ return shapeSns(res);+ }++ /** Check whether `<label>.threews.sol` is free. Wraps GET /api/sns-subdomain?label=. */+ async function checkSubdomain(label, opts = {}) {+ const clean = String(label || '').trim();+ if (!clean) {+ throw new ThreeWsError('checkSubdomain() needs a label.', { code: 'invalid_input' });+ }+ const res = await request('/api/sns-subdomain', { query: { label: clean }, signal: opts.signal });+ return shapeAvailability(res);+ }++ /** Mint `<label>.threews.sol` for an agent. Wraps POST /api/sns-subdomain. Requires auth. */+ async function mintSubdomain(input = {}) {+ const agentId = typeof input.agentId === 'string' ? input.agentId.trim() : '';+ if (!agentId) {+ throw new ThreeWsError('mintSubdomain() needs an `agentId`.', { code: 'invalid_input' });+ }+ if (input.ownerAddress != null && !ADDR_RE.test(String(input.ownerAddress).trim())) {+ throw new ThreeWsError('ownerAddress must be a base58 Solana public key.', { code: 'invalid_input' });+ }+ if (input.space != null && !(Number.isInteger(input.space) && input.space >= 1000 && input.space <= 10000)) {+ throw new ThreeWsError('space must be an integer between 1000 and 10000.', { code: 'invalid_input' });+ }+ const body = prune({+ agent_id: agentId,+ label: input.label,+ owner_address: input.ownerAddress,+ space: input.space,+ });+ const res = await request('/api/sns-subdomain', {+ method: 'POST',+ body,+ headers: authHeaders(input.token, input.headers),+ signal: input.signal,+ });+ return shapeMint(res);+ }++ /** Claim `<username>.threews.sol` for the signed-in user. Wraps POST /api/threews/subdomain. */+ async function claimSubdomain(input = {}) {+ const label = typeof input.label === 'string' ? input.label.trim() : '';+ if (!label) {+ throw new ThreeWsError('claimSubdomain() needs a `label` (your username).', { code: 'invalid_input' });+ }+ if (input.ownerWallet != null && !ADDR_RE.test(String(input.ownerWallet).trim())) {+ throw new ThreeWsError('ownerWallet must be a base58 Solana public key.', { code: 'invalid_input' });+ }+ const body = prune({ label, owner_wallet: input.ownerWallet });+ const res = await request('/api/threews/subdomain', {+ method: 'POST',+ body,+ headers: authHeaders(input.token, input.headers),+ signal: input.signal,+ });+ return shapeClaim(res);+ }++ /** Drop the local `<label>.threews.sol` claim. Wraps DELETE /api/threews/subdomain. */+ async function releaseSubdomain(label, opts = {}) {+ const clean = String(label || '').trim();+ if (!clean) {+ throw new ThreeWsError('releaseSubdomain() needs a label.', { code: 'invalid_input' });+ }+ const res = await request('/api/threews/subdomain', {+ method: 'DELETE',+ query: { label: clean },+ headers: authHeaders(opts.token, opts.headers),+ signal: opts.signal,+ });+ return unwrap(res);+ }++ /** Resolve a payee by name (no payment). Wraps GET /api/x402/pay-by-name?name=. */+ async function resolvePayee(name, opts = {}) {+ const clean = String(name || '').trim();+ if (!clean) {+ throw new ThreeWsError('resolvePayee() needs a name.', { code: 'invalid_input' });+ }+ const res = await request('/api/x402/pay-by-name', { query: { name: clean }, signal: opts.signal });+ return shapePayee(unwrap(res));+ }++ /** Pay a recipient by name in USDC. Wraps POST /api/x402/pay-by-name. */+ async function payByName(name, amountUsdc, opts = {}) {+ const clean = String(name || '').trim();+ if (!clean) {+ throw new ThreeWsError('payByName() needs a name.', { code: 'invalid_input' });+ }+ const amount = Number(amountUsdc);+ if (!Number.isFinite(amount) || amount <= 0 || amount > 10000) {+ throw new ThreeWsError('amountUsdc must be a number > 0 and ≤ 10000.', { code: 'invalid_input' });+ }+ const mode = normalizeEnum(opts.mode, PAY_MODES, 'mode') || 'prep';++ if (mode === 'prep') {+ if (!opts.payerWallet || !ADDR_RE.test(String(opts.payerWallet).trim())) {+ throw new ThreeWsError('prep mode needs a base58 `payerWallet`.', { code: 'invalid_input' });+ }+ } else {+ if (!opts.agentId || typeof opts.agentId !== 'string') {+ throw new ThreeWsError('send mode needs an `agentId`.', { code: 'invalid_input' });+ }+ }++ const body = prune({+ name: clean,+ amount_usdc: amountUsdc,+ mode,+ payer_wallet: opts.payerWallet,+ agent_id: opts.agentId,+ expected_address: opts.expectedAddress,+ message: opts.message,+ });+ const res = await request('/api/x402/pay-by-name', {+ method: 'POST',+ body,+ headers: authHeaders(opts.token, opts.headers),+ signal: opts.signal,+ });+ return shapePay(unwrap(res), mode);+ }++ return {+ resolve,+ reverseLookup,+ checkSubdomain,+ mintSubdomain,+ claimSubdomain,+ releaseSubdomain,+ resolvePayee,+ payByName,+ };+}++// A module-level default client for the zero-config path: `import { resolve }`.+let shared = null;+function defaultClient() {+ return (shared ||= createNames());+}++/** Resolve a name to an address. `.eth` → ENS, `.sol`/bare label → SNS. */+export function resolve(name, opts) {+ return defaultClient().resolve(name, opts);+}+/** Find the primary `.sol` for a wallet. */+export function reverseLookup(address, opts) {+ return defaultClient().reverseLookup(address, opts);+}+/** Check whether `<label>.threews.sol` is free. */+export function checkSubdomain(label, opts) {+ return defaultClient().checkSubdomain(label, opts);+}+/** Mint `<label>.threews.sol` for an agent (requires auth). */+export function mintSubdomain(input) {+ return defaultClient().mintSubdomain(input);+}+/** Claim `<username>.threews.sol` for the signed-in user. */+export function claimSubdomain(input) {+ return defaultClient().claimSubdomain(input);+}+/** Drop the local `<label>.threews.sol` claim. */+export function releaseSubdomain(label, opts) {+ return defaultClient().releaseSubdomain(label, opts);+}+/** Resolve a payee by name (no payment). */+export function resolvePayee(name, opts) {+ return defaultClient().resolvePayee(name, opts);+}+/** Pay a recipient by name in USDC. */+export function payByName(name, amountUsdc, opts) {+ return defaultClient().payByName(name, amountUsdc, opts);+}++// ── shapers: snake_case envelopes → camelCase results, with a `.raw` escape hatch ──++// /api/sns answers in a { data: { … } } envelope; some endpoints answer bare.+function unwrap(res) {+ if (res && typeof res === 'object' && 'data' in res && res.data && typeof res.data === 'object') {+ return res.data;+ }+ return res;+}++function shapeSns(res) {+ const d = unwrap(res) || {};+ return {+ name: d.name ?? null,+ address: d.address ?? null,+ network: d.network || 'solana',+ resolved: Boolean(d.resolved),+ allDomains: Array.isArray(d.all_domains) ? d.all_domains : [],+ favoriteDomain: d.favorite_domain ?? null,+ raw: res,+ };+}++function shapeEns(res) {+ const d = res || {};+ const address = d.address ?? null;+ return {+ name: d.name ?? null,+ address,+ network: 'ethereum',+ resolved: Boolean(address),+ allDomains: [],+ favoriteDomain: null,+ agents: Array.isArray(d.agents) ? d.agents : [],+ raw: res,+ };+}++function shapeAvailability(res) {+ const d = unwrap(res) || {};+ return {+ label: d.label ?? null,+ parent: d.parent ?? null,+ fullName: d.full_name ?? d.full ?? null,+ available: Boolean(d.available),+ owner: d.owner ?? null,+ raw: res,+ };+}++function shapeMint(res) {+ const d = unwrap(res) || {};+ return {+ ok: Boolean(d.ok),+ agentId: d.agent_id ?? null,+ fullName: d.full_name ?? null,+ parent: d.parent ?? null,+ owner: d.owner ?? null,+ signature: d.signature ?? null,+ explorer: d.explorer ?? null,+ urlRecord: d.url_record ?? null,+ agentUrl: d.agent_url ?? null,+ raw: res,+ };+}++function shapeClaim(res) {+ const d = unwrap(res) || {};+ return {+ id: d.id ?? null,+ label: d.label ?? null,+ parent: d.parent ?? null,+ ownerWallet: d.owner_wallet ?? null,+ urlRecord: d.url_record ?? null,+ signature: d.signature ?? null,+ fullName: d.full ?? null,+ showcaseUrl: d.showcase_url ?? null,+ explorer: d.explorer ?? null,+ createdAt: d.created_at ?? null,+ raw: res,+ };+}++function shapePayee(d) {+ const v = d || {};+ return {+ name: v.resolved ?? null,+ address: v.address ?? null,+ source: v.source ?? null,+ resolved: v.resolved ?? null,+ claim: v.claim ?? null,+ raw: d,+ };+}++function shapePay(d, mode) {+ const v = d || {};+ if (mode === 'send') {+ return {+ mode: 'send',+ recipient: shapePayee(v.recipient),+ payer: v.payer ?? null,+ amountUsdc: v.amount_usdc ?? null,+ signature: v.signature ?? null,+ raw: d,+ };+ }+ return {+ mode: 'prep',+ recipient: shapePayee(v.recipient),+ amountUsdc: v.amount_usdc ?? null,+ txBase64: v.tx_base64 ?? null,+ blockhash: v.blockhash ?? null,+ lastValidBlockHeight: v.last_valid_block_height ?? null,+ mint: v.mint ?? null,+ raw: d,+ };+}++function normalizeEnum(value, allowed, label) {+ if (value === undefined || value === null) return undefined;+ if (!allowed.includes(value)) {+ throw new ThreeWsError(`Invalid ${label} "${value}". Expected one of: ${allowed.join(', ')}.`, { code: 'invalid_input' });+ }+ return value;+}++function prune(obj) {+ const out = {};+ for (const [k, v] of Object.entries(obj)) {+ if (v === undefined || v === null) continue;+ out[k] = v;+ }+ return out;+}diff --git a/packages/names/test/names.test.js b/packages/names/test/names.test.jsnew file mode 100644index 000000000..a913978ee--- /dev/null+++ b/packages/names/test/names.test.js@@ -0,0 +1,248 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createNames, ThreeWsError, PaymentRequiredError } from '../src/index.js';++// A scripted fetch double: each call shifts the next queued response and records+// the request. No network, no real endpoints — we assert on request shaping and+// response parsing, which is all the SDK is responsible for.+function stubFetch(responses) {+ const calls = [];+ const queue = [...responses];+ const fetch = async (url, init) => {+ calls.push({ url: new URL(url), init });+ const next = queue.shift();+ if (!next) throw new Error('stubFetch: no more queued responses');+ const { status = 200, body = {}, headers = {} } = next;+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: { get: (k) => headers[k.toLowerCase()] ?? null },+ text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),+ };+ };+ return { fetch, calls };+}++const SYNTH_OWNER = 'THREEsynthetic1111111111111111111111111111';+const SYNTH_PAYER = 'THREEsynthpayer11111111111111111111111111111';++test('resolve() routes a .sol name to /api/sns and camelCases the envelope', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { name: 'bonfida.sol', address: SYNTH_OWNER, network: 'solana', resolved: true, all_domains: ['bonfida.sol', 'naming.sol'], favorite_domain: 'bonfida.sol' } } },+ ]);+ const client = createNames({ fetch, baseUrl: 'https://three.ws' });+ const res = await client.resolve('bonfida.sol');++ assert.equal(calls[0].url.pathname, '/api/sns');+ assert.equal(calls[0].url.searchParams.get('name'), 'bonfida.sol');+ assert.equal(calls[0].init.method, 'GET');+ assert.equal(res.address, SYNTH_OWNER);+ assert.equal(res.network, 'solana');+ assert.equal(res.resolved, true);+ assert.deepEqual(res.allDomains, ['bonfida.sol', 'naming.sol']);+ assert.equal(res.favoriteDomain, 'bonfida.sol');+ assert.ok(res.raw, 'keeps a raw escape hatch');+});++test('resolve() routes a .eth name to the ENS endpoint', async () => {+ const { fetch, calls } = stubFetch([+ { body: { name: 'vitalik.eth', address: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', agents: [{ id: 'agt_1' }] } },+ ]);+ const client = createNames({ fetch });+ const res = await client.resolve('vitalik.eth');++ assert.equal(calls[0].url.pathname, '/api/agents/ens/vitalik.eth');+ assert.equal(res.network, 'ethereum');+ assert.equal(res.resolved, true);+ assert.equal(res.address, '0xd8da6bf26964af9d7eed9e03e53415d37aa96045');+ assert.equal(res.agents.length, 1);+});++test('resolve() treats a .sol miss (resolved:false) as data, not an error', async () => {+ const { fetch } = stubFetch([+ { body: { data: { name: 'nope.sol', address: null, network: 'solana', resolved: false } } },+ ]);+ const client = createNames({ fetch });+ const res = await client.resolve('nope');+ assert.equal(res.resolved, false);+ assert.equal(res.address, null);+});++test('resolve() rejects an empty / malformed name before any network call', async () => {+ const { fetch, calls } = stubFetch([]);+ const client = createNames({ fetch });+ await assert.rejects(() => client.resolve(''), /needs a non-empty name/);+ await assert.rejects(() => client.resolve('not a name!'), /Invalid name/);+ assert.equal(calls.length, 0);+});++test('reverseLookup() queries by address and validates base58 first', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { name: 'bonfida.sol', address: SYNTH_OWNER, network: 'solana', resolved: true } } },+ ]);+ const client = createNames({ fetch });+ const res = await client.reverseLookup(SYNTH_OWNER);+ assert.equal(calls[0].url.searchParams.get('address'), SYNTH_OWNER);+ assert.equal(res.name, 'bonfida.sol');++ await assert.rejects(() => client.reverseLookup('xyz'), /base58 Solana address/);+});++test('checkSubdomain() reads availability and maps full_name → fullName', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { label: 'alice', parent: 'threews.sol', full_name: 'alice.threews.sol', available: true, owner: null } } },+ ]);+ const client = createNames({ fetch });+ const res = await client.checkSubdomain('alice');+ assert.equal(calls[0].url.pathname, '/api/sns-subdomain');+ assert.equal(calls[0].url.searchParams.get('label'), 'alice');+ assert.equal(res.available, true);+ assert.equal(res.fullName, 'alice.threews.sol');+});++test('mintSubdomain() POSTs agent_id + bearer token and shapes the result', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { ok: true, agent_id: 'agt_7', full_name: 'alice.threews.sol', parent: 'threews.sol', owner: SYNTH_OWNER, signature: 'sigSynthetic', explorer: 'https://solscan.io/tx/sigSynthetic', url_record: 'https://three.ws/a/agt_7', agent_url: 'https://three.ws/a/agt_7' } } },+ ]);+ const client = createNames({ fetch });+ const res = await client.mintSubdomain({ agentId: 'agt_7', label: 'alice', token: 'tkn_123' });++ assert.equal(calls[0].url.pathname, '/api/sns-subdomain');+ assert.equal(calls[0].init.method, 'POST');+ assert.equal(calls[0].init.headers.authorization, 'Bearer tkn_123');+ const sent = JSON.parse(calls[0].init.body);+ assert.equal(sent.agent_id, 'agt_7');+ assert.equal(sent.label, 'alice');+ assert.equal(res.ok, true);+ assert.equal(res.fullName, 'alice.threews.sol');+ assert.equal(res.agentId, 'agt_7');+});++test('mintSubdomain() rejects a missing agentId and a bad space before network', async () => {+ const { fetch, calls } = stubFetch([]);+ const client = createNames({ fetch });+ await assert.rejects(() => client.mintSubdomain({}), /needs an `agentId`/);+ await assert.rejects(() => client.mintSubdomain({ agentId: 'a', space: 500 }), /space must be/);+ await assert.rejects(() => client.mintSubdomain({ agentId: 'a', ownerAddress: 'bad' }), /base58/);+ assert.equal(calls.length, 0);+});++test('mintSubdomain() surfaces a 503 config_missing as a typed ThreeWsError', async () => {+ const { fetch } = stubFetch([{ status: 503, body: { error: 'config_missing', message: 'platform owner key not configured' } }]);+ const client = createNames({ fetch });+ await assert.rejects(() => client.mintSubdomain({ agentId: 'agt_7', token: 't' }), (e) => {+ assert.ok(e instanceof ThreeWsError);+ assert.equal(e.code, 'config_missing');+ assert.equal(e.status, 503);+ return true;+ });+});++test('claimSubdomain() POSTs to /api/threews/subdomain with the username label', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { id: 'sub_1', label: 'nick', parent: 'threews', owner_wallet: SYNTH_OWNER, url_record: 'https://three.ws/u/nick', signature: 'sigSynth', full: 'nick.threews.sol', showcase_url: 'https://three.ws/u/nick', created_at: '2026-01-01' } } },+ ]);+ const client = createNames({ fetch, apiKey: 'client_tkn' });+ const res = await client.claimSubdomain({ label: 'nick' });+ assert.equal(calls[0].url.pathname, '/api/threews/subdomain');+ assert.equal(calls[0].init.headers.authorization, 'Bearer client_tkn');+ assert.equal(res.fullName, 'nick.threews.sol');+ assert.equal(res.label, 'nick');+});++test('releaseSubdomain() DELETEs with the label query param', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { released: { id: 'sub_1', label: 'nick', parent: 'threews' }, note: 'on-chain ownership unchanged' } } },+ ]);+ const client = createNames({ fetch, token: 't' });+ const res = await client.releaseSubdomain('nick');+ assert.equal(calls[0].init.method, 'DELETE');+ assert.equal(calls[0].url.searchParams.get('label'), 'nick');+ assert.equal(res.released.label, 'nick');+});++test('resolvePayee() resolves-only via GET and shapes the payee', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { address: SYNTH_OWNER, source: 'sns', resolved: 'alice.threews.sol', claim: { user_id: 'u1', username: 'alice', display_name: 'Alice' } } } },+ ]);+ const client = createNames({ fetch });+ const res = await client.resolvePayee('alice.threews.sol');+ assert.equal(calls[0].url.pathname, '/api/x402/pay-by-name');+ assert.equal(calls[0].url.searchParams.get('name'), 'alice.threews.sol');+ assert.equal(res.address, SYNTH_OWNER);+ assert.equal(res.source, 'sns');+ assert.equal(res.name, 'alice.threews.sol');+ assert.equal(res.claim.username, 'alice');+});++test('payByName() prep builds an unsigned tx and sends payer_wallet', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { recipient: { address: SYNTH_OWNER, source: 'sns', resolved: 'alice.threews.sol' }, amount_usdc: 5, tx_base64: 'AQID', blockhash: 'bh', last_valid_block_height: 123, mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' } } },+ ]);+ const client = createNames({ fetch });+ const res = await client.payByName('alice.threews.sol', '5', { payerWallet: SYNTH_PAYER });++ assert.equal(calls[0].init.method, 'POST');+ const sent = JSON.parse(calls[0].init.body);+ assert.equal(sent.mode, 'prep');+ assert.equal(sent.name, 'alice.threews.sol');+ assert.equal(sent.amount_usdc, '5');+ assert.equal(sent.payer_wallet, SYNTH_PAYER);+ assert.equal(res.mode, 'prep');+ assert.equal(res.txBase64, 'AQID');+ assert.equal(res.lastValidBlockHeight, 123);+ assert.equal(res.recipient.address, SYNTH_OWNER);+});++test('payByName() send forwards agent_id + expected_address and maps the signature', async () => {+ const { fetch, calls } = stubFetch([+ { body: { data: { recipient: { address: SYNTH_OWNER, source: 'sns', resolved: 'alice.threews.sol' }, payer: SYNTH_PAYER, amount_usdc: 5, signature: 'sigSynthetic', mode: 'send' } } },+ ]);+ const client = createNames({ fetch });+ const res = await client.payByName('alice.threews.sol', 5, {+ mode: 'send', agentId: 'agt_7', expectedAddress: SYNTH_OWNER, token: 'tkn',+ });+ const sent = JSON.parse(calls[0].init.body);+ assert.equal(sent.mode, 'send');+ assert.equal(sent.agent_id, 'agt_7');+ assert.equal(sent.expected_address, SYNTH_OWNER);+ assert.equal(calls[0].init.headers.authorization, 'Bearer tkn');+ assert.equal(res.mode, 'send');+ assert.equal(res.signature, 'sigSynthetic');+ assert.equal(res.payer, SYNTH_PAYER);+});++test('payByName() validation runs before any network call', async () => {+ const { fetch, calls } = stubFetch([]);+ const client = createNames({ fetch });+ await assert.rejects(() => client.payByName('alice.sol', '0'), /amountUsdc must be/);+ await assert.rejects(() => client.payByName('alice.sol', '5'), /needs a base58 `payerWallet`/);+ await assert.rejects(() => client.payByName('alice.sol', '5', { mode: 'send' }), /needs an `agentId`/);+ await assert.rejects(() => client.payByName('alice.sol', '5', { mode: 'wire' }), /Invalid mode/);+ assert.equal(calls.length, 0);+});++test('payByName() send maps a 409 recipient_changed to a typed ThreeWsError', async () => {+ const { fetch } = stubFetch([{ status: 409, body: { error: 'recipient_changed', message: 're-preview before sending' } }]);+ const client = createNames({ fetch });+ await assert.rejects(+ () => client.payByName('alice.sol', '5', { mode: 'send', agentId: 'agt_7', token: 't' }),+ (e) => {+ assert.ok(e instanceof ThreeWsError);+ assert.equal(e.code, 'recipient_changed');+ assert.equal(e.status, 409);+ return true;+ },+ );+});++test('a 402 on payByName surfaces as PaymentRequiredError carrying accepts', async () => {+ const accepts = [{ scheme: 'exact', asset: 'USDC', network: 'solana', maxAmountRequired: '5000000' }];+ const { fetch } = stubFetch([{ status: 402, body: { error: 'payment_required', message: 'pay', accepts } }]);+ const client = createNames({ fetch });+ await assert.rejects(() => client.payByName('alice.sol', '5', { payerWallet: SYNTH_PAYER }), (e) => {+ assert.ok(e instanceof PaymentRequiredError);+ assert.deepEqual(e.accepts, accepts);+ return true;+ });+});diff --git a/packages/skill-license/LICENSE b/packages/skill-license/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/skill-license/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/skill-license/src/http.js b/packages/skill-license/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/skill-license/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/skill-license/src/index.js b/packages/skill-license/src/index.jsnew file mode 100644index 000000000..d2ead7b78--- /dev/null+++ b/packages/skill-license/src/index.js@@ -0,0 +1,225 @@+// @three-ws/skill-license — verify, read, and mint on-chain agent skill+// licenses. Thin client over the public, auth-free GET /api/skills/license-onchain+// read path and the authenticated POST /api/skills/mint write path — the+// platform endpoints do the Solana work (PDA derivation, RPC reads, minting),+// so this SDK stays zero-dependency and runs anywhere fetch does. See README.md.++import { createHttp, ThreeWsError } from './http.js';++export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';++const NETWORKS = ['mainnet', 'devnet'];++/** The `skill_license` Anchor program id — identical on every cluster. */+export const PROGRAM_ID = 'EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8';++/**+ * Create a skill-license client bound to a base URL, fetch, and optional auth.+ * For most callers the default `verifyLicense()` / `getLicense()` /+ * `mintLicense()` exports are enough; use this to reuse configuration (a+ * payment-aware fetch, a custom origin, a bearer apiKey) across many calls.+ *+ * @param {import('./index').SkillLicenseClientOptions} [options]+ */+export function createSkillLicense(options = {}) {+ const request = createHttp(options);++ /**+ * Read the full on-chain license record for a holder+agent+skill triple.+ * Returns `null` when no license exists at the derived PDA (never purchased),+ * else a shaped `LicenseRecord`. Wraps GET /api/skills/license-onchain — a+ * public, auth-free read of chain state.+ */+ async function getLicense(input, opts = {}) {+ const query = licenseQuery(input, opts);+ const res = await request('/api/skills/license-onchain', { query, signal: opts.signal });+ const data = res?.data;+ if (!data) {+ throw new ThreeWsError('Unexpected empty response from /api/skills/license-onchain.', { code: 'bad_response' });+ }+ // No PDA on-chain ⇒ never purchased. Surface as null per the README contract.+ if (!data.exists) return null;+ return shapeLicense(data);+ }++ /**+ * The headline check: does `holder` own an active (non-revoked) license for+ * `skill` on `agent`? Resolves to a plain boolean. A missing license, an+ * undeployed program, or a revoked license all read as `false` — never a throw+ * for the "not owned" case. Only a transport/RPC failure rejects.+ */+ async function verifyLicense(input, opts = {}) {+ const query = licenseQuery(input, opts);+ const res = await request('/api/skills/license-onchain', { query, signal: opts.signal });+ return Boolean(res?.data?.owned);+ }++ /**+ * Server-side. Mint the on-chain license to `buyer` after their purchase is+ * confirmed. Wraps POST /api/skills/mint, which verifies the payment reached+ * the agent's payout wallet before minting — a caller can never mint a free+ * license. Idempotent: a second call returns the existing mint with+ * `alreadyMinted: true`.+ *+ * @param {import('./index').MintLicenseInput} input+ */+ async function mintLicense(input = {}, opts = {}) {+ const agentId = req(input.agentId, 'agentId');+ const skill = req(input.skill, 'skill');+ const buyer = req(input.buyer, 'buyer');+ if (skill.length > 100) {+ throw new ThreeWsError('skill must be ≤100 characters.', { code: 'invalid_input' });+ }++ // Per-call apiKey/headers override the client defaults for this request only.+ const headers = { ...(input.headers || {}) };+ if (input.apiKey) headers.authorization = `Bearer ${input.apiKey}`;++ const body = prune({+ agent_id: agentId,+ skill_name: skill,+ user_wallet: buyer,+ transaction_signature: input.txSignature,+ });++ const res = await request('/api/skills/mint', {+ method: 'POST',+ body,+ headers,+ signal: opts.signal,+ });+ return shapeMint(res?.data ?? res);+ }++ return { verifyLicense, getLicense, mintLicense };+}++// Module-level default client for the zero-config path: `import { verifyLicense }`.+let shared = null;+function defaultClient() {+ return (shared ||= createSkillLicense());+}++/** Does `holder` own an active license for `skill` on `agent`? → boolean. */+export function verifyLicense(input, opts) {+ return defaultClient().verifyLicense(input, opts);+}+/** Read the full on-chain license record (or `null` if none exists). */+export function getLicense(input, opts) {+ return defaultClient().getLicense(input, opts);+}+/** Server-side: mint the on-chain license to a buyer after a confirmed purchase. */+export function mintLicense(input, opts) {+ return defaultClient().mintLicense(input, opts);+}++/**+ * sha256(skillName) as a 32-byte hex string — the fixed-length third PDA seed.+ * Matches the Rust `skill_seed()` (Solana `hash::hash` is sha256), so client and+ * program derive identical addresses. Pure and zero-dep via Web Crypto; async+ * because `crypto.subtle.digest` is. The platform endpoint derives full PDAs+ * server-side and returns them on every `getLicense` record, so this is the one+ * derivation that's trivially reproducible client-side without a curve library.+ */+export async function skillSeed(skillName) {+ if (typeof skillName !== 'string' || !skillName) {+ throw new ThreeWsError('skillSeed() needs a non-empty skill name string.', { code: 'invalid_input' });+ }+ const subtle = globalThis.crypto?.subtle;+ if (!subtle) {+ throw new ThreeWsError('Web Crypto (crypto.subtle) is unavailable — run on Node 18+ or a modern browser.', { code: 'no_crypto' });+ }+ const bytes = new TextEncoder().encode(skillName);+ const digest = await subtle.digest('SHA-256', bytes);+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');+}++// --- internal helpers ------------------------------------------------------++// Build the license-onchain query: holder+skill plus agent_mint OR agent_id.+function licenseQuery(input, opts) {+ const i = input && typeof input === 'object' ? input : {};+ const holder = req(i.holder, 'holder');+ const skill = req(i.skill, 'skill');+ if (skill.length > 100) {+ throw new ThreeWsError('skill must be ≤100 characters.', { code: 'invalid_input' });+ }+ if (!i.agent && !i.agentId) {+ throw new ThreeWsError('Pass either `agent` (skill-collection mint) or `agentId` (three.ws uuid).', { code: 'invalid_input' });+ }+ const network = normalizeEnum(i.network ?? opts.network, NETWORKS, 'network');+ return prune({+ wallet: holder,+ skill,+ agent_mint: i.agent,+ agent_id: i.agent ? undefined : i.agentId,+ network,+ });+}++// Shape the verify endpoint's `data` envelope → camelCase LicenseRecord.+function shapeLicense(data) {+ const record = data.record || {};+ return {+ owned: Boolean(data.owned),+ exists: Boolean(data.exists),+ revoked: Boolean(data.revoked),+ deployed: Boolean(data.deployed),+ authority: record.authority ?? null,+ agentMint: record.agentMint ?? data.agent_mint ?? null,+ nftMint: data.nft_mint ?? record.nftMint ?? null,+ ownerTokenAccount: data.owner_token_account ?? null,+ skillName: record.skillName ?? data.skill ?? null,+ skillHash: record.skillHash ?? null,+ purchaseDate: record.purchaseDate ?? null,+ revokedAt: record.revokedAt ?? 0,+ license: data.license ?? null,+ programId: data.program_id ?? PROGRAM_ID,+ network: data.network ?? null,+ explorer: data.explorer ?? null,+ raw: data,+ };+}++// Shape the mint endpoint's `data` envelope → camelCase MintResult.+function shapeMint(data) {+ if (!data || typeof data !== 'object') {+ throw new ThreeWsError('Unexpected empty response from /api/skills/mint.', { code: 'bad_response' });+ }+ return {+ nftMint: data.nftMint ?? null,+ signature: data.signature ?? null,+ collection: data.collection ?? null,+ network: data.network ?? null,+ explorer: data.explorer ?? null,+ skill: data.skill ?? null,+ agentId: data.agent_id ?? null,+ purchaseId: data.purchase_id ?? null,+ alreadyMinted: data.already_minted === true,+ raw: data,+ };+}++function req(value, label) {+ if (typeof value !== 'string' || !value.trim()) {+ throw new ThreeWsError(`${label} is required.`, { code: 'invalid_input' });+ }+ return value.trim();+}++function normalizeEnum(value, allowed, label) {+ if (value === undefined || value === null) return undefined;+ if (!allowed.includes(value)) {+ throw new ThreeWsError(`Invalid ${label} "${value}". Expected one of: ${allowed.join(', ')}.`, { code: 'invalid_input' });+ }+ return value;+}++function prune(obj) {+ const out = {};+ for (const [k, v] of Object.entries(obj)) {+ if (v === undefined || v === null) continue;+ out[k] = v;+ }+ return out;+}diff --git a/packages/vanity/LICENSE b/packages/vanity/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/vanity/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/vanity/package.json b/packages/vanity/package.jsonindex 1ce07ef9b..da386b7d2 100644--- a/packages/vanity/package.json+++ b/packages/vanity/package.json@@ -2,6 +2,26 @@"name": "@three-ws/vanity","version": "0.1.0","description": "Mine Solana vanity addresses (custom prefix/suffix) fast — WASM-accelerated, in the browser or Node. Ergonomic grind() API over a real Rust/ed25519 grinder, with progress, difficulty/ETA, and a paid x402 fallback.",+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "types": "./src/index.d.ts",+ "exports": {+ ".": {+ "types": "./src/index.d.ts",+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test test/*.test.js"+ },"keywords": ["solana","vanity",@@ -16,15 +36,22 @@"x402","three.ws"],+ "author": "nirholas <[email protected]>","license": "MIT",- "private": true,- "type": "module",- "homepage": "https://three.ws",+ "homepage": "https://three.ws/vanity","repository": {"type": "git",- "url": "https://github.com/nirholas/three.ws"+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/vanity"},"bugs": {"url": "https://github.com/nirholas/three.ws/issues"+ },+ "engines": {+ "node": ">=18"+ },+ "dependencies": {},+ "publishConfig": {+ "access": "public"}}diff --git a/packages/vanity/src/http.js b/packages/vanity/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/vanity/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/vanity/src/index.d.ts b/packages/vanity/src/index.d.tsnew file mode 100644index 000000000..dfd59333f--- /dev/null+++ b/packages/vanity/src/index.d.ts@@ -0,0 +1,125 @@+// Type definitions for @three-ws/vanity++export declare class ThreeWsError extends Error {+ name: string;+ code: string;+ status: number | null;+ detail?: string;+ retryAfter?: number;+ body: unknown;+}++export declare class PaymentRequiredError extends ThreeWsError {+ accepts: unknown | null;+}++export declare const DEFAULT_BASE_URL: string;++/** Bitcoin/Solana Base58 alphabet (excludes the confusable 0 O I l). */+export declare const BASE58_ALPHABET: string;++/** Hard ceiling per prefix/suffix pattern. */+export declare const MAX_PATTERN_LENGTH: number;++export interface Pattern {+ /** Base58 prefix the address must start with. */+ prefix?: string;+ /** Base58 suffix the address must end with. */+ suffix?: string;+ /** Case-insensitive match (folds upper+lower Base58 chars). */+ ignoreCase?: boolean;+}++export interface GrindProgress {+ /** Running total of keypairs tried. */+ attempts: number;+ /** Keypairs/sec. */+ rate: number;+ /** Human estimate of remaining time, e.g. "~12 seconds", "unknown". */+ eta: string;+}++export interface GrindOptions extends Pattern {+ /** Alias for `ignoreCase`. */+ caseInsensitive?: boolean;+ /** Cancel the grind; rejects with AbortError. */+ signal?: AbortSignal;+ /** Called ~every 250ms with running attempts / rate / ETA. */+ onProgress?: (progress: GrindProgress) => void;+}++export interface GrindResult {+ /** Base58 address matching your pattern. */+ publicKey: string;+ /** 64-byte Ed25519 secret key — `Keypair.fromSecretKey()`-compatible. */+ secretKey: Uint8Array;+ /** Total keypairs tried. */+ attempts: number;+ /** Wall-clock duration in milliseconds. */+ durationMs: number;+ /** Workers used (always 1 on the local path). */+ workers: number;+}++/** Grind for a vanity Solana address entirely on the local machine. */+export declare function grind(opts?: GrindOptions): Promise<GrindResult>;++/** Mean expected attempts (`58^n`, adjusted for case-insensitivity). */+export declare function expectedAttempts(pattern?: Pattern): number;++/** Validate a single prefix or suffix against Base58 + the length ceiling. */+export declare function validatePattern(pattern: string): { valid: boolean; errors: string[] };++/** Encode a byte array as a Base58 (Solana address) string. */+export declare function base58Encode(bytes: Uint8Array | number[]): string;++export type VanityFormat = 'keypair' | 'mnemonic';++export interface VanityClientOptions {+ baseUrl?: string;+ fetch?: typeof fetch;+ apiKey?: string;+ headers?: Record<string, string>;+}++export interface GrindViaApiOptions extends Pattern {+ /** Alias for `ignoreCase`. */+ caseInsensitive?: boolean;+ /** `keypair` (default) or an importable BIP-39 `mnemonic`. */+ format?: VanityFormat;+ /** Mnemonic only: 128 → 12 words, 256 → 24 words. */+ strength?: 128 | 256;+ /** Optional X25519 public key — the secret is ECIES-sealed to you. */+ sealTo?: string;+ /** An x402-wrapped fetch is supplied via the client, not here. */+ headers?: Record<string, string>;+ signal?: AbortSignal;+}++export interface ApiResult {+ address: string | null;+ prefix: string | null;+ suffix: string | null;+ ignoreCase: boolean;+ format: string | null;+ secretKeyBase58: string | null;+ secretKey: Uint8Array | null;+ mnemonic: string | null;+ wordCount: number | null;+ derivationPath: string | null;+ sealed: boolean;+ sealedSecret: unknown | null;+ attempts: number | null;+ durationMs: number | null;+ expectedAttempts: number | null;+ network: string | null;+ explorerUrl: string | null;+ raw: unknown;+}++export interface VanityClient {+ grindViaApi(params: GrindViaApiOptions): Promise<ApiResult>;+}++export declare function createVanity(options?: VanityClientOptions): VanityClient;+export declare function grindViaApi(params: GrindViaApiOptions): Promise<ApiResult>;diff --git a/packages/vanity/src/index.js b/packages/vanity/src/index.jsnew file mode 100644index 000000000..4dc522326--- /dev/null+++ b/packages/vanity/src/index.js@@ -0,0 +1,450 @@+// @three-ws/vanity — mine Solana vanity addresses (custom prefix/suffix) LOCALLY.+//+// The headline path, `grind()`, never touches the network: it generates Ed25519+// keypairs on your machine, Base58-encodes each public key, and loops until the+// address matches your pattern. Keys are produced with the platform crypto+// primitive — Node's `crypto.generateKeyPairSync('ed25519')`, the browser's+// `crypto.subtle.generateKey('Ed25519')` — and never leave the process. There is+// no telemetry and no API call on this path; that is the entire security posture.+//+// A paid lane, `grindViaApi()`, wraps the hosted x402 endpoint (GET+// /api/x402/vanity) for environments that can't grind locally — short patterns+// only, settled in USDC. See README.md for the full reference.+//+// DEVIATION FROM README (one line): the README describes a Rust→WASM grinder+// fanned across Web Workers; this build ships a zero-dependency pure-platform+// implementation instead (no WASM binary, no Worker pool) so the package stays+// dependency-free and importable everywhere — the `grind()` surface, options,+// validation, difficulty math, and result shape are identical.++import { createHttp, ThreeWsError } from './http.js';++export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';++// ---------------------------------------------------------------------------+// Base58 (Bitcoin/Solana alphabet — drops the confusable 0 O I l).+// ---------------------------------------------------------------------------++export const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+const BASE58_CHARS = new Set(BASE58_ALPHABET);++// Per-character guidance for the four confusable symbols excluded from Base58.+const CONFUSED = {+ '0': '0 (zero) — use 1-9',+ O: 'O (uppercase o) — use other uppercase letters',+ I: 'I (uppercase i) — use other uppercase letters',+ l: 'l (lowercase L) — use other lowercase letters',+};++/** Hard ceiling per pattern — past this, grinding is unrealistic on one machine. */+export const MAX_PATTERN_LENGTH = 6;++/**+ * Encode a byte array as a Base58 string (Solana address form). Pure, no deps:+ * big-integer base conversion via repeated division over the byte array, with a+ * leading-zero pass so 0x00 bytes render as the alphabet's first character.+ * @param {Uint8Array | number[]} bytes+ * @returns {string}+ */+export function base58Encode(bytes) {+ const input = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes);+ if (input.length === 0) return '';++ // Count leading zero bytes — each maps to one leading '1'.+ let zeros = 0;+ while (zeros < input.length && input[zeros] === 0) zeros++;++ // Convert the remaining bytes (base 256) into base 58 digits, big-endian.+ const digits = [0];+ for (let i = zeros; i < input.length; i++) {+ let carry = input[i];+ for (let j = 0; j < digits.length; j++) {+ carry += digits[j] << 8;+ digits[j] = carry % 58;+ carry = (carry / 58) | 0;+ }+ while (carry > 0) {+ digits.push(carry % 58);+ carry = (carry / 58) | 0;+ }+ }++ let out = '1'.repeat(zeros);+ for (let i = digits.length - 1; i >= 0; i--) out += BASE58_ALPHABET[digits[i]];+ return out;+}++// ---------------------------------------------------------------------------+// Validation + difficulty (ported from src/solana/vanity/validation.js).+// ---------------------------------------------------------------------------++/**+ * Validate a single vanity pattern (a prefix or a suffix) against the Base58+ * alphabet and the length ceiling. Returns specific, user-facing error strings.+ * @param {string} pattern+ * @returns {{ valid: boolean, errors: string[] }}+ */+export function validatePattern(pattern) {+ const errors = [];+ if (typeof pattern !== 'string' || pattern.length === 0) {+ return { valid: false, errors: ['pattern is empty'] };+ }+ if (pattern !== pattern.trim()) {+ errors.push('pattern has leading or trailing whitespace');+ }+ if (pattern.length > MAX_PATTERN_LENGTH) {+ errors.push(`length ${pattern.length} exceeds maximum of ${MAX_PATTERN_LENGTH}`);+ }+ for (let i = 0; i < pattern.length; i++) {+ const c = pattern[i];+ if (!BASE58_CHARS.has(c)) {+ const hint = CONFUSED[c];+ errors.push(`invalid character '${c}' at position ${i + 1}${hint ? ` — ${hint}` : ''}`);+ }+ }+ return { valid: errors.length === 0, errors };+}++// How many of the 58 Base58 characters satisfy a single requested character.+// Case-sensitive: exactly one. Case-insensitive: two when the other case is also+// a valid Base58 symbol (the alphabet drops 0 O I l, so o/i/L have only one case).+function matchesPerChar(ch, ignoreCase) {+ if (!ignoreCase) return 1;+ const lower = ch.toLowerCase();+ const upper = ch.toUpperCase();+ if (lower !== upper && BASE58_CHARS.has(lower) && BASE58_CHARS.has(upper)) return 2;+ return 1;+}++/**+ * Expected attempts to grind an address starting with `prefix` and ending with+ * `suffix` — the mean of the geometric distribution, `58^n` adjusted for+ * case-insensitivity per character.+ * @param {{ prefix?: string, suffix?: string, ignoreCase?: boolean }} [pattern]+ * @returns {number}+ */+export function expectedAttempts({ prefix = '', suffix = '', ignoreCase = false } = {}) {+ let attempts = 1;+ for (const ch of String(prefix || '') + String(suffix || '')) {+ attempts *= 58 / matchesPerChar(ch, ignoreCase);+ }+ return attempts;+}++/** Format remaining-time seconds as a human string for the onProgress ETA. */+function formatTimeEstimate(remainingAttempts, ratePerSecond) {+ if (!ratePerSecond || ratePerSecond <= 0) return 'unknown';+ const seconds = remainingAttempts / ratePerSecond;+ if (seconds < 1) return 'less than a second';+ if (seconds < 60) return `~${Math.round(seconds)} seconds`;+ if (seconds < 3600) return `~${Math.round(seconds / 60)} minutes`;+ if (seconds < 86400) return `~${Math.round(seconds / 3600)} hours`;+ if (seconds < 31536000) return `~${Math.round(seconds / 86400)} days`;+ return `~${Math.round(seconds / 31536000)} years`;+}++// ---------------------------------------------------------------------------+// Keypair generation — platform crypto, zero dependencies, keys stay local.+// ---------------------------------------------------------------------------++// A keypair generator returns { publicKey: string (Base58), secretKey: Uint8Array(64) }.+// The 64-byte secret is Solana's standard layout: [32-byte seed][32-byte pubkey],+// directly compatible with `Keypair.fromSecretKey()`.++let cachedGenerator = null;++// Resolve the keygen backend once. Node path uses `generateKeyPairSync`; the+// browser path uses WebCrypto's async Ed25519. We probe lazily so the module+// imports cleanly in either environment.+async function resolveGenerator() {+ if (cachedGenerator) return cachedGenerator;++ // Node: synchronous, fastest. JWK export hands us the raw 32-byte seed (`d`)+ // and raw 32-byte public key (`x`) with no extra parsing or dependencies.+ const nodeCrypto = await tryImportNodeCrypto();+ if (nodeCrypto && typeof nodeCrypto.generateKeyPairSync === 'function') {+ cachedGenerator = () => {+ const { publicKey, privateKey } = nodeCrypto.generateKeyPairSync('ed25519');+ const pub = base64UrlToBytes(publicKey.export({ format: 'jwk' }).x);+ const seed = base64UrlToBytes(privateKey.export({ format: 'jwk' }).d);+ return { publicKey: base58Encode(pub), secretKey: joinKeypair(seed, pub) };+ };+ return cachedGenerator;+ }++ // Browser / Deno / workers: WebCrypto. Ed25519 support is required.+ const subtle = globalThis.crypto?.subtle;+ if (subtle && typeof subtle.generateKey === 'function') {+ const probe = await subtle+ .generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])+ .catch(() => null);+ if (probe) {+ cachedGenerator = async () => {+ const pair = await subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);+ const pubJwk = await subtle.exportKey('jwk', pair.publicKey);+ const privJwk = await subtle.exportKey('jwk', pair.privateKey);+ const pub = base64UrlToBytes(pubJwk.x);+ const seed = base64UrlToBytes(privJwk.d);+ return { publicKey: base58Encode(pub), secretKey: joinKeypair(seed, pub) };+ };+ return cachedGenerator;+ }+ }++ throw new ThreeWsError(+ 'No Ed25519 keypair generator available in this environment. Run in Node 18+ ' ++ '(crypto.generateKeyPairSync) or a browser/runtime with WebCrypto Ed25519 ' ++ '(crypto.subtle.generateKey).',+ { code: 'no_ed25519' },+ );+}++async function tryImportNodeCrypto() {+ // Only Node exposes process.versions.node; skip the dynamic import in browsers+ // so bundlers don't try to resolve 'node:crypto'.+ if (typeof process === 'undefined' || !process.versions?.node) return null;+ try {+ return await import('node:crypto');+ } catch {+ return null;+ }+}++// Decode a Base64url string (JWK `x`/`d`) to a 32-byte Uint8Array without deps.+function base64UrlToBytes(b64url) {+ const b64 = b64url.replace(/-/g, '+').replace(/_/g, '/');+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'));+ const bin = atob(b64.padEnd(Math.ceil(b64.length / 4) * 4, '='));+ const out = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);+ return out;+}++// Solana's 64-byte secret key layout: [32-byte seed || 32-byte public key].+function joinKeypair(seed, pub) {+ const out = new Uint8Array(64);+ out.set(seed.subarray(0, 32), 0);+ out.set(pub.subarray(0, 32), 32);+ return out;+}++// ---------------------------------------------------------------------------+// grind() — the local hot loop.+// ---------------------------------------------------------------------------++const PROGRESS_INTERVAL_MS = 250;+// Keypairs checked between abort/progress yields. Small enough to honour an+// abort promptly, large enough that the per-batch bookkeeping is negligible.+const YIELD_EVERY = 2_000;++function abortError() {+ if (typeof DOMException === 'function') return new DOMException('vanity grind aborted', 'AbortError');+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}++// Compile a matcher closure for the requested pattern. Case-insensitive folds+// both sides to lower-case before comparing.+function buildMatcher({ prefix, suffix, ignoreCase }) {+ const pre = ignoreCase ? prefix.toLowerCase() : prefix;+ const suf = ignoreCase ? suffix.toLowerCase() : suffix;+ return (address) => {+ const candidate = ignoreCase ? address.toLowerCase() : address;+ if (pre && !candidate.startsWith(pre)) return false;+ if (suf && !candidate.endsWith(suf)) return false;+ return true;+ };+}++/**+ * Grind for a vanity Solana address — entirely on the local machine.+ *+ * Resolves with a keypair whose Base58 public key starts with `prefix` and/or+ * ends with `suffix`. Keys are generated with platform crypto and never leave+ * the process. Rejects with `AbortError` if `signal` aborts, or a typed+ * `ThreeWsError` on invalid input / a runtime without Ed25519.+ *+ * @param {GrindOptions} [opts]+ * @returns {Promise<GrindResult>}+ */+export async function grind(opts = {}) {+ const prefix = typeof opts.prefix === 'string' ? opts.prefix : '';+ const suffix = typeof opts.suffix === 'string' ? opts.suffix : '';+ const ignoreCase = !!(opts.ignoreCase ?? opts.caseInsensitive);+ const { signal, onProgress } = opts;++ if (!prefix && !suffix) {+ throw new ThreeWsError('prefix or suffix is required', { code: 'invalid_input' });+ }+ if (prefix) {+ const v = validatePattern(prefix);+ if (!v.valid) throw new ThreeWsError(`invalid prefix: ${v.errors.join('; ')}`, { code: 'invalid_input' });+ }+ if (suffix) {+ const v = validatePattern(suffix);+ if (!v.valid) throw new ThreeWsError(`invalid suffix: ${v.errors.join('; ')}`, { code: 'invalid_input' });+ }++ if (signal?.aborted) throw abortError();++ const generate = await resolveGenerator();+ const matches = buildMatcher({ prefix, suffix, ignoreCase });+ const expected = expectedAttempts({ prefix, suffix, ignoreCase });+ const startedAt = now();++ let attempts = 0;+ let lastProgressAt = startedAt;++ // Yield control to the event loop between batches so an abort lands promptly+ // and onProgress can fire on a wall-clock cadence rather than per-attempt.+ while (true) {+ if (signal?.aborted) throw abortError();++ for (let i = 0; i < YIELD_EVERY; i++) {+ const { publicKey, secretKey } = await generate();+ attempts++;+ if (matches(publicKey)) {+ const durationMs = now() - startedAt;+ onProgress?.(buildProgress(attempts, durationMs, expected));+ return { publicKey, secretKey, attempts, durationMs, workers: 1 };+ }+ }++ const tickAt = now();+ if (onProgress && tickAt - lastProgressAt >= PROGRESS_INTERVAL_MS) {+ lastProgressAt = tickAt;+ onProgress(buildProgress(attempts, tickAt - startedAt, expected));+ }+ // Hand the loop back so abort/timers run; setTimeout(0) keeps Node and the+ // browser responsive without pinning the event loop.+ await yieldToLoop();+ }+}++function buildProgress(attempts, durationMs, expected) {+ const rate = durationMs > 0 ? (attempts / durationMs) * 1000 : 0;+ return {+ attempts,+ rate,+ eta: formatTimeEstimate(Math.max(0, expected - attempts), rate),+ };+}++function yieldToLoop() {+ return new Promise((resolve) => setTimeout(resolve, 0));+}++function now() {+ if (typeof performance !== 'undefined' && typeof performance.now === 'function') return performance.now();+ return Date.now();+}++// ---------------------------------------------------------------------------+// grindViaApi() — the paid x402 lane (GET /api/x402/vanity).+// ---------------------------------------------------------------------------++const API_FORMATS = ['keypair', 'mnemonic'];+const API_STRENGTHS = [128, 256];+// Server cap on the combined prefix+suffix length for the keypair format+// (mnemonic is capped at 2 by the server; both are enforced server-side too).+const API_MAX_COMBINED = 3;++/**+ * Create a Vanity API client bound to a base URL + fetch (+ optional auth).+ * Only the hosted paid lane is HTTP; local `grind()` needs no client. Pass a+ * payment-aware `fetch` (e.g. @three-ws/x402-fetch) to auto-settle the 402.+ * @param {VanityClientOptions} [options]+ * @returns {VanityClient}+ */+export function createVanity(options = {}) {+ const request = createHttp(options);++ async function grindViaApi(params = {}) {+ const prefix = typeof params.prefix === 'string' ? params.prefix.trim() : '';+ const suffix = typeof params.suffix === 'string' ? params.suffix.trim() : '';+ const ignoreCase = !!(params.ignoreCase ?? params.caseInsensitive);+ const format = params.format ?? 'keypair';++ if (!prefix && !suffix) {+ throw new ThreeWsError('prefix or suffix is required', { code: 'invalid_input' });+ }+ if (!API_FORMATS.includes(format)) {+ throw new ThreeWsError(`Invalid format "${format}". Expected one of: ${API_FORMATS.join(', ')}.`, { code: 'invalid_input' });+ }+ for (const [label, pattern] of [['prefix', prefix], ['suffix', suffix]]) {+ if (!pattern) continue;+ const v = validatePattern(pattern);+ if (!v.valid) throw new ThreeWsError(`invalid ${label}: ${v.errors.join('; ')}`, { code: 'invalid_input' });+ }+ if (params.strength != null && !API_STRENGTHS.includes(Number(params.strength))) {+ throw new ThreeWsError(`Invalid strength "${params.strength}". Expected 128 or 256.`, { code: 'invalid_input' });+ }+ const combined = prefix.length + suffix.length;+ if (combined > API_MAX_COMBINED) {+ throw new ThreeWsError(+ `combined pattern length ${combined} exceeds the hosted limit of ${API_MAX_COMBINED} — grind longer patterns locally with grind().`,+ { code: 'invalid_input' },+ );+ }++ const query = {+ prefix: prefix || undefined,+ suffix: suffix || undefined,+ ignoreCase: ignoreCase ? '1' : undefined,+ format: format === 'keypair' ? undefined : format,+ strength: params.strength != null ? String(params.strength) : undefined,+ sealTo: params.sealTo || undefined,+ };++ const res = await request('/api/x402/vanity', {+ query,+ headers: params.headers,+ signal: params.signal,+ });+ return shapeApiResult(res);+ }++ return { grindViaApi };+}++// Lazily-created shared client for the zero-config default `grindViaApi()`.+let sharedClient = null;+function defaultClient() {+ return (sharedClient ||= createVanity());+}++/**+ * Grind a short pattern over the hosted paid x402 endpoint instead of locally.+ * @param {GrindViaApiOptions} params+ * @returns {Promise<ApiResult>}+ */+export function grindViaApi(params) {+ return defaultClient().grindViaApi(params);+}++function shapeApiResult(res) {+ if (!res || typeof res !== 'object') {+ throw new ThreeWsError('Unexpected empty response from /api/x402/vanity.', { code: 'bad_response' });+ }+ return {+ address: res.address ?? null,+ prefix: res.prefix ?? null,+ suffix: res.suffix ?? null,+ ignoreCase: !!res.ignoreCase,+ format: res.format ?? null,+ secretKeyBase58: res.secretKeyBase58 ?? null,+ secretKey: Array.isArray(res.secretKey) ? Uint8Array.from(res.secretKey) : null,+ mnemonic: res.mnemonic ?? null,+ wordCount: res.wordCount ?? null,+ derivationPath: res.derivationPath ?? null,+ sealed: !!res.sealed,+ sealedSecret: res.sealedSecret ?? null,+ attempts: res.attempts ?? null,+ durationMs: res.durationMs ?? null,+ expectedAttempts: res.expectedAttempts ?? null,+ network: res.network ?? null,+ explorerUrl: res.explorerUrl ?? null,+ raw: res,+ };+}diff --git a/packages/voice/LICENSE b/packages/voice/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/voice/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/voice/src/http.js b/packages/voice/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/voice/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/packages/x402-mcp/package.json b/packages/x402-mcp/package.jsonnew file mode 100644index 000000000..c539f034f--- /dev/null+++ b/packages/x402-mcp/package.json@@ -0,0 +1,65 @@+{+ "name": "@three-ws/x402-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/x402-mcp",+ "description": "Give any AI agent a self-custodial x402 wallet. Search the live bazaar, inspect an endpoint's price without paying, and pay_and_call any x402 service in USDC from your own Solana key — real @x402 settlement, bounded by spend caps. No custodial wallet, no account.",+ "type": "module",+ "author": "nirholas <[email protected]>",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/x402-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "model-context-protocol",+ "three.ws",+ "x402",+ "solana",+ "usdc",+ "payments",+ "agent-payments",+ "bazaar",+ "ai-agent"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "x402-mcp": "src/index.js"+ },+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "engines": {+ "node": ">=20"+ },+ "scripts": {+ "start": "node src/index.js",+ "test": "node --test \"test/**/*.test.mjs\"",+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"+ },+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "@solana/kit": "^2.1.0",+ "@solana/spl-token": "^0.4.14",+ "@solana/web3.js": "^1.98.4",+ "@x402/core": "^0.6.0",+ "@x402/fetch": "^0.6.0",+ "@x402/svm": "^0.6.0",+ "bs58": "^6.0.0",+ "zod": "^3.23.8"+ }+}diff --git a/packages/x402-mcp/src/config.js b/packages/x402-mcp/src/config.jsnew file mode 100644index 000000000..748accd5f--- /dev/null+++ b/packages/x402-mcp/src/config.js@@ -0,0 +1,79 @@+// Centralized env for the x402 buyer MCP.+//+// This server is user-keyed: outgoing payments are signed by a Solana keypair+// the operator supplies (SOLANA_SECRET_KEY) or a per-call `secret` overrides.+// We never bake in a key. The read tools (x402_wallet with an explicit address,+// find_services, inspect_endpoint) work with no key at all — only pay_and_call+// (and x402_wallet defaulting to the signer) needs one.++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 (serves /api/bazaar/search for find_services).+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');++// Per-request timeout (ms). Paid calls settle on-chain, so the default is roomy.+export const HTTP_TIMEOUT_MS = (() => {+ const raw = env('THREE_WS_TIMEOUT_MS');+ if (raw === undefined) return 60000;+ 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;+})();++// Validate the Solana RPC endpoint at load. Payments are signed + broadcast over+// this URL, so a plaintext-http endpoint (outside localhost) is a MITM risk.+function validateRpcUrl(raw) {+ let u;+ try {+ u = new URL(raw);+ } catch {+ throw Object.assign(new Error(`SOLANA_RPC_URL is not a valid URL: "${raw}"`), { code: 'bad_rpc_url' });+ }+ if (u.protocol === 'https:') return raw;+ const isLocal = ['localhost', '127.0.0.1', '0.0.0.0', '::1'].includes(u.hostname);+ if (u.protocol === 'http:' && isLocal) return raw;+ throw Object.assign(+ new Error(+ `SOLANA_RPC_URL must be https (got "${u.protocol}//${u.hostname}"). Only http://localhost is allowed for local dev.`,+ ),+ { code: 'insecure_rpc_url' },+ );+}++// Solana mainnet RPC. Bring your own (Helius / QuickNode / Triton) for production.+export const SOLANA_RPC_URL = validateRpcUrl(env('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com'));++// Optional default signer (base58 secret key, or a JSON byte array). pay_and_call+// accepts a per-call `secret` that overrides this.+export const SOLANA_DEFAULT_SECRET = env('SOLANA_SECRET_KEY') || env('FUNDER_SECRET') || '';++// Max USD a single pay_and_call may spend. Default $1 — bounds a runaway/injected+// payment. Raise MAX_PAY_USD to allow larger calls.+export const MAX_PAY_USD = (() => {+ const raw = env('MAX_PAY_USD');+ if (raw === undefined) return 1;+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) {+ throw Object.assign(new Error(`MAX_PAY_USD must be a positive number (got "${raw}")`), { code: 'bad_policy_config' });+ }+ return n;+})();++// Spending money requires an explicit confirm:true unless opted out.+export const REQUIRE_CONFIRM = (() => {+ const raw = env('REQUIRE_CONFIRM');+ if (raw === undefined) return true;+ return !['0', 'false', 'no', 'off'].includes(String(raw).toLowerCase());+})();++// Canonical Solana mainnet USDC mint (6 decimals) — for balance reads.+export const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++export const USER_AGENT = '@three-ws/x402-mcp';diff --git a/packages/x402-mcp/src/index.js b/packages/x402-mcp/src/index.jsnew file mode 100644index 000000000..ddcba382e--- /dev/null+++ b/packages/x402-mcp/src/index.js@@ -0,0 +1,113 @@+#!/usr/bin/env node+// @three-ws/x402-mcp — MCP server entry point.+//+// Gives any AI assistant a self-custodial x402 wallet over stdio:+// • x402_wallet — the wallet's address + SOL/USDC balance (read-only)+// • find_services — search the live x402 bazaar for paid services (read-only)+// • inspect_endpoint— read an endpoint's price/requirements without paying (read-only)+// • pay_and_call — pay an x402 endpoint in USDC and return its result (execution)+//+// Self-custodial: payments are signed by YOUR Solana key (SOLANA_SECRET_KEY),+// not a custodial wallet. The read tools work with no key. Real @x402/* libs do+// the 402 dance + Solana `exact` settlement — nothing is mocked.+//+// Run standalone:+// SOLANA_SECRET_KEY=<base58> node packages/x402-mcp/src/index.js+//+// Or wire into Claude Code / Cursor — see README.md.++import { realpathSync } from 'node:fs';+import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';++import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';++import { def as x402Wallet } from './tools/x402-wallet.js';+import { def as findServices } from './tools/find-services.js';+import { def as inspectEndpoint } from './tools/inspect-endpoint.js';+import { def as payAndCall } from './tools/pay-and-call.js';++const require = createRequire(import.meta.url);+const { version: PKG_VERSION } = require('../package.json');++export const TOOLS = [x402Wallet, findServices, inspectEndpoint, payAndCall];++/**+ * Construct a fully-registered McpServer without connecting a transport or+ * requiring a signer. Registration is env-free; only pay_and_call (and+ * x402_wallet defaulting to the signer) needs SOLANA_SECRET_KEY. Safe to import+ * from tests.+ * @returns {McpServer}+ */+export function buildServer() {+ const server = new McpServer(+ { name: 'x402-mcp', title: 'x402 Wallet', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'x402 buyer MCP — give the agent a self-custodial wallet that can pay for anything on the x402 ' ++ 'network. find_services searches the live bazaar (PayAI + Coinbase CDP). inspect_endpoint reads ' ++ "any endpoint's price/requirements WITHOUT paying. x402_wallet shows the signer wallet's address " ++ 'and SOL/USDC balance. pay_and_call is an EXECUTION ACTION: it pays an x402 endpoint in USDC from ' ++ 'your Solana key (SOLANA_SECRET_KEY or a per-call `secret`) and returns the result, bounded by ' ++ 'MAX_PAY_USD and gated by REQUIRE_CONFIRM. Settlement is the Solana `exact` scheme via the real ' ++ '@x402 libraries — never a wallet you do not control.',+ },+ );++ for (const tool of TOOLS) {+ server.registerTool(+ tool.name,+ {+ title: tool.title,+ description: tool.description,+ inputSchema: tool.inputSchema,+ annotations: tool.annotations,+ },+ async (args, extra) => {+ try {+ const result = await tool.handler(args, extra);+ const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);+ return { content: [{ type: 'text', text }] };+ } catch (err) {+ const payload = {+ ok: false,+ error: err?.code || 'unhandled',+ message: err?.message || String(err),+ ...(err?.status ? { status: err.status } : {}),+ };+ return {+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],+ isError: true,+ };+ }+ },+ );+ }++ return server;+}++async function main() {+ const server = buildServer();+ const transport = new StdioServerTransport();+ await server.connect(transport);+ console.error(`[x402-mcp@${PKG_VERSION}] connected over stdio with ${TOOLS.length} tools`);+}++function isProcessEntryPoint() {+ if (!process.argv[1]) return false;+ try {+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;+ } catch {+ return false;+ }+}++if (isProcessEntryPoint()) {+ main().catch((err) => {+ console.error('[x402-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/x402-mcp/src/lib/api.js b/packages/x402-mcp/src/lib/api.jsnew file mode 100644index 000000000..b3ba420d5--- /dev/null+++ b/packages/x402-mcp/src/lib/api.js@@ -0,0 +1,48 @@+// Plain HTTP access to the three.ws API (used by find_services). Real network+// only — no mocks. Errors normalized into one shape.++import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT } from '../config.js';++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/x402-mcp/src/lib/solana.js b/packages/x402-mcp/src/lib/solana.jsnew file mode 100644index 000000000..3d71427ed--- /dev/null+++ b/packages/x402-mcp/src/lib/solana.js@@ -0,0 +1,29 @@+// Read-only Solana balance helper for x402_wallet. Live RPC only — no mocks.++import { SOLANA_RPC_URL, USDC_MAINNET_MINT } from '../config.js';++/**+ * Read the SOL and USDC balance of a Solana address.+ * @param {string} address base58 pubkey+ * @returns {Promise<{ sol: number, usdc: number|null }>}+ */+export async function getBalances(address) {+ const { Connection, PublicKey } = await import('@solana/web3.js');+ const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');+ const conn = new Connection(SOLANA_RPC_URL, 'confirmed');+ const owner = new PublicKey(address);++ const lamports = await conn.getBalance(owner);+ const sol = lamports / 1e9;++ let usdc = null;+ try {+ const ata = getAssociatedTokenAddressSync(new PublicKey(USDC_MAINNET_MINT), owner, true);+ const bal = await conn.getTokenAccountBalance(ata);+ usdc = bal?.value?.uiAmount ?? 0;+ } catch {+ // No USDC ATA yet → treat as zero, not an error.+ usdc = 0;+ }+ return { sol, usdc };+}diff --git a/packages/x402-mcp/src/lib/x402-buyer.js b/packages/x402-mcp/src/lib/x402-buyer.jsnew file mode 100644index 000000000..48df70737--- /dev/null+++ b/packages/x402-mcp/src/lib/x402-buyer.js@@ -0,0 +1,127 @@+// x402 buyer wiring — pay any x402 endpoint from a local Solana keypair.+//+// Mirrors the canonical three.ws buyer (api/_lib/x402-user-payer.js) but for a+// self-custodial standalone: the signer is YOUR key (SOLANA_SECRET_KEY or a+// per-call `secret`), not a custodial wallet. Real `@x402/*` libraries do the+// 402 dance and sign the Solana `exact`-scheme payment — nothing is mocked.+//+// The flow:+// 1. x402Client + ExactSvmScheme(signer) registered for solana:*+// 2. wrapFetchWithPayment(fetch, client) → a fetch that, on a 402, signs and+// retries with the X-PAYMENT header, then exposes the settlement response.++import bs58 from 'bs58';++import { SOLANA_DEFAULT_SECRET } from '../config.js';++/** Decode a base58 string OR a JSON byte array into raw secret-key bytes. */+function secretKeyBytes(secret) {+ const s = String(secret || '').trim();+ if (!s) {+ throw Object.assign(new Error('No Solana signer configured. Set SOLANA_SECRET_KEY or pass `secret`.'), {+ code: 'no_signer',+ });+ }+ if (s.startsWith('[')) {+ let arr;+ try {+ arr = JSON.parse(s);+ } catch {+ throw Object.assign(new Error('SOLANA_SECRET_KEY looks like a JSON array but failed to parse.'), {+ code: 'bad_secret',+ });+ }+ return Uint8Array.from(arr);+ }+ try {+ return bs58.decode(s);+ } catch {+ throw Object.assign(new Error('SOLANA_SECRET_KEY must be a base58 string or a JSON byte array.'), {+ code: 'bad_secret',+ });+ }+}++/**+ * Build a Solana signer (from @solana/kit) for the given secret. Returns the+ * kit signer (its `.address` is the base58 pubkey).+ */+export async function getSigner(secretOverride) {+ const { createKeyPairSignerFromBytes } = await import('@solana/kit');+ const bytes = secretKeyBytes(secretOverride || SOLANA_DEFAULT_SECRET);+ return createKeyPairSignerFromBytes(bytes);+}++/**+ * Build a payment-aware fetch bound to a Solana signer. The returned `payingFetch`+ * behaves like global fetch but transparently settles a 402 challenge in USDC.+ *+ * @returns {Promise<{ payingFetch: typeof fetch, httpClient: any, address: string }>}+ */+export async function buildPayingFetch(secretOverride) {+ const [{ x402Client, x402HTTPClient }, { ExactSvmScheme }, { wrapFetchWithPayment }] = await Promise.all([+ import('@x402/core/client'),+ import('@x402/svm/exact/client'),+ import('@x402/fetch'),+ ]);+ const signer = await getSigner(secretOverride);+ const client = new x402Client();+ client.register('solana:*', new ExactSvmScheme(signer));+ const httpClient = new x402HTTPClient(client);+ const payingFetch = wrapFetchWithPayment(globalThis.fetch, client);+ return { payingFetch, httpClient, address: String(signer.address) };+}++/** Decode the settlement receipt from a paid response's `x-payment-response` header. */+export async function decodeSettlement(response) {+ const header = response?.headers?.get?.('x-payment-response');+ if (!header) return null;+ try {+ const { decodePaymentResponseHeader } = await import('@x402/fetch');+ return decodePaymentResponseHeader(header);+ } catch {+ try {+ return JSON.parse(Buffer.from(header, 'base64').toString('utf8'));+ } catch {+ return null;+ }+ }+}++/**+ * Fetch an x402 endpoint WITHOUT paying and return its 402 challenge (the+ * `accepts` payment requirements) decoded, or the plain result if it's free.+ */+export async function probeChallenge(url, { method = 'GET', body, timeoutMs = 30000 } = {}) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ let res;+ try {+ res = await fetch(url, {+ method,+ headers: {+ accept: 'application/json',+ ...(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(`${url} timed out`), { code: 'timeout' });+ throw Object.assign(new Error(`${url} request failed: ${err?.message || err}`), { code: 'network_error' });+ }+ clearTimeout(timer);+ const text = await res.text();+ let parsed;+ try {+ parsed = text ? JSON.parse(text) : null;+ } catch {+ parsed = text;+ }+ if (res.status !== 402) {+ return { paid: false, status: res.status, ok: res.ok, result: parsed };+ }+ const accepts = Array.isArray(parsed?.accepts) ? parsed.accepts : [];+ return { paid: true, status: 402, accepts, challenge: parsed };+}diff --git a/packages/x402-mcp/src/tools/find-services.js b/packages/x402-mcp/src/tools/find-services.jsnew file mode 100644index 000000000..0c3e2804e--- /dev/null+++ b/packages/x402-mcp/src/tools/find-services.js@@ -0,0 +1,49 @@+// `find_services` — search the live x402 bazaar for paid services. Read-only.+//+// Wraps GET /api/bazaar/search, which merges the public facilitator discovery+// feeds (PayAI + CDP) and ranks them against your query. Feed a returned+// `resource` into pay_and_call to actually use it.++import { z } from 'zod';++import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'find_services',+ title: 'Find paid x402 services the agent can call',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Search the live x402 facilitator network (PayAI + Coinbase CDP bazaar) for paid services — HTTP APIs and MCP tools. Returns each match with its price, networks, and resource URL. Pass a resource into pay_and_call to use it. Read-only.',+ inputSchema: {+ query: z.string().min(1).describe('What you need, e.g. "weather", "image upscale", "token intel".'),+ type: z.enum(['http', 'mcp']).default('http').describe('Service kind to search.'),+ network: z.string().optional().describe('CAIP-2 network filter, e.g. "solana:*" or "eip155:8453".'),+ max_price_usdc: z.number().min(0).optional().describe('Only return services at or under this USDC price.'),+ limit: z.number().int().min(1).max(100).optional().describe('Max results (default 25).'),+ },+ async handler(args) {+ const query = String(args?.query ?? '').trim();+ const type = args?.type === 'mcp' ? 'mcp' : 'http';+ const maxPrice =+ args?.max_price_usdc != null ? String(Math.round(Number(args.max_price_usdc) * 1_000_000)) : undefined;+ const data = await apiRequest('/api/bazaar/search', {+ query: {+ query,+ type,+ network: args?.network,+ maxPrice,+ limit: args?.limit ?? 25,+ },+ });+ const resources = Array.isArray(data?.resources) ? data.resources : [];+ const services = resources.map((it) => ({+ resource: it.resource,+ name: it.serviceName || it.name || undefined,+ description: it.description || undefined,+ price: it.minPriceLabel || it.price || undefined,+ networks: it.networks,+ tool_name: it.toolName || undefined,+ }));+ return { ok: true, query, type, count: services.length, services };+ },+};diff --git a/packages/x402-mcp/src/tools/inspect-endpoint.js b/packages/x402-mcp/src/tools/inspect-endpoint.jsnew file mode 100644index 000000000..f70bc4a5a--- /dev/null+++ b/packages/x402-mcp/src/tools/inspect-endpoint.js@@ -0,0 +1,51 @@+// `inspect_endpoint` — read an x402 endpoint's payment requirements WITHOUT+// paying. Read-only, no signer needed. The safe way to learn what a call costs+// before committing money with pay_and_call.++import { z } from 'zod';++import { probeChallenge } from '../lib/x402-buyer.js';++export const def = {+ name: 'inspect_endpoint',+ title: 'Inspect an x402 endpoint (price + requirements, no payment)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Fetch an x402 endpoint and return its 402 payment requirements — every accepted scheme, network, asset, price and pay-to address — WITHOUT paying. If the endpoint is free, returns its result instead. No signer required. Use this to learn the cost before pay_and_call.',+ inputSchema: {+ url: z.string().url().describe('The x402 endpoint URL to inspect.'),+ method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method to probe with.'),+ body: z.record(z.any()).optional().describe('JSON body for a POST probe.'),+ },+ async handler(args) {+ const url = String(args?.url ?? '').trim();+ const method = args?.method === 'POST' ? 'POST' : 'GET';+ const probe = await probeChallenge(url, { method, body: args?.body });+ if (!probe.paid) {+ return {+ ok: true,+ url,+ paid: false,+ status: probe.status,+ note: 'Endpoint is not paywalled (no 402) — call it directly.',+ result: probe.result,+ };+ }+ const accepts = probe.accepts.map((a) => ({+ scheme: a.scheme,+ network: a.network,+ price: a.price ?? a.maxAmountRequired ?? undefined,+ asset: a.asset ?? a.extra?.asset ?? undefined,+ pay_to: a.payTo ?? undefined,+ max_timeout_seconds: a.maxTimeoutSeconds ?? undefined,+ }));+ return {+ ok: true,+ url,+ paid: true,+ accepts,+ payable_with_this_wallet: accepts.some((a) => String(a.network || '').startsWith('solana')),+ note: 'This wallet settles Solana (solana:*) requirements. pay_and_call to pay and run it.',+ };+ },+};diff --git a/packages/x402-mcp/src/tools/pay-and-call.js b/packages/x402-mcp/src/tools/pay-and-call.jsnew file mode 100644index 000000000..bb6093fcc--- /dev/null+++ b/packages/x402-mcp/src/tools/pay-and-call.js@@ -0,0 +1,125 @@+// `pay_and_call` — pay an x402 endpoint in USDC from the local Solana wallet and+// return its result. EXECUTION tool: it moves real money.+//+// Guards before any payment: probe the 402 to read the Solana price, refuse if it+// exceeds max_usd or MAX_PAY_USD, and (when REQUIRE_CONFIRM is on) require an+// explicit confirm:true. Payment + settlement are done by the real @x402/* libs.++import { z } from 'zod';++import { buildPayingFetch, decodeSettlement, probeChallenge } from '../lib/x402-buyer.js';+import { MAX_PAY_USD, REQUIRE_CONFIRM, SOLANA_DEFAULT_SECRET } from '../config.js';++// Pull a USD price out of a Solana `accepts` entry. x402 prices are USDC atomic+// (6 decimals) unless already a "$x" string.+function solanaPriceUsd(accepts) {+ const solana = accepts.find((a) => String(a.network || '').startsWith('solana'));+ if (!solana) return { found: false };+ const raw = solana.price ?? solana.maxAmountRequired;+ if (raw == null) return { found: true, requirement: solana, usd: null };+ if (typeof raw === 'string' && raw.trim().startsWith('$')) {+ return { found: true, requirement: solana, usd: Number(raw.replace('$', '').trim()) };+ }+ const atomics = Number(raw);+ if (!Number.isFinite(atomics)) return { found: true, requirement: solana, usd: null };+ return { found: true, requirement: solana, usd: atomics / 1_000_000 };+}++export const def = {+ name: 'pay_and_call',+ title: 'Pay an x402 endpoint in USDC and return its result',+ // Moves real USDC — irreversible transfer.+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Call a paid x402 endpoint and settle the USDC payment automatically from your Solana wallet (SOLANA_SECRET_KEY or a per-call `secret`), then return the result. Bounded by max_usd and the MAX_PAY_USD cap; refuses before any money moves if the price is over the cap. With REQUIRE_CONFIRM on (default), the call refuses until re-issued with confirm:true. Settles the Solana (solana:*) requirement via the `exact` scheme.',+ inputSchema: {+ url: z.string().url().describe('The x402 endpoint to pay and call.'),+ method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method.'),+ body: z.record(z.any()).optional().describe('JSON body for POST requests.'),+ max_usd: z+ .number()+ .positive()+ .optional()+ .describe('Hard ceiling for THIS call in USD. Can only lower the MAX_PAY_USD cap, never raise it.'),+ secret: z.string().optional().describe('Per-call base58 signer override (defaults to SOLANA_SECRET_KEY).'),+ confirm: z.boolean().optional().describe('Must be true to execute when REQUIRE_CONFIRM is on.'),+ },+ async handler(args) {+ const url = String(args?.url ?? '').trim();+ const method = args?.method === 'POST' ? 'POST' : 'GET';+ const secret = args?.secret || SOLANA_DEFAULT_SECRET;+ if (!secret) {+ throw Object.assign(new Error('No signer configured. Set SOLANA_SECRET_KEY or pass `secret`.'), {+ code: 'no_signer',+ });+ }++ // Probe first so we never pay blind and can enforce the cap pre-payment.+ const probe = await probeChallenge(url, { method, body: args?.body });+ if (!probe.paid) {+ return {+ ok: true,+ paid: false,+ url,+ note: 'Endpoint is not paywalled — called directly, no payment needed.',+ status: probe.status,+ result: probe.result,+ };+ }++ const price = solanaPriceUsd(probe.accepts);+ if (!price.found) {+ throw Object.assign(new Error('Endpoint has no Solana (solana:*) payment option this wallet can settle.'), {+ code: 'no_solana_requirement',+ });+ }+ const ceiling = Math.min(MAX_PAY_USD, args?.max_usd ?? Infinity);+ if (price.usd != null && price.usd > ceiling) {+ throw Object.assign(+ new Error(`Price $${price.usd} exceeds the cap $${ceiling}. Raise max_usd / MAX_PAY_USD to allow it.`),+ { code: 'over_cap', price_usd: price.usd, cap_usd: ceiling },+ );+ }+ if (REQUIRE_CONFIRM && args?.confirm !== true) {+ return {+ ok: false,+ error: 'confirm_required',+ message: `This will spend up to $${price.usd ?? '?'} USDC on ${url}. Re-issue with confirm:true to proceed (or set REQUIRE_CONFIRM=0).`,+ price_usd: price.usd,+ url,+ };+ }++ const { payingFetch, address } = await buildPayingFetch(secret);+ const init = {+ method,+ headers: { accept: 'application/json', ...(args?.body !== undefined ? { 'content-type': 'application/json' } : {}) },+ body: args?.body !== undefined ? JSON.stringify(args.body) : undefined,+ };+ const res = await payingFetch(url, init);+ const text = await res.text();+ let result;+ try {+ result = text ? JSON.parse(text) : null;+ } catch {+ result = text;+ }+ if (!res.ok) {+ throw Object.assign(new Error(`Paid call to ${url} returned HTTP ${res.status}`), {+ code: 'call_failed',+ status: res.status,+ body: result,+ });+ }+ const settlement = await decodeSettlement(res);+ return {+ ok: true,+ paid: true,+ url,+ payer: address,+ price_usd: price.usd,+ settlement,+ result,+ };+ },+};diff --git a/packages/x402-mcp/src/tools/x402-wallet.js b/packages/x402-mcp/src/tools/x402-wallet.jsnew file mode 100644index 000000000..5691aaf0c--- /dev/null+++ b/packages/x402-mcp/src/tools/x402-wallet.js@@ -0,0 +1,51 @@+// `x402_wallet` — show a Solana wallet's address + SOL/USDC balance. Read-only.+//+// With no `address`, it derives the address from the configured signer+// (SOLANA_SECRET_KEY) so you can confirm the agent's spending wallet is funded+// before pay_and_call. Pass `address` to inspect any wallet without a key.++import { z } from 'zod';++import { getBalances } from '../lib/solana.js';+import { getSigner } from '../lib/x402-buyer.js';+import { SOLANA_DEFAULT_SECRET } from '../config.js';++export const def = {+ name: 'x402_wallet',+ title: "The agent's x402 spending wallet (address + balance)",+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Show a Solana wallet's address and live SOL + USDC balance. With no `address`, derives the wallet from the configured signer (SOLANA_SECRET_KEY) — call this before pay_and_call to confirm there's USDC to spend. Read-only; never moves funds.",+ inputSchema: {+ address: z+ .string()+ .min(32)+ .max(64)+ .optional()+ .describe('Base58 Solana address to inspect. Omit to use the configured signer wallet.'),+ },+ async handler(args) {+ let address = args?.address ? String(args.address).trim() : '';+ let from_signer = false;+ if (!address) {+ if (!SOLANA_DEFAULT_SECRET) {+ throw Object.assign(+ new Error('No address given and no SOLANA_SECRET_KEY configured. Pass `address` or set a signer.'),+ { code: 'no_signer' },+ );+ }+ const signer = await getSigner();+ address = String(signer.address);+ from_signer = true;+ }+ const { sol, usdc } = await getBalances(address);+ return {+ ok: true,+ address,+ from_signer,+ sol,+ usdc,+ can_pay: from_signer || Boolean(SOLANA_DEFAULT_SECRET),+ };+ },+};diff --git a/packages/x402-server/LICENSE b/packages/x402-server/LICENSEnew file mode 100644index 000000000..bbb838721--- /dev/null+++ b/packages/x402-server/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/x402-server/package.json b/packages/x402-server/package.jsonindex 22b263c9c..a4e402bf7 100644--- a/packages/x402-server/package.json+++ b/packages/x402-server/package.json@@ -2,6 +2,26 @@"name": "@three-ws/x402-server","version": "0.1.0","description": "The merchant side of x402 — turn any HTTP endpoint into a paid one. Issue 402 challenges, price SKUs, verify and settle the X-PAYMENT header on Solana and Base, and take a platform fee.",+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "types": "./src/index.d.ts",+ "exports": {+ ".": {+ "types": "./src/index.d.ts",+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test test/*.test.js"+ },"keywords": ["x402","402",@@ -16,15 +36,22 @@"agent-payments","three.ws"],+ "author": "nirholas <[email protected]>","license": "MIT",- "private": true,- "type": "module","homepage": "https://three.ws","repository": {"type": "git",- "url": "https://github.com/nirholas/three.ws"+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/x402-server"},"bugs": {"url": "https://github.com/nirholas/three.ws/issues"+ },+ "engines": {+ "node": ">=18"+ },+ "dependencies": {},+ "publishConfig": {+ "access": "public"}}diff --git a/packages/x402-server/src/http.js b/packages/x402-server/src/http.jsnew file mode 100644index 000000000..6398a3e53--- /dev/null+++ b/packages/x402-server/src/http.js@@ -0,0 +1,135 @@+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.+// Copied verbatim into each package so every SDK stays dependency-free while+// resolving the base URL, attaching auth, and mapping the platform's JSON error+// envelope onto typed errors the same way everywhere.++export const DEFAULT_BASE_URL = 'https://three.ws';++/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */+export class ThreeWsError extends Error {+ constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {+ super(message);+ this.name = 'ThreeWsError';+ this.code = code;+ this.status = status;+ if (detail) this.detail = detail;+ if (retryAfter != null) this.retryAfter = retryAfter;+ this.body = body;+ }+}++/**+ * Thrown on HTTP 402. The endpoint wants payment before it will do the work.+ * `accepts` is the x402 challenge (asset/amount/network/payTo) when present —+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it+ * automatically, or read `accepts` and pay it yourself.+ */+export class PaymentRequiredError extends ThreeWsError {+ constructor(message, opts = {}) {+ super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });+ this.name = 'PaymentRequiredError';+ this.accepts = opts.accepts ?? null;+ }+}++/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */+export function resolveBaseUrl(baseUrl) {+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;+ return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');+}++function buildUrl(baseUrl, path, query) {+ const url = new URL(String(path).replace(/^\/+/, '/'), baseUrl + '/');+ if (query && typeof query === 'object') {+ for (const [k, v] of Object.entries(query)) {+ if (v === undefined || v === null) continue;+ url.searchParams.set(k, String(v));+ }+ }+ return url;+}++/**+ * Build a `request(path, opts)` function bound to a base URL + fetch + headers.+ * Returns parsed JSON on success; throws a typed error on any non-2xx.+ *+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).+ * @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).+ * @param {string} [opts.apiKey] bearer token attached as Authorization.+ * @param {Record<string,string>} [opts.headers] default headers on every call.+ */+export function createHttp(opts = {}) {+ const baseUrl = resolveBaseUrl(opts.baseUrl);+ const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);+ if (typeof fetchImpl !== 'function') {+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });+ }+ const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;++ return async function request(path, { method = 'GET', query, body, headers, signal } = {}) {+ const url = buildUrl(baseUrl, path, query);+ const init = { method, headers: { ...baseHeaders, ...(headers || {}) }, signal };+ if (body !== undefined) {+ init.body = typeof body === 'string' ? body : JSON.stringify(body);+ init.headers['content-type'] = init.headers['content-type'] || 'application/json';+ }++ let res;+ try {+ res = await fetchImpl(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });+ }++ const text = await res.text();+ let payload = null;+ if (text) {+ try { payload = JSON.parse(text); } catch { payload = { raw: text }; }+ }++ if (res.ok) return payload;++ const code = payload?.error || payload?.code || `http_${res.status}`;+ const message = payload?.message || payload?.error_description || payload?.detail || `Request failed with ${res.status}`;+ const retryAfter = numberOr(res.headers.get('retry-after'), payload?.retry_after);++ if (res.status === 402) {+ throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });+ }+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });+ };+}++function numberOr(...vals) {+ for (const v of vals) {+ if (v == null) continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/** Sleep that respects an AbortSignal (used by client-side job pollers). */+export function delay(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ function onAbort() {+ clearTimeout(t);+ reject(abortError());+ }+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++function abortError() {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ return e;+}diff --git a/prompts/b/33-onboarding-activation.md b/prompts/b/33-onboarding-activation.mddeleted file mode 100644index f9e445e8a..000000000--- a/prompts/b/33-onboarding-activation.md+++ /dev/null@@ -1,102 +0,0 @@-# 33 — Onboarding & activation funnel--> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`-> for shared context.--## Why this matters for $1B--Activation — a new visitor reaching their first "aha" — is the single biggest lever-on growth. Every dollar of acquisition is wasted if a first-timer can't make-something real in the first minute. three.ws already has the pieces (welcome modal,-"Getting started 0/3" checklist, a "What is three.ws" page, an 88-stop guided 3D-tour), but they must compose into one coherent path with a clear, fast first win and-honest measurement, or the funnel leaks at the top.--## Mission--Turn the first-run experience into a single, polished path that gets a brand-new-visitor from "what is this?" to "I made a 3D thing" in about 60 seconds, with every-step instrumented so activation is measurable.--## Map (trust but verify — files move)--- **Getting-started checklist + welcome modal** — [public/getting-started.js](../../public/getting-started.js)- (the `STEPS` array: core `create → brain → embed`, optional `onchain → monetize`;- renders the bottom-right "Getting started N/3" pill), [public/getting-started.css](../../public/getting-started.css).-- **In-product feature discovery** — [public/feature-discovery.js](../../public/feature-discovery.js)- ("Have you tried…", `tws:feature-done` "what's next" cards), [public/feature-discovery.css](../../public/feature-discovery.css).-- **Intro / explainer pages** — [pages/what-is.html](../../pages/what-is.html) (`/what-is`),- [pages/start.html](../../pages/start.html) (`/start`).-- **Guided 3D tour** — [src/feature-tour/director.js](../../src/feature-tour/director.js),- [src/feature-tour/curriculum.js](../../src/feature-tour/curriculum.js),- [public/tour/curriculum.json](../../public/tour/curriculum.json) (built by- `scripts/build-tour.mjs`); tour page is `/tour`.-- **First "aha" surfaces** — [pages/forge.html](../../pages/forge.html) +- [src/forge.js](../../src/forge.js) (free NVIDIA NIM text→3D), `/create` and- [src/create-prompt.js](../../src/create-prompt.js) (text→avatar). The free lanes- need no wallet.-- **Analytics taxonomy** — [src/analytics.js](../../src/analytics.js)- (`FUNNELS.activation`: `landing_viewed → wallet_connect_started →- wallet_connect_succeeded → agent_created`), [src/acquisition-analytics.js](../../src/acquisition-analytics.js).--## Do this--1. **Walk the real funnel in a browser** (`npm run dev`): open `/` in a fresh- incognito profile (clear `localStorage`), follow the welcome modal → `/create` →- finish a free generation. Time it. Note every dead-end, dead click, or moment of- confusion. The free core path must never demand a wallet.-2. **Make the first win the default.** The fastest aha is the free NIM text→3D /- text→avatar lane — ensure the welcome modal and `/start` route there first, with a- one-line prompt suggestion so a blank composer never stalls a first-timer.-3. **Unify the three entry points** so they tell one story: the welcome modal- (`getting-started.js`), `/what-is`, and `/tour`. Cross-link them; remove- contradictory copy; ensure the "Getting started N/3" pill resumes correctly across- pages and reflects real milestones (verify the `done()` route matchers in `STEPS`- still point at live routes via `vercel.json`).-4. **Instrument activation honestly.** Confirm `AGENT_CREATED` / first-generation and- each checklist `complete()` fire `track()` events through `src/analytics.js`- (extend `FUNNELS.activation` or `ANALYTICS_EVENTS` if a step in the real path isn't- covered — keep names in the existing taxonomy, never invent ad-hoc strings). No raw- wallet addresses or PII as props (use `shortWallet()`).-5. **Design every onboarding state:** welcome modal has focus trap + Escape + "Maybe- later" (verify), the checklist has an empty/first-run state and a celebratory- complete state, and `tws:feature-done` "what's next" cards point only at confirmed- live routes.-6. **Reduce time-to-value.** Cut any step that isn't required for the first win;- defer wallet/on-chain prompts until after the user has made something. Lazy-load- the heavy tour director so it never delays the homepage LCP.-7. **Verify resume + opt-out.** `data-getting-started="off"`, "Hide this", and the- immersive-route exclusions must all work; progress persists across reloads and- pages; the tour rehydrates from `sessionStorage` mid-flow.-8. **Run tests + changelog.** `npx vitest run` for any touched module and the tour- build (`node scripts/build-tour.mjs` stays clean). Add a `data/changelog.json`- entry for the user-visible onboarding improvement and run `npm run build:pages`.--## Must-not--- Do not gate the free core path behind a wallet, sign-up, or payment — the first aha- must be free.-- Do not ship a fake progress bar or `setTimeout` "loading"; generation progress comes- from real API responses only.-- Do not send PII (raw wallets, emails) to analytics; route through the taxonomy in- `src/analytics.js` and truncate with `shortWallet()`.-- Do not reference any coin other than `$THREE`; the optional "monetize" step settles- in `$THREE` only.-- Do not break the existing resume/opt-out behavior or double-mount the guide- (`window.__twsGuide` idempotency).--## Acceptance (all true before claiming done)--- [ ] A fresh incognito visitor reaches a finished free 3D creation in ≤60s with no- wallet and no console errors/warnings.-- [ ] Welcome modal, `/what-is`, and `/tour` tell one consistent story and cross-link;- every CTA target is a live route.-- [ ] "Getting started N/3" pill resumes across pages, reflects real milestones, and- has designed first-run + complete states.-- [ ] Each activation step fires a taxonomy event via `src/analytics.js` with no PII;- `FUNNELS.activation` reflects the real path.-- [ ] Opt-out (`data-getting-started="off"`, "Hide this", immersive exclusions) and- tour mid-flow rehydration all work.-- [ ] Touched tests pass, `scripts/build-tour.mjs` is clean, and the changelog entry- is added with `npm run build:pages` clean.diff --git a/prompts/b/34-home-landing-conversion.md b/prompts/b/34-home-landing-conversion.mddeleted file mode 100644index eb5674d5e..000000000--- a/prompts/b/34-home-landing-conversion.md+++ /dev/null@@ -1,101 +0,0 @@-# 34 — Home / landing conversion--> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`-> for shared context.--## Why this matters for $1B--The homepage is where ad spend, press, and word-of-mouth all land. A first-time-visitor decides in about 5 seconds whether to stay. If the hero doesn't instantly-communicate "give your AI a body" and offer an obvious, fast next action, the-acquisition funnel dies before activation (prompt 33) even begins. A clear,-fast-loading, mobile-first, socially-proven landing page is the cheapest growth lever-the platform has.--## Mission--Make the home page make a cold visitor understand the product in 5 seconds and act:-sharp hero, one above-the-fold primary CTA, a live demo they can touch, credible-social proof, benefit-led copy, fast LCP, and flawless mobile.--## Map (trust but verify — files move)--- **Home page** — [pages/home.html](../../pages/home.html) (`/`). Hero h1 currently- "The 3D agent layer of the internet." with bullets Create/Embed/Earn and the- `.hero-cta-row` (`/create`, `/forge`, `#embed`, `/tour`). All inline `<style>` +- `<script type="module">`.-- **Live demo embeds** — [src/home-forge.js](../../src/home-forge.js) (mini Forge:- real `/api/forge` text→3D in-page), [src/forge-showcase.js](../../src/forge-showcase.js)- ("Fresh from the Forge" community feed), [src/home-live-token.js](../../src/home-live-token.js)- (live $THREE price), [src/api-playground.js](../../public/api-playground.js) and the- `<agent-3d>` web component embed (`agent-3d/latest/agent-3d.js`).-- **Social proof / press strip** — the `.press-row` block in- [pages/home.html](../../pages/home.html) (Anthropic, Coinbase, IBM, AWS, Google- Cloud, Alibaba Cloud, Solana, CoinMarketCap, CoinGecko, HackerNoon) with SVGs in- [public/featured-logos/](../../public/featured-logos).-- **CTA + funnel instrumentation** — `data-cta` / `data-cta-loc` attributes on every- CTA, consumed by [src/acquisition-analytics.js](../../src/acquisition-analytics.js)- → [src/analytics.js](../../src/analytics.js) (`CTA_CLICKED`, `LANDING_VIEWED`).-- **Performance budget** — Core Web Vitals work lives in- `prompts/production-1b/10-*`; OG/structured data in `prompts/production-1b/14-*`.--## Do this--1. **Open `/` cold on mobile and desktop** (`npm run dev`; emulate 320 / 768 / 1440).- Read the hero as a stranger: in 5 seconds, is it obvious this turns your AI into an- embeddable 3D avatar? Sharpen the h1/sub/bullets toward the plain promise ("give- your AI a body" — make a 3D agent, embed it anywhere) without losing the existing- voice or the i18n `data-i18n-*` hooks.-2. **One unmistakable primary CTA above the fold.** The hero has four buttons; keep- the primary "Build your agent" visually dominant and make the rest clearly- secondary so the eye has one path. Verify each `href` resolves in `vercel.json` and- carries `data-cta`/`data-cta-loc`.-3. **Prove it with a live demo, not a screenshot.** Confirm the mini-Forge- (`home-forge.js`) and the `<agent-3d>` embed actually run real generations / render- live on load, with real elapsed time and designed loading/empty/error states (no- `setTimeout` fakery). The showcase strip hides itself when empty — verify it never- shows a hollow row.-4. **Make social proof credible and honest.** Keep the press/partner strip truthful- (only real, linkable mentions — the SVGs in `public/featured-logos/`); ensure logos- are lazy, accessible (alt/label), and don't push down the hero. Do not invent or- overstate any endorsement.-5. **Fast LCP.** The hero text/CTA must be the LCP and must not wait on the 3D embed- or model-viewer scripts — defer/lazy-load heavy modules (tour director, model- viewer, showcase) below the fold. Preload the hero font/critical CSS only. Confirm- no layout shift from late-loading logos or demos.-6. **Mobile is first-class.** At 320px the hero, CTA, and one demo must be usable- without horizontal scroll; the CTA stays reachable (sticky or repeated near the- fold). Touch targets ≥44px; the press strip wraps, never overflows.-7. **Wire the funnel.** Every CTA fires `CTA_CLICKED` with `cta`/`location`; the page- fires `LANDING_VIEWED` once with referrer + UTM (already in- `acquisition-analytics.js`) — verify it loads on `/` and no PII leaks.-8. **Verify + changelog.** Lighthouse the page locally (LCP, CLS), run touched tests- (`npx vitest run`), add a `data/changelog.json` entry for the conversion- improvement, and run `npm run build:pages`.--## Must-not--- Do not invent press/partner logos or overstate endorsements — only real, linkable- mentions; this is a trust surface, not a dark pattern.-- Do not block LCP on the 3D embed, model-viewer, or any third-party script.-- Do not ship a fake/looping demo or a `setTimeout` progress bar — the demo is the- real pipeline or it is not shown.-- Do not reference any coin other than `$THREE` (the live token widget is $THREE only).-- Do not strip `data-i18n-*`, `data-cta`, or accessibility attributes from existing- elements.--## Acceptance (all true before claiming done)--- [ ] A cold visitor understands "give your AI a body" in ≤5s; one dominant- above-the-fold CTA; all CTA `href`s resolve.-- [ ] The live demo runs the real pipeline on load with designed loading/empty/error- states; the showcase never shows a hollow row.-- [ ] Press/partner proof is truthful, accessible, lazy, and does not push the hero- below the fold.-- [ ] LCP is the hero (not the 3D embed); no CLS from late logos/demos; verified in- Lighthouse locally.-- [ ] Usable at 320 / 768 / 1440 with no horizontal scroll and ≥44px touch targets.-- [ ] `LANDING_VIEWED` + every `CTA_CLICKED` fire with no PII; no console- errors/warnings.-- [ ] Touched tests pass; changelog entry added and `npm run build:pages` clean.diff --git a/prompts/b/35-pricing-monetization.md b/prompts/b/35-pricing-monetization.mddeleted file mode 100644index ca1e716d9..000000000--- a/prompts/b/35-pricing-monetization.md+++ /dev/null@@ -1,105 +0,0 @@-# 35 — Pricing & monetization surfaces--> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`-> for shared context.--## Why this matters for $1B--Revenue is the proof a platform is worth $1B. A visitor must understand what's free,-what costs, and exactly what they get for the money — in seconds, with no surprise-charges. three.ws monetizes two ways: a public pricing page (Free + paid generation)-and per-call x402 micropayments priced from a single catalog. If costs are opaque,-inconsistent across surfaces, or ever leak a vendor's billing internals, trust and-conversion both collapse.--## Mission--Make pricing and monetization clear, consistent, and value-aligned everywhere: one-source-of-truth catalog driving the pricing page, the x402 pay-per-call flow, and the-`/pay` surface, with transparent costs, honest upgrade paths, and zero vendor billing-exposure.--## Map (trust but verify — files move)--- **Pricing catalog (source of truth)** — [api/_lib/pricing/catalog.js](../../api/_lib/pricing/catalog.js)- (`CATALOG`, `publicCatalog()`, `priceForAction()`, `catalogEntry()`; prices in USD,- settled in `$THREE`; Forge tier prices READ from `forge-tiers.js`, not duplicated),- [api/_lib/pricing/charge-three.js](../../api/_lib/pricing/charge-three.js),- [api/_lib/forge-tiers.js](../../api/_lib/forge-tiers.js) (free draft tier on NVIDIA NIM).-- **Public pricing page** — [pages/pricing.html](../../pages/pricing.html) (`/pricing`),- [public/pricing.css](../../public/pricing.css). Has a Free tier ("$0/forever, no- credit card") + paid tiers in `#pricing-tiers`.-- **x402 pay surfaces** — [public/pay/index.html](../../public/pay/index.html) (`/pay`),- [public/pay/calls/index.html](../../public/pay/calls), [public/pay/c/index.html](../../public/pay/c),- the buyer modal in [api/x402-checkout.js](../../api/x402-checkout.js) +- [public/x402-checkout.js](../../public/x402-checkout.js),- [public/x402-pay-core.js](../../public/x402-pay-core.js).-- **Paid endpoints (catalog consumers)** — [api/x402/](../../api/x402) (e.g.- `forge.js`, `skill-call.js`, `service.js`, `mint-to-mesh.js`),- [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js),- [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js).-- **Conversion instrumentation** — [src/analytics.js](../../src/analytics.js)- (`token_*` and CTA events). Trading/PnL disclaimers live with the market surfaces- (prompt `22-*`).--## Do this--1. **Map every price to the catalog.** Confirm `pages/pricing.html` and every `/pay`- surface read from `api/_lib/pricing/catalog.js` (or `publicCatalog()` over an- endpoint) — no hardcoded dollar amounts duplicated in HTML/JS that can drift from- the catalog. Where a number is hardcoded today, wire it to the catalog or document- why it's a fixed marketing figure.-2. **Walk the buyer flow in a browser** (`npm run dev`): `/pricing`, then a real- per-call purchase via the `/pay` modal (`x402-checkout.js`). Confirm the quote is- shown in USD with the `$THREE` settle amount, costs are explicit before signing,- and the success/receipt state is clear (link to `my-receipts`).-3. **Never expose vendor billing.** Audit every error path in the pay/x402 chain: a- provider quota/credit/billing message, raw 402/429/5xx body, or vendor URL must be- masked to neutral, actionable copy ("Payment couldn't complete — try again");- server logs keep the detail. This is a hard `/CLAUDE.md` rule.-4. **Value-metric alignment.** Make the unit of charge obvious and tied to value- delivered (per generation / per call / per tier), not opaque "credits" with no- anchor. If a credits model is shown, it must convert transparently to the same- catalog prices.-5. **Design every state on the pay surfaces:** loading (quote fetching), empty (no- wallet connected → connect path), error (masked, retryable), and success- (receipt). The free tier must be clearly the default with no card required.-6. **Honest upgrade paths.** From the free Forge draft, the path to Standard/High (and- from a free agent to monetizing it) must be discoverable and benefit-led, never a- nag or a forced wall in front of the free aha. No dark patterns (no fake scarcity,- no pre-checked add-ons, no hidden recurring charges).-7. **Instrument conversion.** Fire the existing `token_*` / CTA taxonomy events- through `src/analytics.js` on pricing views, buy intent, quote shown, and settle —- no raw wallet/PII (use `shortWallet()`).-8. **Test + changelog.** Run the pricing/x402 tests (`npx vitest run` over- `tests/**/x402*`, `tests/**/pricing*`, `tests/**/forge-tiers*` as present), add a- `data/changelog.json` entry for any user-visible pricing change, and run- `npm run build:pages`.--## Must-not--- Do not surface any third party's billing page, credit balance, quota text, or raw- error to a buyer — mask to neutral copy, log detail server-side.-- Do not duplicate prices: the catalog (`api/_lib/pricing/catalog.js`) is the single- source of truth; surfaces read from it.-- Do not use dark patterns — no fake scarcity/countdowns, pre-checked upsells, hidden- recurring charges, or a wall in front of the free aha.-- Do not reference, price, or settle in any coin other than `$THREE` (USD is the quote- unit; `$THREE` is the settle unit).-- Do not show a trading/PnL/market figure without the required disclaimer.--## Acceptance (all true before claiming done)--- [ ] `/pricing` and every `/pay` surface read prices from the catalog; no drifting- hardcoded amounts.-- [ ] A real per-call purchase completes in-browser with USD quote + `$THREE` settle- shown before signing and a clear receipt after.-- [ ] Every pay/x402 failure mode yields neutral, actionable copy — no vendor billing- internals — verified by tests.-- [ ] Free tier is the obvious default (no card); upgrade paths are benefit-led with- no dark patterns.-- [ ] Loading/empty/error/success states designed on the pay surfaces; no console- errors/warnings.-- [ ] Conversion events fire through the taxonomy with no PII.-- [ ] Pricing/x402 tests pass; changelog entry added and `npm run build:pages` clean.diff --git a/prompts/b/36-growth-analytics.md b/prompts/b/36-growth-analytics.mddeleted file mode 100644index ddc63fa50..000000000--- a/prompts/b/36-growth-analytics.md+++ /dev/null@@ -1,111 +0,0 @@-# 36 — Growth analytics instrumentation--> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`-> for shared context.--## Why this matters for $1B--You cannot grow what you cannot measure. To scale acquisition, activation, and-retention deliberately, every meaningful step in the funnel must emit a clean,-consistently-named event — and never leak PII, or the platform becomes a privacy-liability instead of a $1B business. three.ws already has the spine (PostHog +-Vercel Web Analytics injected by Vite, a typed event taxonomy in `src/analytics.js`,-a first-party error reporter). The job is to complete coverage across the full funnel-without drift and without leaking.--## Mission--Complete privacy-respecting, consistently-taxonomied event instrumentation across the-activation → conversion → retention funnels, with dashboards/funnels that line up and-zero PII in any event.--## Map (trust but verify — files move)--- **Event taxonomy + facade (source of truth)** — [src/analytics.js](../../src/analytics.js)- (`ANALYTICS_EVENTS`, `FUNNELS.activation`, `FUNNELS.three`, `track()`,- `trackFunnelStep()`, `identifyUser()` / `resetIdentity()`, `trackError()`,- `shortWallet()`). `track()` validates against the catalog and rejects unknown- events — never bypass it.-- **Acquisition instrumentation** — [src/acquisition-analytics.js](../../src/acquisition-analytics.js)- (`LANDING_VIEWED` once + delegated `CTA_CLICKED` over `data-cta`/`data-cta-loc`).-- **Existing call sites** — [src/wallet-auth.js](../../src/wallet-auth.js),- [src/account.js](../../src/account.js), [src/create-agent.js](../../src/create-agent.js),- [src/marketplace.js](../../src/marketplace.js), [src/three-token-page.js](../../src/three-token-page.js),- [src/swap-jupiter.js](../../src/swap-jupiter.js), [src/agent-detail.js](../../src/agent-detail.js),- [src/dashboard-next/shell.js](../../src/dashboard-next/shell.js).-- **Provider injection (do not duplicate)** — the `posthog-analytics`,- `vercel-analytics`, and `client-error-reporter` plugins in- [vite.config.js](../../vite.config.js) (PostHog snippet, `person_profiles:- 'identified_only'`, ingest proxied through `/ingest`).-- **Server-side event/error sinks** — [public/error-reporter.js](../../public/error-reporter.js)- → [api/client-errors.js](../../api/client-errors.js); per-surface analytics in- [api/marketplace/analytics.js](../../api/marketplace/analytics.js),- [api/walk/analytics.js](../../api/walk/analytics.js),- [api/creators/skill-analytics.js](../../api/creators/skill-analytics.js).-- **Privacy reference** — [public/legal/privacy.html](../../public/legal/privacy.html)- ("no IPs, no fingerprints", "no third-party advertising cookies"). Instrumentation- must stay true to this.--## Do this--1. **Inventory before adding.** Grep for `track(`, `trackFunnelStep(`, `data-cta`, and- `ANALYTICS_EVENTS` to map what already fires. Do not reinvent the spine — extend- `src/analytics.js`. List the funnel gaps (any real step with no event).-2. **Complete the funnels by journey.** Ensure each stage emits a taxonomy event:- acquisition (`landing_viewed`, `cta_clicked`), activation (`agent_created`,- first-generation, checklist steps from prompt 33), conversion (the `token_*` and- pay/x402 events from prompt 35), retention (return visits, key surfaces opened via- `SURFACE_OPENED`, share actions). Add missing event names to `ANALYTICS_EVENTS` and- wire them into `FUNNELS` so PostHog funnel insights line up automatically.-3. **One taxonomy, no drift.** All events go through the validating `track()` /- `trackFunnelStep()` facade — no raw `window.posthog.capture()` ad-hoc strings in- feature code. Names are snake_case and live only in `ANALYTICS_EVENTS`.-4. **PII audit — hard requirement.** No raw wallet addresses, emails, prompt text, or- tokens as event props. Truncate wallets with `shortWallet()`; drop free-text- prompts (send a length/category, not content). Verify `person_profiles:- 'identified_only'` and that `identifyUser()` is called only after auth resolves- with non-PII identifiers. Reconcile with `public/legal/privacy.html`.-5. **Fail-safe by design.** Every analytics call must no-op when PostHog is absent or- blocked (`window.__posthog_blocked`) — verify the app works identically with an ad- blocker on, in an embed iframe, and offline. Analytics can never break the page.-6. **Verify events fire in a browser** (`npm run dev`): with PostHog network calls- visible, walk landing → create → a free generation → a pay flow and confirm each- expected event fires once with correct, PII-free props. Confirm dedupe (e.g.- `LANDING_VIEWED` fires exactly once).-7. **Dashboards/funnels.** Document the canonical activation, conversion, and- retention funnels (the `FUNNELS` map is the contract) so PostHog funnel/insight- definitions match the code. Keep this in the existing analytics docs, not a new- throwaway file.-8. **Test + changelog.** Run touched tests (`npx vitest run`, including any- `tests/**/analytics*`); add a `data/changelog.json` entry only if a user-visible- surface changed (pure instrumentation is internal and usually skips the changelog —- see `/CLAUDE.md`). Run `npm run build:pages` if you touched anything that feeds it.--## Must-not--- Do not send PII as event props — no raw wallets, emails, prompt/message text, or- tokens. Truncate and categorize.-- Do not bypass the `track()` facade with ad-hoc `posthog.capture()` calls or invent- event names outside `ANALYTICS_EVENTS`.-- Do not add a second analytics vendor, advertising pixel, or fingerprinting — stay- within the existing PostHog + Vercel stack and the privacy policy.-- Do not let an analytics failure (blocked/offline/embed) break or block the app.-- Do not reference any coin other than `$THREE` in event names or props.--## Acceptance (all true before claiming done)--- [ ] Every funnel stage (acquisition → activation → conversion → retention) emits a- taxonomy event through `track()` / `trackFunnelStep()`; gaps closed.-- [ ] No ad-hoc event strings or raw `posthog.capture()` in feature code; all names in- `ANALYTICS_EVENTS`.-- [ ] PII audit passes — no raw wallets/emails/prompt text/tokens in any event;- consistent with `public/legal/privacy.html`.-- [ ] App behaves identically with PostHog blocked, in an embed iframe, and offline- (no errors, no broken flows).-- [ ] Each expected event verified firing once with PII-free props in a real browser- session.-- [ ] `FUNNELS` matches documented PostHog funnels; docs updated in place (no- throwaway file).-- [ ] Touched tests pass; changelog handled per `/CLAUDE.md` and `npm run build:pages`- clean if it was touched.diff --git a/workers/agent-mm/config.js b/workers/agent-mm/config.jsnew file mode 100644index 000000000..17f61a771--- /dev/null+++ b/workers/agent-mm/config.js@@ -0,0 +1,62 @@+// agent-mm — environment + runtime configuration for the autonomous fair-launch+// market-maker worker. Validated once at boot so a misconfigured worker fails+// loudly instead of running half a config. Long-lived process (NOT a Vercel+// cron): every cfg.pollMs it sweeps active policies and re-quotes each coin.+//+// MM_MODE=simulate — real quotes + full decision logic, no broadcast (default)+// MM_MODE=live — real floor-defense / recycle fills from agent wallets+// MM_GLOBAL_KILL=1 — halt all MM actions (policies untouched; kill/withdraw still work)++function req(name) {+ const v = process.env[name];+ if (!v || !String(v).trim()) throw new Error(`[agent-mm] missing required env var: ${name}`);+ return v;+}+function num(name, def) {+ const raw = process.env[name];+ if (raw == null || raw === '') return def;+ const n = Number(raw);+ return Number.isFinite(n) ? n : def;+}+function bool(name, def = false) {+ const raw = process.env[name];+ if (raw == null || raw === '') return def;+ return /^(1|true|yes|on)$/i.test(String(raw).trim());+}++export function loadConfig() {+ // DATABASE_URL + JWT_SECRET are consumed transitively by db.js / agent-wallet.js.+ req('DATABASE_URL');+ req('JWT_SECRET');++ const network = (process.env.MM_NETWORK || 'mainnet').trim();+ if (network !== 'mainnet' && network !== 'devnet') {+ throw new Error(`[agent-mm] MM_NETWORK must be mainnet|devnet, got "${network}"`);+ }+ const mode = (process.env.MM_MODE || 'simulate').trim();+ if (mode !== 'live' && mode !== 'simulate') {+ throw new Error(`[agent-mm] MM_MODE must be live|simulate, got "${mode}"`);+ }+ // A live worker on a public RPC will rate-limit under continuous re-quote load —+ // refuse to start live without a real endpoint rather than silently dropping fills.+ if (mode === 'live' && !process.env.SOLANA_RPC_URL && !process.env.HELIUS_API_KEY) {+ throw new Error('[agent-mm] live mode requires SOLANA_RPC_URL or HELIUS_API_KEY (public RPC will rate-limit)');+ }++ return {+ network,+ mode,+ // Emergency stop — halt all MM actions while leaving policies intact+ // (the owner can still kill / withdraw via the API).+ globalKill: bool('MM_GLOBAL_KILL', false),+ // Policy re-quote / decision cadence. The per-policy min_action_interval is+ // the real rate limit on actions; this is just how often we re-evaluate.+ pollMs: Math.max(5_000, num('MM_POLL_MS', 15_000)),+ // Policies evaluated in parallel per sweep (each agent's actions run serially).+ concurrency: Math.max(1, Math.min(16, num('MM_CONCURRENCY', 4))),+ // Liveness heartbeat into bot_heartbeat (shared ops visibility). 0 disables.+ heartbeatMs: Math.max(0, num('MM_HEARTBEAT_MS', 30_000)),+ // Window (seconds) over which "live volume" is measured for the volume cap.+ volumeWindowSeconds: Math.max(60, num('MM_VOLUME_WINDOW_S', 300)),+ };+}diff --git a/workers/agent-mm/engine.js b/workers/agent-mm/engine.jsnew file mode 100644index 000000000..d417e8348--- /dev/null+++ b/workers/agent-mm/engine.js@@ -0,0 +1,350 @@+// agent-mm — the market-maker decision engine.+//+// For one policy this sweep: re-quote the coin (curve pre-grad, AMM post-grad),+// snapshot inventory, run the graduation transition once, then pick AT MOST ONE+// bounded, non-reflexive action — seed → defend → recycle → rebalance — and fire+// it through executeAgentTrade (the same firewall + spend-guard + custody path a+// manual trade uses). The engine adds NO new way to move funds; it only decides+// WHEN and HOW MUCH, inside the policy's published limits.+//+// Anti-manipulation is enforced HERE, in code, every action:+// • interval gate — no action, and NEVER a side flip, inside min_action_interval+// (× a multiple for flips). The MM physically cannot wash-trade / round-trip.+// • volume cap — a single action can't exceed max_volume_pct of LIVE volume; if+// volume can't be measured, it won't act above a tiny conservative slice (it+// never paints a no-volume tape).+// • bounded sizing — defend buys are capped by the dip budget, daily budget,+// wallet SOL, and the inventory ceiling; recycle sells by recycle_pct and the+// volume cap. Nothing is reflexive; it never chases.++import { executeAgentTrade, parseTradeInput } from '../../api/agents/agent-trade.js';+import { getTradeLimits } from '../../api/_lib/agent-trade-guards.js';+import { GUARDS, SOL } from '../../api/_lib/market-maker.js';+import { quoteMarket, getHolding, getSolBalanceLamports, getWindowVolumeLamports } from './market.js';+import { provideLp } from './graduation.js';+import {+ markEvaluated, recordActionAndAdvance, markSeedDone, markGraduation,+ getDeployedLamports24h, getDefenseLamports24h,+} from './store.js';+import { log } from './log.js';++const MIN_TRADE_LAMPORTS = BigInt(GUARDS.MIN_TRADE_LAMPORTS);+const WALLET_HEADROOM_LAMPORTS = 5_000_000n; // leave 0.005 SOL for fees++function lamports(sol) { return BigInt(Math.max(0, Math.round(sol * SOL))); }+function bigMin(...xs) { return xs.reduce((a, b) => (a < b ? a : b)); }++/**+ * Evaluate + (maybe) act on one policy. `agent` is { id, userId, meta }. Returns+ * a short outcome tag for logging. Never throws past the per-policy try in the+ * sweep — a single policy's failure can't abort the others.+ */+export async function runPolicy({ cfg, policy, agent }) {+ const network = policy.network;+ const mint = policy.mint;+ const owner = agent.meta?.solana_address || null;+ // LIVE only when BOTH the worker and the policy are live; otherwise the full+ // logic runs against real quotes but never signs or spends (clearly labeled).+ const simulate = !(cfg.mode === 'live' && policy.mode === 'live');+ const tag = { policy: policy.id, mint, mode: simulate ? 'simulate' : 'live' };++ if (!owner || !agent.meta?.encrypted_solana_secret) {+ await markEvaluated(policy.id, { error: 'no_wallet' });+ return 'no_wallet';+ }++ const market = await quoteMarket({ network, mint });+ if (!market || !(market.price_sol > 0)) {+ await markEvaluated(policy.id, { error: 'no_price' });+ return 'no_price';+ }+ const price = market.price_sol; // SOL per whole token++ const holding = await getHolding({ network, mint, owner });+ const inventoryWhole = holding?.whole ?? 0;+ const inventoryRaw = holding?.raw ?? 0n;+ const inventoryValueLamports = lamports(inventoryWhole * price);+ await markEvaluated(policy.id, { priceSol: price, inventoryTokens: inventoryWhole, inventoryValueLamports, error: null });++ const solBal = (await getSolBalanceLamports({ network, owner })) ?? 0n;++ // ── graduation transition (once) ──────────────────────────────────────────+ if (market.graduated && !policy.graduation_done_at) {+ return runGraduation({ cfg, policy, agent, price, inventoryWhole, inventoryRaw, solBal, simulate, tag });+ }++ // ── decide intent (priority: seed → defend → recycle → rebalance) ─────────+ const slippageBps = Math.round(Number(policy.slippage_bps) || 500);+ const floorPrice = Number(policy.floor_price_sol) || 0;+ const floorBand = Number(policy.floor_band_pct) || 0;+ const takeBand = Number(policy.take_profit_band_pct) || 0;+ const recyclePct = Number(policy.recycle_pct) || 0;+ const maxInv = Number(policy.max_inventory_tokens) || 0;++ const floorTrigger = floorPrice * (1 - floorBand / 100);+ const takeTrigger = floorPrice * (1 + takeBand / 100);++ let intent = null; // { kind, side, lamports?|tokens?, reason }+ if (Number(policy.seed_lamports) > 0 && !policy.seed_done_at) {+ intent = { kind: 'seed', side: 'buy', lamports: BigInt(policy.seed_lamports), reason: 'seed_initial_liquidity' };+ } else if (floorPrice > 0 && price <= floorTrigger) {+ // Defend: buy a measured slice. The per-action slice is a quarter of the dip+ // budget (defend in tranches, never the whole budget at once).+ const dipBudget = BigInt(policy.dip_buy_budget_lamports);+ const slice = dipBudget > 0n ? dipBudget / 4n : lamports(0.02);+ intent = { kind: 'defend_buy', side: 'buy', lamports: slice, reason: `price ${price.toExponential(3)} ≤ floor band ${floorTrigger.toExponential(3)}` };+ } else if (takeBand >= 0 && price >= takeTrigger && inventoryWhole > 0) {+ const tokens = inventoryWhole * (recyclePct / 100);+ if (tokens > 0) intent = { kind: 'recycle_sell', side: 'sell', tokens, reason: `price ${price.toExponential(3)} ≥ take band ${takeTrigger.toExponential(3)}` };+ } else if (maxInv > 0 && inventoryWhole > maxInv) {+ const tokens = inventoryWhole - maxInv;+ intent = { kind: 'rebalance_trim', side: 'sell', tokens, reason: `inventory ${inventoryWhole.toFixed(2)} > ceiling ${maxInv.toFixed(2)}` };+ }++ if (!intent) return 'in_band'; // nothing to do — markEvaluated already recorded the heartbeat++ // ── anti-manipulation: interval + side-flip gate ──────────────────────────+ const interval = Number(policy.min_action_interval_seconds) || 60;+ const lastAt = policy.last_action_at ? new Date(policy.last_action_at).getTime() : 0;+ const sinceSec = lastAt ? (Date.now() - lastAt) / 1000 : Infinity;+ if (sinceSec < interval) {+ return skip({ policy, intent, price, status: 'skipped', detail: `interval guard — ${Math.ceil(interval - sinceSec)}s until next action allowed`, reason: 'interval_guard' });+ }+ if (policy.last_action_side && policy.last_action_side !== intent.side && sinceSec < interval * GUARDS.SIDE_FLIP_INTERVAL_MULTIPLE) {+ return skip({ policy, intent, price, status: 'blocked', detail: `anti-wash guard — a ${intent.side} cannot follow a ${policy.last_action_side} within ${interval * GUARDS.SIDE_FLIP_INTERVAL_MULTIPLE}s`, reason: 'anti_wash_guard' });+ }++ // ── anti-manipulation: live-volume cap (lamports per action) ──────────────+ const windowVol = await getWindowVolumeLamports({ mint, windowSeconds: cfg.volumeWindowSeconds });+ const volumeCapLamports = windowVol == null+ ? BigInt(GUARDS.NO_VOLUME_FALLBACK_LAMPORTS)+ : (windowVol * BigInt(Math.round(Number(policy.max_volume_pct) * 1000))) / 100000n;+ const volumeUnmeasured = windowVol == null;++ // ── size + execute ────────────────────────────────────────────────────────+ if (intent.side === 'buy') {+ return doBuy({ cfg, policy, agent, intent, price, inventoryWhole, maxInv, solBal, volumeCapLamports, volumeUnmeasured, slippageBps, simulate, tag });+ }+ return doSell({ cfg, policy, agent, intent, price, inventoryWhole, inventoryRaw, volumeCapLamports, volumeUnmeasured, slippageBps, simulate, tag });+}++// ── buys (seed + defend) ──────────────────────────────────────────────────────+async function doBuy({ cfg, policy, agent, intent, price, inventoryWhole, maxInv, solBal, volumeCapLamports, volumeUnmeasured, slippageBps, simulate, tag }) {+ let size = intent.lamports;++ // Daily budget (all buys) and dip budget (defense only), measured rolling-24h.+ const dailyBudget = BigInt(policy.daily_budget_lamports);+ if (dailyBudget > 0n) {+ const deployed = await getDeployedLamports24h(policy.id);+ const remaining = dailyBudget > deployed ? dailyBudget - deployed : 0n;+ if (remaining <= 0n) return skip({ policy, intent, price, status: 'skipped', detail: 'daily budget exhausted (24h)', reason: 'daily_budget' });+ size = bigMin(size, remaining);+ }+ if (intent.kind === 'defend_buy') {+ const dipBudget = BigInt(policy.dip_buy_budget_lamports);+ if (dipBudget > 0n) {+ const spent = await getDefenseLamports24h(policy.id);+ const remaining = dipBudget > spent ? dipBudget - spent : 0n;+ if (remaining <= 0n) return skip({ policy, intent, price, status: 'skipped', detail: 'dip-buy budget exhausted (24h)', reason: 'dip_budget' });+ size = bigMin(size, remaining);+ }+ }++ // Inventory ceiling — never buy past it.+ if (maxInv > 0) {+ const headroomTokens = maxInv - inventoryWhole;+ if (headroomTokens <= 0) return skip({ policy, intent, price, status: 'skipped', detail: 'at inventory ceiling', reason: 'at_max_inventory' });+ size = bigMin(size, lamports(headroomTokens * price));+ }++ // Volume cap — the maker can't be more than max_volume_pct of live volume.+ size = bigMin(size, volumeCapLamports);++ // Wallet SOL headroom (leave fees).+ const spendable = solBal > WALLET_HEADROOM_LAMPORTS ? solBal - WALLET_HEADROOM_LAMPORTS : 0n;+ if (spendable <= 0n) return skip({ policy, intent, price, status: 'skipped', detail: 'wallet has no spendable SOL', reason: 'insufficient_sol' });+ size = bigMin(size, spendable);++ if (size < MIN_TRADE_LAMPORTS) {+ const reason = volumeUnmeasured ? 'volume_unmeasured' : 'below_min';+ return skip({ policy, intent, price, status: 'skipped', detail: volumeUnmeasured ? 'live volume unmeasured — holding to the conservative no-volume slice' : 'sized below the dust floor', reason });+ }++ const body = { mint: policy.mint, network: policy.network, side: 'buy', amount: Number(size) / SOL, slippageBps };+ return execute({ cfg, policy, agent, intent, price, body, sizeLamports: size, simulate, tag });+}++// ── sells (recycle + rebalance) ──────────────────────────────────────────────+async function doSell({ cfg, policy, agent, intent, price, inventoryWhole, inventoryRaw, volumeCapLamports, volumeUnmeasured, slippageBps, simulate, tag }) {+ let tokens = Math.min(intent.tokens, inventoryWhole);+ if (!(tokens > 0)) return skip({ policy, intent, price, status: 'skipped', detail: 'no inventory to sell', reason: 'no_inventory' });++ // Volume cap → max tokens this action.+ const capTokens = Number(volumeCapLamports) / SOL / price;+ if (capTokens < tokens) tokens = capTokens;++ const sizeLamports = lamports(tokens * price);+ if (sizeLamports < MIN_TRADE_LAMPORTS) {+ const reason = volumeUnmeasured ? 'volume_unmeasured' : 'below_min';+ return skip({ policy, intent, price, status: 'skipped', detail: volumeUnmeasured ? 'live volume unmeasured — holding to the conservative no-volume slice' : 'sized below the dust floor', reason });+ }++ // Sell whole tokens (executeAgentTrade resolves the base units + venue).+ const body = { mint: policy.mint, network: policy.network, side: 'sell', amount: tokens, slippageBps };+ return execute({ cfg, policy, agent, intent, price, body, sizeLamports, tokens, simulate, tag });+}++// ── execute through the shared, audited trade path ────────────────────────────+async function execute({ cfg, policy, agent, intent, price, body, sizeLamports, tokens = null, simulate, tag }) {+ const tradeLimits = getTradeLimits(agent.meta);+ let input;+ try {+ input = parseTradeInput(body, tradeLimits);+ } catch (e) {+ return skip({ policy, intent, price, status: 'failed', detail: `invalid trade: ${e?.code || e?.message || 'error'}`, reason: 'invalid_trade' });+ }+ // Idempotency bucket = the interval window, so two overlapping sweeps can't+ // double-fire the same action; a fresh window allows the next one.+ const bucket = Math.floor(Date.now() / (Math.max(30, Number(policy.min_action_interval_seconds) || 60) * 1000));+ input.idempotencyKey = `mm:${policy.id}:${intent.kind}:${bucket}`;+ input.simulate = simulate;++ let result;+ try {+ result = await executeAgentTrade({+ id: agent.id, userId: agent.userId, meta: agent.meta, input,+ source: `mm:${intent.kind}`, sourceMeta: { policy_id: policy.id, mint: policy.mint },+ });+ } catch (e) {+ return skip({ policy, intent, price, status: 'failed', detail: `execute crashed: ${e?.message?.slice(0, 120) || 'error'}`, reason: 'execute_error' });+ }++ if (!result.ok) {+ const status = result.code === 'firewall_blocked' ? 'blocked' : 'failed';+ await recordActionAndAdvance({+ policy,+ action: { kind: intent.kind, side: body.side, triggerReason: intent.reason, priceSol: price, status, detail: `${result.code}: ${result.message || ''}`.slice(0, 280), meta: { code: result.code } },+ });+ log.warn('mm action blocked', { ...tag, kind: intent.kind, code: result.code });+ return result.code || 'failed';+ }++ const d = result.data || {};+ const isSim = d.simulated === true || simulate;+ const status = isSim ? 'simulated' : 'executed';+ const solMoved = body.side === 'buy'+ ? (isSim ? Number(sizeLamports) : Math.round((d.sol_spent ?? 0) * SOL))+ : (isSim ? Number(sizeLamports) : Math.round((d.sol_received ?? 0) * SOL));+ const tokenAmount = body.side === 'buy'+ ? (d.tokens_received != null ? Number(d.tokens_received) / 1e6 : null)+ : (tokens ?? null);++ await recordActionAndAdvance({+ policy,+ action: {+ kind: intent.kind, side: body.side, triggerReason: intent.reason, priceSol: price,+ solLamports: solMoved, tokenAmount, priceImpactPct: d.price_impact_pct ?? null,+ venue: d.venue || null, signature: d.signature && d.signature !== 'SIMULATED' ? d.signature : null,+ custodyEventId: d.custody_event_id ?? null, status,+ detail: isSim ? 'paper fill (simulate)' : null, meta: { mode: isSim ? 'simulate' : 'live' },+ },+ effect: { solLamports: solMoved },+ });+ if (intent.kind === 'seed') await markSeedDone(policy.id);+ log.trade('mm action', { ...tag, kind: intent.kind, side: body.side, status, sol: solMoved / SOL, sig: d.signature || null, impact: d.price_impact_pct ?? null });+ return intent.kind;+}++// ── graduation transition (provide_lp | distribute | hold) ────────────────────+async function runGraduation({ cfg, policy, agent, price, inventoryWhole, inventoryRaw, solBal, simulate, tag }) {+ const action = policy.graduation_action || 'hold';+ const slippagePct = (Number(policy.slippage_bps) || 500) / 100;+ log.info('graduation transition', { ...tag, action });++ if (action === 'hold') {+ await recordActionAndAdvance({ policy, action: { kind: 'graduation_hold', triggerReason: 'graduated', priceSol: price, status: 'executed', detail: 'holding inventory; continuing two-sided on the AMM' } });+ await markGraduation(policy.id, { status: 'done', terminal: false });+ return 'graduation_hold';+ }++ if (action === 'provide_lp') {+ if (!(inventoryWhole > 0)) {+ await recordActionAndAdvance({ policy, action: { kind: 'graduation_lp', triggerReason: 'graduated', priceSol: price, status: 'skipped', detail: 'no inventory to provide as LP' } });+ await markGraduation(policy.id, { status: 'done', terminal: true });+ return 'graduation_lp_empty';+ }+ try {+ const lp = await provideLp({+ network: policy.network, mint: policy.mint, meta: agent.meta, userId: agent.userId, agentId: agent.id,+ inventoryRaw, walletLamports: solBal, slippagePct, confirmTimeoutMs: 60_000, simulate,+ });+ await recordActionAndAdvance({+ policy,+ action: {+ kind: 'graduation_lp', triggerReason: 'graduated', priceSol: price,+ solLamports: lp.quoteLamports, tokenAmount: Number(lp.baseDeposited) / 1e6, venue: 'lp',+ signature: lp.signature, status: lp.simulated ? 'simulated' : 'executed',+ detail: lp.simulated ? 'paper LP deposit (simulate)' : 'provided LP into the canonical AMM pool',+ meta: { base_deposited: lp.baseDeposited, quote_lamports: lp.quoteLamports },+ },+ });+ await markGraduation(policy.id, { status: 'done', signature: lp.signature, terminal: true });+ log.trade('graduation lp', { ...tag, sig: lp.signature, base: lp.baseDeposited, quote: lp.quoteLamports, simulated: lp.simulated });+ return 'graduation_lp';+ } catch (e) {+ await recordActionAndAdvance({ policy, action: { kind: 'graduation_lp', triggerReason: 'graduated', priceSol: price, status: 'failed', detail: `${e?.code || e?.message || 'lp_failed'}`.slice(0, 280) } });+ await markGraduation(policy.id, { status: `failed:${e?.code || 'lp_failed'}`, terminal: false });+ log.warn('graduation lp failed (will retry)', { ...tag, code: e?.code, err: e?.message });+ return 'graduation_lp_failed';+ }+ }++ // distribute — liquidate the managed inventory back to SOL in the agent wallet+ // (the owner can then withdraw / distribute). Routed through the audited path.+ if (!(inventoryWhole > 0)) {+ await recordActionAndAdvance({ policy, action: { kind: 'graduation_distribute', triggerReason: 'graduated', priceSol: price, status: 'skipped', detail: 'no inventory to distribute' } });+ await markGraduation(policy.id, { status: 'done', terminal: true });+ return 'graduation_distribute_empty';+ }+ const body = { mint: policy.mint, network: policy.network, side: 'sell', amount: 'max', slippageBps: Math.round(Number(policy.slippage_bps) || 500) };+ const tradeLimits = getTradeLimits(agent.meta);+ let input;+ try { input = parseTradeInput(body, tradeLimits); }+ catch (e) {+ await markGraduation(policy.id, { status: `failed:${e?.code || 'invalid'}`, terminal: false });+ return 'graduation_distribute_failed';+ }+ input.idempotencyKey = `mm:${policy.id}:graduation_distribute`;+ input.simulate = simulate;+ let result;+ try {+ result = await executeAgentTrade({ id: agent.id, userId: agent.userId, meta: agent.meta, input, source: 'mm:graduation_distribute', sourceMeta: { policy_id: policy.id, mint: policy.mint } });+ } catch (e) {+ await markGraduation(policy.id, { status: `failed:${e?.message?.slice(0, 60) || 'error'}`, terminal: false });+ return 'graduation_distribute_failed';+ }+ if (!result.ok) {+ await recordActionAndAdvance({ policy, action: { kind: 'graduation_distribute', triggerReason: 'graduated', priceSol: price, side: 'sell', status: result.code === 'firewall_blocked' ? 'blocked' : 'failed', detail: `${result.code}: ${result.message || ''}`.slice(0, 280) } });+ await markGraduation(policy.id, { status: `failed:${result.code}`, terminal: false });+ return 'graduation_distribute_failed';+ }+ const d = result.data || {};+ const isSim = d.simulated === true || simulate;+ const solMoved = isSim ? lamports(inventoryWhole * price) : Math.round((d.sol_received ?? 0) * SOL);+ await recordActionAndAdvance({+ policy,+ action: { kind: 'graduation_distribute', side: 'sell', triggerReason: 'graduated', priceSol: price, solLamports: Number(solMoved), tokenAmount: inventoryWhole, venue: d.venue || 'amm', signature: d.signature && d.signature !== 'SIMULATED' ? d.signature : null, custodyEventId: d.custody_event_id ?? null, status: isSim ? 'simulated' : 'executed', detail: isSim ? 'paper distribute (simulate)' : 'liquidated inventory to SOL for distribution' },+ effect: { solLamports: Number(solMoved) },+ });+ await markGraduation(policy.id, { status: 'done', signature: d.signature || null, terminal: true });+ return 'graduation_distribute';+}++// Record a non-firing decision (gated / dust / etc.) to the transparent ledger.+async function skip({ policy, intent, price, status, detail, reason }) {+ await recordActionAndAdvance({+ policy,+ action: { kind: intent.kind, side: intent.side, triggerReason: intent.reason, priceSol: price, status, detail, meta: { reason } },+ });+ return reason;+}diff --git a/workers/agent-mm/graduation.js b/workers/agent-mm/graduation.jsnew file mode 100644index 000000000..81becb796--- /dev/null+++ b/workers/agent-mm/graduation.js@@ -0,0 +1,100 @@+// agent-mm — curve → AMM graduation transition.+//+// When a managed coin graduates off the bonding curve onto the canonical pump+// AMM pool, the engine runs the policy's configured graduation_action exactly+// once, so no inventory is left parked in the transition:+//+// provide_lp — deposit the managed inventory (paired with the SOL it requires)+// into the canonical AMM pool as real LP, using the SAME pool+// resolution + PumpAmmSdk the rest of the platform uses. Signed+// from the agent wallet through the protected execution engine.+// distribute — liquidate the managed inventory back to SOL in the agent wallet+// (returned to the owner for withdrawal/distribution). Routed+// through executeAgentTrade by the engine — no new fund path.+// hold — keep the inventory; the maker simply continues two-sided on the+// AMM. Records the handoff and returns control to the engine.+//+// Honest logging at each step; a failure is recorded and retried next sweep+// (never silently swallowed, never double-applied).++import { getAmmPoolState, getConnection } from '../../api/_lib/pump.js';+import { submitProtected } from '../../api/_lib/execution-engine.js';+import { recoverSolanaAgentKeypair } from '../../api/_lib/agent-wallet.js';+import { SOL } from './market.js';++// Leave enough SOL behind to cover rent + fees after pairing the LP deposit.+const SOL_HEADROOM_LAMPORTS = 5_000_000n; // 0.005 SOL++/**+ * Provide LP into the canonical AMM pool from the agent wallet. Deposits the+ * managed inventory paired with the SOL the pool requires, scaling the base down+ * if the wallet can't cover the full pair (so it always deposits the largest+ * balanced amount it can afford rather than failing). LIVE only — caller gates on+ * mode and passes simulate=true to dry-run the build without broadcasting.+ *+ * @returns {Promise<{ signature:string|null, baseDeposited:string, quoteLamports:string, simulated:boolean }>}+ */+export async function provideLp({ network, mint, meta, userId, agentId, inventoryRaw, walletLamports, slippagePct, confirmTimeoutMs, simulate }) {+ const [{ PumpAmmSdk, OnlinePumpAmmSdk }, BNmod] = await Promise.all([+ import('@pump-fun/pump-swap-sdk'),+ import('bn.js').then((m) => m.default || m),+ ]);+ const BN = BNmod;+ const connection = getConnection({ network });++ const amm = await getAmmPoolState({ network, mint }); // throws pool_not_found if not graduated+ const offline = new PumpAmmSdk();+ const online = new OnlinePumpAmmSdk(connection);++ const ownerKeypair = await recoverSolanaAgentKeypair(meta.encrypted_solana_secret, {+ agentId, userId, reason: 'mm:graduation_lp', meta: { mint, network, venue: 'lp' },+ });+ const ownerPk = ownerKeypair.publicKey;++ const liqState = await online.liquiditySolanaState(amm.poolKey, ownerPk);++ let base = new BN(BigInt(inventoryRaw).toString());+ if (base.lten(0)) {+ const e = new Error('no inventory to provide as LP');+ e.code = 'no_inventory';+ throw e;+ }++ // How much SOL the full inventory deposit would require, then scale down to fit+ // the wallet's spendable SOL (minus headroom) so we deposit the largest+ // balanced pair we can actually afford.+ let auto = offline.depositAutocompleteQuoteAndLpTokenFromBase(liqState, base, slippagePct);+ const spendable = BigInt(walletLamports) > SOL_HEADROOM_LAMPORTS ? BigInt(walletLamports) - SOL_HEADROOM_LAMPORTS : 0n;+ let requiredQuote = BigInt(auto.quote.toString());+ if (requiredQuote > spendable) {+ if (spendable <= 0n) {+ const e = new Error('insufficient SOL to pair any LP deposit');+ e.code = 'insufficient_sol';+ throw e;+ }+ // Scale base proportionally to the affordable quote, then recompute exactly.+ const scaled = (BigInt(base.toString()) * spendable) / requiredQuote;+ base = new BN(scaled.toString());+ if (base.lten(0)) {+ const e = new Error('scaled LP deposit rounds to zero');+ e.code = 'insufficient_sol';+ throw e;+ }+ auto = offline.depositAutocompleteQuoteAndLpTokenFromBase(liqState, base, slippagePct);+ requiredQuote = BigInt(auto.quote.toString());+ }++ const instructions = await offline.depositInstructions(liqState, auto.lpToken, slippagePct);++ if (simulate) {+ return { signature: null, baseDeposited: base.toString(), quoteLamports: requiredQuote.toString(), simulated: true };+ }++ const result = await submitProtected({+ network, connection, payer: ownerKeypair, instructions,+ opts: { confirmTimeoutMs, tipMode: 'off' },+ });+ return { signature: result.signature, baseDeposited: base.toString(), quoteLamports: requiredQuote.toString(), simulated: false };+}++export { SOL_HEADROOM_LAMPORTS };diff --git a/workers/agent-mm/log.js b/workers/agent-mm/log.jsnew file mode 100644index 000000000..e529ea7b3--- /dev/null+++ b/workers/agent-mm/log.js@@ -0,0 +1,16 @@+// agent-mm — structured, single-line JSON logging. Keypairs/secrets never reach+// here; callers pass only ids, mints, amounts, and reasons.++function emit(level, msg, meta) {+ const rec = { t: new Date().toISOString(), level, msg, ...(meta || {}) };+ const line = JSON.stringify(rec);+ if (level === 'error' || level === 'warn') console.error(line);+ else console.log(line);+}++export const log = {+ info: (msg, meta) => emit('info', msg, meta),+ warn: (msg, meta) => emit('warn', msg, meta),+ error: (msg, meta) => emit('error', msg, meta),+ trade: (msg, meta) => emit('trade', msg, meta),+};diff --git a/workers/agent-mm/market.js b/workers/agent-mm/market.jsnew file mode 100644index 000000000..53f6011cc--- /dev/null+++ b/workers/agent-mm/market.js@@ -0,0 +1,123 @@+// agent-mm — live market reads for the market-maker engine.+//+// Every value is REAL on-chain or derived-from-on-chain data: price comes from a+// live bonding-curve quote (pre-graduation) or the canonical AMM pool reserves+// (post-graduation); inventory is the agent wallet's actual token balance; live+// volume comes from the same multi-source market feed the rest of the platform+// uses. A source that can't be read returns null and the engine stays honest —+// it never acts on absent data (and never paints a tape it can't measure).++import { getPumpTradeClient, getAmmPoolState, getConnection } from '../../api/_lib/pump.js';+import { fetchTokenMarketData } from '../../api/_lib/market/token-market.js';+import { solUsdPrice } from '../../api/_lib/avatar-wallet.js';+import { PublicKey } from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, getMint,+ TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++// pump.fun mints: fixed 1,000,000,000 supply, 6 decimals.+const TOTAL_SUPPLY_TOKENS = 1_000_000_000;+const TOKEN_DECIMALS = 6;+const SOL = 1_000_000_000;+// A tiny reference buy → near-spot marginal price with negligible impact.+const REF_LAMPORTS = 1_000_000n; // 0.001 SOL++/**+ * Live price + graduation state for a mint. price_sol is SOL per whole token.+ * Routes off the bonding curve, falling back to the canonical AMM pool once the+ * coin has graduated. Returns null on any quote failure so the engine treats it+ * as "skip this sweep", never as a price of 0.+ *+ * @returns {Promise<{ price_sol:number, graduated:boolean } | null>}+ */+export async function quoteMarket({ network, mint }) {+ let ctx;+ try { ctx = await getPumpTradeClient({ network }); } catch { return null; }+ const mintPk = new ctx.web3.PublicKey(mint);+ try {+ const q = await ctx.client.quoteForBuy({ mint: mintPk, quoteAmount: new ctx.BN(REF_LAMPORTS.toString()), slippagePct: 0 });+ const baseOut = Number(q.expectedBaseTokens.toString());+ if (!(baseOut > 0)) return null;+ const tokensOut = baseOut / 10 ** TOKEN_DECIMALS;+ const price_sol = (Number(REF_LAMPORTS) / SOL) / tokensOut;+ return { price_sol, graduated: false };+ } catch (err) {+ if (err?.name === 'CoinGraduatedError' || err?.code === 'CoinGraduated') {+ return quoteMarketAmm({ network, mint });+ }+ return null;+ }+}++// Price off live AMM pool reserves (post-graduation). price = quote/base.+async function quoteMarketAmm({ network, mint }) {+ try {+ const state = await getAmmPoolState({ network, mint });+ const base = Number(state.baseReserve.toString()) / 10 ** TOKEN_DECIMALS;+ const quote = Number(state.quoteReserve.toString()) / SOL;+ if (!(base > 0) || !(quote > 0)) return null;+ return { price_sol: quote / base, graduated: true };+ } catch {+ return null;+ }+}++/**+ * Live token holding for an owner — the MM's managed inventory. Returns whole ++ * raw base-unit balance + decimals, or null if the owner holds none / the mint+ * can't be read.+ */+export async function getHolding({ network, mint, owner }) {+ if (!owner) return null;+ const conn = getConnection({ network });+ const mintPk = new PublicKey(mint);+ const ownerPk = new PublicKey(owner);+ let mintAcc;+ try { mintAcc = await conn.getAccountInfo(mintPk); } catch { return null; }+ if (!mintAcc) return null;+ const tokenProgramId = mintAcc.owner.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;+ let decimals;+ try { decimals = (await getMint(conn, mintPk, 'confirmed', tokenProgramId)).decimals; } catch { return null; }+ const ata = getAssociatedTokenAddressSync(mintPk, ownerPk, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);+ let raw = 0n;+ try { raw = BigInt((await conn.getTokenAccountBalance(ata)).value.amount); } catch { raw = 0n; }+ const whole = Number(raw) / 10 ** decimals;+ return { whole, raw, decimals };+}++/** Live SOL balance (lamports) of an owner. Null on RPC failure. */+export async function getSolBalanceLamports({ network, owner }) {+ try {+ const conn = getConnection({ network });+ return BigInt(await conn.getBalance(new PublicKey(owner), 'confirmed'));+ } catch {+ return null;+ }+}++/**+ * Live market volume in lamports over the given window — the denominator for the+ * anti-manipulation volume cap. Derived from the multi-source market feed's 24h+ * volume (USD), scaled to the window and converted to lamports at the live SOL+ * price. Returns null when volume can't be read; the engine then refuses to act+ * on anything larger than a tiny conservative slice (it never paints a tape it+ * can't measure).+ *+ * @returns {Promise<bigint|null>} lamports of volume in the window+ */+export async function getWindowVolumeLamports({ mint, windowSeconds }) {+ let md;+ try { md = await fetchTokenMarketData(mint); } catch { return null; }+ const vol24hUsd = Number(md?.volume_24h);+ if (!Number.isFinite(vol24hUsd) || vol24hUsd <= 0) return null;+ let solUsd;+ try { solUsd = await solUsdPrice(); } catch { return null; }+ if (!(solUsd > 0)) return null;+ const windowUsd = vol24hUsd * (windowSeconds / 86_400);+ const windowSol = windowUsd / solUsd;+ const lamports = BigInt(Math.max(0, Math.round(windowSol * SOL)));+ return lamports;+}++export { TOTAL_SUPPLY_TOKENS, TOKEN_DECIMALS, SOL };diff --git a/workers/agent-mm/store.js b/workers/agent-mm/store.jsnew file mode 100644index 000000000..dc46d6577--- /dev/null+++ b/workers/agent-mm/store.js@@ -0,0 +1,100 @@+// agent-mm — policy reads + runtime state writes for the engine.+//+// Thin layer over the shared model (api/_lib/market-maker.js): the worker reads+// the active policy set, loads each agent's wallet meta, records every action to+// the transparent ledger, and advances the policy's runtime aggregates (realized+// PnL, deployed/recovered SOL, inventory snapshot, last-action stamps). Single-+// worker assumption (documented, mirrors agent-sniper/agent-orders): per-policy+// state is serialized in-process; the custody idempotency_key on each fill is the+// real cross-process double-spend backstop.++import { sql } from '../../api/_lib/db.js';+import { recordAction } from '../../api/_lib/market-maker.js';++export { getActivePolicies, getDeployedLamports24h, getDefenseLamports24h } from '../../api/_lib/market-maker.js';++/** Load (and lightly cache by the caller) an agent's meta + user for execution. */+export async function loadAgent(agentId) {+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;+ if (!row) return null;+ return { id: row.id, userId: row.user_id, meta: { ...(row.meta || {}) } };+}++/** Persist the per-sweep observation (price + inventory snapshot), fired or not. */+export async function markEvaluated(policyId, { priceSol = null, inventoryTokens = null, inventoryValueLamports = null, error = null } = {}) {+ await sql`+ UPDATE market_maker_policies SET+ last_eval_at = now(),+ last_price_sol = COALESCE(${priceSol}, last_price_sol),+ inventory_tokens = COALESCE(${inventoryTokens}, inventory_tokens),+ inventory_value_lamports = COALESCE(${inventoryValueLamports != null ? String(inventoryValueLamports) : null}, inventory_value_lamports),+ last_error = ${error}+ WHERE id = ${policyId}+ `;+}++/**+ * Record a material action to the ledger AND advance the policy's runtime+ * aggregates in one place. `effect.solLamports` is the gross SOL moved by the+ * fill. Realized PnL is tracked as honest NET CASH FLOW (recovered − deployed):+ * a buy deploys SOL (realized −=), a sell recovers SOL (realized +=). Combined+ * with the live inventory value the UI shows, total = realized + inventory_value.+ * Skips/blocked/failed actions are logged but never move aggregates.+ */+export async function recordActionAndAdvance({ policy, action, effect = null }) {+ const row = await recordAction({+ policyId: policy.id, mint: policy.mint, network: policy.network, ...action,+ });++ const material = ['executed', 'simulated'].includes(action.status) && (action.side === 'buy' || action.side === 'sell');+ if (!material) return row;++ const sol = BigInt(Math.max(0, Math.round(Number(effect?.solLamports || 0))));+ if (action.side === 'buy') {+ await sql`+ UPDATE market_maker_policies SET+ sol_deployed_lamports = sol_deployed_lamports + ${String(sol)},+ realized_pnl_lamports = realized_pnl_lamports - ${String(sol)},+ last_action_at = now(), last_action_side = 'buy', updated_at = now()+ WHERE id = ${policy.id}+ `;+ } else {+ await sql`+ UPDATE market_maker_policies SET+ sol_recovered_lamports = sol_recovered_lamports + ${String(sol)},+ realized_pnl_lamports = realized_pnl_lamports + ${String(sol)},+ last_action_at = now(), last_action_side = 'sell', updated_at = now()+ WHERE id = ${policy.id}+ `;+ }+ return row;+}++/** Stamp the seed as done so it never fires twice. */+export async function markSeedDone(policyId) {+ await sql`UPDATE market_maker_policies SET seed_done_at = now() WHERE id = ${policyId} AND seed_done_at IS NULL`;+}++/**+ * Mark the graduation transition complete (or failed). On a terminal action+ * (provide_lp / distribute) the policy moves to 'graduated' and disables further+ * active trading; 'hold' records the handoff but keeps the maker two-sided on the+ * AMM. Always advances graduation_done_at so the transition runs exactly once.+ */+export async function markGraduation(policyId, { status, signature = null, terminal = false }) {+ if (terminal) {+ await sql`+ UPDATE market_maker_policies SET+ graduation_done_at = now(), graduation_status = ${status}, graduation_signature = ${signature},+ status = 'graduated', enabled = false, updated_at = now()+ WHERE id = ${policyId}+ `;+ return;+ }+ await sql`+ UPDATE market_maker_policies SET+ graduation_done_at = now(), graduation_status = ${status}, graduation_signature = ${signature},+ updated_at = now()+ WHERE id = ${policyId}+ `;+}