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(mcp): give agents portfolio, launch sniper, alert rule and duel tools, with launch-match alerts delivered to the owner
nirholas77fa9b3e2ccc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 88d527829..41f0ec53a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,10 +6,17 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-10-10+- **Agent Mail** (`/agent-mail`): Each agent's own email inbox on agents.three.ws: read threads, send and reply through a quote you approve, set a recipient allowlist and a daily send cap, and route incoming mail to your approvals queue or an automation run.- **Approvals** (`/approvals`): Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.- **Docs · Local agent runtime for the desktop app** (`/docs/desktop-local-runtime`): Run agents, paper and live strategies, limit orders and automations on your own machine: keys in the OS keychain, native approvals with the same payload hash as the web flow, a tray menu, and a mascot that shows agent state.- **Docs · Specialist teams** (`/docs/teams`): How specialist teams work: the four roles and their permission ceilings, the shared findings board and its live stream, the cite-or-research rule the Trader follows, launch prep you sign yourself, and the full API.+- **Docs · Web Domains** (`/docs/domains`): Search, price, check and register web domains from an agent or the dashboard through Google Cloud Domains, paid from credits behind a quote and an explicit confirm, with the daily registrar quota, one-year terms, auto-renew and connecting a domain to an agent's public page.+- **Docs: Agent Mail** (`/docs/agent-mail`): Give an agent a real email address on agents.three.ws: quote-then-confirm sends, the recipient allowlist and daily cap, why received mail is data and never instructions, rules that turn incoming mail into agent runs, and the REST and MCP reference.+- **Domains** (`/domains`): Search live registrar availability, see the exact yearly price, register a web domain from credits and serve an agent's public page on it.- **Specialist Teams: four agents, one board** (`/teams`): Assemble a squad of four 3D agents (a Researcher, an Entry scout, a Trader and a Launcher) under one spend policy. They post to a shared live findings board, the Trader only acts on research it can cite, and the Launcher prepares plans you sign yourself.+- **Agents can find and register web domains**: Search any name across popular extensions with live availability and the exact yearly price, check a single name, and register it from your credits after a quote and an explicit yes. Coin pages now suggest available domains for the project name, and a registered domain can serve your agent's public page. Registration is for one year, renews at the same price, and has no markup. (`/domains`) `[feature]`+- **Agents can read their portfolio, run a launch sniper, set alerts and challenge each other to duels**: Fifteen new tools for Claude or any MCP client, plus a portfolio API at /api/v1/agents/:id/portfolio. An agent can read its own valued Solana portfolio with cost basis and risk flags, its net-worth history (now recorded hourly) and its profit and loss broken down by where it came from. It can check its launch sniper, and arm it only after you have seen the exact budget, per-trade size, limits and network in a preview and said yes; turning it off is one call. It can subscribe to signal feeds in paper mode, and create, list and delete pump alert rules, including a new kind that fires on any new launch matching your filters: a name pattern, a market cap band, a minimum safety score, the creator's track record and risk flags to avoid. Alerts reach you on the bell, by push, and in any Telegram or Discord chat you have paired. Agents can also challenge another agent to a points-only duel, accept one, read a duel and browse the open markets, with every result counted on the duels leaderboard. (`/docs/mcp`) `[feature, sdk]`+- **Agents get their own email inbox**: Every agent can now have an email address on agents.three.ws, with an inbox right on its profile (the Mail button). It can send, read, reply in thread, search and delete, from the web, the API, or any MCP client. Nothing is created or sent until you have seen the exact recipients and message and said yes. You can limit an agent to a list of recipients and a daily number of sends, and only you, signed in, can change those limits. Mail an agent receives is always treated as information, never as orders: hidden characters are shown, links are disabled, and the agent is told not to follow anything inside it. Rules let you turn incoming mail into work, such as "when mail arrives from this sender, summarize it", either right away or after you approve. (`/agent-mail`) `[feature, security]`- **Approve or deny your agent's requests from Telegram and Discord**: When your agent asks before a transfer or a trade, the request now lands in your paired Telegram or Discord chat with the full confirmation table (recipient, amount, asset, chain, risk notes and deadline) and Approve and Deny buttons. Each button is signed for that exact request, your chat and your account, so a changed request, an expired one, a copied button or someone else in a group chat can never trigger it, and pressing Approve twice runs the action once. The chat now also answers /approvals to list everything waiting, /positions for open positions and their live value, /pause to stop one agent and /kill to stop every agent and deny every pending request. A chat can stop your agents but never unfreeze them; that is done on the web. Forwarded messages are never treated as instructions. (`/approvals`) `[feature, security]`- **Approve your agents' payments from a notification**: Set any agent spend rule to Ask me and the agent now waits for your yes instead of failing. You get a notification with the recipient, amount, token and network spelled out, and can approve or deny right from it, from email, or from the new Approvals inbox. Approving runs exactly what you were shown, once; denying or letting it expire runs nothing. You can also create auto-approve rules for small swaps and transfers to addresses you have paid before, and revoke them any time. (`/approvals`) `[feature]`- **Coin logos, agent art and IPFS images load again**: Several public IPFS gateways started refusing image and metadata requests from websites this month, which left coin logos, the 3D coin face, agent cards and on-chain agent art blank or broken across the site. Every page and API now reads IPFS content through gateways that still answer, races them so the fastest wins, and quietly rewrites links that point at the refusing gateways, so art that was published long ago still shows up. Images from a host that no longer serves them now fall back to a clean placeholder instead of a broken-image icon. (`/launches`) `[fix, improvement]`@@ -18,6 +25,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Run your agents on your own desktop**: The three.ws desktop app can now run agents, strategies, limit orders and automations on your machine. Signing keys stay in your operating system keychain, paper strategies keep working with no account or cloud connection, and every live trade waits for your approval in a native window that shows the exact recipient, amount, asset and chain. A tray menu lists each agent with pause, kill and review, and the mascot shows when an agent is working, waiting for you or in trouble. (`/docs/desktop-local-runtime`) `[feature]`- **Set up your AI client with one command, and check it with doctor**: Run npx three-ws --claude (or --cursor, --codex, --vscode, --windsurf) and the CLI signs you in, connects three.ws and verifies it, with no prompts. Keys never land in your client's config file, and running it twice changes nothing. New installers at three.ws/cli/install and three.ws/cli/claude come with a checksum and a signature so you can read and verify them before you run them. npx three-ws doctor finds a broken config, an expired sign-in or an unreachable server and tells you the fix. agent status and team show your agents, wallets and teams from the terminal. (`/docs/cli`) `[feature, improvement]`- **Specialist teams: four agents that research before they trade**: Assemble a squad of four 3D agents in one click: a Researcher that vets a token and posts a scored verdict, an Entry scout that checks fresh launches against your entry gates, a Trader that quotes, simulates or trades inside one spend policy, and a Launcher that prepares a launch plan for you to sign. They share a live findings board. The Trader only acts on research it can cite, reuses a fresh verdict instead of redoing it, and every refusal is posted with its reason. Only the Trader can ever sign, and only a live trade you confirm. (`/teams`) `[feature]`+- **Strategies now research every coin and ask before they buy**: Trading strategies can now check a coin before spending anything: minimum holders, how much the largest holder owns, liquidity, the rug and honeypot safety score, whether the creator can still mint or freeze, and the creator's track record. A coin that fails a check, or whose data cannot be read, is skipped and the decision log on your agent says exactly which check stopped it. You can also cap price impact per buy. Strategies now ask for your approval before each buy by default, with the amount, coin and risk notes on the card, and existing strategies were switched to ask mode too; flip one to Auto once you trust it. The strategy builder edits everything with sliders, toggles or raw JSON, turns a plain-English description into settings, shows a live count of recent launches your settings would have bought, and backtests with the checks applied. (`/strategies`) `[feature]`+- **The 3D agent demos show their agent again**: Every page in the agent interaction lab had stopped drawing its 3D character, so the demos showed only text and buttons. They load again: she climbs the title, catches your cursor, rides the scroll, falls asleep on the headline and the rest. The wrecking-ball entrance was also rebuilt so she really swings in on the rope and hits the button, instead of hovering beside it with the rope pointing the wrong way. (`/demos/agents`) `[fix]`+- **Token ceilings, a spend page, USDC deposits and a way out of the free tier**: Every agent can now carry hourly, daily and per-run token ceilings next to its dollar caps. A ceiling is checked before the model is called; hitting one pauses the agent, tells you, and gives you Resume and Extend once. The new /spend page shows what each agent spends by day, by model and by tool, projects the month end, and alerts at 50, 80 and 100 percent of any cap. Credits can be topped up with USDC at a fixed rate alongside SOL and $THREE, the deposit page lists every accepted asset and its rate from live config, and paying in $THREE earns whatever bonus the owner has set. When the free tier runs out, the error now carries your choices: wait for the reset, top up, bring your own key, or resend the same request with paid_fallback: true to bill it to credits in one step. (`/spend`) `[feature]`## 2026-10-09diff --git a/CLAUDE.md b/CLAUDE.mdindex d766fa231..2fe9cfb8a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -315,7 +315,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).- 3D: Three.js with glTF/GLB.- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (126 as of 2026-10-09, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (129 as of 2026-10-10, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.diff --git a/STRUCTURE.md b/STRUCTURE.mdindex c1e116a49..6139e4135 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -335,6 +335,7 @@ bottom.| Syndicates (copy-trade as a team) | Board [pages/syndicates.html](pages/syndicates.html) + [src/syndicates.js](src/syndicates.js) `→ /syndicates`, detail [pages/syndicate.html](pages/syndicate.html) + [src/syndicate.js](src/syndicate.js) `→ /syndicates/:slug`, shared [src/syndicate-shared.js](src/syndicate-shared.js) + [src/syndicates.css](src/syndicates.css), trader-profile widget [src/trader-syndicates.js](src/trader-syndicates.js); model [api/_lib/syndicates.js](api/_lib/syndicates.js), guarded follow path [api/_lib/copy-subscribe.js](api/_lib/copy-subscribe.js), endpoints [api/syndicates/](api/syndicates/), migration [api/_lib/migrations/20260929120000_copy_syndicates.sql](api/_lib/migrations/20260929120000_copy_syndicates.sql), tests [tests/syndicates.test.js](tests/syndicates.test.js) | Live (non-custodial) | Roadmap 917 item 12.7. A named team (flag, motto, color) following one to three copyable leaders. Joining creates ordinary `copy_subscriptions` through the same guarded path as a single follow (self-copy refusal, copyable bar, the member's own caps); an existing subscription is linked, never overwritten; a join is all or nothing; leaving stops only what the join created. One team per copier per network. Group P&L, the curve and the rival standing are computed on read from members' real `copy_executions` inside their membership window, priced like the performance fee. The empty board lists today's copyable leaders with whole records. Linked from `/trader/:id`, `/dashboard/copy` and `/play/arena`. Doc: [docs/syndicates.md](docs/syndicates.md). || Daily trading quests | [pages/quests.html](pages/quests.html) + [src/quests.js](src/quests.js) `→ /quests`; model [api/_lib/trading-quests.js](api/_lib/trading-quests.js), disarmed $THREE payout [api/_lib/quest-rewards.js](api/_lib/quest-rewards.js), endpoints [api/quests/](api/quests/), trade proof recorded in [api/pump/[action].js](api/pump/[action].js) buy/sell-confirm, migration [api/_lib/migrations/20260929121000_trading_quests.sql](api/_lib/migrations/20260929121000_trading_quests.sql), tests [tests/trading-quests.test.js](tests/trading-quests.test.js), [tests/quest-rewards.test.js](tests/quest-rewards.test.js) | Live (XP + badges); $THREE rewards disarmed | Roadmap 917 item 12.11. Five daily quests scored from proof: verified trades from a linked wallet or owned-agent Co-Pilot, forks, first ghost-copies per leader, acted copy intents, an owned agent's profitable live close. Three a day is a daily clear. XP is an insert-only ledger; badges go to `user_badges`. The $THREE daily-clear reward is complete and tested but inert until `TRADING_QUEST_THREE_REWARDS=on` plus an amount and payout key are set (owner gate). Doc: [docs/trading-quests.md](docs/trading-quests.md). || Trader duels (points-only skill predictions) | Board [pages/duels.html](pages/duels.html) + [src/duels.js](src/duels.js) `→ /duels`, detail [pages/duel.html](pages/duel.html) + [src/duel.js](src/duel.js) `→ /duels/:id`, shared [src/duels-shared.js](src/duels-shared.js) + [src/duels.css](src/duels.css), trader-profile widget [src/trader-duels.js](src/trader-duels.js); model [api/_lib/trader-duels.js](api/_lib/trader-duels.js), endpoints [api/duels/](api/duels/), cron [api/cron/duels-tick.js](api/cron/duels-tick.js), migration [api/_lib/migrations/20260930150000_trader_duels.sql](api/_lib/migrations/20260930150000_trader_duels.sql), tests [tests/trader-duels.test.js](tests/trader-duels.test.js) | Live (points only) | Roadmap 917 item 12.6, built free to play: no token, deposit, escrow or payout, and points have no cash value. The cron opens 24h and week duels for neighbouring traders from the rivalry engine, locks calls at window start, and resolves from `agent_sniper_positions` + `agent_strategy_positions` through `computeTraderMetrics`. Ties, empty windows and private/deleted traders void and refund; an idle trader counts as flat. A correct call pays 2x and 15 XP into `trading_quest_completions`; daily 100-point allowance, monthly season board, four badges. One call per user per duel, no calls on your own agent, overdraft and double payout refused by constraints. Linked from `/trader/:id`, `/trade-rooms`, `/quests` and `/play/arena`. Doc: [docs/trader-duels.md](docs/trader-duels.md). |+| Agent portfolio, launch sniper, alerts and duels (MCP + REST) | MCP tools [api/_mcpagent/portfolio-tools.js](api/_mcpagent/portfolio-tools.js), [api/_mcpagent/sniper-alert-tools.js](api/_mcpagent/sniper-alert-tools.js), [api/_mcpagent/duels-tools.js](api/_mcpagent/duels-tools.js); REST [api/v1/agents/[id]/portfolio/index.js](api/v1/agents/[id]/portfolio/index.js) and [api/v1/agents/[id]/portfolio/[...path].js](api/v1/agents/[id]/portfolio/[...path].js) over [api/_lib/portfolio-routes.js](api/_lib/portfolio-routes.js); stores [api/_lib/portfolio-history.js](api/_lib/portfolio-history.js), [api/_lib/sniper-control.js](api/_lib/sniper-control.js), [api/_lib/signal-subscription-control.js](api/_lib/signal-subscription-control.js), [api/_lib/pump-alert-rules.js](api/_lib/pump-alert-rules.js), [api/_lib/duel-challenges.js](api/_lib/duel-challenges.js); cron [api/cron/agent-portfolio-snapshots.js](api/cron/agent-portfolio-snapshots.js) | Live | Agent-callable portfolio (valuation, net-worth history, P&L by source), launch sniper control behind a preview-and-confirm spend gate, signal subscriptions, pump alert rules including `launch_match` (creator history, market cap band, name pattern, safety score) delivered to the owner by bell, push and paired Telegram/Discord chats, and agent-to-agent duel challenges on the free-play points board. Docs: [docs/mcp.md](docs/mcp.md#agent-wallet-portfolio-launch-sniper-alerts-and-duels), [docs/api-reference.md](docs/api-reference.md#agent-portfolio). || Copy Coach (guided first copy) | [pages/copy-coach.html](pages/copy-coach.html) + [src/copy-coach.js](src/copy-coach.js) + [src/copy-coach.css](src/copy-coach.css) `→ /copy-coach`, model [api/_lib/copy-coach.js](api/_lib/copy-coach.js), endpoint [api/copy/coach.js](api/copy/coach.js), starter caps `STARTER_CAPS` in [api/_lib/copy-engine.js](api/_lib/copy-engine.js), tests [tests/copy-coach.test.js](tests/copy-coach.test.js) | Live | Roadmap 917 prompt 14.3. Four steps for a cautious first-timer: a real signed 25%+ win shown beside the same agent's full 30-day record (a losing record is said plainly), a ghost copy of a leader with fake money ([ghost-copy](api/_lib/ghost-copy.js)), one tiny real copy behind a confirmation card, then what comes next. The real copy goes through `POST /api/copy/subscriptions` with `starter: true`, where the server refuses anything past 0.05 SOL per trade, 0.2 SOL a day, 2 open copies, a 25% drawdown pause, the safety check and an explicit `risk_ack`; it is non-custodial and spends nothing until the user signs each copied trade. The side panel answers questions through the LLM chain from a fact sheet built from real rows (ghost replay recomputed server side), validated against promises, invented numbers, other coins and links, with a deterministic guide as the fallback. Linked from the nav (next to Copy Trading) and [/ghost-copy](pages/ghost-copy.html). Doc: [docs/copy-coach.md](docs/copy-coach.md). || Sentiment Scout (momentum with receipts) | Scout tab and drawer section on [pages/coin-intel.html](pages/coin-intel.html) via [src/coin-intel-scout.js](src/coin-intel-scout.js) `→ /coin-intel?tab=scout`, model [api/_lib/sentiment-scout.js](api/_lib/sentiment-scout.js), X search [api/_lib/x-search.js](api/_lib/x-search.js), LLM notes [api/_lib/scout-notes.js](api/_lib/scout-notes.js), endpoint [api/pump/sentiment-scout.js](api/pump/sentiment-scout.js), MCP `sentiment_scout` in [api/_mcp/tools/trader.js](api/_mcp/tools/trader.js), table `sentiment_scout_reads` ([migration](api/_lib/migrations/20260929120000_sentiment_scout_reads.sql)), tests [tests/sentiment-scout.test.js](tests/sentiment-scout.test.js) | Live | Roadmap 917 prompt 14.2. Ranks the last hour of Coin Intelligence launches by early volume and buyer percentiles, screens out bundles and dev dumps, enriches the shortlist with the live curve, X posts quoting the exact contract address, pump.fun callouts and paid x402 reads, and returns a 0-100 score with its parts, evidence lines that each carry a source URL, a timestamp and (for social or paid claims) the on-chain facts they were checked against, and one worst-first caution (including one-account X chatter). Unreadable sources are listed, never estimated. An LLM-written two-sentence read per candidate is validated against the evidence. Board candidates are recorded so [trade receipts](api/_lib/trade-receipt.js) show a Scout flag that preceded an entry, and the Scout's calls are graded against `pump_coin_outcomes`. LLM-judged sniper strategies opt in with `llm_scout_context` ([workers/agent-sniper/llm-judge.js](workers/agent-sniper/llm-judge.js)). Doc: [docs/sentiment-scout.md](docs/sentiment-scout.md). || Trader Wrapped (season recap) | [pages/wrapped.html](pages/wrapped.html) + [src/wrapped.js](src/wrapped.js) `→ /wrapped`, deck builder [api/_lib/wrapped.js](api/_lib/wrapped.js), endpoint [api/pump/wrapped.js](api/pump/wrapped.js), social card [api/wrapped-og.js](api/wrapped-og.js), share page [api/wrapped-share.js](api/wrapped-share.js) `→ /wrapped/<agent_id>/share`, tests [tests/wrapped.test.js](tests/wrapped.test.js) | Live (read-only, zero custody) | The artifact the trading stack was missing: one image and one link that say what a season was. Eight slides cut server-side from a trader agent's closed on-chain round-trips (scoreboard, best trade, worst trade, the coin that carried it, rhythm, rank against the field with the nearest rival, receipt), swipeable on touch and keyboard-driven on desktop, with the current slide in the URL hash so a share link lands on the slide the sharer was reading. Arithmetic is delegated wholesale to `computeTraderMetrics` in [api/_lib/trader-stats.js](api/_lib/trader-stats.js), the same truth layer the leaderboard and trader profile use, so a recap can never disagree with the profile it links to. Deliberately unflattering: the worst-trade slide is not optional, the scoreboard carries an explicit verdict and colors a red season red, per-coin ranking includes coins that lost money, self-launched coins stay excluded from every superlative, the rank always prints the size of the real field beside it, and under 3 settled round-trips the page says there is no season rather than drawing a chart out of noise. Needs no account, wallet, signature or funded signer. Converts through [Fork](src/fork-trade.js) on the best-trade slide and links onward to the verified profile, [Ghost-copy](pages/ghost-copy.html) and the rival's own wrapped. Doc: [docs/trader-wrapped.md](docs/trader-wrapped.md). |diff --git a/api/_lib/alert-delivery.js b/api/_lib/alert-delivery.jsindex 29f7b9f90..cb592439f 100644--- a/api/_lib/alert-delivery.js+++ b/api/_lib/alert-delivery.js@@ -6,6 +6,14 @@// returns a per-channel result the runner persists to pump_alert_deliveries so// the dashboard can surface "webhook failed" instead of silently dropping it.//+// The in-app channel is the owner's own notification fan-out: it goes through+// insertNotification (api/_lib/notify.js), so one alert reaches the bell, Web+// Push, the iOS app and every chat the owner paired, each gated by the+// preference center's "alerts" category. Its logged detail names what was+// reached ("bell, push x2, telegram x1"). The rule's explicit telegram_chat is+// skipped when it is one of those paired chats, so nobody gets the same alert+// twice in one chat.+//// Webhooks are signed with the rule's per-rule secret using the Standard// Webhooks format (matching api/_lib/webhook-dispatch.js) and pinned to a// validated public address (SSRF guard). Telegram uses the platform bot and@@ -15,6 +23,7 @@ import { sql } from './db.js';import { hmacSha256, randomToken } from './crypto.js';import { validatePublicUrl, resolvePublicHost, pinnedAgent, SsrfError } from './ssrf.js';import { formatAlertSummary } from './pump-alert-eval.js';+import { insertNotification } from './notify.js';import { fetchUpstream } from './upstream-fetch.js';const WEBHOOK_TIMEOUT_MS = 8_000;@@ -33,24 +42,65 @@ const skipped = () => /** @type {ChannelResult} */ ({ attempted: false, ok: fals* @returns {Promise<{ in_app: ChannelResult, webhook: ChannelResult, telegram: ChannelResult }>}*/export async function deliverAlert(rule, payload) {- const [inApp, webhook, telegram] = await Promise.all([- rule.deliver_in_app ? deliverInApp(rule, payload) : skipped(),+ const [owner, webhook] = await Promise.all([+ rule.deliver_in_app ? deliverToOwner(rule, payload) : null,rule.webhook_url ? deliverWebhook(rule, payload) : skipped(),- rule.telegram_chat ? deliverTelegram(rule, payload) : skipped(),]);- return { in_app: inApp, webhook, telegram };+ let telegram = skipped();+ if (rule.telegram_chat) {+ telegram = owner?.telegramQueued && (await isPairedNotifyChat(rule.user_id, rule.telegram_chat))+ ? { attempted: true, ok: true, detail: 'sent_via_paired_chat' }+ : await deliverTelegram(rule, payload);+ }+ return { in_app: owner ? owner.result : skipped(), webhook, telegram };+}++/** The in-app link for an alert: the coin page when the alert names a mint. */+export function alertLink(payload) {+ if (payload.link) return payload.link;+ if (payload.mint) return `/coin/${encodeURIComponent(payload.mint)}`;+ return '/pump-dashboard';}-/** Insert the in-app notification row (type 'pump_alert'). */-async function deliverInApp(rule, payload) {+/**+ * Notify the rule's owner through the platform fan-out (bell, push, APNs,+ * paired chats). ok when at least one channel was reached; a user who muted+ * every channel for alerts gets ok=false with detail 'muted_by_preferences'.+ */+async function deliverToOwner(rule, payload) {try {- await sql`- insert into user_notifications (user_id, type, payload)- values (${rule.user_id}, 'pump_alert', ${JSON.stringify({ ...payload, summary: formatAlertSummary(payload) })}::jsonb)- `;- return { attempted: true, ok: true, detail: null };+ const res = await insertNotification(rule.user_id, 'pump_alert', {+ ...payload,+ summary: formatAlertSummary(payload),+ link: alertLink(payload),+ });+ const reached = [];+ if (res?.id) reached.push('bell');+ for (const [channel, count] of Object.entries(res?.delivered || {})) {+ if (count > 0) reached.push(`${channel} x${count}`);+ }+ const telegramQueued = Number(res?.delivered?.telegram || 0) > 0;+ const result = reached.length+ ? { attempted: true, ok: true, detail: reached.join(', ') }+ : { attempted: true, ok: false, detail: res?.in_app === false && res?.id == null && res?.delivered ? 'muted_by_preferences' : 'not_delivered' };+ return { result: /** @type {ChannelResult} */ (result), telegramQueued };} catch (e) {- return { attempted: true, ok: false, detail: errMsg(e) };+ return { result: { attempted: true, ok: false, detail: errMsg(e) }, telegramQueued: false };+ }+}++/** Is this chat one the owner paired with notifications on? */+async function isPairedNotifyChat(userId, chatId) {+ try {+ const [row] = await sql`+ select 1 as ok from gateway_links+ where user_id = ${userId} and platform = 'telegram' and chat_id = ${String(chatId)}+ and revoked_at is null and notify = true+ limit 1+ `;+ return !!row;+ } catch {+ return false;}}diff --git a/api/_lib/duel-challenges.js b/api/_lib/duel-challenges.jsnew file mode 100644index 000000000..203589557--- /dev/null+++ b/api/_lib/duel-challenges.js@@ -0,0 +1,395 @@+// Agent duel challenges: one agent owner calls out another agent to a duel.+// ---------------------------------------------------------------------------+// The rivalry engine (api/_lib/trader-duels.js) only ever pairs traders that sit+// next to each other on the 30-day board. A challenge lets an owner pick the+// opponent instead:+//+// challenge the owner of agent A challenges agent B (someone else's public+// agent) to a duel over the next day or week window. B's owner is+// notified through insertNotification (bell, push, paired chats).+// respond B's owner accepts or declines; A's owner can withdraw while it is+// pending. Accepting opens a regular duel_markets row for the next+// window, tagged context.source = 'challenge', so the rivalry+// generator leaves that window's own pairings alone. When the pair+// already has a duel in that window the challenge links to it.+// expire a challenge nobody answered within 48 hours expires+// (/api/cron/duels-tick).+// resolve the existing duel engine: realized P&L inside the window decides+// it, and anyone who owns neither trader can call it for points.+//+// Points only, like every duel: nothing here moves a token or touches a wallet.+// challengeLeaderboard ranks agents by their record in challenge duels.++import { sql } from './db.js';+import { insertNotification } from './notify.js';+import { nextWindow, getDuel, duelPhase } from './trader-duels.js';+import { isUuid } from './validate.js';++export const CHALLENGE_NETWORK = 'mainnet';+export const CHALLENGE_WINDOWS = Object.freeze(['day', 'week']);+export const CHALLENGE_STATUSES = Object.freeze(['pending', 'accepted', 'declined', 'expired', 'cancelled']);+export const CHALLENGE_TTL_HOURS = 48;+export const MAX_PENDING_PER_USER = 20;+export const MAX_MESSAGE = 280;++const PG_UNIQUE = '23505';+const iso = (v) => (v == null ? null : new Date(v).toISOString());+const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);++/** A designed refusal: a stable code, a sentence for the caller, an HTTP-ish status. */+export class DuelChallengeError extends Error {+ constructor(code, message, status = 400) {+ super(message);+ this.code = code;+ this.status = status;+ }+}++async function agentsById(ids) {+ const list = ids.filter(isUuid);+ if (!list.length) return new Map();+ const rows = await sql`+ select id, user_id, name, is_public, deleted_at+ from agent_identities where id = any(${list}::uuid[])+ `;+ return new Map(rows.map((r) => [r.id, r]));+}++const isAvailable = (a) => !!a && a.deleted_at == null && a.is_public !== false;++/** The public shape of one challenge row, from the viewer's side. PURE. */+export function challengeView(row, viewerId = null) {+ const role = viewerId && row.challenger_user === viewerId ? 'challenger'+ : viewerId && row.challenged_user === viewerId ? 'challenged'+ : null;+ return {+ id: row.id,+ status: row.status,+ network: row.network,+ window_kind: row.window_kind,+ challenger: { agent_id: row.challenger_agent, name: row.challenger_name || null },+ challenged: { agent_id: row.challenged_agent, name: row.challenged_name || null },+ message: row.message || null,+ market_id: row.market_id || null,+ duel_url: row.market_id ? `/duels/${row.market_id}` : null,+ expires_at: iso(row.expires_at),+ created_at: iso(row.created_at),+ responded_at: iso(row.responded_at),+ your_role: role,+ can_respond: role === 'challenged' && row.status === 'pending',+ can_cancel: role === 'challenger' && row.status === 'pending',+ };+}++const challengeColumns = () => sql`+ c.id, c.network, c.window_kind, c.challenger_agent, c.challenger_user, c.challenged_agent,+ c.challenged_user, c.message, c.status, c.market_id, c.expires_at, c.created_at, c.responded_at,+ ca.name as challenger_name, cb.name as challenged_name+`;++async function loadChallenge(id) {+ if (!isUuid(id)) return null;+ const [row] = await sql`+ select ${challengeColumns()}+ from agent_duel_challenges c+ left join agent_identities ca on ca.id = c.challenger_agent+ left join agent_identities cb on cb.id = c.challenged_agent+ where c.id = ${id}+ `;+ return row || null;+}++/** Challenge another owner's public agent to a duel over the next window. */+export async function createChallenge({ userId, challengerAgentId, challengedAgentId, windowKind = 'day', message = null, now = Date.now() }) {+ if (!CHALLENGE_WINDOWS.includes(windowKind)) throw new DuelChallengeError('invalid_window', 'window must be day or week.');+ if (!isUuid(challengerAgentId) || !isUuid(challengedAgentId)) throw new DuelChallengeError('invalid_agent', 'Both agent ids must be UUIDs.');+ if (challengerAgentId === challengedAgentId) throw new DuelChallengeError('same_agent', 'An agent cannot duel itself.');+ const text = message == null ? null : String(message).trim().slice(0, MAX_MESSAGE) || null;++ const agents = await agentsById([challengerAgentId, challengedAgentId]);+ const me = agents.get(challengerAgentId);+ const them = agents.get(challengedAgentId);+ if (!me || me.deleted_at != null || me.user_id !== userId) {+ throw new DuelChallengeError('not_your_agent', 'You can only challenge with an agent you own.', 403);+ }+ if (me.is_public === false) {+ throw new DuelChallengeError('agent_private', `${me.name} is private. Duels are public, so make it public before challenging.`, 409);+ }+ if (!isAvailable(them)) throw new DuelChallengeError('opponent_unavailable', 'That agent does not exist or is not public.', 404);+ if (them.user_id === userId) {+ throw new DuelChallengeError('own_opponent', 'Both agents are yours. Challenge an agent someone else owns.', 409);+ }++ const w = nextWindow(windowKind, now);+ const [existing] = await sql`+ select id from duel_markets+ where network = ${CHALLENGE_NETWORK} and window_kind = ${windowKind} and window_start = ${iso(w.start)}+ and least(agent_a, agent_b) = least(${challengerAgentId}::uuid, ${challengedAgentId}::uuid)+ and greatest(agent_a, agent_b) = greatest(${challengerAgentId}::uuid, ${challengedAgentId}::uuid)+ `;+ if (existing) {+ throw new DuelChallengeError('already_paired', `These two already duel in that window: /duels/${existing.id}`, 409);+ }+ const [reverse] = await sql`+ select id from agent_duel_challenges+ where status = 'pending' and expires_at > now() and network = ${CHALLENGE_NETWORK} and window_kind = ${windowKind}+ and challenger_agent = ${challengedAgentId} and challenged_agent = ${challengerAgentId}+ `;+ if (reverse) {+ throw new DuelChallengeError('already_challenged_you', `${them.name} already challenged ${me.name} for that window. Accept challenge ${reverse.id} instead.`, 409);+ }+ const [{ c: pending }] = await sql`+ select count(*)::int as c from agent_duel_challenges where challenger_user = ${userId} and status = 'pending' and expires_at > now()+ `;+ if (pending >= MAX_PENDING_PER_USER) {+ throw new DuelChallengeError('too_many_pending', `You have ${pending} unanswered challenges out. Wait for answers or withdraw some first.`, 409);+ }++ let row;+ try {+ [row] = await sql`+ insert into agent_duel_challenges+ (network, window_kind, challenger_agent, challenger_user, challenged_agent, challenged_user, message, expires_at)+ values (${CHALLENGE_NETWORK}, ${windowKind}, ${challengerAgentId}, ${userId}, ${challengedAgentId}, ${them.user_id},+ ${text}, now() + make_interval(hours => ${CHALLENGE_TTL_HOURS}))+ returning id+ `;+ } catch (err) {+ if (err?.code === PG_UNIQUE) throw new DuelChallengeError('already_pending', `${me.name} already has a pending ${windowKind} challenge out to ${them.name}.`, 409);+ throw err;+ }++ const window = windowKind === 'day' ? 'tomorrow (UTC)' : 'next week';+ const delivered = await insertNotification(them.user_id, 'duel_challenge', {+ summary: `${me.name} challenged your agent ${them.name} to a duel ${window}${text ? `: "${text}"` : ''}`,+ challenge_id: row.id,+ challenger: me.name,+ challenged: them.name,+ window_kind: windowKind,+ link: '/duels',+ });+ const view = challengeView(await loadChallenge(row.id), userId);+ return { ...view, notified: { bell: !!delivered?.in_app, ...(delivered?.delivered || {}) } };+}++/**+ * Answer a pending challenge. `accept` and `decline` are for the challenged+ * agent's owner, `cancel` for the challenger's. Accepting opens the duel.+ */+export async function respondChallenge({ userId, challengeId, response, now = Date.now() }) {+ if (!['accept', 'decline', 'cancel'].includes(response)) throw new DuelChallengeError('invalid_response', 'response must be accept, decline or cancel.');+ const row = await loadChallenge(challengeId);+ if (!row || (row.challenger_user !== userId && row.challenged_user !== userId)) {+ throw new DuelChallengeError('not_found', 'No challenge with that id involves your agents.', 404);+ }+ if (row.status !== 'pending') {+ throw new DuelChallengeError('not_pending', `This challenge is already ${row.status}.`, 409);+ }+ if (new Date(row.expires_at).getTime() <= now) {+ await expireChallenges();+ throw new DuelChallengeError('expired', 'This challenge expired before it was answered.', 409);+ }+ if (response === 'cancel' && row.challenger_user !== userId) {+ throw new DuelChallengeError('not_challenger', 'Only the challenger can withdraw a challenge. Decline it instead.', 403);+ }+ if (response !== 'cancel' && row.challenged_user !== userId) {+ throw new DuelChallengeError('not_challenged', 'Only the challenged agent\'s owner can accept or decline. You can cancel it.', 403);+ }++ if (response !== 'accept') {+ const status = response === 'cancel' ? 'cancelled' : 'declined';+ const [done] = await sql`+ update agent_duel_challenges set status = ${status}, responded_at = now()+ where id = ${row.id} and status = 'pending' returning id+ `;+ if (!done) throw new DuelChallengeError('not_pending', 'This challenge was answered a moment ago.', 409);+ if (status === 'declined') {+ await insertNotification(row.challenger_user, 'duel_challenge', {+ summary: `${row.challenged_name} declined ${row.challenger_name}'s duel challenge`,+ challenge_id: row.id,+ link: '/duels',+ });+ }+ return { challenge: challengeView(await loadChallenge(row.id), userId), duel: null };+ }++ const agents = await agentsById([row.challenger_agent, row.challenged_agent]);+ const a = agents.get(row.challenger_agent);+ const b = agents.get(row.challenged_agent);+ if (!isAvailable(a) || !isAvailable(b)) {+ throw new DuelChallengeError('agent_unavailable', 'One of these agents is no longer public, so the duel cannot open.', 409);+ }++ const w = nextWindow(row.window_kind, now);+ const context = {+ source: 'challenge',+ challenge_id: row.id,+ headline: `${a.name} challenged ${b.name}`,+ subline: row.message || `A ${row.window_kind === 'day' ? '24-hour' : 'week-long'} head-to-head on realized P&L, called by the crowd for points.`,+ a: { agent_id: a.id, name: a.name },+ b: { agent_id: b.id, name: b.name },+ };+ // Claim the challenge and open the duel in one statement, so two accepts+ // racing each other open at most one market.+ const [claimed] = await sql`+ with c as (+ update agent_duel_challenges set status = 'accepted', responded_at = now()+ where id = ${row.id} and status = 'pending' and expires_at > now()+ returning id+ ),+ m as (+ insert into duel_markets (network, window_kind, window_start, window_end, agent_a, agent_b, agent_a_name, agent_b_name, context)+ select ${row.network}, ${row.window_kind}, ${iso(w.start)}, ${iso(w.end)}, ${a.id}::uuid, ${b.id}::uuid,+ ${a.name}, ${b.name}, ${JSON.stringify(context)}::jsonb+ from c+ on conflict do nothing+ returning id+ )+ select (select id from c) as challenge_id, (select id from m) as market_id+ `;+ if (!claimed?.challenge_id) throw new DuelChallengeError('not_pending', 'This challenge was answered a moment ago.', 409);++ let marketId = claimed.market_id;+ if (!marketId) {+ // The rivalry engine already paired them for this window: the challenge is that duel.+ const [same] = await sql`+ select id from duel_markets+ where network = ${row.network} and window_kind = ${row.window_kind} and window_start = ${iso(w.start)}+ and least(agent_a, agent_b) = least(${a.id}::uuid, ${b.id}::uuid)+ and greatest(agent_a, agent_b) = greatest(${a.id}::uuid, ${b.id}::uuid)+ `;+ marketId = same?.id || null;+ }+ await sql`update agent_duel_challenges set market_id = ${marketId} where id = ${row.id}`;++ await insertNotification(row.challenger_user, 'duel_challenge', {+ summary: `${b.name} accepted ${a.name}'s duel challenge. The window opens ${new Date(w.start).toUTCString()}.`,+ challenge_id: row.id,+ link: marketId ? `/duels/${marketId}` : '/duels',+ });+ const duel = marketId ? await getDuel(marketId, { userId, now }) : null;+ return { challenge: challengeView(await loadChallenge(row.id), userId), duel };+}++/** One challenge, visible to either side. Includes the duel once accepted. */+export async function getChallenge({ userId, challengeId, now = Date.now() }) {+ const row = await loadChallenge(challengeId);+ if (!row || (row.challenger_user !== userId && row.challenged_user !== userId)) return null;+ const view = challengeView(row, userId);+ const duel = row.market_id ? await getDuel(row.market_id, { userId, now }) : null;+ return { challenge: view, duel };+}++/** The caller's challenges. direction: incoming, outgoing, all. */+export async function listChallenges({ userId, direction = 'all', status = null, limit = 25 }) {+ const dirSql = direction === 'incoming' ? sql`c.challenged_user = ${userId}`+ : direction === 'outgoing' ? sql`c.challenger_user = ${userId}`+ : sql`(c.challenged_user = ${userId} or c.challenger_user = ${userId})`;+ const statusSql = status && CHALLENGE_STATUSES.includes(status) ? sql`and c.status = ${status}` : sql``;+ const rows = await sql`+ select ${challengeColumns()}+ from agent_duel_challenges c+ left join agent_identities ca on ca.id = c.challenger_agent+ left join agent_identities cb on cb.id = c.challenged_agent+ where ${dirSql} ${statusSql}+ order by (c.status = 'pending') desc, c.created_at desc+ limit ${Math.max(1, Math.min(100, n(limit) || 25))}+ `;+ return rows.map((r) => challengeView(r, userId));+}++/** Flip every pending challenge past its deadline to expired. Returns the count. */+export async function expireChallenges() {+ const rows = await sql`+ update agent_duel_challenges set status = 'expired', responded_at = now()+ where status = 'pending' and expires_at <= now()+ returning id+ `;+ return rows.length;+}++/**+ * Rank agents by their record in challenge duels: wins, losses and voids over+ * every settled duel that came from a challenge, with the realized P&L each+ * booked inside those windows. Ties break on fewer losses, then more decided.+ */+export async function challengeLeaderboard({ limit = 25, agentId = null } = {}) {+ const rows = await sql`+ with sides as (+ select m.agent_a as agent_id, m.status, m.winner = 'a' as won, m.winner = 'b' as lost,+ (m.result -> 'a' ->> 'pnl_sol')::numeric as pnl_sol, m.resolved_at+ from duel_markets m+ where m.network = ${CHALLENGE_NETWORK} and m.context ->> 'source' = 'challenge'+ and m.status in ('resolved','void') and m.agent_a is not null+ union all+ select m.agent_b, m.status, m.winner = 'b', m.winner = 'a',+ (m.result -> 'b' ->> 'pnl_sol')::numeric, m.resolved_at+ from duel_markets m+ where m.network = ${CHALLENGE_NETWORK} and m.context ->> 'source' = 'challenge'+ and m.status in ('resolved','void') and m.agent_b is not null+ ),+ agg as (+ select agent_id,+ count(*) filter (where won)::int as wins,+ count(*) filter (where lost)::int as losses,+ count(*) filter (where status = 'void')::int as voids,+ coalesce(sum(pnl_sol), 0)::float8 as pnl_sol,+ max(resolved_at) as last_duel_at+ from sides group by agent_id+ ),+ ranked as (+ select agg.*, rank() over (order by wins desc, losses asc, (wins + losses) desc) as rank+ from agg join agent_identities a on a.id = agg.agent_id+ where a.deleted_at is null and a.is_public is not false+ )+ select r.*, a.name from ranked r join agent_identities a on a.id = r.agent_id+ where r.rank <= ${limit} or r.agent_id = ${agentId}+ order by r.rank asc, a.name asc+ `;+ const [counts] = await sql`+ select count(*) filter (where status = 'pending' and expires_at > now())::int as pending,+ count(*) filter (where status = 'accepted')::int as accepted+ from agent_duel_challenges where network = ${CHALLENGE_NETWORK}+ `;+ const shape = (r) => ({+ rank: n(r.rank),+ agent_id: r.agent_id,+ name: r.name,+ trader: `/trader/${r.agent_id}`,+ wins: n(r.wins),+ losses: n(r.losses),+ voids: n(r.voids),+ decided: n(r.wins) + n(r.losses),+ win_rate: n(r.wins) + n(r.losses) ? n(r.wins) / (n(r.wins) + n(r.losses)) : null,+ realized_pnl_sol: Number(n(r.pnl_sol).toFixed(6)),+ last_duel_at: iso(r.last_duel_at),+ });+ const all = rows.map(shape);+ return {+ leaders: all.filter((r) => r.rank <= limit),+ agent: agentId ? all.find((r) => r.agent_id === agentId) || null : undefined,+ challenges: { pending: n(counts?.pending), accepted: n(counts?.accepted) },+ };+}++/** Challenge duels that are open or live, newest window first. */+export async function listChallengeDuels({ limit = 25, now = Date.now() } = {}) {+ const rows = await sql`+ select id, window_kind, window_start, window_end, status, agent_a_name, agent_b_name, winner, context+ from duel_markets+ where network = ${CHALLENGE_NETWORK} and context ->> 'source' = 'challenge'+ order by (status = 'open') desc, window_start desc+ limit ${limit}+ `;+ return rows.map((m) => ({+ id: m.id,+ url: `/duels/${m.id}`,+ label: `${m.agent_a_name} vs ${m.agent_b_name}`,+ window_kind: m.window_kind,+ window_start: iso(m.window_start),+ window_end: iso(m.window_end),+ phase: duelPhase(m, now),+ winner: m.winner ? (m.winner === 'a' ? m.agent_a_name : m.agent_b_name) : null,+ challenge_id: m.context?.challenge_id || null,+ }));+}diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsindex c344d7bcd..e3dc222c7 100644--- a/api/_lib/notify-prefs.js+++ b/api/_lib/notify-prefs.js@@ -130,6 +130,8 @@ const TYPE_CATEGORY = {dm_received: 'social',agent_review: 'social',quest_complete: 'social',+ // Another owner challenged your agent to a duel, or answered your challenge.+ duel_challenge: 'social',irl_interaction: 'irl',irl_reply: 'irl',@@ -311,6 +313,7 @@ const PUSH_COPY = {dm_received: (p) => ['New message 💬', p.actor ? `${p.actor} sent you a message` : 'You have a new message'],agent_review: (p) => ['New review ⭐', p.actor ? `${p.actor} reviewed your agent` : 'Your agent received a review'],quest_complete: (p) => ['Quest complete 🏆', p.mission ? `You finished "${p.mission}"${p.gold ? ` — earned ${p.gold} gold` : ''}` : 'You finished a quest'],+ duel_challenge: (p) => ['Duel challenge ⚔️', p.summary || 'Another agent challenged yours to a trading duel'],royalty_paid: (p) => ['Royalty earned 💰', p.usd ? `A fork paid you $${Number(p.usd).toFixed(3)} in royalties` : (p.sol ? `A fork paid you ${Number(p.sol).toFixed(4)} SOL in royalties` : 'A fork of your avatar paid you a royalty')],irl_interaction: (p) => ['Met in person 📍', p.message ? `“${p.message}”` : 'Someone interacted with your agent in person'],irl_reply: (p) => ['Agent replied 💬', p.message ? `“${p.message}”` : 'An agent replied to your message'],diff --git a/api/_lib/portfolio-history.js b/api/_lib/portfolio-history.jsnew file mode 100644index 000000000..fa1a3c136--- /dev/null+++ b/api/_lib/portfolio-history.js@@ -0,0 +1,285 @@+/**+ * Agent portfolio history: the time series behind get_balance_history and+ * /api/v1/agents/:id/portfolio/history, and the P&L digest behind get_pnl.+ *+ * Two real sources, never interpolated:+ *+ * 1. agent_portfolio_snapshots: a full valuation (net worth in SOL and USD,+ * realized and unrealized P&L) recorded whenever getPortfolio runs for an+ * agent through the agent tools, the v1 route, or the hourly+ * /api/cron/agent-portfolio-snapshots sweep. Throttled to one row per agent+ * per network per SNAPSHOT_MIN_GAP_MS so a polling client cannot flood it.+ * 2. The realized trade ledger (agent_sniper_positions plus+ * agent_strategy_positions via fetchTraderPositions): every closed trade+ * carries its own closed_at and realized P&L, so the realized curve is+ * exact back to the agent's first trade even before any snapshot existed.+ *+ * Pure helpers (realizedCurve, pnlDigest, bucketSnapshots) are exported for tests.+ */++import { sql } from './db.js';+import { getPortfolio } from './portfolio.js';+import { cachedSolUsd, fetchTraderPositions } from './trader-stats.js';++export const SNAPSHOT_MIN_GAP_MS = 15 * 60 * 1000;+const LAMPORTS_PER_SOL = 1e9;+const DAY_MS = 86_400_000;++const num = (v) => (v == null ? null : Number.isFinite(Number(v)) ? Number(v) : null);+const round = (n, dp = 6) => (n == null || !Number.isFinite(n) ? null : Number(n.toFixed(dp)));++/** A typed error the tool and route layers turn into a designed refusal. */+export class PortfolioAccessError extends Error {+ constructor(code, message, status) {+ super(message);+ this.code = code;+ this.status = status;+ }+}++/**+ * Load an agent and confirm the caller owns it. The portfolio exposes the+ * custody ledger, so every surface built on this module is owner-only.+ */+export async function loadPortfolioAgent(agentId, userId) {+ if (!/^[0-9a-f-]{36}$/i.test(String(agentId || ''))) throw new PortfolioAccessError('invalid_agent_id', 'agent_id must be a UUID.', 400);+ const [row] = await sql`select id, user_id, name, meta from agent_identities where id = ${agentId} and deleted_at is null limit 1`;+ if (!row) throw new PortfolioAccessError('not_found', 'No agent with that id.', 404);+ if (row.user_id !== userId) throw new PortfolioAccessError('forbidden', 'That agent belongs to another account.', 403);+ return row;+}++/**+ * Record one snapshot of a getPortfolio result, unless the agent already has+ * one on this network inside the throttle gap. Returns true when a row landed.+ */+export async function recordPortfolioSnapshot(portfolio, { source = 'read' } = {}) {+ if (!portfolio?.agent?.id || !portfolio.net_worth || portfolio.net_worth.sol == null) return false;+ const cutoff = new Date(Date.now() - SNAPSHOT_MIN_GAP_MS).toISOString();+ const nw = portfolio.net_worth;+ const rows = await sql`+ insert into agent_portfolio_snapshots+ (agent_id, network, net_worth_sol, net_worth_usd, sol_usd, realized_pnl_sol, unrealized_pnl_sol, holdings_count, source)+ select ${portfolio.agent.id}, ${portfolio.network}, ${nw.sol}, ${nw.usd ?? null}, ${portfolio.sol_usd ?? null},+ ${nw.realized_pnl_sol ?? null}, ${nw.unrealized_pnl_sol ?? null}, ${(portfolio.holdings || []).length}, ${source}+ where not exists (+ select 1 from agent_portfolio_snapshots+ where agent_id = ${portfolio.agent.id} and network = ${portfolio.network} and captured_at > ${cutoff}+ )+ returning id+ `;+ return rows.length > 0;+}++/** Value an agent now and record the snapshot. Snapshot failure never fails the read. */+export async function portfolioWithSnapshot({ agentId, network, source = 'read' }) {+ const portfolio = await getPortfolio({ agentId, network });+ if (portfolio) {+ await recordPortfolioSnapshot(portfolio, { source }).catch((e) => {+ console.warn('[portfolio-history] snapshot write failed', e?.message);+ });+ }+ return portfolio;+}++/**+ * Cumulative realized P&L per UTC day from closed trades, oldest first. Days+ * without a close are omitted (the curve is flat across them). Only days at or+ * after sinceMs are returned, but the running total includes everything before,+ * so the first point is the true cumulative figure on that day.+ */+export function realizedCurve(positions, { sinceMs = 0, solUsd = null } = {}) {+ const closed = (positions || [])+ .filter((p) => p.status === 'closed' && p.closed_at && p.realized_pnl_lamports != null)+ .map((p) => ({ t: new Date(p.closed_at).getTime(), lamports: Number(p.realized_pnl_lamports) }))+ .filter((p) => Number.isFinite(p.t) && Number.isFinite(p.lamports))+ .sort((a, b) => a.t - b.t);+ const byDay = new Map();+ let running = 0;+ for (const p of closed) {+ running += p.lamports;+ const day = Math.floor(p.t / DAY_MS) * DAY_MS;+ const entry = byDay.get(day) || { trades: 0 };+ entry.trades += 1;+ entry.cumulative = running;+ byDay.set(day, entry);+ }+ const out = [];+ for (const [day, e] of byDay) {+ if (day + DAY_MS <= sinceMs) continue;+ const sol = e.cumulative / LAMPORTS_PER_SOL;+ out.push({+ date: new Date(day).toISOString().slice(0, 10),+ cumulative_realized_sol: round(sol),+ cumulative_realized_usd: solUsd != null ? round(sol * solUsd, 2) : null,+ trades_closed: e.trades,+ });+ }+ return out;+}++/**+ * Thin a snapshot series to at most maxPoints, keeping the first and last rows+ * exact, so a long history stays a sensible payload for a model.+ */+export function bucketSnapshots(rows, maxPoints = 120) {+ if (rows.length <= maxPoints) return rows;+ const out = [];+ const stride = (rows.length - 1) / (maxPoints - 1);+ for (let i = 0; i < maxPoints - 1; i++) out.push(rows[Math.round(i * stride)]);+ out.push(rows[rows.length - 1]);+ return out;+}++function summarizeSeries(points) {+ if (!points.length) return null;+ const first = points[0];+ const last = points[points.length - 1];+ let peak = -Infinity;+ let maxDd = 0;+ for (const p of points) {+ if (p.net_worth_sol > peak) peak = p.net_worth_sol;+ if (peak > 0) maxDd = Math.max(maxDd, (peak - p.net_worth_sol) / peak);+ }+ const changeSol = last.net_worth_sol - first.net_worth_sol;+ return {+ from: first.t,+ to: last.t,+ start_sol: first.net_worth_sol,+ end_sol: last.net_worth_sol,+ change_sol: round(changeSol),+ change_pct: first.net_worth_sol > 0 ? round((changeSol / first.net_worth_sol) * 100, 2) : null,+ start_usd: first.net_worth_usd,+ end_usd: last.net_worth_usd,+ change_usd: first.net_worth_usd != null && last.net_worth_usd != null ? round(last.net_worth_usd - first.net_worth_usd, 2) : null,+ peak_sol: round(peak),+ max_drawdown_pct: round(maxDd * 100, 2),+ };+}++/**+ * Net-worth history for one agent on one network over the last `days`, plus the+ * exact realized-P&L curve from the trade ledger.+ */+export async function getBalanceHistory({ agentId, network = 'mainnet', days = 30, maxPoints = 120, now = Date.now() }) {+ const net = network === 'devnet' ? 'devnet' : 'mainnet';+ const span = Math.min(Math.max(Math.trunc(Number(days) || 30), 1), 365);+ const since = new Date(now - span * DAY_MS).toISOString();+ const [rows, positions] = await Promise.all([+ sql`+ select captured_at, net_worth_sol, net_worth_usd, sol_usd, realized_pnl_sol, unrealized_pnl_sol, holdings_count, source+ from agent_portfolio_snapshots+ where agent_id = ${agentId} and network = ${net} and captured_at >= ${since}+ order by captured_at asc+ limit 5000+ `,+ fetchTraderPositions({ agentId, network: net, window: 'all', now }).catch(() => []),+ ]);+ const points = bucketSnapshots(rows.map((r) => ({+ t: new Date(r.captured_at).toISOString(),+ net_worth_sol: num(r.net_worth_sol),+ net_worth_usd: num(r.net_worth_usd),+ sol_usd: num(r.sol_usd),+ realized_pnl_sol: num(r.realized_pnl_sol),+ unrealized_pnl_sol: num(r.unrealized_pnl_sol),+ holdings: r.holdings_count,+ source: r.source,+ })), Math.min(Math.max(Math.trunc(Number(maxPoints) || 120), 2), 500));+ const lastUsd = await cachedSolUsd();+ return {+ agent_id: agentId,+ network: net,+ days: span,+ snapshot_count: rows.length,+ points,+ summary: summarizeSeries(points),+ realized_curve: realizedCurve(positions, { sinceMs: now - span * DAY_MS, solUsd: lastUsd }),+ note: rows.length+ ? 'Net-worth points are real valuations recorded at each timestamp; the realized curve is exact from closed trades.'+ : 'No valuations recorded in this window yet. One is recorded now on every portfolio read and hourly for active agents; the realized curve is exact from closed trades.',+ };+}++/**+ * The P&L view of a portfolio: totals, attribution by source, trading+ * performance, and the best and worst open positions. Pure over getPortfolio's+ * output.+ */+export function pnlDigest(portfolio) {+ const nw = portfolio.net_worth || {};+ const m = portfolio.metrics || {};+ const solUsd = portfolio.sol_usd;+ const usd = (sol) => (sol != null && solUsd != null ? round(sol * solUsd, 2) : null);+ const unrealized = nw.unrealized_pnl_sol ?? null;+ const realized = nw.realized_pnl_sol ?? null;+ const total = realized != null || unrealized != null ? round((realized || 0) + (unrealized || 0)) : null;+ const open = (portfolio.holdings || [])+ .filter((h) => h.unrealized_sol != null)+ .map((h) => ({+ mint: h.mint,+ symbol: h.symbol || null,+ name: h.name || null,+ cost_basis_sol: h.cost_basis_sol,+ unrealized_sol: h.unrealized_sol,+ unrealized_pct: h.unrealized_pct,+ }))+ .sort((a, b) => b.unrealized_sol - a.unrealized_sol);+ return {+ agent: portfolio.agent,+ network: portfolio.network,+ sol_usd: solUsd,+ t: portfolio.t,+ totals: {+ realized_sol: realized,+ realized_usd: nw.realized_pnl_usd ?? usd(realized),+ unrealized_sol: unrealized,+ unrealized_usd: usd(unrealized),+ total_sol: total,+ total_usd: usd(total),+ net_worth_sol: nw.sol ?? null,+ net_worth_usd: nw.usd ?? null,+ },+ by_source: portfolio.attribution || [],+ performance: {+ closed_trades: m.closed_count ?? 0,+ open_trades: m.open_count ?? 0,+ win_rate: m.win_rate ?? null,+ roi_pct: m.roi_pct ?? null,+ profit_factor: m.profit_factor ?? null,+ avg_win_pct: m.avg_win_pct ?? null,+ avg_loss_pct: m.avg_loss_pct ?? null,+ best_pnl_pct: m.best_pnl_pct ?? null,+ worst_pnl_pct: m.worst_pnl_pct ?? null,+ max_drawdown_pct: m.max_drawdown_pct ?? null,+ sharpe: m.sharpe ?? null,+ },+ top_winners: open.filter((h) => h.unrealized_sol > 0).slice(0, 5),+ top_losers: open.filter((h) => h.unrealized_sol < 0).slice(-5).reverse(),+ basis_note: portfolio.basis_note,+ };+}++/**+ * The agents worth a scheduled valuation: wallet-bearing agents that traded,+ * moved funds, or had a portfolio read in the last week, least recently+ * snapshotted first, so a capped sweep rotates through all of them.+ */+export async function agentsDueForSnapshot({ limit = 40 } = {}) {+ const since = new Date(Date.now() - 7 * DAY_MS).toISOString();+ return sql`+ with active as (+ select agent_id, network from agent_custody_events where created_at >= ${since}+ union+ select agent_id, network from agent_sniper_positions where coalesce(closed_at, opened_at) >= ${since}+ union+ select agent_id, network from agent_portfolio_snapshots where captured_at >= ${since} and source = 'read'+ )+ select a.agent_id, a.network, max(s.captured_at) as last_snapshot+ from active a+ join agent_identities i on i.id = a.agent_id and i.deleted_at is null and i.meta ? 'solana_address'+ left join agent_portfolio_snapshots s on s.agent_id = a.agent_id and s.network = a.network+ group by a.agent_id, a.network+ order by max(s.captured_at) asc nulls first+ limit ${limit}+ `;+}diff --git a/api/_lib/portfolio-routes.js b/api/_lib/portfolio-routes.jsnew file mode 100644index 000000000..c428b74a4--- /dev/null+++ b/api/_lib/portfolio-routes.js@@ -0,0 +1,57 @@+// Route table for an agent's portfolio, in the v1 API contract+// (api/_lib/agents-v1/http.js: one envelope, per-route auth and scopes,+// rate limits). Mounted at /api/v1/agents/:id/portfolio by+// api/v1/agents/[id]/portfolio/index.js and [...path].js.+//+// GET /agents/:id/portfolio live valuation (records a snapshot)+// GET /agents/:id/portfolio/history net-worth snapshots + realized curve+// GET /agents/:id/portfolio/pnl realized/unrealized P&L by source+//+// Owner-only and wallet:read, because attribution reads the custody ledger.+// The same modules back the MCP tools get_portfolio, get_balance_history and+// get_pnl (api/_mcpagent/portfolio-tools.js).++import { apiError, requireUuid, intParam } from './agents-v1/http.js';+import { loadPortfolioAgent, portfolioWithSnapshot, getBalanceHistory, pnlDigest } from './portfolio-history.js';++function networkOf(query) {+ const n = query.network || 'mainnet';+ if (n !== 'mainnet' && n !== 'devnet') throw apiError(400, 'invalid_network', 'network must be mainnet or devnet.');+ return n;+}++async function ownedAgent(params, principal) {+ const agentId = requireUuid(params.id, 'agent');+ await loadPortfolioAgent(agentId, principal.userId);+ return agentId;+}++async function valued(params, principal, query) {+ const agentId = await ownedAgent(params, principal);+ const p = await portfolioWithSnapshot({ agentId, network: networkOf(query) });+ if (!p) throw apiError(404, 'not_found', 'No agent with that id.');+ return p;+}++export const portfolioRoutes = [+ {+ method: 'GET', path: '/agents/:id/portfolio', name: 'portfolio.get', auth: 'required', scope: 'wallet:read',+ handler: ({ params, principal, query }) => valued(params, principal, query),+ },+ {+ method: 'GET', path: '/agents/:id/portfolio/history', name: 'portfolio.history', auth: 'required', scope: 'wallet:read',+ handler: async ({ params, principal, query }) => {+ const agentId = await ownedAgent(params, principal);+ return getBalanceHistory({+ agentId,+ network: networkOf(query),+ days: intParam(query.days, { name: 'days', min: 1, max: 365, fallback: 30 }),+ maxPoints: intParam(query.max_points, { name: 'max_points', min: 2, max: 500, fallback: 120 }),+ });+ },+ },+ {+ method: 'GET', path: '/agents/:id/portfolio/pnl', name: 'portfolio.pnl', auth: 'required', scope: 'wallet:read',+ handler: async ({ params, principal, query }) => pnlDigest(await valued(params, principal, query)),+ },+];diff --git a/api/_lib/pump-alert-eval.js b/api/_lib/pump-alert-eval.jsindex 5fd231b30..8e7077085 100644--- a/api/_lib/pump-alert-eval.js+++ b/api/_lib/pump-alert-eval.js@@ -10,7 +10,7 @@* @typedef {Object} AlertRule* @property {string} id* @property {string} user_id- * @property {'graduation'|'price_above'|'price_below'|'whale_buy'|'new_mint'|'market_price'} kind+ * @property {'graduation'|'price_above'|'price_below'|'whale_buy'|'new_mint'|'market_price'|'launch_match'} kind* @property {string|null} [target_mint]* @property {string|null} [target_agent]* @property {string|null} [target_market] prediction market id (market_price)@@ -24,6 +24,21 @@* @property {number} cooldown_seconds* @property {boolean} enabled* @property {string|null} [label]+ * @property {LaunchFilters|null} [filters] launch_match only+ */++/**+ * Filters of a launch_match rule. Every key is optional; a launch matches when+ * it passes every filter that is set.+ * @typedef {Object} LaunchFilters+ * @property {string} [name_pattern] case-insensitive, `*` wildcard, `|` alternatives, matched on name and symbol+ * @property {number} [min_market_cap_usd]+ * @property {number} [max_market_cap_usd]+ * @property {number} [min_safety_score] coin-intel quality score, 0..100+ * @property {number} [min_creator_graduated] creator's earlier coins that graduated+ * @property {number} [max_creator_launches] creator's earlier launches (serial-launcher guard)+ * @property {string[]} [exclude_risk_flags] skip a launch carrying any of these flags+ * @property {boolean} [require_socials] at least one of X, Telegram, website*//** Kinds that require a specific mint target. */@@ -32,6 +47,15 @@ export const MINT_TARGETED_KINDS = Object.freeze(['price_above', 'price_below',export const AGENT_TARGETED_KINDS = Object.freeze(['new_mint']);/** Kinds that watch one outcome of a prediction market. */export const MARKET_TARGETED_KINDS = Object.freeze(['market_price']);+/** Kinds that match new launches against a filter set instead of a target. */+export const FILTER_KINDS = Object.freeze(['launch_match']);+/** Every launch_match filter key, in display order. */+export const LAUNCH_FILTER_KEYS = Object.freeze([+ 'name_pattern', 'min_market_cap_usd', 'max_market_cap_usd', 'min_safety_score',+ 'min_creator_graduated', 'max_creator_launches', 'exclude_risk_flags', 'require_socials',+]);+/** Risk flags the coin-intel scorer writes (pump_coin_intel.risk_flags). */+export const LAUNCH_RISK_FLAGS = Object.freeze(['single_whale', 'low_diversity', 'sniped', 'dev_dumped', 'sell_pressure', 'bundle_launch']);/** Kinds whose threshold is meaningful and must be > 0. */export const THRESHOLD_KINDS = Object.freeze(['price_above', 'price_below', 'whale_buy', 'market_price']);@@ -73,6 +97,79 @@ export function newMintMatchesRule(rule, mintRow) {return mintRow?.agent_id === rule.target_agent;}+/**+ * Compile a name pattern into a matcher. Only `*` (any run of characters) and+ * `|` (alternatives) are special; everything else is literal, so a caller can+ * never smuggle in a catastrophic regex. Without a `*` an alternative matches+ * anywhere in the text ("dog" matches "HOTDOG").+ * @param {string|null|undefined} pattern+ * @returns {((text: string) => boolean) | null}+ */+export function compileNamePattern(pattern) {+ const alts = String(pattern || '').split('|').map((a) => a.trim()).filter(Boolean);+ if (!alts.length) return null;+ const escape = (t) => t.replace(/[.+?^${}()[\]\\]/g, '\\$&');+ const parts = alts.map((a) => (a.includes('*') ? `^${a.split('*').map(escape).join('.*')}$` : escape(a)));+ const re = new RegExp(parts.join('|'), 'i');+ return (text) => re.test(String(text || '').trim());+}++/**+ * Does a scored launch pass every filter of a launch_match rule? Returns the+ * list of filters that held (for the alert body) or null on any miss. A filter+ * whose data is missing on the launch (no market cap read yet) is a miss, never+ * a silent pass.+ * @param {AlertRule} rule+ * @param {{ name?: string|null, symbol?: string|null, market_cap_usd?: number|null, quality_score?: number|null,+ * creator_launches?: number|null, creator_graduated?: number|null, risk_flags?: string[]|null, has_socials?: boolean }} launch+ * @returns {string[] | null}+ */+export function launchMatchesRule(rule, launch) {+ if (rule.kind !== 'launch_match' || !launch) return null;+ const f = rule.filters || {};+ const held = [];+ const num = (v) => (v == null || v === '' ? null : Number(v));+ if (f.name_pattern) {+ const match = compileNamePattern(f.name_pattern);+ if (match && !(match(launch.name) || match(launch.symbol))) return null;+ held.push(`name matches "${f.name_pattern}"`);+ }+ const mc = num(launch.market_cap_usd);+ if (f.min_market_cap_usd != null) {+ if (!(mc != null && mc >= Number(f.min_market_cap_usd))) return null;+ held.push(`mcap >= $${Math.round(Number(f.min_market_cap_usd)).toLocaleString('en-US')}`);+ }+ if (f.max_market_cap_usd != null) {+ if (!(mc != null && mc <= Number(f.max_market_cap_usd))) return null;+ held.push(`mcap <= $${Math.round(Number(f.max_market_cap_usd)).toLocaleString('en-US')}`);+ }+ if (f.min_safety_score != null) {+ const q = num(launch.quality_score);+ if (!(q != null && q >= Number(f.min_safety_score))) return null;+ held.push(`safety ${q} >= ${f.min_safety_score}`);+ }+ if (f.min_creator_graduated != null) {+ const g = num(launch.creator_graduated);+ if (!(g != null && g >= Number(f.min_creator_graduated))) return null;+ held.push(`creator graduated ${g}`);+ }+ if (f.max_creator_launches != null) {+ const l = num(launch.creator_launches);+ if (!(l != null && l <= Number(f.max_creator_launches))) return null;+ held.push(`creator launches ${l} <= ${f.max_creator_launches}`);+ }+ if (Array.isArray(f.exclude_risk_flags) && f.exclude_risk_flags.length) {+ const flags = new Set(launch.risk_flags || []);+ if (f.exclude_risk_flags.some((x) => flags.has(x))) return null;+ held.push(`none of ${f.exclude_risk_flags.join(', ')}`);+ }+ if (f.require_socials === true) {+ if (!launch.has_socials) return null;+ held.push('has socials');+ }+ return held;+}+/*** Is this trade a whale buy for the rule (right mint, a buy, >= threshold SOL)?* @param {AlertRule} rule@@ -245,6 +342,33 @@ export function buildMarketPricePayload(rule, m) {};}+/**+ * @param {AlertRule} rule+ * @param {{ mint: string, name?: string|null, symbol?: string|null, creator?: string|null, market_cap_usd?: number|null,+ * quality_score?: number|null, creator_launches?: number|null, creator_graduated?: number|null, risk_flags?: string[]|null,+ * first_seen_at?: any }} l+ * @param {string[]} matched the filters that held (launchMatchesRule)+ */+export function buildLaunchMatchPayload(rule, l, matched = []) {+ return {+ kind: 'launch_match',+ rule_id: rule.id,+ event_id: `launch:${l.mint}`,+ mint: l.mint,+ name: l.name ? String(l.name).trim() : null,+ symbol: l.symbol ? String(l.symbol).trim() : null,+ creator: l.creator || null,+ market_cap_usd: l.market_cap_usd != null ? Math.round(Number(l.market_cap_usd)) : null,+ safety_score: l.quality_score != null ? Number(l.quality_score) : null,+ creator_launches: l.creator_launches != null ? Number(l.creator_launches) : null,+ creator_graduated: l.creator_graduated != null ? Number(l.creator_graduated) : null,+ risk_flags: l.risk_flags || [],+ matched,+ link: `/coin/${encodeURIComponent(l.mint)}`,+ at: iso(l.first_seen_at) || iso(Date.now()),+ };+}+/*** Human-readable one-line summary used for the Telegram message and as the* in-app feed title.@@ -260,6 +384,11 @@ export function formatAlertSummary(p) {}case 'new_mint':return `🆕 ${tok} just launched`;+ case 'launch_match': {+ const mc = usd(p.market_cap_usd);+ const bits = [mc ? `${mc} mcap` : null, p.safety_score != null ? `safety ${p.safety_score}` : null].filter(Boolean);+ return `🎯 ${tok} launched and matches your filters${bits.length ? ` (${bits.join(', ')})` : ''}`;+ }case 'whale_buy': {const sol = p.amount_sol != null ? `${Number(p.amount_sol).toFixed(2)} SOL` : 'a large buy';const u = usd(p.amount_usd);@@ -291,6 +420,8 @@ export function deriveRuleLabel(rule) {return `Graduations · ${target}`;case 'new_mint':return `New launches · ${target}`;+ case 'launch_match':+ return `Launches matching filters · ${describeLaunchFilters(rule.filters) || 'any'}`;case 'whale_buy':return `Whale buys ≥ ${rule.threshold} SOL · ${target}`;case 'price_above':@@ -303,3 +434,20 @@ export function deriveRuleLabel(rule) {return 'Alert';}}++/** Short plain-language summary of a launch_match filter set. */+export function describeLaunchFilters(f) {+ if (!f || typeof f !== 'object') return '';+ const k = (n) => (Number(n) >= 1000 ? `$${Math.round(Number(n) / 1000)}k` : `$${Math.round(Number(n))}`);+ const out = [];+ if (f.name_pattern) out.push(`"${f.name_pattern}"`);+ if (f.min_market_cap_usd != null && f.max_market_cap_usd != null) out.push(`${k(f.min_market_cap_usd)} to ${k(f.max_market_cap_usd)}`);+ else if (f.min_market_cap_usd != null) out.push(`mcap ≥ ${k(f.min_market_cap_usd)}`);+ else if (f.max_market_cap_usd != null) out.push(`mcap ≤ ${k(f.max_market_cap_usd)}`);+ if (f.min_safety_score != null) out.push(`safety ≥ ${f.min_safety_score}`);+ if (f.min_creator_graduated != null) out.push(`creator grads ≥ ${f.min_creator_graduated}`);+ if (f.max_creator_launches != null) out.push(`creator launches ≤ ${f.max_creator_launches}`);+ if (Array.isArray(f.exclude_risk_flags) && f.exclude_risk_flags.length) out.push(`no ${f.exclude_risk_flags.join('/')}`);+ if (f.require_socials) out.push('socials');+ return out.join(' · ');+}diff --git a/api/_lib/pump-alert-rules.js b/api/_lib/pump-alert-rules.jsnew file mode 100644index 000000000..0a296a1f4--- /dev/null+++ b/api/_lib/pump-alert-rules.js@@ -0,0 +1,184 @@+// The pump alert rule store: list, create, update and delete a user's rules.+//+// One implementation behind both surfaces that write rules, the REST endpoints+// (api/alerts/rules.js, api/alerts/rules/[id].js) and the threews-agent MCP+// tools (alert_rule_create, alert_rule_list, alert_rule_delete), so a rule an+// agent creates is byte-for-byte the rule the dashboard would have created:+// same validation (api/alerts/_rules.js), same per-user cap, same webhook+// signing secret. The rules are evaluated by api/_lib/pump-alert-runner.js.++import { sql } from './db.js';+import { parse } from './validate.js';+import { randomToken } from './crypto.js';+import {+ createRuleSchema, updateRuleSchema, validateUpdate, normalizeForKind, rulesMissingWebhookSecret, serializeRule,+} from '../alerts/_rules.js';++export const MAX_RULES_PER_USER = 50;++/** A designed failure with the HTTP status the REST surface answers with. */+export class AlertRuleError extends Error {+ constructor(code, message, status = 400, issues = undefined) {+ super(message);+ this.code = code;+ this.status = status;+ if (issues) this.issues = issues;+ }+}++const newSecret = () => `whsec_${randomToken(24)}`;++/**+ * Every rule the user owns (or just one), newest first, with its last fire and+ * the five most recent delivery attempts. Heals any webhook rule that is+ * missing its signing secret before returning it.+ */+export async function listAlertRules(userId, { ruleId = null } = {}) {+ const rows = await sql`+ SELECT r.id, r.kind, r.target_mint, r.target_agent, r.target_market, r.target_side,+ r.direction, r.threshold, r.filters,+ r.deliver_in_app, r.webhook_url, r.webhook_secret, r.telegram_chat,+ r.cooldown_seconds, r.enabled, r.label, r.created_at, r.updated_at,+ f.last_fired_at,+ coalesce(fail.cnt, 0) AS recent_failures,+ coalesce(rd.deliveries, '[]'::json) AS recent_deliveries+ FROM pump_alert_rules r+ LEFT JOIN pump_alert_rule_fires f ON f.rule_id = r.id+ LEFT JOIN LATERAL (+ SELECT count(*)::int AS cnt+ FROM pump_alert_deliveries d+ WHERE d.rule_id = r.id AND d.ok = false AND d.created_at > now() - interval '24 hours'+ ) fail ON true+ LEFT JOIN LATERAL (+ SELECT json_agg(json_build_object('channel', s.channel, 'ok', s.ok, 'detail', s.detail, 'at', s.created_at) ORDER BY s.created_at DESC) AS deliveries+ FROM (+ SELECT channel, ok, detail, created_at+ FROM pump_alert_deliveries d2+ WHERE d2.rule_id = r.id+ ORDER BY created_at DESC+ LIMIT 5+ ) s+ ) rd ON true+ WHERE r.user_id = ${userId}+ AND (${ruleId}::uuid IS NULL OR r.id = ${ruleId}::uuid)+ ORDER BY r.created_at DESC+ `;+ await healWebhookSecrets(rows);+ return rows.map(serializeRule);+}++/**+ * Back-fill a signing secret for any listed rule that has a webhook but none,+ * mutating the rows in place so the caller serializes the healed value. Those+ * rules deliver unsigned webhooks until this runs, and the list response is+ * where the user reads the secret to configure verification on their receiver.+ * Costs nothing in the normal case: the scan is in-memory and issues no query+ * unless a rule is actually missing its secret.+ */+async function healWebhookSecrets(rows) {+ for (const row of rulesMissingWebhookSecret(rows)) {+ const [updated] = await sql`+ UPDATE pump_alert_rules SET webhook_secret = ${newSecret()}, updated_at = now()+ WHERE id = ${row.id} AND webhook_secret IS NULL+ RETURNING webhook_secret, updated_at+ `;+ if (updated) {+ row.webhook_secret = updated.webhook_secret;+ row.updated_at = updated.updated_at;+ }+ }+}++async function assertAgentExists(agentId) {+ const [agent] = await sql`SELECT 1 AS ok FROM agent_identities WHERE id = ${agentId}`;+ if (!agent) throw new AlertRuleError('validation_error', 'target_agent does not exist');+}++/** Validate and insert one rule. Throws AlertRuleError on a refusal. */+export async function createAlertRule(userId, input) {+ const body = normalizeForKind(parse(createRuleSchema, input || {}));+ if (body.target_agent) await assertAgentExists(body.target_agent);++ const [{ count }] = await sql`SELECT count(*)::int AS count FROM pump_alert_rules WHERE user_id = ${userId}`;+ if (count >= MAX_RULES_PER_USER) {+ throw new AlertRuleError('limit_reached', `you can have at most ${MAX_RULES_PER_USER} alert rules`, 409);+ }++ // A per-rule signing secret whenever a webhook is configured, so the+ // receiver can verify the webhook-signature header.+ const webhookSecret = body.webhook_url ? newSecret() : null;++ const [row] = await sql`+ INSERT INTO pump_alert_rules+ (user_id, kind, target_mint, target_agent, target_market, target_side, direction,+ threshold, filters, deliver_in_app,+ webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, label)+ VALUES+ (${userId}, ${body.kind}, ${body.target_mint || null}, ${body.target_agent || null},+ ${body.target_market || null}, ${body.target_side || null}, ${body.direction || null},+ ${body.threshold ?? null}, ${body.filters ? JSON.stringify(body.filters) : null}::jsonb,+ ${body.deliver_in_app}, ${body.webhook_url || null},+ ${webhookSecret}, ${body.telegram_chat || null}, ${body.cooldown_seconds},+ ${body.enabled}, ${body.label || null})+ RETURNING id, kind, target_mint, target_agent, target_market, target_side, direction,+ threshold, filters, deliver_in_app,+ webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled,+ label, created_at, updated_at+ `;+ return serializeRule({ ...row, last_fired_at: null, recent_failures: 0, recent_deliveries: [] });+}++/** Merge a partial update over the user's rule. Returns null when it is not theirs. */+export async function updateAlertRule(userId, ruleId, patchInput) {+ const [current] = await sql`+ SELECT id, kind, target_mint, target_agent, target_market, target_side, direction,+ threshold, filters, deliver_in_app,+ webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, label+ FROM pump_alert_rules+ WHERE id = ${ruleId} AND user_id = ${userId}+ `;+ if (!current) return null;++ const patch = parse(updateRuleSchema, patchInput || {});+ const result = validateUpdate(current, patch);+ if (!result.ok) throw new AlertRuleError('validation_error', result.message, 400, result.issues);+ const next = result.value;+ if (next.target_agent && next.target_agent !== current.target_agent) await assertAgentExists(next.target_agent);++ // Webhook secret lifecycle: mint one when a webhook is newly configured,+ // drop it when the webhook is removed, otherwise keep the existing secret.+ let webhookSecret = current.webhook_secret;+ if (!next.webhook_url) webhookSecret = null;+ else if (!current.webhook_url || !current.webhook_secret) webhookSecret = newSecret();++ await sql`+ UPDATE pump_alert_rules SET+ kind = ${next.kind},+ target_mint = ${next.target_mint || null},+ target_agent = ${next.target_agent || null},+ target_market = ${next.target_market || null},+ target_side = ${next.target_side || null},+ direction = ${next.direction || null},+ threshold = ${next.threshold ?? null},+ filters = ${next.filters ? JSON.stringify(next.filters) : null}::jsonb,+ deliver_in_app = ${next.deliver_in_app},+ webhook_url = ${next.webhook_url || null},+ webhook_secret = ${webhookSecret},+ telegram_chat = ${next.telegram_chat || null},+ cooldown_seconds = ${next.cooldown_seconds},+ enabled = ${next.enabled},+ label = ${next.label || null},+ updated_at = now()+ WHERE id = ${ruleId} AND user_id = ${userId}+ `;+ // The row can be gone by now if a concurrent delete landed between the+ // update and this read; that is a plain "not there anymore".+ const [rule] = await listAlertRules(userId, { ruleId });+ return rule || null;+}++/** Delete the user's rule (its fires and delivery log cascade). Returns the id, or null. */+export async function deleteAlertRule(userId, ruleId) {+ const [row] = await sql`DELETE FROM pump_alert_rules WHERE id = ${ruleId} AND user_id = ${userId} RETURNING id`;+ return row ? row.id : null;+}diff --git a/api/_lib/pump-alert-runner.js b/api/_lib/pump-alert-runner.jsindex 2aecf4b00..5f610cbee 100644--- a/api/_lib/pump-alert-runner.js+++ b/api/_lib/pump-alert-runner.js@@ -13,6 +13,8 @@// price_* → pump.fun coins API (authoritative USD market cap)// whale_buy → pump.fun trades API (recent buys on the target mint)// market_price → the prediction venue's live market price (api/_lib/predictions/)+// launch_match → pump_coin_intel (every new launch, scored by the coin-intel+// worker within ~90s) + pump_coin_outcomes for creator historyimport { sql } from './db.js';import {@@ -27,6 +29,8 @@ import {buildNewMintPayload,buildWhalePayload,buildPricePayload,+ launchMatchesRule,+ buildLaunchMatchPayload,} from './pump-alert-eval.js';import { deliverAlert } from './alert-delivery.js';import { solPriceUsd as sharedSolPriceUsd } from './sol-price.js';@@ -34,6 +38,8 @@ import { getVenue, sideProbability } from './predictions/index.js';const GRAD_WINDOW = '15 minutes';const NEW_MINT_WINDOW = '60 minutes';+const LAUNCH_WINDOW = '15 minutes';+const LAUNCHES_PER_RUN = 1500; // ~15 min of mainnet launches at today's rateconst GRADS_PER_RUN = 100;const DELIVER_CAP = 5; // max events delivered per rule per run (storm guard)const MAX_PRICE_MINTS = 60; // distinct mints priced per run@@ -66,7 +72,7 @@ export async function runPumpAlertRules(now = Date.now()) {let rules;try {rules = await sql`- SELECT id, user_id, kind, target_mint, target_agent, target_market, target_side, direction, threshold,+ SELECT id, user_id, kind, target_mint, target_agent, target_market, target_side, direction, threshold, filters,deliver_in_app, webhook_url, webhook_secret, telegram_chat,cooldown_seconds, enabled, labelFROM pump_alert_rules@@ -91,13 +97,14 @@ export async function runPumpAlertRules(now = Date.now()) {const fireState = new Map(fireRows.map((f) => [f.rule_id, f]));// Partition rules by kind.- const byKind = { graduation: [], new_mint: [], price: [], whale_buy: [], market_price: [] };+ const byKind = { graduation: [], new_mint: [], price: [], whale_buy: [], market_price: [], launch_match: [] };for (const r of rules) {if (r.kind === 'graduation') byKind.graduation.push(r);else if (r.kind === 'new_mint') byKind.new_mint.push(r);else if (r.kind === 'price_above' || r.kind === 'price_below') byKind.price.push(r);else if (r.kind === 'whale_buy') byKind.whale_buy.push(r);else if (r.kind === 'market_price') byKind.market_price.push(r);+ else if (r.kind === 'launch_match') byKind.launch_match.push(r);}const ctx = { now, solPrice: 0 };@@ -108,6 +115,7 @@ export async function runPumpAlertRules(now = Date.now()) {runPriceRules(byKind.price, fireState, report, ctx).catch((e) => bumpErr(report, e)),runWhaleRules(byKind.whale_buy, fireState, report, ctx).catch((e) => bumpErr(report, e)),runMarketPriceRules(byKind.market_price, fireState, report, ctx).catch((e) => bumpErr(report, e)),+ runLaunchMatchRules(byKind.launch_match, fireState, report, ctx).catch((e) => bumpErr(report, e)),]);await pruneDeliveries();@@ -172,6 +180,52 @@ async function runNewMintRules(rules, fireState, report, ctx) {}}+// ── launch_match (new launches passing a filter set) ─────────────────────────++/**+ * Every mainnet launch the coin-intel worker scored in the window, with its USD+ * market cap at first sight and the creator's PRIOR launch and graduation+ * counts (coins launched before this one only, so a serial launcher's tenth+ * coin is judged on the nine before it).+ */+export async function loadRecentLaunches({ window = LAUNCH_WINDOW, limit = LAUNCHES_PER_RUN, solUsd = 0 } = {}) {+ const rows = await sql`+ SELECT i.mint, i.name, i.symbol, i.creator, i.first_seen_at, i.quality_score, i.risk_flags,+ (i.twitter IS NOT NULL OR i.telegram IS NOT NULL OR i.website IS NOT NULL) AS has_socials,+ (i.signals->>'mc_sol_first_seen')::numeric AS mc_sol,+ (SELECT count(*)::int FROM pump_coin_intel p+ WHERE p.creator = i.creator AND p.first_seen_at < i.first_seen_at) AS creator_launches,+ (SELECT count(*)::int FROM pump_coin_intel p JOIN pump_coin_outcomes o ON o.mint = p.mint AND o.graduated+ WHERE p.creator = i.creator AND p.first_seen_at < i.first_seen_at) AS creator_graduated+ FROM pump_coin_intel i+ WHERE i.network = 'mainnet' AND i.first_seen_at > now() - ${window}::interval+ ORDER BY i.first_seen_at ASC+ LIMIT ${limit}+ `;+ return rows.map((r) => ({+ ...r,+ market_cap_usd: r.mc_sol != null && solUsd > 0 ? Number(r.mc_sol) * solUsd : null,+ }));+}++async function runLaunchMatchRules(rules, fireState, report, ctx) {+ if (!rules.length) return;+ ctx.solPrice = ctx.solPrice || (await getSolPrice());+ const launches = await loadRecentLaunches({ solUsd: ctx.solPrice });+ if (!launches.length) return;++ for (const rule of rules) {+ report.evaluated++;+ const events = [];+ for (const l of launches) {+ const held = launchMatchesRule(rule, l);+ if (held) events.push(buildLaunchMatchPayload(rule, l, held));+ }+ if (!events.length) continue;+ await deliverEventRule(rule, fireState.get(rule.id), events, report, ctx.now);+ }+}+// ── price (USD market cap crossing) ────────────────────────────────────────────async function runPriceRules(rules, fireState, report, ctx) {diff --git a/api/_lib/signal-subscription-control.js b/api/_lib/signal-subscription-control.jsnew file mode 100644index 000000000..debb2fb93--- /dev/null+++ b/api/_lib/signal-subscription-control.js@@ -0,0 +1,197 @@+// Signal subscriptions, the follower side: list, subscribe, pause, resume,+// stop and kill. One implementation behind POST /api/signals/subscribe and the+// threews-agent MCP tool sniper_subscribe, so a subscription an agent opens is+// the row the /signals page would have opened.+//+// A live subscription pays the feed's x402 USDC price and mirrors its trades+// from the subscriber agent's own wallet. Turning one live (or resuming one)+// needs the signed real-funds agreement, which the caller checks because it owns+// the request. simulate mode mirrors on paper: it pays nothing and trades+// nothing, and pause, stop and kill never need the agreement.++import { sql } from './db.js';++export const SUBSCRIPTION_STATUSES = Object.freeze(['active', 'paused', 'stopped']);++/** A designed refusal: a stable code and the HTTP status the REST surface answers with. */+export class SignalSubscriptionError extends Error {+ constructor(code, message, status = 400) {+ super(message);+ this.code = code;+ this.status = status;+ }+}++const num = (v, fallback) => { const n = Number(v); return Number.isFinite(n) ? n : fallback; };+const normNetwork = (n) => (n === 'devnet' ? 'devnet' : 'mainnet');++/** A live subscription that is currently running. PURE. */+export function isLiveRunning(row) {+ return !!row && row.mode === 'live' && row.status === 'active' && row.killed !== true;+}++/** The wire shape of one subscription row. PURE. */+export function shapeSubscription(s) {+ return {+ id: Number(s.id),+ subscriber_agent_id: s.subscriber_agent_id,+ feed_id: Number(s.feed_id),+ network: s.network,+ mode: s.mode,+ billing: s.billing,+ base_sol: num(s.base_sol, 0),+ size_scaling: num(s.size_scaling, 1),+ max_per_trade_sol: num(s.max_per_trade_sol, 0),+ slippage_bps: num(s.slippage_bps, 300),+ firewall_level: s.firewall_level,+ copy_exits: s.copy_exits,+ status: s.status,+ killed: s.killed,+ epoch_paid_until: s.epoch_paid_until || null,+ last_emission_id: Number(s.last_emission_id || 0),+ created_at: s.created_at,+ updated_at: s.updated_at,+ };+}++/**+ * Size and safety knobs for a new or updated subscription, clamped to the+ * ranges the mirror engine accepts. PURE.+ */+export function subscriptionKnobs(body = {}) {+ return {+ mode: body.mode === 'live' ? 'live' : 'simulate',+ billing: body.billing === 'per_epoch' ? 'per_epoch' : 'per_signal',+ baseSol: Math.max(0.001, Math.min(10, num(body.base_sol, 0.05))),+ sizeScaling: Math.max(0.01, Math.min(20, num(body.size_scaling, 1))),+ maxPerTrade: Math.max(0.001, Math.min(50, num(body.max_per_trade_sol, 0.25))),+ slippageBps: Math.round(Math.max(0, Math.min(5000, num(body.slippage_bps, 300)))),+ firewallLevel: body.firewall_level === 'warn' ? 'warn' : 'block',+ copyExits: body.copy_exits !== false,+ };+}++/** The caller's subscriptions with feed, publisher and delivery stats, newest first. */+export async function listSignalSubscriptions(userId) {+ const rows = await sql`+ select s.*, f.slug as feed_slug, f.title as feed_title,+ f.price_per_signal_usdc, f.price_per_epoch_usdc, f.epoch_seconds,+ a.name as publisher_name, a.profile_image_url as publisher_image, a.avatar_url as publisher_avatar,+ sub.name as subscriber_name,+ (select count(*) from signal_deliveries d where d.subscription_id = s.id and d.mirror_status = 'executed') as executed,+ (select count(*) from signal_deliveries d where d.subscription_id = s.id and d.payment_status = 'paid') as paid_count,+ (select coalesce(sum(d.payment_usdc),0) from signal_deliveries d where d.subscription_id = s.id and d.payment_status = 'paid') as usdc_spent+ from signal_subscriptions s+ join signal_feeds f on f.id = s.feed_id+ join agent_identities a on a.id = f.publisher_agent_id+ join agent_identities sub on sub.id = s.subscriber_agent_id+ where s.owner_user_id = ${userId}+ order by s.created_at desc+ `;+ return rows.map((s) => ({+ ...shapeSubscription(s),+ feed: { slug: s.feed_slug, title: s.feed_title, publisher_name: s.publisher_name, publisher_image: s.publisher_image || s.publisher_avatar || null,+ price_per_signal_usdc: num(s.price_per_signal_usdc, 0), price_per_epoch_usdc: num(s.price_per_epoch_usdc, 0), epoch_seconds: num(s.epoch_seconds, 86400) },+ subscriber_name: s.subscriber_name,+ stats: { executed: Number(s.executed) || 0, paid_count: Number(s.paid_count) || 0, usdc_spent: Number(s.usdc_spent) || 0 },+ }));+}++/** The caller's subscription row, or null. */+export async function loadSignalSubscription(subId, userId) {+ const [row] = await sql`select * from signal_subscriptions where id = ${subId} and owner_user_id = ${userId} limit 1`;+ return row || null;+}++/**+ * The feed a subscription would follow, checked for being subscribable by+ * `agentId`. Throws SignalSubscriptionError when it is not.+ */+export async function loadSubscribableFeed(feedId, agentId) {+ const [feed] = await sql`select * from signal_feeds where id = ${feedId} limit 1`;+ if (!feed) throw new SignalSubscriptionError('feed_not_found', 'feed not found', 404);+ if (feed.status !== 'active') throw new SignalSubscriptionError('feed_inactive', 'this feed is not active', 409);+ if (feed.publisher_agent_id === agentId) throw new SignalSubscriptionError('self_subscribe', 'an agent cannot subscribe to its own feed');+ return { ...feed, network: normNetwork(feed.network) };+}++/** The subscriber agent's current subscription to a feed, or null. */+export async function existingSubscription(agentId, feedId) {+ const [cur] = await sql`select * from signal_subscriptions where subscriber_agent_id = ${agentId} and feed_id = ${feedId} limit 1`;+ return cur || null;+}++/**+ * Create or update the subscriber agent's subscription to a feed. A new+ * subscription starts at the feed's current emission head, so it is never+ * charged for or made to mirror a backlog emitted before it subscribed.+ */+export async function upsertSignalSubscription({ userId, agentId, feed, knobs }) {+ const [head] = await sql`select coalesce(max(id),0) as head from signal_emissions where feed_id = ${feed.id}`;+ const startCursor = Number(head?.head || 0);+ const k = knobs;+ const [sub] = await sql`+ insert into signal_subscriptions+ (subscriber_agent_id, owner_user_id, feed_id, network, mode, billing,+ base_sol, size_scaling, max_per_trade_sol, slippage_bps, firewall_level, copy_exits, status, killed, last_emission_id)+ values (${agentId}, ${userId}, ${feed.id}, ${feed.network}, ${k.mode}, ${k.billing},+ ${k.baseSol}, ${k.sizeScaling}, ${k.maxPerTrade}, ${k.slippageBps}, ${k.firewallLevel}, ${k.copyExits}, 'active', false, ${startCursor})+ on conflict (subscriber_agent_id, feed_id) do update set+ mode = excluded.mode, billing = excluded.billing, base_sol = excluded.base_sol,+ size_scaling = excluded.size_scaling, max_per_trade_sol = excluded.max_per_trade_sol,+ slippage_bps = excluded.slippage_bps, firewall_level = excluded.firewall_level,+ copy_exits = excluded.copy_exits, status = 'active', killed = false, updated_at = now()+ returning *+ `;+ return shapeSubscription(sub);+}++/**+ * Pause, resume or stop. Resuming clears any kill; pausing and stopping leave+ * the kill flag as it is. Returns null when the subscription is not the caller's.+ */+export async function setSignalSubscriptionStatus({ userId, subId, status }) {+ const next = SUBSCRIPTION_STATUSES.includes(status) ? status : 'paused';+ const [row] = next === 'active'+ ? await sql`+ update signal_subscriptions set status = 'active', killed = false, updated_at = now()+ where id = ${subId} and owner_user_id = ${userId} returning *`+ : await sql`+ update signal_subscriptions set status = ${next}, updated_at = now()+ where id = ${subId} and owner_user_id = ${userId} returning *`;+ return row ? shapeSubscription(row) : null;+}++/** The instant halt (or its release). Returns null when the subscription is not the caller's. */+export async function setSignalSubscriptionKilled({ userId, subId, killed }) {+ const [row] = await sql`+ update signal_subscriptions set killed = ${killed}, status = ${killed ? 'paused' : 'active'}, updated_at = now()+ where id = ${subId} and owner_user_id = ${userId} returning *+ `;+ return row ? shapeSubscription(row) : null;+}++/** Active public feeds an agent could follow, newest first, for discovery. */+export async function listSubscribableFeeds({ network = 'mainnet', limit = 20 } = {}) {+ const rows = await sql`+ select f.id, f.slug, f.title, f.network, f.price_per_signal_usdc, f.price_per_epoch_usdc, f.epoch_seconds,+ a.id as publisher_agent_id, a.name as publisher_name,+ (select count(*) from signal_subscriptions s where s.feed_id = f.id and s.status = 'active' and s.killed = false)::int as subscribers+ from signal_feeds f join agent_identities a on a.id = f.publisher_agent_id+ where f.network = ${normNetwork(network)} and f.status = 'active' and f.visibility = 'public' and a.is_public is not false+ order by f.created_at desc+ limit ${limit}+ `;+ return rows.map((f) => ({+ id: Number(f.id),+ slug: f.slug,+ title: f.title,+ network: f.network,+ url: `/signals/${f.slug}`,+ publisher_agent_id: f.publisher_agent_id,+ publisher_name: f.publisher_name,+ price_per_signal_usdc: num(f.price_per_signal_usdc, 0),+ price_per_epoch_usdc: num(f.price_per_epoch_usdc, 0),+ subscribers: Number(f.subscribers) || 0,+ }));+}diff --git a/api/_lib/sniper-control.js b/api/_lib/sniper-control.jsnew file mode 100644index 000000000..7ac9bc7ee--- /dev/null+++ b/api/_lib/sniper-control.js@@ -0,0 +1,295 @@+/**+ * Agent sniper control for callers that are not the dashboard form: the+ * threews-agent MCP tools sniper_status, sniper_activate_preview,+ * sniper_activate and sniper_deactivate.+ *+ * It writes the same agent_sniper_strategies row as POST /api/sniper/strategy+ * and the agent-sniper worker reads it the same way, so a strategy armed here+ * is indistinguishable from one armed on /sniper. The guards are the same too:+ * a mandatory stop loss, a positive per-trade size and daily budget, a per-trade+ * size no larger than the budget, and the signed real-funds agreement before a+ * mainnet strategy is armed (enforced by the caller, which owns the session).+ *+ * Arming never moves funds by itself: the worker spends from the agent's own+ * wallet only when a launch passes the strategy's filters, inside the daily+ * budget. Treasury auto-funding stays operator-granted and is never touched.+ */++import { sql } from './db.js';+import { solanaConnection } from './solana/connection.js';+import { deriveSniperState } from './sniper-solvency.js';++const LAMPORTS_PER_SOL = 1_000_000_000n;+const HEARTBEAT_FRESH_MS = 90_000;+export const SNIPER_TRIGGERS = ['new_mint', 'first_claim', 'intel_confirmed', 'prelaunch_radar', 'alpha_hunt', 'graduation_ride'];++const TRIGGER_LABELS = {+ new_mint: 'every new pump.fun launch that passes the filters',+ first_claim: "a creator's coin the first time they ever claim rewards",+ intel_confirmed: 'launches confirmed by the coin-intel scorer',+ prelaunch_radar: 'launches by creators on the pre-launch radar',+ alpha_hunt: 'launches with smart-money and narrative signals',+ graduation_ride: 'AMM pools at graduation, sold into the buyback window',+};++/** A designed refusal the tool layer turns into an isError result. */+export class SniperControlError extends Error {+ constructor(code, message) {+ super(message);+ this.code = code;+ }+}++/** SOL (number) to an exact lamport string, refusing anything below one lamport. */+export function solToLamports(sol) {+ const n = Number(sol);+ if (!Number.isFinite(n) || n <= 0) return null;+ const [whole, frac = ''] = n.toFixed(9).split('.');+ const lamports = BigInt(whole) * LAMPORTS_PER_SOL + BigInt(frac.padEnd(9, '0').slice(0, 9));+ return lamports > 0n ? lamports.toString() : null;+}++export const lamportsToSol = (l) => (l == null ? null : Number(BigInt(String(l))) / 1e9);++async function ownedAgent(agentId, userId) {+ const [row] = await sql`+ select id, name, meta->>'solana_address' as wallet+ from agent_identities+ where id = ${agentId} and user_id = ${userId} and deleted_at is null+ limit 1+ `;+ if (!row) throw new SniperControlError('not_found', 'No agent with that id on your account.');+ return row;+}++async function walletSol(address, network) {+ if (!address) return null;+ try {+ const conn = solanaConnection({ network: network === 'devnet' ? 'devnet' : 'mainnet' });+ const { PublicKey } = await import('@solana/web3.js');+ return (await conn.getBalance(new PublicKey(address))) / 1e9;+ } catch {+ return null;+ }+}++/** The agent-sniper worker's live state, the same derivation as /api/sniper/status. */+export async function sniperWorkerState() {+ const [beat] = await sql`select mode, last_beat_at, meta from bot_heartbeat where worker = 'agent-sniper' limit 1`;+ if (!beat) return { state: 'unknown', reason: 'no heartbeat reported yet', network: null, mode: null };+ const ageMs = beat.last_beat_at ? Date.now() - new Date(beat.last_beat_at).getTime() : null;+ const alive = ageMs != null && ageMs < HEARTBEAT_FRESH_MS;+ const meta = beat.meta && typeof beat.meta === 'object' ? beat.meta : {};+ const feedLive = alive && meta.feedConnected === true;+ const feedSilent = alive && Number(meta.lastEventAgeMs) > (Number(meta.feedWatchdogMs) || 180_000);+ const solvency = meta.solvency && typeof meta.solvency === 'object' ? meta.solvency : null;+ return {+ state: deriveSniperState({ alive, feedLive, feedSilent: !!feedSilent, solvencyState: solvency?.state || 'unknown' }),+ mode: beat.mode || meta.mode || null,+ network: meta.network || 'mainnet',+ heartbeat_age_ms: ageMs,+ feed_live: feedLive,+ global_kill: meta.globalKill ?? null,+ };+}++function strategyView(s, stats, spentToday) {+ const perTrade = String(s.per_trade_lamports);+ const daily = String(s.daily_budget_lamports);+ return {+ agent_id: s.agent_id,+ agent_name: s.agent_name,+ wallet: s.wallet || null,+ network: s.network,+ armed: s.enabled === true && s.kill_switch !== true,+ enabled: s.enabled,+ kill_switch: s.kill_switch,+ trigger: s.trigger || 'new_mint',+ trigger_description: TRIGGER_LABELS[s.trigger || 'new_mint'] || s.trigger,+ per_trade_sol: lamportsToSol(perTrade),+ daily_budget_sol: lamportsToSol(daily),+ spent_today_sol: lamportsToSol(spentToday || '0'),+ max_concurrent_positions: s.max_concurrent_positions,+ stop_loss_pct: Number(s.stop_loss_pct),+ take_profit_pct: s.take_profit_pct != null ? Number(s.take_profit_pct) : null,+ trailing_stop_pct: s.trailing_stop_pct != null ? Number(s.trailing_stop_pct) : null,+ max_hold_seconds: s.max_hold_seconds,+ filters: {+ min_market_cap_usd: s.min_market_cap_usd != null ? Number(s.min_market_cap_usd) : null,+ max_market_cap_usd: s.max_market_cap_usd != null ? Number(s.max_market_cap_usd) : null,+ min_creator_graduated: s.min_creator_graduated,+ max_creator_launches: s.max_creator_launches,+ require_socials: s.require_socials,+ min_quality_score: s.min_quality_score != null ? Number(s.min_quality_score) : null,+ },+ positions: {+ open: Number(stats?.open_positions || 0),+ closed: Number(stats?.closed_positions || 0),+ wins: Number(stats?.wins || 0),+ realized_pnl_sol: lamportsToSol(stats?.realized_pnl_lamports || '0'),+ },+ updated_at: s.updated_at,+ };+}++/**+ * Every sniper strategy the caller owns (optionally one agent or network), with+ * today's committed spend, the position ledger summary, and the worker state.+ */+export async function sniperStatus({ userId, agentId = null, network = null }) {+ const rows = await sql`+ select s.*, a.name as agent_name, a.meta->>'solana_address' as wallet+ from agent_sniper_strategies s+ join agent_identities a on a.id = s.agent_id and a.deleted_at is null+ where s.user_id = ${userId}+ and (${agentId}::uuid is null or s.agent_id = ${agentId}::uuid)+ and (${network}::text is null or s.network = ${network}::text)+ order by s.updated_at desc+ limit 50+ `;+ const ids = rows.map((r) => r.agent_id);+ const [stats, spend, worker] = await Promise.all([+ ids.length+ ? sql`+ select agent_id, network,+ count(*) filter (where status in ('opening','open','closing')) as open_positions,+ count(*) filter (where status = 'closed') as closed_positions,+ count(*) filter (where status = 'closed' and realized_pnl_lamports > 0) as wins,+ coalesce(sum(realized_pnl_lamports) filter (where status = 'closed'), 0)::text as realized_pnl_lamports+ from agent_sniper_positions+ where agent_id = any(${ids}::uuid[])+ group by agent_id, network+ `+ : [],+ ids.length+ ? sql`+ select agent_id, network, coalesce(sum(coalesce(stake_lamports, entry_quote_lamports)), 0)::text as spent+ from agent_sniper_positions+ where agent_id = any(${ids}::uuid[]) and opened_at >= date_trunc('day', now()) and status <> 'failed'+ group by agent_id, network+ `+ : [],+ sniperWorkerState().catch(() => ({ state: 'unknown', reason: 'status store unreachable' })),+ ]);+ const key = (r) => `${r.agent_id}:${r.network}`;+ const statsBy = new Map(stats.map((r) => [key(r), r]));+ const spendBy = new Map(spend.map((r) => [key(r), r.spent]));+ const strategies = rows.map((s) => strategyView(s, statsBy.get(key(s)), spendBy.get(key(s))));+ return { worker, strategies, armed_count: strategies.filter((s) => s.armed).length };+}++function readSizing(input) {+ const perTrade = solToLamports(input.per_trade_sol);+ const daily = solToLamports(input.daily_budget_sol);+ if (!perTrade) throw new SniperControlError('invalid_size', 'per_trade_sol must be a positive SOL amount.');+ if (!daily) throw new SniperControlError('invalid_budget', 'daily_budget_sol must be a positive SOL amount.');+ if (BigInt(perTrade) > BigInt(daily)) throw new SniperControlError('invalid_size', 'per_trade_sol cannot exceed daily_budget_sol.');+ const stopLoss = input.stop_loss_pct == null ? null : Number(input.stop_loss_pct);+ if (stopLoss != null && !(stopLoss > 0 && stopLoss <= 95)) throw new SniperControlError('invalid_stop_loss', 'stop_loss_pct must be between 0 and 95.');+ return { perTrade, daily, stopLoss };+}++/**+ * Describe exactly what arming would do, without writing anything: the agent,+ * its wallet and live balance, the sizing, the trigger and exits, and every+ * reason it would be refused. The MCP policy stamps a preview_id on this.+ */+export async function previewActivation({ userId, agentId, network = 'mainnet', input }) {+ const agent = await ownedAgent(agentId, userId);+ const { perTrade, daily, stopLoss } = readSizing(input);+ const [existing] = await sql`select * from agent_sniper_strategies where agent_id = ${agentId} and network = ${network} limit 1`;+ const [balance, worker] = await Promise.all([+ walletSol(agent.wallet, network),+ sniperWorkerState().catch(() => ({ state: 'unknown', network: null })),+ ]);+ const trigger = input.trigger || existing?.trigger || 'new_mint';+ const perTradeSol = lamportsToSol(perTrade);+ const checks = [+ { id: 'wallet', ok: !!agent.wallet, label: agent.wallet ? `Agent wallet ${agent.wallet}` : 'The agent has no Solana wallet yet (provision_wallet creates one)' },+ { id: 'balance', ok: balance == null || balance >= perTradeSol, label: balance == null ? 'Wallet balance could not be read right now' : `Wallet holds ${balance.toFixed(4)} SOL against a ${perTradeSol} SOL entry` },+ { id: 'worker', ok: worker.network == null || worker.network === network, label: worker.network && worker.network !== network ? `The sniper worker currently trades ${worker.network}, so a ${network} strategy is stored but idle` : `Sniper worker ${worker.state}` },+ ];+ const blocked = checks.filter((c) => !c.ok && c.id === 'wallet').map((c) => c.id);+ return {+ agent: { id: agent.id, name: agent.name, wallet: agent.wallet },+ network,+ chain: 'Solana',+ asset: 'SOL',+ recipient: 'pump.fun bonding curves and AMM pools of the launches the strategy buys; proceeds return to the agent wallet',+ per_trade_sol: perTradeSol,+ daily_budget_sol: lamportsToSol(daily),+ per_trade_lamports: perTrade,+ daily_budget_lamports: daily,+ max_concurrent_positions: input.max_concurrent_positions ?? existing?.max_concurrent_positions ?? 1,+ trigger,+ trigger_description: TRIGGER_LABELS[trigger] || trigger,+ stop_loss_pct: stopLoss ?? (existing ? Number(existing.stop_loss_pct) : 30),+ take_profit_pct: input.take_profit_pct ?? (existing?.take_profit_pct != null ? Number(existing.take_profit_pct) : null),+ wallet_sol: balance,+ previously: existing ? { enabled: existing.enabled, kill_switch: existing.kill_switch } : null,+ worker,+ checks,+ executable: blocked.length === 0,+ blocked_by: blocked,+ real_funds: network === 'mainnet',+ };+}++/**+ * Arm the strategy: insert or update the row with the previewed sizing and set+ * enabled, clearing the kill switch. Every other knob keeps its stored value+ * (or the column default for a new row), so the dashboard's finer settings are+ * never clobbered.+ */+export async function activateSniper({ userId, agentId, network = 'mainnet', input }) {+ const agent = await ownedAgent(agentId, userId);+ if (!agent.wallet) throw new SniperControlError('no_wallet', 'The agent has no Solana wallet yet. Provision one before arming the sniper.');+ const { perTrade, daily, stopLoss } = readSizing(input);+ const trigger = input.trigger || null;+ if (trigger && !SNIPER_TRIGGERS.includes(trigger)) throw new SniperControlError('invalid_trigger', `trigger must be one of ${SNIPER_TRIGGERS.join(', ')}.`);+ const maxConcurrent = input.max_concurrent_positions != null ? Math.min(50, Math.max(1, Math.trunc(input.max_concurrent_positions))) : null;+ const takeProfit = input.take_profit_pct != null ? Number(input.take_profit_pct) : null;+ const [row] = await sql`+ insert into agent_sniper_strategies+ (agent_id, user_id, network, enabled, kill_switch, trigger, per_trade_lamports, daily_budget_lamports,+ stop_loss_pct, max_concurrent_positions, take_profit_pct, updated_at)+ values+ (${agentId}, ${userId}, ${network}, true, false, coalesce(${trigger}::text, 'new_mint'), ${perTrade}, ${daily},+ coalesce(${stopLoss}::numeric, 30), coalesce(${maxConcurrent}::int, 1), ${takeProfit}, now())+ on conflict (agent_id, network) do update set+ enabled = true,+ kill_switch = false,+ trigger = coalesce(${trigger}::text, agent_sniper_strategies.trigger),+ per_trade_lamports = excluded.per_trade_lamports,+ daily_budget_lamports = excluded.daily_budget_lamports,+ stop_loss_pct = coalesce(${stopLoss}::numeric, agent_sniper_strategies.stop_loss_pct),+ max_concurrent_positions = coalesce(${maxConcurrent}::int, agent_sniper_strategies.max_concurrent_positions),+ take_profit_pct = coalesce(${takeProfit}::numeric, agent_sniper_strategies.take_profit_pct),+ updated_at = now()+ returning *+ `;+ return strategyView({ ...row, agent_name: agent.name, wallet: agent.wallet }, null, null);+}++/**+ * Disarm: enabled=false, or with kill the kill switch as well (the worker also+ * stops managing exits for a killed strategy's new entries). Idempotent; a+ * strategy that does not exist is reported, not created.+ */+export async function deactivateSniper({ userId, agentId, network = 'mainnet', kill = false }) {+ const agent = await ownedAgent(agentId, userId);+ const [row] = await sql`+ update agent_sniper_strategies+ set enabled = false,+ kill_switch = case when ${kill} then true else kill_switch end,+ updated_at = now()+ where agent_id = ${agentId} and network = ${network} and user_id = ${userId}+ returning *+ `;+ if (!row) return { agent_id: agentId, network, existed: false, armed: false };+ const [open] = await sql`+ select count(*)::int as n from agent_sniper_positions+ where agent_id = ${agentId} and network = ${network} and status in ('opening','open','closing')+ `;+ return { ...strategyView({ ...row, agent_name: agent.name, wallet: agent.wallet }, { open_positions: open?.n }, null), existed: true };+}diff --git a/api/_lib/trader-duels.js b/api/_lib/trader-duels.jsindex 5d98c5f43..20d94a2c7 100644--- a/api/_lib/trader-duels.js+++ b/api/_lib/trader-duels.js@@ -415,7 +415,10 @@ export async function generateDuels({ network = 'mainnet', now = Date.now() } =const [existing] = await sql`select count(*)::int as c from duel_marketswhere network = ${network} and window_kind = ${kind} and window_start = ${iso(w.start)}+ and coalesce(context ->> 'source', '') <> 'challenge'`;+ // Challenge duels (api/_lib/duel-challenges.js) can open a window before+ // this generator reaches it, so only rivalry-made duels count as "done".if (n(existing?.c) > 0) continue;if (!rivalries) {const board = await getRivalries({ network, window: DUEL_RULES.board_window, lookback: '7d', limit: 12, now });diff --git a/api/_mcpagent/catalog.js b/api/_mcpagent/catalog.jsindex ea17fcba2..954b720bf 100644--- a/api/_mcpagent/catalog.js+++ b/api/_mcpagent/catalog.js@@ -5,8 +5,12 @@ import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';import { toolDefs as walletToolDefs } from './tools.js';import { marketplaceToolDefs } from './marketplace-tools.js';import { predictionToolDefs } from './predictions-tools.js';+import { portfolioToolDefs } from './portfolio-tools.js';+import { sniperAlertToolDefs } from './sniper-alert-tools.js';+import { duelToolDefs } from './duels-tools.js';-const toolDefs = [...walletToolDefs, ...marketplaceToolDefs, ...predictionToolDefs];+const toolDefs = [...walletToolDefs, ...marketplaceToolDefs, ...predictionToolDefs,+ ...portfolioToolDefs, ...sniperAlertToolDefs, ...duelToolDefs];// Free, public entry point, listed first so discovery clients see it up top.// Annotations: a static, local overview built at module load: read-only,diff --git a/api/_mcpagent/dispatch.js b/api/_mcpagent/dispatch.jsindex efaed3021..4338a52ae 100644--- a/api/_mcpagent/dispatch.js+++ b/api/_mcpagent/dispatch.js@@ -28,6 +28,16 @@ const INSTRUCTIONS = ['predictions_positions reads an agent, predictions_watch sets a probability alert. predictions_open,','predictions_close and predictions_redeem move funds: call the matching *_preview tool, show its','table, wait for a clear yes, then call with confirm_trade: true and the preview_id.',+ 'Portfolio: get_portfolio values an agent wallet (SOL and SPL, FIFO cost basis, risk flags),',+ 'get_balance_history reads its hourly snapshots and get_pnl splits realized and unrealized P&L by source.',+ 'Launch sniper: sniper_status reads strategies; sniper_activate spends SOL on new launches, so call',+ 'sniper_activate_preview, show its table (recipient, amount, asset, chain), wait for a clear yes, then',+ 'call it with confirm_spend: true and the preview_id. sniper_deactivate disarms at once. sniper_subscribe',+ 'follows a signal feed on paper. Alerts: alert_rule_create (launch_match filters a new launch by name,',+ 'market cap, safety score and creator history) notifies the owner by bell, push and paired chats;',+ 'alert_rule_list, and alert_rule_delete with confirm_delete and the list preview_id.',+ 'Duels: duel_challenge pits your agent against another owner\'s over the next day or week, duel_accept',+ 'answers one, duel_details reads a duel or challenge and duel_markets lists duels, challenges and the leaderboard.',].join(' ');export const dispatch = makeDispatcher({diff --git a/api/_mcpagent/duels-tools.js b/api/_mcpagent/duels-tools.jsnew file mode 100644index 000000000..d78b5c3ba--- /dev/null+++ b/api/_mcpagent/duels-tools.js@@ -0,0 +1,245 @@+// threews-agent MCP: trader duels and agent-to-agent challenges.+//+// Thin adapters over the free-play duel engine (api/_lib/trader-duels.js, the+// /duels pages and api/duels/*) and the challenge store+// (api/_lib/duel-challenges.js). A duel scores the two agents' realized P&L over+// one UTC window; the duels-tick cron resolves it and settles the crowd's+// points. Nothing here moves funds: challenges and calls are free-play.+//+// read duel_details, duel_markets (markets, challenges, leaderboard)+// write duel_challenge (notifies the opponent's owner),+// duel_accept (accept opens the duel; decline and cancel close the+// challenge)++import { hasScope } from '../_lib/auth.js';+import { limits } from '../_lib/rate-limit.js';+import { listDuels, getDuel, seasonLeaderboard } from '../_lib/trader-duels.js';+import {+ CHALLENGE_NETWORK, CHALLENGE_STATUSES, CHALLENGE_TTL_HOURS, MAX_MESSAGE, DuelChallengeError,+ createChallenge, respondChallenge, getChallenge, listChallenges, challengeLeaderboard,+} from '../_lib/duel-challenges.js';++// Duel state moves with the window clock and the traders' fills, so reads are+// not idempotent; they read only three.ws state.+const LIVE_READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false };+// Creates or answers a challenge and notifies the other owner.+const ACT = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };++const WRITE_SCOPES = ['wallet:trade', 'agents:write'];++function refusal(text, reason, extra = {}) {+ return { content: [{ type: 'text', text }], structuredContent: { ok: false, reason, ...extra }, isError: true };+}++async function enforce(auth) {+ const rl = await limits.mcpAgent(auth.userId || auth.rateKey || 'anon');+ if (!rl.success) {+ throw Object.assign(new Error('rate_limited'), { code: -32000, data: { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) } });+ }+}++/** Sign-in and scope gate (when asked for) plus the designed-error mapping. */+async function run(auth, { signIn = false, scopes = null }, fn) {+ await enforce(auth);+ if (signIn && !auth.userId) return refusal('Sign in to three.ws to duel with your agents.', 'auth_required', { signed_in: false });+ if (scopes && !scopes.some((s) => hasScope(auth.scope, s))) {+ return refusal(`This action needs the ${scopes.join(' or ')} scope. Re-authorize with it granted.`, 'insufficient_scope', { required: scopes[0] });+ }+ try {+ return await fn();+ } catch (err) {+ if (err instanceof DuelChallengeError) return refusal(err.message, err.code);+ throw err;+ }+}++const ok = (lines, structured) => ({ content: [{ type: 'text', text: lines.filter(Boolean).join('\n') }], structuredContent: structured });+const sol = (n) => (n == null ? 'n/a' : `${Number(n) >= 0 ? '+' : ''}${Number(n).toFixed(4)} SOL`);+const pct = (r) => (r == null ? 'n/a' : `${Math.round(r * 100)}%`);++function duelLine(d) {+ const winner = d.winner ? `, won by ${d.winner === 'a' ? d.a.name : d.b.name}` : d.void_reason ? `, void (${d.void_reason})` : '';+ return `- ${d.a.name} vs ${d.b.name}: ${d.window_kind} window ${d.window_start.slice(0, 10)}, ${d.phase}${winner}. Crowd ${d.crowd.a.calls}:${d.crowd.b.calls}. ${d.url}`;+}++function challengeLine(c) {+ const action = c.can_respond ? ' Answer with duel_accept.' : c.can_cancel ? ' duel_accept with response "cancel" withdraws it.' : '';+ return `- [${c.id}] ${c.challenger.name} challenged ${c.challenged.name} (${c.window_kind}): ${c.status}${c.duel_url ? `, duel ${c.duel_url}` : ''}.${action}`;+}++function standingLines(d) {+ if (!d.standing) return [];+ const side = (s, name) => (s ? `${name}: ${s.closed ?? 0} closed, ${s.wins ?? 0} wins, ${sol(s.pnl_sol)}` : `${name}: unavailable`);+ const head = d.standing.final ? 'Final:' : `Standing as of ${d.standing.as_of}:`;+ const leading = d.standing.leading ? ` ${d.standing.leading === 'a' ? d.a.name : d.b.name} leads.` : '';+ return [`${head}${leading}`, ` ${side(d.standing.a, d.a.name)}`, ` ${side(d.standing.b, d.b.name)}`];+}++// The UTC dates a window covers: one day, or the first and last day of a week.+function windowSpan(d) {+ const first = String(d.window_start).slice(0, 10);+ const last = new Date(new Date(d.window_end).getTime() - 1).toISOString().slice(0, 10);+ return first === last ? `${first} (UTC)` : `${first} to ${last} (UTC)`;+}++function duelDetailLines(d) {+ // A challenge duel's headline only restates the matchup, so it is shown for+ // generated duels alone.+ const headline = d.headline && !(d.headline.includes(d.a.name) && d.headline.includes(d.b.name)) ? `: ${d.headline}` : '';+ return [+ `${d.a.name} vs ${d.b.name}${headline}`,+ `${d.window_kind} window ${windowSpan(d)}, ${d.phase}. ${d.url}`,+ ...standingLines(d),+ `Crowd: ${d.crowd.a.calls} calls (${d.crowd.a.points} pts) on ${d.a.name}, ${d.crowd.b.calls} calls (${d.crowd.b.points} pts) on ${d.b.name}.`,+ d.my_call ? `Your call: ${d.my_call.side === 'a' ? d.a.name : d.b.name} for ${d.my_call.stake} pts (${d.my_call.status}).` : null,+ ];+}++const agentIdProp = { type: 'string', format: 'uuid' };++export const duelToolDefs = [+ {+ name: 'duel_challenge',+ title: 'Challenge another agent to a duel',+ group: 'predictions',+ tier: 'write',+ annotations: ACT,+ description: `Challenge another owner's public agent to a trading duel over the next UTC day or week, with one of your public agents. The opponent's owner is notified (bell, push and paired chats) and has ${CHALLENGE_TTL_HOURS} hours to accept. Accepted duels score both agents' realized P&L over the window, are open to free-play crowd calls until the window starts, and count toward the challenge leaderboard (duel_markets view "leaderboard"). Free-play: no funds move. Duels resolve on ${CHALLENGE_NETWORK}. Use this when the owner wants to pit one of their agents against another owner's agent.`,+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { ...agentIdProp, description: 'Your agent that issues the challenge.' },+ opponent_agent_id: { ...agentIdProp, description: 'The agent you challenge. duel_markets view "leaderboard" and /duels show candidates.' },+ window: { type: 'string', enum: ['day', 'week'], default: 'day', description: 'day: the next UTC day. week: the next UTC week.' },+ message: { type: 'string', maxLength: MAX_MESSAGE, description: 'Optional note shown to the opponent\'s owner.' },+ },+ required: ['agent_id', 'opponent_agent_id'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { signIn: true, scopes: WRITE_SCOPES }, async () => {+ const c = await createChallenge({+ userId: auth.userId,+ challengerAgentId: args.agent_id,+ challengedAgentId: args.opponent_agent_id,+ windowKind: args.window || 'day',+ message: args.message ?? null,+ });+ const channels = Object.entries(c.notified || {}).filter(([, v]) => v === true || (typeof v === 'number' && v > 0)).map(([k]) => k);+ return ok([+ `Challenge ${c.id} sent: ${c.challenger.name} vs ${c.challenged.name}, ${c.window_kind} window. It expires ${c.expires_at}.`,+ channels.length ? `The opponent's owner was notified by ${channels.join(', ')}.` : 'The opponent\'s owner will see it in their challenges list.',+ 'duel_details with this challenge_id shows its status.',+ ], { ok: true, challenge: c });+ }),+ },+ {+ name: 'duel_accept',+ title: 'Answer a duel challenge',+ group: 'predictions',+ tier: 'write',+ annotations: ACT,+ description: 'Answer a pending challenge. "accept" (the challenged agent\'s owner) opens the duel for its window and notifies the challenger; "decline" turns it down; "cancel" (the challenger\'s owner) withdraws it. duel_markets view "challenges" lists the ones waiting on you. Use this when the owner wants to accept, decline or withdraw a pending challenge.',+ inputSchema: {+ type: 'object',+ properties: {+ challenge_id: { type: 'string', format: 'uuid' },+ response: { type: 'string', enum: ['accept', 'decline', 'cancel'], default: 'accept' },+ },+ required: ['challenge_id'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { signIn: true, scopes: WRITE_SCOPES }, async () => {+ const response = args.response || 'accept';+ const { challenge, duel } = await respondChallenge({ userId: auth.userId, challengeId: args.challenge_id, response });+ if (response !== 'accept') return ok([`Challenge ${challenge.id} is ${challenge.status}.`], { ok: true, challenge });+ return ok([+ `Accepted. The duel is open: ${challenge.challenger.name} vs ${challenge.challenged.name}.`,+ ...(duel ? duelDetailLines(duel) : [challenge.duel_url]),+ ], { ok: true, challenge, duel });+ }),+ },+ {+ name: 'duel_details',+ title: 'Duel details',+ group: 'predictions',+ tier: 'read',+ annotations: LIVE_READ,+ description: 'One duel or challenge in full. duel_id: both traders\' 30-day records, the in-window standing (live while running, final once resolved), the crowd\'s calls and your own call. challenge_id (yours, either side): its status and, once accepted, the duel. Use this to follow one duel\'s standing or check where a challenge stands.',+ inputSchema: {+ type: 'object',+ properties: {+ duel_id: { type: 'string', format: 'uuid' },+ challenge_id: { type: 'string', format: 'uuid' },+ },+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, {}, async () => {+ if (!args.duel_id && !args.challenge_id) return refusal('Pass duel_id or challenge_id.', 'invalid_request');+ if (args.challenge_id) {+ if (!auth.userId) return refusal('Sign in to read a challenge.', 'auth_required', { signed_in: false });+ const found = await getChallenge({ userId: auth.userId, challengeId: args.challenge_id });+ if (!found) return refusal('No challenge with that id involves your agents.', 'not_found');+ return ok([+ challengeLine(found.challenge),+ found.challenge.message ? `Message: "${found.challenge.message}"` : null,+ ...(found.duel ? duelDetailLines(found.duel) : []),+ ], found);+ }+ const duel = await getDuel(args.duel_id, { userId: auth.userId || null });+ if (!duel) return refusal('No duel with that id.', 'not_found');+ return ok(duelDetailLines(duel), { duel });+ }),+ },+ {+ name: 'duel_markets',+ title: 'Duels, challenges and leaderboard',+ group: 'predictions',+ tier: 'read',+ annotations: LIVE_READ,+ description: 'Browse duels. view "markets" (default): duels by phase (open for calls, live, settled, all), optionally for one agent. view "challenges": your incoming and outgoing challenges (sign in). view "leaderboard": agents ranked by their challenge-duel record (wins, losses, realized P&L) plus this season\'s top predictors. Call this first to find a duel_id or challenge_id, or to see the leaderboard.',+ inputSchema: {+ type: 'object',+ properties: {+ view: { type: 'string', enum: ['markets', 'challenges', 'leaderboard'], default: 'markets' },+ phase: { type: 'string', enum: ['open', 'live', 'settled', 'all'], default: 'open', description: 'markets view.' },+ agent_id: { ...agentIdProp, description: 'markets: duels featuring this agent. leaderboard: also return this agent\'s row.' },+ direction: { type: 'string', enum: ['incoming', 'outgoing', 'all'], default: 'all', description: 'challenges view.' },+ status: { type: 'string', enum: CHALLENGE_STATUSES, description: 'challenges view.' },+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },+ },+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, {}, async () => {+ const view = args.view || 'markets';+ const limit = args.limit || 20;+ if (view === 'challenges') {+ if (!auth.userId) return refusal('Sign in to see your challenges.', 'auth_required', { signed_in: false });+ const challenges = await listChallenges({ userId: auth.userId, direction: args.direction || 'all', status: args.status || null, limit });+ return ok([+ challenges.length ? `${challenges.length} challenge${challenges.length === 1 ? '' : 's'}:` : 'No challenges yet. duel_challenge sends one.',+ ...challenges.map(challengeLine),+ ], { challenges });+ }+ if (view === 'leaderboard') {+ const [board, predictors] = await Promise.all([+ challengeLeaderboard({ limit, agentId: args.agent_id || null }),+ seasonLeaderboard({ limit: Math.min(limit, 10), userId: auth.userId || null }),+ ]);+ return ok([+ board.leaders.length ? 'Challenge duel leaderboard:' : 'No challenge duel has settled yet. The first accepted challenge to resolve starts the board.',+ ...board.leaders.map((r) => `${r.rank}. ${r.name}: ${r.wins}W ${r.losses}L${r.voids ? ` ${r.voids} void` : ''}, win rate ${pct(r.win_rate)}, ${sol(r.realized_pnl_sol)} (${r.trader})`),+ board.agent ? `${board.agent.name}: rank ${board.agent.rank}, ${board.agent.wins}W ${board.agent.losses}L.` : args.agent_id ? 'That agent has no settled challenge duel yet.' : null,+ `${board.challenges.pending} challenges pending, ${board.challenges.accepted} accepted.`,+ predictors.leaders.length ? `Top predictors (season ${predictors.season.id}):` : null,+ ...predictors.leaders.map((p) => `${p.rank}. ${p.name}: ${p.net >= 0 ? '+' : ''}${p.net} pts, ${p.wins}/${p.decided} right`),+ ], { leaderboard: board, predictors });+ }+ const phase = args.phase || 'open';+ const duels = await listDuels({ network: CHALLENGE_NETWORK, phase, agentId: args.agent_id || null, userId: auth.userId || null, limit });+ return ok([+ duels.length ? `${duels.length} ${phase} duel${duels.length === 1 ? '' : 's'}:` : `No ${phase} duels right now. New ones open daily on /duels, and duel_challenge starts your own.`,+ ...duels.map(duelLine),+ ], { phase, duels });+ }),+ },+];diff --git a/api/_mcpagent/portfolio-tools.js b/api/_mcpagent/portfolio-tools.jsnew file mode 100644index 000000000..d7a7518bc--- /dev/null+++ b/api/_mcpagent/portfolio-tools.js@@ -0,0 +1,150 @@+// threews-agent MCP: an agent's valued portfolio, its net-worth history, and+// its P&L.+//+// Thin adapters over api/_lib/portfolio.js (live valuation, FIFO cost basis,+// attribution, risk) and api/_lib/portfolio-history.js (snapshots and the+// realized curve), the same modules behind the wallet hub's Portfolio tab and+// /api/v1/agents/:id/portfolio. Every tool is owner-only, because attribution+// reads the agent's custody ledger, and none of them moves funds.+//+// read get_portfolio, get_balance_history, get_pnl++import { hasScope } from '../_lib/auth.js';+import { limits } from '../_lib/rate-limit.js';+import {+ PortfolioAccessError, loadPortfolioAgent, portfolioWithSnapshot, getBalanceHistory, pnlDigest,+} from '../_lib/portfolio-history.js';++// Live chain reads: the answer moves with prices, so not idempotent.+const LIVE_READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true };+// Recorded history: the same arguments return the same stored series.+const HISTORY_READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };++const sol = (n) => (n == null ? 'n/a' : `${Number(n).toFixed(4)} SOL`);+const usd = (n) => (n == null ? 'n/a' : `$${Number(n).toLocaleString('en-US', { maximumFractionDigits: 2 })}`);+const pct = (n) => (n == null ? 'n/a' : `${Number(n).toFixed(2)}%`);++function refusal(text, reason, extra = {}) {+ return { content: [{ type: 'text', text }], structuredContent: { ok: false, reason, ...extra }, isError: true };+}++async function enforce(auth) {+ const rl = await limits.mcpAgent(auth.userId || auth.rateKey || 'anon');+ if (!rl.success) {+ throw Object.assign(new Error('rate_limited'), { code: -32000, data: { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) } });+ }+}++async function run(auth, agentId, fn) {+ await enforce(auth);+ if (!auth.userId) return refusal('Sign in to three.ws to read your agents.', 'auth_required', { signed_in: false });+ if (!hasScope(auth.scope, 'wallet:read') && !hasScope(auth.scope, 'wallet:write')) {+ return refusal('Reading a portfolio needs the wallet:read scope. Re-authorize with it granted.', 'insufficient_scope', { required: 'wallet:read' });+ }+ try {+ await loadPortfolioAgent(agentId, auth.userId);+ return await fn();+ } catch (err) {+ if (err instanceof PortfolioAccessError) return refusal(err.message, err.code);+ throw err;+ }+}++const agentIdProp = { type: 'string', format: 'uuid', description: 'The agent whose wallet to read. wallet_status or three://agents lists yours.' };+const networkProp = { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet', description: 'Solana cluster.' };++function holdingLine(h) {+ const label = h.isNative ? 'SOL' : (h.symbol || (h.mint ? `${h.mint.slice(0, 4)}...${h.mint.slice(-4)}` : 'token'));+ const basis = h.cost_basis_sol != null ? `, cost ${sol(h.cost_basis_sol)}, unrealized ${sol(h.unrealized_sol)} (${pct(h.unrealized_pct)})` : '';+ const flag = h.liquidity_warning ? ` [${h.liquidity_warning}]` : '';+ return `- ${label}: ${h.amount ?? 'n/a'} worth ${usd(h.usd_value)}${basis}${flag}`;+}++export const portfolioToolDefs = [+ {+ name: 'get_portfolio',+ title: "Value an agent's portfolio",+ group: 'wallet',+ tier: 'read',+ annotations: LIVE_READ,+ description: "Live valuation of one of your agents' Solana wallet: SOL and every SPL holding in SOL and USD, FIFO cost basis and unrealized P&L per holding, realized and unrealized P&L by source (sniper, discretionary trades, strategies, x402 spend, withdrawals), risk metrics and plain-language risk flags. Records a net-worth point for get_balance_history. Use this when the user asks what an agent holds, what it is worth, or how risky its wallet is.",+ inputSchema: {+ type: 'object',+ properties: { agent_id: agentIdProp, network: networkProp, max_holdings: { type: 'integer', minimum: 1, maximum: 100, default: 25 } },+ required: ['agent_id'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, args.agent_id, async () => {+ const p = await portfolioWithSnapshot({ agentId: args.agent_id, network: args.network || 'mainnet' });+ if (!p) return refusal('No agent with that id.', 'not_found');+ const max = args.max_holdings || 25;+ const holdings = p.holdings.slice(0, max);+ const lines = [+ `${p.agent.name} on ${p.network}${p.agent.wallet ? ` (${p.agent.wallet})` : ', no wallet provisioned'}`,+ `Net worth ${sol(p.net_worth.sol)} = ${usd(p.net_worth.usd)} (SOL ${usd(p.sol_usd)}). Realized ${sol(p.net_worth.realized_pnl_sol)}, unrealized ${sol(p.net_worth.unrealized_pnl_sol)}.`,+ holdings.length ? `Holdings (${p.holdings.length}):` : 'No holdings.',+ ...holdings.map(holdingLine),+ p.holdings.length > max ? `(+${p.holdings.length - max} smaller holdings)` : null,+ p.risk_flags.length ? `Risk flags: ${p.risk_flags.map((f) => `${f.level}: ${f.text}`).join('; ')}` : 'No risk flags.',+ ].filter(Boolean);+ return { content: [{ type: 'text', text: lines.join('\n') }], structuredContent: { ...p, holdings } };+ }),+ },+ {+ name: 'get_balance_history',+ title: "An agent's net-worth history",+ group: 'wallet',+ tier: 'read',+ annotations: HISTORY_READ,+ description: "How one of your agents' net worth moved over the last N days: recorded valuations (SOL, USD, realized and unrealized P&L at each point) with change, peak and max drawdown, plus the exact cumulative realized P&L per day from closed trades. Use this to chart or describe how an agent's net worth changed over time.",+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: agentIdProp,+ network: networkProp,+ days: { type: 'integer', minimum: 1, maximum: 365, default: 30 },+ max_points: { type: 'integer', minimum: 2, maximum: 500, default: 120, description: 'Thin the series to at most this many points; first and last stay exact.' },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, args.agent_id, async () => {+ const h = await getBalanceHistory({ agentId: args.agent_id, network: args.network || 'mainnet', days: args.days || 30, maxPoints: args.max_points || 120 });+ const s = h.summary;+ const curve = h.realized_curve;+ const lines = [+ `Net worth over ${h.days} days on ${h.network}: ${h.snapshot_count} recorded valuations.`,+ s ? `${sol(s.start_sol)} to ${sol(s.end_sol)} (${sol(s.change_sol)}, ${pct(s.change_pct)}); USD ${usd(s.start_usd)} to ${usd(s.end_usd)}. Peak ${sol(s.peak_sol)}, max drawdown ${pct(s.max_drawdown_pct)}.` : h.note,+ curve.length ? `Realized P&L by day (cumulative): ${curve.slice(-10).map((c) => `${c.date} ${sol(c.cumulative_realized_sol)}`).join(', ')}` : 'No trades closed in this window.',+ ];+ return { content: [{ type: 'text', text: lines.join('\n') }], structuredContent: h };+ }),+ },+ {+ name: 'get_pnl',+ title: "An agent's profit and loss",+ group: 'wallet',+ tier: 'read',+ annotations: LIVE_READ,+ description: "Realized, unrealized and total P&L for one of your agents in SOL and USD, broken down by source (sniper, discretionary, strategies, x402 spend, withdrawals), with trading performance (win rate, ROI, profit factor, drawdown) and the biggest open winners and losers. Use this when the user asks whether an agent is making or losing money, and from what.",+ inputSchema: { type: 'object', properties: { agent_id: agentIdProp, network: networkProp }, required: ['agent_id'], additionalProperties: false },+ handler: (args, auth) => run(auth, args.agent_id, async () => {+ const p = await portfolioWithSnapshot({ agentId: args.agent_id, network: args.network || 'mainnet' });+ if (!p) return refusal('No agent with that id.', 'not_found');+ const d = pnlDigest(p);+ const t = d.totals;+ const perf = d.performance;+ const lines = [+ `${d.agent.name} on ${d.network}: total P&L ${sol(t.total_sol)} (${usd(t.total_usd)}), realized ${sol(t.realized_sol)}, unrealized ${sol(t.unrealized_sol)}.`,+ `Trades: ${perf.closed_trades} closed, ${perf.open_trades} open, win rate ${perf.win_rate == null || !perf.closed_trades ? 'n/a' : pct(perf.win_rate * 100)}, ROI ${perf.closed_trades ? pct(perf.roi_pct) : 'n/a'}, max drawdown ${pct(perf.max_drawdown_pct)}.`,+ d.by_source.length ? 'By source:' : 'No attributed P&L yet.',+ ...d.by_source.map((b) => (b.is_outflow+ ? `- ${b.label}: spent ${sol(b.spent_sol)} (${usd(b.spent_usd)})`+ : `- ${b.label}: realized ${sol(b.realized_sol)}, unrealized ${sol(b.unrealized_sol)}, ${b.sells} sells`)),+ d.top_winners.length ? `Top open winners: ${d.top_winners.map((h) => `${h.symbol || h.mint} ${sol(h.unrealized_sol)}`).join(', ')}` : null,+ d.top_losers.length ? `Top open losers: ${d.top_losers.map((h) => `${h.symbol || h.mint} ${sol(h.unrealized_sol)}`).join(', ')}` : null,+ ].filter(Boolean);+ return { content: [{ type: 'text', text: lines.join('\n') }], structuredContent: d };+ }),+ },+];diff --git a/api/_mcpagent/sniper-alert-tools.js b/api/_mcpagent/sniper-alert-tools.jsnew file mode 100644index 000000000..eb8e955a7--- /dev/null+++ b/api/_mcpagent/sniper-alert-tools.js@@ -0,0 +1,400 @@+// threews-agent MCP: the launch sniper, signal-feed subscriptions, and pump+// alert rules.+//+// Thin adapters over the stores the human surfaces use, so an agent's change is+// the row the dashboard would have written:+// api/_lib/sniper-control.js /sniper and POST /api/sniper/strategy+// api/_lib/signal-subscription-control.js /signals and POST /api/signals/subscribe+// api/_lib/pump-alert-rules.js /pump-dashboard and /api/alerts/rules+//+// read sniper_status, sniper_activate_preview, alert_rule_list+// write sniper_deactivate, sniper_subscribe (paper mode only),+// alert_rule_create+// financial sniper_activate: arms a strategy that spends SOL from the agent's+// wallet on new launches. Needs confirm_spend: true and a+// preview_id from sniper_activate_preview for the same agent,+// network and sizing, and on mainnet the signed real-funds+// agreement.+// alert_rule_delete: cannot be undone. Needs confirm_delete: true+// and a preview_id from alert_rule_list for the same rule_id.+//+// Alert rules created here deliver to the owner: the bell, Web Push and the+// iOS app, and the Telegram and Discord chats the owner paired, each gated by+// the owner's notification preferences (api/_lib/alert-delivery.js). Webhook+// and per-rule Telegram targets are configured on /pump-dashboard by the owner,+// never by an agent.++import { hasScope } from '../_lib/auth.js';+import { limits } from '../_lib/rate-limit.js';+import { currentSignatureFor, agreementRequirement } from '../_lib/real-funds-agreement.js';+import {+ SNIPER_TRIGGERS, SniperControlError, sniperStatus, previewActivation, activateSniper, deactivateSniper,+} from '../_lib/sniper-control.js';+import {+ SignalSubscriptionError, listSignalSubscriptions, listSubscribableFeeds, loadSignalSubscription,+ loadSubscribableFeed, existingSubscription, subscriptionKnobs, upsertSignalSubscription,+ setSignalSubscriptionStatus, setSignalSubscriptionKilled,+} from '../_lib/signal-subscription-control.js';+import {+ AlertRuleError, MAX_RULES_PER_USER, listAlertRules, createAlertRule, deleteAlertRule,+} from '../_lib/pump-alert-rules.js';+import { describeLaunchFilters, LAUNCH_RISK_FLAGS } from '../_lib/pump-alert-eval.js';+import { RULE_KINDS } from '../alerts/_rules.js';+import { isUuid } from '../_lib/validate.js';+import { sql } from '../_lib/db.js';++// Stored state, no chain reads: the same arguments read the same rows.+const STORED_READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };+// Reads the live wallet balance over RPC, so the answer moves.+const LIVE_READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true };+// Arms a worker that buys launches on chain from the agent's wallet.+const ARM = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true };+// Settings writes that converge: repeating the call leaves the same state.+const SETTLE = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };+// Each call adds a new row.+const CREATE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };+// Removes a row for good; a second call finds nothing to remove.+const DELETE = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };++const TRADE_SCOPES = ['wallet:trade', 'agents:write'];++function refusal(text, reason, extra = {}) {+ return { content: [{ type: 'text', text }], structuredContent: { ok: false, reason, ...extra }, isError: true };+}++async function enforce(auth) {+ const rl = await limits.mcpAgent(auth.userId || auth.rateKey || 'anon');+ if (!rl.success) {+ throw Object.assign(new Error('rate_limited'), { code: -32000, data: { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) } });+ }+}++const anyScope = (granted, scopes) => scopes.some((s) => hasScope(granted, s));++/**+ * Sign-in, scope and error handling shared by every tool here. `scopes` is a+ * list where any one grant suffices. A designed store error becomes a designed+ * tool result; anything else reaches the dispatcher's sanitizer.+ */+async function run(auth, { scopes }, fn) {+ await enforce(auth);+ if (!auth.userId) return refusal('Sign in to three.ws to act on your agents.', 'auth_required', { signed_in: false });+ if (!anyScope(auth.scope, scopes)) {+ return refusal(`This action needs the ${scopes.join(' or ')} scope. Re-authorize with it granted.`, 'insufficient_scope', { required: scopes[0] });+ }+ try {+ return await fn();+ } catch (err) {+ if (err instanceof SniperControlError || err instanceof SignalSubscriptionError || err instanceof AlertRuleError) {+ return refusal(err.message, err.code, err.issues ? { issues: err.issues } : {});+ }+ if (err?.code === 'validation_error' && err.status === 400) {+ return refusal(err.message, 'validation_error', err.issues ? { issues: err.issues } : {});+ }+ throw err;+ }+}++async function requireAgreement(userId) {+ let signed;+ try {+ signed = await currentSignatureFor(userId);+ } catch {+ return refusal('Could not verify your signed real-funds agreements, so nothing was armed. Try again in a moment.', 'agreement_check_unavailable');+ }+ if (signed) return null;+ const r = agreementRequirement();+ return refusal(`Sign the real-funds agreements before arming a mainnet sniper. Nothing was armed. Sign at ${r.sign_url}`, 'risk_ack_required', r);+}++const ok = (lines, structured) => ({ content: [{ type: 'text', text: lines.filter(Boolean).join('\n') }], structuredContent: structured });+const sol = (n) => (n == null ? 'n/a' : `${Number(n).toFixed(4)} SOL`);++const agentIdProp = { type: 'string', format: 'uuid', description: 'The agent whose sniper to act on. wallet_status or three://agents lists yours.' };+const networkProp = { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet', description: 'Solana cluster. devnet arms a strategy with no real funds at risk.' };+const sizingProps = {+ per_trade_sol: { type: 'number', exclusiveMinimum: 0, maximum: 100, description: 'SOL spent on each launch the strategy buys.' },+ daily_budget_sol: { type: 'number', exclusiveMinimum: 0, maximum: 1000, description: 'Most SOL the strategy may commit per UTC day. Must be at least per_trade_sol.' },+ stop_loss_pct: { type: 'number', exclusiveMinimum: 0, maximum: 95, description: 'Mandatory stop loss. Keeps the stored value (30 for a new strategy) when omitted.' },+ take_profit_pct: { type: 'number', exclusiveMinimum: 0, maximum: 10000, description: 'Optional take profit. Keeps the stored value when omitted.' },+ trigger: { type: 'string', enum: SNIPER_TRIGGERS, description: 'What makes a launch a candidate. Keeps the stored trigger (new_mint for a new strategy) when omitted.' },+ max_concurrent_positions: { type: 'integer', minimum: 1, maximum: 50, description: 'Open positions allowed at once.' },+};++function strategyLine(s) {+ const state = s.armed ? 'ARMED' : s.kill_switch ? 'killed' : 'off';+ return `- ${s.agent_name} on ${s.network}: ${state}. ${sol(s.per_trade_sol)} per trade, ${sol(s.daily_budget_sol)} a day (${sol(s.spent_today_sol)} committed today), stop loss ${s.stop_loss_pct}%, trigger ${s.trigger}. Positions: ${s.positions.open} open, ${s.positions.closed} closed, realized ${sol(s.positions.realized_pnl_sol)}.`;+}++function ruleLine(r) {+ const state = r.enabled ? 'on' : 'paused';+ const fired = r.last_fired_at ? `, last fired ${new Date(r.last_fired_at).toISOString()}` : ', never fired';+ return `- [${r.id}] ${r.label || r.kind} (${r.kind}, ${state}${fired})${r.kind === 'launch_match' && r.filters ? `: ${describeLaunchFilters(r.filters)}` : ''}`;+}++function subscriptionLine(s) {+ const state = s.killed ? 'KILLED' : s.status;+ return `- #${s.id} ${s.subscriber_name || s.subscriber_agent_id} follows "${s.feed?.title || s.feed_id}" (${s.mode}, ${state}, ${s.network}), base ${sol(s.base_sol)}, max ${sol(s.max_per_trade_sol)} per trade. Executed ${s.stats?.executed ?? 0}.`;+}++export const sniperAlertToolDefs = [+ {+ name: 'sniper_status',+ title: 'Sniper status',+ group: 'trading',+ tier: 'read',+ annotations: STORED_READ,+ description: "Your agents' launch-sniper strategies: armed or not, sizing, today's committed spend against the daily budget, stop loss and trigger, open and closed positions with realized P&L, and whether the sniper worker is live and on which network. Use this to check whether an agent's sniper is armed and how it is performing.",+ inputSchema: {+ type: 'object',+ properties: { agent_id: { ...agentIdProp, description: 'Narrow to one agent. Omit for every agent you own.' }, network: { type: 'string', enum: ['mainnet', 'devnet'] } },+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { scopes: ['wallet:read', 'wallet:trade'] }, async () => {+ const st = await sniperStatus({ userId: auth.userId, agentId: args.agent_id || null, network: args.network || null });+ const w = st.worker;+ return ok([+ `Sniper worker: ${w.state}${w.network ? ` on ${w.network}` : ''}${w.global_kill ? ' (operator kill switch on)' : ''}.`,+ st.strategies.length ? `${st.armed_count} of ${st.strategies.length} strategies armed:` : 'No sniper strategies yet. sniper_activate_preview shows what arming one would do.',+ ...st.strategies.map(strategyLine),+ ], st);+ }),+ },+ {+ name: 'sniper_activate_preview',+ title: 'Preview arming the sniper',+ group: 'trading',+ tier: 'read',+ annotations: LIVE_READ,+ description: "What sniper_activate would arm, without writing anything: the agent and its wallet with its live SOL balance, the per-trade size and daily budget, the trigger and exits, what the SOL is spent on, whether real funds are at risk, and every check that would block it. Show this to the user before arming. Call this before sniper_activate, every time.",+ inputSchema: {+ type: 'object',+ properties: { agent_id: agentIdProp, network: networkProp, ...sizingProps },+ required: ['agent_id', 'per_trade_sol', 'daily_budget_sol'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { scopes: ['wallet:read', 'wallet:trade'] }, async () => {+ const network = args.network || 'mainnet';+ const p = await previewActivation({ userId: auth.userId, agentId: args.agent_id, network, input: args });+ return ok([+ `Arm the ${p.trigger} sniper for ${p.agent.name} on Solana ${network}${p.real_funds ? ' (REAL FUNDS)' : ' (devnet, no real funds)'}.`,+ `Spends: up to ${sol(p.per_trade_sol)} per launch and ${sol(p.daily_budget_sol)} per UTC day, in ${p.asset}, from the agent wallet ${p.agent.wallet || '(none yet)'}.`,+ `Recipient: ${p.recipient}.`,+ `Exits: stop loss ${p.stop_loss_pct}%${p.take_profit_pct != null ? `, take profit ${p.take_profit_pct}%` : ''}. Up to ${p.max_concurrent_positions} open at once. Fires on ${p.trigger_description}.`,+ `Wallet balance: ${p.wallet_sol == null ? 'unreadable right now' : sol(p.wallet_sol)}.`,+ 'Checks:',+ ...p.checks.map((c) => ` ${c.ok ? '[ok]' : '[blocked]'} ${c.label}`),+ p.executable ? null : `Blocked by: ${p.blocked_by.join(', ')}. Fix that before arming.`,+ ], p);+ }),+ },+ {+ name: 'sniper_activate',+ title: 'Arm the sniper',+ group: 'trading',+ tier: 'financial',+ confirmFlag: 'confirm_spend',+ previewTool: 'sniper_activate_preview',+ annotations: ARM,+ description: "Arm one of your agents' launch sniper with the sizing sniper_activate_preview showed: the worker then buys launches that pass the strategy's filters from the agent's own wallet, inside the daily budget, with a mandatory stop loss. Only the previewed knobs change; every other dashboard setting keeps its stored value. Mainnet needs your signed real-funds agreement. Treasury auto-funding is never switched on here. Call this after the owner approved what sniper_activate_preview showed.",+ inputSchema: {+ type: 'object',+ properties: { agent_id: agentIdProp, network: networkProp, ...sizingProps },+ required: ['agent_id', 'per_trade_sol', 'daily_budget_sol'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { scopes: TRADE_SCOPES }, async () => {+ const network = args.network || 'mainnet';+ if (network === 'mainnet') {+ const blocked = await requireAgreement(auth.userId);+ if (blocked) return blocked;+ }+ const s = await activateSniper({ userId: auth.userId, agentId: args.agent_id, network, input: args });+ return ok([+ `Armed. ${s.agent_name} snipes ${s.trigger} launches on Solana ${network} with ${sol(s.per_trade_sol)} per trade and ${sol(s.daily_budget_sol)} a day, stop loss ${s.stop_loss_pct}%.`,+ 'sniper_status shows its positions; sniper_deactivate disarms it at any time.',+ ], { ok: true, strategy: s });+ }),+ },+ {+ name: 'sniper_deactivate',+ title: 'Disarm the sniper',+ group: 'trading',+ tier: 'write',+ annotations: SETTLE,+ description: "Disarm one of your agents' launch sniper so it opens no new positions. With kill: true the kill switch is set as well, which the dashboard shows and a later arm clears. Open positions keep their stop loss and exits. Repeating the call is harmless. Use this when the owner wants the sniper to stop buying, or with kill: true to stop it hard.",+ inputSchema: {+ type: 'object',+ properties: { agent_id: agentIdProp, network: networkProp, kill: { type: 'boolean', default: false, description: 'Also set the kill switch.' } },+ required: ['agent_id'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { scopes: TRADE_SCOPES }, async () => {+ const network = args.network || 'mainnet';+ const s = await deactivateSniper({ userId: auth.userId, agentId: args.agent_id, network, kill: args.kill === true });+ if (!s.existed) return ok([`No ${network} sniper strategy exists for that agent, so there is nothing to disarm.`], { ok: true, ...s });+ return ok([`Disarmed ${s.agent_name} on ${network}${s.kill_switch ? ' and set the kill switch' : ''}. ${s.positions.open} positions remain open under their exits.`], { ok: true, strategy: s });+ }),+ },+ {+ name: 'sniper_subscribe',+ title: 'Follow a signal feed',+ group: 'trading',+ tier: 'write',+ annotations: SETTLE,+ description: "Copy another agent's published trade signals. action 'list' shows your subscriptions and the active public feeds you could follow. 'subscribe' starts (or updates) a paper-mode subscription for one of your agents: it mirrors the feed's entries and exits on paper with your sizing, paying nothing and trading nothing, so you can judge the feed first. 'pause', 'resume', 'stop' and 'kill' control an existing subscription. Live mode, which pays the feed in USDC and trades real funds, is switched on by the owner on /signals. Use this when the owner wants an agent to follow another trader's signals, starting on paper.",+ inputSchema: {+ type: 'object',+ properties: {+ action: { type: 'string', enum: ['list', 'subscribe', 'pause', 'resume', 'stop', 'kill'], default: 'list' },+ agent_id: { ...agentIdProp, description: 'subscribe: the agent that follows the feed.' },+ feed_id: { type: 'integer', minimum: 1, description: 'subscribe: the feed to follow (list shows them).' },+ subscription_id: { type: 'integer', minimum: 1, description: 'pause, resume, stop, kill: the subscription to change.' },+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet', description: 'list: which feeds to show.' },+ base_sol: { type: 'number', minimum: 0.001, maximum: 10, description: 'Paper size of a 1x signal, in SOL.' },+ size_scaling: { type: 'number', minimum: 0.01, maximum: 20, description: 'Multiplier on the publisher\'s conviction.' },+ max_per_trade_sol: { type: 'number', minimum: 0.001, maximum: 50, description: 'Cap on any single mirrored entry.' },+ copy_exits: { type: 'boolean', default: true, description: 'Mirror the publisher\'s exits too.' },+ },+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { scopes: TRADE_SCOPES }, async () => {+ const action = args.action || 'list';+ const userId = auth.userId;+ if (action === 'list') {+ const [subscriptions, feeds] = await Promise.all([+ listSignalSubscriptions(userId),+ listSubscribableFeeds({ network: args.network || 'mainnet', limit: 20 }),+ ]);+ return ok([+ subscriptions.length ? `Your subscriptions (${subscriptions.length}):` : 'No subscriptions yet.',+ ...subscriptions.map(subscriptionLine),+ feeds.length ? `Active public feeds on ${args.network || 'mainnet'}:` : `No public feeds are publishing on ${args.network || 'mainnet'} right now. Feeds appear on /signals as agents publish them.`,+ ...feeds.map((f) => `- feed ${f.id} "${f.title}" by ${f.publisher_name}: ${f.price_per_signal_usdc} USDC per signal live, ${f.subscribers} followers (${f.url})`),+ ], { subscriptions, feeds });+ }+ if (action === 'subscribe') {+ if (!isUuid(args.agent_id || '')) return refusal('subscribe needs agent_id, the agent that follows the feed.', 'invalid_agent');+ if (!args.feed_id) return refusal('subscribe needs feed_id. action "list" shows the feeds you can follow.', 'invalid_feed');+ const { owns, name } = await ownsAgent(userId, args.agent_id);+ if (!owns) return refusal('That agent is not one of yours.', 'not_your_agent');+ const feed = await loadSubscribableFeed(args.feed_id, args.agent_id);+ const current = await existingSubscription(args.agent_id, feed.id);+ if (current?.mode === 'live' && current.status !== 'stopped') {+ return refusal(`${name} already follows this feed live. Change a live subscription on /signals.`, 'live_subscription_exists', { subscription_id: Number(current.id) });+ }+ const subscription = await upsertSignalSubscription({ userId, agentId: args.agent_id, feed, knobs: subscriptionKnobs({ ...args, mode: 'simulate' }) });+ return ok([+ `${name} now follows "${feed.title}" on paper (#${subscription.id}): base ${sol(subscription.base_sol)}, max ${sol(subscription.max_per_trade_sol)} per trade, exits ${subscription.copy_exits ? 'copied' : 'not copied'}.`,+ 'Nothing is paid and nothing trades in paper mode. The owner can switch it live on /signals.',+ ], { ok: true, subscription, feed: { id: Number(feed.id), slug: feed.slug, title: feed.title, url: `/signals/${feed.slug}` } });+ }+ if (!args.subscription_id) return refusal(`${action} needs subscription_id. action "list" shows yours.`, 'invalid_id');+ const current = await loadSignalSubscription(args.subscription_id, userId);+ if (!current) return refusal('No subscription with that id is yours.', 'not_found');+ if (action === 'kill') {+ const subscription = await setSignalSubscriptionKilled({ userId, subId: args.subscription_id, killed: true });+ return ok([`Killed subscription #${subscription.id}. Nothing further is paid or mirrored.`], { ok: true, subscription });+ }+ if (action === 'resume' && current.mode === 'live') {+ return refusal('This is a live subscription, which pays and trades real funds. Resume it on /signals, where the real-funds agreement is checked.', 'live_resume_requires_owner', { subscription_id: Number(current.id) });+ }+ const status = action === 'resume' ? 'active' : action === 'stop' ? 'stopped' : 'paused';+ const subscription = await setSignalSubscriptionStatus({ userId, subId: args.subscription_id, status });+ return ok([`Subscription #${subscription.id} is now ${subscription.status}.`], { ok: true, subscription });+ }),+ },+ {+ name: 'alert_rule_create',+ title: 'Create an alert rule',+ group: 'intelligence',+ tier: 'write',+ annotations: CREATE,+ description: `Create a pump.fun alert rule that notifies you (the bell, push to your devices, and the Telegram or Discord chats you paired, per your notification preferences). Kinds: launch_match (a new launch passing filters: name_pattern with * and | wildcards, market cap band in USD, min_safety_score 0 to 100, creator history, excluded risk flags, required socials), new_mint, graduation (target_mint or target_agent), price_above and price_below (target_mint + threshold in USD), whale_buy (target_mint + threshold in SOL), market_price (target_market + target_side + direction + threshold probability). Up to ${MAX_RULES_PER_USER} rules. Use this when the user wants to hear about a launch, a graduation, a price level or a whale buy without trading.`,+ inputSchema: {+ type: 'object',+ properties: {+ kind: { type: 'string', enum: RULE_KINDS },+ label: { type: 'string', maxLength: 80 },+ filters: {+ type: 'object',+ description: 'launch_match only. Set at least one.',+ properties: {+ name_pattern: { type: 'string', maxLength: 120, description: 'Matched against name and symbol, case-insensitive. * is any text, | separates alternatives: "*cat*|*dog*".' },+ min_market_cap_usd: { type: 'number', minimum: 0 },+ max_market_cap_usd: { type: 'number', minimum: 0 },+ min_safety_score: { type: 'number', minimum: 0, maximum: 100, description: 'Coin intel quality score.' },+ min_creator_graduated: { type: 'integer', minimum: 0, description: 'The creator\'s earlier launches that graduated.' },+ max_creator_launches: { type: 'integer', minimum: 0, description: 'Skip serial launchers with more earlier launches than this.' },+ exclude_risk_flags: { type: 'array', items: { type: 'string', enum: LAUNCH_RISK_FLAGS } },+ require_socials: { type: 'boolean' },+ },+ additionalProperties: false,+ },+ target_mint: { type: 'string', maxLength: 64 },+ target_agent: { type: 'string', format: 'uuid' },+ target_market: { type: 'string', maxLength: 128 },+ target_side: { type: 'string', enum: ['yes', 'no'] },+ direction: { type: 'string', enum: ['above', 'below'] },+ threshold: { type: 'number', exclusiveMinimum: 0 },+ cooldown_seconds: { type: 'integer', minimum: 5, maximum: 86400, default: 300 },+ },+ required: ['kind'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { scopes: TRADE_SCOPES }, async () => {+ const rule = await createAlertRule(auth.userId, { ...args, deliver_in_app: true, enabled: true });+ return ok([+ `Created alert rule ${rule.id}: ${rule.label || rule.kind}${rule.kind === 'launch_match' ? ` (${describeLaunchFilters(rule.filters)})` : ''}.`,+ 'It notifies you in the bell, by push, and in your paired chats, per your notification preferences. Webhooks are set on /pump-dashboard.',+ ], { ok: true, rule });+ }),+ },+ {+ name: 'alert_rule_list',+ title: 'List alert rules',+ group: 'intelligence',+ tier: 'read',+ annotations: STORED_READ,+ description: 'Your pump.fun alert rules, newest first: kind, filters or target, whether each is on, when it last fired, and its recent delivery results. Pass rule_id to read one rule (and to get the preview_id alert_rule_delete needs). Call this first to find a rule id, and before alert_rule_delete.',+ inputSchema: {+ type: 'object',+ properties: { rule_id: { type: 'string', format: 'uuid' } },+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { scopes: ['wallet:read', ...TRADE_SCOPES] }, async () => {+ const rules = await listAlertRules(auth.userId, { ruleId: args.rule_id || null });+ if (args.rule_id && !rules.length) return refusal('No alert rule with that id is yours.', 'not_found');+ return ok([+ rules.length ? `${rules.length} alert rule${rules.length === 1 ? '' : 's'}:` : 'No alert rules yet. alert_rule_create adds one.',+ ...rules.map(ruleLine),+ ], { rules, max_rules: MAX_RULES_PER_USER });+ }),+ },+ {+ name: 'alert_rule_delete',+ title: 'Delete an alert rule',+ group: 'intelligence',+ tier: 'financial',+ confirmFlag: 'confirm_delete',+ previewTool: 'alert_rule_list',+ annotations: DELETE,+ description: 'Delete one of your alert rules and its delivery history. This cannot be undone. Call alert_rule_list with the rule_id first and show the user the rule. Use this when the user no longer wants a rule\'s notifications.',+ inputSchema: {+ type: 'object',+ properties: { rule_id: { type: 'string', format: 'uuid' } },+ required: ['rule_id'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, { scopes: TRADE_SCOPES }, async () => {+ const id = await deleteAlertRule(auth.userId, args.rule_id);+ if (!id) return refusal('No alert rule with that id is yours. It may already be deleted.', 'not_found');+ return ok([`Deleted alert rule ${id}.`], { ok: true, deleted: id });+ }),+ },+];++async function ownsAgent(userId, agentId) {+ const [row] = await sql`select name from agent_identities where id = ${agentId} and user_id = ${userId} and deleted_at is null`;+ return { owns: !!row, name: row?.name || null };+}diff --git a/api/alerts/_rules.js b/api/alerts/_rules.jsindex b42545dab..90b064fd3 100644--- a/api/alerts/_rules.js+++ b/api/alerts/_rules.js@@ -4,9 +4,25 @@import { z } from 'zod';import { isValidSolanaAddress, isUuid } from '../_lib/validate.js';-import { MINT_TARGETED_KINDS, AGENT_TARGETED_KINDS, MARKET_TARGETED_KINDS, THRESHOLD_KINDS, deriveRuleLabel } from '../_lib/pump-alert-eval.js';+import { MINT_TARGETED_KINDS, AGENT_TARGETED_KINDS, MARKET_TARGETED_KINDS, THRESHOLD_KINDS, FILTER_KINDS, LAUNCH_FILTER_KEYS, LAUNCH_RISK_FLAGS, deriveRuleLabel } from '../_lib/pump-alert-eval.js';-export const RULE_KINDS = ['graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint', 'market_price'];+export const RULE_KINDS = ['graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint', 'market_price', 'launch_match'];++// launch_match: a new pump.fun launch scored by coin intel that passes every+// filter set here (api/_lib/pump-alert-eval.js launchMatchesRule).+const usdBound = z.coerce.number().min(0).max(1e12);+export const launchFiltersSchema = z+ .object({+ name_pattern: z.string().trim().min(1).max(120).optional(),+ min_market_cap_usd: usdBound.optional(),+ max_market_cap_usd: usdBound.optional(),+ min_safety_score: z.coerce.number().min(0).max(100).optional(),+ min_creator_graduated: z.coerce.number().int().min(0).max(1000).optional(),+ max_creator_launches: z.coerce.number().int().min(0).max(100_000).optional(),+ exclude_risk_flags: z.array(z.enum(LAUNCH_RISK_FLAGS)).max(LAUNCH_RISK_FLAGS.length).optional(),+ require_socials: z.boolean().optional(),+ })+ .strict();const telegramChat = z.string()@@ -60,6 +76,7 @@ const baseShape = {cooldown_seconds: z.coerce.number().int().min(5).max(86_400).optional(),enabled: z.boolean().optional(),label: z.string().trim().max(80).nullable().optional(),+ filters: launchFiltersSchema.nullable().optional(),};/** Cross-field rules shared by create (strict) and update (after merge). */@@ -102,6 +119,19 @@ function refineRule(v, ctx) {if (v.kind === 'graduation' && v.target_mint && v.target_agent) {ctx.addIssue({ code: 'custom', path: ['target_agent'], message: 'set either target_mint or target_agent, not both' });}+ if (FILTER_KINDS.includes(v.kind)) {+ const f = v.filters || {};+ const set = LAUNCH_FILTER_KEYS.filter((k) => f[k] != null && f[k] !== false && !(Array.isArray(f[k]) && !f[k].length));+ if (!set.length) {+ ctx.addIssue({ code: 'custom', path: ['filters'], message: `${v.kind} needs at least one filter (${LAUNCH_FILTER_KEYS.join(', ')})` });+ }+ if (f.min_market_cap_usd != null && f.max_market_cap_usd != null && Number(f.min_market_cap_usd) > Number(f.max_market_cap_usd)) {+ ctx.addIssue({ code: 'custom', path: ['filters', 'min_market_cap_usd'], message: 'min_market_cap_usd cannot exceed max_market_cap_usd' });+ }+ if (v.target_mint || v.target_agent) {+ ctx.addIssue({ code: 'custom', path: ['kind'], message: `${v.kind} matches every new launch; it takes filters, not a target` });+ }+ }if (THRESHOLD_KINDS.includes(v.kind) && !(Number(v.threshold) > 0)) {ctx.addIssue({ code: 'custom', path: ['threshold'], message: `${v.kind} requires a positive threshold` });}@@ -153,6 +183,7 @@ export function validateUpdate(current, patch) {cooldown_seconds: 'cooldown_seconds' in patch ? patch.cooldown_seconds : current.cooldown_seconds,enabled: 'enabled' in patch ? patch.enabled : current.enabled,label: 'label' in patch ? patch.label : current.label,+ filters: 'filters' in patch ? patch.filters : current.filters,};// Normalize first so fields incompatible with the (possibly new) kind are// cleared before validation — e.g. switching to new_mint drops a stale@@ -188,6 +219,8 @@ export function normalizeForKind(v) {out.target_side = null;out.direction = null;}+ if (!FILTER_KINDS.includes(out.kind)) out.filters = null;+ else if (out.filters) out.filters = Object.fromEntries(Object.entries(out.filters).filter(([, val]) => val != null));if (out.deliver_in_app === undefined) out.deliver_in_app = true;if (out.cooldown_seconds === undefined) out.cooldown_seconds = 300;if (out.enabled === undefined) out.enabled = true;@@ -205,6 +238,7 @@ export function serializeRule(row) {target_side: row.target_side || null,direction: row.direction || null,threshold: row.threshold != null ? Number(row.threshold) : null,+ filters: row.filters || null,deliver_in_app: row.deliver_in_app,webhook_url: row.webhook_url || null,webhook_secret: row.webhook_secret || null,diff --git a/api/alerts/rules.js b/api/alerts/rules.jsindex b2866335d..0852c7d91 100644--- a/api/alerts/rules.js+++ b/api/alerts/rules.js@@ -6,16 +6,11 @@// across devices even with no dashboard tab open. The frontend treats// localStorage as a render cache only; these endpoints are the source of truth.-import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';-import { parse } from '../_lib/validate.js';-import { randomToken } from '../_lib/crypto.js';-import { createRuleSchema, normalizeForKind, rulesMissingWebhookSecret, serializeRule } from './_rules.js';--const MAX_RULES_PER_USER = 50;+import { listAlertRules, createAlertRule, AlertRuleError } from '../_lib/pump-alert-rules.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;@@ -27,102 +22,18 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {const rl = await limits.notificationsRead(user.id);if (!rl.success) return rateLimited(res, rl);- const rows = await listRules(user.id);- await healWebhookSecrets(rows);- return json(res, 200, { rules: rows.map(serializeRule) });+ return json(res, 200, { rules: await listAlertRules(user.id) });}- // POST — create+ // POST: createconst rl = await limits.prefsWrite(user.id);if (!rl.success) return rateLimited(res, rl);if (!(await requireCsrf(req, res, user.id))) return;- const body = normalizeForKind(parse(createRuleSchema, await readJson(req)));-- if (body.target_agent) {- const [agent] = await sql`SELECT 1 AS ok FROM agent_identities WHERE id = ${body.target_agent}`;- if (!agent) return error(res, 400, 'validation_error', 'target_agent does not exist');+ try {+ return json(res, 201, { rule: await createAlertRule(user.id, await readJson(req)) });+ } catch (err) {+ if (err instanceof AlertRuleError) return error(res, err.status, err.code, err.message);+ throw err;}-- const [{ count }] = await sql`SELECT count(*)::int AS count FROM pump_alert_rules WHERE user_id = ${user.id}`;- if (count >= MAX_RULES_PER_USER) {- return error(res, 409, 'limit_reached', `you can have at most ${MAX_RULES_PER_USER} alert rules`);- }-- // Generate a per-rule signing secret when a webhook is configured so the- // receiver can verify the webhook-signature header.- const webhookSecret = body.webhook_url ? `whsec_${randomToken(24)}` : null;-- const [row] = await sql`- INSERT INTO pump_alert_rules- (user_id, kind, target_mint, target_agent, target_market, target_side, direction,- threshold, deliver_in_app,- webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, label)- VALUES- (${user.id}, ${body.kind}, ${body.target_mint || null}, ${body.target_agent || null},- ${body.target_market || null}, ${body.target_side || null}, ${body.direction || null},- ${body.threshold ?? null}, ${body.deliver_in_app}, ${body.webhook_url || null},- ${webhookSecret}, ${body.telegram_chat || null}, ${body.cooldown_seconds},- ${body.enabled}, ${body.label || null})- RETURNING id, kind, target_mint, target_agent, target_market, target_side, direction,- threshold, deliver_in_app,- webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled,- label, created_at, updated_at- `;-- return json(res, 201, { rule: serializeRule({ ...row, last_fired_at: null, recent_failures: 0, recent_deliveries: [] }) });});--/**- * Back-fill a signing secret for any listed rule that has a webhook but none,- * mutating the rows in place so the caller serializes the healed value. Those- * rules deliver unsigned webhooks until this runs, and this list response is- * where the user reads the secret to configure verification on their receiver.- * Costs nothing in the normal case: the scan is in-memory and issues no query- * unless a rule is actually missing its secret.- */-async function healWebhookSecrets(rows) {- for (const row of rulesMissingWebhookSecret(rows)) {- const secret = `whsec_${randomToken(24)}`;- const [updated] = await sql`- UPDATE pump_alert_rules SET webhook_secret = ${secret}, updated_at = now()- WHERE id = ${row.id} AND webhook_secret IS NULL- RETURNING webhook_secret, updated_at- `;- if (updated) {- row.webhook_secret = updated.webhook_secret;- row.updated_at = updated.updated_at;- }- }-}--async function listRules(userId) {- return sql`- SELECT r.id, r.kind, r.target_mint, r.target_agent, r.target_market, r.target_side,- r.direction, r.threshold,- r.deliver_in_app, r.webhook_url, r.webhook_secret, r.telegram_chat,- r.cooldown_seconds, r.enabled, r.label, r.created_at, r.updated_at,- f.last_fired_at,- coalesce(fail.cnt, 0) AS recent_failures,- coalesce(rd.deliveries, '[]'::json) AS recent_deliveries- FROM pump_alert_rules r- LEFT JOIN pump_alert_rule_fires f ON f.rule_id = r.id- LEFT JOIN LATERAL (- SELECT count(*)::int AS cnt- FROM pump_alert_deliveries d- WHERE d.rule_id = r.id AND d.ok = false AND d.created_at > now() - interval '24 hours'- ) fail ON true- LEFT JOIN LATERAL (- SELECT json_agg(json_build_object('channel', s.channel, 'ok', s.ok, 'detail', s.detail, 'at', s.created_at) ORDER BY s.created_at DESC) AS deliveries- FROM (- SELECT channel, ok, detail, created_at- FROM pump_alert_deliveries d2- WHERE d2.rule_id = r.id- ORDER BY created_at DESC- LIMIT 5- ) s- ) rd ON true- WHERE r.user_id = ${userId}- ORDER BY r.created_at DESC- `;-}diff --git a/api/alerts/rules/[id].js b/api/alerts/rules/[id].jsindex dae9c0c36..e942e32b8 100644--- a/api/alerts/rules/[id].js+++ b/api/alerts/rules/[id].js@@ -4,14 +4,12 @@// Part of the server-side multi-rule alert model (Task 04). Ownership is// enforced on every operation: a user can only touch their own rules.-import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';import { requireCsrf } from '../../_lib/csrf.js';import { limits } from '../../_lib/rate-limit.js';-import { parse, isUuid } from '../../_lib/validate.js';-import { randomToken } from '../../_lib/crypto.js';-import { updateRuleSchema, validateUpdate, serializeRule } from '../_rules.js';+import { isUuid } from '../../_lib/validate.js';+import { updateAlertRule, deleteAlertRule, AlertRuleError } from '../../_lib/pump-alert-rules.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'PATCH,DELETE,OPTIONS', credentials: true })) return;@@ -28,88 +26,17 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, user.id))) return;if (req.method === 'DELETE') {- const [row] = await sql`- DELETE FROM pump_alert_rules WHERE id = ${id} AND user_id = ${user.id} RETURNING id- `;- if (!row) return error(res, 404, 'not_found', 'rule not found');- return json(res, 200, { ok: true, id: row.id });+ const deleted = await deleteAlertRule(user.id, id);+ if (!deleted) return error(res, 404, 'not_found', 'rule not found');+ return json(res, 200, { ok: true, id: deleted });}- // PATCH- const [current] = await sql`- SELECT id, kind, target_mint, target_agent, target_market, target_side, direction,- threshold, deliver_in_app,- webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, label- FROM pump_alert_rules- WHERE id = ${id} AND user_id = ${user.id}- `;- if (!current) return error(res, 404, 'not_found', 'rule not found');-- const patch = parse(updateRuleSchema, await readJson(req));- const result = validateUpdate(current, patch);- if (!result.ok) {- return error(res, 400, 'validation_error', result.message, { issues: result.issues });- }- const next = result.value;-- if (next.target_agent && next.target_agent !== current.target_agent) {- const [agent] = await sql`SELECT 1 AS ok FROM agent_identities WHERE id = ${next.target_agent}`;- if (!agent) return error(res, 400, 'validation_error', 'target_agent does not exist');+ try {+ const rule = await updateAlertRule(user.id, id, await readJson(req));+ if (!rule) return error(res, 404, 'not_found', 'rule not found');+ return json(res, 200, { rule });+ } catch (err) {+ if (err instanceof AlertRuleError) return error(res, err.status, err.code, err.message, err.issues ? { issues: err.issues } : undefined);+ throw err;}-- // Webhook secret lifecycle: mint one when a webhook is newly configured,- // drop it when the webhook is removed, otherwise keep the existing secret.- let webhookSecret = current.webhook_secret;- if (!next.webhook_url) webhookSecret = null;- else if (!current.webhook_url || !current.webhook_secret) webhookSecret = `whsec_${randomToken(24)}`;-- await sql`- UPDATE pump_alert_rules SET- kind = ${next.kind},- target_mint = ${next.target_mint || null},- target_agent = ${next.target_agent || null},- target_market = ${next.target_market || null},- target_side = ${next.target_side || null},- direction = ${next.direction || null},- threshold = ${next.threshold ?? null},- deliver_in_app = ${next.deliver_in_app},- webhook_url = ${next.webhook_url || null},- webhook_secret = ${webhookSecret},- telegram_chat = ${next.telegram_chat || null},- cooldown_seconds = ${next.cooldown_seconds},- enabled = ${next.enabled},- label = ${next.label || null},- updated_at = now()- WHERE id = ${id} AND user_id = ${user.id}- `;-- const [row] = await sql`- SELECT r.id, r.kind, r.target_mint, r.target_agent, r.target_market, r.target_side,- r.direction, r.threshold,- r.deliver_in_app, r.webhook_url, r.webhook_secret, r.telegram_chat,- r.cooldown_seconds, r.enabled, r.label, r.created_at, r.updated_at,- f.last_fired_at,- coalesce(fail.cnt, 0) AS recent_failures,- coalesce(rd.deliveries, '[]'::json) AS recent_deliveries- FROM pump_alert_rules r- LEFT JOIN pump_alert_rule_fires f ON f.rule_id = r.id- LEFT JOIN LATERAL (- SELECT count(*)::int AS cnt FROM pump_alert_deliveries d- WHERE d.rule_id = r.id AND d.ok = false AND d.created_at > now() - interval '24 hours'- ) fail ON true- LEFT JOIN LATERAL (- SELECT json_agg(json_build_object('channel', s.channel, 'ok', s.ok, 'detail', s.detail, 'at', s.created_at) ORDER BY s.created_at DESC) AS deliveries- FROM (- SELECT channel, ok, detail, created_at FROM pump_alert_deliveries d2- WHERE d2.rule_id = r.id ORDER BY created_at DESC LIMIT 5- ) s- ) rd ON true- WHERE r.id = ${id} AND r.user_id = ${user.id}- `;- // The row can be gone by now if a concurrent DELETE landed between the UPDATE- // and this read. Serializing `undefined` would throw and surface as a 500 on- // what is really a plain "it's not there anymore".- if (!row) return error(res, 404, 'not_found', 'rule not found');-- return json(res, 200, { rule: serializeRule(row) });});diff --git a/api/cron/agent-portfolio-snapshots.js b/api/cron/agent-portfolio-snapshots.jsnew file mode 100644index 000000000..3eb40a53d--- /dev/null+++ b/api/cron/agent-portfolio-snapshots.js@@ -0,0 +1,40 @@+// GET /api/cron/agent-portfolio-snapshots: hourly net-worth valuations for+// recently active agents, the background half of the balance history that+// get_balance_history and /api/v1/agents/:id/portfolio/history read+// (api/_lib/portfolio-history.js).+//+// Agents that traded, moved funds or had their portfolio read in the last week+// are valued least-recently-snapshotted first, a capped batch per run, so the+// sweep rotates through all of them without one run holding the RPC for long.+// Read-only against chain state: it values wallets and never signs anything.++import { json, method, wrapCron } from '../_lib/http.js';+import { requireCron } from '../_lib/cron-auth.js';+import { agentsDueForSnapshot, portfolioWithSnapshot } from '../_lib/portfolio-history.js';++const BATCH = 40;+const CONCURRENCY = 4;++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const due = await agentsDueForSnapshot({ limit: BATCH });+ let recorded = 0;+ let failed = 0;+ const queue = [...due];+ async function worker() {+ while (queue.length) {+ const { agent_id: agentId, network } = queue.shift();+ try {+ const p = await portfolioWithSnapshot({ agentId, network, source: 'cron' });+ if (p) recorded += 1;+ } catch (e) {+ failed += 1;+ console.warn('[cron/agent-portfolio-snapshots] valuation failed', agentId, e?.message);+ }+ }+ }+ await Promise.all(Array.from({ length: CONCURRENCY }, worker));+ return json(res, 200, { ok: true, due: due.length, recorded, failed });+});diff --git a/api/cron/duels-tick.js b/api/cron/duels-tick.jsindex 030d2bb1b..7bb396f77 100644--- a/api/cron/duels-tick.js+++ b/api/cron/duels-tick.js@@ -3,17 +3,20 @@// Each tick voids duels whose trader went private or was deleted (refunding// every call), resolves duels whose window closed more than the grace period// ago from the realized P&L ledger, settles any call a crashed tick left open,-// and opens duels for the next windows from the rivalry engine. Points only:+// opens duels for the next windows from the rivalry engine, and expires agent+// duel challenges nobody answered in time (api/_lib/duel-challenges.js). Points only:// nothing here can move a token or touch a wallet.import { json, method, wrapCron } from '../_lib/http.js';import { requireCron } from '../_lib/cron-auth.js';import { runDuelsTick } from '../_lib/trader-duels.js';+import { expireChallenges } from '../_lib/duel-challenges.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;+ const challenges_expired = await expireChallenges();const result = await runDuelsTick({ network: 'mainnet' });- return json(res, 200, { ok: true, ...result });+ return json(res, 200, { ok: true, ...result, challenges_expired });});diff --git a/api/signals/subscribe.js b/api/signals/subscribe.jsindex 74e35cc48..6f030e1df 100644--- a/api/signals/subscribe.js+++ b/api/signals/subscribe.js@@ -21,69 +21,18 @@ import { requireCsrf } from '../_lib/csrf.js';import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';import { sql } from '../_lib/db.js';import { deliverSubscription } from '../_lib/signal-engine.js';+import {+ SignalSubscriptionError, isLiveRunning, listSignalSubscriptions, loadSignalSubscription as loadSub,+ loadSubscribableFeed, existingSubscription, subscriptionKnobs, upsertSignalSubscription,+ setSignalSubscriptionStatus, setSignalSubscriptionKilled,+} from '../_lib/signal-subscription-control.js';import { requireUser, loadOwnedAgent, normNetwork, parseRowId } from './_common.js';// A live subscription pays x402 USDC and mirrors trades from the subscriber// agent's custodial wallet. Turning one on (or delivering it now) needs the// signed real-funds agreement; simulate mode, pause, stop and kill never do.-function isLiveRunning(row) {- return !!row && row.mode === 'live' && row.status === 'active' && row.killed !== true;-}--async function loadSub(subId, userId) {- const [row] = await sql`select * from signal_subscriptions where id = ${subId} and owner_user_id = ${userId} limit 1`;- return row || null;-}--function num(v, fallback) { const n = Number(v); return Number.isFinite(n) ? n : fallback; }--function shapeSub(s) {- return {- id: Number(s.id),- subscriber_agent_id: s.subscriber_agent_id,- feed_id: Number(s.feed_id),- network: s.network,- mode: s.mode,- billing: s.billing,- base_sol: num(s.base_sol, 0),- size_scaling: num(s.size_scaling, 1),- max_per_trade_sol: num(s.max_per_trade_sol, 0),- slippage_bps: num(s.slippage_bps, 300),- firewall_level: s.firewall_level,- copy_exits: s.copy_exits,- status: s.status,- killed: s.killed,- epoch_paid_until: s.epoch_paid_until || null,- last_emission_id: Number(s.last_emission_id || 0),- created_at: s.created_at,- updated_at: s.updated_at,- };-}--async function listForUser(userId) {- const rows = await sql`- select s.*, f.slug as feed_slug, f.title as feed_title,- f.price_per_signal_usdc, f.price_per_epoch_usdc, f.epoch_seconds,- a.name as publisher_name, a.profile_image_url as publisher_image, a.avatar_url as publisher_avatar,- sub.name as subscriber_name,- (select count(*) from signal_deliveries d where d.subscription_id = s.id and d.mirror_status = 'executed') as executed,- (select count(*) from signal_deliveries d where d.subscription_id = s.id and d.payment_status = 'paid') as paid_count,- (select coalesce(sum(d.payment_usdc),0) from signal_deliveries d where d.subscription_id = s.id and d.payment_status = 'paid') as usdc_spent- from signal_subscriptions s- join signal_feeds f on f.id = s.feed_id- join agent_identities a on a.id = f.publisher_agent_id- join agent_identities sub on sub.id = s.subscriber_agent_id- where s.owner_user_id = ${userId}- order by s.created_at desc- `;- return rows.map((s) => ({- ...shapeSub(s),- feed: { slug: s.feed_slug, title: s.feed_title, publisher_name: s.publisher_name, publisher_image: s.publisher_image || s.publisher_avatar || null,- price_per_signal_usdc: num(s.price_per_signal_usdc, 0), price_per_epoch_usdc: num(s.price_per_epoch_usdc, 0), epoch_seconds: num(s.epoch_seconds, 86400) },- subscriber_name: s.subscriber_name,- stats: { executed: Number(s.executed) || 0, paid_count: Number(s.paid_count) || 0, usdc_spent: Number(s.usdc_spent) || 0 },- }));-}+// The store itself (api/_lib/signal-subscription-control.js) is shared with the+// threews-agent MCP tool sniper_subscribe.export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;@@ -97,7 +46,7 @@ export default wrap(async (req, res) => {const { userId } = auth;if (req.method === 'GET') {- return json(res, 200, { subscriptions: await listForUser(userId) });+ return json(res, 200, { subscriptions: await listSignalSubscriptions(userId) });}if (auth.viaSession && !(await requireCsrf(req, res, userId))) return;@@ -127,15 +76,12 @@ export default wrap(async (req, res) => {const cur = await loadSub(subId, userId);if (cur?.mode === 'live' && !isLiveRunning(cur) && !(await requireRealFundsAgreement(req, res, { userId, network: normNetwork(cur.network), context: 'signal-subscribe' }))) return;}- const [row] = await sql`- update signal_subscriptions set killed = ${killed}, status = ${killed ? 'paused' : 'active'}, updated_at = now()- where id = ${subId} and owner_user_id = ${userId} returning *- `;+ const row = await setSignalSubscriptionKilled({ userId, subId, killed });if (!row) return error(res, 404, 'not_found', 'subscription not found');- return json(res, 200, { subscription: shapeSub(row) });+ return json(res, 200, { subscription: row });}if (body.action === 'sync') {- const [row] = await sql`select * from signal_subscriptions where id = ${subId} and owner_user_id = ${userId} limit 1`;+ const row = await loadSub(subId, userId);if (!row) return error(res, 404, 'not_found', 'subscription not found');if (row.mode === 'live' && !(await requireRealFundsAgreement(req, res, { userId, network: normNetwork(row.network), context: 'signal-subscribe' }))) return;const result = await deliverSubscription(row, { maxEvents: 10 });@@ -148,15 +94,9 @@ export default wrap(async (req, res) => {if (cur?.mode === 'live' && !isLiveRunning(cur) && !(await requireRealFundsAgreement(req, res, { userId, network: normNetwork(cur.network), context: 'signal-subscribe' }))) return;}// Resuming clears any kill; pausing/stopping leaves the kill flag untouched.- const [row] = status === 'active'- ? await sql`- update signal_subscriptions set status = 'active', killed = false, updated_at = now()- where id = ${subId} and owner_user_id = ${userId} returning *`- : await sql`- update signal_subscriptions set status = ${status}, updated_at = now()- where id = ${subId} and owner_user_id = ${userId} returning *`;+ const row = await setSignalSubscriptionStatus({ userId, subId, status });if (!row) return error(res, 404, 'not_found', 'subscription not found');- return json(res, 200, { subscription: shapeSub(row) });+ return json(res, 200, { subscription: row });}return error(res, 400, 'no_op', 'nothing to update');}@@ -168,42 +108,20 @@ export default wrap(async (req, res) => {const owned = await loadOwnedAgent(req, res, userId, body.agent_id);if (owned.error) return;- const [feed] = await sql`select * from signal_feeds where id = ${feedId} limit 1`;- if (!feed) return error(res, 404, 'feed_not_found', 'feed not found');- if (feed.status !== 'active') return error(res, 409, 'feed_inactive', 'this feed is not active');- if (feed.publisher_agent_id === body.agent_id) return error(res, 400, 'self_subscribe', 'an agent cannot subscribe to its own feed');-- const network = normNetwork(feed.network);- const mode = body.mode === 'live' ? 'live' : 'simulate';- const billing = body.billing === 'per_epoch' ? 'per_epoch' : 'per_signal';- const baseSol = Math.max(0.001, Math.min(10, num(body.base_sol, 0.05)));- const sizeScaling = Math.max(0.01, Math.min(20, num(body.size_scaling, 1)));- const maxPerTrade = Math.max(0.001, Math.min(50, num(body.max_per_trade_sol, 0.25)));- const slippageBps = Math.round(Math.max(0, Math.min(5000, num(body.slippage_bps, 300))));- const firewallLevel = body.firewall_level === 'warn' ? 'warn' : 'block';- const copyExits = body.copy_exits !== false;- if (mode === 'live') {- const [cur] = await sql`select mode, status, killed from signal_subscriptions where subscriber_agent_id = ${body.agent_id} and feed_id = ${feed.id} limit 1`;- if (!isLiveRunning(cur) && !(await requireRealFundsAgreement(req, res, { userId, network, context: 'signal-subscribe' }))) return;+ let feed;+ try {+ feed = await loadSubscribableFeed(feedId, body.agent_id);+ } catch (err) {+ if (err instanceof SignalSubscriptionError) return error(res, err.status, err.code, err.message);+ throw err;}- // New subscriptions start at the current emission head: never charged for or- // made to mirror a backlog of signals emitted before they subscribed.- const [head] = await sql`select coalesce(max(id),0) as head from signal_emissions where feed_id = ${feed.id}`;- const startCursor = Number(head?.head || 0);+ const knobs = subscriptionKnobs(body);+ if (knobs.mode === 'live') {+ const cur = await existingSubscription(body.agent_id, feed.id);+ if (!isLiveRunning(cur) && !(await requireRealFundsAgreement(req, res, { userId, network: feed.network, context: 'signal-subscribe' }))) return;+ }- const [sub] = await sql`- insert into signal_subscriptions- (subscriber_agent_id, owner_user_id, feed_id, network, mode, billing,- base_sol, size_scaling, max_per_trade_sol, slippage_bps, firewall_level, copy_exits, status, killed, last_emission_id)- values (${body.agent_id}, ${userId}, ${feed.id}, ${network}, ${mode}, ${billing},- ${baseSol}, ${sizeScaling}, ${maxPerTrade}, ${slippageBps}, ${firewallLevel}, ${copyExits}, 'active', false, ${startCursor})- on conflict (subscriber_agent_id, feed_id) do update set- mode = excluded.mode, billing = excluded.billing, base_sol = excluded.base_sol,- size_scaling = excluded.size_scaling, max_per_trade_sol = excluded.max_per_trade_sol,- slippage_bps = excluded.slippage_bps, firewall_level = excluded.firewall_level,- copy_exits = excluded.copy_exits, status = 'active', killed = false, updated_at = now()- returning *- `;- return json(res, 200, { subscription: shapeSub(sub) });+ const subscription = await upsertSignalSubscription({ userId, agentId: body.agent_id, feed, knobs });+ return json(res, 200, { subscription });});diff --git a/api/v1/agents/[id]/portfolio/[...path].js b/api/v1/agents/[id]/portfolio/[...path].jsnew file mode 100644index 000000000..b8e59d240--- /dev/null+++ b/api/v1/agents/[id]/portfolio/[...path].js@@ -0,0 +1,8 @@+// /api/v1/agents/:id/portfolio[/history|/pnl]: an agent's valued portfolio,+// net-worth history and P&L. Route table: api/_lib/portfolio-routes.js.+// Guide: docs/api-reference.md.++import { defineRouter } from '../../../../_lib/agents-v1/http.js';+import { portfolioRoutes } from '../../../../_lib/portfolio-routes.js';++export default defineRouter({ base: '/api/v1', routes: portfolioRoutes });diff --git a/api/v1/agents/[id]/portfolio/index.js b/api/v1/agents/[id]/portfolio/index.jsnew file mode 100644index 000000000..b8e59d240--- /dev/null+++ b/api/v1/agents/[id]/portfolio/index.js@@ -0,0 +1,8 @@+// /api/v1/agents/:id/portfolio[/history|/pnl]: an agent's valued portfolio,+// net-worth history and P&L. Route table: api/_lib/portfolio-routes.js.+// Guide: docs/api-reference.md.++import { defineRouter } from '../../../../_lib/agents-v1/http.js';+import { portfolioRoutes } from '../../../../_lib/portfolio-routes.js';++export default defineRouter({ base: '/api/v1', routes: portfolioRoutes });diff --git a/data/changelog.json b/data/changelog.jsonindex 68c272344..6e16fc10c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-10",+ "title": "Agents can read their portfolio, run a launch sniper, set alerts and challenge each other to duels",+ "summary": "Fifteen new tools for Claude or any MCP client, plus a portfolio API at /api/v1/agents/:id/portfolio. An agent can read its own valued Solana portfolio with cost basis and risk flags, its net-worth history (now recorded hourly) and its profit and loss broken down by where it came from. It can check its launch sniper, and arm it only after you have seen the exact budget, per-trade size, limits and network in a preview and said yes; turning it off is one call. It can subscribe to signal feeds in paper mode, and create, list and delete pump alert rules, including a new kind that fires on any new launch matching your filters: a name pattern, a market cap band, a minimum safety score, the creator's track record and risk flags to avoid. Alerts reach you on the bell, by push, and in any Telegram or Discord chat you have paired. Agents can also challenge another agent to a points-only duel, accept one, read a duel and browse the open markets, with every result counted on the duels leaderboard.",+ "tags": ["feature", "sdk"],+ "link": "/docs/mcp"+ },{"date": "2026-10-10","title": "The 3D agent demos show their agent again",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 226cf8bb8..215694335 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -4196,6 +4196,95 @@ trade guards and listed in `clamped`.---+## Agent portfolio++An agent's valued Solana portfolio, its net-worth history and its P&L, in the+versioned v1 envelope. Owner only: a session, or an API key or OAuth token with+`wallet:read`. The same modules back the MCP tools `get_portfolio`,+`get_balance_history` and `get_pnl` ([MCP integration](./mcp.md#agent-wallet-portfolio-launch-sniper-alerts-and-duels)).++```+GET /api/v1/agents/:id/portfolio?network=mainnet+GET /api/v1/agents/:id/portfolio/history?network=mainnet&days=30&max_points=120+GET /api/v1/agents/:id/portfolio/pnl?network=mainnet+```++- **`/portfolio`**: SOL and every SPL holding valued in SOL and USD, FIFO cost+ basis and unrealized P&L per holding, `attribution` (realized and unrealized+ P&L by source: sniper, discretionary trades, strategies, x402 spend,+ withdrawals), `metrics` and `risk_flags`. Each call records a net-worth+ snapshot (at most one per agent and network every 15 minutes); the hourly+ `/api/cron/agent-portfolio-snapshots` cron records one for every active agent.+- **`/portfolio/history`**: `points` (recorded valuations over `days`, 1 to 365,+ thinned to `max_points`, 2 to 500, first and last exact), `summary` (start,+ end, change, peak, max drawdown) and `realized_curve` (exact cumulative+ realized P&L per UTC day from closed trades).+- **`/portfolio/pnl`**: `totals` (realized, unrealized, total, net worth, in SOL+ and USD), `by_source`, `performance` (win rate, ROI, profit factor, drawdown,+ Sharpe) and the top open `top_winners` and `top_losers`.++```bash+curl -s "https://three.ws/api/v1/agents/$AGENT_ID/portfolio/pnl?network=mainnet" \+ -H "authorization: Bearer $THREE_WS_API_KEY"+```++| Status | Code | Meaning |+| ------ | ---- | ------- |+| `400` | `invalid_network` | `network` is not `mainnet` or `devnet` |+| `400` | `invalid_parameter` | `days` or `max_points` out of range |+| `401` | `unauthorized` | No session or bearer token |+| `403` | `forbidden` | The agent belongs to another account |+| `403` | `insufficient_scope` | The token lacks `wallet:read` |+| `404` | `not_found` | No agent with that id, or an unknown sub-path |++---++## Pump alert rules API++Per-user pump.fun alert rules, evaluated server-side against the live launch+and trade stream, so they fire with no dashboard tab open. Session auth with a+CSRF token (the pump dashboard), and the same store as the MCP tools+`alert_rule_create`, `alert_rule_list` and `alert_rule_delete`.++```+GET /api/alerts/rules+POST /api/alerts/rules { kind, ...targeting, filters?, deliver_in_app?, webhook_url?, telegram_chat?, cooldown_seconds?, label? }+PATCH /api/alerts/rules/:id { any field above, enabled? }+DELETE /api/alerts/rules/:id+```++Kinds: `graduation`, `new_mint`, `price_above`, `price_below`, `whale_buy`,+`market_price`, and `launch_match`. Up to 50 rules per user.++**`launch_match`** fires once per new launch that coin intel has scored and that+passes every filter set in `filters` (at least one is required, and the rule+takes no `target_mint` or `target_agent`):++| Filter | Type | Matches when |+| ------ | ---- | ------------ |+| `name_pattern` | string, up to 120 | The name or symbol matches, case-insensitive. `*` is any text, `\|` separates alternatives; nothing else is special. Without a `*`, an alternative matches anywhere. |+| `min_market_cap_usd`, `max_market_cap_usd` | number | The market cap is inside the band. Min cannot exceed max. |+| `min_safety_score` | 0 to 100 | The coin intel quality score is at least this. |+| `min_creator_graduated` | integer | The creator's earlier launches that graduated are at least this. |+| `max_creator_launches` | integer | The creator's earlier launches are at most this (skips serial launchers). |+| `exclude_risk_flags` | array of `single_whale`, `low_diversity`, `sniped`, `dev_dumped`, `sell_pressure`, `bundle_launch` | None of these flags is set. |+| `require_socials` | boolean | The launch lists at least one social link. |++A filter whose data is missing on the launch (no market cap read yet) is a miss,+never a pass. The alert payload carries the mint, name, symbol, creator, market+cap, safety score, creator history, risk flags, the `matched` filters and a+`/coin/:mint` link.++**Delivery.** With `deliver_in_app` (the default) an alert reaches the owner+through the platform notification fan-out as a `pump_alert`: the bell, Web Push,+the iOS app, and every Telegram or Discord chat paired for notifications, each+gated by the `alerts` preference category ([notifications](./notifications.md)).+A `webhook_url` gets a signed Standard Webhooks POST, and a `telegram_chat` that+is not already a paired chat gets a direct message. Each attempt is recorded per+channel and returned as `recent_deliveries` on the rule.++---+## Trader Passport APIA trader's daily on-chain score attestation (`threews.tradescore.v1`), served as adiff --git a/docs/mcp-agent.md b/docs/mcp-agent.mdindex b43286fd8..6600a5bd6 100644--- a/docs/mcp-agent.md+++ b/docs/mcp-agent.md@@ -60,6 +60,36 @@ as the `/api/v1/agents/:id/predictions/*` routes and the `/predictions` pages.| `predictions_open`, `predictions_close`, `predictions_redeem` | financial | `wallet:write` | Execute with `agent_id`, the `preview_id`, and `confirm_trade: true`. || `predictions_watch` | write | `wallet:write` | Alert when an outcome's probability crosses a threshold, in-app and optionally to Telegram or a webhook. Moves no funds. |+### Portfolio, launch sniper, alerts and duels++An agent's valued portfolio and P&L, control of its pump.fun launch sniper and+signal subscriptions, launch alert rules, and agent-vs-agent duels. Each tool is+a thin adapter over the library the dashboards use: `api/_lib/portfolio.js` and+`api/_lib/portfolio-history.js` (the wallet hub's Portfolio tab and+`/api/v1/agents/:id/portfolio`), `api/_lib/sniper-control.js` (the sniper+dashboard), `api/_lib/signal-subscription-control.js` (`/signals`),+`api/_lib/pump-alert-rules.js` (`/api/alerts/rules` and the pump dashboard), and+`api/_lib/duel-challenges.js` with `api/_lib/trader-duels.js` (`/duels`).+Full reference with examples: [MCP integration](./mcp.md#agent-wallet-portfolio-launch-sniper-alerts-and-duels).++| Tool | Tier (group) | Scope | What it does |+|------|--------------|-------|--------------|+| `get_portfolio(agent_id, network?, max_holdings?)` | read (wallet) | `wallet:read` | Live valuation: SOL and every SPL holding in SOL and USD, FIFO cost basis and unrealized P&L per holding, P&L by source, risk flags. Records a net-worth point. |+| `get_balance_history(agent_id, network?, days?, max_points?)` | read (wallet) | `wallet:read` | Recorded net-worth points over 1 to 365 days with change, peak and max drawdown, plus the exact cumulative realized P&L per day. |+| `get_pnl(agent_id, network?)` | read (wallet) | `wallet:read` | Realized, unrealized and total P&L in SOL and USD, by source, with win rate, ROI, profit factor and the biggest open winners and losers. |+| `sniper_status(agent_id?, network?)` | read (trading) | `wallet:read` | Whether the sniper worker is live, and each of your strategies: armed or not, sizing, exits, today's spend and open positions. |+| `sniper_activate_preview(...)` | read (trading) | `wallet:read` | What arming would do: agent and wallet with its live SOL balance, per-trade size, daily budget, trigger, exits, what the SOL is spent on, whether real funds are at risk, and every blocking check. Returns a `preview_id`. |+| `sniper_activate(...)` | financial (trading) | `wallet:trade` or `agents:write` | Arm the sniper with exactly the previewed agent, network and sizing, `preview_id` and `confirm_spend: true`. Mainnet needs the signed real-funds agreement. |+| `sniper_deactivate(agent_id, network?, kill?)` | write (trading) | `wallet:trade` or `agents:write` | Disarm; `kill: true` also sets the kill switch. Open positions stay under their exits. |+| `sniper_subscribe(action, ...)` | write (trading) | `wallet:trade` or `agents:write` | List feeds and your subscriptions; subscribe an agent to a signal feed on paper; pause, resume, stop or kill a subscription. Live mode is owner-only on `/signals`. |+| `alert_rule_create(kind, ...)` | write (intelligence) | `wallet:trade` or `agents:write` | Create a pump.fun alert rule, including `launch_match` (a new launch that passes name pattern, market cap band, safety score, creator history, risk flag and socials filters). Always delivers to you. |+| `alert_rule_list(rule_id?)` | read (intelligence) | `wallet:read` | Your rules with their filters, state, last fire and recent deliveries. With `rule_id`, returns the `preview_id` `alert_rule_delete` needs. |+| `alert_rule_delete(rule_id)` | financial (intelligence) | `wallet:trade` or `agents:write` | Delete a rule for good, with the `preview_id` from `alert_rule_list` for the same rule and `confirm_delete: true`. |+| `duel_challenge(agent_id, opponent_agent_id, window?, message?)` | write (predictions) | `wallet:trade` or `agents:write` | Challenge another public agent to a day or week trading duel. The opponent's owner is notified. Free-play points, no funds. |+| `duel_accept(challenge_id, response?)` | write (predictions) | `wallet:trade` or `agents:write` | Accept or decline a challenge to your agent, or cancel one you sent. Accepting opens the duel. |+| `duel_details(duel_id or challenge_id)` | read (predictions) | none for a duel, sign-in for a challenge | One duel with its window, phase, standings and crowd calls, or one challenge with its duel. |+| `duel_markets(view?, ...)` | read (predictions) | none, sign-in for `challenges` | Duels by phase, your incoming and outgoing challenges, or the challenge leaderboard plus this season's top predictors. |+### Resources and promptsThis server also answers `resources/*` and `prompts/*`: the `three://` resourcesdiff --git a/docs/mcp.md b/docs/mcp.mdindex 413e64cff..e2e59d6f5 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -1078,6 +1078,107 @@ own machine with no three.ws account at all, use[`@three-ws/home-mcp`](../packages/home-mcp/README.md) instead, where a guarded action is refusedoutright because an MCP client has no person in it to confirm one.+### Agent wallet: portfolio, launch sniper, alerts and duels++These fifteen tools live on the agent wallet server (`https://three.ws/api/mcp-agent`), not on+`/api/mcp`. They give an agent the same view and controls its owner has on the wallet hub, the+sniper dashboard, `/signals`, the pump dashboard and `/duels`. Every one carries all four MCP+annotation hints, so a client knows which calls only read, which change state, and which are+irreversible.++| Tool | Hints | Policy |+|------|-------|--------|+| `get_portfolio` | readOnly, openWorld (live chain prices) | read, `wallet` group |+| `get_balance_history` | readOnly, idempotent | read, `wallet` group |+| `get_pnl` | readOnly, openWorld | read, `wallet` group |+| `sniper_status` | readOnly, idempotent | read, `trading` group |+| `sniper_activate_preview` | readOnly, openWorld (live wallet balance) | read, `trading` group |+| `sniper_activate` | destructive, idempotent, openWorld | **financial**: `confirm_spend` plus the `preview_id` from `sniper_activate_preview` |+| `sniper_deactivate` | idempotent | write, `trading` group |+| `sniper_subscribe` | idempotent | write, `trading` group |+| `alert_rule_create` | none (creates a new rule each call) | write, `intelligence` group |+| `alert_rule_list` | readOnly, idempotent | read, `intelligence` group |+| `alert_rule_delete` | destructive, idempotent | **financial**: `confirm_delete` plus the `preview_id` from `alert_rule_list` for that rule |+| `duel_challenge` | none | write, `predictions` group |+| `duel_accept` | none | write, `predictions` group |+| `duel_details` | readOnly | read, `predictions` group |+| `duel_markets` | readOnly | read, `predictions` group |++Financial tools are hidden until the connection turns their group on, for example with+`X-Three-Tools: default,trading,intelligence`. The full scope table is in+[the agent wallet server guide](./mcp-agent.md#portfolio-launch-sniper-alerts-and-duels).++**Portfolio.** `get_portfolio` values SOL and every SPL holding of one of your agents in SOL and+USD, with FIFO cost basis and unrealized P&L per holding, realized and unrealized P&L by source+(sniper, discretionary trades, strategies, x402 spend, withdrawals), and plain-language risk flags.+Every read records a net-worth point, and a cron (`/api/cron/agent-portfolio-snapshots`, hourly)+records one for every active agent. `get_balance_history` reads those points back over 1 to 365+days, thinned to `max_points`, with change, peak, max drawdown and the exact realized P&L per day+from closed trades. `get_pnl` is the P&L view: totals, by source, win rate, ROI, profit factor and+the biggest open winners and losers. The same data is on REST at+`GET /api/v1/agents/:id/portfolio`, `/portfolio/history` and `/portfolio/pnl`+([API reference](./api-reference.md#agent-portfolio)).++**Launch sniper.** The sniper buys new pump.fun launches that pass its filters, from the agent's+own wallet, inside a daily budget, with a mandatory stop loss. Arming it commits SOL, so it takes+two steps, and the second step must repeat the first exactly:++```json+{ "name": "sniper_activate_preview",+ "arguments": { "agent_id": "<agent>", "network": "devnet", "per_trade_sol": 0.01, "daily_budget_sol": 0.05, "stop_loss_pct": 25 } }+```++The preview names the chain, the asset (SOL), the wallet it spends from, what each buy pays+(the launch's bonding curve), the per-trade size and daily budget, whether real funds are at risk,+and every check that would block arming. Show it to the user. Only after an explicit yes:++```json+{ "name": "sniper_activate",+ "arguments": { "agent_id": "<agent>", "network": "devnet", "per_trade_sol": 0.01, "daily_budget_sol": 0.05, "stop_loss_pct": 25,+ "preview_id": "p_...", "confirm_spend": true } }+```++A missing preview is refused with `preview_required`, sizing that differs from the preview with+`preview_mismatch`, a reused preview with `preview_unknown`, and a mainnet arm without the signed+real-funds agreement with `risk_ack_required`. `sniper_deactivate` disarms without a preview+(stopping spend is always allowed); `kill: true` also sets the kill switch. `sniper_status` shows+whether the sniper worker is live and every strategy's spend today and open positions.++**Signal subscriptions.** `sniper_subscribe` follows another agent's published trade signals. An+agent subscribes on paper only: it mirrors the feed's entries and exits with your sizing, pays+nothing and trades nothing, so you can judge a feed first. `mode` is not an argument. Turning a+subscription live, which pays the feed in USDC and trades real funds, stays with the owner on+`/signals`, and the tool will not resume a paused live subscription either+(`live_resume_requires_owner`).++**Alert rules.** `alert_rule_create` adds a pump.fun alert. The `launch_match` kind fires on a new+launch that passes every filter you set:++```json+{ "name": "alert_rule_create",+ "arguments": { "kind": "launch_match", "label": "Safe cat coins",+ "filters": { "name_pattern": "*cat*|*kitty*", "min_market_cap_usd": 5000, "max_market_cap_usd": 60000,+ "min_safety_score": 60, "min_creator_graduated": 1, "max_creator_launches": 10,+ "exclude_risk_flags": ["bundle_launch", "dev_dumped"], "require_socials": true } } }+```++`name_pattern` treats only `*` (any text) and `|` (alternatives) as special, and a filter whose data+is missing on a launch counts as a miss, never a silent pass. Every alert reaches the owner through+the platform notification fan-out: the bell, Web Push to every subscribed device, the iOS app, and+every Telegram or Discord chat paired for notifications, each gated by the "alerts" category of the+[preference center](./notifications.md). The other kinds (`graduation`, `new_mint`, `price_above`,+`price_below`, `whale_buy`, `market_price`) are the same as on `/api/alerts/rules`. Deleting a rule+is irreversible, so `alert_rule_delete` needs `alert_rule_list` with that `rule_id` first, then its+`preview_id` and `confirm_delete: true`.++**Duels.** `duel_challenge` challenges another owner's public agent to a trading duel over the next+UTC day or week. The opponent's owner gets a `duel_challenge` notification and has 48 hours to+answer with `duel_accept` (`accept` or `decline`; the challenger can `cancel`). Accepting opens a+duel that scores both agents' realized P&L over the window and takes free-play crowd calls until it+starts. No funds move. `duel_details` reads one duel or one challenge, and `duel_markets` lists+duels by phase, your challenges, or the leaderboard: agents ranked by challenge-duel wins, with+losses, win rate and realized P&L, next to this season's top predictors.+---## Resourcesdiff --git a/docs/notifications.md b/docs/notifications.mdindex 5eb8a4b7d..071032d08 100644--- a/docs/notifications.md+++ b/docs/notifications.md@@ -67,7 +67,7 @@ category; the mapping (`TYPE_CATEGORY`) lives in|---|---|---|| Sales & earnings | `sales` | `skill_purchased`, `asset_purchased`, `sale`, `payment-earned`, `payment_received`, `referral_earned`, `referral_signup`, `referral_reward`, `pump_launch_filled`, `royalty_paid` || Purchases | `purchases` | `skill_purchase_confirmed`, `asset_purchase_confirmed`, `skill_gift_received`, `skill_gift_sent`, `print_update` |-| Social | `social` | `remix`, `reply`, `comment`, `embed`, `mention`, `fork`, `follow`, `dm_received`, `agent_review`, `quest_complete` |+| Social | `social` | `remix`, `reply`, `comment`, `embed`, `mention`, `fork`, `follow`, `dm_received`, `agent_review`, `quest_complete`, `duel_challenge` (another owner challenged your agent to a duel, or answered your challenge) || In person | `irl` | `irl_interaction`, `irl_reply` || Market alerts | `alerts` | `pump_alert` || Creations | `creations` | `forge_complete`, `forge_failed` |diff --git a/packages/mcp-policy/src/table.js b/packages/mcp-policy/src/table.jsindex b655aafa3..49c31b1be 100644--- a/packages/mcp-policy/src/table.js+++ b/packages/mcp-policy/src/table.js@@ -242,6 +242,27 @@ export const POLICY = {predictions_redeem_preview: r('predictions'),predictions_redeem: own('predictions', 'confirm_trade', 'predictions_redeem_preview'),predictions_watch: w('predictions'),+ // Portfolio (api/_mcpagent/portfolio-tools.js): valued holdings, the+ // hourly snapshot history and FIFO P&L. Reads only.+ get_portfolio: r('wallet'),+ get_balance_history: r('wallet'),+ get_pnl: r('wallet'),+ // Launch sniper, signal subscriptions and alert rules+ // (api/_mcpagent/sniper-alert-tools.js). Arming the sniper commits SOL, so+ // it binds the previewed agent, network and sizing.+ sniper_status: r('trading'),+ sniper_activate_preview: r('trading'),+ sniper_activate: f('trading', 'confirm_spend', 'sniper_activate_preview', ['agent_id', 'network', 'per_trade_sol', 'daily_budget_sol', 'stop_loss_pct', 'take_profit_pct', 'trigger', 'max_concurrent_positions']),+ sniper_deactivate: w('trading'),+ sniper_subscribe: w('trading'),+ alert_rule_create: w('intelligence'),+ alert_rule_list: r('intelligence'),+ alert_rule_delete: f('intelligence', 'confirm_delete', 'alert_rule_list', ['rule_id']),+ // Trader duels and challenges (api/_mcpagent/duels-tools.js). Free-play.+ duel_challenge: w('predictions'),+ duel_accept: w('predictions'),+ duel_details: r('predictions'),+ duel_markets: r('predictions'),},// /api/mcp-3ddiff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.htmlindex 2fe33d057..4630580fd 100644--- a/pages/pump-dashboard.html+++ b/pages/pump-dashboard.html@@ -869,6 +869,7 @@<option value="price_below" data-i18n="pump_dashboard.market_cap_falls_below">Market cap falls below</option><option value="whale_buy" data-i18n="pump_dashboard.whale_buy">Whale buy</option><option value="new_mint" data-i18n="pump_dashboard.new_launch_by_agent">New launch by agent</option>+ <option value="launch_match">New launch matching filters</option></select><div class="pd-field-hint" id="pd-rule-kind-hint"></div></div>@@ -891,6 +892,46 @@</select><div class="pd-field-hint" id="pd-rule-agent-hint">Fires when this agent launches a coin through three.ws.</div></div>+ <fieldset class="pd-rule-channels pd-rule-launch" id="pd-rule-launch-group" hidden>+ <legend class="pd-rule-channels-title">Launch filters</legend>+ <div class="pd-form-group">+ <label for="pd-rule-lf-name">Name or ticker <span class="pd-muted">(optional)</span></label>+ <input class="pd-input" type="text" id="pd-rule-lf-name" maxlength="120" placeholder="dog|cat or ai*" autocomplete="off" spellcheck="false" />+ <div class="pd-field-hint">Case-insensitive. <code>|</code> separates alternatives, <code>*</code> is a wildcard.</div>+ </div>+ <div class="pd-rule-launch-grid">+ <div class="pd-form-group">+ <label for="pd-rule-lf-mcmin">Min market cap (USD)</label>+ <input class="pd-input" type="number" id="pd-rule-lf-mcmin" min="0" step="100" inputmode="numeric" />+ </div>+ <div class="pd-form-group">+ <label for="pd-rule-lf-mcmax">Max market cap (USD)</label>+ <input class="pd-input" type="number" id="pd-rule-lf-mcmax" min="0" step="100" inputmode="numeric" />+ </div>+ <div class="pd-form-group">+ <label for="pd-rule-lf-safety">Min safety score (0 to 100)</label>+ <input class="pd-input" type="number" id="pd-rule-lf-safety" min="0" max="100" step="1" inputmode="numeric" />+ </div>+ <div class="pd-form-group">+ <label for="pd-rule-lf-grads">Creator's graduated coins, at least</label>+ <input class="pd-input" type="number" id="pd-rule-lf-grads" min="0" step="1" inputmode="numeric" />+ </div>+ <div class="pd-form-group">+ <label for="pd-rule-lf-launches">Creator's earlier launches, at most</label>+ <input class="pd-input" type="number" id="pd-rule-lf-launches" min="0" step="1" inputmode="numeric" />+ </div>+ </div>+ <div class="pd-rule-launch-flags" role="group" aria-labelledby="pd-rule-lf-flags-title">+ <div class="pd-field-hint" id="pd-rule-lf-flags-title">Skip launches flagged as</div>+ <label class="pd-check"><input type="checkbox" data-lf-flag="dev_dumped" /> Dev dumped</label>+ <label class="pd-check"><input type="checkbox" data-lf-flag="bundle_launch" /> Bundled launch</label>+ <label class="pd-check"><input type="checkbox" data-lf-flag="sniped" /> Sniped</label>+ <label class="pd-check"><input type="checkbox" data-lf-flag="single_whale" /> Single whale</label>+ <label class="pd-check"><input type="checkbox" data-lf-flag="low_diversity" /> Low holder diversity</label>+ <label class="pd-check"><input type="checkbox" data-lf-flag="sell_pressure" /> Sell pressure</label>+ </div>+ <label class="pd-check"><input type="checkbox" id="pd-rule-lf-socials" /> Require at least one social link</label>+ </fieldset><div class="pd-form-group" id="pd-rule-threshold-group" hidden><label for="pd-rule-threshold" id="pd-rule-threshold-label" data-i18n="pump_dashboard.threshold">Threshold</label><input class="pd-input" type="number" id="pd-rule-threshold" min="0" step="any" />@@ -903,6 +944,7 @@<div class="pd-rule-channels"><div class="pd-rule-channels-title">Delivery channels</div><label class="pd-check"><input type="checkbox" id="pd-rule-inapp" checked /> <span data-i18n="pump_dashboard.in_app_notification">In-app notification</span></label>+ <div class="pd-field-hint pd-rule-inapp-hint">Also sent as a push to your devices and to the Telegram or Discord chats you paired, following your <a href="/dashboard/settings">notification preferences</a>.</div><div class="pd-form-group"><label for="pd-rule-webhook" data-i18n-html="pump_dashboard.webhook_url_optional">Webhook URL <span class="pd-muted">(optional)</span></label><input class="pd-input" type="url" id="pd-rule-webhook" placeholder="https://your-server.com/pump-alerts" autocomplete="off" spellcheck="false" />@@ -3008,6 +3050,11 @@price_below: { icon: '\u{1F4C9}', label: 'Mcap below' },whale_buy: { icon: '\u{1F40B}', label: 'Whale buy' },new_mint: { icon: '\u{1F195}', label: 'New launch' },+ launch_match: { icon: '\u{1F3AF}', label: 'Launch match' },+ };+ const LAUNCH_FLAG_LABELS = {+ dev_dumped: 'dev dumped', bundle_launch: 'bundled', sniped: 'sniped',+ single_whale: 'single whale', low_diversity: 'low diversity', sell_pressure: 'sell pressure',};let _ruleEditingId = null;@@ -3192,6 +3239,19 @@return 'When someone buys ≥ ' + escapeHtml(String(r.threshold)) + ' SOL of <span class="pd-mono">' + short(r.target_mint) + '</span>';case 'new_mint':return 'When this agent launches a new coin';+ case 'launch_match': {+ const f = r.filters || {};+ const parts = [];+ if (f.name_pattern) parts.push('named <span class="pd-mono">' + escapeHtml(f.name_pattern) + '</span>');+ if (f.min_market_cap_usd != null) parts.push('mcap ≥ ' + usd(f.min_market_cap_usd));+ if (f.max_market_cap_usd != null) parts.push('mcap ≤ ' + usd(f.max_market_cap_usd));+ if (f.min_safety_score != null) parts.push('safety ≥ ' + escapeHtml(String(f.min_safety_score)));+ if (f.min_creator_graduated != null) parts.push('creator with ≥ ' + escapeHtml(String(f.min_creator_graduated)) + ' graduated');+ if (f.max_creator_launches != null) parts.push('creator with ≤ ' + escapeHtml(String(f.max_creator_launches)) + ' earlier launches');+ if (Array.isArray(f.exclude_risk_flags) && f.exclude_risk_flags.length) parts.push('not ' + f.exclude_risk_flags.map((x) => escapeHtml(LAUNCH_FLAG_LABELS[x] || x)).join(', '));+ if (f.require_socials) parts.push('with socials');+ return 'When a new pump.fun coin launches' + (parts.length ? ': ' + parts.join(', ') : '');+ }default:return '';}@@ -3271,6 +3331,7 @@const agentGroup = $('pd-rule-agent-group');const thrGroup = $('pd-rule-threshold-group');const hint = $('pd-rule-kind-hint');+ $('pd-rule-launch-group').hidden = kind !== 'launch_match';scopeGroup.hidden = true;mintGroup.hidden = true;agentGroup.hidden = true;@@ -3307,7 +3368,37 @@agentGroup.hidden = false;populateAgentOptions();hint.textContent = 'Fires when the selected agent launches a new coin.';+ } else if (kind === 'launch_match') {+ hint.textContent = 'Fires for every new pump.fun launch that passes all of these filters, about 90 seconds after it launches, once coin intel has scored it.';+ }+ }++ function readLaunchFilters() {+ const f = {};+ const name = $('pd-rule-lf-name').value.trim();+ if (name) f.name_pattern = name;+ const nums = { min_market_cap_usd: 'pd-rule-lf-mcmin', max_market_cap_usd: 'pd-rule-lf-mcmax', min_safety_score: 'pd-rule-lf-safety', min_creator_graduated: 'pd-rule-lf-grads', max_creator_launches: 'pd-rule-lf-launches' };+ for (const [key, id] of Object.entries(nums)) {+ const v = numOrNull($(id).value);+ if (v != null) f[key] = v;}+ const flags = [...document.querySelectorAll('[data-lf-flag]:checked')].map((el) => el.dataset.lfFlag);+ if (flags.length) f.exclude_risk_flags = flags;+ if ($('pd-rule-lf-socials').checked) f.require_socials = true;+ return f;+ }++ function writeLaunchFilters(f) {+ f = f || {};+ $('pd-rule-lf-name').value = f.name_pattern || '';+ $('pd-rule-lf-mcmin').value = f.min_market_cap_usd != null ? f.min_market_cap_usd : '';+ $('pd-rule-lf-mcmax').value = f.max_market_cap_usd != null ? f.max_market_cap_usd : '';+ $('pd-rule-lf-safety').value = f.min_safety_score != null ? f.min_safety_score : '';+ $('pd-rule-lf-grads').value = f.min_creator_graduated != null ? f.min_creator_graduated : '';+ $('pd-rule-lf-launches').value = f.max_creator_launches != null ? f.max_creator_launches : '';+ const ex = new Set(f.exclude_risk_flags || []);+ document.querySelectorAll('[data-lf-flag]').forEach((el) => { el.checked = ex.has(el.dataset.lfFlag); });+ $('pd-rule-lf-socials').checked = !!f.require_socials;}function buildRulePayload() {@@ -3329,6 +3420,8 @@p.threshold = numOrNull($('pd-rule-threshold').value);} else if (kind === 'new_mint') {p.target_agent = $('pd-rule-agent').value || null;+ } else if (kind === 'launch_match') {+ p.filters = readLaunchFilters();}return p;}@@ -3339,6 +3432,12 @@if (!(p.threshold > 0)) return 'Enter a threshold greater than 0.';}if (p.kind === 'new_mint' && !p.target_agent) return 'Select an agent.';+ if (p.kind === 'launch_match') {+ if (!Object.keys(p.filters || {}).length) return 'Set at least one launch filter.';+ const f = p.filters;+ if (f.min_market_cap_usd != null && f.max_market_cap_usd != null && f.min_market_cap_usd > f.max_market_cap_usd) return 'Min market cap cannot exceed max market cap.';+ if (f.min_safety_score != null && (f.min_safety_score < 0 || f.min_safety_score > 100)) return 'Safety score is between 0 and 100.';+ }if (p.kind === 'graduation') {const scope = $('pd-rule-scope').value;if (scope === 'mint' && !p.target_mint) return 'Enter a token mint address.';@@ -3408,6 +3507,7 @@$('pd-rule-webhook').value = r.webhook_url || '';$('pd-rule-telegram').value = r.telegram_chat || '';$('pd-rule-cooldown').value = r.cooldown_seconds || 300;+ writeLaunchFilters(r.kind === 'launch_match' ? r.filters : null);updateRuleFormFields();// Agent options may load async; set the value once they're present.const applyAgent = () => {@@ -3433,6 +3533,7 @@$('pd-rule-webhook').value = '';$('pd-rule-telegram').value = '';$('pd-rule-cooldown').value = '300';+ writeLaunchFilters(null);updateRuleFormFields();$('pd-rule-form-title').textContent = 'New alert rule';$('pd-rule-save').textContent = 'Create alert rule';@@ -3447,6 +3548,8 @@const el = $(id);if (el) el.disabled = disabled;});+ const launchGroup = $('pd-rule-launch-group');+ if (launchGroup) launchGroup.disabled = disabled;}async function deleteRule(id) {diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 5805e3db1..14f37cb32 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,24 @@{- "generated_at": "2026-10-10T06:12:03.237Z",+ "generated_at": "2026-10-10T06:37:18.384Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 3896,+ "total": 3906,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-10-10",+ "type": "launch",+ "title": "Agent Mail",+ "summary": "Each agent's own email inbox on agents.three.ws: read threads, send and reply through a quote you approve, set a recipient allowlist and a daily send cap, and route incoming mail to your approvals queue or an automation run.",+ "link": "/agent-mail",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-10","type": "launch",@@ -39,6 +49,36 @@"launch"]},+ {+ "date": "2026-10-10",+ "type": "launch",+ "title": "Docs · Web Domains",+ "summary": "Search, price, check and register web domains from an agent or the dashboard through Google Cloud Domains, paid from credits behind a quote and an explicit confirm, with the daily registrar quota, one-year terms, auto-renew and connecting a domain to an agent's public page.",+ "link": "/docs/domains",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "launch",+ "title": "Docs: Agent Mail",+ "summary": "Give an agent a real email address on agents.three.ws: quote-then-confirm sends, the recipient allowlist and daily cap, why received mail is data and never instructions, rules that turn incoming mail into agent runs, and the REST and MCP reference.",+ "link": "/docs/agent-mail",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "launch",+ "title": "Domains",+ "summary": "Search live registrar availability, see the exact yearly price, register a web domain from credits and serve an agent's public page on it.",+ "link": "/domains",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-10","type": "launch",@@ -49,6 +89,38 @@"launch"]},+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Agents can find and register web domains",+ "summary": "Search any name across popular extensions with live availability and the exact yearly price, check a single name, and register it from your credits after a quote and an explicit yes. Coin pages now suggest available domains for the project name, and a registered domain can serve your agent's public page. Registration is for one year, renews at the same price, and has no markup.",+ "link": "/domains",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Agents can read their portfolio, run a launch sniper, set alerts and challenge each other to duels",+ "summary": "Fifteen new tools for Claude or any MCP client, plus a portfolio API at /api/v1/agents/:id/portfolio. An agent can read its own valued Solana portfolio with cost basis and risk flags, its net-worth history (now recorded hourly) and its profit and loss broken down by where it came from. It can check its launch sniper, and arm it only after you have seen the exact budget, per-trade size, limits and network in a preview and said yes; turning it off is one call. It can subscribe to signal feeds in paper mode, and create, list and delete pump alert rules, including a new kind that fires on any new launch matching your filters: a name pattern, a market cap band, a minimum safety score, the creator's track record and risk flags to avoid. Alerts reach you on the bell, by push, and in any Telegram or Discord chat you have paired. Agents can also challenge another agent to a points-only duel, accept one, read a duel and browse the open markets, with every result counted on the duels leaderboard.",+ "link": "/docs/mcp",+ "tags": [+ "feature",+ "sdk"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Agents get their own email inbox",+ "summary": "Every agent can now have an email address on agents.three.ws, with an inbox right on its profile (the Mail button). It can send, read, reply in thread, search and delete, from the web, the API, or any MCP client. Nothing is created or sent until you have seen the exact recipients and message and said yes. You can limit an agent to a list of recipients and a daily number of sends, and only you, signed in, can change those limits. Mail an agent receives is always treated as information, never as orders: hidden characters are shown, links are disabled, and the agent is told not to follow anything inside it. Rules let you turn incoming mail into work, such as \"when mail arrives from this sender, summarize it\", either right away or after you approve.",+ "link": "/agent-mail",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-10-10","type": "update",@@ -132,6 +204,36 @@"feature"]},+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Strategies now research every coin and ask before they buy",+ "summary": "Trading strategies can now check a coin before spending anything: minimum holders, how much the largest holder owns, liquidity, the rug and honeypot safety score, whether the creator can still mint or freeze, and the creator's track record. A coin that fails a check, or whose data cannot be read, is skipped and the decision log on your agent says exactly which check stopped it. You can also cap price impact per buy. Strategies now ask for your approval before each buy by default, with the amount, coin and risk notes on the card, and existing strategies were switched to ask mode too; flip one to Auto once you trust it. The strategy builder edits everything with sliders, toggles or raw JSON, turns a plain-English description into settings, shows a live count of recent launches your settings would have bought, and backtests with the checks applied.",+ "link": "/strategies",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "The 3D agent demos show their agent again",+ "summary": "Every page in the agent interaction lab had stopped drawing its 3D character, so the demos showed only text and buttons. They load again: she climbs the title, catches your cursor, rides the scroll, falls asleep on the headline and the rest. The wrecking-ball entrance was also rebuilt so she really swings in on the rope and hits the button, instead of hovering beside it with the rope pointing the wrong way.",+ "link": "/demos/agents",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Token ceilings, a spend page, USDC deposits and a way out of the free tier",+ "summary": "Every agent can now carry hourly, daily and per-run token ceilings next to its dollar caps. A ceiling is checked before the model is called; hitting one pauses the agent, tells you, and gives you Resume and Extend once. The new /spend page shows what each agent spends by day, by model and by tool, projects the month end, and alerts at 50, 80 and 100 percent of any cap. Credits can be topped up with USDC at a fixed rate alongside SOL and $THREE, the deposit page lists every accepted asset and its rate from live config, and paying in $THREE earns whatever bonus the owner has set. When the free tier runs out, the error now carries your choices: wait for the reset, top up, bring your own key, or resend the same request with paid_fallback: true to bill it to credits in one step.",+ "link": "/spend",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-09","type": "launch",@@ -1436,108 +1538,6 @@"fix","infra"]- },- {- "date": "2026-09-25",- "type": "update",- "title": "The model catalog AI clients read now shows the real price of every model",- "summary": "The three://models resource that Claude and other MCP clients read listed free models with no price and left some paid models blank. Free models now read as costing nothing, and a model served through a partner route is priced at the model that actually answers, so an assistant comparing costs for you works from real numbers.",- "link": "/docs/mcp",- "tags": [- "fix",- "sdk"- ]- },- {- "date": "2026-09-24",- "type": "launch",- "title": "Docs · Trade receipts",- "summary": "Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.",- "link": "/docs/trade-receipts",- "tags": [- "launch"- ]- },- {- "date": "2026-09-24",- "type": "update",- "title": "Paying the Club cover in USDC works in wallets that refused to show the request",- "summary": "Some visitors paying the Club cover in USDC saw their wallet refuse to open the approval window, and the payment stopped with \"Your wallet could not display this payment request\". The payment itself was well formed; the problem was in how the page handed it to the wallet. The payment window now passes the transaction to your wallet through the Wallet Standard interface that Phantom, Solflare and Backpack all support, exactly as our server built it, and only falls back to the older wallet connection for wallets that do not offer it. Nothing was ever charged on a refused attempt.",- "link": "/club",- "tags": [- "fix"- ]- },- {- "date": "2026-09-24",- "type": "update",- "title": "See why an AI trader bought, with the evidence it had",- "summary": "Every closed trade on an agent's track record now has a why link. It opens the trade's receipt: what triggered the entry, the Oracle score and the base-rate reasons behind it, the trade firewall's on-chain buy and sell simulation, the LLM judge's thesis when one ran, the Risk Officer's review, and paid market and rug-pull reads with the payment transaction that bought them. Every entry and exit leg links to its transaction. Each piece of evidence shows when it was recorded relative to the entry. Anything logged after the exit is left out, because it could not have caused the trade. The same receipt appears on every shareable trade page, a link with ?trade= opens it directly, and agents can read it through the new trade_receipt MCP tool.",- "link": "/docs/trade-receipts",- "tags": [- "feature"- ]- },- {- "date": "2026-09-24",- "type": "update",- "title": "The x402 payment rail stops starting payments it cannot afford to finish",- "summary": "The platform's own agents pay each other for services over x402, and a daily budget caps how much SOL the shared fee wallet spends on network fees. When that budget was nearly used up, our agents kept starting payments anyway: they looked up accounts, signed transfers and ran a simulated check, only to be turned away at the last step. About 1,700 payments an hour ended that way beside roughly 230 that settled. Each agent now reserves its share of the remaining budget before it starts, so a payment only begins when the fee wallet can fund it. The economy lab also now counts every refused payment instead of about one in a hundred, and the treasury report tells a wallet holding a little spare SOL apart from one that is empty. Payments from customer wallets are never held back by this budget.",- "link": "/economy-lab",- "tags": [- "fix",- "infra"- ]- },- {- "date": "2026-09-22",- "type": "launch",- "title": "Authorize the three-ws CLI",- "summary": "Approve a sign-in started by npx three-ws in your terminal. Check the code matches, choose what the new API key may do (money-moving permissions are flagged and can be removed), and the CLI finishes setup on its own.",- "link": "/cli/authorize",- "tags": [- "launch"- ]- },- {- "date": "2026-09-22",- "type": "launch",- "title": "Community Skills",- "summary": "Open-source skills for AI agents: one markdown file of instructions each, contributed by pull request and imported onto any three.ws agent in one click. Search by tag or author, preview the full SKILL.md, then manage your agent's skills and token budget.",- "link": "/skills/community",- "tags": [- "launch"- ]- },- {- "date": "2026-09-22",- "type": "launch",- "title": "Data Desk",- "summary": "Live market data bought minute by minute by brand-new agent wallets over x402. Every dataset carries its receipt: the wallet that paid, the price, and the Solana settlement transaction.",- "link": "/data-desk",- "tags": [- "launch"- ]- },- {- "date": "2026-09-22",- "type": "launch",- "title": "Docs · Fresh-wallet workers",- "summary": "How the platform mints a brand-new Solana wallet for every x402 purchase, what those wallets buy (3D props for the library, datasets for the data desk), how each wallet is emptied and closed so nothing strands, and where to watch it.",- "link": "/docs/x402-fresh-workers",- "tags": [- "launch"- ]- },- {- "date": "2026-09-22",- "type": "update",- "title": "Agents now buy real work from brand-new wallets, and you can watch it",- "summary": "The platform's agent economy used to prove the payment rail from a few long-lived wallets buying test calls. It now mints a fresh Solana wallet for every purchase: each one is created, given exactly one job's worth of USDC, pays a three.ws endpoint, and is emptied and closed within the minute. Every purchase does something useful. Some buy a 3D generation that lands in the Agent-Forged Gallery, where a new fresh wallet badge marks it. The rest buy live market data, which now has its own page, the Data Desk, showing each dataset with the wallet that paid, the price, and the Solana receipt. Both feeds are public JSON as well, and a new stats endpoint lists every wallet with its three transactions.",- "link": "/data-desk",- "tags": [- "feature"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex 9c504d437..246c27107 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-10-10T06:12:03.140Z",+ "generated_at": "2026-10-10T06:37:18.335Z","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-10-10",+ "type": "launch",+ "title": "Agent Mail",+ "summary": "Each agent's own email inbox on agents.three.ws: read threads, send and reply through a quote you approve, set a recipient allowlist and a daily send cap, and route incoming mail to your approvals queue or an automation run.",+ "link": "/agent-mail",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-10","type": "launch",@@ -36,6 +46,36 @@"launch"]},+ {+ "date": "2026-10-10",+ "type": "launch",+ "title": "Docs · Web Domains",+ "summary": "Search, price, check and register web domains from an agent or the dashboard through Google Cloud Domains, paid from credits behind a quote and an explicit confirm, with the daily registrar quota, one-year terms, auto-renew and connecting a domain to an agent's public page.",+ "link": "/docs/domains",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "launch",+ "title": "Docs: Agent Mail",+ "summary": "Give an agent a real email address on agents.three.ws: quote-then-confirm sends, the recipient allowlist and daily cap, why received mail is data and never instructions, rules that turn incoming mail into agent runs, and the REST and MCP reference.",+ "link": "/docs/agent-mail",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "launch",+ "title": "Domains",+ "summary": "Search live registrar availability, see the exact yearly price, register a web domain from credits and serve an agent's public page on it.",+ "link": "/domains",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-10","type": "launch",@@ -46,6 +86,38 @@"launch"]},+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Agents can find and register web domains",+ "summary": "Search any name across popular extensions with live availability and the exact yearly price, check a single name, and register it from your credits after a quote and an explicit yes. Coin pages now suggest available domains for the project name, and a registered domain can serve your agent's public page. Registration is for one year, renews at the same price, and has no markup.",+ "link": "/domains",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Agents can read their portfolio, run a launch sniper, set alerts and challenge each other to duels",+ "summary": "Fifteen new tools for Claude or any MCP client, plus a portfolio API at /api/v1/agents/:id/portfolio. An agent can read its own valued Solana portfolio with cost basis and risk flags, its net-worth history (now recorded hourly) and its profit and loss broken down by where it came from. It can check its launch sniper, and arm it only after you have seen the exact budget, per-trade size, limits and network in a preview and said yes; turning it off is one call. It can subscribe to signal feeds in paper mode, and create, list and delete pump alert rules, including a new kind that fires on any new launch matching your filters: a name pattern, a market cap band, a minimum safety score, the creator's track record and risk flags to avoid. Alerts reach you on the bell, by push, and in any Telegram or Discord chat you have paired. Agents can also challenge another agent to a points-only duel, accept one, read a duel and browse the open markets, with every result counted on the duels leaderboard.",+ "link": "/docs/mcp",+ "tags": [+ "feature",+ "sdk"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Agents get their own email inbox",+ "summary": "Every agent can now have an email address on agents.three.ws, with an inbox right on its profile (the Mail button). It can send, read, reply in thread, search and delete, from the web, the API, or any MCP client. Nothing is created or sent until you have seen the exact recipients and message and said yes. You can limit an agent to a list of recipients and a daily number of sends, and only you, signed in, can change those limits. Mail an agent receives is always treated as information, never as orders: hidden characters are shown, links are disabled, and the agent is told not to follow anything inside it. Rules let you turn incoming mail into work, such as \"when mail arrives from this sender, summarize it\", either right away or after you approve.",+ "link": "/agent-mail",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-10-10","type": "update",@@ -129,6 +201,36 @@"feature"]},+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Strategies now research every coin and ask before they buy",+ "summary": "Trading strategies can now check a coin before spending anything: minimum holders, how much the largest holder owns, liquidity, the rug and honeypot safety score, whether the creator can still mint or freeze, and the creator's track record. A coin that fails a check, or whose data cannot be read, is skipped and the decision log on your agent says exactly which check stopped it. You can also cap price impact per buy. Strategies now ask for your approval before each buy by default, with the amount, coin and risk notes on the card, and existing strategies were switched to ask mode too; flip one to Auto once you trust it. The strategy builder edits everything with sliders, toggles or raw JSON, turns a plain-English description into settings, shows a live count of recent launches your settings would have bought, and backtests with the checks applied.",+ "link": "/strategies",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "The 3D agent demos show their agent again",+ "summary": "Every page in the agent interaction lab had stopped drawing its 3D character, so the demos showed only text and buttons. They load again: she climbs the title, catches your cursor, rides the scroll, falls asleep on the headline and the rest. The wrecking-ball entrance was also rebuilt so she really swings in on the rope and hits the button, instead of hovering beside it with the rope pointing the wrong way.",+ "link": "/demos/agents",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-10-10",+ "type": "update",+ "title": "Token ceilings, a spend page, USDC deposits and a way out of the free tier",+ "summary": "Every agent can now carry hourly, daily and per-run token ceilings next to its dollar caps. A ceiling is checked before the model is called; hitting one pauses the agent, tells you, and gives you Resume and Extend once. The new /spend page shows what each agent spends by day, by model and by tool, projects the month end, and alerts at 50, 80 and 100 percent of any cap. Credits can be topped up with USDC at a fixed rate alongside SOL and $THREE, the deposit page lists every accepted asset and its rate from live config, and paying in $THREE earns whatever bonus the owner has set. When the free tier runs out, the error now carries your choices: wait for the reset, top up, bring your own key, or resend the same request with paid_fallback: true to bill it to credits in one step.",+ "link": "/spend",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-09","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 92fa97e3e..9b4a77e66 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 Mail</title>+ <link>https://three.ws/agent-mail</link>+ <guid isPermaLink="false">2026-10-10:Agent Mail</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Each agent's own email inbox on agents.three.ws: read threads, send and reply through a quote you approve, set a recipient allowlist and a daily send cap, and route incoming mail to your approvals queue or an automation run.</description>+ </item><item><title>Approvals</title><link>https://three.ws/approvals</link>@@ -30,6 +38,30 @@<category>launch</category><description>How specialist teams work: the four roles and their permission ceilings, the shared findings board and its live stream, the cite-or-research rule the Trader follows, launch prep you sign yourself, and the full API.</description></item>+ <item>+ <title>Docs · Web Domains</title>+ <link>https://three.ws/docs/domains</link>+ <guid isPermaLink="false">2026-10-10:Docs · Web Domains</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Search, price, check and register web domains from an agent or the dashboard through Google Cloud Domains, paid from credits behind a quote and an explicit confirm, with the daily registrar quota, one-year terms, auto-renew and connecting a domain to an agent's public page.</description>+ </item>+ <item>+ <title>Docs: Agent Mail</title>+ <link>https://three.ws/docs/agent-mail</link>+ <guid isPermaLink="false">2026-10-10:Docs: Agent Mail</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Give an agent a real email address on agents.three.ws: quote-then-confirm sends, the recipient allowlist and daily cap, why received mail is data and never instructions, rules that turn incoming mail into agent runs, and the REST and MCP reference.</description>+ </item>+ <item>+ <title>Domains</title>+ <link>https://three.ws/domains</link>+ <guid isPermaLink="false">2026-10-10:Domains</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Search live registrar availability, see the exact yearly price, register a web domain from credits and serve an agent's public page on it.</description>+ </item><item><title>Specialist Teams: four agents, one board</title><link>https://three.ws/teams</link>@@ -38,6 +70,30 @@<category>launch</category><description>Assemble a squad of four 3D agents (a Researcher, an Entry scout, a Trader and a Launcher) under one spend policy. They post to a shared live findings board, the Trader only acts on research it can cite, and the Launcher prepares plans you sign yourself.</description></item>+ <item>+ <title>Agents can find and register web domains</title>+ <link>https://three.ws/domains</link>+ <guid isPermaLink="false">2026-10-10:Agents can find and register web domains</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Search any name across popular extensions with live availability and the exact yearly price, check a single name, and register it from your credits after a quote and an explicit yes. Coin pages now suggest available domains for the project name, and a registered domain can serve your agent's public page. Registration is for one year, renews at the same price, and has no markup.</description>+ </item>+ <item>+ <title>Agents can read their portfolio, run a launch sniper, set alerts and challenge each other to duels</title>+ <link>https://three.ws/docs/mcp</link>+ <guid isPermaLink="false">2026-10-10:Agents can read their portfolio, run a launch sniper, set alerts and challenge each other to duels</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Fifteen new tools for Claude or any MCP client, plus a portfolio API at /api/v1/agents/:id/portfolio. An agent can read its own valued Solana portfolio with cost basis and risk flags, its net-worth history (now recorded hourly) and its profit and loss broken down by where it came from. It can check its launch sniper, and arm it only after you have seen the exact budget, per-trade size, limits and network in a preview and said yes; turning it off is one call. It can subscribe to signal feeds in paper mode, and create, list and delete pump alert rules, including a new kind that fires on any new launch matching your filters: a name pattern, a market cap band, a minimum safety score, the creator's track record and risk flags to avoid. Alerts reach you on the bell, by push, and in any Telegram or Discord chat you have paired. Agents can also challenge another agent to a points-only duel, accept one, read a duel and browse the open markets, with every result counted on the duels leaderboard.</description>+ </item>+ <item>+ <title>Agents get their own email inbox</title>+ <link>https://three.ws/agent-mail</link>+ <guid isPermaLink="false">2026-10-10:Agents get their own email inbox</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every agent can now have an email address on agents.three.ws, with an inbox right on its profile (the Mail button). It can send, read, reply in thread, search and delete, from the web, the API, or any MCP client. Nothing is created or sent until you have seen the exact recipients and message and said yes. You can limit an agent to a list of recipients and a daily number of sends, and only you, signed in, can change those limits. Mail an agent receives is always treated as information, never as orders: hidden characters are shown, links are disabled, and the agent is told not to follow anything inside it. Rules let you turn incoming mail into work, such as "when mail arrives from this sender, summarize it", either right away or after you approve.</description>+ </item><item><title>Approve or deny your agent's requests from Telegram and Discord</title><link>https://three.ws/approvals</link>@@ -102,6 +158,30 @@<category>feature</category><description>Assemble a squad of four 3D agents in one click: a Researcher that vets a token and posts a scored verdict, an Entry scout that checks fresh launches against your entry gates, a Trader that quotes, simulates or trades inside one spend policy, and a Launcher that prepares a launch plan for you to sign. They share a live findings board. The Trader only acts on research it can cite, reuses a fresh verdict instead of redoing it, and every refusal is posted with its reason. Only the Trader can ever sign, and only a live trade you confirm.</description></item>+ <item>+ <title>Strategies now research every coin and ask before they buy</title>+ <link>https://three.ws/strategies</link>+ <guid isPermaLink="false">2026-10-10:Strategies now research every coin and ask before they buy</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Trading strategies can now check a coin before spending anything: minimum holders, how much the largest holder owns, liquidity, the rug and honeypot safety score, whether the creator can still mint or freeze, and the creator's track record. A coin that fails a check, or whose data cannot be read, is skipped and the decision log on your agent says exactly which check stopped it. You can also cap price impact per buy. Strategies now ask for your approval before each buy by default, with the amount, coin and risk notes on the card, and existing strategies were switched to ask mode too; flip one to Auto once you trust it. The strategy builder edits everything with sliders, toggles or raw JSON, turns a plain-English description into settings, shows a live count of recent launches your settings would have bought, and backtests with the checks applied.</description>+ </item>+ <item>+ <title>The 3D agent demos show their agent again</title>+ <link>https://three.ws/demos/agents</link>+ <guid isPermaLink="false">2026-10-10:The 3D agent demos show their agent again</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Every page in the agent interaction lab had stopped drawing its 3D character, so the demos showed only text and buttons. They load again: she climbs the title, catches your cursor, rides the scroll, falls asleep on the headline and the rest. The wrecking-ball entrance was also rebuilt so she really swings in on the rope and hits the button, instead of hovering beside it with the rope pointing the wrong way.</description>+ </item>+ <item>+ <title>Token ceilings, a spend page, USDC deposits and a way out of the free tier</title>+ <link>https://three.ws/spend</link>+ <guid isPermaLink="false">2026-10-10:Token ceilings, a spend page, USDC deposits and a way out of the free tier</guid>+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every agent can now carry hourly, daily and per-run token ceilings next to its dollar caps. A ceiling is checked before the model is called; hitting one pauses the agent, tells you, and gives you Resume and Extend once. The new /spend page shows what each agent spends by day, by model and by tool, projects the month end, and alerts at 50, 80 and 100 percent of any cap. Credits can be topped up with USDC at a fixed rate alongside SOL and $THREE, the deposit page lists every accepted asset and its rate from live config, and paying in $THREE earns whatever bonus the owner has set. When the free tier runs out, the error now carries your choices: wait for the reset, top up, bring your own key, or resend the same request with paid_fallback: true to bill it to credits in one step.</description>+ </item><item><title>CAD Forge</title><link>https://three.ws/cad</link>diff --git a/public/pump-dashboard.css b/public/pump-dashboard.cssindex 2b5d6e9ae..ccef90c14 100644--- a/public/pump-dashboard.css+++ b/public/pump-dashboard.css@@ -1238,3 +1238,20 @@ code, .pd-mono-inline {filter var(--duration-fast) var(--ease-standard),text-decoration-thickness var(--duration-fast) var(--ease-standard);}++/* launch_match filters in the alert rule form */+.pd-rule-launch { min-width: 0; }+.pd-rule-launch legend { padding: 0 0.3rem; }+.pd-rule-launch-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));+ gap: 0 0.8rem;+}+.pd-rule-launch-flags {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 0 0.8rem;+ margin-bottom: 0.4rem;+}+.pd-rule-launch-flags .pd-field-hint { grid-column: 1 / -1; margin: 0 0 0.5rem; }+.pd-rule-launch code { font-size: 0.7rem; }diff --git a/src/notifications-page.js b/src/notifications-page.jsindex 5b2b870a9..c14850fdc 100644--- a/src/notifications-page.js+++ b/src/notifications-page.js@@ -21,7 +21,7 @@ const TYPE_CATEGORY = {print_update: 'purchases',remix: 'social', reply: 'social', comment: 'social', embed: 'social', mention: 'social',fork: 'social', follow: 'social', dm_received: 'social', agent_review: 'social',- quest_complete: 'social',+ quest_complete: 'social', duel_challenge: 'social',irl_interaction: 'irl', irl_reply: 'irl',pump_alert: 'alerts',companion_delivery: 'companion',diff --git a/src/notifications.js b/src/notifications.jsindex 1ceca05dd..3a29e7cd1 100644--- a/src/notifications.js+++ b/src/notifications.js@@ -89,6 +89,7 @@ export const TYPE_ICON = {forge_complete: '✨',forge_failed: '⚠️',quest_complete: '🏆',+ duel_challenge: '⚔️',royalty_paid: '💰',companion_delivery: '👋',print_update: '📦',@@ -178,6 +179,8 @@ export function notifLabel(n) {return p.message || `Your print order was updated${p.status ? `: ${String(p.status).replace(/_/g, ' ')}` : ''}`;case 'pump_alert':return p.summary || 'An alert rule fired';+ case 'duel_challenge':+ return p.summary || 'Another agent challenged yours to a trading duel';case 'inference_topup':return `${p.source === 'intent' ? 'Auto top-up: ' : ''}${Number(p.amount_usdc) || 0} USDC from your agent's wallet added $${(Number(p.credits_usd) || 0).toFixed(2)} of credits`;case 'inference_budget_exhausted':diff --git a/tests/api/mcp-agent-catalog.test.js b/tests/api/mcp-agent-catalog.test.jsindex 20d5932bc..f37230a1b 100644--- a/tests/api/mcp-agent-catalog.test.js+++ b/tests/api/mcp-agent-catalog.test.js@@ -49,6 +49,24 @@ describe('agent-wallet MCP catalog', () => {'predictions_redeem_preview','predictions_redeem','predictions_watch',+ // Portfolio reads (api/_mcpagent/portfolio-tools.js)+ 'get_portfolio',+ 'get_balance_history',+ 'get_pnl',+ // Launch sniper, signal subscriptions and alert rules (api/_mcpagent/sniper-alert-tools.js)+ 'sniper_status',+ 'sniper_activate_preview',+ 'sniper_activate',+ 'sniper_deactivate',+ 'sniper_subscribe',+ 'alert_rule_create',+ 'alert_rule_list',+ 'alert_rule_delete',+ // Agent duels (api/_mcpagent/duels-tools.js)+ 'duel_challenge',+ 'duel_accept',+ 'duel_details',+ 'duel_markets',]);});diff --git a/tests/api/mcp-agent-portfolio-sniper-duels.test.js b/tests/api/mcp-agent-portfolio-sniper-duels.test.jsnew file mode 100644index 000000000..b6d1dc009--- /dev/null+++ b/tests/api/mcp-agent-portfolio-sniper-duels.test.js@@ -0,0 +1,485 @@+// The threews-agent MCP portfolio, sniper, alert-rule and duel tools, driven+// through the real dispatcher: the real policy gate (enablement, confirm flags,+// bound preview ids), the real scope checks and Ajv validation. Only the store+// and chain boundaries underneath the tools are stubbed, so these tests prove+// the tool surface and its gates, not the stores (which have their own suites).++import { describe, it, expect, vi, beforeEach } from 'vitest';++process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';++const USER = '0a1b2c3d-0000-4000-8000-0000000009a1';+const AGENT = '7e57a9e1-0000-4000-8000-000000000946';+const OPPONENT = '7e57a9e1-0000-4000-8000-000000000947';+const RULE = 'a1e47000-0000-4000-8000-000000000946';+const CHALLENGE = 'c4a11e00-0000-4000-8000-000000000946';+const DUEL = 'd0e10000-0000-4000-8000-000000000946';+const WALLET = 'THREEsyntheticWa11et111111111111111111111111';++const state = vi.hoisted(() => ({ owned: true, signed: true }));++vi.mock('../../api/_lib/db.js', () => ({+ // The only query a tool here runs itself: sniper_subscribe's ownership read.+ sql: vi.fn(async () => (state.owned ? [{ name: 'Scout' }] : [])),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: new Proxy({}, { get: () => vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })) }),+ clientIp: vi.fn(() => '203.0.113.46'),+}));++vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++vi.mock('../../api/_lib/real-funds-agreement.js', () => ({+ currentSignatureFor: vi.fn(async () => (state.signed ? { signedAt: '2026-10-01T00:00:00.000Z', signatureName: 'Test Signer' } : null)),+ agreementRequirement: () => ({ version: 2, sign_url: 'https://three.ws/legal/agreements', documents: [] }),+}));++vi.mock('../../api/_lib/portfolio-history.js', async (orig) => ({+ ...(await orig()),+ loadPortfolioAgent: vi.fn(async () => ({ id: AGENT })),+ portfolioWithSnapshot: vi.fn(),+ getBalanceHistory: vi.fn(),+}));++vi.mock('../../api/_lib/sniper-control.js', async (orig) => ({+ ...(await orig()),+ sniperStatus: vi.fn(),+ previewActivation: vi.fn(),+ activateSniper: vi.fn(),+ deactivateSniper: vi.fn(),+}));++vi.mock('../../api/_lib/signal-subscription-control.js', async (orig) => ({+ ...(await orig()),+ listSignalSubscriptions: vi.fn(async () => []),+ listSubscribableFeeds: vi.fn(async () => []),+ loadSignalSubscription: vi.fn(),+ loadSubscribableFeed: vi.fn(),+ existingSubscription: vi.fn(async () => null),+ upsertSignalSubscription: vi.fn(),+ setSignalSubscriptionStatus: vi.fn(),+ setSignalSubscriptionKilled: vi.fn(),+}));++vi.mock('../../api/_lib/pump-alert-rules.js', async (orig) => ({+ ...(await orig()),+ listAlertRules: vi.fn(),+ createAlertRule: vi.fn(),+ deleteAlertRule: vi.fn(),+}));++vi.mock('../../api/_lib/duel-challenges.js', async (orig) => ({+ ...(await orig()),+ createChallenge: vi.fn(),+ respondChallenge: vi.fn(),+ getChallenge: vi.fn(),+ listChallenges: vi.fn(async () => []),+ challengeLeaderboard: vi.fn(),+}));++vi.mock('../../api/_lib/trader-duels.js', async (orig) => ({+ ...(await orig()),+ listDuels: vi.fn(async () => []),+ getDuel: vi.fn(),+ seasonLeaderboard: vi.fn(async () => ({ season: { id: '2026-10' }, leaders: [] })),+}));++const portfolio = await import('../../api/_lib/portfolio-history.js');+const sniper = await import('../../api/_lib/sniper-control.js');+const signals = await import('../../api/_lib/signal-subscription-control.js');+const alerts = await import('../../api/_lib/pump-alert-rules.js');+const challenges = await import('../../api/_lib/duel-challenges.js');+const duels = await import('../../api/_lib/trader-duels.js');+const { dispatch } = await import('../../api/_mcpagent/dispatch.js');++const ALL = { userId: USER, rateKey: USER, scope: 'wallet:read wallet:write wallet:trade agents:write', source: 'bearer' };+const READONLY = { userId: USER, rateKey: USER, scope: 'wallet:read', source: 'bearer' };+const ANON = { userId: null, rateKey: 'anon', scope: '', source: 'x402' };+const GROUPS_ON = 'default,wallet,trading,intelligence,predictions';+const req = (tools) => ({ url: '/api/mcp-agent', headers: { 'x-three-tools': tools } });++const call = (name, args, auth = ALL, tools = GROUPS_ON) =>+ dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth, req(tools));+const list = (tools = GROUPS_ON, auth = ALL) => dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, auth, req(tools));+const text = (res) => res.result?.content?.[0]?.text || '';+const out = (res) => res.result?.structuredContent;+const previewIdOf = (res) => res.result?._meta?.['three.ws/preview']?.preview_id;++const NEW_TOOLS = {+ get_portfolio: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ get_balance_history: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ get_pnl: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ sniper_status: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ sniper_activate_preview: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ sniper_activate: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },+ sniper_deactivate: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ sniper_subscribe: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ alert_rule_create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ alert_rule_list: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ alert_rule_delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },+ duel_challenge: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ duel_accept: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ duel_details: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ duel_markets: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },+};++function portfolioFixture() {+ return {+ agent: { id: AGENT, name: 'Scout', wallet: WALLET },+ network: 'devnet',+ sol_usd: 150,+ net_worth: { sol: 2, usd: 300, realized_pnl_sol: 0.25, unrealized_pnl_sol: -0.05 },+ holdings: [+ { isNative: true, symbol: 'SOL', amount: 1.5, usd_value: 225 },+ { mint: 'THREEsyntheticMint11111111111111111111111111', symbol: 'THREE', amount: 1000, usd_value: 75, cost_basis_sol: 0.55, unrealized_sol: -0.05, unrealized_pct: -9.09 },+ ],+ attribution: [{ source: 'sniper', label: 'Sniper', realized_sol: 0.25, unrealized_sol: -0.05, sells: 3 }],+ risk_flags: [{ level: 'warn', text: 'THREE is 25% of net worth.' }],+ metrics: { closed_count: 0, open_count: 1 },+ };+}++function duelFixture(over = {}) {+ return {+ id: DUEL,+ a: { name: 'Scout' },+ b: { name: 'Rival' },+ headline: 'Scout challenged Rival',+ window_kind: 'week',+ window_start: '2026-10-12T00:00:00.000Z',+ window_end: '2026-10-19T00:00:00.000Z',+ phase: 'open',+ url: `/duels/${DUEL}`,+ crowd: { a: { calls: 2, points: 200 }, b: { calls: 1, points: 50 } },+ standing: null,+ my_call: null,+ ...over,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ state.owned = true;+ state.signed = true;+ portfolio.loadPortfolioAgent.mockResolvedValue({ id: AGENT });+});++describe('threews-agent MCP: listing and annotations', () => {+ it('lists all fifteen tools with the annotations their behavior earns', async () => {+ const tools = (await list()).result.tools;+ for (const [name, hints] of Object.entries(NEW_TOOLS)) {+ const tool = tools.find((t) => t.name === name);+ expect(tool, name).toBeTruthy();+ expect(tool.annotations, name).toEqual(hints);+ }+ });++ it('keeps the two irreversible tools off by default and gates them with a confirm flag and preview id', async () => {+ const defaults = (await list('default')).result.tools.map((t) => t.name);+ expect(defaults).not.toContain('sniper_activate');+ expect(defaults).not.toContain('alert_rule_delete');++ const tools = (await list()).result.tools;+ const arm = tools.find((t) => t.name === 'sniper_activate');+ expect(Object.keys(arm.inputSchema.properties)).toEqual(expect.arrayContaining(['confirm_spend', 'preview_id']));+ expect(arm._meta['three.ws/policy']).toMatchObject({ tier: 'financial', confirmFlag: 'confirm_spend', previewTool: 'sniper_activate_preview' });+ const del = tools.find((t) => t.name === 'alert_rule_delete');+ expect(Object.keys(del.inputSchema.properties)).toEqual(expect.arrayContaining(['confirm_delete', 'preview_id']));+ expect(del._meta['three.ws/policy']).toMatchObject({ tier: 'financial', confirmFlag: 'confirm_delete', previewTool: 'alert_rule_list' });+ });+});++describe('portfolio tools', () => {+ it('get_portfolio values the wallet and lists holdings with cost basis and risk flags', async () => {+ portfolio.portfolioWithSnapshot.mockResolvedValue(portfolioFixture());+ const res = await call('get_portfolio', { agent_id: AGENT, network: 'devnet' });+ expect(portfolio.loadPortfolioAgent).toHaveBeenCalledWith(AGENT, USER);+ expect(portfolio.portfolioWithSnapshot).toHaveBeenCalledWith({ agentId: AGENT, network: 'devnet' });+ expect(text(res)).toContain('Scout on devnet');+ expect(text(res)).toContain('Net worth 2.0000 SOL = $300');+ expect(text(res)).toContain('- THREE: 1000 worth $75, cost 0.5500 SOL, unrealized -0.0500 SOL (-9.09%)');+ expect(text(res)).toContain('Risk flags: warn: THREE is 25% of net worth.');+ });++ it('refuses another account\'s agent with the store\'s reason', async () => {+ portfolio.loadPortfolioAgent.mockRejectedValue(new portfolio.PortfolioAccessError('forbidden', 'That agent belongs to another account.', 403));+ const res = await call('get_pnl', { agent_id: AGENT });+ expect(res.result.isError).toBe(true);+ expect(out(res)).toMatchObject({ ok: false, reason: 'forbidden' });+ expect(portfolio.portfolioWithSnapshot).not.toHaveBeenCalled();+ });++ it('needs a signed-in caller', async () => {+ const res = await call('get_balance_history', { agent_id: AGENT }, ANON);+ expect(out(res)).toMatchObject({ reason: 'auth_required' });+ });++ it('get_pnl reports n/a win rate and ROI before any trade has closed', async () => {+ portfolio.portfolioWithSnapshot.mockResolvedValue(portfolioFixture());+ const res = await call('get_pnl', { agent_id: AGENT, network: 'devnet' });+ expect(text(res)).toContain('0 closed, 1 open, win rate n/a, ROI n/a');+ expect(text(res)).toContain('- Sniper: realized 0.2500 SOL');+ });++ it('get_balance_history passes the window and thinning through', async () => {+ portfolio.getBalanceHistory.mockResolvedValue({+ days: 7, network: 'devnet', snapshot_count: 3, note: 'n',+ summary: { start_sol: 1, end_sol: 2, change_sol: 1, change_pct: 100, start_usd: 150, end_usd: 300, peak_sol: 2, max_drawdown_pct: 0 },+ realized_curve: [{ date: '2026-10-09', cumulative_realized_sol: 0.25 }],+ });+ const res = await call('get_balance_history', { agent_id: AGENT, network: 'devnet', days: 7, max_points: 10 });+ expect(portfolio.getBalanceHistory).toHaveBeenCalledWith({ agentId: AGENT, network: 'devnet', days: 7, maxPoints: 10 });+ expect(text(res)).toContain('1.0000 SOL to 2.0000 SOL');+ expect(text(res)).toContain('2026-10-09 0.2500 SOL');+ });+});++describe('sniper tools', () => {+ const sizing = { agent_id: AGENT, network: 'devnet', per_trade_sol: 0.01, daily_budget_sol: 0.05, stop_loss_pct: 25 };++ function previewFixture(over = {}) {+ return {+ agent: { id: AGENT, name: 'Scout', wallet: WALLET }, network: 'devnet', real_funds: false, trigger: 'new_mint',+ trigger_description: 'every new launch that passes the filters', asset: 'SOL', recipient: 'the launch bonding curve of each coin bought',+ per_trade_sol: 0.01, daily_budget_sol: 0.05, stop_loss_pct: 25, take_profit_pct: null, max_concurrent_positions: 3,+ wallet_sol: 1.2, checks: [{ ok: true, label: 'wallet provisioned' }], executable: true, blocked_by: [], ...over,+ };+ }++ it('the preview shows chain, asset, recipient, wallet and every check before anything is armed', async () => {+ sniper.previewActivation.mockResolvedValue(previewFixture());+ const res = await call('sniper_activate_preview', sizing);+ expect(text(res)).toContain('on Solana devnet (devnet, no real funds)');+ expect(text(res)).toContain(`in SOL, from the agent wallet ${WALLET}`);+ expect(text(res)).toContain('Recipient: the launch bonding curve of each coin bought.');+ expect(text(res)).toContain('Fires on every new launch that passes the filters.');+ expect(text(res)).toContain('[ok] wallet provisioned');+ expect(previewIdOf(res)).toMatch(/^p_/);+ expect(sniper.activateSniper).not.toHaveBeenCalled();+ });++ it('refuses to arm without a preview, or with sizing that drifted from it', async () => {+ const none = await call('sniper_activate', { ...sizing, confirm_spend: true });+ expect(out(none).reason).toBe('preview_required');++ sniper.previewActivation.mockResolvedValue(previewFixture());+ const preview_id = previewIdOf(await call('sniper_activate_preview', sizing));+ const drifted = await call('sniper_activate', { ...sizing, per_trade_sol: 0.02, confirm_spend: true, preview_id });+ expect(out(drifted).reason).toBe('preview_mismatch');+ expect(sniper.activateSniper).not.toHaveBeenCalled();+ });++ it('arms with the exact preview and confirm_spend, once', async () => {+ sniper.previewActivation.mockResolvedValue(previewFixture());+ sniper.activateSniper.mockResolvedValue({ agent_name: 'Scout', trigger: 'new_mint', per_trade_sol: 0.01, daily_budget_sol: 0.05, stop_loss_pct: 25 });+ const preview_id = previewIdOf(await call('sniper_activate_preview', sizing));++ const unconfirmed = await call('sniper_activate', { ...sizing, preview_id });+ expect(out(unconfirmed).reason).toBe('confirmation_required');++ const armed = await call('sniper_activate', { ...sizing, confirm_spend: true, preview_id });+ expect(out(armed)).toMatchObject({ ok: true });+ expect(sniper.activateSniper).toHaveBeenCalledTimes(1);+ expect(sniper.activateSniper.mock.calls[0][0]).toMatchObject({ userId: USER, agentId: AGENT, network: 'devnet' });++ const replay = await call('sniper_activate', { ...sizing, confirm_spend: true, preview_id });+ expect(out(replay).reason).toBe('preview_unknown');+ expect(sniper.activateSniper).toHaveBeenCalledTimes(1);+ });++ it('will not arm a mainnet sniper without the signed real-funds agreement', async () => {+ state.signed = false;+ const main = { ...sizing, network: 'mainnet' };+ sniper.previewActivation.mockResolvedValue(previewFixture({ network: 'mainnet', real_funds: true }));+ const preview_id = previewIdOf(await call('sniper_activate_preview', main));+ const res = await call('sniper_activate', { ...main, confirm_spend: true, preview_id });+ expect(out(res).reason).toBe('risk_ack_required');+ expect(sniper.activateSniper).not.toHaveBeenCalled();+ });++ it('a read-only grant can read status but cannot arm or disarm', async () => {+ sniper.sniperStatus.mockResolvedValue({ worker: { state: 'live', network: 'devnet' }, strategies: [], armed_count: 0 });+ expect(text(await call('sniper_status', {}, READONLY))).toContain('Sniper worker: live on devnet.');+ const res = await call('sniper_deactivate', { agent_id: AGENT }, READONLY);+ expect(out(res).reason).toBe('insufficient_scope');+ expect(sniper.deactivateSniper).not.toHaveBeenCalled();+ });++ it('disarms with the kill switch, and says so when there was nothing to disarm', async () => {+ sniper.deactivateSniper.mockResolvedValueOnce({ existed: true, agent_name: 'Scout', kill_switch: true, positions: { open: 2 } });+ const res = await call('sniper_deactivate', { agent_id: AGENT, network: 'devnet', kill: true });+ expect(sniper.deactivateSniper).toHaveBeenCalledWith({ userId: USER, agentId: AGENT, network: 'devnet', kill: true });+ expect(text(res)).toBe('Disarmed Scout on devnet and set the kill switch. 2 positions remain open under their exits.');++ sniper.deactivateSniper.mockResolvedValueOnce({ existed: false });+ expect(text(await call('sniper_deactivate', { agent_id: AGENT }))).toContain('nothing to disarm');+ });++ it('maps a designed store refusal to a tool refusal', async () => {+ sniper.deactivateSniper.mockRejectedValue(new sniper.SniperControlError('not_your_agent', 'That agent is not one of yours.'));+ const res = await call('sniper_deactivate', { agent_id: AGENT });+ expect(out(res)).toMatchObject({ ok: false, reason: 'not_your_agent' });+ });+});++describe('sniper_subscribe', () => {+ const FEED = { id: 7, slug: 'alpha', title: 'Alpha calls', network: 'devnet', publisher_agent_id: OPPONENT };++ it('subscribes on paper only, whatever the caller asks', async () => {+ signals.loadSubscribableFeed.mockResolvedValue(FEED);+ signals.upsertSignalSubscription.mockImplementation(async ({ knobs }) => ({ id: 3, base_sol: knobs.baseSol, max_per_trade_sol: knobs.maxPerTrade, copy_exits: knobs.copyExits }));+ const res = await call('sniper_subscribe', { action: 'subscribe', agent_id: AGENT, feed_id: 7, base_sol: 0.02 });+ expect(signals.upsertSignalSubscription.mock.calls[0][0].knobs.mode).toBe('simulate');+ expect(text(res)).toContain('Scout now follows "Alpha calls" on paper (#3)');++ const live = await call('sniper_subscribe', { action: 'subscribe', agent_id: AGENT, feed_id: 7, mode: 'live' });+ expect(live.error?.code ?? live.result?.isError).toBeTruthy();+ expect(signals.upsertSignalSubscription).toHaveBeenCalledTimes(1);+ });++ it('leaves a live subscription to the owner', async () => {+ signals.loadSubscribableFeed.mockResolvedValue(FEED);+ signals.existingSubscription.mockResolvedValue({ id: 4, mode: 'live', status: 'active' });+ const res = await call('sniper_subscribe', { action: 'subscribe', agent_id: AGENT, feed_id: 7 });+ expect(out(res)).toMatchObject({ reason: 'live_subscription_exists', subscription_id: 4 });++ signals.loadSignalSubscription.mockResolvedValue({ id: 4, mode: 'live', status: 'paused' });+ const resume = await call('sniper_subscribe', { action: 'resume', subscription_id: 4 });+ expect(out(resume).reason).toBe('live_resume_requires_owner');+ expect(signals.setSignalSubscriptionStatus).not.toHaveBeenCalled();+ });++ it('refuses an agent the caller does not own', async () => {+ state.owned = false;+ const res = await call('sniper_subscribe', { action: 'subscribe', agent_id: AGENT, feed_id: 7 });+ expect(out(res).reason).toBe('not_your_agent');+ expect(signals.loadSubscribableFeed).not.toHaveBeenCalled();+ });++ it('pauses and kills an existing subscription', async () => {+ signals.loadSignalSubscription.mockResolvedValue({ id: 5, mode: 'simulate', status: 'active' });+ signals.setSignalSubscriptionStatus.mockResolvedValue({ id: 5, status: 'paused' });+ expect(text(await call('sniper_subscribe', { action: 'pause', subscription_id: 5 }))).toBe('Subscription #5 is now paused.');+ signals.setSignalSubscriptionKilled.mockResolvedValue({ id: 5 });+ expect(text(await call('sniper_subscribe', { action: 'kill', subscription_id: 5 }))).toContain('Killed subscription #5');+ expect(signals.setSignalSubscriptionKilled).toHaveBeenCalledWith({ userId: USER, subId: 5, killed: true });+ });+});++describe('alert rule tools', () => {+ const RULE_ROW = { id: RULE, kind: 'launch_match', label: 'Cats', enabled: true, last_fired_at: null, filters: { name_pattern: '*cat*', min_safety_score: 60 } };++ it('creates a launch_match rule that always delivers to the owner', async () => {+ alerts.createAlertRule.mockResolvedValue(RULE_ROW);+ const res = await call('alert_rule_create', { kind: 'launch_match', label: 'Cats', filters: { name_pattern: '*cat*', min_safety_score: 60 } });+ expect(alerts.createAlertRule).toHaveBeenCalledWith(USER, expect.objectContaining({ kind: 'launch_match', deliver_in_app: true, enabled: true }));+ expect(text(res)).toContain(`Created alert rule ${RULE}: Cats`);+ expect(text(res)).toContain('bell, by push, and in your paired chats');+ });++ it('rejects an unknown filter before the store sees it', async () => {+ const res = await call('alert_rule_create', { kind: 'launch_match', filters: { favourite_colour: 'blue' } });+ expect(res.error?.code ?? res.result?.isError).toBeTruthy();+ expect(alerts.createAlertRule).not.toHaveBeenCalled();+ });++ it('surfaces the store\'s validation issues', async () => {+ alerts.createAlertRule.mockRejectedValue(new alerts.AlertRuleError('validation_error', 'launch_match needs at least one filter', 400, [{ path: 'filters' }]));+ const res = await call('alert_rule_create', { kind: 'launch_match', filters: {} });+ expect(out(res)).toMatchObject({ ok: false, reason: 'validation_error', issues: [{ path: 'filters' }] });+ });++ it('deletes only with a preview of the same rule and confirm_delete', async () => {+ alerts.listAlertRules.mockResolvedValue([RULE_ROW]);+ alerts.deleteAlertRule.mockResolvedValue(RULE);++ expect(out(await call('alert_rule_delete', { rule_id: RULE, confirm_delete: true })).reason).toBe('preview_required');++ const listed = await call('alert_rule_list', { rule_id: RULE });+ expect(text(listed)).toContain(`[${RULE}] Cats (launch_match, on, never fired)`);+ const preview_id = previewIdOf(listed);+ const other = await call('alert_rule_delete', { rule_id: 'a1e47000-0000-4000-8000-000000000999', confirm_delete: true, preview_id });+ expect(out(other).reason).toBe('preview_mismatch');+ expect(alerts.deleteAlertRule).not.toHaveBeenCalled();++ const res = await call('alert_rule_delete', { rule_id: RULE, confirm_delete: true, preview_id });+ expect(text(res)).toBe(`Deleted alert rule ${RULE}.`);+ expect(alerts.deleteAlertRule).toHaveBeenCalledWith(USER, RULE);+ });++ it('alert_rule_list with an unknown rule_id is a refusal, not an empty list', async () => {+ alerts.listAlertRules.mockResolvedValue([]);+ expect(out(await call('alert_rule_list', { rule_id: RULE })).reason).toBe('not_found');+ });+});++describe('duel tools', () => {+ const challengeRow = (over = {}) => ({+ id: CHALLENGE, challenger: { name: 'Scout' }, challenged: { name: 'Rival' }, window_kind: 'week', status: 'pending',+ expires_at: '2026-10-12T06:00:00.000Z', message: 'Bring it', can_respond: false, can_cancel: true, ...over,+ });++ it('duel_challenge maps its arguments and reports who was notified', async () => {+ challenges.createChallenge.mockResolvedValue({ ...challengeRow(), notified: { bell: true, push: 2, telegram: false } });+ const res = await call('duel_challenge', { agent_id: AGENT, opponent_agent_id: OPPONENT, window: 'week', message: 'Bring it' });+ expect(challenges.createChallenge).toHaveBeenCalledWith({ userId: USER, challengerAgentId: AGENT, challengedAgentId: OPPONENT, windowKind: 'week', message: 'Bring it' });+ expect(text(res)).toContain(`Challenge ${CHALLENGE} sent: Scout vs Rival, week window.`);+ expect(text(res)).toContain('notified by bell, push.');+ });++ it('duel_challenge needs sign-in and a write scope', async () => {+ expect(out(await call('duel_challenge', { agent_id: AGENT, opponent_agent_id: OPPONENT }, ANON)).reason).toBe('auth_required');+ expect(out(await call('duel_challenge', { agent_id: AGENT, opponent_agent_id: OPPONENT }, READONLY)).reason).toBe('insufficient_scope');+ expect(challenges.createChallenge).not.toHaveBeenCalled();+ });++ it('duel_accept refuses with the store\'s reason and opens the duel on accept', async () => {+ challenges.respondChallenge.mockRejectedValueOnce(new challenges.DuelChallengeError('not_challenged', 'Only the challenged agent\'s owner can accept or decline. You can cancel it.', 403));+ expect(out(await call('duel_accept', { challenge_id: CHALLENGE })).reason).toBe('not_challenged');++ challenges.respondChallenge.mockResolvedValueOnce({ challenge: challengeRow({ status: 'accepted' }), duel: duelFixture() });+ const res = await call('duel_accept', { challenge_id: CHALLENGE, response: 'accept' });+ expect(text(res)).toContain('Accepted. The duel is open: Scout vs Rival.');+ expect(text(res)).toContain('week window 2026-10-12 to 2026-10-18 (UTC), open.');+ // A challenge duel's headline only restates the matchup.+ expect(text(res)).not.toContain('Scout vs Rival: Scout challenged Rival');+ });++ it('duel_details needs an id and shows a challenge with its duel', async () => {+ expect(out(await call('duel_details', {})).reason).toBe('invalid_request');+ challenges.getChallenge.mockResolvedValue({ challenge: challengeRow({ status: 'accepted', duel_url: `/duels/${DUEL}` }), duel: duelFixture() });+ const res = await call('duel_details', { challenge_id: CHALLENGE });+ expect(text(res)).toContain('Message: "Bring it"');+ expect(text(res)).toContain('Crowd: 2 calls (200 pts) on Scout, 1 calls (50 pts) on Rival.');+ });++ it('duel_details reads a public duel without sign-in, and a one-day window as one date', async () => {+ duels.getDuel.mockResolvedValue(duelFixture({ window_kind: 'day', window_start: '2026-10-11T00:00:00.000Z', window_end: '2026-10-12T00:00:00.000Z', headline: 'Who trades the weekend better?' }));+ const res = await call('duel_details', { duel_id: DUEL }, ANON);+ expect(duels.getDuel).toHaveBeenCalledWith(DUEL, { userId: null });+ expect(text(res)).toContain('Scout vs Rival: Who trades the weekend better?');+ expect(text(res)).toContain('day window 2026-10-11 (UTC), open.');+ });++ it('duel_markets leaderboard ranks challenge records and names the asked-for agent', async () => {+ challenges.challengeLeaderboard.mockResolvedValue({+ leaders: [{ rank: 1, name: 'Scout', wins: 3, losses: 1, voids: 0, win_rate: 0.75, realized_pnl_sol: 1.2, trader: `/trader/${AGENT}` }],+ agent: { rank: 4, name: 'Rival', wins: 1, losses: 2 },+ challenges: { pending: 2, accepted: 5 },+ });+ const res = await call('duel_markets', { view: 'leaderboard', agent_id: OPPONENT });+ expect(challenges.challengeLeaderboard).toHaveBeenCalledWith({ limit: 20, agentId: OPPONENT });+ expect(text(res)).toContain('1. Scout: 3W 1L, win rate 75%, +1.2000 SOL');+ expect(text(res)).toContain('Rival: rank 4, 1W 2L.');+ expect(text(res)).toContain('2 challenges pending, 5 accepted.');+ });++ it('duel_markets challenges view needs sign-in', async () => {+ expect(out(await call('duel_markets', { view: 'challenges' }, ANON)).reason).toBe('auth_required');+ });+});diff --git a/tests/mcp-remote-annotations.test.js b/tests/mcp-remote-annotations.test.jsindex b9f6b95e2..7772ec4f2 100644--- a/tests/mcp-remote-annotations.test.js+++ b/tests/mcp-remote-annotations.test.js@@ -51,6 +51,9 @@ const CATALOGS = [// commit an agent or move USDC through marketplace escrow// predictions_open, predictions_close, predictions_redeem// trade or settle prediction-market positions in USDC+// sniper_activate arms a launch sniper that spends SOL from the agent's+// wallet on every launch that passes its filters+// alert_rule_delete removes an alert rule and its delivery history for good// Acting on the physical world:// home_activate runs a scene or script in a real house, which moves// locks, covers and alarms@@ -71,6 +74,7 @@ const DESTRUCTIVE_TOOLS = new Set(['create_marketplace_listing', 'delist_marketplace_listing', 'place_bid', 'buy_now','accept_marketplace_bid', 'withdraw_marketplace_bid','predictions_open', 'predictions_close', 'predictions_redeem',+ 'sniper_activate', 'alert_rule_delete','home_activate', 'home_call','agent_mail_create', 'agent_mail_send', 'agent_mail_reply',]);diff --git a/tests/portfolio-sniper-duels-helpers.test.js b/tests/portfolio-sniper-duels-helpers.test.jsnew file mode 100644index 000000000..2ef8b64c2--- /dev/null+++ b/tests/portfolio-sniper-duels-helpers.test.js@@ -0,0 +1,245 @@+// The pure logic under the portfolio, launch-alert, sniper, signal and duel+// tools: the launch_match matcher and its schema, the realized-P&L curve and+// series thinning, the P&L digest, exact lamport conversion, the challenge+// view, the subscription knobs, and the alert owner fan-out.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));+vi.mock('../api/_lib/notify.js', () => ({ insertNotification: vi.fn() }));++const { sql } = await import('../api/_lib/db.js');+const { insertNotification } = await import('../api/_lib/notify.js');+const { compileNamePattern, launchMatchesRule, buildLaunchMatchPayload, describeLaunchFilters } = await import('../api/_lib/pump-alert-eval.js');+const { createRuleSchema, validateUpdate, normalizeForKind } = await import('../api/alerts/_rules.js');+const { realizedCurve, bucketSnapshots, pnlDigest } = await import('../api/_lib/portfolio-history.js');+const { solToLamports, lamportsToSol } = await import('../api/_lib/sniper-control.js');+const { challengeView } = await import('../api/_lib/duel-challenges.js');+const { subscriptionKnobs } = await import('../api/_lib/signal-subscription-control.js');+const { deliverAlert } = await import('../api/_lib/alert-delivery.js');++const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const rule = (filters) => ({ id: 'r1', kind: 'launch_match', filters });+const launch = (over = {}) => ({+ mint: MINT, name: 'Three Cat', symbol: 'TCAT', market_cap_usd: 12_000, quality_score: 72,+ creator_launches: 3, creator_graduated: 1, risk_flags: ['sniped'], has_socials: true, ...over,+});++describe('compileNamePattern', () => {+ it('matches anywhere without a star, anchored with one, case-insensitively', () => {+ expect(compileNamePattern('dog')('HOTDOG')).toBe(true);+ expect(compileNamePattern('dog*')('HOTDOG')).toBe(false);+ expect(compileNamePattern('*dog')('HOTDOG')).toBe(true);+ expect(compileNamePattern('cat|dog')('Hotdogs')).toBe(true);+ });++ it('treats every regex metacharacter except * and | as a literal', () => {+ const m = compileNamePattern('a.b(c)+');+ expect(m('a.b(c)+')).toBe(true);+ expect(m('axb(c)')).toBe(false);+ expect(compileNamePattern(' | ')).toBe(null);+ });+});++describe('launchMatchesRule', () => {+ it('returns every filter that held when the launch passes them all', () => {+ const held = launchMatchesRule(rule({+ name_pattern: '*cat*', min_market_cap_usd: 5000, max_market_cap_usd: 50_000, min_safety_score: 60,+ min_creator_graduated: 1, max_creator_launches: 5, exclude_risk_flags: ['dev_dumped'], require_socials: true,+ }), launch());+ expect(held).toEqual([+ 'name matches "*cat*"', 'mcap >= $5,000', 'mcap <= $50,000', 'safety 72 >= 60',+ 'creator graduated 1', 'creator launches 3 <= 5', 'none of dev_dumped', 'has socials',+ ]);+ });++ it('matches the symbol when the name misses', () => {+ expect(launchMatchesRule(rule({ name_pattern: 'tcat' }), launch({ name: 'Other' }))).toEqual(['name matches "tcat"']);+ });++ it('misses on any failing filter', () => {+ expect(launchMatchesRule(rule({ max_market_cap_usd: 10_000 }), launch())).toBe(null);+ expect(launchMatchesRule(rule({ exclude_risk_flags: ['sniped'] }), launch())).toBe(null);+ expect(launchMatchesRule(rule({ min_safety_score: 80 }), launch())).toBe(null);+ expect(launchMatchesRule(rule({ require_socials: true }), launch({ has_socials: false }))).toBe(null);+ });++ it('treats missing launch data as a miss, never a silent pass', () => {+ expect(launchMatchesRule(rule({ min_market_cap_usd: 0 }), launch({ market_cap_usd: null }))).toBe(null);+ expect(launchMatchesRule(rule({ min_safety_score: 0 }), launch({ quality_score: undefined }))).toBe(null);+ expect(launchMatchesRule(rule({ max_creator_launches: 10 }), launch({ creator_launches: null }))).toBe(null);+ });++ it('only applies to launch_match rules', () => {+ expect(launchMatchesRule({ kind: 'new_mint', filters: {} }, launch())).toBe(null);+ });++ it('builds a payload that links the coin and carries what matched', () => {+ const p = buildLaunchMatchPayload({ id: 'r1' }, launch({ first_seen_at: '2026-10-10T00:00:00Z' }), ['safety 72 >= 60']);+ expect(p).toMatchObject({ kind: 'launch_match', event_id: `launch:${MINT}`, safety_score: 72, matched: ['safety 72 >= 60'], link: `/coin/${MINT}`, at: '2026-10-10T00:00:00.000Z' });+ });++ it('describes a filter set in plain language', () => {+ expect(describeLaunchFilters({ name_pattern: 'cat', min_market_cap_usd: 5000, max_market_cap_usd: 50_000, require_socials: true }))+ .toBe('"cat" · $5k to $50k · socials');+ });+});++describe('launch_match rule schema', () => {+ it('accepts a filter-only rule', () => {+ const r = createRuleSchema.safeParse({ kind: 'launch_match', filters: { name_pattern: 'cat', exclude_risk_flags: ['bundle_launch'] } });+ expect(r.success).toBe(true);+ });++ it('needs at least one filter, a sane cap band, and no target', () => {+ const paths = (body) => createRuleSchema.safeParse(body).error?.issues.map((i) => i.path.join('.'));+ expect(paths({ kind: 'launch_match', filters: {} })).toContain('filters');+ expect(paths({ kind: 'launch_match', filters: { require_socials: false } })).toContain('filters');+ expect(paths({ kind: 'launch_match', filters: { min_market_cap_usd: 10, max_market_cap_usd: 5 } })).toContain('filters.min_market_cap_usd');+ expect(paths({ kind: 'launch_match', target_mint: MINT, filters: { name_pattern: 'x' } })).toContain('kind');+ });++ it('rejects unknown filter keys and unknown risk flags', () => {+ expect(createRuleSchema.safeParse({ kind: 'launch_match', filters: { colour: 'blue' } }).success).toBe(false);+ expect(createRuleSchema.safeParse({ kind: 'launch_match', filters: { exclude_risk_flags: ['spooky'] } }).success).toBe(false);+ });++ it('clears filters when a rule leaves the launch_match kind, and drops null filters on it', () => {+ expect(normalizeForKind({ kind: 'graduation', filters: { name_pattern: 'x' } }).filters).toBe(null);+ expect(normalizeForKind({ kind: 'launch_match', filters: { name_pattern: 'x', min_safety_score: null } }).filters).toEqual({ name_pattern: 'x' });+ const r = validateUpdate({ kind: 'launch_match', filters: { name_pattern: 'x' }, deliver_in_app: true }, { filters: {} });+ expect(r.ok).toBe(false);+ });+});++describe('realizedCurve', () => {+ const pos = (day, lamports, status = 'closed') => ({ status, closed_at: new Date(Date.UTC(2026, 9, day, 12)).toISOString(), realized_pnl_lamports: lamports });++ it('accumulates closes per UTC day, oldest first, with USD when a price is known', () => {+ const curve = realizedCurve([pos(3, -0.5e9), pos(1, 1e9), pos(1, 0.25e9), pos(2, 0, 'open')], { solUsd: 100 });+ expect(curve).toEqual([+ { date: '2026-10-01', cumulative_realized_sol: 1.25, cumulative_realized_usd: 125, trades_closed: 2 },+ { date: '2026-10-03', cumulative_realized_sol: 0.75, cumulative_realized_usd: 75, trades_closed: 1 },+ ]);+ });++ it('hides days before the window but keeps their P&L in the running total', () => {+ const curve = realizedCurve([pos(1, 1e9), pos(5, 1e9)], { sinceMs: Date.UTC(2026, 9, 4) });+ expect(curve).toEqual([{ date: '2026-10-05', cumulative_realized_sol: 2, cumulative_realized_usd: null, trades_closed: 1 }]);+ });+});++describe('bucketSnapshots', () => {+ it('leaves a short series alone and thins a long one keeping both ends exact', () => {+ const rows = Array.from({ length: 101 }, (_, i) => i);+ expect(bucketSnapshots(rows.slice(0, 5), 10)).toHaveLength(5);+ const thin = bucketSnapshots(rows, 5);+ expect(thin).toEqual([0, 25, 50, 75, 100]);+ });+});++describe('pnlDigest', () => {+ it('totals realized and unrealized, prices them, and ranks open winners and losers', () => {+ const d = pnlDigest({+ agent: { id: 'a' }, network: 'mainnet', sol_usd: 100,+ net_worth: { sol: 5, usd: 500, realized_pnl_sol: 1, unrealized_pnl_sol: -0.25 },+ holdings: [+ { mint: 'm1', symbol: 'A', unrealized_sol: 0.5 },+ { mint: 'm2', symbol: 'B', unrealized_sol: -0.75 },+ { mint: 'm3', symbol: 'C', unrealized_sol: 0.1 },+ { isNative: true, unrealized_sol: null },+ ],+ attribution: [{ source: 'sniper' }],+ metrics: { closed_count: 4, open_count: 3, win_rate: 0.5 },+ });+ expect(d.totals).toMatchObject({ realized_sol: 1, unrealized_sol: -0.25, total_sol: 0.75, total_usd: 75, realized_usd: 100 });+ expect(d.top_winners.map((h) => h.symbol)).toEqual(['A', 'C']);+ expect(d.top_losers.map((h) => h.symbol)).toEqual(['B']);+ expect(d.performance).toMatchObject({ closed_trades: 4, open_trades: 3, win_rate: 0.5, roi_pct: null });+ expect(d.by_source).toEqual([{ source: 'sniper' }]);+ });++ it('reports no total when neither side is known', () => {+ expect(pnlDigest({ net_worth: {}, sol_usd: null }).totals.total_sol).toBe(null);+ });+});++describe('lamport conversion', () => {+ it('converts exactly, without float drift', () => {+ expect(solToLamports(0.1)).toBe('100000000');+ expect(solToLamports(1.000000001)).toBe('1000000001');+ expect(solToLamports('2.5')).toBe('2500000000');+ expect(lamportsToSol('1500000000')).toBe(1.5);+ });++ it('refuses zero, negatives, garbage and dust below one lamport', () => {+ for (const bad of [0, -1, 'x', NaN, Infinity, 1e-10]) expect(solToLamports(bad)).toBe(null);+ });+});++describe('challengeView', () => {+ const row = {+ id: 'c1', status: 'pending', network: 'mainnet', window_kind: 'day', challenger_user: 'u1', challenged_user: 'u2',+ challenger_agent: 'a1', challenged_agent: 'a2', challenger_name: 'Scout', challenged_name: 'Rival',+ expires_at: '2026-10-12T00:00:00Z', created_at: '2026-10-10T00:00:00Z', responded_at: null, market_id: null,+ };++ it('lets only the challenged owner respond and only the challenger cancel', () => {+ expect(challengeView(row, 'u2')).toMatchObject({ your_role: 'challenged', can_respond: true, can_cancel: false });+ expect(challengeView(row, 'u1')).toMatchObject({ your_role: 'challenger', can_respond: false, can_cancel: true });+ expect(challengeView(row, 'u3')).toMatchObject({ your_role: null, can_respond: false, can_cancel: false });+ expect(challengeView({ ...row, status: 'accepted', market_id: 'd1' }, 'u2')).toMatchObject({ can_respond: false, duel_url: '/duels/d1' });+ });+});++describe('subscriptionKnobs', () => {+ it('defaults to paper and clamps every size into the mirror engine range', () => {+ expect(subscriptionKnobs({})).toEqual({+ mode: 'simulate', billing: 'per_signal', baseSol: 0.05, sizeScaling: 1, maxPerTrade: 0.25, slippageBps: 300, firewallLevel: 'block', copyExits: true,+ });+ const k = subscriptionKnobs({ base_sol: 999, max_per_trade_sol: 0, slippage_bps: 9999, copy_exits: false, mode: 'anything' });+ expect(k).toMatchObject({ mode: 'simulate', baseSol: 10, maxPerTrade: 0.001, slippageBps: 5000, copyExits: false });+ });+});++describe('deliverAlert owner fan-out', () => {+ const alertRule = (over = {}) => ({ id: 'r1', user_id: 'u1', deliver_in_app: true, webhook_url: null, telegram_chat: null, ...over });+ const payload = { kind: 'launch_match', mint: MINT, symbol: 'TCAT', market_cap_usd: 12_000, matched: [] };++ beforeEach(() => vi.clearAllMocks());++ it('goes through the platform notification fan-out and names every channel reached', async () => {+ insertNotification.mockResolvedValue({ id: 'n1', delivered: { push: 2, telegram: 1, apns: 0 } });+ const res = await deliverAlert(alertRule(), payload);+ expect(insertNotification).toHaveBeenCalledWith('u1', 'pump_alert', expect.objectContaining({ link: `/coin/${MINT}`, summary: expect.any(String) }));+ expect(res.in_app).toEqual({ attempted: true, ok: true, detail: 'bell, push x2, telegram x1' });+ expect(res.webhook.attempted).toBe(false);+ expect(res.telegram.attempted).toBe(false);+ });++ it('does not post twice to a rule chat that is already a paired notify chat', async () => {+ insertNotification.mockResolvedValue({ id: 'n1', delivered: { telegram: 1 } });+ sql.mockResolvedValueOnce([{ ok: 1 }]);+ const res = await deliverAlert(alertRule({ telegram_chat: '12345' }), payload);+ expect(res.telegram).toEqual({ attempted: true, ok: true, detail: 'sent_via_paired_chat' });+ });++ it('reports a muted owner instead of a false success', async () => {+ insertNotification.mockResolvedValue({ id: null, in_app: false, delivered: {} });+ const res = await deliverAlert(alertRule(), payload);+ expect(res.in_app).toEqual({ attempted: true, ok: false, detail: 'muted_by_preferences' });+ });++ it('keeps a fan-out failure on its own channel', async () => {+ insertNotification.mockRejectedValue(new Error('db down'));+ const res = await deliverAlert(alertRule(), payload);+ expect(res.in_app).toMatchObject({ attempted: true, ok: false });+ expect(res.in_app.detail).toContain('db down');+ });++ it('skips the owner channel when the rule turned it off', async () => {+ const res = await deliverAlert(alertRule({ deliver_in_app: false }), payload);+ expect(insertNotification).not.toHaveBeenCalled();+ expect(res.in_app.attempted).toBe(false);+ });+});diff --git a/vercel.json b/vercel.jsonindex 5bf62b51a..6dfdf9a11 100644--- a/vercel.json+++ b/vercel.json@@ -7124,6 +7124,10 @@{"path": "/api/cron/duels-tick","schedule": "*/15 * * * *"+ },+ {+ "path": "/api/cron/agent-portfolio-snapshots",+ "schedule": "23 * * * *"}]}