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(predictions): record strategy decisions in shadow mode and scan Solana event contracts for fee-aware arbitrage
nirholas5eb7890ff435
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex d7e135abe..b39cecd4e 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -132,6 +132,7 @@ packages, a generated standalone GitHub mirror). See| Agent mail (inbox, rules, send controls) | Page [pages/agent-mail.html](pages/agent-mail.html) `→ /agents/:id/mail` and `/agent-mail` + [src/agent-mail.js](src/agent-mail.js), REST [api/v1/agent-mail.js](api/v1/agent-mail.js) `→ /api/v1/agents/:id/mail/*`, MCP [api/_mcp/tools/mail.js](api/_mcp/tools/mail.js), service [api/_lib/mail/](api/_lib/mail) (service, controls, untrusted, rules, inbound, content rules, spam, threading, extract, otp), webhook [api/mail/inbound.js](api/mail/inbound.js), migration [api/_lib/migrations/20261010184500_agent_mail_controls.sql](api/_lib/migrations/20261010184500_agent_mail_controls.sql) | Built, ships with the next deploy; outside delivery waits on the `agents.three.ws` DNS records (owner) | Each agent can hold an address on `agents.three.ws`: quote-then-confirm mailbox creation and sends that show the exact recipients and body first, content rules, a per-agent recipient allowlist and daily send cap that only a signed-in owner can change, instant delivery between agent mailboxes, received mail fenced as untrusted data on every surface, and inbox tools (`inbox_wait_for_code`) that extract one-time codes and sign-in links for signups from owner-listed, authenticated senders only (migration [20261023160000_agent_mail_code_senders.sql](api/_lib/migrations/20261023160000_agent_mail_code_senders.sql)). Owner rules turn matching mail into a read-only, zero-budget agent run, either at once or after a yes in /approvals. Docs: [docs/agent-mail.md](docs/agent-mail.md). Tests: [tests/agent-mail-controls.test.js](tests/agent-mail-controls.test.js) || Agent commerce (invoices, sends, offers, limit requests) | Owner console [pages/commerce.html](pages/commerce.html) `→ /commerce` and `/invoices` + [src/commerce-page.js](src/commerce-page.js), public invoice and receipt page [pages/agent-invoice.html](pages/agent-invoice.html) `→ /invoices/:id` + [src/agent-invoice-page.js](src/agent-invoice-page.js), REST [api/agent-commerce/[...route].js](api/agent-commerce/[...route].js) `→ /api/agent-commerce/*`, library [api/_lib/agent-commerce/](api/_lib/agent-commerce), MCP [api/_mcpagent/commerce-tools.js](api/_mcpagent/commerce-tools.js) on `/api/mcp-agent`, watcher cron [api/cron/agent-invoice-watch.js](api/cron/agent-invoice-watch.js), migration [api/_lib/migrations/20261010221500_agent_commerce.sql](api/_lib/migrations/20261010221500_agent_commerce.sql) | Built, ships with the next deploy | Agents and owners issue invoices in USDC, SOL or $THREE, payable by Solana Pay link or QR; a per-minute watcher matches payments by reference key and memo and moves invoices to paid, underpaid or expired, with webhooks, owner notifications and a public receipt. Paid mainnet invoices feed the earnings ledger. `agent_send` is preview-then-confirm and gated by the destination allowlist and approvals; offers sell with a quote and an explicit confirm and release the fulfillment only once the chain shows payment; `spending_setup` proposals need the owner's step-up (password, fresh sign-in or a linked-wallet signature) and can never be approved by the agent. Docs: [docs/agent-commerce.md](docs/agent-commerce.md). Tests: [tests/agent-commerce-invoices.test.js](tests/agent-commerce-invoices.test.js) || Agent perps (perpetual futures desk) | Page [pages/agent-perps.html](pages/agent-perps.html) `→ /agents/:id/perps` and `/agent-perps` + [src/agent-perps.js](src/agent-perps.js) + [src/agent-perps.css](src/agent-perps.css), REST [api/v1/agents/[id]/perps/[...path].js](api/v1/agents/[id]/perps/[...path].js) over [api/_lib/perps/routes.js](api/_lib/perps/routes.js) `→ /api/v1/agents/:id/perps/*`, MCP [api/_mcpagent/perps-tools.js](api/_mcpagent/perps-tools.js) (`perps_*` on `/api/mcp-agent`), service [api/_lib/perps/service.js](api/_lib/perps/service.js), venue contract and registry [api/_lib/perps/index.js](api/_lib/perps/index.js), venue modules [phoenix](api/_lib/perps/phoenix.js), [jupiter](api/_lib/perps/jupiter.js) and [hyperliquid](api/_lib/perps/hyperliquid.js) (signing in [hyperliquid-signing.js](api/_lib/perps/hyperliquid-signing.js), shared math in [venue-common.js](api/_lib/perps/venue-common.js), outage failover in [venue-health.js](api/_lib/perps/venue-health.js)), live probe [scripts/perps-venue-probe.mjs](scripts/perps-venue-probe.mjs), paper ledger [api/_lib/perps/paper.js](api/_lib/perps/paper.js), limits [api/_lib/perps/limits.js](api/_lib/perps/limits.js), alerts [api/_lib/perps/alerts.js](api/_lib/perps/alerts.js), cron [api/cron/perps-tick.js](api/cron/perps-tick.js), migration [api/_lib/migrations/20261010213000_perps_desk.sql](api/_lib/migrations/20261010213000_perps_desk.sql) | Built, ships with the next deploy (paper by default; live per agent once the owner turns it on) | An agent goes long or short with USDC collateral from its own Solana wallet. Every action is a preview then a confirmed, idempotent execute that refuses if the quote moved past tolerance. Mandatory per-agent leverage and per-position margin caps (2x and $25 by default), slippage and quote-move limits, a live tracker stream with PnL, funding and liquidation distance, owner alert thresholds delivered through notifications, and a kill switch that cancels and closes everything. Paper mode fills at live prices; live transactions are simulated before the agent wallet signs. Docs: [docs/perps.md](docs/perps.md). Tests: [tests/perps-desk.test.js](tests/perps-desk.test.js), [tests/perps-venues.test.js](tests/perps-venues.test.js), [tests/perps-mcp-permission.test.js](tests/perps-mcp-permission.test.js) |+| Agent predictions (shadow mode and arbitrage scanner) | Page [pages/agent-predictions.html](pages/agent-predictions.html) `→ /agents/:id/predictions` and `/agent-predictions` + [src/agent-predictions.js](src/agent-predictions.js) + [src/agent-predictions.css](src/agent-predictions.css), shadow ledger [api/_lib/predictions/shadow.js](api/_lib/predictions/shadow.js), scanner [api/_lib/predictions/arb.js](api/_lib/predictions/arb.js), fee models [api/_lib/predictions/fee-models.json](api/_lib/predictions/fee-models.json), routes in [api/_lib/predictions/routes.js](api/_lib/predictions/routes.js), migration [api/_lib/migrations/20261024020000_prediction_shadow_ledger.sql](api/_lib/migrations/20261024020000_prediction_shadow_ledger.sql) | Built, ships with the next deploy (shadow by default; live is owner-session only) | Records each strategy decision at the live order-book price without sending an order, marks it at resolution, and reports shadow beside live P&L before and after fees. A scanner finds YES plus NO pairs under $1 after venue and provider fees. Docs: [docs/predictions.md](docs/predictions.md). Tests: [tests/predictions-shadow.test.js](tests/predictions-shadow.test.js) || Papertrade reads (HyperEVM synthetic perps) | REST [api/papertrade.js](api/papertrade.js) `→ /api/papertrade?view=markets, quote, account or protocol`, MCP [api/_mcpagent/papertrade-tools.js](api/_mcpagent/papertrade-tools.js) (`papertrade_*` on `/api/mcp-agent`), client and service [api/_lib/papertrade/index.js](api/_lib/papertrade/index.js), position math [api/_lib/papertrade/math.js](api/_lib/papertrade/math.js) | Built, ships with the next deploy | Read-only window onto Papertrade: live markets priced at the Hyperliquid mid, exact open quotes (hard-bust price, capacity limits, and the payout ladder after the deadband, impact haircut and live win fee), any wallet's positions valued live, and protocol health including the payout queue. Nothing signs or trades. Docs: [docs/papertrade.md](docs/papertrade.md). Tests: [tests/papertrade-math.test.js](tests/papertrade-math.test.js) || Solana trading tools (MCP + REST) | registry [api/_lib/trading-tools/registry.js](api/_lib/trading-tools/registry.js), REST [api/v1/trading/[...path].js](api/v1/trading/[...path].js) and [api/v1/trading/index.js](api/v1/trading/index.js) over [api/_lib/trading-tools/routes.js](api/_lib/trading-tools/routes.js) `→ /api/v1/trading/*`, MCP [api/_mcpagent/trading-tools.js](api/_mcpagent/trading-tools.js) (on `/api/mcp-agent`, group `trading`), swap comparison and router transaction check [api/_lib/trading-tools/swap-routes.js](api/_lib/trading-tools/swap-routes.js), quote and guarded fill [api/_lib/trading-tools/swap.js](api/_lib/trading-tools/swap.js) through [api/agents/solana-trade.js](api/agents/solana-trade.js), research [api/_lib/trading-tools/market.js](api/_lib/trading-tools/market.js), ecosystem signals [api/_lib/trading-tools/ecosystem.js](api/_lib/trading-tools/ecosystem.js), arbitrage [api/_lib/trading-tools/arbitrage.js](api/_lib/trading-tools/arbitrage.js), live route check [scripts/check-trading-routes.mjs](scripts/check-trading-routes.mjs) (`npm run check:trading-routes`) | Built, ships with the next deploy | Ten tools an agent trades Solana with, one registry for both surfaces: token search, price, indicators, news, and market signals (one token, or with no mint the ecosystem view: macro readings, top movers and anomalies with their inputs and `as_of`). `swap_quote` compares every aggregator on net output after fees and impact and says why one route won; with `agent_id` it runs the guard chain and issues a five-minute `quote_id`. `swap_simulate` dry-runs it; `swap_execute` fills it only with `confirm_swap: true`, re-priced and refused below the approved minimum, once per quote. `arbitrage_quote` shows the non-atomic risk, a simulated worst case and a verdict, and refuses above $100 unless asked. Docs: [docs/trading-tools.md](docs/trading-tools.md) `→ /docs/trading-tools`. Tests: [tests/trading-tools-swap.test.js](tests/trading-tools-swap.test.js), [tests/trading-tools-arbitrage.test.js](tests/trading-tools-arbitrage.test.js) || Web domains (`/domains`) | [pages/domains.html](pages/domains.html) `→ /domains` + [src/domains/](src/domains), API [api/domains/[action].js](api/domains/%5Baction%5D.js) `→ /api/domains/*`, MCP [api/_mcp/tools/domains.js](api/_mcp/tools/domains.js), service [api/_lib/domains-service.js](api/_lib/domains-service.js) + [api/_lib/cloud-domains.js](api/_lib/cloud-domains.js) + [api/_lib/domain-connect.js](api/_lib/domain-connect.js), renewals [api/cron/domain-renewals.js](api/cron/domain-renewals.js), schema [api/_lib/migrations/20261011000000_web_domains.sql](api/_lib/migrations/20261011000000_web_domains.sql) | Live pending deploy | Search, price, check and register web domains through Google Cloud Domains, paid from credits behind a quote, an explicit confirm and an idempotency key, then serve an agent's public page on the domain. Coin pages carry a live domain suggestion panel. Docs: [docs/domains.md](docs/domains.md). Tests: [tests/domains-service.test.js](tests/domains-service.test.js) |diff --git a/api/_lib/migrations/20261024020000_prediction_shadow_ledger.sql b/api/_lib/migrations/20261024020000_prediction_shadow_ledger.sqlnew file mode 100644index 000000000..e88a87ede--- /dev/null+++ b/api/_lib/migrations/20261024020000_prediction_shadow_ledger.sql@@ -0,0 +1,50 @@+-- Prediction shadow ledger (api/_lib/predictions/shadow.js).+--+-- Every agent's prediction strategy defaults to shadow mode: the intended trade is+-- recorded here with the price at decision time and no order is built or sent.+-- Entries are marked to market while the market is open and settled when it+-- resolves, so the owner can compare shadow P&L with what live would have paid+-- before turning live on. Live-mode decisions are recorded in the same table+-- (mode = 'live') so the dashboard can show the two side by side.+--+-- price_at_decision the best ask for the side when the decision was made+-- entry_price average fill price from walking the order book for the stake+-- fees_usd estimated fees from fee-models.json at decision time+-- cost_usd stake spent on contracts (entry_price * contracts)+-- status open | won | lost | void (refund or unresolvable)++create table if not exists prediction_shadow_ledger (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid references users(id) on delete cascade,+ venue text not null,+ mode text not null check (mode in ('shadow', 'live')),+ market_id text not null,+ event_id text,+ title text not null,+ provider text,+ side text not null check (side in ('yes', 'no')),+ stake_usd numeric(14, 2) not null,+ contracts numeric(18, 4) not null,+ price_at_decision numeric(8, 4) not null,+ entry_price numeric(8, 4) not null,+ fees_usd numeric(14, 4) not null default 0,+ cost_usd numeric(14, 4) not null,+ edge_pct numeric(10, 4),+ reason text,+ source text not null default 'agent',+ status text not null default 'open' check (status in ('open', 'won', 'lost', 'void')),+ mark_price numeric(8, 4),+ marked_at timestamptz,+ payout_usd numeric(14, 4),+ pnl_usd numeric(14, 4),+ close_time timestamptz,+ decided_at timestamptz not null default now(),+ resolved_at timestamptz+);++create index if not exists prediction_shadow_ledger_agent_decided+ on prediction_shadow_ledger (agent_id, decided_at desc);++create index if not exists prediction_shadow_ledger_open+ on prediction_shadow_ledger (agent_id) where status = 'open';diff --git a/api/_lib/predictions/arb.js b/api/_lib/predictions/arb.jsnew file mode 100644index 000000000..e91726237--- /dev/null+++ b/api/_lib/predictions/arb.js@@ -0,0 +1,203 @@+// @ts-check+// No-arbitrage scanner for binary event contracts.+//+// A YES and a NO contract on one market together pay exactly $1 whichever way+// it resolves. When the cheapest YES ask plus the cheapest NO ask, plus every+// fee, is under $1, buying both locks in the difference. Everything here that+// decides what counts as an opportunity (fee models, minimum edge, depth) is+// data read from fee-models.json, never a constant in this file.+//+// The arithmetic is pure and unit-tested (tests/predictions-shadow.test.js).+// `scanVenue` is the only function that does I/O: it reads live markets and+// order books from a venue and never places or builds an order.++import MODELS from './fee-models.json' with { type: 'json' };+import { asksFor } from './book.js';++/** @typedef {import('./book.js').Book} Book */++const round = (n, dp = 6) => Math.round(n * 10 ** dp) / 10 ** dp + 0;++export const DEFAULT_MODELS = MODELS;++/**+ * Fee, in dollars, for buying one contract at `price` under one fee model.+ * @param {{kind: string, bps?: number, rate?: number, usd?: number}} model+ * @param {number} price probability in (0, 1)+ */+export function feePerContract(model, price) {+ if (!model) return 0;+ if (model.kind === 'bps_of_notional') return (price * (model.bps || 0)) / 10_000;+ if (model.kind === 'p_one_minus_p') return (model.rate || 0) * price * (1 - price);+ if (model.kind === 'flat_per_contract') return model.usd || 0;+ throw new Error(`unknown fee model kind: ${model.kind}`);+}++/** Total fee per contract bought at `price` on a market from `provider`. */+export function totalFee(models, provider, price) {+ const prov = (models.providers && models.providers[provider]) || models.default_provider;+ return feePerContract(models.venue, price) + feePerContract(prov, price);+}++/**+ * Walk YES and NO asks together, buying one of each per step, while the next+ * pair still clears `minEdge` after fees. Asks are [price, contracts], cheapest+ * first.+ * @param {[number, number][]} yesAsks+ * @param {[number, number][]} noAsks+ * @param {{ models?: typeof MODELS, provider?: string|null, minEdge?: number }} [opts]+ */+export function walkComplement(yesAsks, noAsks, { models = MODELS, provider = null, minEdge = models.thresholds.min_edge_per_contract } = {}) {+ let i = 0;+ let j = 0;+ let yLeft = yesAsks[0] ? yesAsks[0][1] : 0;+ let nLeft = noAsks[0] ? noAsks[0][1] : 0;+ let contracts = 0;+ let cost = 0;+ let fees = 0;+ while (i < yesAsks.length && j < noAsks.length) {+ const py = yesAsks[i][0];+ const pn = noAsks[j][0];+ const fee = totalFee(models, provider, py) + totalFee(models, provider, pn);+ const edge = 1 - py - pn - fee;+ if (edge < minEdge) break;+ const take = Math.min(yLeft, nLeft);+ if (!(take > 0)) break;+ contracts += take;+ cost += take * (py + pn);+ fees += take * fee;+ yLeft -= take;+ nLeft -= take;+ if (yLeft <= 1e-9) {+ i += 1;+ yLeft = yesAsks[i] ? yesAsks[i][1] : 0;+ }+ if (nLeft <= 1e-9) {+ j += 1;+ nLeft = noAsks[j] ? noAsks[j][1] : 0;+ }+ }+ const profit = contracts - cost - fees;+ return {+ contracts: round(contracts, 4),+ cost_usd: round(cost, 4),+ fees_usd: round(fees, 4),+ profit_usd: round(profit, 4),+ edge_pct: cost + fees > 0 ? round((profit / (cost + fees)) * 100, 4) : 0,+ };+}++/**+ * Edge at the top of the book, whether or not it clears the threshold. Negative+ * values are the normal state of an efficient market.+ * @param {Book} book+ * @param {{ models?: typeof MODELS, provider?: string|null }} [opts]+ */+export function topOfBookEdge(book, { models = MODELS, provider = null } = {}) {+ const yes = asksFor(book, 'yes')[0];+ const no = asksFor(book, 'no')[0];+ if (!yes || !no) return null;+ const fee = totalFee(models, provider, yes[0]) + totalFee(models, provider, no[0]);+ const gross = 1 - yes[0] - no[0];+ const edge = gross - fee;+ return {+ yes_ask: yes[0],+ no_ask: no[0],+ yes_size: yes[1],+ no_size: no[1],+ gross_edge: round(gross, 6),+ fees_per_contract: round(fee, 6),+ net_edge: round(edge, 6),+ net_edge_pct: round((edge / (yes[0] + no[0] + fee)) * 100, 4),+ };+}++/**+ * Score one market's book into a scanner row.+ * @param {{ id: string, title: string, provider: string|null, event_id?: string|null, close_time?: string|null }} market+ * @param {Book} book+ * @param {{ models?: typeof MODELS, minEdge?: number, minDepthUsd?: number }} [opts]+ */+export function scoreMarket(market, book, { models = MODELS, minEdge, minDepthUsd } = {}) {+ const th = models.thresholds;+ const edgeFloor = minEdge ?? th.min_edge_per_contract;+ const depthFloor = minDepthUsd ?? th.min_depth_usd;+ const top = topOfBookEdge(book, { models, provider: market.provider });+ if (!top) return null;+ const fill = walkComplement(asksFor(book, 'yes'), asksFor(book, 'no'), { models, provider: market.provider, minEdge: edgeFloor });+ const executable = fill.contracts > 0 && fill.cost_usd >= depthFloor && fill.edge_pct >= th.min_edge_pct;+ return {+ market_id: market.id,+ event_id: market.event_id || null,+ title: market.title,+ provider: market.provider,+ close_time: market.close_time || null,+ ...top,+ fill,+ executable,+ };+}++/** Rank: executable first, then by net edge, best first. */+export function rankRows(rows) {+ return [...rows].sort((a, b) => Number(b.executable) - Number(a.executable) || b.net_edge - a.net_edge);+}++async function mapLimit(items, limit, fn) {+ const out = new Array(items.length);+ let next = 0;+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {+ while (next < items.length) {+ const idx = next++;+ out[idx] = await fn(items[idx], idx);+ }+ });+ await Promise.all(workers);+ return out;+}++/**+ * Scan a venue's most active open markets. Reads only. Candidates are the most+ * active markets whose listed YES+NO ask sum is inside the data-defined window;+ * their order books are fetched and scored.+ * @param {{ listEvents: Function, getOrderbook: Function, id: string }} venue+ * @param {{ models?: typeof MODELS, limit?: number }} [opts]+ */+export async function scanVenue(venue, { models = MODELS, limit = 20 } = {}) {+ const th = models.thresholds;+ const pageSize = 25;+ const markets = [];+ for (let start = 0; markets.length < th.max_markets_scanned && start < 100; start += pageSize) {+ const page = await venue.listEvents({ sort: 'volume_24h', start, limit: pageSize });+ for (const ev of page.events || []) {+ for (const m of ev.markets || []) {+ if (m.tradable) markets.push({ ...m, event_title: ev.title });+ }+ }+ if (!page.has_more) break;+ }+ const priced = markets+ .map((m) => {+ const y = m.outcomes.find((o) => o.side === 'yes')?.buy_price;+ const n = m.outcomes.find((o) => o.side === 'no')?.buy_price;+ return { m, sum: y != null && n != null ? y + n : null };+ })+ .filter((x) => x.sum != null && x.sum >= th.candidate_sum_min && x.sum <= th.candidate_sum_max)+ .slice(0, th.max_books_fetched);++ const rows = (+ await mapLimit(priced, 6, async ({ m }) => {+ const book = await venue.getOrderbook(m.id).catch(() => null);+ return book ? scoreMarket(m, book, { models }) : null;+ })+ ).filter(Boolean);++ return {+ venue: venue.id,+ scanned_markets: markets.length,+ books_read: rows.length,+ scanned_at: new Date().toISOString(),+ thresholds: th,+ opportunities: rankRows(rows).slice(0, limit),+ };+}diff --git a/api/_lib/predictions/fee-models.json b/api/_lib/predictions/fee-models.jsonnew file mode 100644index 000000000..b2cdbd033--- /dev/null+++ b/api/_lib/predictions/fee-models.json@@ -0,0 +1,20 @@+{+ "$comment": "Fee models and scanner thresholds for prediction markets. Data, not constants: edit this file (or pass an override to the scanner) to change what counts as an opportunity. A fee model is applied per contract at the price it is bought. kinds: bps_of_notional (price * bps / 10000), p_one_minus_p (rate * price * (1 - price), the published exchange schedule shape), flat_per_contract (usd). `providers` is keyed by the provider id the venue reports on a market; an id with no entry falls back to `default_provider`, set to the steepest published schedule so an unknown provider can only understate an edge, never overstate it. `venue` is charged by the Solana venue on top of the provider. Until a quote reports the venue's real fee (quote.fees_usd on a preview), the venue entry is a conservative allowance, so a reported edge is never overstated.",+ "venue": { "kind": "bps_of_notional", "bps": 100 },+ "providers": {},+ "default_provider": { "kind": "p_one_minus_p", "rate": 0.07 },+ "thresholds": {+ "min_edge_per_contract": 0.005,+ "min_edge_pct": 0.5,+ "min_depth_usd": 25,+ "max_markets_scanned": 60,+ "max_books_fetched": 30,+ "candidate_sum_min": 0.9,+ "candidate_sum_max": 1.05+ },+ "strategy_defaults": {+ "mode": "shadow",+ "max_stake_usd": 25,+ "min_edge_pct": 1+ }+}diff --git a/api/_lib/predictions/routes.js b/api/_lib/predictions/routes.jsindex e9d93d28e..434443fe0 100644--- a/api/_lib/predictions/routes.js+++ b/api/_lib/predictions/routes.js@@ -21,6 +21,8 @@ import {agentPositions, loadOwnedAgent, describeError,} from './engine.js';import { createWatch, listWatches, deleteWatch } from './watch.js';+import { scanVenue } from './arb.js';+import { getStrategy, setStrategy, submitIntent, listLedger } from './shadow.js';const SORTS = new Set(['volume', 'volume_24h', 'close', 'new']);const RANGES = new Set(['1d', '1w', '1m', 'max']);@@ -90,12 +92,18 @@ async function marketRoute({ params, query }) {return run(() => marketDetail(venue, market, range));}+async function scanRoute({ query }) {+ const out = await run(() => scanVenue(getVenue(venueId(query)), { limit: intParam(query.limit, { name: 'limit', min: 1, max: 40, fallback: 20 }) }));+ return { ...out, venue: venueId(query) };+}+export function publicRoutes(prefix) {return [{ method: 'GET', path: `${prefix}/events`, name: 'predictions.events', auth: 'public', handler: listEventsRoute },{ method: 'GET', path: `${prefix}/categories`, name: 'predictions.categories', auth: 'public', handler: categoriesRoute },{ method: 'GET', path: `${prefix}/event/:eventId`, name: 'predictions.event', auth: 'public', handler: eventRoute },{ method: 'GET', path: `${prefix}/market/:marketId`, name: 'predictions.market', auth: 'public', handler: marketRoute },+ { method: 'GET', path: `${prefix}/scan`, name: 'predictions.scan', auth: 'public', handler: scanRoute },];}@@ -123,6 +131,31 @@ export const agentRoutes = [method: 'GET', path: '/agents/:id/predictions/positions', name: 'predictions.positions', auth: 'required', scope: 'wallet:read',handler: ({ params, principal }) => run(() => agentPositions({ agentId: agentOf(params), userId: principal.userId })),},+ {+ method: 'GET', path: '/agents/:id/predictions/strategy', name: 'predictions.strategy.get', auth: 'required', scope: 'wallet:read',+ handler: async ({ params, principal }) => {+ const agent = await run(() => loadOwnedAgent(agentOf(params), principal.userId));+ return getStrategy(agent.meta);+ },+ },+ {+ method: 'PUT', path: '/agents/:id/predictions/strategy', name: 'predictions.strategy.set', auth: 'required', scope: 'wallet:trade',+ handler: ({ params, principal, body, req }) => run(() => setStrategy({+ agentId: agentOf(params), userId: principal.userId, patch: body, ownerSession: principal.source === 'session', req,+ })),+ },+ {+ method: 'GET', path: '/agents/:id/predictions/shadow', name: 'predictions.shadow.list', auth: 'required', scope: 'wallet:read',+ handler: ({ params, principal, query }) => run(() => listLedger({+ agentId: agentOf(params), userId: principal.userId, limit: intParam(query.limit, { name: 'limit', min: 1, max: 500, fallback: 100 }),+ })),+ },+ {+ method: 'POST', path: '/agents/:id/predictions/shadow/intent', name: 'predictions.shadow.intent', auth: 'required', scope: 'wallet:trade',+ handler: async ({ params, principal, body }) => created(await run(() => submitIntent({+ agentId: agentOf(params), userId: principal.userId, intent: body, source: sourceOf(principal), venueId: venueId(body),+ }))),+ },{method: 'GET', path: '/agents/:id/predictions/limits', name: 'predictions.limits.get', auth: 'required', scope: 'wallet:read',handler: async ({ params, principal }) => {diff --git a/api/_lib/predictions/shadow.js b/api/_lib/predictions/shadow.jsnew file mode 100644index 000000000..c76d54701--- /dev/null+++ b/api/_lib/predictions/shadow.js@@ -0,0 +1,284 @@+// Shadow mode for agent prediction strategies.+//+// Every agent's strategy defaults to `shadow`. An intent (market, side, stake)+// is priced against the live order book, recorded to prediction_shadow_ledger+// with the price at decision time, and nothing else happens: no preview, no+// order build, no wallet access. Going live is an explicit setting only the+// signed-in owner can flip (PUT .../predictions/strategy); even then an intent+// only produces the engine's normal preview, and the confirmed execute stays+// the owner's call.+//+// Open entries are marked to market from the venue's bid and settled when the+// market resolves, so the dashboard can compare what shadow would have earned,+// net of fees and slippage, before the owner enables live.++import { sql } from '../db.js';+import { logAudit } from '../audit.js';+import { getVenue, DEFAULT_VENUE } from './index.js';+import { asksFor, estimateBuy } from './book.js';+import { totalFee, DEFAULT_MODELS } from './arb.js';+import { PredictionError, MIN_STAKE_USD, MAX_STAKE_USD, loadOwnedAgent, previewOpen } from './engine.js';++export const MODES = Object.freeze(['shadow', 'live']);+const round = (n, dp = 4) => Math.round(n * 10 ** dp) / 10 ** dp + 0;++// ── Strategy setting ─────────────────────────────────────────────────────────++/** The agent's strategy, with defaults. Anything but an explicit 'live' is shadow. */+export function getStrategy(meta, models = DEFAULT_MODELS) {+ const d = models.strategy_defaults;+ const s = meta?.prediction_strategy || {};+ const num = (v, fallback, lo, hi) => {+ const n = Number(v);+ return Number.isFinite(n) && n >= lo && n <= hi ? n : fallback;+ };+ return {+ mode: s.mode === 'live' ? 'live' : 'shadow',+ max_stake_usd: num(s.max_stake_usd, d.max_stake_usd, MIN_STAKE_USD, MAX_STAKE_USD),+ min_edge_pct: num(s.min_edge_pct, d.min_edge_pct, 0, 100),+ updated_at: s.updated_at || null,+ };+}++/** Whether a patch moves the strategy toward live or loosens a cap. */+export function strategyLoosens(prev, next) {+ return (next.mode === 'live' && prev.mode !== 'live') || next.max_stake_usd > prev.max_stake_usd || next.min_edge_pct < prev.min_edge_pct;+}++/**+ * Patch the strategy. Loosening (live, a larger stake cap, a lower edge floor)+ * needs the owner's signed-in session; tightening is open to any caller.+ */+export async function setStrategy({ agentId, userId, patch, ownerSession, req = null }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const prev = getStrategy(agent.meta);+ const p = patch && typeof patch === 'object' ? patch : {};+ if ('mode' in p && !MODES.includes(p.mode)) throw new PredictionError('invalid_mode', `mode must be one of: ${MODES.join(', ')}.`);+ const next = getStrategy({ prediction_strategy: { ...prev, ...pick(p, ['mode', 'max_stake_usd', 'min_edge_pct']) } });+ if (strategyLoosens(prev, next) && !ownerSession) {+ throw new PredictionError(+ 'owner_session_required',+ 'Turning live on or loosening a strategy cap needs the owner signed in on three.ws. Nothing changed.',+ 403,+ { keys: Object.keys(p) },+ );+ }+ next.updated_at = new Date().toISOString();+ await sql`+ UPDATE agent_identities+ SET meta = jsonb_set(coalesce(meta, '{}'::jsonb), '{prediction_strategy}', ${JSON.stringify(next)}::jsonb)+ WHERE id = ${agentId}+ `;+ logAudit({ userId, action: 'custody.prediction_strategy_change', resourceId: agentId, meta: { prev, next }, req });+ return next;+}++function pick(obj, keys) {+ const out = {};+ for (const k of keys) if (k in obj) out[k] = obj[k];+ return out;+}++// ── Pricing an intent ────────────────────────────────────────────────────────++/**+ * Price a buy of `stakeUsd` of one side from the order book. Pure.+ * @returns {{ price_at_decision: number, entry_price: number, contracts: number, cost_usd: number, fees_usd: number, filled_fully: boolean }|null}+ */+export function priceIntent({ book, side, stakeUsd, provider, maxPrice = 0.99, models = DEFAULT_MODELS }) {+ const asks = asksFor(book, side);+ if (!asks.length) return null;+ const est = estimateBuy(asks, stakeUsd, maxPrice);+ if (!est.contracts || est.avg_price == null) return null;+ const cost = est.spent_usd;+ const fees = est.contracts * totalFee(models, provider, est.avg_price);+ return {+ price_at_decision: asks[0][0],+ entry_price: round(est.avg_price),+ contracts: round(est.contracts),+ cost_usd: round(cost),+ fees_usd: round(fees),+ filled_fully: est.filled_fully,+ };+}++// ── Marking ──────────────────────────────────────────────────────────────────++/**+ * Mark or settle one ledger entry against the current market. Pure.+ * A resolved market pays $1 a contract on the winning side; a refund or draw+ * returns the cost; an open market is valued at the side's bid, less the exit+ * fee, which is what selling now would have realized.+ */+export function markEntry(entry, market, models = DEFAULT_MODELS) {+ const contracts = Number(entry.contracts);+ const spent = Number(entry.cost_usd) + Number(entry.fees_usd);+ const result = market?.result || null;+ if (result === 'yes' || result === 'no') {+ const won = result === entry.side;+ const payout = won ? contracts : 0;+ return { status: won ? 'won' : 'lost', mark_price: won ? 1 : 0, payout_usd: round(payout), pnl_usd: round(payout - spent), resolved: true };+ }+ if (result === 'refund' || result === 'draw' || market?.status === 'void') {+ return {+ status: 'void',+ mark_price: Number(entry.entry_price),+ payout_usd: round(Number(entry.cost_usd)),+ pnl_usd: round(-Number(entry.fees_usd)),+ resolved: true,+ };+ }+ const bid = market?.outcomes?.find((o) => o.side === entry.side)?.sell_price;+ if (bid == null) return { status: 'open', mark_price: null, payout_usd: null, pnl_usd: null, resolved: false };+ const exitFee = contracts * totalFee(models, market.provider, bid);+ return {+ status: 'open',+ mark_price: bid,+ payout_usd: round(contracts * bid - exitFee),+ pnl_usd: round(contracts * bid - exitFee - spent),+ resolved: false,+ };+}++// ── Summary ──────────────────────────────────────────────────────────────────++/**+ * Compare shadow with live. For each mode: realized P&L (settled entries),+ * unrealized P&L (open entries at the bid), win rate, and the gross P&L the+ * same trades would show with no fees and no slippage, to expose what the+ * costs take. Pure.+ */+export function summarize(rows) {+ const blank = () => ({+ entries: 0,+ open: 0,+ settled: 0,+ won: 0,+ lost: 0,+ staked_usd: 0,+ realized_pnl_usd: 0,+ unrealized_pnl_usd: 0,+ total_pnl_usd: 0,+ gross_pnl_usd: 0,+ costs_usd: 0,+ win_rate: null,+ });+ const out = { shadow: blank(), live: blank() };+ for (const r of rows) {+ const s = out[r.mode] || out.shadow;+ const contracts = Number(r.contracts);+ const cost = Number(r.cost_usd);+ const fees = Number(r.fees_usd);+ s.entries += 1;+ s.staked_usd += cost;+ if (r.status === 'open') s.open += 1;+ else s.settled += 1;+ if (r.status === 'won') s.won += 1;+ if (r.status === 'lost') s.lost += 1;+ if (r.pnl_usd != null) {+ if (r.status === 'open') s.unrealized_pnl_usd += Number(r.pnl_usd);+ else s.realized_pnl_usd += Number(r.pnl_usd);+ }+ const quoted = contracts * Number(r.price_at_decision);+ if (r.status === 'won') s.gross_pnl_usd += contracts - quoted;+ else if (r.status === 'lost') s.gross_pnl_usd -= quoted;+ else if (r.status === 'open' && r.mark_price != null) s.gross_pnl_usd += contracts * Number(r.mark_price) - quoted;+ s.costs_usd += fees + contracts * (Number(r.entry_price) - Number(r.price_at_decision));+ }+ for (const s of Object.values(out)) {+ s.total_pnl_usd = round(s.realized_pnl_usd + s.unrealized_pnl_usd, 2);+ for (const k of ['staked_usd', 'realized_pnl_usd', 'unrealized_pnl_usd', 'gross_pnl_usd', 'costs_usd']) s[k] = round(s[k], 2);+ s.win_rate = s.won + s.lost > 0 ? round(s.won / (s.won + s.lost), 4) : null;+ }+ return out;+}++// ── Ledger I/O ───────────────────────────────────────────────────────────────++/**+ * Record an intent. In shadow mode this is the whole story: no engine call, no+ * wallet read, no order. In live mode the intent is recorded as well and the+ * engine's normal preview is returned for the owner to confirm.+ */+export async function submitIntent({ agentId, userId, intent, source = 'agent', venueId = DEFAULT_VENUE, deps = {} }) {+ const preview = deps.previewOpen || previewOpen;+ const agent = await loadOwnedAgent(agentId, userId);+ const strategy = getStrategy(agent.meta);+ const side = String(intent?.side || '').toLowerCase();+ if (side !== 'yes' && side !== 'no') throw new PredictionError('invalid_side', 'side must be "yes" or "no".');+ const stake = Number(intent?.stake_usd);+ if (!Number.isFinite(stake) || stake < MIN_STAKE_USD || stake > strategy.max_stake_usd) {+ throw new PredictionError('invalid_stake', `stake_usd must be between $${MIN_STAKE_USD} and this agent's strategy cap of $${strategy.max_stake_usd}.`);+ }+ const venue = getVenue(venueId);+ const market = await venue.getMarket(String(intent?.market_id || ''));+ if (!market.tradable) throw new PredictionError('market_closed', `This market is ${market.status || 'not open'}; there is nothing to decide on.`, 409);+ const book = await venue.getOrderbook(market.id);+ const priced = priceIntent({ book, side, stakeUsd: stake, provider: market.provider, maxPrice: intent?.max_price ?? 0.99 });+ if (!priced) throw new PredictionError('no_liquidity', 'Nobody is selling this side right now, so there is no price to decide at.', 409);+ const edge = intent?.edge_pct != null && Number.isFinite(Number(intent.edge_pct)) ? Number(intent.edge_pct) : null;+ if (edge != null && edge < strategy.min_edge_pct) {+ throw new PredictionError(+ 'edge_below_floor',+ `The stated edge of ${edge}% is under this agent's floor of ${strategy.min_edge_pct}%, so nothing was recorded.`,+ 409,+ );+ }++ const [row] = await sql`+ INSERT INTO prediction_shadow_ledger+ (agent_id, user_id, venue, mode, market_id, event_id, title, provider, side, stake_usd, contracts,+ price_at_decision, entry_price, fees_usd, cost_usd, edge_pct, reason, source, close_time)+ VALUES+ (${agent.id}, ${userId}, ${venue.id}, ${strategy.mode}, ${market.id}, ${market.event_id}, ${market.title}, ${market.provider},+ ${side}, ${stake}, ${priced.contracts}, ${priced.price_at_decision}, ${priced.entry_price}, ${priced.fees_usd},+ ${priced.cost_usd}, ${edge}, ${intent?.reason ? String(intent.reason).slice(0, 500) : null}, ${source}, ${market.close_time})+ RETURNING *+ `;+ if (strategy.mode === 'shadow') {+ return { mode: 'shadow', recorded: row, note: 'Shadow mode: the decision was recorded at the live price. No order was built and no funds can move.' };+ }+ const quote = await preview({ agentId, userId, venueId: venue.id, marketId: market.id, side, stakeUsd: stake, maxPrice: intent?.max_price });+ return {+ mode: 'live',+ recorded: row,+ preview: quote,+ note: 'Live mode: the decision was recorded and the order is previewed. Nothing is sent until the owner confirms the preview.',+ };+}++/** Mark every open entry for an agent against current markets, then return the page. */+export async function listLedger({ agentId, userId, limit = 100, venueId = DEFAULT_VENUE, deps = {} }) {+ await loadOwnedAgent(agentId, userId);+ const venue = deps.venue || getVenue(venueId);+ const open = await sql`SELECT * FROM prediction_shadow_ledger WHERE agent_id = ${agentId} AND status = 'open'`;+ const ids = [...new Set(open.map((r) => r.market_id))].slice(0, 40);+ const markets = new Map();+ await Promise.all(+ ids.map(async (id) => {+ try {+ markets.set(id, await venue.getMarket(id));+ } catch {+ /* an unreadable market keeps its last mark */+ }+ }),+ );+ for (const r of open) {+ const m = markets.get(r.market_id);+ if (!m) continue;+ const mk = markEntry(r, m);+ await sql`+ UPDATE prediction_shadow_ledger+ SET status = ${mk.status}, mark_price = ${mk.mark_price}, payout_usd = ${mk.payout_usd}, pnl_usd = ${mk.pnl_usd}, marked_at = now(),+ resolved_at = ${mk.resolved ? new Date().toISOString() : null}+ WHERE id = ${r.id}+ `;+ }+ const rows = await sql`+ SELECT * FROM prediction_shadow_ledger WHERE agent_id = ${agentId}+ ORDER BY decided_at DESC LIMIT ${Math.min(500, Math.max(1, limit))}+ `;+ const all =+ await sql`SELECT mode, status, contracts, cost_usd, fees_usd, price_at_decision, entry_price, mark_price, pnl_usd FROM prediction_shadow_ledger WHERE agent_id = ${agentId}`;+ return { entries: rows, summary: summarize(all) };+}diff --git a/data/changelog.json b/data/changelog.jsonindex 55dcc8184..a66a70591 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-24",+ "title": "See what a prediction strategy would have earned before it trades",+ "summary": "Agent Predictions records every strategy decision at the live order-book price in shadow mode, marks it at resolution, and shows shadow beside live results. A fee-aware scanner reads Solana event contracts for YES plus NO pairs under $1. Live stays owner-only.",+ "tags": ["feature"],+ "link": "/agent-predictions"+ },{"date": "2026-10-24","title": "Scene from a photo, built and waiting on weights",diff --git a/data/pages.json b/data/pages.jsonindex 9751bd600..686898269 100644--- a/data/pages.json+++ b/data/pages.json@@ -3101,6 +3101,15 @@"added": "2026-10-10","indexable": false},+ {+ "path": "/agent-predictions",+ "title": "Agent Predictions",+ "description": "See what your agent's prediction strategy would have earned before it trades: shadow mode records every decision at the live price and marks it at resolution, beside a live fee-aware no-arbitrage scanner for Solana event contracts.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-10-24",+ "indexable": false+ },{"path": "/agent-perps","title": "Agent Perps",@@ -5561,6 +5570,13 @@"priority": 0.7,"changefreq": "monthly"},+ {+ "path": "/docs/predictions",+ "title": "Docs: Agent Predictions",+ "description": "How a prediction strategy runs in shadow mode first: every decision recorded at the live order-book price and marked at resolution, shadow beside live results, the fee-aware no-arbitrage scanner, the editable fee models, and the REST routes behind the dashboard.",+ "priority": 0.6,+ "changefreq": "monthly"+ },{"path": "/docs/papertrade","title": "Docs: Papertrade",diff --git a/docs/predictions.md b/docs/predictions.mdnew file mode 100644index 000000000..5103f6a8f--- /dev/null+++ b/docs/predictions.md@@ -0,0 +1,39 @@+# Agent Predictions: shadow mode and the no-arbitrage scanner++Agents trade USDC prediction markets on Solana through the engine in `api/_lib/predictions/` (see [mcp-agent.md](./mcp-agent.md) for the trading tools). This page covers the layer on top: a **shadow ledger** that records what a strategy would have done at the live price, and a **scanner** that looks for a YES plus NO pair that costs less than the $1 it pays.++Nothing here moves funds. Order build and quote stay in the existing open/close routes, which keep their own limits, previews and confirmations.++## Shadow mode++Every agent's strategy defaults to `shadow`. A decision posted in shadow mode is priced against the live order book (walking the asks for the stake, including the venue and provider fee from the fee model), written to the `prediction_shadow_ledger` table, and marked later from the market's current or resolved price. No order is built.++`live` mode is an owner-session-only setting. In live mode a decision is still recorded and returns the engine's preview. The owner confirms the execute separately through the normal open route, so a strategy can never spend on its own.++Read the results side by side: the summary reports shadow and live separately, each with decisions, staked, realized and unrealized P&L, P&L before and after fees and slippage, and win rate.++## Scanner++`GET /api/predictions/scan` reads the most active open markets, fetches order books for the ones whose YES plus NO prices sit near par, and reports for each the gross edge (`1 - yes_ask - no_ask`), the net edge after fees, and how much is fillable at positive net edge. `executable` is true only when the net edge clears the thresholds in the fee model file. A negative edge is the normal state of an efficient market, and the scanner says so rather than inventing opportunities.++## Fee models++`api/_lib/predictions/fee-models.json` holds the venue fee, per-provider fee schedules, scanner thresholds and strategy defaults. It is data: edit it, or pass an override to the scanner. Fee kinds: `bps_of_notional`, `p_one_minus_p` and `flat_per_contract`. The shipped venue fee is a conservative allowance. Replace it with the venue's measured fee (the quote's `fees_usd` on a preview) before relying on a small edge.++## Routes++| Method and path | Auth | Purpose |+| --- | --- | --- |+| `GET /api/predictions/scan` | public | Scanner results |+| `GET /api/v1/agents/:id/predictions/strategy` | owner | Mode, stake cap and edge floor |+| `PUT /api/v1/agents/:id/predictions/strategy` | owner session | Change mode or limits (live needs a browser session) |+| `GET /api/v1/agents/:id/predictions/shadow` | owner | Ledger entries and shadow versus live summary |+| `POST /api/v1/agents/:id/predictions/shadow/intent` | owner or key | Record one decision |++## Dashboard++[/agent-predictions](https://three.ws/agent-predictions), or `/agents/<agent id>/predictions`: strategy card with the mode toggle, shadow and live result cards, the decision table, and the scanner. Without an agent id only the scanner shows.++## Tests++`npx vitest run tests/predictions-shadow.test.js tests/predictions-book.test.js`. The ledger migration is `api/_lib/migrations/20261024020000_prediction_shadow_ledger.sql` and applies at deploy.diff --git a/pages/agent-predictions.html b/pages/agent-predictions.htmlnew file mode 100644index 000000000..120295765--- /dev/null+++ b/pages/agent-predictions.html@@ -0,0 +1,48 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot: no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <title>Agent Predictions · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="theme-color" content="#000000" />+ <meta name="description" content="See what your agent's prediction strategy would have earned before it trades: shadow mode records every decision at the live price, marks it at resolution, and sits beside a live scanner for fee-adjusted no-arbitrage edges on Solana event contracts." />+ <meta name="robots" content="noindex" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/agent-predictions" />+ <meta property="og:title" content="Agent Predictions · three.ws" />+ <meta property="og:description" content="Shadow mode P&L versus live, plus a fee-aware no-arbitrage scanner for Solana event contracts." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Predictions&d=Shadow+mode+first%2C+live+only+when+you+say+so.&p=%2Fagent-predictions" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <link rel="canonical" href="https://three.ws/agent-predictions" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ </head>+ <body>+ <div id="nav-container"></div>++ <main class="apd-wrap">+ <p class="apd-crumb"><a href="/">Home</a> / <a href="/agents">Agents</a> / Predictions</p>+ <div id="apd-root"></div>+ </main>++ <script type="module" src="/src/agent-predictions.js"></script>+ <script src="/nav.js" defer></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/src/agent-predictions.css b/src/agent-predictions.cssnew file mode 100644index 000000000..c0c6da37d--- /dev/null+++ b/src/agent-predictions.css@@ -0,0 +1,46 @@+/* Agent Predictions page (/agents/:id/predictions). Tokens come from+ public/tokens.css, so the page follows the light and dark themes. */++.apd-wrap {+ width: 100%;+ max-width: 1120px;+ margin: 0 auto;+ padding: calc(var(--space-md) * 2) var(--space-md) calc(var(--space-md) * 4);+}+.apd-crumb { font: var(--text-sm) var(--font-body); color: var(--ink-dim); margin: 0 0 var(--space-lg); }+.apd-crumb a { color: inherit; }+.apd-crumb a:hover { color: var(--ink); }+.apd-h1 { font-family: var(--font-display); font-size: var(--text-xl); color: var(--ink-bright); margin: 0; line-height: 1.15; }+.apd-lede { color: var(--ink-dim); margin: var(--space-xs) 0 var(--space-lg); max-width: 68ch; }+.apd-section { margin: 0 0 var(--space-xl); }+.apd-section h2 { font-size: var(--text-md); color: var(--ink-bright); margin: 0 0 var(--space-sm); }+.apd-note { color: var(--ink-dim); font-size: var(--text-sm); margin: 0 0 var(--space-sm); max-width: 72ch; }+.apd-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: var(--space-md); }+.apd-card { background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md, 10px); padding: var(--space-md); }+.apd-card h3 { margin: 0 0 var(--space-sm); font-size: var(--text-sm); color: var(--ink-dim); font-weight: 600; letter-spacing: .02em; text-transform: uppercase; }+.apd-big { font: 600 var(--text-xl) var(--font-display); color: var(--ink-bright); }+.apd-pos { color: var(--success); }+.apd-neg { color: var(--danger); }+.apd-kv { display: grid; grid-template-columns: 1fr auto; gap: 4px var(--space-md); margin: var(--space-sm) 0 0; font-size: var(--text-sm); }+.apd-kv dt { color: var(--ink-dim); }+.apd-kv dd { margin: 0; text-align: right; font-variant-numeric: tabular-nums; }+.apd-table-wrap { overflow-x: auto; border: 1px solid var(--stroke); border-radius: var(--radius-md, 10px); }+.apd-table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); }+.apd-table th, .apd-table td { padding: 8px 12px; text-align: right; white-space: nowrap; border-bottom: 1px solid var(--stroke); font-variant-numeric: tabular-nums; }+.apd-table th:first-child, .apd-table td:first-child { text-align: left; white-space: normal; min-width: 220px; max-width: 420px; }+.apd-table th { color: var(--ink-dim); font-weight: 600; }+.apd-table tr:last-child td { border-bottom: 0; }+.apd-pill { display: inline-block; padding: 1px 8px; border-radius: 999px; background: var(--accent-soft); font-size: var(--text-xs, 12px); }+.apd-pill.is-live { color: var(--danger); }+.apd-pill.is-shadow { color: var(--success); }+.apd-btn { font: inherit; padding: 8px 14px; border-radius: 8px; border: 1px solid var(--stroke); background: var(--surface-1); color: var(--ink); cursor: pointer; }+.apd-btn:hover { border-color: var(--ink-dim); }+.apd-btn:active { transform: translateY(1px); }+.apd-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.apd-btn.is-primary { background: var(--accent); color: var(--on-accent, #000); border-color: var(--accent); }+.apd-btn[disabled] { opacity: .5; cursor: not-allowed; }+.apd-msg { padding: var(--space-md); border-radius: 10px; border: 1px solid var(--stroke); background: var(--surface-1); }+.apd-msg.is-error { border-color: var(--danger); }+.apd-skel { height: 14px; border-radius: 4px; background: var(--accent-soft); margin: 8px 0; animation: apd-pulse 1.2s ease-in-out infinite; }+@keyframes apd-pulse { 50% { opacity: .45; } }+@media (prefers-reduced-motion: reduce) { .apd-skel { animation: none; } }diff --git a/src/agent-predictions.js b/src/agent-predictions.jsnew file mode 100644index 000000000..f57e09820--- /dev/null+++ b/src/agent-predictions.js@@ -0,0 +1,194 @@+/**+ * Agent Predictions: shadow-mode P&L versus live, plus the no-arbitrage scanner.+ *+ * Routes: /agents/:id/predictions and /agent-predictions (?id=<uuid>). Without+ * an id the page shows the public scanner only. API: /api/v1/agents/:id/predictions+ * (docs/predictions.md). Nothing on this page moves funds: it reads the shadow+ * ledger, reads the scanner, and flips the strategy mode, which only the+ * signed-in owner may turn to live.+ */++import './agent-predictions.css';+import { consumeCsrfToken } from './api.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const root = document.getElementById('apd-root');++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const usd = (n, sign = false) => {+ const v = Number(n);+ if (n == null || !Number.isFinite(v)) return '-';+ const s = Math.abs(v).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ return `${sign ? (v > 0 ? '+' : v < 0 ? '-' : '') : v < 0 ? '-' : ''}$${s}`;+};+const cents = (p) => (p == null ? '-' : `${(Number(p) * 100).toFixed(1)}c`);+const pct = (n, d = 2) => (n == null || !Number.isFinite(Number(n)) ? '-' : `${Number(n).toFixed(d)}%`);+const tone = (n) => (Number(n) > 0 ? 'apd-pos' : Number(n) < 0 ? 'apd-neg' : '');++class ApiFailure extends Error {+ constructor(status, code, message) {+ super(message);+ this.status = status;+ this.code = code;+ }+}++async function api(path, { method = 'GET', body } = {}) {+ const opts = { method, credentials: 'include', headers: { accept: 'application/json' } };+ if (body !== undefined) {+ opts.headers['content-type'] = 'application/json';+ opts.body = JSON.stringify(body);+ }+ if (method !== 'GET') {+ const token = await consumeCsrfToken();+ if (token) opts.headers['x-csrf-token'] = token;+ }+ let res;+ try {+ res = await fetch(path, opts);+ } catch {+ throw new ApiFailure(0, 'network_error', 'Could not reach three.ws. Check your connection and try again.');+ }+ let j = null;+ try {+ j = await res.json();+ } catch {+ j = null;+ }+ if (!res.ok) throw new ApiFailure(res.status, j?.error?.code || 'error', j?.error?.message || `Request failed (${res.status}).`);+ return j?.data;+}++function skeleton(rows = 4) {+ return `<div aria-busy="true" aria-label="Loading">${'<div class="apd-skel"></div>'.repeat(rows)}</div>`;+}++function message(title, body, actions = [], error = false) {+ return `<div class="apd-msg${error ? ' is-error' : ''}" role="${error ? 'alert' : 'status'}"><strong>${esc(title)}</strong><p>${esc(body)}</p>${actions+ .map((a) => `<a class="apd-btn${a.primary ? ' is-primary' : ''}" href="${esc(a.href)}">${esc(a.label)}</a>`)+ .join(' ')}</div>`;+}++// ── scanner ──────────────────────────────────────────────────────────────────++function scannerHtml(scan) {+ if (!scan.opportunities.length) {+ return message('No priced books right now', 'The scanner read the most active markets but none had both sides quoted. It refreshes whenever you reload.');+ }+ const rows = scan.opportunities+ .map(+ (o) => `<tr>+ <td>${esc(o.title)}<br /><span class="apd-pill">${esc(o.provider || 'venue')}</span> ${o.executable ? '<span class="apd-pill is-shadow">opportunity</span>' : ''}</td>+ <td>${cents(o.yes_ask)}</td><td>${cents(o.no_ask)}</td>+ <td class="${tone(o.gross_edge)}">${cents(o.gross_edge)}</td>+ <td class="${tone(o.net_edge)}">${cents(o.net_edge)}</td>+ <td class="${tone(o.net_edge_pct)}">${pct(o.net_edge_pct)}</td>+ <td>${o.fill.contracts ? `${usd(o.fill.profit_usd, true)} on ${usd(o.fill.cost_usd)}` : '-'}</td></tr>`,+ )+ .join('');+ return `<p class="apd-note">${scan.books_read} order books read of ${scan.scanned_markets} open markets, ${esc(new Date(scan.scanned_at).toLocaleTimeString())}. Edge is what buying both YES and NO locks in per contract after the venue and provider fees in the fee model. Negative is the normal state of an efficient market.</p>+ <div class="apd-table-wrap"><table class="apd-table"><thead><tr><th>Market</th><th>YES ask</th><th>NO ask</th><th>Gross edge</th><th>Net edge</th><th>Net %</th><th>Fillable profit</th></tr></thead><tbody>${rows}</tbody></table></div>`;+}++// ── shadow vs live ───────────────────────────────────────────────────────────++function modeCard(label, s) {+ return `<div class="apd-card"><h3>${esc(label)}</h3>+ <div class="apd-big ${tone(s.total_pnl_usd)}">${usd(s.total_pnl_usd, true)}</div>+ <dl class="apd-kv">+ <dt>Decisions</dt><dd>${s.entries} (${s.open} open)</dd>+ <dt>Staked</dt><dd>${usd(s.staked_usd)}</dd>+ <dt>Realized</dt><dd class="${tone(s.realized_pnl_usd)}">${usd(s.realized_pnl_usd, true)}</dd>+ <dt>Unrealized</dt><dd class="${tone(s.unrealized_pnl_usd)}">${usd(s.unrealized_pnl_usd, true)}</dd>+ <dt>Before fees and slippage</dt><dd class="${tone(s.gross_pnl_usd)}">${usd(s.gross_pnl_usd, true)}</dd>+ <dt>Fees and slippage</dt><dd>${usd(s.costs_usd)}</dd>+ <dt>Win rate</dt><dd>${s.win_rate == null ? 'no settled trades' : pct(s.win_rate * 100, 0)}</dd>+ </dl></div>`;+}++function ledgerHtml(entries) {+ if (!entries.length) {+ return message('No decisions recorded yet', 'In shadow mode your agent records every trade it would make, at the live price, without sending anything. Have it post an intent to /api/v1/agents/:id/predictions/shadow/intent, or call the prediction tools over MCP. Results appear here.');+ }+ const rows = entries+ .map(+ (e) => `<tr>+ <td>${esc(e.title)}<br /><span class="apd-pill is-${esc(e.mode)}">${esc(e.mode)}</span> <span class="apd-pill">${esc(e.side)}</span> ${e.reason ? `<span class="apd-note">${esc(e.reason)}</span>` : ''}</td>+ <td>${esc(new Date(e.decided_at).toLocaleDateString())}</td>+ <td>${cents(e.price_at_decision)}</td><td>${cents(e.entry_price)}</td>+ <td>${usd(e.cost_usd)}</td>+ <td>${e.mark_price == null ? '-' : cents(e.mark_price)}</td>+ <td><span class="apd-pill">${esc(e.status)}</span></td>+ <td class="${tone(e.pnl_usd)}">${e.pnl_usd == null ? '-' : usd(e.pnl_usd, true)}</td></tr>`,+ )+ .join('');+ return `<div class="apd-table-wrap"><table class="apd-table"><thead><tr><th>Decision</th><th>Date</th><th>Price at decision</th><th>Avg fill</th><th>Cost</th><th>Mark</th><th>Status</th><th>P&L</th></tr></thead><tbody>${rows}</tbody></table></div>`;+}++function strategyHtml(st) {+ const live = st.mode === 'live';+ return `<div class="apd-card"><h3>Strategy mode</h3>+ <div class="apd-big"><span class="apd-pill ${live ? 'is-live' : 'is-shadow'}">${live ? 'Live' : 'Shadow'}</span></div>+ <p class="apd-note">${live ? 'Live: decisions are recorded and each one is previewed for you to confirm. Nothing is sent without your confirmation.' : 'Shadow: decisions are recorded at the live price. No order is built and no funds can move.'}</p>+ <dl class="apd-kv"><dt>Max stake per decision</dt><dd>${usd(st.max_stake_usd)}</dd><dt>Minimum stated edge</dt><dd>${pct(st.min_edge_pct, 1)}</dd></dl>+ <p><button class="apd-btn${live ? '' : ' is-primary'}" id="apd-mode" data-to="${live ? 'shadow' : 'live'}">${live ? 'Switch back to shadow' : 'Enable live decisions'}</button></p>+ <p class="apd-note" id="apd-mode-msg" role="status"></p></div>`;+}++async function loadAgentSection(agentId, host) {+ host.innerHTML = skeleton(5);+ const base = `/api/v1/agents/${encodeURIComponent(agentId)}/predictions`;+ try {+ const [strategy, shadow] = await Promise.all([api(`${base}/strategy`), api(`${base}/shadow`)]);+ host.innerHTML = `<div class="apd-grid">${strategyHtml(strategy)}${modeCard('Shadow results', shadow.summary.shadow)}${modeCard('Live results', shadow.summary.live)}</div>+ <h2 style="margin-top:var(--space-lg)">Decisions</h2>${ledgerHtml(shadow.entries)}`;+ const btn = host.querySelector('#apd-mode');+ btn?.addEventListener('click', async () => {+ const to = btn.dataset.to;+ const out = host.querySelector('#apd-mode-msg');+ btn.disabled = true;+ try {+ await api(`${base}/strategy`, { method: 'PUT', body: { mode: to } });+ await loadAgentSection(agentId, host);+ } catch (err) {+ out.textContent = err.code === 'owner_session_required' ? 'Only you, signed in on three.ws, can turn live on. Sign in and try again.' : err.message;+ btn.disabled = false;+ }+ });+ } catch (err) {+ host.innerHTML = err.status === 401 || err.status === 403+ ? message('Sign in as this agent\'s owner', 'Shadow results are private to the agent\'s owner.', [{ href: `/login?next=${encodeURIComponent(location.pathname + location.search)}`, label: 'Sign in', primary: true }])+ : message('Could not load shadow results', err.message, [], true);+ }+}++async function loadScanner(host) {+ host.innerHTML = skeleton(6);+ try {+ host.innerHTML = scannerHtml(await api('/api/predictions/scan?limit=15'));+ } catch (err) {+ host.innerHTML = message('The scanner could not read the venue', `${err.message} Reload to try again.`, [], true);+ }+}++function agentIdFromUrl() {+ const q = new URLSearchParams(location.search).get('id');+ if (q) return q;+ const m = location.pathname.match(/\/agents\/([^/]+)\/predictions/);+ return m ? decodeURIComponent(m[1]) : null;+}++function boot() {+ const agentId = agentIdFromUrl();+ const valid = agentId && UUID_RE.test(agentId);+ document.title = 'Agent Predictions · three.ws';+ root.innerHTML = `<h1 class="apd-h1">Agent Predictions</h1>+ <p class="apd-lede">Your agent decides on Solana event contracts in shadow mode first: every trade is recorded at the live price and marked at resolution, so you can see what live would have paid before you turn it on.</p>+ ${agentId && !valid ? message('That agent link is not valid', 'Open predictions from one of your agents.', [{ href: '/agents', label: 'Your agents', primary: true }], true) : ''}+ ${valid ? '<section class="apd-section" aria-labelledby="apd-h-shadow"><h2 id="apd-h-shadow">Shadow versus live</h2><div id="apd-agent"></div></section>' : ''}+ <section class="apd-section" aria-labelledby="apd-h-scan"><h2 id="apd-h-scan">No-arbitrage scanner</h2><div id="apd-scan"></div></section>`;+ if (valid) loadAgentSection(agentId, root.querySelector('#apd-agent'));+ loadScanner(root.querySelector('#apd-scan'));+}++boot();diff --git a/tests/predictions-shadow-routes.test.js b/tests/predictions-shadow-routes.test.jsnew file mode 100644index 000000000..ee761d724--- /dev/null+++ b/tests/predictions-shadow-routes.test.js@@ -0,0 +1,49 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const setStrategy = vi.fn(async () => ({ mode: 'shadow' }));+const submitIntent = vi.fn(async () => ({ mode: 'shadow', recorded: {} }));+vi.mock('../api/_lib/predictions/shadow.js', () => ({+ getStrategy: vi.fn(() => ({ mode: 'shadow' })),+ setStrategy: (...a) => setStrategy(...a),+ submitIntent: (...a) => submitIntent(...a),+ listLedger: vi.fn(async () => ({ entries: [], summary: {} })),+}));+vi.mock('../api/_lib/predictions/engine.js', () => ({+ previewOpen: vi.fn(), executeOpen: vi.fn(), previewClose: vi.fn(), executeClose: vi.fn(), previewRedeem: vi.fn(), executeRedeem: vi.fn(),+ agentPositions: vi.fn(), loadOwnedAgent: vi.fn(), describeError: vi.fn(() => null),+}));+vi.mock('../api/_lib/predictions/index.js', () => ({ getVenue: vi.fn(() => ({ id: 'solana' })), DEFAULT_VENUE: 'solana', listVenues: vi.fn(() => []) }));+vi.mock('../api/_lib/agent-trade-guards.js', () => ({ getPredictionLimits: vi.fn(), setPredictionLimits: vi.fn() }));+vi.mock('../api/_lib/real-funds-agreement.js', () => ({ currentSignatureFor: vi.fn(), agreementRequirement: vi.fn() }));+vi.mock('../api/_lib/predictions/watch.js', () => ({ createWatch: vi.fn(), listWatches: vi.fn(), deleteWatch: vi.fn() }));++const { agentRoutes, publicRoutes } = await import('../api/_lib/predictions/routes.js');+const ID = '11111111-1111-4111-8111-111111111111';+const route = (name) => agentRoutes.find((r) => r.name === name);++beforeEach(() => vi.clearAllMocks());++describe('shadow routes', () => {+ it('registers the scanner as a public read on both mounts', () => {+ expect(publicRoutes('/predictions').find((r) => r.name === 'predictions.scan')).toMatchObject({ method: 'GET', auth: 'public', path: '/predictions/scan' });+ expect(agentRoutes.find((r) => r.name === 'predictions.scan')).toMatchObject({ auth: 'public' });+ });++ it('only treats a browser session as the owner session when changing the strategy', async () => {+ const r = route('predictions.strategy.set');+ await r.handler({ params: { id: ID }, principal: { userId: 'u', source: 'api_key' }, body: { mode: 'live' }, req: {} });+ expect(setStrategy.mock.calls[0][0].ownerSession).toBe(false);+ await r.handler({ params: { id: ID }, principal: { userId: 'u', source: 'session' }, body: { mode: 'live' }, req: {} });+ expect(setStrategy.mock.calls[1][0].ownerSession).toBe(true);+ });++ it('records an intent for the owned agent and marks API callers in the source', async () => {+ const out = await route('predictions.shadow.intent').handler({ params: { id: ID }, principal: { userId: 'u', source: 'api_key' }, body: { market_id: 'M', side: 'yes', stake_usd: 5 } });+ expect(submitIntent.mock.calls[0][0]).toMatchObject({ agentId: ID, userId: 'u', source: 'api:api_key' });+ expect(out.data.mode).toBe('shadow');+ });++ it('rejects a malformed agent id before touching the ledger', async () => {+ await expect(route('predictions.shadow.list').handler({ params: { id: 'nope' }, principal: { userId: 'u' }, query: {} })).rejects.toBeTruthy();+ });+});diff --git a/tests/predictions-shadow.test.js b/tests/predictions-shadow.test.jsnew file mode 100644index 000000000..05d855e0a--- /dev/null+++ b/tests/predictions-shadow.test.js@@ -0,0 +1,248 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const state = { rows: [], agentMeta: {} };+const sqlSpy = vi.fn();+vi.mock('../api/_lib/db.js', () => {+ const sql = (strings, ...vals) => {+ const text = strings.join('?');+ sqlSpy(text, vals);+ if (/INSERT INTO prediction_shadow_ledger/.test(text)) {+ const row = { id: 'row-1', mode: vals[3], market_id: vals[4], side: vals[8], contracts: vals[10], price_at_decision: vals[11], entry_price: vals[12], fees_usd: vals[13], cost_usd: vals[14], status: 'open' };+ state.rows.push(row);+ return Promise.resolve([row]);+ }+ return Promise.resolve([]);+ };+ return { sql };+});+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));++const previewOpen = vi.fn(async () => ({ preview_id: 'p1' }));+const executeOpen = vi.fn();+vi.mock('../api/_lib/predictions/engine.js', () => ({+ MIN_STAKE_USD: 1,+ MAX_STAKE_USD: 100000,+ PredictionError: class PredictionError extends Error {+ constructor(code, message, status = 400, detail = null) {+ super(message);+ this.code = code;+ this.status = status;+ this.detail = detail;+ }+ },+ loadOwnedAgent: vi.fn(async (id) => ({ id, user_id: 'u1', meta: state.agentMeta })),+ previewOpen: (...a) => previewOpen(...a),+ executeOpen: (...a) => executeOpen(...a),+}));++const buildOpenOrder = vi.fn();+const buildCloseOrder = vi.fn();+const buildRedeem = vi.fn();+const submit = vi.fn();+const market = {+ id: 'SYN-1',+ event_id: 'SYN-E1',+ title: 'Synthetic market',+ provider: 'provider-a',+ status: 'open',+ tradable: true,+ close_time: '2027-01-01T00:00:00.000Z',+ outcomes: [+ { side: 'yes', buy_price: 0.4, sell_price: 0.39 },+ { side: 'no', buy_price: 0.61, sell_price: 0.6 },+ ],+};+const fakeVenue = {+ id: 'solana',+ getMarket: vi.fn(async () => market),+ getOrderbook: vi.fn(async () => ({ yes_bids: [[0.39, 500]], no_bids: [[0.6, 500]] })),+ buildOpenOrder,+ buildCloseOrder,+ buildRedeem,+ submit,+};+vi.mock('../api/_lib/predictions/index.js', () => ({ DEFAULT_VENUE: 'solana', getVenue: () => fakeVenue, listVenues: () => [], VenueError: class VenueError extends Error {} }));++const { feePerContract, totalFee, walkComplement, topOfBookEdge, scoreMarket, rankRows, DEFAULT_MODELS } = await import('../api/_lib/predictions/arb.js');+const { getStrategy, strategyLoosens, setStrategy, priceIntent, markEntry, summarize, submitIntent } = await import('../api/_lib/predictions/shadow.js');++const FLAT = { venue: { kind: 'bps_of_notional', bps: 0 }, providers: {}, default_provider: { kind: 'bps_of_notional', bps: 0 }, thresholds: DEFAULT_MODELS.thresholds, strategy_defaults: DEFAULT_MODELS.strategy_defaults };++beforeEach(() => {+ state.rows = [];+ state.agentMeta = {};+ for (const f of [sqlSpy, previewOpen, executeOpen, buildOpenOrder, buildCloseOrder, buildRedeem, submit]) f.mockClear();+});++describe('fee models', () => {+ it.each([+ [{ kind: 'bps_of_notional', bps: 100 }, 0.5, 0.005],+ [{ kind: 'bps_of_notional', bps: 0 }, 0.5, 0],+ [{ kind: 'p_one_minus_p', rate: 0.07 }, 0.5, 0.0175],+ [{ kind: 'p_one_minus_p', rate: 0.07 }, 0.1, 0.0063],+ [{ kind: 'flat_per_contract', usd: 0.01 }, 0.9, 0.01],+ ])('%j at %d costs %d a contract', (model, price, fee) => {+ expect(feePerContract(model, price)).toBeCloseTo(fee, 10);+ });++ it('stacks the venue fee on the provider fee', () => {+ const m = { ...FLAT, venue: { kind: 'bps_of_notional', bps: 100 }, providers: { 'provider-b': { kind: 'p_one_minus_p', rate: 0.07 } } };+ expect(totalFee(m, 'provider-b', 0.5)).toBeCloseTo(0.005 + 0.0175, 10);+ expect(totalFee(m, 'unknown', 0.5)).toBeCloseTo(0.005 + 0, 10);+ });+});++describe('fee-adjusted edge', () => {+ const cases = [+ // name, yes ask, no ask, models, expected net edge per contract+ ['efficient market, no fees', 0.4, 0.6, FLAT, 0],+ ['two cents under par, no fees', 0.4, 0.58, FLAT, 0.02],+ ['two cents under par, 1% venue fee eats part', 0.4, 0.58, { ...FLAT, venue: { kind: 'bps_of_notional', bps: 100 } }, 0.02 - 0.01 * (0.4 + 0.58)],+ ['two cents under par, provider-b schedule at 50/50', 0.5, 0.48, { ...FLAT, providers: { 'provider-b': { kind: 'p_one_minus_p', rate: 0.07 } } }, 0.02 - 0.0175 - 0.07 * 0.48 * 0.52],+ ['over par is negative', 0.55, 0.5, FLAT, -0.05],+ ];+ it.each(cases)('%s', (_n, y, n, models, expected) => {+ const provider = Object.keys(models.providers)[0] || null;+ const top = topOfBookEdge({ yes_bids: [[1 - n, 100]], no_bids: [[1 - y, 100]] }, { models, provider });+ expect(top.net_edge).toBeCloseTo(expected, 5);+ });++ it('walks levels while the marginal pair still clears the floor', () => {+ const yes = [[0.4, 100], [0.45, 100]];+ const no = [[0.58, 150], [0.6, 100]];+ const r = walkComplement(yes, no, { models: FLAT, minEdge: 0.005 });+ // pair 1: 0.4+0.58 = 0.98 edge .02 for 100 contracts; pair 2: 0.45+0.58 = 1.03 stops.+ expect(r.contracts).toBe(100);+ expect(r.cost_usd).toBe(98);+ expect(r.profit_usd).toBe(2);+ expect(r.edge_pct).toBeCloseTo((2 / 98) * 100, 3);+ });++ it('takes nothing when fees consume the gross edge', () => {+ const r = walkComplement([[0.4, 100]], [[0.58, 100]], { models: { ...FLAT, venue: { kind: 'bps_of_notional', bps: 300 } }, minEdge: 0.005 });+ expect(r.contracts).toBe(0);+ expect(r.profit_usd).toBe(0);+ });++ it('marks a market executable only past the depth and edge floors, and ranks it first', () => {+ const m = { id: 'SYN-A', title: 'a', provider: 'provider-a' };+ const thick = { yes_bids: [[0.42, 500]], no_bids: [[0.6, 500]] }; // asks 0.40 / 0.58+ const thin = { yes_bids: [[0.42, 1]], no_bids: [[0.6, 1]] };+ const flat = { yes_bids: [[0.4, 500]], no_bids: [[0.6, 500]] }; // asks 0.40 / 0.60+ const a = scoreMarket({ ...m, id: 'thick' }, thick, { models: FLAT });+ const b = scoreMarket({ ...m, id: 'thin' }, thin, { models: FLAT });+ const c = scoreMarket({ ...m, id: 'flat' }, flat, { models: FLAT });+ expect(a.executable).toBe(true);+ expect(b.executable).toBe(false);+ expect(c.executable).toBe(false);+ expect(rankRows([c, b, a]).map((r) => r.market_id)).toEqual(['thick', 'thin', 'flat']);+ });+});++describe('strategy setting', () => {+ it('defaults to shadow', () => {+ expect(getStrategy({}).mode).toBe('shadow');+ expect(getStrategy(null).mode).toBe('shadow');+ expect(getStrategy({ prediction_strategy: { mode: 'anything-else' } }).mode).toBe('shadow');+ expect(getStrategy({ prediction_strategy: { mode: 'live' } }).mode).toBe('live');+ });++ it('treats live and looser caps as loosening', () => {+ const base = getStrategy({});+ expect(strategyLoosens(base, { ...base, mode: 'live' })).toBe(true);+ expect(strategyLoosens(base, { ...base, max_stake_usd: base.max_stake_usd + 1 })).toBe(true);+ expect(strategyLoosens(base, { ...base, min_edge_pct: 0 })).toBe(true);+ expect(strategyLoosens(base, { ...base, max_stake_usd: 1 })).toBe(false);+ });++ it('refuses to go live without the owner session and writes nothing', async () => {+ await expect(setStrategy({ agentId: 'a1', userId: 'u1', patch: { mode: 'live' }, ownerSession: false })).rejects.toMatchObject({ code: 'owner_session_required' });+ expect(sqlSpy).not.toHaveBeenCalled();+ await setStrategy({ agentId: 'a1', userId: 'u1', patch: { mode: 'live' }, ownerSession: true });+ expect(sqlSpy).toHaveBeenCalledTimes(1);+ });+});++describe('shadow mode never trades', () => {+ it('records the decision and calls no order function', async () => {+ const out = await submitIntent({ agentId: 'a1', userId: 'u1', intent: { market_id: 'SYN-1', side: 'yes', stake_usd: 10, reason: 'test' } });+ expect(out.mode).toBe('shadow');+ expect(out.recorded.mode).toBe('shadow');+ expect(state.rows).toHaveLength(1);+ expect(previewOpen).not.toHaveBeenCalled();+ expect(executeOpen).not.toHaveBeenCalled();+ expect(buildOpenOrder).not.toHaveBeenCalled();+ expect(buildCloseOrder).not.toHaveBeenCalled();+ expect(buildRedeem).not.toHaveBeenCalled();+ expect(submit).not.toHaveBeenCalled();+ });++ it('treats a corrupt strategy as shadow', async () => {+ state.agentMeta = { prediction_strategy: { mode: 'LIVE ' } };+ const out = await submitIntent({ agentId: 'a1', userId: 'u1', intent: { market_id: 'SYN-1', side: 'no', stake_usd: 5 } });+ expect(out.mode).toBe('shadow');+ expect(previewOpen).not.toHaveBeenCalled();+ expect(buildOpenOrder).not.toHaveBeenCalled();+ });++ it('in live mode previews through the engine but still never executes or builds', async () => {+ state.agentMeta = { prediction_strategy: { mode: 'live' } };+ const out = await submitIntent({ agentId: 'a1', userId: 'u1', intent: { market_id: 'SYN-1', side: 'yes', stake_usd: 10 } });+ expect(out.mode).toBe('live');+ expect(previewOpen).toHaveBeenCalledTimes(1);+ expect(executeOpen).not.toHaveBeenCalled();+ expect(buildOpenOrder).not.toHaveBeenCalled();+ expect(submit).not.toHaveBeenCalled();+ });++ it('refuses a stake over the strategy cap before touching the ledger', async () => {+ await expect(submitIntent({ agentId: 'a1', userId: 'u1', intent: { market_id: 'SYN-1', side: 'yes', stake_usd: 5000 } })).rejects.toMatchObject({ code: 'invalid_stake' });+ expect(state.rows).toHaveLength(0);+ });+});++describe('pricing and marking', () => {+ const book = { yes_bids: [[0.39, 500]], no_bids: [[0.6, 500]] };++ it('prices the decision at the best ask and the entry at the walked average', () => {+ const p = priceIntent({ book, side: 'yes', stakeUsd: 10, provider: 'provider-a', models: FLAT });+ expect(p.price_at_decision).toBe(0.4);+ expect(p.entry_price).toBe(0.4);+ expect(p.contracts).toBe(25);+ expect(p.fees_usd).toBe(0);+ });++ it('returns null when the side has no asks', () => {+ expect(priceIntent({ book: { yes_bids: [], no_bids: [] }, side: 'yes', stakeUsd: 10, provider: null })).toBeNull();+ });++ const entry = { side: 'yes', contracts: 25, cost_usd: 10, fees_usd: 0.1, entry_price: 0.4 };+ it('settles a win at one dollar a contract, net of cost and fees', () => {+ expect(markEntry(entry, { result: 'yes' })).toMatchObject({ status: 'won', payout_usd: 25, pnl_usd: 14.9, resolved: true });+ });+ it('settles a loss as the whole stake plus fees', () => {+ expect(markEntry(entry, { result: 'no' })).toMatchObject({ status: 'lost', payout_usd: 0, pnl_usd: -10.1, resolved: true });+ });+ it('returns the cost on a refund', () => {+ expect(markEntry(entry, { result: 'refund' })).toMatchObject({ status: 'void', payout_usd: 10, pnl_usd: -0.1, resolved: true });+ });+ it('values an open entry at the bid, less the exit fee', () => {+ const m = { provider: 'provider-a', outcomes: [{ side: 'yes', sell_price: 0.5 }, { side: 'no', sell_price: 0.5 }] };+ const r = markEntry(entry, m, FLAT);+ expect(r).toMatchObject({ status: 'open', mark_price: 0.5, resolved: false });+ expect(r.pnl_usd).toBeCloseTo(25 * 0.5 - 10.1, 4);+ });++ it('summarizes shadow and live separately and exposes the cost of fees and slippage', () => {+ const rows = [+ { mode: 'shadow', status: 'won', contracts: 25, cost_usd: 10, fees_usd: 0.1, price_at_decision: 0.39, entry_price: 0.4, mark_price: 1, pnl_usd: 14.9 },+ { mode: 'shadow', status: 'lost', contracts: 10, cost_usd: 5, fees_usd: 0.05, price_at_decision: 0.5, entry_price: 0.5, mark_price: 0, pnl_usd: -5.05 },+ { mode: 'live', status: 'open', contracts: 10, cost_usd: 4, fees_usd: 0.04, price_at_decision: 0.4, entry_price: 0.4, mark_price: 0.45, pnl_usd: 0.4 },+ ];+ const s = summarize(rows);+ expect(s.shadow).toMatchObject({ entries: 2, settled: 2, won: 1, lost: 1, win_rate: 0.5, realized_pnl_usd: 9.85, total_pnl_usd: 9.85 });+ expect(s.shadow.gross_pnl_usd).toBeCloseTo(25 - 25 * 0.39 - 10 * 0.5, 1);+ expect(s.shadow.costs_usd).toBeCloseTo(0.1 + 0.05 + 25 * 0.01, 2);+ expect(s.live).toMatchObject({ entries: 1, open: 1, unrealized_pnl_usd: 0.4, win_rate: null });+ });+});diff --git a/vercel.json b/vercel.jsonindex cb353e4d0..135c490bd 100644--- a/vercel.json+++ b/vercel.json@@ -343,6 +343,10 @@"src": "/agent-perps/?","dest": "/agent-perps.html"},+ {+ "src": "/agent-predictions/?",+ "dest": "/agent-predictions.html"+ },{"src": "/agent-mail/?","dest": "/agent-mail.html"@@ -5856,6 +5860,10 @@"src": "/agents/[^/.]+/perps/?","dest": "/agent-perps.html"},+ {+ "src": "/agents/[^/.]+/predictions/?",+ "dest": "/agent-predictions.html"+ },{"src": "/agents/[^/.]+/mail/?","dest": "/agent-mail.html"diff --git a/vite.config.js b/vite.config.jsindex 5f113695d..0e687f627 100644--- a/vite.config.js+++ b/vite.config.js@@ -856,6 +856,7 @@ const appConfig = {'agent-wallet': resolve(__dirname, 'pages/agent-wallet.html'),'agent-cards': resolve(__dirname, 'pages/agent-cards.html'),'agent-perps': resolve(__dirname, 'pages/agent-perps.html'),+ 'agent-predictions': resolve(__dirname, 'pages/agent-predictions.html'),'agent-mail': resolve(__dirname, 'pages/agent-mail.html'),wallet: resolve(__dirname, 'pages/wallet.html'),guardian: resolve(__dirname, 'pages/guardian.html'),@@ -2530,6 +2531,9 @@ const appConfig = {// /agents/:id/perps and /agent-perps → Agent Perps (perpetual futures).else if (!filePath && /^\/(agents\/[^/.]+\/perps|agent-perps)\/?$/.test(path))filePath = resolve(root, 'pages/agent-perps.html');+ // /agents/:id/predictions and /agent-predictions → Agent Predictions (shadow mode and scanner).+ else if (!filePath && /^\/(agents\/[^/.]+\/predictions|agent-predictions)\/?$/.test(path))+ filePath = resolve(root, 'pages/agent-predictions.html');// /agents/:id/mail and /agent-mail → Agent Mail (the agent's inbox).else if (!filePath && /^\/(agents\/[^/.]+\/mail|agent-mail)\/?$/.test(path))filePath = resolve(root, 'pages/agent-mail.html');