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
feat: add alpha_hunt strategy scorer for low-cap coins with buying activity
qrqk52f7c652a15d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d4c430a8..a47356ac4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,14 +6,17 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-26+- **Agent Payment Sessions** (`/payments`) — Create budget-limited payment sessions for AI agents. Governance-enforced spend limits, URL allowlists, and expiry — agents pay x402 APIs without holding a private key.- **Agent Screen** (`/agent-screen`) — Watch your agent work in real time — split view with the agent's live screen on the left and their 3D avatar rendered as a webcam on the right.- **Avatar Engines Atlas** (`/avatar-engines`) — A curated, factual atlas of the open-source and commercial engines that build high-quality and photoreal 3D human avatars — Gaussian-splat heads, single-photo humans, text→avatar generators, and the rigs three.ws already animates. Technique, license, compute, and integration status for each.- **Integrations** (`/integrations`) — Drop-in 3D agents, chat widgets, walk companions, and live token embeds for any site. One script tag. Powered by three.ws.- **Splat Viewer — Photoreal Gaussian Avatars** (`/splat`) — Render Gaussian-splat and radiance-field avatars in the browser — the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.- **3D avatars look brighter and more lifelike everywhere — new studio lighting rig** — Auto-generated avatars used to render dark and flat in the gallery — dark-clothed agents could all but disappear into the black cards. The 3D viewer now lights every avatar with a proper studio three-point rig (key, fill, and a rim/back light that traces a bright edge around the silhouette so no avatar blends into the background), boosted ambient and image-based lighting, and the Khronos PBR-Neutral tone mapper, which keeps colors bright and true instead of crushing them. The preview-card edge vignette was softened so small thumbnails no longer look murky. The same rig now also drives the server-rendered poster images used for share cards and gallery warm-up, so avatars look consistent and vivid the instant they appear. `[improvement]`+- **4 new agent capabilities: Alpha Hunt, Coin Launcher, Creator Auto-Claim, and Market Maker** — Agents can now do a lot more. Alpha Hunt is a new strategy trigger that scores coins using smart-money signals, organic growth patterns, quality scores, and narrative keywords — finding undervalued gems before they move. Coin Launcher lets an agent autonomously launch coins on pump.fun on a schedule, with configurable metadata templates, initial dev buys, and Telegram notifications. Creator Auto-Claim watches your agent's launched coins and automatically claims creator fees when they exceed a configurable threshold, with optional reinvestment into the sniper buy budget. Market Maker uses Jito-accelerated execution to provide liquidity on any pump.fun coin, placing buy and sell orders in a configured spread band to capture the spread. All four capabilities are wired into the agent-sniper worker and configurable from the agent edit page. (`/play`) `[feature]`- **A stale Arena link no longer dead-ends on a 'not found' screen** — Opening a shared tournament link after the competition has ended or rolled off used to leave you stranded on a bare 'Tournament not found' page whose only button was a Retry that could never work. Now that case turns into a way forward: a clear explanation plus a live grid of the tournaments running and starting right now, so there's always something to jump into. Genuine connection hiccups (as opposed to a missing tournament) keep a Retry alongside a 'Back to all tournaments' escape hatch. Every tournament page also gets a Share button that copies its link, sets a proper browser-tab title, and scrolls cleanly to the top as you move between views. (`/arena`) `[fix, improvement]`- **Agent Activity is now a live trading floor — Conviction Board rail, richer trade detail and a real KPI bar that never shows an empty void** — The /activity page used to go blank whenever no agent had traded recently. It no longer does. A new Conviction Board rail sits alongside the feed with three always-on cards: Top Agents ranked by win rate and ROI, the biggest 24-hour conviction movers, and the best proven wins by ATH multiple — so there's live signal to act on even between trades. An insight strip surfaces the single standout in each. The KPI bar now reads from the Oracle stats engine, so Agents armed, Coins scored 24h, Open positions, Win rate and Best ATH show real numbers immediately. Each action row gained detail it always had but never displayed: the entry market cap, the agent's reason for the trade, how long the position was held, peak multiple, and a one-click Solscan link for live fills. Plus a type-to-filter box (press /), an Escape-to-clear, a press-r refresh, a '↑ N new' jump pill when trades land while you've scrolled, and a designed empty state that points you to arm the first agent. (`/activity`) `[feature, improvement]`- **Agent editor redesigned — one unified page instead of 15 sidebar tabs** — The agent editor no longer makes you click through 15 tabs to configure your agent. Everything — Persona, Outfit, Voice, Brain, Knowledge, Mind Palace, Dreams, Skills, Autopilot, Publish, Embed, Widgets, Social, Monetization, Wallet, Analytics, Studio, and Danger zone — is now visible at once in a single scrollable page. The 3D avatar preview is pinned permanently on the left so you always see your agent while you work. A sticky section nav (Identity / Brain / Distribute / Money / Advanced) lets you jump to any area instantly. (`/agent-edit`) `[improvement]`+- **Agent Payment Sessions — governed x402 spend without private keys** — Agents can now pay x402 APIs without holding a private key. Create a Payment Session with a budget (drawn from credits), hand the token to an agent, and the platform signs every Solana USDC transfer. Five governance checks fire before any money moves: token auth, session status, URL allowlist, per-tx ceiling, and atomic budget reservation. Sessions expire automatically; un-spent budget is refunded on cancel. Also ships: a /payments dashboard to manage sessions and view payment history, and the @three-ws/agentcore-payments-mcp MCP server with create_payment_session, pay_with_session, check_payment_session, list_payment_sessions, and cancel_payment_session tools. (`/payments`) `[feature, sdk]`- **Agent profile pages no longer fail to load over a hiccup** — Opening an agent's profile (/agents/<id>) could show a full-page "Couldn't load this agent" error even when the agent was perfectly fine — a brief stumble in a side service (skill pricing, or the avatar self-heal check) was allowed to take down the whole profile. Those extras are now best-effort: if one can't answer in the moment, the page degrades gracefully and still renders the agent instead of erroring out. The page also quietly retries once on a transient network blip before ever showing the error screen, so cold loads and flaky connections recover on their own. (`/agents`) `[fix]`- **Agent profile pages render again** — Every agent profile (/agents/<id>) had stopped loading — the page sat on its loading skeleton and never revealed the agent. The cause was the new living, idle-animated 3D avatar on the profile: it sets up its 3D stage before the avatar model has loaded, and that setup step assumed a model was already present, throwing an error that took the whole page down with it. The setup now handles the not-yet-loaded state cleanly, so the profile renders immediately and the avatar comes to life as soon as its model arrives. Every agent page — custom avatar or default body — loads correctly again. (`/agents`) `[fix]`- **Agent Screen — watch your agent's live screen and avatar cam in 2D and in the 3D world** — Agents can now broadcast what they're doing in real time. On any agent's profile, a new Watch view shows a split-panel: left is the agent's live screen (browser screenshots streamed at up to 2fps), right is the agent's avatar rendered as a webcam feed. In /play, agents with active streams appear seated at physical desks — walk up and their monitor shows the live feed, with an overlay that links to the full Watch view. Agents push frames and activity narration via POST /api/agent-screen-push from any worker or script. The stream stays live as long as the agent is active; when it goes dark the screen shows a waiting state that resumes automatically. (`/agent-screen`) `[feature]`diff --git a/api/_lib/migrations/20260626010000_payment_sessions.sql b/api/_lib/migrations/20260626010000_payment_sessions.sqlnew file mode 100644index 000000000..0c634fdb4--- /dev/null+++ b/api/_lib/migrations/20260626010000_payment_sessions.sql@@ -0,0 +1,112 @@+-- Agent Payment Sessions — platform-funded spend envelopes for autonomous agents.+--+-- The core concept (borrowed from AWS AgentCore Payments patterns):+-- "The agent does not hold a wallet. It proposes spend. Governance enforces policy."+--+-- A PaymentSession lets a developer pre-fund a budget (drawn from their credits)+-- and give an agent a session token. The agent uses the token to call paid x402+-- endpoints via /api/pay/execute. The platform's own payer wallet executes the+-- on-chain transaction; the session atomically tracks spend and enforces limits.+--+-- This separates WALLET CUSTODY (platform holds keys) from BUDGET AUTHORITY+-- (developer sets limits per session) from EXECUTION (agent calls endpoints).+--+-- Schema:+-- id — UUID primary key, used as the session identifier in tokens+-- user_id — owner (who funded this session / whose credits are drawn)+-- agent_id — optional: which agent is authorized to use this session+-- label — human-readable name (e.g. "Research run #4")+-- budget_usdc — total budget in USDC atomic units (6 decimals)+-- spent_usdc — running spend counter (atomically incremented)+-- max_per_tx_usdc — optional per-payment ceiling (rejects over-priced endpoints)+-- allowed_hosts — if non-empty, only pay endpoints at these hosts (allowlist)+-- network — settlement network ('solana' or 'base')+-- connector_ref — opaque reference to which wallet/connector to use (null = platform default)+-- status — 'active' | 'exhausted' | 'expired' | 'cancelled'+-- expires_at — hard expiry; payments rejected after this time+-- token_hash — bcrypt hash of the bearer token (token itself never stored)+-- session_metadata — arbitrary JSON for caller bookkeeping+-- created_at / updated_at++create table if not exists payment_sessions (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid references agent_identities(id) on delete set null,++ label text not null default '',+ budget_usdc bigint not null check (budget_usdc > 0),+ spent_usdc bigint not null default 0 check (spent_usdc >= 0),+ max_per_tx_usdc bigint check (max_per_tx_usdc > 0),+ allowed_hosts text[] not null default '{}',+ network text not null default 'solana' check (network in ('solana', 'base')),+ connector_ref text,++ status text not null default 'active'+ check (status in ('active', 'exhausted', 'expired', 'cancelled')),+ expires_at timestamptz not null,+ token_hash text not null,++ session_metadata jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- Efficient lookup for active sessions by user+create index if not exists payment_sessions_user_status+ on payment_sessions (user_id, status, expires_at desc);++-- Efficient sweep of expired/exhausted sessions+create index if not exists payment_sessions_status_expires+ on payment_sessions (status, expires_at);++-- Agent-scoped lookup (which sessions is this agent authorized for)+create index if not exists payment_sessions_agent_id+ on payment_sessions (agent_id)+ where agent_id is not null;++-- Payment execution log — immutable record of every x402 payment made through a session.+--+-- Governs idempotency (idempotency_key prevents double-billing on retries),+-- provides the audit trail, and is the source-of-truth for reconciling+-- session.spent_usdc if needed.++create table if not exists payment_session_executions (+ id uuid primary key default gen_random_uuid(),+ session_id uuid not null references payment_sessions(id) on delete restrict,+ user_id uuid not null references users(id),++ -- The x402 endpoint that was paid+ endpoint_url text not null,+ endpoint_host text not null,+ method text not null default 'GET',++ -- Settlement details+ amount_usdc bigint not null check (amount_usdc > 0),+ network text not null,+ tx_hash text,+ payer_address text,+ payee_address text,++ -- Outcome+ status text not null default 'pending'+ check (status in ('pending', 'settled', 'failed', 'refunded')),+ error_code text,+ error_message text,+ response_body jsonb,+ duration_ms integer,++ idempotency_key text unique,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create index if not exists pse_session_id+ on payment_session_executions (session_id, created_at desc);++create index if not exists pse_user_id+ on payment_session_executions (user_id, created_at desc);++create index if not exists pse_endpoint_host+ on payment_session_executions (endpoint_host, created_at desc);++-- Idempotency index already covered by the UNIQUE constraint on idempotency_key.diff --git a/api/_lib/migrations/20260626200000_agent_capabilities.sql b/api/_lib/migrations/20260626200000_agent_capabilities.sqlnew file mode 100644index 000000000..97d3cb4bd--- /dev/null+++ b/api/_lib/migrations/20260626200000_agent_capabilities.sql@@ -0,0 +1,123 @@+-- 1. Add alpha_hunt as a valid trigger in agent_sniper_strategies.+-- The trigger column is text (no enum constraint), so we just document the new value.+-- Add alpha-hunt-specific gate columns:+ALTER TABLE agent_sniper_strategies+ ADD COLUMN IF NOT EXISTS alpha_min_smart_money INTEGER DEFAULT NULL,+ ADD COLUMN IF NOT EXISTS alpha_min_organic_score NUMERIC DEFAULT NULL,+ ADD COLUMN IF NOT EXISTS alpha_max_mcap_usd NUMERIC DEFAULT NULL,+ ADD COLUMN IF NOT EXISTS alpha_narrative_keywords TEXT[] DEFAULT NULL,+ ADD COLUMN IF NOT EXISTS alpha_min_quality_score INTEGER DEFAULT NULL;++-- 2. Launcher configs — one row per agent launch program+CREATE TABLE IF NOT EXISTS agent_launcher_configs (+ id BIGSERIAL PRIMARY KEY,+ agent_id UUID NOT NULL,+ user_id UUID NOT NULL,+ enabled BOOLEAN NOT NULL DEFAULT false,+ network TEXT NOT NULL DEFAULT 'mainnet',+ -- Schedule+ interval_hours NUMERIC DEFAULT NULL, -- null = manual only+ max_launches INTEGER DEFAULT NULL, -- null = unlimited+ -- Token metadata template+ name_template TEXT NOT NULL DEFAULT 'Agent Coin',+ symbol TEXT NOT NULL DEFAULT 'AGENT',+ description TEXT DEFAULT NULL,+ image_url TEXT DEFAULT NULL,+ twitter TEXT DEFAULT NULL,+ telegram TEXT DEFAULT NULL,+ website TEXT DEFAULT NULL,+ -- Initial dev buy+ initial_buy_sol NUMERIC NOT NULL DEFAULT 0,+ initial_buy_slippage_bps INTEGER NOT NULL DEFAULT 500,+ -- Auto-claim from launches+ auto_claim_enabled BOOLEAN NOT NULL DEFAULT false,+ auto_claim_threshold_sol NUMERIC NOT NULL DEFAULT 0.5,+ auto_claim_reinvest_pct INTEGER NOT NULL DEFAULT 0 CHECK (auto_claim_reinvest_pct BETWEEN 0 AND 100),+ -- State+ launches_count INTEGER NOT NULL DEFAULT 0,+ last_launched_at TIMESTAMPTZ DEFAULT NULL,+ next_launch_at TIMESTAMPTZ DEFAULT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS idx_agent_launcher_agent ON agent_launcher_configs(agent_id);+CREATE INDEX IF NOT EXISTS idx_agent_launcher_next ON agent_launcher_configs(next_launch_at) WHERE enabled = true;++-- 3. Track each coin an agent has launched+CREATE TABLE IF NOT EXISTS agent_launched_coins (+ id BIGSERIAL PRIMARY KEY,+ launcher_id BIGINT REFERENCES agent_launcher_configs(id) ON DELETE SET NULL,+ agent_id UUID NOT NULL,+ user_id UUID NOT NULL,+ network TEXT NOT NULL,+ mint TEXT NOT NULL,+ symbol TEXT NOT NULL,+ name TEXT NOT NULL,+ launch_sig TEXT DEFAULT NULL,+ -- Performance tracking+ peak_mcap_usd NUMERIC DEFAULT NULL,+ is_graduated BOOLEAN NOT NULL DEFAULT false,+ graduated_at TIMESTAMPTZ DEFAULT NULL,+ -- Creator fee state+ claimable_lamports BIGINT NOT NULL DEFAULT 0,+ total_claimed_lamports BIGINT NOT NULL DEFAULT 0,+ last_claim_sig TEXT DEFAULT NULL,+ last_claim_at TIMESTAMPTZ DEFAULT NULL,+ last_fee_check_at TIMESTAMPTZ DEFAULT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (mint, network)+);+CREATE INDEX IF NOT EXISTS idx_launched_coins_agent ON agent_launched_coins(agent_id);+CREATE INDEX IF NOT EXISTS idx_launched_coins_claim ON agent_launched_coins(agent_id, network) WHERE auto_claim_enabled OR launcher_id IS NOT NULL;++-- auto_claim_enabled column convenience (on the launcher drives per-coin default,+-- but allow per-coin override in agent_launched_coins):+ALTER TABLE agent_launched_coins+ ADD COLUMN IF NOT EXISTS auto_claim_enabled BOOLEAN NOT NULL DEFAULT false;++-- 4. Market maker configs — one per agent per coin+CREATE TABLE IF NOT EXISTS agent_market_maker_configs (+ id BIGSERIAL PRIMARY KEY,+ agent_id UUID NOT NULL,+ user_id UUID NOT NULL,+ enabled BOOLEAN NOT NULL DEFAULT false,+ network TEXT NOT NULL DEFAULT 'mainnet',+ mint TEXT NOT NULL,+ symbol TEXT DEFAULT NULL,+ -- Strategy parameters+ spread_bps INTEGER NOT NULL DEFAULT 200 CHECK (spread_bps >= 10),+ order_size_sol NUMERIC NOT NULL DEFAULT 0.05,+ max_inventory_sol NUMERIC NOT NULL DEFAULT 1.0,+ min_profit_bps INTEGER NOT NULL DEFAULT 50,+ rebalance_interval_ms INTEGER NOT NULL DEFAULT 10000,+ -- Execution+ mev_tip_mode TEXT NOT NULL DEFAULT 'economy' CHECK (mev_tip_mode IN ('off','economy','turbo')),+ -- Running totals+ total_buys INTEGER NOT NULL DEFAULT 0,+ total_sells INTEGER NOT NULL DEFAULT 0,+ total_volume_sol NUMERIC NOT NULL DEFAULT 0,+ total_pnl_sol NUMERIC NOT NULL DEFAULT 0,+ current_inventory_sol NUMERIC NOT NULL DEFAULT 0,+ last_tick_at TIMESTAMPTZ DEFAULT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (agent_id, mint, network)+);+CREATE INDEX IF NOT EXISTS idx_mm_agent ON agent_market_maker_configs(agent_id);+CREATE INDEX IF NOT EXISTS idx_mm_enabled ON agent_market_maker_configs(network) WHERE enabled = true;++-- 5. Market maker trade ledger+CREATE TABLE IF NOT EXISTS agent_market_maker_trades (+ id BIGSERIAL PRIMARY KEY,+ config_id BIGINT NOT NULL REFERENCES agent_market_maker_configs(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL,+ network TEXT NOT NULL,+ side TEXT NOT NULL CHECK (side IN ('buy','sell')),+ base_amount BIGINT NOT NULL,+ quote_lamports BIGINT NOT NULL,+ sig TEXT DEFAULT NULL,+ price_lamports_per_token NUMERIC DEFAULT NULL,+ realized_pnl_lamports BIGINT DEFAULT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS idx_mm_trades_config ON agent_market_maker_trades(config_id, created_at DESC);diff --git a/api/_lib/pay/payment-session.js b/api/_lib/pay/payment-session.jsnew file mode 100644index 000000000..94a251f1a--- /dev/null+++ b/api/_lib/pay/payment-session.js@@ -0,0 +1,336 @@+// Payment Session CRUD — lifecycle management for Agent Payment Sessions.+//+// Sessions are the funding envelope for platform-managed agent payments.+// A developer creates a session with a budget (drawn from their credits),+// hands the session token to an agent, and the agent calls paid x402+// endpoints via /api/pay/execute without needing its own private key.+//+// Token design:+// - Generated as `pss_<sessionId>_<random32hex>`+// - Never stored plaintext; only the HMAC-SHA256 hash is persisted+// - Caller holds the token; server verifies it by hashing and comparing+//+// Budget accounting:+// - budget_usdc is USDC atomic units (6 decimals), matching the x402 standard+// - budget is drawn from the creator's credit balance at creation time+// - a cancelled/expired session refunds the un-spent portion back to credits++import { randomUUID } from 'node:crypto';+import { sql } from '../db.js';+import { debitCredits, creditAccount } from '../credits.js';+import {+ generateSessionToken,+ hashToken,+ usdToAtomics,+ atomicsToUsd,+ normalizeHost,+} from './spend-governor.js';++const MAX_LABEL_LEN = 120;+const MAX_ALLOWED_HOSTS = 50;+const MIN_BUDGET_USD = 0.001; // $0.001 minimum+const MAX_BUDGET_USD = 1000; // $1000 maximum per session+const MIN_TTL_SECONDS = 60;+const MAX_TTL_SECONDS = 90 * 24 * 3600; // 90 days++function bad(message, code = 'bad_request') {+ return Object.assign(new Error(message), { status: 400, code });+}++function normalizeTtl(ttlSeconds) {+ const n = Number(ttlSeconds ?? 3600);+ if (!Number.isFinite(n) || n < MIN_TTL_SECONDS || n > MAX_TTL_SECONDS) {+ throw bad(+ `expiry_seconds must be between ${MIN_TTL_SECONDS} and ${MAX_TTL_SECONDS}`,+ 'invalid_ttl',+ );+ }+ return Math.round(n);+}++function normalizeAllowedHosts(raw) {+ if (!raw) return [];+ const arr = Array.isArray(raw) ? raw : String(raw).split(/[\s,]+/);+ const hosts = arr.map(normalizeHost).filter(Boolean);+ if (hosts.length > MAX_ALLOWED_HOSTS)+ throw bad(`allowed_hosts may contain at most ${MAX_ALLOWED_HOSTS} entries`);+ return [...new Set(hosts)]; // deduplicate+}++function normalizeBudget(budgetUsd) {+ const n = Number(budgetUsd);+ if (!Number.isFinite(n) || n < MIN_BUDGET_USD || n > MAX_BUDGET_USD) {+ throw bad(+ `budget_usd must be between $${MIN_BUDGET_USD} and $${MAX_BUDGET_USD}`,+ 'invalid_budget',+ );+ }+ return n;+}++function normalizeMaxPerTx(maxPerTxUsd) {+ if (maxPerTxUsd == null) return null;+ const n = Number(maxPerTxUsd);+ if (!Number.isFinite(n) || n < 0.000001) throw bad('max_per_tx_usd must be > $0.000001');+ return n;+}++/**+ * Create a new payment session.+ *+ * @param {object} opts+ * @param {string} opts.userId - Creator's user ID+ * @param {string} [opts.agentId] - Optional: agent authorized to use this session+ * @param {string} [opts.label] - Human-readable label+ * @param {number} opts.budgetUsd - Total budget in USD+ * @param {number} [opts.maxPerTxUsd] - Per-payment ceiling in USD+ * @param {string[]} [opts.allowedHosts] - If set, only pay endpoints at these hosts+ * @param {string} [opts.network] - 'solana' | 'base' (default: 'solana')+ * @param {number} [opts.expirySeconds] - Session lifetime in seconds (default: 3600)+ * @param {object} [opts.metadata] - Arbitrary caller metadata+ * @returns {Promise<{ session: object, token: string }>}+ */+export async function createPaymentSession({+ userId,+ agentId,+ label,+ budgetUsd,+ maxPerTxUsd,+ allowedHosts,+ network = 'solana',+ expirySeconds,+ metadata = {},+}) {+ if (!userId) throw bad('userId is required');++ const budgetN = normalizeBudget(budgetUsd);+ const budgetAtomics = usdToAtomics(budgetN);+ const maxPerTxAtomics = maxPerTxUsd != null ? usdToAtomics(normalizeMaxPerTx(maxPerTxUsd)) : null;+ const hosts = normalizeAllowedHosts(allowedHosts);+ const ttl = normalizeTtl(expirySeconds);+ const net = network === 'base' ? 'base' : 'solana';+ const cleanLabel = String(label ?? '').trim().slice(0, MAX_LABEL_LEN);++ // Debit the budget from the user's credit balance up-front.+ // If the balance is insufficient, this throws a 402 from credits.js.+ const idempotencyKey = `paysess_create_${randomUUID()}`;+ await debitCredits({+ userId,+ amountUsd: budgetN,+ action: 'payment_session_create',+ refType: 'payment_session',+ refId: null, // filled in after INSERT+ idempotencyKey,+ });++ // Generate the bearer token (never stored; only its hash is persisted)+ // We generate the UUID first so we can include it in the token.+ const sessionId = randomUUID();+ const token = generateSessionToken(sessionId);+ const tokenHash = hashToken(token);++ const expiresAt = new Date(Date.now() + ttl * 1000);++ const [row] = await sql`+ INSERT INTO payment_sessions+ (id, user_id, agent_id, label, budget_usdc, max_per_tx_usdc,+ allowed_hosts, network, status, expires_at, token_hash, session_metadata)+ VALUES+ (${sessionId}, ${userId}, ${agentId ?? null},+ ${cleanLabel}, ${budgetAtomics.toString()},+ ${maxPerTxAtomics != null ? maxPerTxAtomics.toString() : null},+ ${hosts}, ${net}, 'active', ${expiresAt.toISOString()},+ ${tokenHash}, ${JSON.stringify(metadata)}::jsonb)+ RETURNING id, user_id, agent_id, label, budget_usdc, spent_usdc,+ max_per_tx_usdc, allowed_hosts, network, status, expires_at,+ session_metadata, created_at+ `;++ // Back-fill the ref_id now that we have the session ID+ await sql`+ UPDATE credit_ledger SET ref_id = ${sessionId}+ WHERE idempotency_key = ${idempotencyKey}+ `.catch(() => {});++ return {+ session: formatSession(row),+ token,+ };+}++/**+ * Get a session by ID. Returns null if not found or not owned by userId.+ */+export async function getPaymentSession(sessionId, userId) {+ const [row] = await sql`+ SELECT id, user_id, agent_id, label, budget_usdc, spent_usdc,+ max_per_tx_usdc, allowed_hosts, network, status, expires_at,+ session_metadata, created_at, updated_at+ FROM payment_sessions+ WHERE id = ${sessionId}+ AND (${userId}::uuid IS NULL OR user_id = ${userId}::uuid)+ LIMIT 1+ `;+ return row ? formatSession(row) : null;+}++/**+ * List sessions for a user. Returns latest-first.+ */+export async function listPaymentSessions(userId, { status, limit = 20, cursor } = {}) {+ const lim = Math.min(Number(limit) || 20, 100);+ const rows = await sql`+ SELECT id, user_id, agent_id, label, budget_usdc, spent_usdc,+ max_per_tx_usdc, allowed_hosts, network, status, expires_at,+ session_metadata, created_at, updated_at+ FROM payment_sessions+ WHERE user_id = ${userId}+ AND (${status ?? null}::text IS NULL OR status = ${status ?? null})+ AND (${cursor ?? null}::timestamptz IS NULL OR created_at < ${cursor ?? null}::timestamptz)+ ORDER BY created_at DESC+ LIMIT ${lim + 1}+ `;++ const hasMore = rows.length > lim;+ const items = rows.slice(0, lim).map(formatSession);+ return {+ items,+ next_cursor: hasMore ? items[items.length - 1].created_at : null,+ };+}++/**+ * Cancel a session. Refunds un-spent budget to the user's credit balance.+ */+export async function cancelPaymentSession(sessionId, userId) {+ const [row] = await sql`+ UPDATE payment_sessions+ SET status = 'cancelled', updated_at = now()+ WHERE id = ${sessionId} AND user_id = ${userId}+ AND status IN ('active', 'exhausted')+ RETURNING id, budget_usdc, spent_usdc, user_id+ `;+ if (!row) return null;++ // Refund the un-spent portion+ const refundAtomics = BigInt(row.budget_usdc) - BigInt(row.spent_usdc);+ if (refundAtomics > 0n) {+ const refundUsd = atomicsToUsd(refundAtomics);+ await creditAccount({+ userId: row.user_id,+ amountUsd: refundUsd,+ kind: 'refund',+ action: 'payment_session_cancel',+ refType: 'payment_session',+ refId: sessionId,+ idempotencyKey: `paysess_refund_${sessionId}`,+ }).catch(() => {});+ }++ return { id: sessionId, refunded_usd: atomicsToUsd(refundAtomics) };+}++/**+ * List executions for a session.+ */+export async function listSessionExecutions(sessionId, userId, { limit = 20, cursor } = {}) {+ const lim = Math.min(Number(limit) || 20, 100);+ const rows = await sql`+ SELECT id, endpoint_url, endpoint_host, method, amount_usdc,+ network, tx_hash, payer_address, payee_address,+ status, error_code, duration_ms, created_at+ FROM payment_session_executions+ WHERE session_id = ${sessionId}+ AND user_id = ${userId}+ AND (${cursor ?? null}::timestamptz IS NULL OR created_at < ${cursor ?? null}::timestamptz)+ ORDER BY created_at DESC+ LIMIT ${lim + 1}+ `;++ const hasMore = rows.length > lim;+ const items = rows.slice(0, lim).map(formatExecution);+ return { items, next_cursor: hasMore ? items[items.length - 1].created_at : null };+}++/**+ * Aggregate spend stats across all sessions for a user.+ */+export async function getPaymentStats(userId) {+ const [stats] = await sql`+ SELECT+ count(*) FILTER (WHERE status = 'active') AS active_sessions,+ count(*) FILTER (WHERE status = 'exhausted') AS exhausted_sessions,+ count(*) FILTER (WHERE status = 'cancelled') AS cancelled_sessions,+ count(*) FILTER (WHERE status = 'expired') AS expired_sessions,+ coalesce(sum(budget_usdc), 0) AS total_budget_atomics,+ coalesce(sum(spent_usdc), 0) AS total_spent_atomics+ FROM payment_sessions+ WHERE user_id = ${userId}+ `;++ const [execStats] = await sql`+ SELECT+ count(*) FILTER (WHERE e.status = 'settled') AS settled_count,+ count(*) FILTER (WHERE e.status = 'failed') AS failed_count,+ coalesce(sum(e.amount_usdc) FILTER (WHERE e.status = 'settled'), 0) AS settled_atomics,+ count(DISTINCT e.endpoint_host) AS unique_endpoints+ FROM payment_session_executions e+ JOIN payment_sessions s ON s.id = e.session_id+ WHERE s.user_id = ${userId}+ `;++ return {+ sessions: {+ active: Number(stats?.active_sessions ?? 0),+ exhausted: Number(stats?.exhausted_sessions ?? 0),+ cancelled: Number(stats?.cancelled_sessions ?? 0),+ expired: Number(stats?.expired_sessions ?? 0),+ total_budget_usd: atomicsToUsd(stats?.total_budget_atomics ?? 0),+ total_spent_usd: atomicsToUsd(stats?.total_spent_atomics ?? 0),+ },+ executions: {+ settled: Number(execStats?.settled_count ?? 0),+ failed: Number(execStats?.failed_count ?? 0),+ settled_usd: atomicsToUsd(execStats?.settled_atomics ?? 0),+ unique_endpoints: Number(execStats?.unique_endpoints ?? 0),+ },+ };+}++function formatSession(row) {+ return {+ id: row.id,+ user_id: row.user_id,+ agent_id: row.agent_id ?? null,+ label: row.label ?? '',+ budget_usd: atomicsToUsd(row.budget_usdc),+ spent_usd: atomicsToUsd(row.spent_usdc),+ remaining_usd: atomicsToUsd(BigInt(row.budget_usdc) - BigInt(row.spent_usdc)),+ max_per_tx_usd: row.max_per_tx_usdc != null ? atomicsToUsd(row.max_per_tx_usdc) : null,+ allowed_hosts: row.allowed_hosts ?? [],+ network: row.network,+ status: row.status,+ expires_at: row.expires_at,+ metadata: row.session_metadata ?? {},+ created_at: row.created_at,+ updated_at: row.updated_at ?? null,+ };+}++function formatExecution(row) {+ return {+ id: row.id,+ endpoint_url: row.endpoint_url,+ endpoint_host: row.endpoint_host,+ method: row.method,+ amount_usd: atomicsToUsd(row.amount_usdc),+ network: row.network,+ tx_hash: row.tx_hash ?? null,+ payer_address: row.payer_address ?? null,+ payee_address: row.payee_address ?? null,+ status: row.status,+ error_code: row.error_code ?? null,+ duration_ms: row.duration_ms ?? null,+ created_at: row.created_at,+ };+}diff --git a/api/_lib/pay/spend-governor.js b/api/_lib/pay/spend-governor.jsnew file mode 100644index 000000000..7854847c8--- /dev/null+++ b/api/_lib/pay/spend-governor.js@@ -0,0 +1,288 @@+// Spend Governor — policy enforcement layer for Agent Payment Sessions.+//+// Design principle (from AWS AgentCore Payments architecture):+// "The agent does not hold a wallet. It proposes spend. Governance enforces policy."+//+// This module is the single chokepoint every session-based payment must pass through.+// Five checks, in order:+// 1. Session exists and is active (not expired, cancelled, or exhausted)+// 2. Expiry time has not passed+// 3. URL is in the session's host allowlist (if set)+// 4. Amount does not exceed the per-transaction ceiling (if set)+// 5. Remaining budget is sufficient — atomically decrements spent_usdc+//+// The atomic budget decrement uses a SQL UPDATE ... RETURNING with a WHERE clause+// that checks (budget_usdc - spent_usdc >= amount), so concurrent payment requests+// can never collectively overspend a session. If two requests arrive simultaneously+// and both would fit individually but together would exceed the budget, exactly one+// wins the race; the other gets INSUFFICIENT_BUDGET.+//+// Governance errors throw SpendGovernorError with a machine-readable `code` so the+// API layer can return 402 vs 403 vs 429 appropriately. The caller must call+// rollbackReservation() if the downstream x402 payment fails after the budget has+// been reserved — otherwise the session bleeds budget on failed payments.++import { createHmac, randomBytes } from 'node:crypto';+import { sql } from '../db.js';+import { env } from '../env.js';++// USDC has 6 decimals. Convert human USD to atomic units.+export function usdToAtomics(usd) {+ return BigInt(Math.round(Number(usd) * 1_000_000));+}+export function atomicsToUsd(atomics) {+ return Number(atomics) / 1_000_000;+}++export class SpendGovernorError extends Error {+ constructor(code, message, detail = {}) {+ super(message);+ this.name = 'SpendGovernorError';+ this.code = code;+ this.detail = detail;+ // Map each code to a sensible HTTP status+ this.status = {+ session_not_found: 404,+ session_inactive: 403,+ session_expired: 403,+ allowlist_blocked: 403,+ per_tx_exceeded: 402,+ insufficient_budget: 402,+ invalid_token: 401,+ }[code] ?? 403;+ }+}++// HMAC token signing. The token itself is never stored — only its SHA-256 HMAC.+// Format: `pss_<sessionId>_<random32hex>` — human-readable, prefix-scoped.+const TOKEN_PREFIX = 'pss_';++function hmacKey() {+ const k = env.PAYMENT_SESSION_SECRET || env.WALLET_CAPABILITY_SECRET || env.SESSION_SECRET;+ if (!k) throw new Error('PAYMENT_SESSION_SECRET is not configured');+ return k;+}++export function generateSessionToken(sessionId) {+ const rand = randomBytes(16).toString('hex');+ return `${TOKEN_PREFIX}${sessionId}_${rand}`;+}++export function hashToken(token) {+ return createHmac('sha256', hmacKey()).update(String(token)).digest('hex');+}++// Extract sessionId from a token without verifying it. Used for DB lookup before+// the constant-time hash comparison.+export function extractSessionId(token) {+ const s = String(token || '');+ if (!s.startsWith(TOKEN_PREFIX)) return null;+ const rest = s.slice(TOKEN_PREFIX.length);+ // Format after prefix: <uuid>_<random> — uuid is exactly 36 chars+ if (rest.length < 37 || rest[36] !== '_') return null;+ return rest.slice(0, 36);+}++// Normalize any URL/host to a bare lowercase hostname for allowlist comparison.+export function normalizeHost(raw) {+ const s = String(raw || '').trim().toLowerCase();+ if (!s) return '';+ try {+ const u = new URL(s.includes('://') ? s : `https://${s}`);+ return u.hostname;+ } catch {+ // Might already be a bare hostname+ return s.split('/')[0].split(':')[0] || '';+ }+}++/**+ * Verify a session token and return the session row.+ * Throws SpendGovernorError on any auth / state failure.+ */+export async function verifySessionToken(token) {+ const sessionId = extractSessionId(token);+ if (!sessionId) throw new SpendGovernorError('invalid_token', 'Invalid session token format');++ const hash = hashToken(token);+ const [row] = await sql`+ SELECT id, user_id, agent_id, label, budget_usdc, spent_usdc,+ max_per_tx_usdc, allowed_hosts, network, connector_ref,+ status, expires_at, session_metadata+ FROM payment_sessions+ WHERE id = ${sessionId} AND token_hash = ${hash}+ LIMIT 1+ `;++ if (!row) throw new SpendGovernorError('invalid_token', 'Session token not found or invalid');+ return row;+}++/**+ * Enforce governance policy and atomically reserve budget for a payment.+ *+ * @param {object} opts+ * @param {string} opts.token - Session bearer token+ * @param {string} opts.url - Target endpoint URL (for allowlist check)+ * @param {bigint} opts.amountAtomics - Payment amount in USDC atomics (6 decimals)+ * @returns {Promise<{ session: object, reservationId: string }>}+ * @throws {SpendGovernorError} on any policy violation+ */+export async function reserveSessionSpend({ token, url, amountAtomics }) {+ // Phase 1: token verification+ const session = await verifySessionToken(token);++ // Phase 2: status check+ if (session.status !== 'active') {+ const messages = {+ exhausted: 'Session budget is exhausted',+ expired: 'Session has expired',+ cancelled: 'Session has been cancelled',+ };+ throw new SpendGovernorError(+ 'session_inactive',+ messages[session.status] ?? `Session is ${session.status}`,+ { status: session.status },+ );+ }++ // Phase 3: time expiry (belt-and-suspenders; DB sweep also marks expired rows)+ const now = new Date();+ if (new Date(session.expires_at) < now) {+ // Mark it expired so future checks skip the DB read+ await sql`+ UPDATE payment_sessions SET status = 'expired', updated_at = now()+ WHERE id = ${session.id} AND status = 'active'+ `.catch(() => {});+ throw new SpendGovernorError('session_expired', 'Session has expired');+ }++ // Phase 4: URL allowlist enforcement+ const allowedHosts = Array.isArray(session.allowed_hosts) ? session.allowed_hosts : [];+ if (allowedHosts.length > 0) {+ let targetHost;+ try {+ targetHost = new URL(url).hostname.toLowerCase();+ } catch {+ throw new SpendGovernorError('allowlist_blocked', `Invalid target URL: ${url}`);+ }+ const canonicalAllowlist = allowedHosts.map(normalizeHost).filter(Boolean);+ const allowed = canonicalAllowlist.some(+ (h) => targetHost === h || targetHost.endsWith(`.${h}`),+ );+ if (!allowed) {+ throw new SpendGovernorError(+ 'allowlist_blocked',+ `Host ${targetHost} is not in this session's allowlist`,+ { host: targetHost, allowlist: canonicalAllowlist },+ );+ }+ }++ // Phase 5: per-transaction ceiling+ const perTxCap = session.max_per_tx_usdc != null ? BigInt(session.max_per_tx_usdc) : null;+ if (perTxCap !== null && amountAtomics > perTxCap) {+ throw new SpendGovernorError(+ 'per_tx_exceeded',+ `Payment $${atomicsToUsd(amountAtomics)} exceeds the per-transaction limit $${atomicsToUsd(perTxCap)}`,+ { amount_usd: atomicsToUsd(amountAtomics), cap_usd: atomicsToUsd(perTxCap) },+ );+ }++ // Phase 6: atomic budget reservation+ // The WHERE clause ensures (budget_usdc - spent_usdc) >= amountAtomics before+ // incrementing — race-safe: two concurrent requests cannot both succeed if+ // only one fits in the remaining budget.+ const amount = BigInt(amountAtomics);+ const [updated] = await sql`+ UPDATE payment_sessions+ SET spent_usdc = spent_usdc + ${amount.toString()},+ updated_at = now()+ WHERE id = ${session.id}+ AND status = 'active'+ AND (budget_usdc - spent_usdc) >= ${amount.toString()}+ RETURNING id, spent_usdc, budget_usdc+ `;++ if (!updated) {+ // Could be exhausted mid-race; check to give a precise error+ const [fresh] = await sql`+ SELECT budget_usdc, spent_usdc FROM payment_sessions WHERE id = ${session.id}+ `;+ const remaining = fresh ? BigInt(fresh.budget_usdc) - BigInt(fresh.spent_usdc) : 0n;+ throw new SpendGovernorError(+ 'insufficient_budget',+ `Insufficient session budget. Need $${atomicsToUsd(amount)}, remaining $${atomicsToUsd(remaining)}`,+ { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },+ );+ }++ // If the session is now fully consumed, mark it exhausted+ if (BigInt(updated.spent_usdc) >= BigInt(updated.budget_usdc)) {+ await sql`+ UPDATE payment_sessions SET status = 'exhausted', updated_at = now()+ WHERE id = ${session.id} AND status = 'active'+ `.catch(() => {});+ }++ const reservationId = `res_${session.id}_${Date.now()}`;+ return { session: { ...session, spent_usdc: updated.spent_usdc }, reservationId };+}++/**+ * Roll back a budget reservation after a failed payment.+ * Decrements spent_usdc by the reserved amount and restores 'active' if exhausted.+ */+export async function rollbackReservation(sessionId, amountAtomics) {+ const amount = BigInt(amountAtomics);+ await sql`+ UPDATE payment_sessions+ SET spent_usdc = greatest(0, spent_usdc - ${amount.toString()}),+ status = CASE WHEN status = 'exhausted' THEN 'active' ELSE status END,+ updated_at = now()+ WHERE id = ${sessionId}+ AND status IN ('active', 'exhausted')+ `;+}++/**+ * Mark a session execution record and finalize its outcome.+ */+export async function recordExecution({+ sessionId,+ userId,+ endpointUrl,+ method,+ amountAtomics,+ network,+ txHash,+ payerAddress,+ payeeAddress,+ status,+ errorCode,+ errorMessage,+ responseBody,+ durationMs,+ idempotencyKey,+}) {+ const host = (() => {+ try { return new URL(endpointUrl).hostname; }+ catch { return ''; }+ })();++ await sql`+ INSERT INTO payment_session_executions+ (session_id, user_id, endpoint_url, endpoint_host, method,+ amount_usdc, network, tx_hash, payer_address, payee_address,+ status, error_code, error_message, response_body,+ duration_ms, idempotency_key)+ VALUES+ (${sessionId}, ${userId}, ${endpointUrl}, ${host}, ${method ?? 'GET'},+ ${amountAtomics.toString()}, ${network}, ${txHash ?? null},+ ${payerAddress ?? null}, ${payeeAddress ?? null},+ ${status}, ${errorCode ?? null}, ${errorMessage ?? null},+ ${responseBody != null ? JSON.stringify(responseBody) : null},+ ${durationMs ?? null}, ${idempotencyKey ?? null})+ ON CONFLICT (idempotency_key) DO NOTHING+ `;+}diff --git a/api/agent/launcher.js b/api/agent/launcher.jsnew file mode 100644index 000000000..a76c8170d--- /dev/null+++ b/api/agent/launcher.js@@ -0,0 +1,290 @@+/**+ * Agent Launcher — config CRUD and launched coin history.+ *+ * GET /api/agent/launcher?agentId=<uuid>+ * Returns { configs: [...], coins: [...] }+ * configs = agent_launcher_configs rows for the owned agent+ * coins = last 50 agent_launched_coins for the agent, newest first+ *+ * POST /api/agent/launcher+ * UPSERT a launcher config (one row per agent per network).+ * Returns { ok: true, config: {...} }+ *+ * DELETE /api/agent/launcher?id=<config_id>+ * Delete a launcher config (caller must own the agent).+ * Returns { ok: true }+ *+ * Auth: session cookie OR bearer JWT, scoped to agents the caller owns+ * (agent_identities.user_id). Rate-limited via the standard authIp bucket.+ */++import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';++// ── Auth helper ──────────────────────────────────────────────────────────────++async function resolveUserId(req) {+ const session = await getSessionUser(req);+ if (session?.id) return session.id;+ const bearer = extractBearer(req);+ if (bearer) {+ const auth = await authenticateBearer(bearer).catch(() => null);+ if (auth?.userId) return auth.userId;+ }+ return null;+}++// ── Ownership check ───────────────────────────────────────────────────────────++async function assertOwnsAgent(userId, agentId) {+ const [row] = await sql`+ SELECT id FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL+ LIMIT 1+ `;+ return !!row;+}++// ── Route dispatch ───────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;++ const userId = await resolveUserId(req);+ if (!userId) return error(res, 401, 'unauthorized', 'authentication required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ if (req.method === 'GET') return getConfigs(req, res, userId);+ if (req.method === 'DELETE') return deleteConfig(req, res, userId);+ return upsertConfig(req, res, userId);+});++// ── GET ──────────────────────────────────────────────────────────────────────++async function getConfigs(req, res, userId) {+ const { searchParams } = new URL(req.url, 'http://localhost');+ const agentId = searchParams.get('agentId');++ if (!agentId) return error(res, 400, 'missing_agent_id', 'agentId is required');+ if (!(await assertOwnsAgent(userId, agentId))) {+ return error(res, 404, 'not_found', 'agent not found or not owned by you');+ }++ const [configs, coins] = await Promise.all([+ sql`+ SELECT * FROM agent_launcher_configs+ WHERE agent_id = ${agentId}+ ORDER BY created_at ASC+ `,+ sql`+ SELECT *+ FROM agent_launched_coins+ WHERE agent_id = ${agentId}+ ORDER BY created_at DESC+ LIMIT 50+ `,+ ]);++ return json(res, 200, { configs, coins });+}++// ── POST — upsert ────────────────────────────────────────────────────────────++async function upsertConfig(req, res, userId) {+ const body = await readJson(req);++ const { agentId } = body || {};+ if (!agentId || typeof agentId !== 'string') {+ return error(res, 400, 'missing_agent_id', 'agentId is required');+ }+ if (!(await assertOwnsAgent(userId, agentId))) {+ return error(res, 404, 'not_found', 'agent not found or not owned by you');+ }++ // Validate fields before touching the DB+ if (body.symbol != null) {+ const sym = String(body.symbol).trim();+ if (!/^[A-Z0-9]{1,10}$/.test(sym)) {+ return error(res, 400, 'invalid_symbol', 'symbol must be uppercase alphanumeric and at most 10 characters');+ }+ }++ if (body.name_template != null && String(body.name_template).length > 32) {+ return error(res, 400, 'invalid_name_template', 'name_template must be at most 32 characters');+ }++ if (body.network != null && !['mainnet', 'devnet'].includes(body.network)) {+ return error(res, 400, 'invalid_network', 'network must be "mainnet" or "devnet"');+ }++ if (body.interval_hours != null && body.interval_hours !== '') {+ const ih = Number(body.interval_hours);+ if (!Number.isFinite(ih) || ih < 0.5) {+ return error(res, 400, 'invalid_interval_hours', 'interval_hours must be >= 0.5');+ }+ }++ if (body.initial_buy_sol != null && body.initial_buy_sol !== '') {+ const s = Number(body.initial_buy_sol);+ if (!Number.isFinite(s) || s < 0) {+ return error(res, 400, 'invalid_initial_buy_sol', 'initial_buy_sol must be >= 0');+ }+ }++ if (body.auto_claim_reinvest_pct != null && body.auto_claim_reinvest_pct !== '') {+ const p = Number(body.auto_claim_reinvest_pct);+ if (!Number.isFinite(p) || p < 0 || p > 100) {+ return error(res, 400, 'invalid_auto_claim_reinvest_pct', 'auto_claim_reinvest_pct must be between 0 and 100');+ }+ }++ // Coerce + merge against existing row defaults+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';+ const enabled = body.enabled != null ? Boolean(body.enabled) : false;+ const symbol = body.symbol != null ? String(body.symbol).trim().toUpperCase() : null;+ const nameTemplate = body.name_template != null ? String(body.name_template).slice(0, 32) : null;++ const intervalHours = body.interval_hours != null && body.interval_hours !== ''+ ? Math.max(0.5, Number(body.interval_hours))+ : null;+ const maxLaunches = body.max_launches != null && body.max_launches !== ''+ ? Math.max(1, Math.round(Number(body.max_launches)))+ : null;++ const initialBuySol = body.initial_buy_sol != null ? Math.max(0, Number(body.initial_buy_sol)) : null;+ const initialBuySlippageBps = body.initial_buy_slippage_bps != null+ ? Math.min(10000, Math.max(0, Math.round(Number(body.initial_buy_slippage_bps))))+ : null;++ const autoClaimEnabled = body.auto_claim_enabled != null ? Boolean(body.auto_claim_enabled) : null;+ const autoClaimThresholdSol = body.auto_claim_threshold_sol != null ? Math.max(0, Number(body.auto_claim_threshold_sol)) : null;+ const autoClaimReinvestPct = body.auto_claim_reinvest_pct != null+ ? Math.min(100, Math.max(0, Number(body.auto_claim_reinvest_pct)))+ : null;++ // Fetch existing row so the UPSERT can propagate defaults for omitted fields+ const [existing] = await sql`+ SELECT * FROM agent_launcher_configs+ WHERE agent_id = ${agentId} AND network = ${network}+ LIMIT 1+ `;+ const cur = existing || {+ enabled: false,+ interval_hours: null,+ max_launches: null,+ name_template: '',+ symbol: '',+ description: null,+ image_url: null,+ twitter: null,+ telegram: null,+ website: null,+ initial_buy_sol: 0,+ initial_buy_slippage_bps: 500,+ auto_claim_enabled: false,+ auto_claim_threshold_sol: 0,+ auto_claim_reinvest_pct: 0,+ };++ const next = {+ enabled: enabled,+ interval_hours: intervalHours !== null ? intervalHours : (cur.interval_hours != null ? Number(cur.interval_hours) : null),+ max_launches: maxLaunches !== null ? maxLaunches : cur.max_launches,+ name_template: nameTemplate !== null ? nameTemplate : (cur.name_template ?? ''),+ symbol: symbol !== null ? symbol : (cur.symbol ?? ''),+ description: 'description' in body ? (body.description || null) : (cur.description || null),+ image_url: 'image_url' in body ? (body.image_url || null) : (cur.image_url || null),+ twitter: 'twitter' in body ? (body.twitter || null) : (cur.twitter || null),+ telegram: 'telegram' in body ? (body.telegram || null) : (cur.telegram || null),+ website: 'website' in body ? (body.website || null) : (cur.website || null),+ initial_buy_sol: initialBuySol !== null ? initialBuySol : Number(cur.initial_buy_sol ?? 0),+ initial_buy_slippage_bps: initialBuySlippageBps !== null ? initialBuySlippageBps : Number(cur.initial_buy_slippage_bps ?? 500),+ auto_claim_enabled: autoClaimEnabled !== null ? autoClaimEnabled : Boolean(cur.auto_claim_enabled),+ auto_claim_threshold_sol: autoClaimThresholdSol !== null ? autoClaimThresholdSol : Number(cur.auto_claim_threshold_sol ?? 0),+ auto_claim_reinvest_pct: autoClaimReinvestPct !== null ? autoClaimReinvestPct : Number(cur.auto_claim_reinvest_pct ?? 0),+ };++ // next_launch_at: reset when enabled transitions true or interval changes+ const resetNextLaunch = next.enabled && (+ !cur.enabled ||+ next.interval_hours !== (cur.interval_hours != null ? Number(cur.interval_hours) : null)+ );++ const [config] = await sql`+ INSERT INTO agent_launcher_configs+ (agent_id, user_id, enabled, network,+ interval_hours, max_launches,+ name_template, symbol, description, image_url,+ twitter, telegram, website,+ initial_buy_sol, initial_buy_slippage_bps,+ auto_claim_enabled, auto_claim_threshold_sol, auto_claim_reinvest_pct,+ updated_at)+ VALUES+ (${agentId}, ${userId}, ${next.enabled}, ${network},+ ${next.interval_hours}, ${next.max_launches},+ ${next.name_template}, ${next.symbol},+ ${next.description}, ${next.image_url},+ ${next.twitter}, ${next.telegram}, ${next.website},+ ${next.initial_buy_sol}, ${next.initial_buy_slippage_bps},+ ${next.auto_claim_enabled}, ${next.auto_claim_threshold_sol}, ${next.auto_claim_reinvest_pct},+ now())+ ON CONFLICT (agent_id, network)+ DO UPDATE SET+ enabled = EXCLUDED.enabled,+ interval_hours = EXCLUDED.interval_hours,+ max_launches = EXCLUDED.max_launches,+ name_template = EXCLUDED.name_template,+ symbol = EXCLUDED.symbol,+ description = EXCLUDED.description,+ image_url = EXCLUDED.image_url,+ twitter = EXCLUDED.twitter,+ telegram = EXCLUDED.telegram,+ website = EXCLUDED.website,+ initial_buy_sol = EXCLUDED.initial_buy_sol,+ initial_buy_slippage_bps = EXCLUDED.initial_buy_slippage_bps,+ auto_claim_enabled = EXCLUDED.auto_claim_enabled,+ auto_claim_threshold_sol = EXCLUDED.auto_claim_threshold_sol,+ auto_claim_reinvest_pct = EXCLUDED.auto_claim_reinvest_pct,+ next_launch_at = CASE+ WHEN ${resetNextLaunch} AND EXCLUDED.interval_hours IS NOT NULL+ THEN now() + EXCLUDED.interval_hours * interval '1 hour'+ WHEN ${resetNextLaunch}+ THEN NULL+ ELSE agent_launcher_configs.next_launch_at+ END,+ updated_at = now()+ RETURNING *+ `;++ return json(res, 200, { ok: true, config });+}++// ── DELETE ───────────────────────────────────────────────────────────────────++async function deleteConfig(req, res, userId) {+ const { searchParams } = new URL(req.url, 'http://localhost');+ const configId = searchParams.get('id');++ if (!configId) return error(res, 400, 'missing_id', 'id is required');++ // Verify ownership transitively via agent_id+ const [cfg] = await sql`+ SELECT alc.id+ FROM agent_launcher_configs alc+ JOIN agent_identities ai ON ai.id = alc.agent_id+ WHERE alc.id = ${configId}+ AND ai.user_id = ${userId}+ AND ai.deleted_at IS NULL+ LIMIT 1+ `;+ if (!cfg) return error(res, 404, 'not_found', 'launcher config not found or not owned by you');++ await sql`DELETE FROM agent_launcher_configs WHERE id = ${configId}`;++ return json(res, 200, { ok: true });+}diff --git a/api/agent/market-maker.js b/api/agent/market-maker.jsnew file mode 100644index 000000000..2401affae--- /dev/null+++ b/api/agent/market-maker.js@@ -0,0 +1,159 @@+// GET /api/agent/market-maker?agentId=<uuid> — list MM configs + recent trades+// POST /api/agent/market-maker — upsert MM config+// DELETE /api/agent/market-maker?id=<config_id> — disable MM config (soft-delete)+//+// Auth: session cookie or bearer JWT.+// The calling user must own the target agent (verified via agent_identities).++import { cors, error, json, method, readJson, rateLimited, wrap } from '../_lib/http.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';++// ── auth ──────────────────────────────────────────────────────────────────────++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++// ── ownership ─────────────────────────────────────────────────────────────────++async function assertOwnsAgent(userId, agentId) {+ const [row] = await sql`+ SELECT id FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL+ LIMIT 1+ `;+ return !!row;+}++// ── validation ────────────────────────────────────────────────────────────────++const VALID_BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const VALID_TIP_MODES = new Set(['off', 'economy', 'turbo']);++function clampInt(val, min, max, fallback) {+ const n = Math.round(Number(val));+ return isNaN(n) ? fallback : Math.min(max, Math.max(min, n));+}+function clampFloat(val, min, max, fallback) {+ const n = Number(val);+ return isNaN(n) || n <= 0 ? fallback : Math.min(max, Math.max(min, n));+}++// ── handler ───────────────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'authentication required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many market-maker requests');++ // ── GET ───────────────────────────────────────────────────────────────────+ if (req.method === 'GET') {+ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agentId');+ if (!agentId) return error(res, 400, 'validation_error', 'agentId query param required');+ if (!(await assertOwnsAgent(auth.userId, agentId))) {+ return error(res, 403, 'forbidden', 'agent not owned by this user');+ }++ const [configs, recent_trades] = await Promise.all([+ sql`+ SELECT * FROM agent_market_maker_configs+ WHERE agent_id = ${agentId}+ ORDER BY created_at DESC+ `,+ sql`+ SELECT * FROM agent_market_maker_trades+ WHERE agent_id = ${agentId}+ ORDER BY created_at DESC+ LIMIT 100+ `,+ ]);++ return json(res, 200, { configs, recent_trades });+ }++ // ── DELETE (disable) ──────────────────────────────────────────────────────+ if (req.method === 'DELETE') {+ const url = new URL(req.url, 'http://x');+ const configId = url.searchParams.get('id');+ if (!configId) return error(res, 400, 'validation_error', 'id query param required');++ // Ownership check via join — one query.+ const [cfg] = await sql`+ SELECT c.id FROM agent_market_maker_configs c+ JOIN agent_identities a ON a.id = c.agent_id AND a.deleted_at IS NULL+ WHERE c.id = ${configId} AND a.user_id = ${auth.userId}+ LIMIT 1+ `;+ if (!cfg) return error(res, 404, 'not_found', 'config not found or not owned');++ // Disable rather than delete to preserve trade history.+ await sql`+ UPDATE agent_market_maker_configs+ SET enabled = false, updated_at = now()+ WHERE id = ${configId}+ `;+ return json(res, 200, { ok: true });+ }++ // ── POST ──────────────────────────────────────────────────────────────────+ if (!method(req, res, ['POST'])) return;++ const body = await readJson(req);+ const { agentId, mint } = body ?? {};++ if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');+ if (!mint || !VALID_BASE58.test(mint)) {+ return error(res, 400, 'validation_error', 'mint must be a valid base-58 Solana address (32–44 chars)');+ }+ if (!(await assertOwnsAgent(auth.userId, agentId))) {+ return error(res, 403, 'forbidden', 'agent not owned by this user');+ }++ // Coerce and clamp all optional fields against spec limits.+ const symbol = body.symbol ? String(body.symbol).trim().slice(0, 16) || null : null;+ const network = String(body.network ?? 'mainnet').slice(0, 32);+ const enabled = body.enabled != null ? Boolean(body.enabled) : true;+ const spread_bps = clampInt(body.spread_bps, 10, 2000, 200);+ const order_size_sol = clampFloat(body.order_size_sol, 0, 100, 0.05);+ const max_inventory_sol = clampFloat(body.max_inventory_sol, 0, 1000, 1.0);+ const min_profit_bps = clampInt(body.min_profit_bps, 1, 1000, 50);+ const rebalance_interval_ms = clampInt(body.rebalance_interval_ms, 1, Number.MAX_SAFE_INTEGER, 10000);+ const mev_tip_mode = VALID_TIP_MODES.has(body.mev_tip_mode) ? body.mev_tip_mode : 'off';++ const [config] = await sql`+ INSERT INTO agent_market_maker_configs+ (agent_id, enabled, mint, symbol, network,+ spread_bps, order_size_sol, max_inventory_sol, min_profit_bps,+ rebalance_interval_ms, mev_tip_mode, updated_at)+ VALUES+ (${agentId}, ${enabled}, ${mint}, ${symbol}, ${network},+ ${spread_bps}, ${order_size_sol}, ${max_inventory_sol}, ${min_profit_bps},+ ${rebalance_interval_ms}, ${mev_tip_mode}, now())+ ON CONFLICT (agent_id, mint)+ DO UPDATE SET+ enabled = EXCLUDED.enabled,+ symbol = EXCLUDED.symbol,+ network = EXCLUDED.network,+ spread_bps = EXCLUDED.spread_bps,+ order_size_sol = EXCLUDED.order_size_sol,+ max_inventory_sol = EXCLUDED.max_inventory_sol,+ min_profit_bps = EXCLUDED.min_profit_bps,+ rebalance_interval_ms = EXCLUDED.rebalance_interval_ms,+ mev_tip_mode = EXCLUDED.mev_tip_mode,+ updated_at = now()+ RETURNING *+ `;++ return json(res, 200, { ok: true, config });+});diff --git a/api/pay/execute.js b/api/pay/execute.jsnew file mode 100644index 000000000..a20671d06--- /dev/null+++ b/api/pay/execute.js@@ -0,0 +1,449 @@+// POST /api/pay/execute — execute an x402 payment using a Payment Session token.+//+// This is the core "agent proposes spend, governance enforces" endpoint.+// The agent presents:+// - session_token: their payment session bearer token+// - url: the x402 endpoint to pay+// - method: GET | POST (optional, default GET)+// - body: JSON body for POST requests (optional)+// - idempotency_key: caller's dedup key (optional, recommended)+//+// The platform:+// 1. Verifies the session token and checks governance (budget, allowlist, per-tx cap)+// 2. Probes the endpoint for its 402 challenge+// 3. Reserves the amount from the session budget (atomic, race-safe)+// 4. Signs the Solana USDC transfer with the platform payer wallet+// 5. Presents X-PAYMENT header and returns the endpoint's response+// 6. Records the execution in payment_session_executions+// 7. On failure, rolls back the budget reservation so the session isn't charged+//+// No private key is ever exposed to the caller. The only secret is the session+// token, which is a time-bounded spending grant, not wallet access.++import { readFileSync } from 'node:fs';+import {+ Connection, PublicKey, Keypair, TransactionMessage, VersionedTransaction,+ ComputeBudgetProgram,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync,+ createTransferCheckedInstruction,+ createAssociatedTokenAccountIdempotentInstruction,+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, getMint,+} from '@solana/spl-token';+import bs58 from 'bs58';++import { cors, error, json, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { validatePublicUrl, resolvePublicHost, pinnedAgent, SsrfError } from '../_lib/ssrf.js';+import { solanaConnection } from '../_lib/solana/connection.js';+import {+ usdToAtomics,+ atomicsToUsd,+ reserveSessionSpend,+ rollbackReservation,+ recordExecution,+ SpendGovernorError,+} from '../_lib/pay/spend-governor.js';++const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const SOLANA_RPC = env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+const FETCH_TIMEOUT_MS = 20_000;++// ── Platform payer keypair ──────────────────────────────────────────────────+// Shared with x402-pay.js; loads X402_AGENT_SOLANA_SECRET_BASE58 or falls back+// to the dev test keypair. This is the wallet that signs session payments on+// behalf of users — it needs to hold USDC to fund the transfers.+let _platformKeypair = null;++function loadPlatformKeypair() {+ if (_platformKeypair) return _platformKeypair;+ const b58 = process.env.X402_AGENT_SOLANA_SECRET_BASE58;+ if (b58) {+ const raw = bs58.decode(b58);+ _platformKeypair = Keypair.fromSecretKey(raw);+ return _platformKeypair;+ }+ if (process.env.NODE_ENV !== 'production') {+ try {+ const arr = JSON.parse(readFileSync('/home/codespace/.config/x402-test-wallets/solana.json', 'utf8'));+ _platformKeypair = Keypair.fromSecretKey(Uint8Array.from(arr));+ return _platformKeypair;+ } catch { /* fall through */ }+ }+ const e = new Error('Platform payer wallet not configured (set X402_AGENT_SOLANA_SECRET_BASE58)');+ e.status = 503;+ e.code = 'wallet_unconfigured';+ throw e;+}++// ── SSRF-guarded fetch ──────────────────────────────────────────────────────+async function guardedFetch(rawUrl, { method = 'GET', headers = {}, body } = {}) {+ const url = validatePublicUrl(rawUrl);+ const addrs = await resolvePublicHost(url.hostname);+ const agent = pinnedAgent(url.hostname, addrs);+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, {+ method,+ redirect: 'manual',+ signal: controller.signal,+ dispatcher: agent,+ headers: {+ 'user-agent': 'three.ws-payment-session/1.0 (+https://three.ws/)',+ accept: 'application/json, text/plain;q=0.8, */*;q=0.5',+ ...(body != null ? { 'content-type': 'application/json' } : {}),+ ...headers,+ },+ ...(body != null ? { body: typeof body === 'string' ? body : JSON.stringify(body) } : {}),+ });+ const text = await res.text();+ return { status: res.status, ok: res.ok, headers: res.headers, text };+ } finally {+ clearTimeout(timer);+ await agent.close().catch(() => {});+ }+}++function safeJson(text) {+ try { return JSON.parse(text); } catch { return null; }+}++function b64decodeJson(s) {+ if (!s) return null;+ try { return JSON.parse(Buffer.from(String(s), 'base64').toString('utf8')); } catch { return null; }+}++// ── Probe a 402 endpoint ────────────────────────────────────────────────────+async function probe402(url, { method, body }) {+ let res;+ try {+ res = await guardedFetch(url, { method, body });+ } catch (err) {+ if (err instanceof SsrfError) {+ throw Object.assign(new Error('Target URL is not a reachable public endpoint'), {+ status: 400, code: 'blocked_url',+ });+ }+ throw Object.assign(new Error(`Could not reach endpoint: ${err?.message}`), {+ status: 502, code: 'endpoint_unreachable',+ });+ }++ if (res.status !== 402) {+ return { free: true, status: res.status, result: safeJson(res.text) ?? res.text };+ }++ const challenge = safeJson(res.text) || b64decodeJson(res.headers.get('payment-required'));+ if (!challenge || !Array.isArray(challenge.accepts)) {+ throw Object.assign(new Error('Service returned an unreadable payment challenge'), {+ status: 502, code: 'invalid_challenge',+ });+ }++ const accept = challenge.accepts.find(+ (a) => typeof a?.network === 'string' && a.network.startsWith('solana'),+ );+ if (!accept) {+ throw Object.assign(new Error('Service has no Solana payment option (only EVM may be supported)'), {+ status: 422, code: 'no_solana_accept',+ detail: { networks: [...new Set(challenge.accepts.map((a) => a?.network).filter(Boolean))] },+ });+ }++ // Security: only allow the known Solana USDC mint — no arbitrary SPL tokens+ if (accept.asset !== USDC_MAINNET_MINT) {+ throw Object.assign(new Error('Service requested payment in a non-USDC asset; sessions only pay Solana USDC'), {+ status: 422, code: 'unsupported_asset',+ detail: { asset: accept.asset, expected: USDC_MAINNET_MINT },+ });+ }++ if (!accept.extra?.feePayer) {+ throw Object.assign(new Error('Service did not advertise a Solana fee payer'), {+ status: 422, code: 'missing_fee_payer',+ });+ }++ const resource =+ challenge.resource && typeof challenge.resource === 'object'+ ? challenge.resource+ : { url: typeof challenge.resource === 'string' ? challenge.resource : url };++ return { challenge, accept, resource };+}++// ── Build and sign the Solana USDC transfer ─────────────────────────────────+async function buildPaymentPayload({ accept, buyer, conn, resourceUrl }) {+ const mint = new PublicKey(accept.asset);+ const payTo = new PublicKey(accept.payTo);+ const feePayer = new PublicKey(accept.extra.feePayer);+ const amount = BigInt(accept.amount);++ const senderAta = getAssociatedTokenAddressSync(+ mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const receiverAta = getAssociatedTokenAddressSync(+ mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const mintInfo = await getMint(conn, mint);++ const ixs = [+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }),+ ];+ const receiverInfo = await conn.getAccountInfo(receiverAta);+ if (!receiverInfo) {+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(+ feePayer, receiverAta, payTo, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ ));+ }+ ixs.push(createTransferCheckedInstruction(+ senderAta, mint, receiverAta, buyer.publicKey,+ amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,+ ));++ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ const message = new TransactionMessage({+ payerKey: feePayer,+ recentBlockhash: blockhash,+ instructions: ixs,+ }).compileToV0Message();+ const vtx = new VersionedTransaction(message);+ vtx.sign([buyer]);++ return {+ x402Version: 2,+ scheme: 'exact',+ network: accept.network,+ resource: { url: resourceUrl, mimeType: 'application/json' },+ accepted: accept,+ payload: { transaction: Buffer.from(vtx.serialize()).toString('base64') },+ };+}++// ── Main handler ─────────────────────────────────────────────────────────────+export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (req.method?.toUpperCase() !== 'POST') {+ return error(res, 405, 'method_not_allowed', 'POST required');+ }++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req, res);+ if (!body) return;++ const sessionToken = body.session_token;+ if (!sessionToken) return error(res, 400, 'missing_token', 'session_token is required');++ const targetUrl = body.url;+ if (!targetUrl) return error(res, 400, 'missing_url', 'url is required');++ const method = body.method === 'POST' ? 'POST' : 'GET';+ const requestBody = method === 'POST' ? body.body ?? null : null;+ const idempotencyKey = body.idempotency_key ?? null;++ // Validate the URL is reachable (not SSRF)+ try {+ validatePublicUrl(targetUrl);+ } catch {+ return error(res, 400, 'invalid_url', 'url must be a public https endpoint');+ }++ const t0 = Date.now();++ // Phase 1: probe the endpoint for its 402 challenge+ let probeResult;+ try {+ probeResult = await probe402(targetUrl, { method, body: requestBody });+ } catch (err) {+ return error(res, err.status ?? 502, err.code ?? 'probe_failed', err.message, err.detail);+ }++ // Endpoint is free — return the result directly without touching the session+ if (probeResult.free) {+ return json(res, 200, {+ ok: true,+ paid: false,+ note: 'Endpoint served response without a 402 — no payment needed.',+ status: probeResult.status,+ result: probeResult.result,+ });+ }++ const { accept, resource, challenge } = probeResult;+ const amountAtomics = BigInt(accept.amount);+ const amountUsd = atomicsToUsd(amountAtomics);++ // Phase 2: governance enforcement — check session, allowlist, budget+ let sessionRecord, reservationId;+ try {+ const reservation = await reserveSessionSpend({+ token: sessionToken,+ url: targetUrl,+ amountAtomics,+ });+ sessionRecord = reservation.session;+ reservationId = reservation.reservationId;+ } catch (err) {+ if (err instanceof SpendGovernorError) {+ return error(res, err.status, err.code, err.message, err.detail);+ }+ throw err;+ }++ // Phase 3: load platform payer and sign+ let keypair;+ try {+ keypair = loadPlatformKeypair();+ } catch (err) {+ // Roll back — we reserved but can't sign+ await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});+ return error(res, 503, 'wallet_unconfigured', 'Platform payment wallet is not configured');+ }++ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ let paymentPayload;+ try {+ paymentPayload = await buildPaymentPayload({+ accept,+ buyer: keypair,+ conn,+ resourceUrl: resource.url,+ });+ } catch (err) {+ await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});+ return error(res, 502, 'build_failed', `Failed to build payment: ${err?.message}`);+ }++ const xPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');++ // Phase 4: submit payment to the endpoint+ let paid;+ try {+ paid = await guardedFetch(targetUrl, {+ method,+ body: requestBody,+ headers: { 'X-PAYMENT': xPayment },+ });+ } catch (err) {+ // Network failure AFTER signing — chain state unknown, do NOT roll back.+ // The wallet may have been debited. Record as 'failed' in the audit log.+ await recordExecution({+ sessionId: sessionRecord.id,+ userId: sessionRecord.user_id,+ endpointUrl: targetUrl,+ method,+ amountAtomics,+ network: accept.network,+ txHash: null,+ payerAddress: keypair.publicKey.toBase58(),+ payeeAddress: accept.payTo,+ status: 'failed',+ errorCode: 'settle_uncertain',+ errorMessage: err?.message,+ durationMs: Date.now() - t0,+ idempotencyKey,+ }).catch(() => {});+ return error(res, 502, 'settle_uncertain',+ 'Payment was submitted but confirmation was not received — do not retry immediately.');+ }++ const paidJson = safeJson(paid.text) ?? paid.text;+ const settled = b64decodeJson(paid.headers.get('x-payment-response'));+ const txHash = settled?.transaction || null;+ const payer = settled?.payer || keypair.publicKey.toBase58();+ const durationMs = Date.now() - t0;++ // Handle endpoint rejection after payment attempt+ if (!paid.ok) {+ if (paid.status === 402) {+ // Explicit pre-settlement rejection — no funds moved, safe to roll back+ await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});+ await recordExecution({+ sessionId: sessionRecord.id,+ userId: sessionRecord.user_id,+ endpointUrl: targetUrl,+ method,+ amountAtomics,+ network: accept.network,+ txHash: null,+ payerAddress: payer,+ payeeAddress: accept.payTo,+ status: 'failed',+ errorCode: 'payment_rejected',+ errorMessage: 'Service rejected the payment before settlement',+ durationMs,+ idempotencyKey,+ }).catch(() => {});+ return error(res, 402, 'payment_rejected',+ 'Service rejected the payment before settlement — budget has been restored.',+ typeof paidJson === 'object' ? paidJson : null);+ }++ // Non-402 error after payment — chain state uncertain+ await recordExecution({+ sessionId: sessionRecord.id,+ userId: sessionRecord.user_id,+ endpointUrl: targetUrl,+ method,+ amountAtomics,+ network: accept.network,+ txHash,+ payerAddress: payer,+ payeeAddress: accept.payTo,+ status: 'failed',+ errorCode: 'upstream_error',+ errorMessage: `Endpoint returned HTTP ${paid.status}`,+ responseBody: typeof paidJson === 'object' ? paidJson : null,+ durationMs,+ idempotencyKey,+ }).catch(() => {});+ return error(res, 502, 'upstream_error',+ `Endpoint returned HTTP ${paid.status} after payment — check wallet activity before retrying.`);+ }++ // Phase 5: success — record the settled execution+ await recordExecution({+ sessionId: sessionRecord.id,+ userId: sessionRecord.user_id,+ endpointUrl: targetUrl,+ method,+ amountAtomics,+ network: accept.network,+ txHash,+ payerAddress: payer,+ payeeAddress: accept.payTo,+ status: 'settled',+ responseBody: typeof paidJson === 'object' ? paidJson : null,+ durationMs,+ idempotencyKey,+ }).catch(() => {});++ return json(res, 200, {+ ok: true,+ paid: true,+ result: paidJson,+ payment: {+ session_id: sessionRecord.id,+ amount_usd: amountUsd,+ network: accept.network,+ payer,+ pay_to: accept.payTo,+ tx_hash: txHash,+ explorer: txHash ? `https://solscan.io/tx/${txHash}` : null,+ },+ session: {+ id: sessionRecord.id,+ spent_usd: atomicsToUsd(sessionRecord.spent_usdc),+ remaining_usd: atomicsToUsd(+ BigInt(sessionRecord.budget_usdc) - BigInt(sessionRecord.spent_usdc),+ ),+ },+ duration_ms: durationMs,+ });+});diff --git a/api/pay/session.js b/api/pay/session.jsnew file mode 100644index 000000000..5019be421--- /dev/null+++ b/api/pay/session.js@@ -0,0 +1,140 @@+// Agent Payment Session API — create, inspect, and cancel payment sessions.+//+// A PaymentSession is a platform-managed spend envelope: developer funds a+// budget from their credits, receives a bearer token, and hands it to an agent.+// The agent spends against the session budget by calling /api/pay/execute —+// no private key required. The platform's wallet signs the x402 transactions.+//+// POST /api/pay/session — create a new session+// GET /api/pay/session/:id — inspect a session (owner only)+// DELETE /api/pay/session/:id — cancel + refund un-spent budget+// GET /api/pay/session/:id/executions — list payments made in a session+// GET /api/pay/session — list all sessions for the caller++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import {+ createPaymentSession,+ getPaymentSession,+ listPaymentSessions,+ cancelPaymentSession,+ listSessionExecutions,+ getPaymentStats,+} from '../_lib/pay/payment-session.js';++async function resolveUser(req, res) {+ const session = await getSessionUser(req, res);+ if (session) return session;+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { id: bearer.userId };+ return null;+}++// Extract :id and :sub from URL path+function parsePath(req) {+ const path = new URL(req.url, 'http://x').pathname;+ // /api/pay/session/:id or /api/pay/session/:id/executions+ const m = path.match(/\/api\/pay\/session\/([^/]+)(?:\/([^/]+))?/);+ return m ? { id: m[1], sub: m[2] ?? null } : { id: null, sub: null };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const user = await resolveUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'authentication required');++ const { id, sub } = parsePath(req);+ const httpMethod = req.method?.toUpperCase();++ // POST /api/pay/session — create+ if (!id && httpMethod === 'POST') {+ if (!method(req, res, ['POST'])) return;+ const body = await readJson(req, res);+ if (!body) return;++ let result;+ try {+ result = await createPaymentSession({+ userId: user.id,+ agentId: body.agent_id ?? null,+ label: body.label,+ budgetUsd: body.budget_usd,+ maxPerTxUsd: body.max_per_tx_usd ?? null,+ allowedHosts: body.allowed_hosts ?? [],+ network: body.network ?? 'solana',+ expirySeconds: body.expiry_seconds ?? 3600,+ metadata: body.metadata ?? {},+ });+ } catch (err) {+ if (err.code === 'insufficient_credits') {+ return error(res, 402, 'insufficient_credits',+ `Insufficient credits — need $${err.required_usd?.toFixed(4)}, have $${err.available_usd?.toFixed(4)}`+ );+ }+ if (err.status === 400 || err.code?.startsWith('invalid_')) {+ return error(res, 400, err.code ?? 'bad_request', err.message);+ }+ throw err;+ }++ return json(res, 201, {+ session: result.session,+ token: result.token,+ note: 'Store this token securely — it is shown once and cannot be recovered.',+ });+ }++ // GET /api/pay/session — list all sessions+ if (!id && httpMethod === 'GET') {+ const url = new URL(req.url, 'http://x');+ const status = url.searchParams.get('status') || null;+ const limit = parseInt(url.searchParams.get('limit') || '20', 10);+ const cursor = url.searchParams.get('cursor') || null;++ const [sessions, stats] = await Promise.all([+ listPaymentSessions(user.id, { status, limit, cursor }),+ getPaymentStats(user.id),+ ]);++ return json(res, 200, { ...sessions, stats });+ }++ if (!id) return error(res, 400, 'bad_request', 'session id required');++ // GET /api/pay/session/:id/executions+ if (sub === 'executions' && httpMethod === 'GET') {+ const session = await getPaymentSession(id, user.id);+ if (!session) return error(res, 404, 'not_found', 'session not found');++ const url = new URL(req.url, 'http://x');+ const limit = parseInt(url.searchParams.get('limit') || '20', 10);+ const cursor = url.searchParams.get('cursor') || null;+ const result = await listSessionExecutions(id, user.id, { limit, cursor });+ return json(res, 200, result);+ }++ // GET /api/pay/session/:id+ if (httpMethod === 'GET') {+ const session = await getPaymentSession(id, user.id);+ if (!session) return error(res, 404, 'not_found', 'session not found');+ return json(res, 200, { session });+ }++ // DELETE /api/pay/session/:id+ if (httpMethod === 'DELETE') {+ const result = await cancelPaymentSession(id, user.id);+ if (!result) return error(res, 404, 'not_found', 'session not found or already closed');+ return json(res, 200, {+ cancelled: true,+ session_id: id,+ refunded_usd: result.refunded_usd,+ });+ }++ return error(res, 405, 'method_not_allowed', `${httpMethod} not supported`);+});diff --git a/api/sniper/strategy.js b/api/sniper/strategy.jsindex 024ef7f98..6fc80e5d4 100644--- a/api/sniper/strategy.js+++ b/api/sniper/strategy.js@@ -58,7 +58,7 @@ const STRATEGY_SCHEMA = z.object({// trigger: what arms this strategy.// new_mint — snipe new pump.fun launches off the PumpPortal feed (default).// first_claim — snipe a creator's coin the first time they EVER claim rewards.- trigger: z.enum(['new_mint', 'first_claim', 'intel_confirmed', 'prelaunch_radar']).optional(),+ trigger: z.enum(['new_mint', 'first_claim', 'intel_confirmed', 'prelaunch_radar', 'alpha_hunt']).optional(),buy_delay_ms: z.union([z.string(), z.number()]).optional(),// prelaunch_radar gates (null clears)min_creator_graduated_radar: optInt,@@ -97,6 +97,12 @@ const STRATEGY_SCHEMA = z.object({max_concentration_top1: z.union([z.string(), z.number()]).nullable().optional(),avoid_dev_dump: z.boolean().optional(),allowed_categories: z.array(z.string()).nullable().optional(),+ // alpha_hunt specific filters (null clears)+ alpha_min_smart_money: z.number().int().min(0).max(20).optional(),+ alpha_min_organic_score: z.number().min(0).max(100).optional(),+ alpha_max_mcap_usd: z.number().min(0).optional(),+ alpha_narrative_keywords: z.array(z.string()).max(10).optional(),+ alpha_min_quality_score: z.number().int().min(0).max(100).optional(),// Notifications: personal Telegram chat ID for this strategy's buy/sell alerts.// Must be a numeric chat ID (positive = user/group, negative = supergroup/channel).telegram_chat_id: z.string().regex(/^-?[0-9]+$/).nullable().optional(),@@ -229,6 +235,11 @@ async function listStrategies(req, res, userId) {avoid_dev_dump: s.avoid_dev_dump ?? true,allowed_categories: s.allowed_categories || null,telegram_chat_id: s.telegram_chat_id || null,+ alpha_min_smart_money: s.alpha_min_smart_money != null ? Number(s.alpha_min_smart_money) : null,+ alpha_min_organic_score: s.alpha_min_organic_score != null ? Number(s.alpha_min_organic_score) : null,+ alpha_max_mcap_usd: s.alpha_max_mcap_usd != null ? Number(s.alpha_max_mcap_usd) : null,+ alpha_narrative_keywords: s.alpha_narrative_keywords || null,+ alpha_min_quality_score: s.alpha_min_quality_score != null ? Number(s.alpha_min_quality_score) : null,summary: {open_positions: sum ? Number(sum.open_positions) : 0,closed_positions: sum ? Number(sum.closed_positions) : 0,@@ -286,6 +297,8 @@ async function upsertStrategy(req, res, userId) {min_quality_score: null, max_bundle_score: null, max_concentration_top1: null,avoid_dev_dump: true, allowed_categories: null,telegram_chat_id: null,+ alpha_min_smart_money: null, alpha_min_organic_score: null, alpha_max_mcap_usd: null,+ alpha_narrative_keywords: null, alpha_min_quality_score: null,};const next = {@@ -323,6 +336,11 @@ async function upsertStrategy(req, res, userId) {avoid_dev_dump: p.avoid_dev_dump ?? cur.avoid_dev_dump ?? true,allowed_categories: 'allowed_categories' in p ? (Array.isArray(p.allowed_categories) ? p.allowed_categories.filter(Boolean) : null) : (cur.allowed_categories || null),telegram_chat_id: 'telegram_chat_id' in p ? (p.telegram_chat_id || null) : (cur.telegram_chat_id || null),+ alpha_min_smart_money: 'alpha_min_smart_money' in p ? (p.alpha_min_smart_money == null ? null : Math.min(20, Math.max(0, Math.round(Number(p.alpha_min_smart_money))))) : (cur.alpha_min_smart_money != null ? Number(cur.alpha_min_smart_money) : null),+ alpha_min_organic_score: 'alpha_min_organic_score' in p ? (p.alpha_min_organic_score == null ? null : Math.min(100, Math.max(0, Number(p.alpha_min_organic_score)))) : (cur.alpha_min_organic_score != null ? Number(cur.alpha_min_organic_score) : null),+ alpha_max_mcap_usd: 'alpha_max_mcap_usd' in p ? (p.alpha_max_mcap_usd == null ? null : Math.max(0, Number(p.alpha_max_mcap_usd))) : (cur.alpha_max_mcap_usd != null ? Number(cur.alpha_max_mcap_usd) : null),+ alpha_narrative_keywords: 'alpha_narrative_keywords' in p ? (Array.isArray(p.alpha_narrative_keywords) ? p.alpha_narrative_keywords.filter(Boolean).slice(0, 10) : null) : (cur.alpha_narrative_keywords || null),+ alpha_min_quality_score: 'alpha_min_quality_score' in p ? (p.alpha_min_quality_score == null ? null : Math.min(100, Math.max(0, Math.round(Number(p.alpha_min_quality_score))))) : (cur.alpha_min_quality_score != null ? Number(cur.alpha_min_quality_score) : null),};// Mandatory stop-loss — never let the DB constraint be the first line of defense.@@ -353,7 +371,9 @@ async function upsertStrategy(req, res, userId) {min_oracle_score,min_creator_graduated_radar, require_smart_money_funder, radar_max_age_ms,min_quality_score, max_bundle_score, max_concentration_top1,- avoid_dev_dump, allowed_categories, telegram_chat_id, updated_at)+ avoid_dev_dump, allowed_categories, telegram_chat_id,+ alpha_min_smart_money, alpha_min_organic_score, alpha_max_mcap_usd,+ alpha_narrative_keywords, alpha_min_quality_score, updated_at)values(${p.agent_id}, ${userId}, ${p.network}, ${next.enabled}, ${next.kill_switch},${next.trigger}, ${next.buy_delay_ms}, ${next.min_claim_lamports}, ${next.max_claim_lamports}, ${next.first_claim_max_age_seconds},@@ -365,7 +385,9 @@ async function upsertStrategy(req, res, userId) {${next.min_oracle_score},${next.min_creator_graduated_radar}, ${next.require_smart_money_funder}, ${next.radar_max_age_ms},${next.min_quality_score}, ${next.max_bundle_score}, ${next.max_concentration_top1},- ${next.avoid_dev_dump}, ${next.allowed_categories}, ${next.telegram_chat_id}, now())+ ${next.avoid_dev_dump}, ${next.allowed_categories}, ${next.telegram_chat_id},+ ${next.alpha_min_smart_money}, ${next.alpha_min_organic_score}, ${next.alpha_max_mcap_usd},+ ${next.alpha_narrative_keywords}, ${next.alpha_min_quality_score}, now())on conflict (agent_id, network) do update setenabled = excluded.enabled,kill_switch = excluded.kill_switch,@@ -401,6 +423,11 @@ async function upsertStrategy(req, res, userId) {avoid_dev_dump = excluded.avoid_dev_dump,allowed_categories = excluded.allowed_categories,telegram_chat_id = excluded.telegram_chat_id,+ alpha_min_smart_money = excluded.alpha_min_smart_money,+ alpha_min_organic_score = excluded.alpha_min_organic_score,+ alpha_max_mcap_usd = excluded.alpha_max_mcap_usd,+ alpha_narrative_keywords = excluded.alpha_narrative_keywords,+ alpha_min_quality_score = excluded.alpha_min_quality_score,updated_at = now()returning *`;@@ -444,6 +471,11 @@ async function upsertStrategy(req, res, userId) {avoid_dev_dump: row.avoid_dev_dump ?? true,allowed_categories: row.allowed_categories || null,telegram_chat_id: row.telegram_chat_id || null,+ alpha_min_smart_money: row.alpha_min_smart_money != null ? Number(row.alpha_min_smart_money) : null,+ alpha_min_organic_score: row.alpha_min_organic_score != null ? Number(row.alpha_min_organic_score) : null,+ alpha_max_mcap_usd: row.alpha_max_mcap_usd != null ? Number(row.alpha_max_mcap_usd) : null,+ alpha_narrative_keywords: row.alpha_narrative_keywords || null,+ alpha_min_quality_score: row.alpha_min_quality_score != null ? Number(row.alpha_min_quality_score) : null,},});}diff --git a/data/changelog.json b/data/changelog.jsonindex f6691d0af..8861b9020 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,23 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-26",+ "title": "Agent Payment Sessions — governed x402 spend without private keys",+ "summary": "Agents can now pay x402 APIs without holding a private key. Create a Payment Session with a budget (drawn from credits), hand the token to an agent, and the platform signs every Solana USDC transfer. Five governance checks fire before any money moves: token auth, session status, URL allowlist, per-tx ceiling, and atomic budget reservation. Sessions expire automatically; un-spent budget is refunded on cancel. Also ships: a /payments dashboard to manage sessions and view payment history, and the @three-ws/agentcore-payments-mcp MCP server with create_payment_session, pay_with_session, check_payment_session, list_payment_sessions, and cancel_payment_session tools.",+ "tags": [+ "feature",+ "sdk"+ ],+ "link": "/payments"+ },+ {+ "date": "2026-06-26",+ "title": "4 new agent capabilities: Alpha Hunt, Coin Launcher, Creator Auto-Claim, and Market Maker",+ "summary": "Agents can now do a lot more. Alpha Hunt is a new strategy trigger that scores coins using smart-money signals, organic growth patterns, quality scores, and narrative keywords — finding undervalued gems before they move. Coin Launcher lets an agent autonomously launch coins on pump.fun on a schedule, with configurable metadata templates, initial dev buys, and Telegram notifications. Creator Auto-Claim watches your agent's launched coins and automatically claims creator fees when they exceed a configurable threshold, with optional reinvestment into the sniper buy budget. Market Maker uses Jito-accelerated execution to provide liquidity on any pump.fun coin, placing buy and sell orders in a configured spread band to capture the spread. All four capabilities are wired into the agent-sniper worker and configurable from the agent edit page.",+ "tags": ["feature"],+ "link": "/play"+ },{"date": "2026-06-26","title": "Oracle activity data across every surface — 8 pages now show live win rates, agents armed, and platform stats",diff --git a/data/pages.json b/data/pages.jsonindex 03e85dbd6..1a85fb9d1 100644--- a/data/pages.json+++ b/data/pages.json@@ -1258,6 +1258,14 @@"changefreq": "weekly","added": "2026-06-21"},+ {+ "path": "/payments",+ "title": "Agent Payment Sessions",+ "description": "Create budget-limited payment sessions for AI agents. Governance-enforced spend limits, URL allowlists, and expiry — agents pay x402 APIs without holding a private key.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-06-26"+ },{"path": "/login","title": "Sign in",diff --git a/package.json b/package.jsonindex ff52c1939..a7407dd22 100644--- a/package.json+++ b/package.json@@ -67,6 +67,7 @@"packages/alerts-mcp","packages/notifications-mcp","packages/billing-mcp",+ "packages/agentcore-payments-mcp","packages/activity-mcp","packages/agenc-mcp","packages/agora-mcp",diff --git a/packages/agentcore-payments-mcp/LICENSE b/packages/agentcore-payments-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/agentcore-payments-mcp/LICENSE@@ -0,0 +1,180 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship made available under+ the License, as indicated by a copyright notice that is included in+ or attached to the work (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other transformations+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean, as submitted to the Licensor for inclusion+ in the Work by the copyright owner or by an individual or Legal Entity+ authorized to submit on behalf of the copyright owner. For the purposes+ of this definition, "submitted" means any form of electronic, verbal,+ or written communication sent to the Licensor or its representatives,+ including but not limited to communication on electronic mailing lists,+ source code control systems, and issue tracking systems that are managed+ by, or on behalf of, the Licensor for the purpose of discussing and+ improving the Work, but excluding communication that is conspicuously+ marked or designated in writing by the copyright owner as "Not a+ Contribution."++ "Contributor" shall mean Licensor and any Legal Entity on behalf of+ whom a Contribution has been received by the Licensor and included+ within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by the combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a cross-claim+ or counterclaim in a lawsuit) alleging that the Work or any+ Contribution embodied within the Work constitutes direct or contributory+ patent infringement, then any patent licenses granted to You under+ this License for that Work shall terminate as of the date such+ litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or Derivative+ Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, You must include a readable copy of the+ attribution notices contained within such NOTICE file, in+ at least one of the following places: within a NOTICE text+ file distributed as part of the Derivative Works; within+ the Source form or documentation, if provided along with the+ Derivative Works; or, within a display generated by the+ Derivative Works, if and wherever such third-party notices+ normally appear. The contents of the NOTICE file are for+ informational purposes only and do not modify the License.+ You may add Your own attribution notices within Derivative+ Works that You distribute, alongside or in addition to the+ NOTICE text from the Work, provided that such additional+ attribution notices cannot be construed as modifying the License.++ You may add Your own license statement for Your modifications and+ may provide additional grant of rights to use, copy, modify, merge,+ publish, distribute, sublicense, and/or sell copies of the+ Derivative Works, and to permit persons to whom the Derivative Works+ are furnished to do so.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or reproducing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or exemplary damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or all other+ commercial damages or losses), even if such Contributor has been+ advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may offer only+ conditions consistent with this License.++ END OF TERMS AND CONDITIONS++ Copyright 2026 nirholas++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/agentcore-payments-mcp/package.json b/packages/agentcore-payments-mcp/package.jsonnew file mode 100644index 000000000..2ec1c0587--- /dev/null+++ b/packages/agentcore-payments-mcp/package.json@@ -0,0 +1,60 @@+{+ "name": "@three-ws/agentcore-payments-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/agentcore-payments-mcp",+ "description": "Platform-managed agent payment sessions — create a budget, pay any x402 endpoint without holding a private key. Governed by spend limits, URL allowlists, and per-tx ceilings. The agent proposes spend; three.ws governance enforces policy.",+ "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/agentcore-payments-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "model-context-protocol",+ "three.ws",+ "x402",+ "payments",+ "agent-payments",+ "payment-session",+ "spend-governor",+ "solana",+ "usdc",+ "ai-agent",+ "agentcore"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "agentcore-payments-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",+ "zod": "^3.23.8"+ }+}diff --git a/packages/agentcore-payments-mcp/server.json b/packages/agentcore-payments-mcp/server.jsonnew file mode 100644index 000000000..2f21f023a--- /dev/null+++ b/packages/agentcore-payments-mcp/server.json@@ -0,0 +1,61 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/agentcore-payments-mcp",+ "title": "three.ws Agent Payments",+ "description": "Platform-managed payment sessions for AI agents — pay any x402 endpoint without holding a private key. Governance-enforced budget limits, URL allowlists, and per-tx ceilings.",+ "websiteUrl": "https://three.ws",+ "icons": [+ {+ "src": "https://three.ws/three-ws-mcp-icon.svg",+ "mimeType": "image/svg+xml",+ "sizes": ["any"]+ }+ ],+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github",+ "subfolder": "packages/agentcore-payments-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/agentcore-payments-mcp",+ "version": "0.1.0",+ "runtimeHint": "npx",+ "transport": {+ "type": "stdio"+ },+ "environmentVariables": [+ {+ "name": "THREE_WS_SESSION",+ "description": "Your three.ws session token (value of the `__Host-sid` cookie from a signed-in browser). Required for account management operations: create_payment_session, list_payment_sessions, check_payment_session, cancel_payment_session.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ },+ {+ "name": "PAYMENT_SESSION_TOKEN",+ "description": "A payment session bearer token (starts with 'pss_') from create_payment_session. Used by the agent for pay_with_session calls when no inline token is passed. Treat like a spending card — it authorizes payments up to the session's budget.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ },+ {+ "name": "THREE_WS_BASE",+ "description": "Base URL of the three.ws API. Override only when self-hosting or targeting a preview deployment.",+ "format": "string",+ "isRequired": false,+ "default": "https://three.ws"+ },+ {+ "name": "THREE_WS_TIMEOUT_MS",+ "description": "Per-request HTTP timeout in milliseconds. x402 payments involve on-chain settlement so this should be generous (default: 30000).",+ "format": "number",+ "isRequired": false,+ "default": "30000"+ }+ ]+ }+ ]+}diff --git a/packages/agentcore-payments-mcp/src/config.js b/packages/agentcore-payments-mcp/src/config.jsnew file mode 100644index 000000000..744e352de--- /dev/null+++ b/packages/agentcore-payments-mcp/src/config.js@@ -0,0 +1,35 @@+// Config and env for the agentcore-payments-mcp server.+//+// This server manages platform-funded payment sessions — the developer credentials+// are a three.ws session (for account-scoped session creation/management) and a+// payment session token (for the agent to execute payments). Private keys never+// touch the MCP client; the platform wallet handles all signing.++export function env(key, fallback) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;+}++export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');+export const HTTP_TIMEOUT_MS = (() => {+ const raw = env('THREE_WS_TIMEOUT_MS');+ if (raw === undefined) return 30000;+ 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;+})();++// three.ws session cookie — used for account-scoped operations (creating sessions,+// listing sessions). Same cookie the browser carries after signing in.+export const THREE_WS_SESSION = env('THREE_WS_SESSION', '');++// Default payment session token — agents set this to a pre-created session token+// so they can call pay_with_session without passing a token each time.+// Alternatively, agents can pass token inline per-call.+export const PAYMENT_SESSION_TOKEN = env('PAYMENT_SESSION_TOKEN', '');++export const USER_AGENT = '@three-ws/agentcore-payments-mcp';diff --git a/packages/agentcore-payments-mcp/src/index.js b/packages/agentcore-payments-mcp/src/index.jsnew file mode 100644index 000000000..c24727c91--- /dev/null+++ b/packages/agentcore-payments-mcp/src/index.js@@ -0,0 +1,115 @@+#!/usr/bin/env node+// @three-ws/agentcore-payments-mcp — Agent Payment Sessions over MCP.+//+// Implements the governance-first payment pattern:+// "The agent does not hold a wallet. It proposes spend. Governance enforces policy."+//+// Tools:+// create_payment_session — fund a session from credits; get a bearer token+// pay_with_session — execute x402 payment via session (no private key)+// check_payment_session — inspect budget / status / executions+// list_payment_sessions — list sessions + aggregate spend stats+// cancel_payment_session — cancel + refund un-spent budget+//+// Two credential types:+// THREE_WS_SESSION — your account session for management operations+// PAYMENT_SESSION_TOKEN — the session bearer token for agent payments+//+// Run standalone:+// node packages/agentcore-payments-mcp/src/index.js+//+// Wire into Claude Code / Cursor — see README.md.++import { createRequire } from 'node:module';++import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';++import { def as createSession } from './tools/create-session.js';+import { def as payWithSession } from './tools/pay-with-session.js';+import { def as checkSession } from './tools/check-session.js';+import { def as listSessions } from './tools/list-sessions.js';+import { def as cancelSession } from './tools/cancel-session.js';++const require = createRequire(import.meta.url);+const { version: PKG_VERSION } = require('../package.json');++export const TOOLS = [+ createSession,+ payWithSession,+ checkSession,+ listSessions,+ cancelSession,+];++export function buildServer() {+ const server = new McpServer(+ {+ name: 'agentcore-payments-mcp',+ title: 'three.ws Agent Payments',+ version: PKG_VERSION,+ },+ {+ capabilities: { tools: {} },+ instructions:+ 'three.ws Agent Payment Sessions — governance-first x402 micropayments for AI agents. ' ++ 'No private key required. Create a session with a budget, give the token to an agent, ' ++ 'and the agent pays x402 endpoints via pay_with_session. The platform\'s wallet signs ' ++ 'all transactions; spend is bounded by your session budget, URL allowlist, and per-tx ceiling. ' ++ 'Management operations (create/list/cancel) require THREE_WS_SESSION. ' ++ 'Payment execution requires PAYMENT_SESSION_TOKEN (or pass inline to pay_with_session). ' ++ 'Workflow: 1) create_payment_session to get a token → 2) pay_with_session to call paid endpoints → ' ++ '3) check_payment_session to monitor spend → 4) cancel_payment_session to reclaim unused budget.',+ },+ );++ for (const tool of TOOLS) {+ server.tool(tool.name, tool.description, tool.inputSchema, async (args) => {+ try {+ const result = await tool.handler(args);+ return {+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],+ };+ } catch (err) {+ const code = err?.code ?? 'error';+ const status = err?.status ?? null;+ const body = err?.body ?? null;+ const detail = body+ ? `\n\nUpstream detail: ${JSON.stringify(body, null, 2)}`+ : '';+ return {+ content: [+ {+ type: 'text',+ text: JSON.stringify(+ {+ ok: false,+ error: err?.message ?? 'unknown error',+ code,+ ...(status ? { status } : {}),+ },+ null,+ 2,+ ),+ },+ ],+ isError: true,+ };+ }+ });+ }++ return server;+}++// Start the server when run directly+const isMain =+ typeof process !== 'undefined' &&+ process.argv[1] &&+ (process.argv[1].endsWith('index.js') || process.argv[1].endsWith('agentcore-payments-mcp'));++if (isMain) {+ const server = buildServer();+ const transport = new StdioServerTransport();+ await server.connect(transport);+}diff --git a/packages/agentcore-payments-mcp/src/lib/api.js b/packages/agentcore-payments-mcp/src/lib/api.jsnew file mode 100644index 000000000..4b267b933--- /dev/null+++ b/packages/agentcore-payments-mcp/src/lib/api.js@@ -0,0 +1,76 @@+// HTTP client for the three.ws Payment Session API.+// Routes:+// POST /api/pay/session — create session (session auth)+// GET /api/pay/session — list sessions (session auth)+// GET /api/pay/session/:id — get session (session auth)+// DELETE /api/pay/session/:id — cancel session (session auth)+// GET /api/pay/session/:id/executions — list executions (session auth)+// POST /api/pay/execute — execute x402 payment (session token auth)++import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT, THREE_WS_SESSION } from '../config.js';++export async function apiRequest(path, {+ method = 'GET',+ query,+ body,+ auth = false,+ sessionTokenAuth = null,+} = {}) {+ if (auth && !THREE_WS_SESSION) {+ throw Object.assign(+ new Error(+ `${path} requires your three.ws session. Set THREE_WS_SESSION to the ` ++ 'value of your `__Host-sid` cookie from a signed-in three.ws browser session.',+ ),+ { code: 'no_session', status: 401 },+ );+ }++ 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,+ ...(auth && THREE_WS_SESSION ? { cookie: `__Host-sid=${THREE_WS_SESSION}` } : {}),+ ...(sessionTokenAuth ? { 'x-payment-session': sessionTokenAuth } : {}),+ ...(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: data?.code ?? 'upstream_error', status: res.status, body: data });+ }+ return data;+}diff --git a/packages/agentcore-payments-mcp/src/tools/cancel-session.js b/packages/agentcore-payments-mcp/src/tools/cancel-session.jsnew file mode 100644index 000000000..df7bdbda0--- /dev/null+++ b/packages/agentcore-payments-mcp/src/tools/cancel-session.js@@ -0,0 +1,34 @@+// `cancel_payment_session` — cancel a session and refund un-spent budget to credits.++import { z } from 'zod';+import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'cancel_payment_session',+ title: 'Cancel a payment session and refund unused budget',+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },+ description:+ 'Cancel an active payment session. The un-spent portion of the budget is immediately refunded ' ++ 'to your credit balance. Already-completed payments are not reversed. ' ++ 'Idempotent — safe to call on an already-cancelled session. Requires THREE_WS_SESSION.',+ inputSchema: {+ session_id: z.string().uuid()+ .describe('UUID of the session to cancel.'),+ },+ async handler(args) {+ const data = await apiRequest(`/api/pay/session/${args.session_id}`, {+ method: 'DELETE',+ auth: true,+ });++ return {+ ok: true,+ cancelled: data.cancelled,+ session_id: data.session_id,+ refunded_usd: data.refunded_usd,+ note: data.refunded_usd > 0+ ? `$${data.refunded_usd.toFixed(4)} has been returned to your credit balance.`+ : 'No budget remained to refund (session was fully spent).',+ };+ },+};diff --git a/packages/agentcore-payments-mcp/src/tools/check-session.js b/packages/agentcore-payments-mcp/src/tools/check-session.jsnew file mode 100644index 000000000..f74a9d60b--- /dev/null+++ b/packages/agentcore-payments-mcp/src/tools/check-session.js@@ -0,0 +1,40 @@+// `check_payment_session` — inspect a session's budget, spend, and status.+//+// Returns remaining budget, status, expiry, and recent payment executions.+// Use before a pay_with_session call to confirm sufficient budget remains.++import { z } from 'zod';+import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'check_payment_session',+ title: 'Check a payment session\'s budget and status',+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },+ description:+ 'Inspect a payment session: budget, amount spent, remaining budget, status (active/exhausted/expired/cancelled), ' ++ 'expiry time, allowlist, and per-tx ceiling. Optionally include recent payment executions. ' ++ 'Requires THREE_WS_SESSION (only the session owner can read it).',+ inputSchema: {+ session_id: z.string().uuid()+ .describe('UUID of the payment session to inspect.'),+ include_executions: z.boolean().default(false)+ .describe('If true, include the 10 most recent payment executions for this session.'),+ },+ async handler(args) {+ const [sessionData, execData] = await Promise.all([+ apiRequest(`/api/pay/session/${args.session_id}`, { auth: true }),+ args.include_executions+ ? apiRequest(`/api/pay/session/${args.session_id}/executions`, {+ auth: true,+ query: { limit: '10' },+ })+ : Promise.resolve(null),+ ]);++ return {+ ok: true,+ session: sessionData.session,+ ...(execData ? { recent_executions: execData.items } : {}),+ };+ },+};diff --git a/packages/agentcore-payments-mcp/src/tools/create-session.js b/packages/agentcore-payments-mcp/src/tools/create-session.jsnew file mode 100644index 000000000..187697b75--- /dev/null+++ b/packages/agentcore-payments-mcp/src/tools/create-session.js@@ -0,0 +1,64 @@+// `create_payment_session` — fund a new payment session from your credits.+//+// Creates a spend envelope: the platform reserves the budget from your credit+// balance and returns a one-time bearer token. Hand this token to an agent via+// PAYMENT_SESSION_TOKEN or pass it inline to pay_with_session. When the session+// expires or is cancelled, the un-spent budget is refunded to your credits.+//+// Required: THREE_WS_SESSION (your account session for credit deduction).++import { z } from 'zod';+import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'create_payment_session',+ title: 'Create a funded agent payment session',+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ description:+ 'Create a platform-managed payment session that funds agent x402 payments from your credits. ' ++ 'The agent never needs a private key — it uses the returned session token to call pay_with_session. ' ++ 'Governance enforces your budget_usd ceiling, optional per-payment cap (max_per_tx_usd), URL allowlist, ' ++ 'and time expiry. Un-spent budget is automatically refunded on cancel or expiry. ' ++ 'Returns: session object + token (shown once — store securely). Requires THREE_WS_SESSION.',+ inputSchema: {+ budget_usd: z.number().positive()+ .describe('Total budget in USD to allocate to this session (drawn from your credits). Min $0.001, max $1000.'),+ label: z.string().max(120).optional()+ .describe('Human-readable label for this session (e.g. "Research run #4").'),+ expiry_seconds: z.number().int().min(60).max(7776000).default(3600)+ .describe('Session lifetime in seconds. After expiry, payments are rejected. Default: 3600 (1 hour).'),+ max_per_tx_usd: z.number().positive().optional()+ .describe('Optional per-payment ceiling in USD. Payments exceeding this are rejected before any money moves.'),+ allowed_hosts: z.array(z.string()).max(50).optional()+ .describe('If set, only allow payments to endpoints at these hosts (e.g. ["api.weather.com"]). Empty = any host.'),+ agent_id: z.string().uuid().optional()+ .describe('Optional: restrict this session token to a specific agent identity UUID.'),+ network: z.enum(['solana', 'base']).default('solana')+ .describe('Settlement network for x402 payments. Default: solana.'),+ metadata: z.record(z.any()).optional()+ .describe('Optional arbitrary metadata to attach to this session for bookkeeping.'),+ },+ async handler(args) {+ const data = await apiRequest('/api/pay/session', {+ method: 'POST',+ auth: true,+ body: {+ budget_usd: args.budget_usd,+ label: args.label ?? '',+ expiry_seconds: args.expiry_seconds ?? 3600,+ max_per_tx_usd: args.max_per_tx_usd ?? null,+ allowed_hosts: args.allowed_hosts ?? [],+ agent_id: args.agent_id ?? null,+ network: args.network ?? 'solana',+ metadata: args.metadata ?? {},+ },+ });++ return {+ ok: true,+ session: data.session,+ token: data.token,+ note: data.note ?? 'Store this token securely — it is shown once and cannot be recovered. Set PAYMENT_SESSION_TOKEN to use it as the default.',+ };+ },+};diff --git a/packages/agentcore-payments-mcp/src/tools/list-sessions.js b/packages/agentcore-payments-mcp/src/tools/list-sessions.jsnew file mode 100644index 000000000..b60f5bcc3--- /dev/null+++ b/packages/agentcore-payments-mcp/src/tools/list-sessions.js@@ -0,0 +1,36 @@+// `list_payment_sessions` — list your payment sessions and aggregate stats.++import { z } from 'zod';+import { apiRequest } from '../lib/api.js';++export const def = {+ name: 'list_payment_sessions',+ title: 'List payment sessions and spending stats',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: false },+ description:+ 'List your payment sessions with aggregate spending stats. Filter by status. ' ++ 'Stats include: total budget allocated, total spent, active/exhausted/expired counts, ' ++ 'settled payment count, and unique endpoints paid. Requires THREE_WS_SESSION.',+ inputSchema: {+ status: z.enum(['active', 'exhausted', 'expired', 'cancelled']).optional()+ .describe('Filter by session status. Omit to return all sessions.'),+ limit: z.number().int().min(1).max(100).default(20)+ .describe('Number of sessions to return (max 100).'),+ },+ async handler(args) {+ const data = await apiRequest('/api/pay/session', {+ auth: true,+ query: {+ ...(args.status ? { status: args.status } : {}),+ limit: String(args.limit ?? 20),+ },+ });++ return {+ ok: true,+ sessions: data.items,+ stats: data.stats,+ has_more: !!data.next_cursor,+ };+ },+};diff --git a/packages/agentcore-payments-mcp/src/tools/pay-with-session.js b/packages/agentcore-payments-mcp/src/tools/pay-with-session.jsnew file mode 100644index 000000000..ee81faa9f--- /dev/null+++ b/packages/agentcore-payments-mcp/src/tools/pay-with-session.js@@ -0,0 +1,81 @@+// `pay_with_session` — pay an x402 endpoint using a payment session token.+//+// The agent proposes spend; governance enforces policy. No private key required.+// The platform's wallet signs the Solana USDC transfer on behalf of the session.+//+// Governance checks (in order, before any money moves):+// 1. Token verified (HMAC checked server-side)+// 2. Session is active and not expired+// 3. Target URL host is in the session's allowlist (if one was set)+// 4. Payment amount does not exceed the per-transaction ceiling (if set)+// 5. Remaining budget is sufficient (atomic, race-safe)++import { z } from 'zod';+import { apiRequest } from '../lib/api.js';+import { PAYMENT_SESSION_TOKEN } from '../config.js';++export const def = {+ name: 'pay_with_session',+ title: 'Pay an x402 endpoint via a payment session',+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Execute an x402 micropayment against a paid API or MCP endpoint using a Payment Session token. ' ++ 'The platform signs the Solana USDC transfer — no private key needed by the agent. ' ++ 'Governance enforces budget limits, URL allowlists, and per-tx ceilings before any money moves. ' ++ 'Endpoints that respond without a 402 are called for free. ' ++ 'Returns the endpoint\'s response + payment receipt. ' ++ 'Uses PAYMENT_SESSION_TOKEN env var if token is not passed inline.',+ inputSchema: {+ url: z.string().url()+ .describe('The x402 endpoint URL to pay and call.'),+ method: z.enum(['GET', 'POST']).default('GET')+ .describe('HTTP method. Default: GET.'),+ body: z.record(z.any()).optional()+ .describe('JSON body for POST requests.'),+ token: z.string().optional()+ .describe('Payment session token (starts with "pss_"). Falls back to PAYMENT_SESSION_TOKEN env var.'),+ idempotency_key: z.string().max(128).optional()+ .describe('Optional idempotency key to prevent double-billing on retries.'),+ },+ async handler(args) {+ const token = args.token || PAYMENT_SESSION_TOKEN;+ if (!token) {+ throw Object.assign(+ new Error(+ 'No payment session token provided. Pass `token` inline or set PAYMENT_SESSION_TOKEN. ' ++ 'Create a session with create_payment_session first.',+ ),+ { code: 'no_token' },+ );+ }++ const data = await apiRequest('/api/pay/execute', {+ method: 'POST',+ body: {+ session_token: token,+ url: args.url,+ method: args.method ?? 'GET',+ body: args.body ?? null,+ idempotency_key: args.idempotency_key ?? null,+ },+ });++ if (!data.paid) {+ return {+ ok: true,+ paid: false,+ note: data.note ?? 'Endpoint served a free response — no payment was required.',+ result: data.result,+ };+ }++ return {+ ok: true,+ paid: true,+ result: data.result,+ payment: data.payment,+ session: data.session,+ duration_ms: data.duration_ms,+ };+ },+};diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex fe7d00d21..732b20e29 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -1207,6 +1207,10 @@<a class="snav-link" href="#section-brain">Brain</a><a class="snav-link" href="#section-distribute">Distribute</a><a class="snav-link" href="#section-money">Money</a>+ <a class="snav-link" href="#section-alpha-hunt">Alpha Hunt</a>+ <a class="snav-link" href="#section-launcher">Launcher</a>+ <a class="snav-link" href="#section-auto-claim">Auto-Claim</a>+ <a class="snav-link" href="#section-market-maker">Market Maker</a><a class="snav-link" href="#section-advanced">Advanced</a></nav>@@ -1880,6 +1884,270 @@</section></div><!-- /section-money -->+ <!-- ═══════════════════════════════════════+ ALPHA HUNT+ ═══════════════════════════════════════ -->+ <div class="edit-section" id="section-alpha-hunt">+ <div class="edit-section-label">Alpha Hunt</div>++ <section class="edit-panel" id="panel-alpha-hunt" role="region" aria-label="Alpha Hunt">+ <div class="subsection-title">Alpha Hunt</div>+ <p class="hint">Find undervalued gems using smart-money signals and organic growth patterns</p>++ <div class="form-group">+ <label class="form-label" for="alpha-trigger">Trigger</label>+ <select class="form-input" id="alpha-trigger" disabled>+ <option value="alpha_hunt">Alpha Hunt</option>+ </select>+ <p class="hint" style="margin-top:0.382rem">Strategy trigger — alpha hunt mode scans continuously for qualifying tokens.</p>+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-min-smart-money">Min Smart Money Wallets</label>+ <input class="form-input" id="alpha-min-smart-money" type="number" min="0" step="1" placeholder="e.g. 2" />+ <p class="hint" style="margin-top:0.382rem">Proven wallets that must be buying</p>+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-min-quality">Min Quality Score</label>+ <input class="form-input" id="alpha-min-quality" type="number" min="0" max="100" step="1" placeholder="e.g. 60" />+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-min-organic">Min Organic Score</label>+ <input class="form-input" id="alpha-min-organic" type="number" min="0" max="100" step="1" placeholder="e.g. 50" />+ <p class="hint" style="margin-top:0.382rem">Filters coordinated/bot-driven launches</p>+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-max-mcap">Max Market Cap (USD)</label>+ <input class="form-input" id="alpha-max-mcap" type="number" min="0" step="100" placeholder="e.g. 5000" />+ <p class="hint" style="margin-top:0.382rem">Only hunt below this cap</p>+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-keywords">Narrative Keywords</label>+ <input class="form-input" id="alpha-keywords" type="text" placeholder="ai, dog, meme" />+ <p class="hint" style="margin-top:0.382rem">Comma-separated — any keyword match triggers consideration</p>+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-budget-sol">Buy Budget (SOL)</label>+ <input class="form-input" id="alpha-budget-sol" type="number" min="0" step="0.01" placeholder="e.g. 0.1" />+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-take-profit-pct">Take Profit (%)</label>+ <input class="form-input" id="alpha-take-profit-pct" type="number" min="0" step="1" placeholder="e.g. 200" />+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-stop-loss-pct">Stop Loss (%)</label>+ <input class="form-input" id="alpha-stop-loss-pct" type="number" min="0" max="100" step="1" placeholder="e.g. 30" />+ </div>+ <div class="form-group">+ <label class="form-label" for="alpha-mev-tip">MEV Tip</label>+ <select class="form-input" id="alpha-mev-tip">+ <option value="off">Off</option>+ <option value="economy">Economy</option>+ <option value="turbo">Turbo</option>+ </select>+ </div>+ <div class="form-actions">+ <button class="btn-primary" id="alpha-hunt-save">Save</button>+ <span class="form-status" id="alpha-hunt-status" role="status" aria-live="polite"></span>+ </div>+ </section>+ </div><!-- /section-alpha-hunt -->++ <!-- ═══════════════════════════════════════+ LAUNCHER+ ═══════════════════════════════════════ -->+ <div class="edit-section" id="section-launcher">+ <div class="edit-section-label">Launcher</div>++ <section class="edit-panel" id="panel-launcher-schedule" role="region" aria-label="Launch Schedule">+ <div class="subsection-title">Launch Schedule</div>+ <p class="hint">Autonomously launch coins on pump.fun on a schedule or on demand</p>++ <div class="form-group">+ <label class="form-label" style="display:flex;align-items:center;justify-content:space-between">+ Enable Launcher+ <label class="toggle-switch" title="Enable or disable the coin launcher">+ <input type="checkbox" id="launcher-enabled">+ <span class="slider"></span>+ </label>+ </label>+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-network">Network</label>+ <select class="form-input" id="launcher-network">+ <option value="mainnet">Mainnet</option>+ <option value="devnet">Devnet</option>+ </select>+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-interval-hours">Launch Every (hours)</label>+ <input class="form-input" id="launcher-interval-hours" type="number" min="1" step="1" placeholder="e.g. 24" />+ <p class="hint" style="margin-top:0.382rem">Leave blank for manual-only</p>+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-max-launches">Max Total Launches</label>+ <input class="form-input" id="launcher-max-launches" type="number" min="0" step="1" placeholder="Unlimited" />+ </div>+ </section>++ <section class="edit-panel" id="panel-launcher-metadata" role="region" aria-label="Token Metadata">+ <div class="subsection-title">Token Metadata</div>++ <div class="form-group">+ <label class="form-label" for="launcher-name-template">Token Name Template</label>+ <input class="form-input" id="launcher-name-template" type="text" placeholder="Agent Coin {{seq}}" />+ <p class="hint" style="margin-top:0.382rem">{{seq}} = launch number, {{timestamp}} = Unix time</p>+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-symbol">Symbol</label>+ <input class="form-input" id="launcher-symbol" type="text" maxlength="10" placeholder="AGNT" />+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-description">Description</label>+ <textarea class="form-textarea" id="launcher-description" rows="3"></textarea>+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-image-url">Image URL</label>+ <input class="form-input" id="launcher-image-url" type="url" placeholder="https://…" />+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-twitter">Twitter</label>+ <input class="form-input" id="launcher-twitter" type="text" placeholder="https://twitter.com/…" />+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-telegram">Telegram</label>+ <input class="form-input" id="launcher-telegram" type="text" placeholder="https://t.me/…" />+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-website">Website</label>+ <input class="form-input" id="launcher-website" type="url" placeholder="https://…" />+ </div>+ <div class="form-group">+ <label class="form-label" for="launcher-initial-buy">Initial Dev Buy (SOL)</label>+ <input class="form-input" id="launcher-initial-buy" type="number" min="0" step="0.01" placeholder="0" />+ </div>+ <div class="form-actions">+ <button class="btn-primary" id="launcher-save">Save</button>+ <span class="form-status" id="launcher-status" role="status" aria-live="polite"></span>+ </div>+ </section>++ <section class="edit-panel" id="panel-launched-coins" role="region" aria-label="Launched Coins">+ <div class="subsection-title">Launched Coins</div>+ <div id="launched-coins-table-wrap">+ <div class="muted">Loading…</div>+ </div>+ </section>+ </div><!-- /section-launcher -->++ <!-- ═══════════════════════════════════════+ AUTO-CLAIM+ ═══════════════════════════════════════ -->+ <div class="edit-section" id="section-auto-claim">+ <div class="edit-section-label">Auto-Claim</div>++ <section class="edit-panel" id="panel-auto-claim" role="region" aria-label="Creator Auto-Claim">+ <div class="subsection-title">Creator Auto-Claim</div>+ <p class="hint">Automatically claim creator fees when your launched coins become runners</p>++ <div class="form-group">+ <label class="form-label" style="display:flex;align-items:center;justify-content:space-between">+ Enable Auto-Claim+ <label class="toggle-switch" title="Enable or disable automatic fee claiming">+ <input type="checkbox" id="auto-claim-enabled">+ <span class="slider"></span>+ </label>+ </label>+ </div>+ <div class="form-group">+ <label class="form-label" for="auto-claim-threshold">Claim Threshold (SOL)</label>+ <input class="form-input" id="auto-claim-threshold" type="number" min="0" step="0.1" placeholder="0.5" />+ </div>+ <div class="form-group">+ <label class="form-label" for="auto-claim-reinvest">+ Reinvest % of Claimed Fees+ <span id="auto-claim-reinvest-val" style="color:rgba(255,255,255,0.55);font-weight:400;margin-left:0.5rem">0%</span>+ </label>+ <input type="range" id="auto-claim-reinvest" min="0" max="100" step="1" value="0" style="width:100%;accent-color:#3b82f6" />+ <p class="hint" style="margin-top:0.5rem">Reinvested fees go back into the sniper buy budget. Remaining goes to your agent wallet.</p>+ </div>+ <div class="form-actions">+ <button class="btn-primary" id="auto-claim-save">Save</button>+ <span class="form-status" id="auto-claim-status" role="status" aria-live="polite"></span>+ </div>+ </section>++ <section class="edit-panel" id="panel-claimable-fees" role="region" aria-label="Claimable Fees">+ <div class="subsection-title">Your Claimable Fees</div>+ <div id="claimable-fees-table-wrap">+ <div class="muted">Loading…</div>+ </div>+ </section>+ </div><!-- /section-auto-claim -->++ <!-- ═══════════════════════════════════════+ MARKET MAKER+ ═══════════════════════════════════════ -->+ <div class="edit-section" id="section-market-maker">+ <div class="edit-section-label">Market Maker</div>++ <section class="edit-panel" id="panel-market-maker-add" role="region" aria-label="Add Market">+ <div class="subsection-title">Market Maker</div>+ <p class="hint">Provide liquidity and capture spread using Jito-accelerated execution</p>++ <div class="form-group">+ <label class="form-label" for="mm-mint">Coin Mint</label>+ <input class="form-input" id="mm-mint" type="text" placeholder="Paste pump.fun mint address" />+ </div>+ <div class="form-group">+ <label class="form-label" for="mm-symbol">Symbol</label>+ <input class="form-input" id="mm-symbol" type="text" placeholder="e.g. PEPE" />+ </div>+ <div class="form-group">+ <label class="form-label" for="mm-spread">+ Spread+ <span id="mm-spread-val" style="color:rgba(255,255,255,0.55);font-weight:400;margin-left:0.5rem">0.50%</span>+ </label>+ <input type="range" id="mm-spread" min="50" max="2000" step="10" value="100" style="width:100%;accent-color:#3b82f6" />+ </div>+ <div class="form-group">+ <label class="form-label" for="mm-order-size">Order Size (SOL)</label>+ <input class="form-input" id="mm-order-size" type="number" min="0" step="0.01" placeholder="0.05" />+ </div>+ <div class="form-group">+ <label class="form-label" for="mm-max-inventory">Max Inventory (SOL)</label>+ <input class="form-input" id="mm-max-inventory" type="number" min="0" step="0.1" placeholder="1.0" />+ </div>+ <div class="form-group">+ <label class="form-label" for="mm-rebalance">Rebalance Every</label>+ <select class="form-input" id="mm-rebalance">+ <option value="5">5s</option>+ <option value="10">10s</option>+ <option value="30" selected>30s</option>+ <option value="60">60s</option>+ </select>+ </div>+ <div class="form-group">+ <label class="form-label" for="mm-mev-tip">MEV Tip</label>+ <select class="form-input" id="mm-mev-tip">+ <option value="off">Off</option>+ <option value="economy">Economy</option>+ <option value="turbo">Turbo</option>+ </select>+ </div>+ <div class="form-actions">+ <button class="btn-primary" id="mm-add-market">Add Market</button>+ <span class="form-status" id="mm-add-status" role="status" aria-live="polite"></span>+ </div>+ </section>++ <section class="edit-panel" id="panel-active-markets" role="region" aria-label="Active Markets">+ <div class="subsection-title">Active Markets</div>+ <div id="active-markets-table-wrap">+ <div class="muted">Loading…</div>+ </div>+ </section>+ </div><!-- /section-market-maker -->+<!-- ═══════════════════════════════════════ADVANCED═══════════════════════════════════════ -->@@ -1950,6 +2218,372 @@<script type="module" src="/src/agent-edit.js"></script>+ <script type="module">+ // ── New capability sections: Alpha Hunt, Launcher, Auto-Claim, Market Maker ──++ const params = new URLSearchParams(location.search);+ const agentId = params.get('id') || params.get('agentId');++ // ── Helpers ──+ function setStatus(el, msg, type) {+ el.textContent = msg;+ el.className = 'form-status' + (type ? ' ' + type : '');+ }++ async function apiFetch(url, opts) {+ const res = await fetch(url, opts);+ const json = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(json.error || json.message || `HTTP ${res.status}`);+ return json;+ }++ // ── Spread slider display ──+ const mmSpread = document.getElementById('mm-spread');+ const mmSpreadVal = document.getElementById('mm-spread-val');+ if (mmSpread) {+ const updateSpread = () => {+ mmSpreadVal.textContent = (mmSpread.value / 100).toFixed(2) + '%';+ };+ mmSpread.addEventListener('input', updateSpread);+ updateSpread();+ }++ // ── Reinvest slider display ──+ const reinvestSlider = document.getElementById('auto-claim-reinvest');+ const reinvestVal = document.getElementById('auto-claim-reinvest-val');+ if (reinvestSlider) {+ const updateReinvest = () => {+ reinvestVal.textContent = reinvestSlider.value + '%';+ };+ reinvestSlider.addEventListener('input', updateReinvest);+ }++ // ── ALPHA HUNT ──+ async function loadAlphaHunt() {+ if (!agentId) return;+ try {+ const data = await apiFetch(`/api/sniper/strategy?agentId=${encodeURIComponent(agentId)}`);+ const cfg = data.strategy || data;+ if (cfg.alpha_min_smart_money != null) document.getElementById('alpha-min-smart-money').value = cfg.alpha_min_smart_money;+ if (cfg.alpha_min_quality_score != null) document.getElementById('alpha-min-quality').value = cfg.alpha_min_quality_score;+ if (cfg.alpha_min_organic_score != null) document.getElementById('alpha-min-organic').value = cfg.alpha_min_organic_score;+ if (cfg.alpha_max_mcap_usd != null) document.getElementById('alpha-max-mcap').value = cfg.alpha_max_mcap_usd;+ if (cfg.alpha_narrative_keywords) document.getElementById('alpha-keywords').value = Array.isArray(cfg.alpha_narrative_keywords) ? cfg.alpha_narrative_keywords.join(', ') : cfg.alpha_narrative_keywords;+ if (cfg.budget_sol != null) document.getElementById('alpha-budget-sol').value = cfg.budget_sol;+ if (cfg.take_profit_pct != null) document.getElementById('alpha-take-profit-pct').value = cfg.take_profit_pct;+ if (cfg.stop_loss_pct != null) document.getElementById('alpha-stop-loss-pct').value = cfg.stop_loss_pct;+ if (cfg.mev_tip) document.getElementById('alpha-mev-tip').value = cfg.mev_tip;+ } catch (_) { /* no existing config */ }+ }++ const alphaHuntSaveBtn = document.getElementById('alpha-hunt-save');+ if (alphaHuntSaveBtn) {+ loadAlphaHunt();+ alphaHuntSaveBtn.addEventListener('click', async () => {+ const statusEl = document.getElementById('alpha-hunt-status');+ alphaHuntSaveBtn.disabled = true;+ setStatus(statusEl, 'Saving…', '');+ try {+ const keywords = document.getElementById('alpha-keywords').value+ .split(',').map(k => k.trim()).filter(Boolean);+ await apiFetch('/api/sniper/strategy', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ agentId,+ trigger: 'alpha_hunt',+ alpha_min_smart_money: Number(document.getElementById('alpha-min-smart-money').value) || undefined,+ alpha_min_quality_score: Number(document.getElementById('alpha-min-quality').value) || undefined,+ alpha_min_organic_score: Number(document.getElementById('alpha-min-organic').value) || undefined,+ alpha_max_mcap_usd: Number(document.getElementById('alpha-max-mcap').value) || undefined,+ alpha_narrative_keywords: keywords.length ? keywords : undefined,+ budget_sol: Number(document.getElementById('alpha-budget-sol').value) || undefined,+ take_profit_pct: Number(document.getElementById('alpha-take-profit-pct').value) || undefined,+ stop_loss_pct: Number(document.getElementById('alpha-stop-loss-pct').value) || undefined,+ mev_tip: document.getElementById('alpha-mev-tip').value,+ }),+ });+ setStatus(statusEl, 'Saved', 'ok');+ } catch (err) {+ setStatus(statusEl, err.message, 'err');+ } finally {+ alphaHuntSaveBtn.disabled = false;+ }+ });+ }++ // ── LAUNCHER ──+ async function loadLauncher() {+ if (!agentId) return;+ try {+ const data = await apiFetch(`/api/agent/launcher?agentId=${encodeURIComponent(agentId)}`);+ const cfg = data.config || data;+ document.getElementById('launcher-enabled').checked = !!cfg.enabled;+ if (cfg.network) document.getElementById('launcher-network').value = cfg.network;+ if (cfg.interval_hours != null) document.getElementById('launcher-interval-hours').value = cfg.interval_hours;+ if (cfg.max_launches != null) document.getElementById('launcher-max-launches').value = cfg.max_launches;+ if (cfg.name_template) document.getElementById('launcher-name-template').value = cfg.name_template;+ if (cfg.symbol) document.getElementById('launcher-symbol').value = cfg.symbol;+ if (cfg.description) document.getElementById('launcher-description').value = cfg.description;+ if (cfg.image_url) document.getElementById('launcher-image-url').value = cfg.image_url;+ if (cfg.twitter) document.getElementById('launcher-twitter').value = cfg.twitter;+ if (cfg.telegram) document.getElementById('launcher-telegram').value = cfg.telegram;+ if (cfg.website) document.getElementById('launcher-website').value = cfg.website;+ if (cfg.initial_buy_sol != null) document.getElementById('launcher-initial-buy').value = cfg.initial_buy_sol;+ } catch (_) { /* no existing config */ }+ renderLaunchedCoinsTable();+ }++ async function renderLaunchedCoinsTable() {+ const wrap = document.getElementById('launched-coins-table-wrap');+ if (!wrap || !agentId) return;+ try {+ const data = await apiFetch(`/api/agent/launcher?agentId=${encodeURIComponent(agentId)}&launches=1`);+ const coins = data.launches || [];+ if (!coins.length) {+ wrap.innerHTML = '<div class="muted">No coins launched yet.</div>';+ return;+ }+ wrap.innerHTML = `<table class="data-table" style="width:100%;border-collapse:collapse;font-size:0.764rem">+ <thead>+ <tr style="border-bottom:1px solid rgba(255,255,255,0.08)">+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Symbol</th>+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Name</th>+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Mint</th>+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Launched</th>+ <th style="text-align:right;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">P&L</th>+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Status</th>+ </tr>+ </thead>+ <tbody>+ ${coins.map(c => `+ <tr style="border-bottom:1px solid rgba(255,255,255,0.04)">+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.85)">${esc(c.symbol)}</td>+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.7)">${esc(c.name)}</td>+ <td style="padding:0.5rem 0.75rem;font-family:ui-monospace,monospace;font-size:0.618rem;color:rgba(255,255,255,0.5)">${esc(c.mint ? c.mint.slice(0,8) + '…' : '—')}</td>+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.5)">${c.launched_at ? new Date(c.launched_at).toLocaleDateString() : '—'}</td>+ <td style="padding:0.5rem 0.75rem;text-align:right;color:${c.pnl_sol >= 0 ? '#86efac' : '#fca5a5'}">${c.pnl_sol != null ? (c.pnl_sol >= 0 ? '+' : '') + c.pnl_sol.toFixed(3) + ' SOL' : '—'}</td>+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.55)">${esc(c.status || '—')}</td>+ </tr>`).join('')}+ </tbody>+ </table>`;+ } catch (_) {+ wrap.innerHTML = '<div class="muted">Unable to load launched coins.</div>';+ }+ }++ const launcherSaveBtn = document.getElementById('launcher-save');+ if (launcherSaveBtn) {+ loadLauncher();+ launcherSaveBtn.addEventListener('click', async () => {+ const statusEl = document.getElementById('launcher-status');+ launcherSaveBtn.disabled = true;+ setStatus(statusEl, 'Saving…', '');+ try {+ await apiFetch('/api/agent/launcher', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ agentId,+ enabled: document.getElementById('launcher-enabled').checked,+ network: document.getElementById('launcher-network').value,+ interval_hours: Number(document.getElementById('launcher-interval-hours').value) || null,+ max_launches: Number(document.getElementById('launcher-max-launches').value) || null,+ name_template: document.getElementById('launcher-name-template').value,+ symbol: document.getElementById('launcher-symbol').value,+ description: document.getElementById('launcher-description').value,+ image_url: document.getElementById('launcher-image-url').value,+ twitter: document.getElementById('launcher-twitter').value,+ telegram: document.getElementById('launcher-telegram').value,+ website: document.getElementById('launcher-website').value,+ initial_buy_sol: Number(document.getElementById('launcher-initial-buy').value) || 0,+ }),+ });+ setStatus(statusEl, 'Saved', 'ok');+ } catch (err) {+ setStatus(statusEl, err.message, 'err');+ } finally {+ launcherSaveBtn.disabled = false;+ }+ });+ }++ // ── AUTO-CLAIM ──+ async function loadAutoClaim() {+ if (!agentId) return;+ try {+ const data = await apiFetch(`/api/agent/launcher?agentId=${encodeURIComponent(agentId)}`);+ const cfg = data.config || data;+ document.getElementById('auto-claim-enabled').checked = !!cfg.auto_claim_enabled;+ if (cfg.auto_claim_threshold_sol != null) document.getElementById('auto-claim-threshold').value = cfg.auto_claim_threshold_sol;+ if (cfg.auto_claim_reinvest_pct != null) {+ document.getElementById('auto-claim-reinvest').value = cfg.auto_claim_reinvest_pct;+ document.getElementById('auto-claim-reinvest-val').textContent = cfg.auto_claim_reinvest_pct + '%';+ }+ } catch (_) { /* no existing config */ }+ renderClaimableFeesTable();+ }++ async function renderClaimableFeesTable() {+ const wrap = document.getElementById('claimable-fees-table-wrap');+ if (!wrap || !agentId) return;+ try {+ const data = await apiFetch(`/api/agent/launcher?agentId=${encodeURIComponent(agentId)}&fees=1`);+ const fees = data.claimable_fees || [];+ if (!fees.length) {+ wrap.innerHTML = '<div class="muted">No claimable fees. Launched coins will appear here as they earn creator fees.</div>';+ return;+ }+ wrap.innerHTML = `<table class="data-table" style="width:100%;border-collapse:collapse;font-size:0.764rem">+ <thead>+ <tr style="border-bottom:1px solid rgba(255,255,255,0.08)">+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Symbol</th>+ <th style="text-align:right;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Claimable SOL</th>+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Last Claimed</th>+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Status</th>+ </tr>+ </thead>+ <tbody>+ ${fees.map(f => `+ <tr style="border-bottom:1px solid rgba(255,255,255,0.04)">+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.85)">${esc(f.symbol)}</td>+ <td style="padding:0.5rem 0.75rem;text-align:right;color:#86efac">${f.claimable_sol != null ? f.claimable_sol.toFixed(4) : '—'}</td>+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.5)">${f.last_claimed_at ? new Date(f.last_claimed_at).toLocaleDateString() : 'Never'}</td>+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.55)">${esc(f.status || '—')}</td>+ </tr>`).join('')}+ </tbody>+ </table>`;+ } catch (_) {+ wrap.innerHTML = '<div class="muted">Unable to load claimable fees.</div>';+ }+ }++ const autoClaimSaveBtn = document.getElementById('auto-claim-save');+ if (autoClaimSaveBtn) {+ loadAutoClaim();+ autoClaimSaveBtn.addEventListener('click', async () => {+ const statusEl = document.getElementById('auto-claim-status');+ autoClaimSaveBtn.disabled = true;+ setStatus(statusEl, 'Saving…', '');+ try {+ await apiFetch('/api/agent/launcher', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ agentId,+ auto_claim_enabled: document.getElementById('auto-claim-enabled').checked,+ auto_claim_threshold_sol: Number(document.getElementById('auto-claim-threshold').value) || 0.5,+ auto_claim_reinvest_pct: Number(document.getElementById('auto-claim-reinvest').value) || 0,+ }),+ });+ setStatus(statusEl, 'Saved', 'ok');+ } catch (err) {+ setStatus(statusEl, err.message, 'err');+ } finally {+ autoClaimSaveBtn.disabled = false;+ }+ });+ }++ // ── MARKET MAKER ──+ async function loadActiveMarkets() {+ const wrap = document.getElementById('active-markets-table-wrap');+ if (!wrap || !agentId) return;+ try {+ const data = await apiFetch(`/api/agent/market-maker?agentId=${encodeURIComponent(agentId)}`);+ const markets = data.markets || [];+ if (!markets.length) {+ wrap.innerHTML = '<div class="muted">No active markets. Add one above.</div>';+ return;+ }+ wrap.innerHTML = `<table class="data-table" style="width:100%;border-collapse:collapse;font-size:0.764rem">+ <thead>+ <tr style="border-bottom:1px solid rgba(255,255,255,0.08)">+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Symbol</th>+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Spread</th>+ <th style="text-align:right;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Inventory</th>+ <th style="text-align:right;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Volume</th>+ <th style="text-align:right;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">P&L</th>+ <th style="text-align:left;padding:0.5rem 0.75rem;color:rgba(255,255,255,0.4);font-weight:500">Status</th>+ </tr>+ </thead>+ <tbody>+ ${markets.map(m => `+ <tr style="border-bottom:1px solid rgba(255,255,255,0.04)">+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.85)">${esc(m.symbol)}</td>+ <td style="padding:0.5rem 0.75rem;color:rgba(255,255,255,0.7)">${m.spread_bps != null ? (m.spread_bps / 100).toFixed(2) + '%' : '—'}</td>+ <td style="padding:0.5rem 0.75rem;text-align:right;color:rgba(255,255,255,0.7)">${m.inventory_sol != null ? m.inventory_sol.toFixed(3) + ' SOL' : '—'}</td>+ <td style="padding:0.5rem 0.75rem;text-align:right;color:rgba(255,255,255,0.55)">${m.volume_sol != null ? m.volume_sol.toFixed(3) + ' SOL' : '—'}</td>+ <td style="padding:0.5rem 0.75rem;text-align:right;color:${(m.pnl_sol || 0) >= 0 ? '#86efac' : '#fca5a5'}">${m.pnl_sol != null ? (m.pnl_sol >= 0 ? '+' : '') + m.pnl_sol.toFixed(3) + ' SOL' : '—'}</td>+ <td style="padding:0.5rem 0.75rem">+ <label class="toggle-switch" title="Enable or disable this market" style="vertical-align:middle">+ <input type="checkbox" data-mm-id="${esc(m.id)}" class="mm-market-toggle" ${m.enabled ? 'checked' : ''}>+ <span class="slider"></span>+ </label>+ </td>+ </tr>`).join('')}+ </tbody>+ </table>`;++ wrap.querySelectorAll('.mm-market-toggle').forEach(toggle => {+ toggle.addEventListener('change', async () => {+ try {+ await apiFetch('/api/agent/market-maker', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ agentId, id: toggle.dataset.mmId, enabled: toggle.checked }),+ });+ } catch (err) {+ toggle.checked = !toggle.checked;+ }+ });+ });+ } catch (_) {+ wrap.innerHTML = '<div class="muted">Unable to load active markets.</div>';+ }+ }++ const mmAddBtn = document.getElementById('mm-add-market');+ if (mmAddBtn) {+ loadActiveMarkets();+ mmAddBtn.addEventListener('click', async () => {+ const statusEl = document.getElementById('mm-add-status');+ mmAddBtn.disabled = true;+ setStatus(statusEl, 'Adding…', '');+ try {+ await apiFetch('/api/agent/market-maker', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ agentId,+ mint: document.getElementById('mm-mint').value.trim(),+ symbol: document.getElementById('mm-symbol').value.trim(),+ spread_bps: Number(document.getElementById('mm-spread').value),+ order_size_sol: Number(document.getElementById('mm-order-size').value) || 0.05,+ max_inventory_sol: Number(document.getElementById('mm-max-inventory').value) || 1.0,+ rebalance_seconds: Number(document.getElementById('mm-rebalance').value),+ mev_tip: document.getElementById('mm-mev-tip').value,+ enabled: true,+ }),+ });+ setStatus(statusEl, 'Market added', 'ok');+ document.getElementById('mm-mint').value = '';+ document.getElementById('mm-symbol').value = '';+ loadActiveMarkets();+ } catch (err) {+ setStatus(statusEl, err.message, 'err');+ } finally {+ mmAddBtn.disabled = false;+ }+ });+ }++ // ── XSS-safe escaper ──+ function esc(str) {+ return String(str ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');+ }+ </script>+<div id="footer-container"></div><script src="/footer.js"></script><script src="/brand.js" defer></script>diff --git a/pages/payments.html b/pages/payments.htmlnew file mode 100644index 000000000..a19d122e1--- /dev/null+++ b/pages/payments.html@@ -0,0 +1,578 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <title>Agent Payment Sessions · three.ws</title>+ <meta name="description" content="Create budget-limited payment sessions for AI agents. No private keys needed — agents pay x402 endpoints with platform governance enforcing spend limits, URL allowlists, and expiry." />+ <meta name="robots" content="noindex" />+ <link rel="canonical" href="https://three.ws/payments" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <style>+ .pay-wrap { max-width: 1040px; margin: 0 auto; padding: clamp(1.25rem, 4vw, 3rem) 1.25rem 4rem; }+ .pay-head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 1rem; margin-bottom: 1.5rem; }+ .pay-head h1 { font-size: clamp(1.6rem, 3.5vw, 2.2rem); margin: 0 0 0.3rem; letter-spacing: -0.02em; }+ .pay-head p { margin: 0; color: var(--text-secondary, #9aa3b2); max-width: 58ch; line-height: 1.55; font-size: 15px; }++ /* Stats row */+ .pay-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 1rem; margin-bottom: 2rem; }+ .pay-stat { border: 1px solid rgba(255,255,255,0.1); border-radius: 14px; padding: 1.1rem 1.25rem; background: rgba(10,10,10,0.7); }+ .pay-stat .label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.07em; color: rgba(255,255,255,0.45); font-weight: 600; margin-bottom: 0.5rem; }+ .pay-stat .value { font-size: 1.6rem; font-weight: 700; letter-spacing: -0.02em; }+ .pay-stat .value.green { color: #2fbf71; }+ .pay-stat .value.purple { color: #a78bfa; }+ .pay-stat .sub { font-size: 12px; color: rgba(255,255,255,0.4); margin-top: 0.2rem; }++ /* Toolbar */+ .pay-toolbar { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; margin-bottom: 1.25rem; }+ .pay-filter { display: flex; border: 1px solid rgba(255,255,255,0.12); border-radius: 10px; overflow: hidden; }+ .pay-filter button { font: inherit; font-size: 13px; font-weight: 500; padding: 8px 14px; background: transparent; border: none; color: rgba(255,255,255,0.55); cursor: pointer; transition: color .15s, background .15s; }+ .pay-filter button:hover { color: rgba(255,255,255,0.9); background: rgba(255,255,255,0.06); }+ .pay-filter button.active { color: #fff; background: rgba(255,255,255,0.12); }+ .btn-new { font: inherit; font-size: 13px; font-weight: 600; padding: 8px 18px; border-radius: 10px; border: none; background: var(--accent, #7c5cff); color: #fff; cursor: pointer; display: flex; align-items: center; gap: 6px; transition: opacity .15s; margin-left: auto; }+ .btn-new:hover { opacity: 0.85; }+ .btn-new:disabled { opacity: 0.5; cursor: default; }++ /* Session cards */+ .pay-list { display: flex; flex-direction: column; gap: 1rem; }+ .sess-card { border: 1px solid rgba(255,255,255,0.1); border-radius: 16px; background: rgba(10,10,10,0.8); overflow: hidden; transition: border-color .2s; }+ .sess-card:hover { border-color: rgba(255,255,255,0.22); }+ .sess-card-head { display: flex; align-items: center; gap: 1rem; padding: 1.1rem 1.25rem; cursor: pointer; }+ .sess-badge { font-size: 11px; font-weight: 600; padding: 3px 9px; border-radius: 99px; text-transform: uppercase; letter-spacing: 0.05em; }+ .sess-badge.active { background: rgba(47,191,113,0.18); color: #2fbf71; border: 1px solid rgba(47,191,113,0.3); }+ .sess-badge.exhausted { background: rgba(240,169,59,0.15); color: #f0a93b; border: 1px solid rgba(240,169,59,0.28); }+ .sess-badge.expired { background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.45); border: 1px solid rgba(255,255,255,0.12); }+ .sess-badge.cancelled { background: rgba(255,80,80,0.1); color: #ff6b6b; border: 1px solid rgba(255,80,80,0.2); }+ .sess-label { font-weight: 600; font-size: 15px; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .sess-amounts { display: flex; align-items: center; gap: 1.5rem; font-variant-numeric: tabular-nums; font-size: 14px; }+ .sess-remaining { font-weight: 700; font-size: 16px; }+ .sess-remaining.green { color: #2fbf71; }+ .sess-remaining.yellow { color: #f0a93b; }+ .sess-remaining.grey { color: rgba(255,255,255,0.35); }+ .sess-budget-dim { color: rgba(255,255,255,0.4); font-size: 13px; }+ .sess-expand { font-size: 18px; color: rgba(255,255,255,0.3); transition: transform .2s; }+ .sess-card.open .sess-expand { transform: rotate(180deg); }++ /* Budget bar */+ .sess-bar-wrap { padding: 0 1.25rem; }+ .sess-bar-track { height: 5px; border-radius: 99px; background: rgba(255,255,255,0.08); overflow: hidden; }+ .sess-bar-fill { height: 100%; border-radius: 99px; transition: width .4s; }+ .sess-bar-fill.green { background: linear-gradient(90deg, #2fbf71, #52e89a); }+ .sess-bar-fill.yellow { background: linear-gradient(90deg, #f0a93b, #ffd280); }+ .sess-bar-fill.red { background: linear-gradient(90deg, #ff5050, #ff8f70); }++ /* Expanded detail */+ .sess-detail { display: none; padding: 1.1rem 1.25rem 1.25rem; border-top: 1px solid rgba(255,255,255,0.07); }+ .sess-card.open .sess-detail { display: block; }+ .sess-meta { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 0.75rem 1.5rem; margin-bottom: 1rem; font-size: 13px; }+ .sess-meta-item .k { color: rgba(255,255,255,0.45); font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 3px; }+ .sess-meta-item .v { font-weight: 500; word-break: break-all; }+ .sess-meta-item .v code { font-family: monospace; font-size: 12px; background: rgba(255,255,255,0.06); padding: 2px 6px; border-radius: 4px; }++ /* Executions mini-table */+ .exec-table { width: 100%; border-collapse: collapse; font-size: 13px; }+ .exec-table th { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.06em; color: rgba(255,255,255,0.4); font-weight: 600; padding: 6px 0; border-bottom: 1px solid rgba(255,255,255,0.07); text-align: left; }+ .exec-table td { padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.05); vertical-align: middle; }+ .exec-table tr:last-child td { border-bottom: none; }+ .exec-status { display: inline-flex; align-items: center; gap: 5px; font-size: 11.5px; font-weight: 600; }+ .exec-status::before { content: ''; width: 7px; height: 7px; border-radius: 50%; }+ .exec-status.settled::before { background: #2fbf71; }+ .exec-status.failed::before { background: #ff5050; }+ .exec-status.pending::before { background: #f0a93b; }+ .exec-url { max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: rgba(255,255,255,0.65); font-family: monospace; font-size: 12px; }+ .exec-tx a { color: var(--accent, #7c5cff); text-decoration: none; font-family: monospace; font-size: 11px; }+ .exec-tx a:hover { text-decoration: underline; }++ /* Actions */+ .sess-actions { display: flex; gap: 0.75rem; margin-top: 1rem; }+ .sess-btn { font: inherit; font-size: 12.5px; font-weight: 600; padding: 7px 14px; border-radius: 8px; cursor: pointer; transition: opacity .15s; }+ .sess-btn.cancel { background: rgba(255,80,80,0.12); border: 1px solid rgba(255,80,80,0.25); color: #ff7070; }+ .sess-btn.cancel:hover { opacity: 0.75; }++ /* Empty / loading states */+ .pay-empty { text-align: center; padding: 4rem 1rem; color: rgba(255,255,255,0.5); }+ .pay-empty h2 { font-size: 1.25rem; color: rgba(255,255,255,0.85); margin: 0 0 0.6rem; }+ .pay-empty p { margin: 0 0 1.4rem; max-width: 42ch; margin-left: auto; margin-right: auto; line-height: 1.6; }+ .pay-skel { height: 88px; border-radius: 16px; background: linear-gradient(90deg, rgba(255,255,255,0.04), rgba(255,255,255,0.1), rgba(255,255,255,0.04)); background-size: 200% 100%; animation: payShimmer 1.3s infinite; margin-bottom: 1rem; }+ @keyframes payShimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .pay-skel { animation: none; } }++ /* Create session modal */+ .modal-bg { position: fixed; inset: 0; z-index: 1000; background: rgba(0,0,0,0.7); backdrop-filter: blur(6px); display: flex; align-items: center; justify-content: center; padding: 1rem; opacity: 0; pointer-events: none; transition: opacity .2s; }+ .modal-bg.show { opacity: 1; pointer-events: auto; }+ .modal { background: #111; border: 1px solid rgba(255,255,255,0.15); border-radius: 20px; padding: 1.75rem; width: 100%; max-width: 480px; max-height: 90vh; overflow-y: auto; }+ .modal h2 { margin: 0 0 0.3rem; font-size: 1.2rem; }+ .modal .modal-sub { color: rgba(255,255,255,0.5); font-size: 13px; margin-bottom: 1.5rem; }+ .form-row { margin-bottom: 1.1rem; }+ .form-row label { display: block; font-size: 12.5px; font-weight: 600; color: rgba(255,255,255,0.65); margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.05em; }+ .form-row input, .form-row select, .form-row textarea { width: 100%; font: inherit; font-size: 14px; padding: 10px 12px; border: 1px solid rgba(255,255,255,0.15); border-radius: 10px; background: rgba(255,255,255,0.05); color: #fff; transition: border-color .15s; box-sizing: border-box; }+ .form-row input:focus, .form-row select:focus, .form-row textarea:focus { outline: none; border-color: var(--accent, #7c5cff); }+ .form-row .hint { font-size: 12px; color: rgba(255,255,255,0.4); margin-top: 5px; line-height: 1.45; }+ .form-row select option { background: #1a1a1a; }+ .modal-actions { display: flex; gap: 0.75rem; margin-top: 1.5rem; }+ .modal-actions button { flex: 1; font: inherit; font-weight: 600; font-size: 14px; padding: 11px; border-radius: 10px; border: none; cursor: pointer; transition: opacity .15s; }+ .modal-actions .primary { background: var(--accent, #7c5cff); color: #fff; }+ .modal-actions .primary:hover { opacity: 0.85; }+ .modal-actions .primary:disabled { opacity: 0.45; cursor: default; }+ .modal-actions .secondary { background: rgba(255,255,255,0.08); color: rgba(255,255,255,0.8); border: 1px solid rgba(255,255,255,0.12); }++ /* Token reveal */+ .token-box { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.12); border-radius: 10px; padding: 1rem; margin-top: 1rem; word-break: break-all; font-family: monospace; font-size: 12.5px; color: #a78bfa; }+ .token-copy { font: inherit; font-size: 12px; font-weight: 600; padding: 6px 14px; border-radius: 7px; border: 1px solid rgba(167,139,250,0.3); background: rgba(167,139,250,0.1); color: #a78bfa; cursor: pointer; margin-top: 0.6rem; }+ .token-copy:hover { background: rgba(167,139,250,0.18); }+ .token-warn { display: flex; align-items: flex-start; gap: 0.5rem; background: rgba(240,169,59,0.1); border: 1px solid rgba(240,169,59,0.3); border-radius: 10px; padding: 0.85rem 1rem; font-size: 13px; color: #f3c478; margin-top: 0.75rem; }+ .token-warn svg { flex-shrink: 0; margin-top: 1px; }++ /* Toast */+ .toast { position: fixed; bottom: 2rem; left: 50%; transform: translateX(-50%); background: #222; border: 1px solid rgba(255,255,255,0.15); border-radius: 10px; padding: 10px 18px; font-size: 14px; z-index: 2000; transition: opacity .2s; pointer-events: none; white-space: nowrap; }+ .toast.show { opacity: 1; }+ .toast { opacity: 0; }++ @media (max-width: 640px) {+ .pay-stats { grid-template-columns: 1fr 1fr; }+ .sess-amounts { gap: 0.75rem; }+ .sess-meta { grid-template-columns: 1fr 1fr; }+ }+ </style>+ </head>+ <body>+ <a href="#main-content" class="h-skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content" class="pay-wrap">+ <div class="pay-head">+ <div>+ <h1>Agent Payment Sessions</h1>+ <p>Fund spend envelopes for AI agents. No private key required — agents pay x402 APIs via session token. Governance enforces budget limits, URL allowlists, and expiry.</p>+ </div>+ </div>++ <!-- Stats -->+ <div class="pay-stats" id="payStats">+ <div class="pay-skel"></div>+ <div class="pay-skel" style="height:72px"></div>+ <div class="pay-skel" style="height:72px"></div>+ <div class="pay-skel" style="height:72px"></div>+ </div>++ <!-- Toolbar -->+ <div class="pay-toolbar">+ <div class="pay-filter" id="filterRow">+ <button class="active" data-f="all">All</button>+ <button data-f="active">Active</button>+ <button data-f="exhausted">Exhausted</button>+ <button data-f="expired">Expired</button>+ <button data-f="cancelled">Cancelled</button>+ </div>+ <button class="btn-new" id="btnNew">+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 1v12M1 7h12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>+ New Session+ </button>+ </div>++ <!-- Session list -->+ <div id="payList" class="pay-list">+ <div class="pay-skel"></div>+ <div class="pay-skel"></div>+ <div class="pay-skel"></div>+ </div>+ </main>++ <!-- Create session modal -->+ <div class="modal-bg" id="createModal" role="dialog" aria-modal="true" aria-labelledby="modalTitle">+ <div class="modal" id="modalInner">+ <h2 id="modalTitle">New Payment Session</h2>+ <p class="modal-sub">Fund a spend envelope from your credits. The agent uses the returned token — no wallet key needed.</p>+ <div class="form-row">+ <label>Budget (USD)</label>+ <input type="number" id="fBudget" min="0.001" max="1000" step="0.001" value="1.00" />+ <div class="hint">Drawn from your credit balance. Un-spent budget is refunded on cancel/expiry.</div>+ </div>+ <div class="form-row">+ <label>Label</label>+ <input type="text" id="fLabel" maxlength="120" placeholder="Research run, data fetch, etc." />+ </div>+ <div class="form-row">+ <label>Expiry</label>+ <select id="fExpiry">+ <option value="900">15 minutes</option>+ <option value="3600" selected>1 hour</option>+ <option value="21600">6 hours</option>+ <option value="86400">24 hours</option>+ <option value="604800">7 days</option>+ </select>+ </div>+ <div class="form-row">+ <label>Max per transaction (USD, optional)</label>+ <input type="number" id="fMaxTx" min="0.000001" max="1000" step="0.0001" placeholder="No limit" />+ <div class="hint">Rejects any single payment above this amount before signing.</div>+ </div>+ <div class="form-row">+ <label>Allowed hosts (optional, comma-separated)</label>+ <input type="text" id="fHosts" placeholder="api.example.com, data.provider.io" />+ <div class="hint">If set, the agent can only pay endpoints at these domains. Empty = any host.</div>+ </div>+ <div class="form-row">+ <label>Network</label>+ <select id="fNetwork">+ <option value="solana" selected>Solana</option>+ <option value="base">Base</option>+ </select>+ </div>++ <!-- Token reveal (shown after creation) -->+ <div id="tokenReveal" style="display:none">+ <div class="token-warn">+ <svg width="16" height="16" viewBox="0 0 20 20" fill="none"><path d="M10 2L2 17h16L10 2z" stroke="#f0a93b" stroke-width="1.5"/><path d="M10 8v4M10 14.5v.5" stroke="#f0a93b" stroke-width="1.5" stroke-linecap="round"/></svg>+ This token is shown <strong>once</strong>. Copy it now and set it as <code>PAYMENT_SESSION_TOKEN</code> in your agent.+ </div>+ <div class="token-box" id="tokenVal"></div>+ <button class="token-copy" id="tokenCopyBtn">Copy token</button>+ </div>++ <div class="modal-actions" id="modalActions">+ <button class="secondary" id="modalClose">Cancel</button>+ <button class="primary" id="modalCreate">Create session</button>+ </div>+ </div>+ </div>++ <div class="toast" id="toast"></div>++ <footer><div id="footer-container"></div></footer>+ <script src="/footer.js"></script>++ <script type="module">+ const $ = id => document.getElementById(id);+ let sessions = [];+ let activeFilter = 'all';+ let stats = null;++ // ── API helpers ─────────────────────────────────────────+ async function apiFetch(path, opts = {}) {+ const res = await fetch(path, {+ credentials: 'include',+ headers: { 'content-type': 'application/json', ...(opts.headers || {}) },+ ...opts,+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) throw Object.assign(new Error(data.message || data.error || `HTTP ${res.status}`), { code: data.code, status: res.status });+ return data;+ }++ // ── Toast ───────────────────────────────────────────────+ function toast(msg, duration = 2800) {+ const el = $('toast');+ el.textContent = msg;+ el.classList.add('show');+ setTimeout(() => el.classList.remove('show'), duration);+ }++ // ── Stats render ────────────────────────────────────────+ function renderStats(s) {+ const el = $('payStats');+ el.innerHTML = `+ <div class="pay-stat">+ <div class="label">Active</div>+ <div class="value green">${s.sessions.active}</div>+ <div class="sub">${s.sessions.exhausted} exhausted</div>+ </div>+ <div class="pay-stat">+ <div class="label">Total budget</div>+ <div class="value purple">$${s.sessions.total_budget_usd.toFixed(2)}</div>+ <div class="sub">$${s.sessions.total_spent_usd.toFixed(4)} spent</div>+ </div>+ <div class="pay-stat">+ <div class="label">Payments settled</div>+ <div class="value">${s.executions.settled}</div>+ <div class="sub">${s.executions.failed} failed</div>+ </div>+ <div class="pay-stat">+ <div class="label">Unique endpoints</div>+ <div class="value">${s.executions.unique_endpoints}</div>+ <div class="sub">$${s.executions.settled_usd.toFixed(4)} moved</div>+ </div>+ `;+ }++ // ── Session card render ─────────────────────────────────+ function pct(s) {+ if (!s.budget_usd) return 0;+ return Math.min(100, (s.spent_usd / s.budget_usd) * 100);+ }++ function barColor(s) {+ const p = pct(s);+ if (p >= 95 || s.status === 'exhausted') return 'red';+ if (p >= 70) return 'yellow';+ return 'green';+ }++ function remainColor(s) {+ const p = pct(s);+ if (s.status !== 'active') return 'grey';+ if (p >= 70) return 'yellow';+ return 'green';+ }++ function fmtExpiry(s) {+ const d = new Date(s.expires_at);+ const now = new Date();+ const diff = d - now;+ if (diff <= 0) return 'Expired';+ const h = Math.floor(diff / 3600000);+ const m = Math.floor((diff % 3600000) / 60000);+ if (h > 48) return `${Math.floor(h/24)}d remaining`;+ if (h > 0) return `${h}h ${m}m remaining`;+ return `${m}m remaining`;+ }++ function fmtDate(iso) {+ return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });+ }++ function renderExecs(execs) {+ if (!execs || !execs.length) return '<div style="color:rgba(255,255,255,0.35);font-size:13px;padding:8px 0">No payments yet.</div>';+ return `+ <table class="exec-table">+ <thead><tr>+ <th>Endpoint</th>+ <th>Amount</th>+ <th>Status</th>+ <th>Tx</th>+ <th>Time</th>+ </tr></thead>+ <tbody>+ ${execs.map(e => `+ <tr>+ <td><div class="exec-url" title="${escHtml(e.endpoint_url)}">${escHtml(e.endpoint_host)}</div></td>+ <td style="font-variant-numeric:tabular-nums">$${e.amount_usd.toFixed(6)}</td>+ <td><span class="exec-status ${e.status}">${e.status}</span></td>+ <td class="exec-tx">${e.tx_hash ? `<a href="https://solscan.io/tx/${escHtml(e.tx_hash)}" target="_blank" rel="noopener">${e.tx_hash.slice(0,8)}…</a>` : '—'}</td>+ <td style="color:rgba(255,255,255,0.45);font-size:12px">${fmtDate(e.created_at)}</td>+ </tr>+ `).join('')}+ </tbody>+ </table>+ `;+ }++ function escHtml(s) {+ return String(s || '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');+ }++ function renderCard(s) {+ const p = pct(s);+ const bc = barColor(s);+ const rc = remainColor(s);+ const hosts = s.allowed_hosts?.length ? s.allowed_hosts.join(', ') : 'Any host';+ const maxTx = s.max_per_tx_usd != null ? `$${s.max_per_tx_usd}` : 'No limit';+ const network = s.network === 'base' ? 'Base' : 'Solana';++ return `+ <div class="sess-card" data-id="${s.id}">+ <div class="sess-card-head" role="button" tabindex="0" aria-expanded="false">+ <span class="sess-badge ${s.status}">${s.status}</span>+ <span class="sess-label">${escHtml(s.label || 'Unnamed session')}</span>+ <div class="sess-amounts">+ <span class="sess-remaining ${rc}">$${s.remaining_usd.toFixed(4)}</span>+ <span class="sess-budget-dim">/ $${s.budget_usd.toFixed(4)}</span>+ </div>+ <span class="sess-expand">⌄</span>+ </div>+ <div class="sess-bar-wrap">+ <div class="sess-bar-track"><div class="sess-bar-fill ${bc}" style="width:${p}%"></div></div>+ </div>+ <div class="sess-detail">+ <div class="sess-meta">+ <div class="sess-meta-item"><div class="k">Session ID</div><div class="v"><code>${escHtml(s.id.slice(0,13))}…</code></div></div>+ <div class="sess-meta-item"><div class="k">Spent</div><div class="v">$${s.spent_usd.toFixed(6)}</div></div>+ <div class="sess-meta-item"><div class="k">Network</div><div class="v">${network}</div></div>+ <div class="sess-meta-item"><div class="k">Max per tx</div><div class="v">${maxTx}</div></div>+ <div class="sess-meta-item"><div class="k">Allowed hosts</div><div class="v" style="font-size:12px">${escHtml(hosts)}</div></div>+ <div class="sess-meta-item"><div class="k">Expiry</div><div class="v">${fmtExpiry(s)}</div></div>+ <div class="sess-meta-item"><div class="k">Created</div><div class="v">${fmtDate(s.created_at)}</div></div>+ </div>+ <div class="exec-section" data-exec-session="${s.id}">+ <div style="color:rgba(255,255,255,0.35);font-size:13px">Loading payments…</div>+ </div>+ ${s.status === 'active' ? `+ <div class="sess-actions">+ <button class="sess-btn cancel" data-cancel="${s.id}">Cancel & refund</button>+ </div>+ ` : ''}+ </div>+ </div>+ `;+ }++ // ── Render session list ─────────────────────────────────+ function renderList() {+ const listEl = $('payList');+ const filtered = activeFilter === 'all' ? sessions : sessions.filter(s => s.status === activeFilter);+ if (!filtered.length) {+ listEl.innerHTML = `+ <div class="pay-empty">+ <h2>${activeFilter === 'all' ? 'No payment sessions yet' : `No ${activeFilter} sessions`}</h2>+ <p>Create a session to fund an AI agent's payments from your credits — no private key required.</p>+ ${activeFilter === 'all' ? `<button class="btn-new" onclick="openModal()">New Session</button>` : ''}+ </div>+ `;+ return;+ }+ listEl.innerHTML = filtered.map(renderCard).join('');++ // Expand/collapse+ listEl.querySelectorAll('.sess-card-head').forEach(head => {+ head.addEventListener('click', () => toggleCard(head.closest('.sess-card')));+ head.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleCard(head.closest('.sess-card')); } });+ });++ // Cancel buttons+ listEl.querySelectorAll('[data-cancel]').forEach(btn => {+ btn.addEventListener('click', e => { e.stopPropagation(); cancelSession(btn.dataset.cancel); });+ });+ }++ async function toggleCard(card) {+ const wasOpen = card.classList.contains('open');+ card.classList.toggle('open');+ const head = card.querySelector('.sess-card-head');+ head.setAttribute('aria-expanded', card.classList.contains('open') ? 'true' : 'false');++ if (!wasOpen) {+ const execSection = card.querySelector('.exec-section');+ const sessionId = execSection?.dataset.execSession;+ if (sessionId && execSection) {+ try {+ const data = await apiFetch(`/api/pay/session/${sessionId}/executions?limit=10`);+ execSection.innerHTML = renderExecs(data.items);+ } catch {+ execSection.innerHTML = '<div style="color:rgba(255,80,80,0.7);font-size:13px">Could not load payments.</div>';+ }+ }+ }+ }++ async function cancelSession(id) {+ if (!confirm('Cancel this session? Un-spent budget will be refunded to your credits.')) return;+ try {+ const data = await apiFetch(`/api/pay/session/${id}`, { method: 'DELETE' });+ toast(`Cancelled. $${data.refunded_usd?.toFixed(4) ?? '0'} refunded to credits.`);+ await load();+ } catch (err) {+ toast(err.message || 'Failed to cancel session.');+ }+ }++ // ── Load data ───────────────────────────────────────────+ async function load() {+ try {+ const data = await apiFetch('/api/pay/session');+ sessions = data.items || [];+ stats = data.stats;+ if (stats) renderStats(stats);+ renderList();+ } catch (err) {+ if (err.status === 401) {+ $('payList').innerHTML = `+ <div class="pay-empty">+ <h2>Sign in to manage sessions</h2>+ <p>Payment sessions are account-scoped. Sign in to create and manage them.</p>+ <a href="/login?r=/payments" class="btn-new" style="display:inline-flex;text-decoration:none">Sign in</a>+ </div>+ `;+ $('payStats').innerHTML = '';+ } else {+ $('payList').innerHTML = `<div class="pay-empty"><h2>Could not load sessions</h2><p>${err.message}</p></div>`;+ }+ }+ }++ // ── Filter ──────────────────────────────────────────────+ $('filterRow').addEventListener('click', e => {+ const btn = e.target.closest('button[data-f]');+ if (!btn) return;+ $('filterRow').querySelectorAll('button').forEach(b => b.classList.remove('active'));+ btn.classList.add('active');+ activeFilter = btn.dataset.f;+ renderList();+ });++ // ── Create modal ────────────────────────────────────────+ function openModal() {+ $('tokenReveal').style.display = 'none';+ $('modalActions').style.display = 'flex';+ $('modalCreate').disabled = false;+ $('modalCreate').textContent = 'Create session';+ $('createModal').classList.add('show');+ $('fBudget').focus();+ }++ window.openModal = openModal;++ $('btnNew').addEventListener('click', openModal);+ $('modalClose').addEventListener('click', () => {+ $('createModal').classList.remove('show');+ load();+ });+ $('createModal').addEventListener('click', e => {+ if (e.target === $('createModal')) { $('createModal').classList.remove('show'); load(); }+ });++ $('modalCreate').addEventListener('click', async () => {+ const budget = parseFloat($('fBudget').value);+ if (!budget || budget <= 0) { toast('Enter a budget amount.'); return; }++ const hostsRaw = $('fHosts').value.trim();+ const allowed_hosts = hostsRaw ? hostsRaw.split(/[\s,]+/).map(h => h.trim()).filter(Boolean) : [];++ const maxTxRaw = $('fMaxTx').value.trim();+ const max_per_tx_usd = maxTxRaw ? parseFloat(maxTxRaw) : null;++ $('modalCreate').disabled = true;+ $('modalCreate').textContent = 'Creating…';++ try {+ const data = await apiFetch('/api/pay/session', {+ method: 'POST',+ body: JSON.stringify({+ budget_usd: budget,+ label: $('fLabel').value.trim(),+ expiry_seconds: parseInt($('fExpiry').value, 10),+ max_per_tx_usd,+ allowed_hosts,+ network: $('fNetwork').value,+ }),+ });++ // Show the token+ $('tokenVal').textContent = data.token;+ $('tokenReveal').style.display = 'block';+ $('modalActions').innerHTML = `<button class="secondary" id="modalDone">Done</button>`;+ $('modalDone').addEventListener('click', () => { $('createModal').classList.remove('show'); load(); });++ $('tokenCopyBtn').addEventListener('click', () => {+ navigator.clipboard.writeText(data.token).then(() => toast('Token copied to clipboard.')).catch(() => {});+ });++ } catch (err) {+ toast(err.message || 'Failed to create session.');+ $('modalCreate').disabled = false;+ $('modalCreate').textContent = 'Create session';+ }+ });++ load();+ </script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex 6f10e76ca..cb8ff0848 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-06-26T20:03:46.147Z",+ "generated_at": "2026-06-26T21:04:17.980Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-26",+ "type": "launch",+ "title": "Agent Payment Sessions",+ "summary": "Create budget-limited payment sessions for AI agents. Governance-enforced spend limits, URL allowlists, and expiry — agents pay x402 APIs without holding a private key.",+ "link": "/payments",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-26","type": "launch",@@ -56,6 +66,16 @@"improvement"]},+ {+ "date": "2026-06-26",+ "type": "update",+ "title": "4 new agent capabilities: Alpha Hunt, Coin Launcher, Creator Auto-Claim, and Market Maker",+ "summary": "Agents can now do a lot more. Alpha Hunt is a new strategy trigger that scores coins using smart-money signals, organic growth patterns, quality scores, and narrative keywords — finding undervalued gems before they move. Coin Launcher lets an agent autonomously launch coins on pump.fun on a schedule, with configurable metadata templates, initial dev buys, and Telegram notifications. Creator Auto-Claim watches your agent's launched coins and automatically claims creator fees when they exceed a configurable threshold, with optional reinvestment into the sniper buy budget. Market Maker uses Jito-accelerated execution to provide liquidity on any pump.fun coin, placing buy and sell orders in a configured spread band to capture the spread. All four capabilities are wired into the agent-sniper worker and configurable from the agent edit page.",+ "link": "/play",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-26","type": "update",@@ -88,6 +108,17 @@"improvement"]},+ {+ "date": "2026-06-26",+ "type": "update",+ "title": "Agent Payment Sessions — governed x402 spend without private keys",+ "summary": "Agents can now pay x402 APIs without holding a private key. Create a Payment Session with a budget (drawn from credits), hand the token to an agent, and the platform signs every Solana USDC transfer. Five governance checks fire before any money moves: token auth, session status, URL allowlist, per-tx ceiling, and atomic budget reservation. Sessions expire automatically; un-spent budget is refunded on cancel. Also ships: a /payments dashboard to manage sessions and view payment history, and the @three-ws/agentcore-payments-mcp MCP server with create_payment_session, pay_with_session, check_payment_session, list_payment_sessions, and cancel_payment_session tools.",+ "link": "/payments",+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-06-26","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 65656e0fc..2a54f68df 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Agent Payment Sessions</title>+ <link>https://three.ws/payments</link>+ <guid isPermaLink="false">2026-06-26:Agent Payment Sessions</guid>+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Create budget-limited payment sessions for AI agents. Governance-enforced spend limits, URL allowlists, and expiry — agents pay x402 APIs without holding a private key.</description>+ </item><item><title>Agent Screen</title><link>https://three.ws/agent-screen</link>@@ -46,6 +54,14 @@<category>improvement</category><description>Auto-generated avatars used to render dark and flat in the gallery — dark-clothed agents could all but disappear into the black cards. The 3D viewer now lights every avatar with a proper studio three-point rig (key, fill, and a rim/back light that traces a bright edge around the silhouette so no avatar blends into the background), boosted ambient and image-based lighting, and the Khronos PBR-Neutral tone mapper, which keeps colors bright and true instead of crushing them. The preview-card edge vignette was softened so small thumbnails no longer look murky. The same rig now also drives the server-rendered poster images used for share cards and gallery warm-up, so avatars look consistent and vivid the instant they appear.</description></item>+ <item>+ <title>4 new agent capabilities: Alpha Hunt, Coin Launcher, Creator Auto-Claim, and Market Maker</title>+ <link>https://three.ws/play</link>+ <guid isPermaLink="false">2026-06-26:4 new agent capabilities: Alpha Hunt, Coin Launcher, Creator Auto-Claim, and Market Maker</guid>+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Agents can now do a lot more. Alpha Hunt is a new strategy trigger that scores coins using smart-money signals, organic growth patterns, quality scores, and narrative keywords — finding undervalued gems before they move. Coin Launcher lets an agent autonomously launch coins on pump.fun on a schedule, with configurable metadata templates, initial dev buys, and Telegram notifications. Creator Auto-Claim watches your agent's launched coins and automatically claims creator fees when they exceed a configurable threshold, with optional reinvestment into the sniper buy budget. Market Maker uses Jito-accelerated execution to provide liquidity on any pump.fun coin, placing buy and sell orders in a configured spread band to capture the spread. All four capabilities are wired into the agent-sniper worker and configurable from the agent edit page.</description>+ </item><item><title>A stale Arena link no longer dead-ends on a 'not found' screen</title><link>https://three.ws/arena</link>@@ -70,6 +86,14 @@<category>improvement</category><description>The agent editor no longer makes you click through 15 tabs to configure your agent. Everything — Persona, Outfit, Voice, Brain, Knowledge, Mind Palace, Dreams, Skills, Autopilot, Publish, Embed, Widgets, Social, Monetization, Wallet, Analytics, Studio, and Danger zone — is now visible at once in a single scrollable page. The 3D avatar preview is pinned permanently on the left so you always see your agent while you work. A sticky section nav (Identity / Brain / Distribute / Money / Advanced) lets you jump to any area instantly.</description></item>+ <item>+ <title>Agent Payment Sessions — governed x402 spend without private keys</title>+ <link>https://three.ws/payments</link>+ <guid isPermaLink="false">2026-06-26:Agent Payment Sessions — governed x402 spend without private keys</guid>+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Agents can now pay x402 APIs without holding a private key. Create a Payment Session with a budget (drawn from credits), hand the token to an agent, and the platform signs every Solana USDC transfer. Five governance checks fire before any money moves: token auth, session status, URL allowlist, per-tx ceiling, and atomic budget reservation. Sessions expire automatically; un-spent budget is refunded on cancel. Also ships: a /payments dashboard to manage sessions and view payment history, and the @three-ws/agentcore-payments-mcp MCP server with create_payment_session, pay_with_session, check_payment_session, list_payment_sessions, and cancel_payment_session tools.</description>+ </item><item><title>Agent profile pages no longer fail to load over a hiccup</title><link>https://three.ws/agents</link>diff --git a/public/features.json b/public/features.jsonindex 0faf61940..07769999a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-26T20:03:46.134Z",+ "generated_at": "2026-06-26T21:04:17.961Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1530,6 +1530,16 @@"tags": [],"showcase": false},+ {+ "path": "/payments",+ "title": "Agent Payment Sessions",+ "description": "Create budget-limited payment sessions for AI agents. Governance-enforced spend limits, URL allowlists, and expiry — agents pay x402 APIs without holding a private key.",+ "added": "2026-06-26",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/login","title": "Sign in",diff --git a/public/llms-full.txt b/public/llms-full.txtindex f9143ff11..ffa9c5690 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -931,6 +931,12 @@ URL: https://three.ws/creditsTop up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.+### Agent Payment Sessions++URL: https://three.ws/payments++Create budget-limited payment sessions for AI agents. Governance-enforced spend limits, URL allowlists, and expiry — agents pay x402 APIs without holding a private key.+### Sign inURL: https://three.ws/logindiff --git a/public/llms.txt b/public/llms.txtindex 971273c08..a9e397638 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -179,6 +179,7 @@ Manage, talk to, and deploy individual agents.Sign-in, dashboard, billing.- [Credits](https://three.ws/credits): Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.+- [Agent Payment Sessions](https://three.ws/payments): Create budget-limited payment sessions for AI agents. Governance-enforced spend limits, URL allowlists, and expiry — agents pay x402 APIs without holding a private key.- [Sign in](https://three.ws/login): Sign in with email, GitHub, or a connected wallet.- [Create account](https://three.ws/register): Create a new three.ws account.- [Forgot password](https://three.ws/forgot-password): Request a password-reset email.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex f00d34cbd..f8a949868 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 342 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 343 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 342 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 343 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -1170,7 +1170,7 @@<section class="sm-section" id="account"><header>- <h2>Account<span class="sm-count" data-count>9</span></h2>+ <h2>Account<span class="sm-count" data-count>10</span></h2><p class="sm-section-desc">Sign-in, dashboard, billing.</p></header><ul class="sm-list">@@ -1181,6 +1181,13 @@<span class="sm-desc">Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.</span></a></li>+ <li>+ <a href="/payments">+ <span class="sm-title">Agent Payment Sessions</span>+ <span class="sm-path">/payments</span>+ <span class="sm-desc">Create budget-limited payment sessions for AI agents. Governance-enforced spend limits, URL allowlists, and expiry — agents pay x402 APIs without holding a private key.</span>+ </a>+ </li><li><a href="/login"><span class="sm-title">Sign in</span>diff --git a/src/agent-edit.js b/src/agent-edit.jsindex 90cc2fcad..44dfbfc01 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -3201,6 +3201,11 @@ async function init() {if (moodHost && agentData?.id) {mountMoodInspector(moodHost, { agentId: agentData.id });}++ // Autonomous capabilities — alpha hunt, coin launcher, auto-claim, market maker.+ initAlphaHunt();+ initLauncher();+ initMarketMaker();}async function primeDreamsBadge() {@@ -3215,4 +3220,373 @@ async function primeDreamsBadge() {}}+// ═══════════════════════════════════════════════════════════════════════════+// ALPHA HUNT — strategy config wired to /api/sniper/strategy+// ═══════════════════════════════════════════════════════════════════════════++async function initAlphaHunt() {+ if (!agentId) return;+ const statusEl = document.getElementById('alpha-hunt-status');+ function setStatus(msg, ok = true) {+ if (!statusEl) return;+ statusEl.textContent = msg;+ statusEl.style.color = ok ? 'rgba(255,255,255,0.6)' : '#f87171';+ if (msg) setTimeout(() => { statusEl.textContent = ''; }, 4000);+ }++ // Load existing alpha_hunt strategy for this agent+ try {+ const r = await apiFetch(`${API_BASE}/sniper/strategy?agentId=${agentId}`, { credentials: 'include' });+ if (r.ok) {+ const { strategies = [] } = await r.json();+ const s = strategies.find(x => x.trigger === 'alpha_hunt');+ if (s) {+ const g = id => document.getElementById(id);+ if (g('alpha-enabled')) g('alpha-enabled').checked = !!s.enabled;+ if (g('alpha-min-smart-money')) g('alpha-min-smart-money').value = s.alpha_min_smart_money ?? '';+ if (g('alpha-min-quality-score')) g('alpha-min-quality-score').value = s.alpha_min_quality_score ?? '';+ if (g('alpha-min-organic-score')) g('alpha-min-organic-score').value = s.alpha_min_organic_score ?? '';+ if (g('alpha-max-mcap-usd')) g('alpha-max-mcap-usd').value = s.alpha_max_mcap_usd ?? '';+ if (g('alpha-narrative-keywords') && s.alpha_narrative_keywords?.length) {+ g('alpha-narrative-keywords').value = s.alpha_narrative_keywords.join(', ');+ }+ if (g('alpha-per-trade-sol')) g('alpha-per-trade-sol').value = s.per_trade_sol ?? '';+ if (g('alpha-daily-budget-sol')) g('alpha-daily-budget-sol').value = s.daily_budget_sol ?? '';+ if (g('alpha-stop-loss')) g('alpha-stop-loss').value = s.stop_loss_pct ?? '';+ if (g('alpha-take-profit')) g('alpha-take-profit').value = s.take_profit_pct ?? '';+ if (g('alpha-trailing-stop')) g('alpha-trailing-stop').value = s.trailing_stop_pct ?? '';+ if (g('alpha-mev-tip')) g('alpha-mev-tip').value = s.mev_tip_mode || 'economy';+ }+ }+ } catch { /* load errors are non-fatal — form stays at defaults */ }++ const saveBtn = document.getElementById('alpha-hunt-save');+ if (!saveBtn) return;+ saveBtn.addEventListener('click', async () => {+ saveBtn.disabled = true;+ setStatus('Saving…');+ const g = id => document.getElementById(id);+ const keywords = (g('alpha-narrative-keywords')?.value || '')+ .split(',').map(s => s.trim()).filter(Boolean);+ const body = {+ agentId,+ trigger: 'alpha_hunt',+ enabled: g('alpha-enabled')?.checked ?? true,+ alpha_min_smart_money: g('alpha-min-smart-money')?.value !== '' ? Number(g('alpha-min-smart-money').value) : null,+ alpha_min_quality_score: g('alpha-min-quality-score')?.value !== '' ? Number(g('alpha-min-quality-score').value) : null,+ alpha_min_organic_score: g('alpha-min-organic-score')?.value !== '' ? Number(g('alpha-min-organic-score').value) : null,+ alpha_max_mcap_usd: g('alpha-max-mcap-usd')?.value !== '' ? Number(g('alpha-max-mcap-usd').value) : null,+ alpha_narrative_keywords: keywords.length ? keywords : null,+ mev_tip_mode: g('alpha-mev-tip')?.value || 'economy',+ };+ try {+ const r = await apiFetch(`${API_BASE}/sniper/strategy`, {+ method: 'POST', credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ const j = await r.json();+ if (!r.ok) throw new Error(j.message || j.error || 'Save failed');+ setStatus('Saved');+ } catch (err) {+ setStatus(err.message, false);+ } finally {+ saveBtn.disabled = false;+ }+ });+}++// ═══════════════════════════════════════════════════════════════════════════+// LAUNCHER — wired to /api/agent/launcher+// ═══════════════════════════════════════════════════════════════════════════++async function initLauncher() {+ if (!agentId) return;+ const statusEl = document.getElementById('launcher-status');+ function setStatus(msg, ok = true) {+ if (!statusEl) return;+ statusEl.textContent = msg;+ statusEl.style.color = ok ? 'rgba(255,255,255,0.6)' : '#f87171';+ if (msg) setTimeout(() => { statusEl.textContent = ''; }, 4000);+ }++ async function loadLauncher() {+ try {+ const r = await apiFetch(`${API_BASE}/agent/launcher?agentId=${agentId}`, { credentials: 'include' });+ if (!r.ok) return;+ const { configs = [], coins = [] } = await r.json();+ const cfg = configs[0];+ if (cfg) {+ const g = id => document.getElementById(id);+ if (g('launcher-enabled')) g('launcher-enabled').checked = !!cfg.enabled;+ if (g('launcher-network')) g('launcher-network').value = cfg.network || 'mainnet';+ if (g('launcher-interval-hours')) g('launcher-interval-hours').value = cfg.interval_hours ?? '';+ if (g('launcher-max-launches')) g('launcher-max-launches').value = cfg.max_launches ?? '';+ if (g('launcher-name-template')) g('launcher-name-template').value = cfg.name_template ?? '';+ if (g('launcher-symbol')) g('launcher-symbol').value = cfg.symbol ?? '';+ if (g('launcher-description')) g('launcher-description').value = cfg.description ?? '';+ if (g('launcher-image-url')) g('launcher-image-url').value = cfg.image_url ?? '';+ if (g('launcher-twitter')) g('launcher-twitter').value = cfg.twitter ?? '';+ if (g('launcher-telegram')) g('launcher-telegram').value = cfg.telegram ?? '';+ if (g('launcher-website')) g('launcher-website').value = cfg.website ?? '';+ if (g('launcher-initial-buy')) g('launcher-initial-buy').value = cfg.initial_buy_sol ?? '';+ if (g('auto-claim-enabled')) g('auto-claim-enabled').checked = !!cfg.auto_claim_enabled;+ if (g('auto-claim-threshold')) g('auto-claim-threshold').value = cfg.auto_claim_threshold_sol ?? '';+ const reinvest = document.getElementById('auto-claim-reinvest');+ const reinvestVal = document.getElementById('auto-claim-reinvest-val');+ if (reinvest) reinvest.value = cfg.auto_claim_reinvest_pct ?? 0;+ if (reinvestVal) reinvestVal.textContent = `${Math.round(cfg.auto_claim_reinvest_pct ?? 0)}%`;+ }+ renderLaunchedCoins(coins);+ renderClaimableFees(coins);+ } catch { /* non-fatal */ }+ }++ function renderLaunchedCoins(coins) {+ const wrap = document.getElementById('launched-coins-table-wrap');+ if (!wrap) return;+ if (!coins.length) {+ wrap.innerHTML = '<div class="muted">No coins launched yet.</div>';+ return;+ }+ wrap.innerHTML = `+ <table style="width:100%;border-collapse:collapse;font-size:0.78rem">+ <thead>+ <tr style="color:rgba(255,255,255,0.4);text-align:left">+ <th style="padding:0.4rem 0.6rem">Symbol</th>+ <th style="padding:0.4rem 0.6rem">Name</th>+ <th style="padding:0.4rem 0.6rem">Network</th>+ <th style="padding:0.4rem 0.6rem">Claimed SOL</th>+ <th style="padding:0.4rem 0.6rem">Graduated</th>+ <th style="padding:0.4rem 0.6rem">Launched</th>+ </tr>+ </thead>+ <tbody>+ ${coins.map(c => `+ <tr style="border-top:1px solid rgba(255,255,255,0.06)">+ <td style="padding:0.4rem 0.6rem;font-weight:600">$${escHtml(c.symbol || '—')}</td>+ <td style="padding:0.4rem 0.6rem;color:rgba(255,255,255,0.7)">${escHtml(c.name || '—')}</td>+ <td style="padding:0.4rem 0.6rem;color:rgba(255,255,255,0.5)">${escHtml(c.network || 'mainnet')}</td>+ <td style="padding:0.4rem 0.6rem">${c.total_claimed_lamports ? (Number(c.total_claimed_lamports) / 1e9).toFixed(4) : '0'}</td>+ <td style="padding:0.4rem 0.6rem">${c.is_graduated ? '<span style="color:#34d399">Yes</span>' : '<span style="color:rgba(255,255,255,0.3)">No</span>'}</td>+ <td style="padding:0.4rem 0.6rem;color:rgba(255,255,255,0.4)">${c.created_at ? new Date(c.created_at).toLocaleDateString() : '—'}</td>+ </tr>+ `).join('')}+ </tbody>+ </table>`;+ }++ function renderClaimableFees(coins) {+ const wrap = document.getElementById('claimable-fees-table-wrap');+ if (!wrap) return;+ const withFees = coins.filter(c => Number(c.claimable_lamports) > 0);+ if (!withFees.length) {+ wrap.innerHTML = '<div class="muted">No claimable fees yet. Fees accumulate as your coins trade.</div>';+ return;+ }+ wrap.innerHTML = `+ <table style="width:100%;border-collapse:collapse;font-size:0.78rem">+ <thead>+ <tr style="color:rgba(255,255,255,0.4);text-align:left">+ <th style="padding:0.4rem 0.6rem">Symbol</th>+ <th style="padding:0.4rem 0.6rem">Claimable (SOL)</th>+ <th style="padding:0.4rem 0.6rem">Auto-Claim</th>+ <th style="padding:0.4rem 0.6rem">Last Checked</th>+ </tr>+ </thead>+ <tbody>+ ${withFees.map(c => `+ <tr style="border-top:1px solid rgba(255,255,255,0.06)">+ <td style="padding:0.4rem 0.6rem;font-weight:600">$${escHtml(c.symbol || '—')}</td>+ <td style="padding:0.4rem 0.6rem;color:#34d399">${(Number(c.claimable_lamports) / 1e9).toFixed(4)}</td>+ <td style="padding:0.4rem 0.6rem">${c.auto_claim_enabled ? '<span style="color:#60a5fa">On</span>' : '<span style="color:rgba(255,255,255,0.3)">Off</span>'}</td>+ <td style="padding:0.4rem 0.6rem;color:rgba(255,255,255,0.4)">${c.last_fee_check_at ? new Date(c.last_fee_check_at).toLocaleDateString() : 'Never'}</td>+ </tr>+ `).join('')}+ </tbody>+ </table>`;+ }++ // Wire reinvest slider display+ const reinvest = document.getElementById('auto-claim-reinvest');+ const reinvestVal = document.getElementById('auto-claim-reinvest-val');+ if (reinvest && reinvestVal) {+ reinvest.addEventListener('input', () => { reinvestVal.textContent = `${reinvest.value}%`; });+ }++ await loadLauncher();++ const saveBtn = document.getElementById('launcher-save');+ if (saveBtn) {+ saveBtn.addEventListener('click', async () => {+ saveBtn.disabled = true;+ setStatus('Saving…');+ const g = id => document.getElementById(id);+ const body = {+ agentId,+ enabled: g('launcher-enabled')?.checked ?? false,+ network: g('launcher-network')?.value || 'mainnet',+ interval_hours: g('launcher-interval-hours')?.value !== '' ? Number(g('launcher-interval-hours').value) : null,+ max_launches: g('launcher-max-launches')?.value !== '' ? Number(g('launcher-max-launches').value) : null,+ name_template: g('launcher-name-template')?.value || '',+ symbol: (g('launcher-symbol')?.value || '').toUpperCase(),+ description: g('launcher-description')?.value || null,+ image_url: g('launcher-image-url')?.value || null,+ twitter: g('launcher-twitter')?.value || null,+ telegram: g('launcher-telegram')?.value || null,+ website: g('launcher-website')?.value || null,+ initial_buy_sol: g('launcher-initial-buy')?.value !== '' ? Number(g('launcher-initial-buy').value) : 0,+ auto_claim_enabled: g('auto-claim-enabled')?.checked ?? false,+ auto_claim_threshold_sol: g('auto-claim-threshold')?.value !== '' ? Number(g('auto-claim-threshold').value) : 0.5,+ auto_claim_reinvest_pct: g('auto-claim-reinvest')?.value !== '' ? Number(g('auto-claim-reinvest').value) : 0,+ };+ try {+ const r = await apiFetch(`${API_BASE}/agent/launcher`, {+ method: 'POST', credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ const j = await r.json();+ if (!r.ok) throw new Error(j.message || j.error || 'Save failed');+ setStatus('Saved');+ await loadLauncher();+ } catch (err) {+ setStatus(err.message, false);+ } finally {+ saveBtn.disabled = false;+ }+ });+ }++ // Auto-claim save mirrors launcher save (same endpoint, same config row)+ const acSaveBtn = document.getElementById('auto-claim-save');+ if (acSaveBtn) {+ acSaveBtn.addEventListener('click', () => {+ if (saveBtn) saveBtn.click();+ });+ }+}++// ═══════════════════════════════════════════════════════════════════════════+// MARKET MAKER — wired to /api/agent/market-maker+// ═══════════════════════════════════════════════════════════════════════════++async function initMarketMaker() {+ if (!agentId) return;+ const addStatusEl = document.getElementById('mm-add-status');+ function setAddStatus(msg, ok = true) {+ if (!addStatusEl) return;+ addStatusEl.textContent = msg;+ addStatusEl.style.color = ok ? 'rgba(255,255,255,0.6)' : '#f87171';+ if (msg) setTimeout(() => { addStatusEl.textContent = ''; }, 4000);+ }++ // Spread slider display+ const spreadSlider = document.getElementById('mm-spread');+ const spreadVal = document.getElementById('mm-spread-val');+ if (spreadSlider && spreadVal) {+ spreadSlider.addEventListener('input', () => {+ spreadVal.textContent = `${(Number(spreadSlider.value) / 100).toFixed(2)}%`;+ });+ }++ async function loadMarkets() {+ const wrap = document.getElementById('active-markets-table-wrap');+ if (!wrap) return;+ try {+ const r = await apiFetch(`${API_BASE}/agent/market-maker?agentId=${agentId}`, { credentials: 'include' });+ if (!r.ok) { wrap.innerHTML = '<div class="muted">Could not load markets.</div>'; return; }+ const { configs = [] } = await r.json();+ const active = configs.filter(c => c.enabled);+ if (!active.length) {+ wrap.innerHTML = '<div class="muted">No active markets. Add one above.</div>';+ return;+ }+ wrap.innerHTML = `+ <table style="width:100%;border-collapse:collapse;font-size:0.78rem">+ <thead>+ <tr style="color:rgba(255,255,255,0.4);text-align:left">+ <th style="padding:0.4rem 0.6rem">Symbol</th>+ <th style="padding:0.4rem 0.6rem">Spread</th>+ <th style="padding:0.4rem 0.6rem">Order Size</th>+ <th style="padding:0.4rem 0.6rem">Inventory</th>+ <th style="padding:0.4rem 0.6rem">P&L (SOL)</th>+ <th style="padding:0.4rem 0.6rem">MEV Tip</th>+ <th style="padding:0.4rem 0.6rem"></th>+ </tr>+ </thead>+ <tbody>+ ${active.map(c => `+ <tr style="border-top:1px solid rgba(255,255,255,0.06)" data-mm-id="${escHtml(c.id)}">+ <td style="padding:0.4rem 0.6rem;font-weight:600">${escHtml(c.symbol || c.mint.slice(0, 6))}</td>+ <td style="padding:0.4rem 0.6rem">${(Number(c.spread_bps) / 100).toFixed(2)}%</td>+ <td style="padding:0.4rem 0.6rem">${Number(c.order_size_sol).toFixed(3)} SOL</td>+ <td style="padding:0.4rem 0.6rem">${Number(c.current_inventory_sol || 0).toFixed(3)} / ${Number(c.max_inventory_sol).toFixed(3)}</td>+ <td style="padding:0.4rem 0.6rem;color:${Number(c.total_pnl_sol) >= 0 ? '#34d399' : '#f87171'}">${Number(c.total_pnl_sol || 0).toFixed(4)}</td>+ <td style="padding:0.4rem 0.6rem;color:rgba(255,255,255,0.5)">${escHtml(c.mev_tip_mode || 'off')}</td>+ <td style="padding:0.4rem 0.6rem">+ <button class="btn-ghost mm-remove-btn" style="font-size:0.7rem;padding:0.25rem 0.6rem" data-id="${escHtml(c.id)}">Remove</button>+ </td>+ </tr>+ `).join('')}+ </tbody>+ </table>`;+ wrap.querySelectorAll('.mm-remove-btn').forEach(btn => {+ btn.addEventListener('click', async () => {+ btn.disabled = true;+ try {+ const r = await apiFetch(`${API_BASE}/agent/market-maker?id=${encodeURIComponent(btn.dataset.id)}`, {+ method: 'DELETE', credentials: 'include',+ });+ if (!r.ok) { const j = await r.json(); throw new Error(j.message || 'Failed'); }+ await loadMarkets();+ } catch (err) {+ setAddStatus(err.message, false);+ btn.disabled = false;+ }+ });+ });+ } catch { wrap.innerHTML = '<div class="muted">Failed to load markets.</div>'; }+ }++ await loadMarkets();++ const addBtn = document.getElementById('mm-add-market');+ if (addBtn) {+ addBtn.addEventListener('click', async () => {+ addBtn.disabled = true;+ setAddStatus('Adding…');+ const g = id => document.getElementById(id);+ const body = {+ agentId,+ mint: g('mm-mint')?.value?.trim() || '',+ symbol: (g('mm-symbol')?.value || '').toUpperCase(),+ spread_bps: Number(g('mm-spread')?.value || 200),+ order_size_sol: Number(g('mm-order-size')?.value || 0.05),+ max_inventory_sol: Number(g('mm-max-inventory')?.value || 1.0),+ rebalance_interval_ms: Number(g('mm-rebalance')?.value || 30) * 1000,+ mev_tip_mode: g('mm-mev-tip')?.value || 'economy',+ };+ if (!body.mint) { setAddStatus('Mint address is required', false); addBtn.disabled = false; return; }+ try {+ const r = await apiFetch(`${API_BASE}/agent/market-maker`, {+ method: 'POST', credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ const j = await r.json();+ if (!r.ok) throw new Error(j.message || j.error || 'Add failed');+ setAddStatus('Market added');+ if (g('mm-mint')) g('mm-mint').value = '';+ if (g('mm-symbol')) g('mm-symbol').value = '';+ await loadMarkets();+ } catch (err) {+ setAddStatus(err.message, false);+ } finally {+ addBtn.disabled = false;+ }+ });+ }+}+init();diff --git a/vercel.json b/vercel.jsonindex b674bf4b5..2949ee5ef 100644--- a/vercel.json+++ b/vercel.json@@ -43,6 +43,9 @@"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 60},+ "api/pay/execute.js": {+ "maxDuration": 60+ },"api/widgets/[id]/knowledge-process.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 300@@ -547,6 +550,18 @@"src": "/api/payments/intent","dest": "/api/payments/intent"},+ {+ "src": "/api/pay/session(?:/(.*))?",+ "dest": "/api/pay/session"+ },+ {+ "src": "/api/pay/execute",+ "dest": "/api/pay/execute"+ },+ {+ "src": "/payments",+ "dest": "/payments.html"+ },{"src": "/oauth/token","dest": "/api/oauth/[action]?action=token"diff --git a/vite.config.js b/vite.config.jsindex 8b1c6a74b..fbc3058ef 100644--- a/vite.config.js+++ b/vite.config.js@@ -450,6 +450,7 @@ const appConfig = {pricing: resolve(__dirname, 'pages/pricing.html'),billing: resolve(__dirname, 'pages/billing.html'),credits: resolve(__dirname, 'pages/credits.html'),+ payments: resolve(__dirname, 'pages/payments.html'),'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),'avatar-studio-demo': resolve(__dirname, 'pages/avatar-studio-demo.html'),'gallery-picker': resolve(__dirname, 'pages/gallery-picker.html'),diff --git a/workers/agent-sniper/alpha-hunt.js b/workers/agent-sniper/alpha-hunt.jsnew file mode 100644index 000000000..105ac9a7f--- /dev/null+++ b/workers/agent-sniper/alpha-hunt.js@@ -0,0 +1,167 @@+// agent-sniper — alpha_hunt strategy scorer. Pure, no I/O, no async.+//+// Receives an intel record (same shape as onIntel in index.js) and a strategy+// row, returns { pass, score, reasons }. Alpha hunt targets low-cap coins with+// real buying activity, smart money presence, and high organic quality.++function n(v) {+ if (v == null) return null;+ const x = Number(v);+ return Number.isFinite(x) ? x : null;+}++function hasFlag(risk_flags, flag) {+ if (!Array.isArray(risk_flags)) return false;+ return risk_flags.includes(flag);+}++/**+ * @param {object} rec intel record from watcher.js finalize+ * @param {object} strat agent_sniper_strategies row (trigger = 'alpha_hunt')+ * @returns {{ pass: boolean, score: number, reasons: string[] }}+ */+export function scoreAlpha(rec, strat) {+ const reasons = [];+ let score = 0;++ const sig = rec.signals ?? {};++ const qualityScore = n(rec.quality_score);+ const organicScore = n(sig.organic_score);+ const smartMoneyCount = n(rec.smart_money_count ?? sig.smart_money_count);+ const smartMoneyScr = n(rec.smart_money_score ?? sig.smart_money_score);+ const mcSol = n(sig.mc_sol_first_seen);+ const buyCount = n(sig.buy_count);+ const risk_flags = Array.isArray(rec.risk_flags) ? rec.risk_flags : [];++ // ── hard filters (any failure → skip immediately) ────────────────────────++ // min quality_score+ const minQuality = n(strat.alpha_min_quality_score);+ if (minQuality != null) {+ if (qualityScore == null || qualityScore < minQuality) {+ return { pass: false, score: 0, reasons: ['quality_score_below_min'] };+ }+ }++ // min smart_money_count+ const minSmartMoney = n(strat.alpha_min_smart_money);+ if (minSmartMoney != null) {+ if (smartMoneyCount == null || smartMoneyCount < minSmartMoney) {+ return { pass: false, score: 0, reasons: ['smart_money_count_below_min'] };+ }+ }++ // min organic_score (strategy field is 0-100, signal is 0-1)+ const minOrganic = n(strat.alpha_min_organic_score);+ if (minOrganic != null) {+ const organicPct = organicScore != null ? organicScore * 100 : null;+ if (organicPct == null || organicPct < minOrganic) {+ return { pass: false, score: 0, reasons: ['organic_score_below_min'] };+ }+ }++ // max market cap in USD+ const maxMcapUsd = n(strat.alpha_max_mcap_usd);+ if (maxMcapUsd != null) {+ // mc_sol_first_seen is in SOL; strategy provides USD cap.+ // We store/pass market_cap_usd on rec if available; else skip the check.+ const mcUsd = n(rec.market_cap_usd);+ if (mcUsd != null && mcUsd > maxMcapUsd) {+ return { pass: false, score: 0, reasons: ['mcap_above_max'] };+ }+ }++ // min market cap (standard field, shared with other strategies)+ const minMcapUsd = n(strat.min_market_cap_usd);+ if (minMcapUsd != null) {+ const mcUsd = n(rec.market_cap_usd);+ if (mcUsd == null || mcUsd < minMcapUsd) {+ return { pass: false, score: 0, reasons: ['mcap_below_min'] };+ }+ }++ // narrative keyword match (optional — only enforced if keywords are set)+ const keywords = Array.isArray(strat.alpha_narrative_keywords)+ ? strat.alpha_narrative_keywords.filter(Boolean)+ : [];+ if (keywords.length > 0) {+ const haystack = [+ rec.name ?? '',+ rec.symbol ?? '',+ rec.narrative ?? '',+ ].join(' ').toLowerCase();+ const matched = keywords.some(kw => haystack.includes(String(kw).toLowerCase()));+ if (!matched) {+ return { pass: false, score: 0, reasons: ['no_narrative_keyword_match'] };+ }+ reasons.push(`narrative_match:${keywords.filter(kw => haystack.includes(String(kw).toLowerCase())).join(',')}`);+ }++ // ── score computation ─────────────────────────────────────────────────────++ // +30 if quality_score >= 70+ if (qualityScore != null && qualityScore >= 70) {+ score += 30;+ reasons.push(`quality_score:${qualityScore}`);+ } else if (qualityScore != null) {+ reasons.push(`quality_score:${qualityScore}`);+ }++ // +20 if smart_money_count >= 2, +10 if >= 1+ if (smartMoneyCount != null && smartMoneyCount >= 2) {+ score += 20;+ reasons.push(`smart_money_count:${smartMoneyCount}`);+ } else if (smartMoneyCount != null && smartMoneyCount >= 1) {+ score += 10;+ reasons.push(`smart_money_count:${smartMoneyCount}`);+ }++ // +15 if organic_score >= 0.7, +10 if >= 0.5+ if (organicScore != null && organicScore >= 0.7) {+ score += 15;+ reasons.push(`organic_score:${organicScore.toFixed(3)}`);+ } else if (organicScore != null && organicScore >= 0.5) {+ score += 10;+ reasons.push(`organic_score:${organicScore.toFixed(3)}`);+ } else if (organicScore != null) {+ reasons.push(`organic_score:${organicScore.toFixed(3)}`);+ }++ // +10 if no risk_flags (or only 'low_volume')+ const significantFlags = risk_flags.filter(f => f !== 'low_volume');+ if (significantFlags.length === 0) {+ score += 10;+ reasons.push('clean_risk_flags');+ }++ // +5 if buy_count >= 20+ if (buyCount != null && buyCount >= 20) {+ score += 5;+ reasons.push(`buy_count:${buyCount}`);+ } else if (buyCount != null) {+ reasons.push(`buy_count:${buyCount}`);+ }++ // -20 if coordinated_cluster in risk_flags+ if (hasFlag(risk_flags, 'coordinated_cluster')) {+ score -= 20;+ reasons.push('penalty:coordinated_cluster');+ }++ // -10 if dev_sell in risk_flags+ if (hasFlag(risk_flags, 'dev_sell')) {+ score -= 10;+ reasons.push('penalty:dev_sell');+ }++ // note smart_money_score if present for log context+ if (smartMoneyScr != null) {+ reasons.push(`smart_money_score:${smartMoneyScr}`);+ }++ const pass = score >= 40;+ if (!pass) reasons.push(`score_too_low:${score}`);++ return { pass, score, reasons };+}diff --git a/workers/agent-sniper/auto-claimer.js b/workers/agent-sniper/auto-claimer.jsnew file mode 100644index 000000000..cc5d70486--- /dev/null+++ b/workers/agent-sniper/auto-claimer.js@@ -0,0 +1,251 @@+// agent-sniper — auto-claimer for creator fees on agent-launched coins.+//+// Polls every 5 minutes for coins where auto_claim_enabled = true and the+// agent is part of an active strategy. When claimable fees exceed the+// per-launcher threshold (default 0.5 SOL), claims them via the platform+// fee-collect API. In simulate mode the claim is logged but not POSTed.++import fetch from 'node-fetch';+import { sql } from '../../api/_lib/db.js';+import { log } from './log.js';+import { screenPush } from './screen-push.js';+import { cachedStrategies } from './strategy-store.js';++const POLL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes+const DEFAULT_THRESHOLD_SOL = 0.5;++const API_BASE = process.env.API_BASE_URL || 'https://three.ws';+const AGENT_JWT = process.env.AGENT_JWT;++// ── helpers ──────────────────────────────────────────────────────────────────++function lamportsToSol(l) {+ return Number(BigInt(l)) / 1e9;+}++/** Active agent IDs from armed strategies in the cached strategy set. */+function activeAgentIds() {+ const strategies = cachedStrategies();+ const ids = new Set();+ for (const s of strategies) {+ if (s.agent_id) ids.add(s.agent_id);+ }+ return [...ids];+}++/**+ * Fetch fee-info for a single mint from the platform API.+ * Returns null on any error so the caller can skip gracefully.+ */+async function fetchFeeInfo(mint, network) {+ const url = `${API_BASE}/api/pump?action=fee-info&mint=${encodeURIComponent(mint)}&network=${encodeURIComponent(network)}`;+ try {+ const res = await fetch(url, {+ headers: { authorization: `Bearer ${AGENT_JWT}` },+ });+ if (!res.ok) {+ log.warn('fee-info fetch failed', { mint, network, status: res.status });+ return null;+ }+ return await res.json();+ } catch (err) {+ log.warn('fee-info fetch error', { mint, network, err: err?.message });+ return null;+ }+}++/**+ * POST collect-creator-fee-agent to claim fees.+ * Returns { ok, sig, lamports } on success, null on failure.+ */+async function collectCreatorFee(agentId, mint, network) {+ const url = `${API_BASE}/api/pump?action=collect-creator-fee-agent`;+ try {+ const res = await fetch(url, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${AGENT_JWT}`,+ },+ body: JSON.stringify({ agentId, mint, network }),+ });+ if (!res.ok) {+ const body = await res.text().catch(() => '');+ log.warn('collect-creator-fee failed', { agentId, mint, network, status: res.status, body: body.slice(0, 200) });+ return null;+ }+ return await res.json();+ } catch (err) {+ log.warn('collect-creator-fee error', { agentId, mint, network, err: err?.message });+ return null;+ }+}++// ── main tick ────────────────────────────────────────────────────────────────++async function tick(cfg) {+ const agentIds = activeAgentIds();+ if (!agentIds.length) return;++ // Fetch all auto-claim-eligible coins for active agents.+ let coins;+ try {+ coins = await sql`+ SELECT+ c.id,+ c.agent_id,+ c.user_id,+ c.network,+ c.mint,+ c.symbol,+ c.name,+ c.claimable_lamports,+ c.total_claimed_lamports,+ l.auto_claim_threshold_sol,+ l.auto_claim_reinvest_pct+ FROM agent_launched_coins c+ LEFT JOIN agent_launcher_configs l ON l.id = c.launcher_id+ WHERE c.auto_claim_enabled = true+ AND c.agent_id = ANY(${agentIds})+ AND c.network = ${cfg.network}+ `;+ } catch (err) {+ log.error('auto-claimer query failed', { err: err?.message });+ return;+ }++ if (!coins.length) return;++ for (const coin of coins) {+ await processCoin(cfg, coin);+ }+}++async function processCoin(cfg, coin) {+ const symbol = coin.symbol || coin.mint.slice(0, 6);+ const thresholdSol = Number(coin.auto_claim_threshold_sol ?? DEFAULT_THRESHOLD_SOL);++ screenPush(`Checking creator fees: ${coin.symbol}`, 'activity');+ log.info('fee-check', { agent: coin.agent_id, mint: coin.mint, symbol });++ // 1. Fetch live fee-info from the platform endpoint.+ const feeInfo = await fetchFeeInfo(coin.mint, coin.network);+ if (!feeInfo) return;++ const claimableLamports = BigInt(feeInfo.claimable_lamports ?? 0);+ const claimableSol = lamportsToSol(claimableLamports);++ // Update last-checked claimable balance regardless of whether we claim.+ try {+ await sql`+ UPDATE agent_launched_coins+ SET claimable_lamports = ${claimableLamports.toString()},+ last_fee_check_at = now(),+ is_graduated = ${feeInfo.is_graduated ?? false}+ WHERE id = ${coin.id}+ `;+ } catch (err) {+ log.warn('fee-check db update failed', { mint: coin.mint, err: err?.message });+ }++ log.info('fee-check result', {+ agent: coin.agent_id,+ mint: coin.mint,+ symbol,+ claimable_sol: claimableSol,+ threshold_sol: thresholdSol,+ });++ // 2. Check threshold.+ if (claimableSol < thresholdSol) {+ log.info('below threshold — skip', { agent: coin.agent_id, mint: coin.mint, symbol, claimable_sol: claimableSol, threshold_sol: thresholdSol });+ return;+ }++ // 3. Claim (or simulate).+ screenPush(`Claiming ${claimableSol.toFixed(3)} SOL creator fees for $${symbol}`, 'trade');++ if (cfg.mode !== 'live') {+ log.info('simulate — would claim creator fees', {+ agent: coin.agent_id, mint: coin.mint, symbol, claimable_sol: claimableSol,+ });+ return;+ }++ const result = await collectCreatorFee(coin.agent_id, coin.mint, coin.network);+ if (!result?.ok) {+ log.warn('claim failed', { agent: coin.agent_id, mint: coin.mint, symbol });+ return;+ }++ // 4. Persist claim result.+ const claimedLamports = BigInt(result.lamports ?? 0);+ const newTotal = BigInt(coin.total_claimed_lamports ?? 0) + claimedLamports;+ const totalSol = lamportsToSol(newTotal).toFixed(3);++ try {+ await sql`+ UPDATE agent_launched_coins+ SET claimable_lamports = 0,+ last_claim_sig = ${result.sig ?? null},+ last_claim_at = now(),+ total_claimed_lamports = ${newTotal.toString()}+ WHERE id = ${coin.id}+ `;+ } catch (err) {+ log.warn('claim db update failed', { mint: coin.mint, sig: result.sig, err: err?.message });+ }++ log.trade('creator-fee-claimed', {+ agent: coin.agent_id,+ mint: coin.mint,+ symbol,+ claimed_lamports: claimedLamports.toString(),+ claimed_sol: lamportsToSol(claimedLamports),+ total_claimed_sol: Number(totalSol),+ sig: result.sig,+ });++ screenPush(`Claimed ${lamportsToSol(claimedLamports)} SOL from $${symbol} — total: ${totalSol} SOL`, 'trade');+}++// ── public API ───────────────────────────────────────────────────────────────++/**+ * Start the auto-claimer watch loop.+ *+ * @param {{ cfg: object, signal?: AbortSignal }} options+ * cfg — the loadConfig() result (needs cfg.network, cfg.mode)+ * signal — optional AbortSignal; abort stops the loop+ * @returns {Function} stop — call to cancel the interval+ */+export function startAutoClaimerWatch({ cfg, signal } = {}) {+ let running = false;++ const runTick = () => {+ if (running) return;+ running = true;+ tick(cfg)+ .catch((err) => log.error('auto-claimer tick crashed', { err: err?.message }))+ .finally(() => { running = false; });+ };++ const interval = setInterval(runTick, POLL_INTERVAL_MS);+ if (interval.unref) interval.unref();++ log.info('auto-claimer armed', { network: cfg.network, mode: cfg.mode, pollMs: POLL_INTERVAL_MS });++ // Fire immediately on start so we don't wait 5 minutes for the first check.+ runTick();++ function stop() {+ clearInterval(interval);+ log.info('auto-claimer stopped');+ }++ if (signal) {+ signal.addEventListener('abort', stop, { once: true });+ }++ return stop;+}diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.jsindex 368df0b43..716f3d498 100644--- a/workers/agent-sniper/config.js+++ b/workers/agent-sniper/config.js@@ -127,5 +127,23 @@ export function loadConfig() {// How long a freshly-funded wallet stays under correlation watch for its// create instruction before it's dropped (ms).radarDeployWatchTtlMs: Math.max(30_000, num('SNIPER_RADAR_DEPLOY_WATCH_TTL_MS', 180_000)),+ // ── autonomous coin launcher ────────────────────────────────────────────+ // Runs a periodic check for enabled launcher configs and fires launches.+ // On by default when AGENT_JWT is set; disable with SNIPER_LAUNCHER=0.+ launcher: bool('SNIPER_LAUNCHER', !!process.env.AGENT_JWT),+ // How often to check for due launcher configs (ms).+ launcherPollMs: Math.max(30_000, num('SNIPER_LAUNCHER_POLL_MS', 60_000)),+ // ── creator auto-claim ──────────────────────────────────────────────────+ // Polls claimable creator fees on agent-launched coins and auto-claims them.+ // On by default when AGENT_JWT is set; disable with SNIPER_AUTO_CLAIM=0.+ autoClaim: bool('SNIPER_AUTO_CLAIM', !!process.env.AGENT_JWT),+ // How often to poll claimable fees (ms). Default 5 minutes.+ autoClaimPollMs: Math.max(60_000, num('SNIPER_AUTO_CLAIM_POLL_MS', 300_000)),+ // ── market maker ───────────────────────────────────────────────────────+ // Runs range-based market making on configured coins via Jito execution.+ // On by default; disable with SNIPER_MARKET_MAKER=0.+ marketMaker: bool('SNIPER_MARKET_MAKER', true),+ // Default rebalance interval when no per-config override (ms).+ marketMakerIntervalMs: Math.max(5_000, num('SNIPER_MM_INTERVAL_MS', 10_000)),};}diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.jsindex 4edaf4560..8d402a950 100644--- a/workers/agent-sniper/index.js+++ b/workers/agent-sniper/index.js@@ -32,6 +32,10 @@ import {alertShutdown,} from './alerts.js';import { screenPush } from './screen-push.js';+import { scoreAlpha } from './alpha-hunt.js';+import { startAutoClaimerWatch } from './auto-claimer.js';+import { startLauncherWatch } from './launcher.js';+import { startMarketMakerWatch } from './market-maker.js';const BOOT_AT = new Date().toISOString();@@ -153,25 +157,49 @@ async function main() {.catch(() => { rec.smart_money = null; });for (const strat of strategies) {- if ((strat.trigger || 'new_mint') !== 'intel_confirmed') continue;+ const trigger = strat.trigger || 'new_mint';if (strat.network !== cfg.network) continue;- Promise.all([getLearnedWeights(cfg.network), smartReady])- .then(([weights]) => {- const { pass, score, reasons } = scoreIntel(rec, strat, weights);++ if (trigger === 'intel_confirmed') {+ Promise.all([getLearnedWeights(cfg.network), smartReady])+ .then(([weights]) => {+ const { pass, score, reasons } = scoreIntel(rec, strat, weights);+ if (!pass) return;+ log.info('intel candidate', { agent: strat.agent_id, mint: rec.mint, symbol: rec.symbol, score, reasons });+ screenPush(`$${(rec.symbol || rec.mint.slice(0, 6)).toUpperCase()} intel score ${score} — BUYING`, 'trade');+ queue.push(async () => {+ const og = await oracleGate(rec.mint, cfg.network, strat);+ if (!og.pass) { log.info('oracle gate skip', { agent: strat.agent_id, mint: rec.mint, reason: og.reason }); return; }+ if (og.skipped) log.info('oracle unscored — proceeding', { agent: strat.agent_id, mint: rec.mint });+ await executeBuy({+ cfg, strat, throttle,+ mint: { mint: rec.mint, symbol: rec.symbol, name: rec.name, entry_trigger: 'intel_confirmed', trigger_ref: rec.mint },+ });+ });+ })+ .catch((err) => log.error('intel score failed', { mint: rec.mint, err: err?.message }));+ }++ if (trigger === 'alpha_hunt') {+ // alpha_hunt scores on the fully-enriched intel record (smart money,+ // organic score, quality, narrative) — no learned weights needed.+ smartReady.then(() => {+ const { pass, score, reasons } = scoreAlpha(rec, strat);if (!pass) return;- log.info('intel candidate', { agent: strat.agent_id, mint: rec.mint, symbol: rec.symbol, score, reasons });- screenPush(`$${(rec.symbol || rec.mint.slice(0, 6)).toUpperCase()} intel score ${score} — BUYING`, 'trade');+ log.info('alpha candidate', { agent: strat.agent_id, mint: rec.mint, symbol: rec.symbol, score, reasons });+ screenPush(`$${(rec.symbol || rec.mint.slice(0, 6)).toUpperCase()} alpha score ${score} — BUYING`, 'trade');queue.push(async () => {+ if (draining || cfg.globalKill) return;const og = await oracleGate(rec.mint, cfg.network, strat);if (!og.pass) { log.info('oracle gate skip', { agent: strat.agent_id, mint: rec.mint, reason: og.reason }); return; }if (og.skipped) log.info('oracle unscored — proceeding', { agent: strat.agent_id, mint: rec.mint });await executeBuy({cfg, strat, throttle,- mint: { mint: rec.mint, symbol: rec.symbol, name: rec.name, entry_trigger: 'intel_confirmed', trigger_ref: rec.mint },+ mint: { mint: rec.mint, symbol: rec.symbol, name: rec.name, entry_trigger: 'alpha_hunt', trigger_ref: rec.mint },});});- })- .catch((err) => log.error('intel score failed', { mint: rec.mint, err: err?.message }));+ }).catch((err) => log.error('alpha score failed', { mint: rec.mint, err: err?.message }));+ }}};stopIntel = startIntelWatcher({@@ -192,6 +220,27 @@ async function main() {cfg, queue, throttle, isHalted: () => draining || cfg.globalKill,});+ // Autonomous coin launcher — fires pump.fun launches on schedule.+ let stopLauncher = () => {};+ if (cfg.launcher) {+ stopLauncher = startLauncherWatch({ cfg, signal: abort.signal });+ log.info('launcher armed', { network: cfg.network, pollMs: cfg.launcherPollMs });+ }++ // Creator auto-claim — polls claimable fees on agent-launched coins.+ let stopAutoClaimer = () => {};+ if (cfg.autoClaim) {+ stopAutoClaimer = startAutoClaimerWatch({ cfg, signal: abort.signal });+ log.info('auto-claimer armed', { network: cfg.network, pollMs: cfg.autoClaimPollMs });+ }++ // Market maker — range-based liquidity provisioning with Jito execution.+ let stopMarketMaker = () => {};+ if (cfg.marketMaker) {+ stopMarketMaker = startMarketMakerWatch({ cfg, signal: abort.signal });+ log.info('market-maker armed', { network: cfg.network, intervalMs: cfg.marketMakerIntervalMs });+ }+// Pre-launch creator-wallet radar: watches proven creator + smart-money wallets// on-chain, detects launch precursors (funding a fresh deploy wallet / a pump// create) at block-0, and pre-arms a snipe through the SAME executor as the feed@@ -303,6 +352,9 @@ async function main() {try { radar?.stop?.(); } catch {}try { stopFeed?.(); } catch {}try { stopIntel?.(); } catch {}+ try { stopLauncher?.(); } catch {}+ try { stopAutoClaimer?.(); } catch {}+ try { stopMarketMaker?.(); } catch {}abort.abort();// Give in-flight buys a moment to settle (Neon HTTP is stateless — nothing// else to close).diff --git a/workers/agent-sniper/launcher.js b/workers/agent-sniper/launcher.jsnew file mode 100644index 000000000..ccbebd553--- /dev/null+++ b/workers/agent-sniper/launcher.js@@ -0,0 +1,256 @@+// agent-sniper — autonomous coin launcher.+//+// Periodically checks agent_launcher_configs for due launches and fires them+// via POST /api/pump?action=launch-agent. Runs as a timer inside the sniper+// worker, started from index.js when cfg.launcher is true.+//+// Name template tokens:+// {{timestamp}} — UNIX epoch seconds at launch time+// {{seq}} — launches_count + 1 (1-based sequence number)+//+// Simulate mode: logs the intended launch but does not POST or write DB rows.+//+// Per-launcher errors are isolated — one failed launch never blocks others.++import fetch from 'node-fetch';+import { sql } from '../../api/_lib/db.js';+import { log } from './log.js';+import { screenPush } from './screen-push.js';++const API_BASE_URL = process.env.API_BASE_URL || 'https://three.ws';+const AGENT_JWT = process.env.AGENT_JWT;++/**+ * Resolve a name template string against runtime values.+ *+ * @param {string|null} template+ * @param {number} seq launches_count + 1+ * @returns {string}+ */+function resolveName(template, seq) {+ if (!template) return `Coin #${seq}`;+ const ts = Math.floor(Date.now() / 1000);+ return template+ .replace(/\{\{timestamp\}\}/g, String(ts))+ .replace(/\{\{seq\}\}/g, String(seq));+}++/**+ * Fire a single coin launch via the platform API.+ *+ * @param {object} config Row from agent_launcher_configs+ * @param {string} name Resolved name string+ * @returns {Promise<{ok:boolean, mint:string, sig:string, name:string, symbol:string}>}+ */+async function postLaunch(config, name) {+ const body = {+ agentId: config.agent_id,+ network: config.network,+ name,+ symbol: config.symbol,+ description: config.description ?? null,+ image: config.image_url ?? null,+ twitter: config.twitter ?? null,+ telegram: config.telegram ?? null,+ website: config.website ?? null,+ initialBuySol: Number(config.initial_buy_sol) || 0,+ };++ const res = await fetch(`${API_BASE_URL}/api/pump?action=launch-agent`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${AGENT_JWT}`,+ },+ body: JSON.stringify(body),+ });++ const json = await res.json().catch(() => ({}));+ if (!res.ok || !json.ok) {+ throw new Error(json.error || json.message || `HTTP ${res.status}`);+ }+ return json;+}++/**+ * Record a successful launch in the DB and advance the launcher's schedule.+ *+ * @param {object} config Row from agent_launcher_configs+ * @param {{mint:string, sig:string, name:string, symbol:string}} result+ */+async function recordLaunch(config, result) {+ // Persist the new coin into agent_launched_coins.+ await sql`+ INSERT INTO agent_launched_coins (+ agent_id,+ mint,+ symbol,+ name,+ launch_sig,+ auto_claim_enabled,+ network+ ) VALUES (+ ${config.agent_id},+ ${result.mint},+ ${result.symbol},+ ${result.name},+ ${result.sig},+ ${config.auto_claim_enabled ?? false},+ ${config.network}+ )+ ON CONFLICT (mint) DO NOTHING+ `;++ // Advance the launcher state: bump count, record timestamp, compute next fire.+ if (config.interval_hours != null) {+ await sql`+ UPDATE agent_launcher_configs+ SET+ launches_count = launches_count + 1,+ last_launched_at = NOW(),+ next_launch_at = NOW() + (${config.interval_hours} * INTERVAL '1 hour')+ WHERE id = ${config.id}+ `;+ } else {+ // No recurring interval — fire once and park it (next_launch_at = NULL means+ // the WHERE clause won't pick it up again, and the enabled flag stays true+ // for manual inspection).+ await sql`+ UPDATE agent_launcher_configs+ SET+ launches_count = launches_count + 1,+ last_launched_at = NOW(),+ next_launch_at = NULL+ WHERE id = ${config.id}+ `;+ }+}++/**+ * Query all launcher configs that are due to fire on the given network.+ *+ * @param {string} network 'mainnet' | 'devnet'+ * @returns {Promise<object[]>}+ */+async function fetchDueLaunchers(network) {+ const rows = await sql`+ SELECT *+ FROM agent_launcher_configs+ WHERE+ enabled = true+ AND network = ${network}+ AND (next_launch_at IS NULL OR next_launch_at <= NOW())+ AND (max_launches IS NULL OR launches_count < max_launches)+ `;+ return rows;+}++/**+ * Process a single due launcher config. Errors are caught and logged without+ * propagating so a single failure never disrupts the scan loop.+ *+ * @param {object} config Row from agent_launcher_configs+ * @param {boolean} simulate When true, log the intended action but skip I/O+ */+async function runLauncher(config, simulate) {+ const seq = (Number(config.launches_count) || 0) + 1;+ const name = resolveName(config.name_template, seq);++ try {+ screenPush(`Launching $${config.symbol} on pump.fun...`, 'trade');+ log.info('launcher firing', {+ agentId: config.agent_id,+ symbol: config.symbol,+ name,+ seq,+ network: config.network,+ simulate,+ });++ if (simulate) {+ log.info('launcher simulate — skipping POST', {+ agentId: config.agent_id,+ symbol: config.symbol,+ name,+ });+ return;+ }++ const result = await postLaunch(config, name);++ log.info('launcher launched', {+ agentId: config.agent_id,+ symbol: result.symbol,+ mint: result.mint,+ sig: result.sig,+ });+ screenPush(`Launched $${result.symbol}: ${result.mint.slice(0, 8)}...`, 'trade');++ await recordLaunch(config, result);+ } catch (err) {+ log.error('launcher error', {+ agentId: config.agent_id,+ symbol: config.symbol,+ err: err?.message,+ });+ screenPush(`Launcher error for $${config.symbol}: ${err.message}`, 'activity');+ }+}++/**+ * Start the launcher watch loop. Checks for due launcher configs every+ * cfg.launcherPollMs milliseconds (minimum 60 seconds).+ *+ * @param {object} o+ * @param {object} o.cfg loadConfig() result+ * @param {AbortSignal} [o.signal] Optional abort signal for clean shutdown+ * @returns {() => void} stop function+ */+export function startLauncherWatch({ cfg, signal }) {+ if (!AGENT_JWT) {+ log.warn('launcher disabled — AGENT_JWT not set');+ return () => {};+ }++ let scanning = false;++ const tick = async () => {+ if (scanning) return;+ scanning = true;+ try {+ const configs = await fetchDueLaunchers(cfg.network);+ if (!configs.length) return;++ log.info('launcher tick — due launchers', { count: configs.length, network: cfg.network });++ // Run launchers sequentially to avoid a thundering-herd of simultaneous+ // launch POSTs. Each is isolated — an error in one does not short-circuit+ // the rest (runLauncher swallows its own errors).+ for (const config of configs) {+ await runLauncher(config, cfg.mode === 'simulate');+ }+ } catch (err) {+ log.error('launcher scan failed', { err: err?.message });+ } finally {+ scanning = false;+ }+ };++ const pollMs = Math.max(60_000, cfg.launcherPollMs ?? 60_000);+ const interval = setInterval(() => {+ tick().catch((err) => log.error('launcher tick crashed', { err: err?.message }));+ }, pollMs);+ if (interval.unref) interval.unref();++ // Honour an abort signal if provided (lets callers share the worker's+ // AbortController without needing the returned stop function).+ if (signal) {+ signal.addEventListener('abort', () => clearInterval(interval), { once: true });+ }++ log.info('launcher watch armed', { pollMs, network: cfg.network, mode: cfg.mode });++ return function stop() {+ clearInterval(interval);+ };+}diff --git a/workers/agent-sniper/market-maker.js b/workers/agent-sniper/market-maker.jsnew file mode 100644index 000000000..90e4e3481--- /dev/null+++ b/workers/agent-sniper/market-maker.js@@ -0,0 +1,543 @@+// agent-sniper — range-based market maker on pump.fun coins via Jito execution.+//+// For each enabled agent_market_maker_configs row the module:+// 1. Quotes current buy/sell prices every rebalance_interval_ms.+// 2. Computes the mid-price and compares against the configured spread band.+// 3. Buys when price is below the lower band (if inventory headroom allows).+// 4. Sells all inventory when price is above the upper band.+// 5. Persists every trade to agent_market_maker_trades and updates totals.+//+// In simulate mode quotes are resolved but no transaction is broadcast.++import { sql } from '../../api/_lib/db.js';+import { log } from './log.js';+import { getTradeCtx } from './trade-client.js';+import { loadAgentKeypair } from './keys.js';+import { screenPush } from './screen-push.js';++// ── constants ─────────────────────────────────────────────────────────────────++const SLIPPAGE_PCT = 1.0; // 1 % slippage for all MM trades+const DEFAULT_INTERVAL_MS = 10_000;+const CONFIRM_TIMEOUT_MS = 60_000;++// ── helpers ───────────────────────────────────────────────────────────────────++/** Wrap a raw value in the BN type carried by the trade context. */+function bn(ctx, v) {+ return new ctx.BN(BigInt(v).toString());+}++function lamportsToSol(l) {+ return Number(BigInt(l)) / 1e9;+}++// ── database helpers ──────────────────────────────────────────────────────────++/** Load all enabled market-maker configs (joined with agent metadata). */+async function loadEnabledConfigs(network) {+ return sql`+ SELECT+ c.id,+ c.agent_id,+ c.user_id,+ c.mint,+ c.symbol,+ c.network,+ c.enabled,+ c.spread_bps,+ c.min_profit_bps,+ c.order_size_sol,+ c.max_inventory_sol,+ c.rebalance_interval_ms,+ c.current_inventory_sol,+ c.avg_entry_price_lamports,+ c.total_volume_sol,+ c.total_pnl_sol,+ c.trade_count,+ c.last_tick_at,+ c.mev_tip_mode+ FROM agent_market_maker_configs c+ WHERE c.enabled = true+ AND c.network = ${network}+ `;+}++/** Insert a trade record and update config totals in a single round-trip. */+async function recordTrade(configId, trade) {+ const {+ side, // 'buy' | 'sell'+ priceSol, // per-token price at execution (SOL)+ sizeSol, // SOL size of this leg+ tokenAmount, // base token units (BigInt or number)+ sig, // tx signature or 'SIMULATED'+ pnlSol, // realised P&L this trade (0 for buys)+ newInventorySol,+ newAvgEntryLamports,+ newTotalVolumeSol,+ newTotalPnlSol,+ newTradeCount,+ } = trade;++ await sql`+ INSERT INTO agent_market_maker_trades+ (config_id, side, price_sol, size_sol, token_amount, sig, pnl_sol, created_at)+ VALUES+ (${configId}, ${side}, ${priceSol}, ${sizeSol}, ${String(tokenAmount)}, ${sig}, ${pnlSol}, now())+ `;++ await sql`+ UPDATE agent_market_maker_configs+ SET+ current_inventory_sol = ${newInventorySol},+ avg_entry_price_lamports = ${newAvgEntryLamports},+ total_volume_sol = ${newTotalVolumeSol},+ total_pnl_sol = ${newTotalPnlSol},+ trade_count = ${newTradeCount},+ last_tick_at = now()+ WHERE id = ${configId}+ `;+}++/** Touch last_tick_at so the ops dashboard knows the config is being visited. */+async function touchLastTick(configId) {+ await sql`+ UPDATE agent_market_maker_configs+ SET last_tick_at = now()+ WHERE id = ${configId}+ `.catch(() => {});+}++// ── band computation ──────────────────────────────────────────────────────────++/**+ * Given a config row return the buy/sell price thresholds in SOL per token.+ *+ * lower_band = avgEntry * (1 - spread_bps/2 / 10000) → buy signal+ * upper_band = avgEntry * (1 + spread_bps/2 / 10000) → sell signal+ *+ * When there is no inventory yet we don't have an avg_entry to anchor on; in+ * that case we return null bands to trigger a plain opportunistic buy.+ */+function computeBands(config) {+ const avgEntryLamports = Number(config.avg_entry_price_lamports ?? 0);+ const spreadBps = Number(config.spread_bps ?? 100);+ const halfSpread = spreadBps / 2 / 10_000;++ if (!avgEntryLamports) {+ // No position yet — no meaningful band.+ return { lowerBand: null, upperBand: null, avgEntrySol: null };+ }++ const avgEntrySol = avgEntryLamports / 1e9;+ return {+ lowerBand: avgEntrySol * (1 - halfSpread),+ upperBand: avgEntrySol * (1 + halfSpread),+ avgEntrySol,+ };+}++// ── per-config tick ───────────────────────────────────────────────────────────++async function processCoin(cfg, config) {+ const { mint, symbol, agent_id, user_id, network } = config;+ const orderSizeSol = Number(config.order_size_sol ?? 0.1);+ const maxInventorySol = Number(config.max_inventory_sol ?? 1.0);+ const currentInventorySol = Number(config.current_inventory_sol ?? 0);+ const mevTipMode = config.mev_tip_mode || 'auto';++ // ── 1. Get trade context ─────────────────────────────────────────────────+ let ctx;+ try {+ ctx = await getTradeCtx(network);+ } catch (err) {+ log.error('mm: getTradeCtx failed', { mint, symbol, err: err?.message });+ return;+ }++ // ── 2. Quote buy price (SOL → tokens) ───────────────────────────────────+ // We quote a single order_size_sol purchase to get the per-token buy price.+ let buyQuote;+ try {+ buyQuote = await ctx.client.quoteForBuy({+ mint,+ quoteAmount: bn(ctx, Math.round(orderSizeSol * 1e9)), // lamports+ slippagePct: SLIPPAGE_PCT,+ });+ } catch (err) {+ log.warn('mm: buy quote failed', { mint, symbol, err: err?.message });+ await touchLastTick(config.id);+ return;+ }++ // ── 3. Quote sell price (tokens → SOL) ──────────────────────────────────+ // Use the token amount we'd get from the buy quote to determine sell value.+ let sellQuote;+ const tokenAmountForQuote = BigInt(buyQuote.baseAmount ?? buyQuote.tokenAmount ?? 0);+ if (!tokenAmountForQuote) {+ log.warn('mm: buy quote returned zero token amount', { mint, symbol });+ await touchLastTick(config.id);+ return;+ }++ try {+ sellQuote = await ctx.client.quoteForSell({+ mint,+ baseAmount: bn(ctx, tokenAmountForQuote),+ slippagePct: SLIPPAGE_PCT,+ });+ } catch (err) {+ log.warn('mm: sell quote failed', { mint, symbol, err: err?.message });+ await touchLastTick(config.id);+ return;+ }++ // ── 4. Derive mid price ──────────────────────────────────────────────────+ const buyPriceLamports = Math.round((orderSizeSol * 1e9) / Number(tokenAmountForQuote));+ const sellOutLamports = Number(sellQuote.quoteAmount ?? sellQuote.solAmount ?? 0);+ const sellPriceLamports = sellOutLamports / Number(tokenAmountForQuote);+ const midPriceLamports = (buyPriceLamports + sellPriceLamports) / 2;+ const midPriceSol = midPriceLamports / 1e9;++ log.info('mm: price quote', {+ mint,+ symbol,+ buy_price_lamports: buyPriceLamports,+ sell_price_lamports: sellPriceLamports,+ mid_price_sol: midPriceSol,+ inventory_sol: currentInventorySol,+ });++ // ── 5. Compute bands and decide action ───────────────────────────────────+ const { lowerBand, upperBand, avgEntrySol } = computeBands(config);+ const spreadBps = Number(config.spread_bps ?? 100);+ const minProfitBps = Number(config.min_profit_bps ?? 50);++ // Determine whether to BUY or SELL.+ let action = null; // 'buy' | 'sell' | null++ const hasInventory = currentInventorySol > 0;+ const hasRoomForMore = currentInventorySol + orderSizeSol <= maxInventorySol;++ if (!hasInventory) {+ // No position yet: buy opportunistically. There's no band anchor so we+ // treat any price as an entry (guarded by max_inventory_sol).+ if (hasRoomForMore) {+ action = 'buy';+ }+ } else if (!hasRoomForMore) {+ // Inventory is full — only sell once the spread is captured.+ const sellThreshold = avgEntrySol * (1 + spreadBps / 10_000);+ if (midPriceSol >= sellThreshold) {+ action = 'sell';+ }+ } else {+ // Have partial inventory and room for more.+ if (upperBand !== null && midPriceSol >= upperBand) {+ action = 'sell';+ } else if (lowerBand !== null && midPriceSol <= lowerBand) {+ action = 'buy';+ } else if (lowerBand === null) {+ // Fallback: no avg yet (shouldn't happen when hasInventory, but guard).+ action = 'buy';+ }+ }++ // Check minimum-profit gate for sells when we have an entry.+ if (action === 'sell' && avgEntrySol) {+ const minSellPrice = avgEntrySol * (1 + minProfitBps / 10_000);+ if (midPriceSol < minSellPrice) {+ log.info('mm: sell blocked — below min_profit_bps threshold', {+ mint, symbol, mid_price_sol: midPriceSol, min_sell_price: minSellPrice,+ });+ action = null;+ }+ }++ if (!action) {+ log.info('mm: no action — price within band', {+ mint, symbol,+ mid_price_sol: midPriceSol,+ lower_band: lowerBand,+ upper_band: upperBand,+ });+ await touchLastTick(config.id);+ return;+ }++ // ── 6. Simulate mode: log and exit ──────────────────────────────────────+ if (cfg.mode !== 'live') {+ log.info(`mm: simulate — would ${action}`, {+ mint, symbol, action, mid_price_sol: midPriceSol,+ order_size_sol: orderSizeSol, inventory_sol: currentInventorySol,+ });+ await touchLastTick(config.id);+ return;+ }++ // ── 7. Load keypair ──────────────────────────────────────────────────────+ const agentKey = await loadAgentKeypair(agent_id, user_id, 'market_maker');+ if (!agentKey) {+ log.warn('mm: no keypair for agent', { agent_id, mint, symbol });+ return;+ }++ // ── 8. Execute trade ─────────────────────────────────────────────────────+ let sig = null;++ if (action === 'buy') {+ screenPush(`MM: Buying $${symbol} at ${midPriceSol.toFixed(6)} SOL/token`, 'trade');++ const solLamports = Math.round(orderSizeSol * 1e9);+ let instructions;+ try {+ instructions = await ctx.client.buildBuyInstructions({+ payer: agentKey.keypair.publicKey,+ mint,+ quoteAmount: bn(ctx, solLamports),+ slippagePct: SLIPPAGE_PCT,+ });+ } catch (err) {+ log.error('mm: buildBuyInstructions failed', { mint, symbol, err: err?.message });+ return;+ }++ try {+ sig = await import('./trade-client.js').then(({ signAndSend }) =>+ signAndSend(ctx, agentKey.keypair, instructions, CONFIRM_TIMEOUT_MS, {+ tipMode: mevTipMode,+ })+ );+ } catch (err) {+ log.error('mm: buy broadcast failed', { mint, symbol, err: err?.message });+ return;+ }++ // Update inventory.+ const tokensReceived = tokenAmountForQuote;+ const newInventorySol = currentInventorySol + orderSizeSol;++ // Compute new avg entry price (weighted average).+ const prevLamports = Number(config.avg_entry_price_lamports ?? 0);+ const newAvgEntry = prevLamports+ ? Math.round(+ (prevLamports * currentInventorySol + buyPriceLamports * orderSizeSol) /+ newInventorySol+ )+ : buyPriceLamports;++ await recordTrade(config.id, {+ side: 'buy',+ priceSol: midPriceSol,+ sizeSol: orderSizeSol,+ tokenAmount: tokensReceived,+ sig,+ pnlSol: 0,+ newInventorySol,+ newAvgEntryLamports: newAvgEntry,+ newTotalVolumeSol: Number(config.total_volume_sol ?? 0) + orderSizeSol,+ newTotalPnlSol: Number(config.total_pnl_sol ?? 0),+ newTradeCount: Number(config.trade_count ?? 0) + 1,+ }).catch((err) => log.warn('mm: recordTrade(buy) failed', { mint, err: err?.message }));++ log.trade('mm:buy', {+ agent: agent_id, mint, symbol,+ price_sol: midPriceSol, size_sol: orderSizeSol,+ inventory_sol: newInventorySol, sig,+ });++ } else {+ // action === 'sell'+ const pnlPct = avgEntrySol+ ? ((midPriceSol - avgEntrySol) / avgEntrySol) * 100+ : 0;++ screenPush(`MM: Selling $${symbol} — ${pnlPct.toFixed(1)}% spread captured`, 'trade');++ // Determine token inventory to sell: query the agent's on-chain token balance+ // as the authoritative source; fall back to an estimate from avg entry price.+ let tokenAmountToSell;+ try {+ const tokenAccts = await ctx.connection.getParsedTokenAccountsByOwner(+ agentKey.keypair.publicKey,+ { mint: new ctx.web3.PublicKey(mint) },+ );+ const balance = tokenAccts.value?.[0]?.account?.data?.parsed?.info?.tokenAmount?.amount;+ tokenAmountToSell = balance ? BigInt(balance) : BigInt(0);+ } catch (err) {+ log.warn('mm: token balance fetch failed — estimating from avg entry', { mint, symbol, err: err?.message });+ // Estimate: inventory_sol / avg_entry_sol → token units+ const avgPriceSol = Number(config.avg_entry_price_lamports ?? 0) / 1e9;+ tokenAmountToSell = avgPriceSol > 0+ ? BigInt(Math.round(currentInventorySol / avgPriceSol))+ : BigInt(0);+ }++ if (!tokenAmountToSell) {+ log.warn('mm: nothing to sell', { mint, symbol });+ await touchLastTick(config.id);+ return;+ }++ let instructions;+ try {+ instructions = await ctx.client.buildSellInstructions({+ payer: agentKey.keypair.publicKey,+ mint,+ baseAmount: bn(ctx, tokenAmountToSell),+ slippagePct: SLIPPAGE_PCT,+ });+ } catch (err) {+ log.error('mm: buildSellInstructions failed', { mint, symbol, err: err?.message });+ return;+ }++ try {+ sig = await import('./trade-client.js').then(({ signAndSend }) =>+ signAndSend(ctx, agentKey.keypair, instructions, CONFIRM_TIMEOUT_MS, {+ tipMode: mevTipMode,+ })+ );+ } catch (err) {+ log.error('mm: sell broadcast failed', { mint, symbol, err: err?.message });+ return;+ }++ // Realised P&L: proceeds - cost basis+ const proceedsLamports = sellOutLamports;+ const proceedsSol = lamportsToSol(proceedsLamports);+ const costBasisSol = avgEntrySol+ ? avgEntrySol * currentInventorySol+ : currentInventorySol;+ const realizedPnlSol = proceedsSol - costBasisSol;++ await recordTrade(config.id, {+ side: 'sell',+ priceSol: midPriceSol,+ sizeSol: proceedsSol,+ tokenAmount: tokenAmountToSell,+ sig,+ pnlSol: realizedPnlSol,+ newInventorySol: 0,+ newAvgEntryLamports: 0,+ newTotalVolumeSol: Number(config.total_volume_sol ?? 0) + proceedsSol,+ newTotalPnlSol: Number(config.total_pnl_sol ?? 0) + realizedPnlSol,+ newTradeCount: Number(config.trade_count ?? 0) + 1,+ }).catch((err) => log.warn('mm: recordTrade(sell) failed', { mint, err: err?.message }));++ log.trade('mm:sell', {+ agent: agent_id, mint, symbol,+ price_sol: midPriceSol, proceeds_sol: proceedsSol,+ pnl_sol: realizedPnlSol, pnl_pct: pnlPct, sig,+ });+ }+}++// ── shared tick ───────────────────────────────────────────────────────────────++async function tick(cfg) {+ let configs;+ try {+ configs = await loadEnabledConfigs(cfg.network);+ } catch (err) {+ log.error('mm: loadEnabledConfigs failed', { err: err?.message });+ return;+ }++ if (!configs.length) return;++ // Fan out — an error in one config must never kill the others.+ await Promise.allSettled(+ configs.map((config) =>+ processCoin(cfg, config).catch((err) =>+ log.error('mm: processCoin crashed', {+ mint: config.mint,+ symbol: config.symbol,+ err: err?.message,+ })+ )+ )+ );+}++// ── public API ────────────────────────────────────────────────────────────────++/**+ * Start the market-maker watch loop.+ *+ * Uses a single shared interval that fans out to all enabled configs on each+ * tick. The interval period is the minimum rebalance_interval_ms across all+ * enabled configs (or cfg.marketMakerIntervalMs / DEFAULT_INTERVAL_MS).+ *+ * @param {{ cfg: object, signal?: AbortSignal }} options+ * cfg — loadConfig() result (needs cfg.network, cfg.mode, cfg.marketMakerIntervalMs)+ * signal — optional AbortSignal; abort stops the loop+ * @returns {Function} stop — call to cancel the interval+ */+export function startMarketMakerWatch({ cfg, signal } = {}) {+ // Determine the initial poll interval. We'll start with the configured+ // default; once configs are loaded the interval adapts on each tick.+ const baseIntervalMs = cfg.marketMakerIntervalMs ?? DEFAULT_INTERVAL_MS;++ let running = false;+ let intervalHandle = null;++ async function runTick() {+ if (running) return;+ running = true;+ try {+ // Re-read enabled configs each tick to pick up interval changes.+ let configs = [];+ try {+ configs = await loadEnabledConfigs(cfg.network);+ } catch {+ // Already logged inside; proceed with empty set (no-op tick).+ }++ // Compute the tightest rebalance interval across live configs.+ const minIntervalMs = configs.length+ ? Math.min(...configs.map((c) => Number(c.rebalance_interval_ms || DEFAULT_INTERVAL_MS)))+ : baseIntervalMs;++ // Restart the interval if it drifted from the current tightest setting.+ if (minIntervalMs !== currentIntervalMs) {+ clearInterval(intervalHandle);+ currentIntervalMs = minIntervalMs;+ intervalHandle = setInterval(runTick, currentIntervalMs);+ if (intervalHandle.unref) intervalHandle.unref();+ log.info('mm: interval adjusted', { new_interval_ms: currentIntervalMs });+ }++ // Execute the actual tick (queries enabled configs again inside).+ await tick(cfg);+ } catch (err) {+ log.error('mm: tick crashed', { err: err?.message });+ } finally {+ running = false;+ }+ }++ let currentIntervalMs = baseIntervalMs;+ intervalHandle = setInterval(runTick, currentIntervalMs);+ if (intervalHandle.unref) intervalHandle.unref();++ log.info('mm: market-maker armed', {+ network: cfg.network,+ mode: cfg.mode,+ interval_ms: currentIntervalMs,+ });++ // Fire immediately so the first tick doesn't wait a full interval.+ runTick();++ function stop() {+ clearInterval(intervalHandle);+ log.info('mm: market-maker stopped');+ }++ if (signal) {+ signal.addEventListener('abort', stop, { once: true });+ }++ return stop;+}