Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(approvals): let agents pause for the owner's yes instead of failing, with an /approvals inbox, push Approve/Deny and strategy ask mode

nirholas48731af8b1bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 92ef673e4..6a6c2d103 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-10-10
+- **Approvals** (`/approvals`): Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.
+- **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]`
- **Live agent payments keep running when fee sponsorship pauses**: When the wallet that covers Solana network fees for agent payments runs low, agents on three.ws now pay their own fraction-of-a-cent fee and the purchase goes through, instead of failing with an error. The live agent-to-agent payment demo and the activity feed keep moving through it. (`/agent-exchange`) `[fix]`
- **Quieter, cleaner pages: dead links fixed and console errors gone**: We swept every page on three.ws with the browser developer console open and fixed what it found. Links to pages that moved now redirect to where they live today, share buttons always have a destination, 3D viewers decode compressed models on every page, the missing bow animation thumbnail is back on the choreography and gestures pages, and pages full of brand-new coins or agents without a wallet no longer fill the console with errors while they wait for data. (`/gestures`) `[fix]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 49287a2cf..d2d31a14c 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -81,6 +81,7 @@ bottom.
| Follow graph | [api/users/[username]/follow.js](api/users/%5Busername%5D/follow.js) + [api/users/[username]/follows.js](api/users/%5Busername%5D/follows.js), table `user_follows`, buttons on [pages/profile.html](pages/profile.html) | Live | `GET` returns `{following, followed_by, followers_count, following_count}`; `POST`/`DELETE` are idempotent (session + CSRF, self-follow 400) and return the same envelope so one round-trip updates the button and the counts. A genuinely new edge (`ON CONFLICT DO NOTHING`) publishes a `follow` user event to the notification bell exactly once. Feeds the activity feed's following scope, search ranking, and the `followers` leaderboard metric. Tests: [tests/api/users-follow.test.js](tests/api/users-follow.test.js). Docs: [docs/social-layer.md](docs/social-layer.md) |
| Herald: messages delivered in person | SDK [herald-sdk/](herald-sdk) `→ /herald.js` (published as `@three-ws/herald`), rail [api/herald/announce.js](api/herald/announce.js) + [api/herald/stream.js](api/herald/stream.js) + [api/_lib/herald.js](api/_lib/herald.js), playground [pages/herald.html](pages/herald.html) `→ /herald` + [src/herald-page.js](src/herald-page.js), CLI [herald-sdk/bin/herald.mjs](herald-sdk/bin/herald.mjs), MCP [packages/herald-mcp/](packages/herald-mcp) | Live | A 3D character walks onto the page and says what happened, instead of a badge nobody notices. The library is the interrupt budget: importance scoring with pluggable scorers, a floor, quiet hours, a rate limit, dedupe with a TTL, freshness, batch collapse, focus awareness, and a stable reason for every message it refuses (`duplicate`, `rate-limited`, `quiet-hours`, `below-importance-floor`). Delivery is the walk companion ([walk-sdk](walk-sdk) `control.announce`) with an accessible `aria-live` card fallback for anything that cannot render 3D, and opt-in gesture-gated voice. **The rail is the part nobody expects:** `POST /api/herald/announce` with an API key carrying the `herald:announce` scope reaches the browser tab the caller has open over SSE, so `herald watch -- npm test` makes your avatar tell you the build finished, and an AI agent can do the same through the MCP server. An announcement is always delivered to the caller's own sessions (no recipient field, so no key can interrupt anyone else); the queue is Redis-backed, drained not broadcast, and expires in five minutes. Docs: [docs/herald.md](docs/herald.md), [docs/api-reference.md](docs/api-reference.md). Tests: [tests/herald-rules.test.js](tests/herald-rules.test.js), [tests/herald-runtime.test.js](tests/herald-runtime.test.js), [tests/herald-rail.test.js](tests/herald-rail.test.js), [tests/herald-announce-endpoint.test.js](tests/herald-announce-endpoint.test.js) |
| Notification bell & preferences | Event vocabulary [api/_lib/feed.js](api/_lib/feed.js) (`USER_EVENT_TYPES` → `publishUserEvent()` → `user_notifications`), endpoints [api/notifications/](api/notifications), preference matrix [api/_lib/notify-prefs.js](api/_lib/notify-prefs.js), bell client [src/notifications.js](src/notifications.js), avatar announcements [src/notification-herald.js](src/notification-herald.js), settings panel [src/dashboard-next/pages/settings.js](src/dashboard-next/pages/settings.js) | Live | In-app inbox covering remixes ([api/x402/remix-asset.js](api/x402/remix-asset.js)), DMs ([api/friends/messages.js](api/friends/messages.js)), coin bonding-curve graduations (pump cron in [api/cron/[name].js](api/cron/%5Bname%5D.js)), follows, sales, purchases, IRL, market, and account events. Preferences are a category × channel matrix (`in_app` always on; push/email/telegram/avatar are per-category opt-outs) edited from `/dashboard/settings`. **The `avatar` channel delivers in person:** for a fresh, unread notification in an opted-in category the corner companion walks on screen, gestures, and says the line with a link straight to it, summoning itself for that one message and retreating if it was off ([walk-sdk](walk-sdk) `control.announce`). Rules (15-minute freshness, once per browser, two per batch, visible tab only, device-level mute) live in [src/notification-herald.js](src/notification-herald.js). Docs: [docs/notifications.md](docs/notifications.md), [docs/social-layer.md](docs/social-layer.md). Tests: [tests/notification-herald.test.js](tests/notification-herald.test.js), [tests/notify-prefs.test.js](tests/notify-prefs.test.js) |
+| Approval inbox | Page [pages/approvals.html](pages/approvals.html) `→ /approvals` (deep links `/approvals/<id>?t=`) + [src/approvals-page.js](src/approvals-page.js), API [api/approvals/](api/approvals), library [api/_lib/approvals.js](api/_lib/approvals.js), wallet-intent wiring [api/_lib/wallet-intents.js](api/_lib/wallet-intents.js), push actions [public/push-sw.js](public/push-sw.js), migration [api/_lib/migrations/20261010120000_approval_requests.sql](api/_lib/migrations/20261010120000_approval_requests.sql) | Live | When an agent's spend rule is set to "Ask me", the action becomes an approval request instead of executing: a confirmation table (recipient, amount, asset and chain, USD value, risk notes), a SHA-256 payload hash, and a deadline (15 min for swaps, 6 h for transfers). Delivered through the notification fan-out (bell, web push with Approve/Deny buttons, iOS, Telegram/Discord) with a signed deep link, plus email when nothing else reached the owner. Approving re-checks the hash and claims the row with a conditional update, so it executes exactly the shown action once; deny and expiry fail closed. The inbox adds status tabs, an agent filter, bulk deny, revocable auto-approve rules (per venue, capped at $1,000, optionally per agent or team), and an activity log from the audit log. Docs: [docs/approvals.md](docs/approvals.md). Tests: [tests/approvals.test.js](tests/approvals.test.js) |
| Personal companion (`/companion`) | Page [pages/companion.html](pages/companion.html) `→ /companion` + [src/companion/](src/companion) (page, source cards, voice), API [api/companion/](api/companion) (settings, sources, contacts, events, `ingest`, `stream`, `poll`), engine [api/_lib/companion/](api/_lib/companion) (store, encrypted BYOK configs, triage, lanes for Telegram / iCal / IMAP), cron [api/cron/companion-poll.js](api/cron/companion-poll.js), migration [api/_lib/migrations/20260828140000_companion_harness.sql](api/_lib/migrations/20260828140000_companion_harness.sql) | Live | Turns a person's own inbox, chats, calendar and phone into deliveries a 3D character makes **in person**. BYOK per source (a Telegram bot the user made, a private iCal URL, IMAP with an app password) plus a universal bridge token anything can POST to. Every message is scored 0-100 by the shared deterministic rules ([@three-ws/companion/triage](packages/companion-sdk/src/triage-rules.js), the same module the CLI runs locally) and optionally refined by the user's own Anthropic key; above their threshold and outside quiet hours it is delivered through `companion_delivery` notifications, so the bell, Web Push, and the avatar channel all carry it. A contact's message is spoken by **that contact's avatar and voice** (`control.announce({ avatar })` in [walk-sdk](walk-sdk)). A delivery whose lane can carry an answer (Telegram, through the user's own bot) offers a reply box in place, and the reply is stored with the message. Live SSE at `/api/companion/stream` feeds the desktop app and any third-party body. Docs: [docs/companion.md](docs/companion.md). Tests: [tests/companion-triage.test.js](tests/companion-triage.test.js), [tests/companion-calendar.test.js](tests/companion-calendar.test.js), [packages/companion-sdk/tests/](packages/companion-sdk/tests) |
| three.ws Drive: the agent in the car (`/drive`) | Page [pages/drive.html](pages/drive.html) `→ /drive` + [src/drive/](src/drive) (page controller, surface presets, native bridge, local commands, motion gate); native CarPlay scene [ios/native/App/App/CarPlaySceneDelegate.swift](ios/native/App/App/CarPlaySceneDelegate.swift) + [DriveLink.swift](ios/native/App/App/DriveLink.swift); Android Auto car app [solana-mobile/android-overlay/app/src/main/java/ws/three/app/drive/](solana-mobile/android-overlay/app/src/main/java/ws/three/app/drive) | Live (web) / built and compiled (Android Auto) / built, entitlement pending (CarPlay) | The existing talk loop (`/api/asr` → `/api/chat` → `/api/tts` → lipsync on a real rigged avatar) rebuilt for a car panel: one glanceable two-line reply instead of a transcript, exactly four controls, night by default, and a keyboard that hides itself while the wheels turn. Speed comes from `navigator.geolocation`'s real ground speed, so moving above walking pace locks text entry back and a sustained stop is what unlocks it. Control phrases ("repeat that", "stop talking", "louder", "night mode") are answered locally with no round trip, matched against the whole utterance so "stop at the next charger" still reaches the agent. Hands free ends a turn from the real captured mic level on the Riva lane. **The car screen is never ours to draw on, on either platform:** Apple's voice-based conversational category (iOS 26.4) grants templates and an audio session and no drawing surface, and Android grants a canvas only to navigation apps and has no conversational category at all, so both car screens render the same four rows and this page runs beside them, joined by the versioned `threeWsDrive` channel (a WebKit message handler on iOS, a JavaScript interface on Android). Android Auto declares `androidx.car.app.category.IOT` because that is accurate: the home tools in `api/chat.js` reach a real house, so "turn the porch light on" from the car is the product. Its web view has no window and therefore no animation frames, so `?surface=androidauto` runs the loop as audio with the stage off, and refuses tap-to-approve for guarded actions because a person who cannot see what they are approving must not be asked. A guarded action while moving is refused on every surface and offered for when the car stops. Docs: [docs/carplay.md](docs/carplay.md), [ios/docs/CARPLAY.md](ios/docs/CARPLAY.md), [solana-mobile/docs/ANDROID-AUTO.md](solana-mobile/docs/ANDROID-AUTO.md). Tests: [tests/drive-surface.test.js](tests/drive-surface.test.js) |
| Hands-free voice for the house (`/voice/home`) | Loop [src/voice/home-voice.js](src/voice/home-voice.js), VAD [src/voice/vad.js](src/voice/vad.js), wake word [src/voice/wake-word.js](src/voice/wake-word.js) + catalog [src/voice/wake-words.js](src/voice/wake-words.js), panel [src/voice/home-voice-ui.js](src/voice/home-voice-ui.js) + [public/home-voice.css](public/home-voice.css); page [pages/voice-home.html](pages/voice-home.html) `→ /voice/home` + [src/voice-home.js](src/voice-home.js); models committed under [public/models/voice/wake-word/](public/models/voice/wake-word) with the silero + onnxruntime runtime staged by [scripts/copy-voice-models.mjs](scripts/copy-voice-models.mjs) | Live | The browser half of three.ws Home: mic → silero VAD → openWakeWord → `/api/asr` → `/api/chat` (home tools) → `/api/tts/speak` → lipsync, with one `getUserMedia` shared by all three consumers. Wake-word matching runs entirely in the tab on committed openWakeWord v0.5.1 weights served from three.ws, so nothing is uploaded until after the wake word; nothing about detection is even downloaded until the user opts in. Barge-in cuts playback ~110 ms after the user starts talking, and a playback-aware guard means the agent saying its own wake word (score 0.99) wakes it zero times. A pause is not an ending: a closed segment stays open 450 ms so "Hey Jarvis… turn the kitchen light off" is one command. Guarded actions are spoken in full, shown on screen by name and entity id, and satisfied only by the token `confirm` redeemed at `POST /api/home/:id/confirm`; a general "yeah" is refused by name and a screenless surface is refused outright. Twelve designed states, mute that ends the track rather than hiding a dot, and every leg timed live. Docs: [docs/home-voice.md](docs/home-voice.md). Proof: [scripts/check-home-voice.mjs](scripts/check-home-voice.mjs) (36 assertions in a real Chromium, plus two `--live` scenarios against a real Home Assistant: `live-confirm` mints a real confirmation and proves redeeming it really unlocks a real deadbolt and cannot be replayed, and `live` proves the spoken command really turns the light off wherever a tool-calling provider key is configured, skipping with its reason where none is). Tests: [tests/home-voice.test.js](tests/home-voice.test.js) |
diff --git a/api/_lib/agent-strategy-runtime.js b/api/_lib/agent-strategy-runtime.js
index dfcaf4b82..da1900c01 100644
--- a/api/_lib/agent-strategy-runtime.js
+++ b/api/_lib/agent-strategy-runtime.js
@@ -38,8 +38,16 @@ import {
checkPerTradeCap, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,
SOL_FEE_HEADROOM_LAMPORTS,
} from './agent-trade-guards.js';
-import { normalizeStrategyConfig, matchesEntry, shouldExit } from './strategy-schema.js';
+import {
+ normalizeStrategyConfig, matchesEntry, shouldExit,
+ researchGatesActive, evaluateResearchGates,
+} from './strategy-schema.js';
import { recentPumpLaunches, enrichCreatorStats } from './pump-launch-feed.js';
+import { buildGateReport } from './strategy-research.js';
+import {
+ recordCandidateDecision, createStrategyApproval, pendingApprovalCount, recentDecisions,
+ payloadHash, STRATEGY_APPROVAL_SOURCE,
+} from './strategy-approvals.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
const lamToSol = (l) => Number(BigInt(l)) / LAMPORTS_PER_SOL;
@@ -66,6 +74,8 @@ export const STRATEGY_SKIP_LABELS = Object.freeze({
already_held: 'agent already holds a position in this mint',
wallet_preparing: 'agent wallet still provisioning',
no_holding: 'no token balance to exit',
+ research_blocked: 'blocked by the strategy’s research gates',
+ approval_unavailable: 'ask mode could not file an approval request',
});
// ── agent loader ──────────────────────────────────────────────────────────────
@@ -108,8 +118,16 @@ async function readTokenBalance(conn, ownerPk, mintPk) {
// mirror executor, composed for a server-initiated strategy action. Returns a
// structured result — never throws past the boundary. Labels the custody trail
// with reason 'strategy:<slug>' so every fill is attributable to the strategy.
+//
+// `maxPriceImpactPct` tightens the agent's breaker for this trade (a strategy's
+// own max_price_impact_bps); it can never loosen it. `preAssessment` reuses a
+// firewall verdict the research gates already computed for this exact buy, so
+// the firewall is not run twice. `dryRun` stops after every guard and returns
+// { status: 'ready', quote } without claiming custody or signing: ask mode uses
+// it so an owner is only ever asked about a trade the guards would allow.
export async function runStrategyTrade({
agent, side, mint, network, solAmount, tokenAmountRaw, slippageBps, idempotencyKey, strategyRef,
+ maxPriceImpactPct = null, preAssessment = null, dryRun = false,
}) {
const { id, ownerId, meta, address, encryptedSecret } = agent;
if (!address || !encryptedSecret) return { status: 'failed', code: 'wallet_preparing' };
@@ -165,14 +183,18 @@ export async function runStrategyTrade({
}
}
- if (checkPriceImpact(quote.priceImpactPct, tradeLimits.max_price_impact_pct)) {
- return { status: 'skipped', code: 'price_impact' };
+ const agentImpactCap = tradeLimits.max_price_impact_pct;
+ const impactCap = side === 'buy' && maxPriceImpactPct != null
+ ? (agentImpactCap == null ? maxPriceImpactPct : Math.min(maxPriceImpactPct, agentImpactCap))
+ : agentImpactCap;
+ if (checkPriceImpact(quote.priceImpactPct, impactCap)) {
+ return { status: 'skipped', code: 'price_impact', priceImpact: quote.priceImpactPct, impactCap };
}
// 3. Rug/honeypot firewall — buys only, the unsafe direction. A 'block' verdict
// refuses the entry (degrades to allow when a source is down, never stalls).
if (side === 'buy') {
- const assessment = await assessTradeSafety({
+ const assessment = preAssessment || await assessTradeSafety({
network, mint: mintPk, side: 'buy', payer: ownerPk,
quoteAmount: BigInt(quote.inAtomics), priceImpactPct: quote.priceImpactPct,
}).catch(() => null);
@@ -198,6 +220,8 @@ export async function runStrategyTrade({
}
}
+ if (dryRun) return { status: 'ready', quote, usd: usdValue, priceImpact: quote.priceImpactPct, impactCap };
+
// 5. Idempotency claim in the custody ledger (also the spend row). A retry with
// the same key replays instead of double-spending.
const [prior] = await sql`
@@ -294,6 +318,68 @@ export async function runStrategyTrade({
// Best-effort. Opens at most `maxEntries` real positions this sweep. Records an
// open position row per confirmed buy; the unique (agent,mint,network) index and
// the custody idempotency key both prevent a double entry.
+//
+// Order of checks for each launch: entry filter (cheap, pure) → already held →
+// research gates against a cited gate report → mode. In auto mode the buy runs
+// through the full guarded path within the agent's caps; in ask mode the same
+// guards run as a dry run and, if they would allow it, an approval request is
+// filed for the owner instead of buying. Every candidate that clears the entry
+// filter gets a decision row saying what happened and which check decided it.
+
+// Upsert the open position for a confirmed (or unconfirmed-but-sent) entry buy.
+// A fresh open position, OR revive a previously-CLOSED row for the same mint
+// (re-entry after a take-profit/stop). The WHERE guard means an already-open row
+// (another strategy) is never clobbered.
+export async function recordEntryPosition({ equip, agentId, network, mint, symbol = null, name = null, result }) {
+ const entryLamports = result.quote ? result.quote.inAtomics : null;
+ const baseAmount = result.quote ? result.quote.outAtomics : null;
+ await sql`
+ INSERT INTO agent_strategy_positions
+ (equip_id, strategy_id, agent_id, owner_id, network, mint, symbol, name, status,
+ entry_sig, entry_lamports, base_amount, entry_price_impact_pct,
+ peak_value_lamports, last_value_lamports, last_quoted_at)
+ VALUES (
+ ${equip.id}, ${equip.strategy_id}, ${agentId}, ${equip.owner_id}, ${network},
+ ${mint}, ${symbol}, ${name}, 'open',
+ ${result.signature || null}, ${entryLamports}, ${baseAmount}, ${result.priceImpact ?? null},
+ ${entryLamports}, ${entryLamports}, now()
+ )
+ ON CONFLICT (agent_id, mint, network) DO UPDATE SET
+ equip_id = excluded.equip_id, strategy_id = excluded.strategy_id, owner_id = excluded.owner_id,
+ symbol = excluded.symbol, name = excluded.name, status = 'open', exit_reason = NULL,
+ entry_sig = excluded.entry_sig, entry_lamports = excluded.entry_lamports,
+ base_amount = excluded.base_amount, entry_price_impact_pct = excluded.entry_price_impact_pct,
+ peak_value_lamports = excluded.peak_value_lamports, last_value_lamports = excluded.last_value_lamports,
+ last_quoted_at = now(), exit_sig = NULL, exit_lamports = NULL,
+ realized_pnl_lamports = NULL, realized_pnl_pct = NULL, error = NULL,
+ opened_at = now(), closed_at = NULL
+ WHERE agent_strategy_positions.status = 'closed'
+ `.catch(() => {});
+ await sql`
+ UPDATE agent_strategy_equips
+ SET last_fired_at = now(), fires_count = fires_count + 1, last_eval_at = now(), updated_at = now()
+ WHERE id = ${equip.id}
+ `.catch(() => {});
+}
+
+// Tag the launches an agent launched through three.ws, for entry.sources. One
+// indexed query per sweep, only when the strategy filters on it.
+async function tagThreeWsLaunches(launches, network) {
+ const mints = launches.map((l) => l.mint).filter(Boolean);
+ if (!mints.length) return launches;
+ const rows = await sql`
+ SELECT mint FROM pump_agent_mints WHERE network = ${network} AND mint = ANY(${mints})
+ `.catch(() => []);
+ const ours = new Set(rows.map((r) => r.mint));
+ return launches.map((l) => (ours.has(l.mint) ? { ...l, three_ws_launch: true } : l));
+}
+
+const guardDecision = (result) => {
+ if (result.status === 'executed' || result.status === 'unconfirmed') return 'executed';
+ if (result.status === 'skipped') return 'skipped';
+ return 'failed';
+};
+
async function evaluateEntries({ equip, agent, launches, nowMs, maxEntries = 3 }) {
const config = normalizeStrategyConfig(equip.config_snapshot);
const network = netOf(equip.network);
@@ -309,18 +395,31 @@ async function evaluateEntries({ equip, agent, launches, nowMs, maxEntries = 3 }
if (sinceMin < config.risk.cooldown_minutes) return results;
}
- // Concurrency — never exceed the strategy's max concurrent open positions.
+ // Concurrency — never exceed the strategy's max concurrent open positions. In
+ // ask mode a pending approval holds a slot too, so the owner is never asked for
+ // more buys than the strategy may hold at once.
const [openCnt] = await sql`
SELECT count(*)::int AS n FROM agent_strategy_positions
WHERE equip_id = ${equip.id} AND status IN ('open','closing')
`;
- let room = Math.max(0, (config.risk.max_concurrent_positions || 0) - Number(openCnt?.n || 0));
+ const pending = config.mode === 'ask' ? await pendingApprovalCount(equip.id) : 0;
+ let room = Math.max(0, (config.risk.max_concurrent_positions || 0) - Number(openCnt?.n || 0) - pending);
if (room <= 0) return results;
+ const candidates = config.entry.sources.includes('three_ws_launch')
+ ? await tagThreeWsLaunches(launches, network)
+ : launches;
+ const gated = researchGatesActive(config);
+ // A candidate decided recently is not re-researched every sweep: approvals and
+ // buys are final for that coin, and a block is re-checked after a short pause
+ // (holders and liquidity grow, so a coin can clear a gate later).
+ const decided = await recentDecisions(equip.id, candidates.map((l) => l.mint));
const slippageBps = config.sizing.max_slippage_bps;
+ const maxPriceImpactPct = config.sizing.max_price_impact_bps == null ? null : config.sizing.max_price_impact_bps / 100;
let opened = 0;
- for (const launchRaw of launches) {
+ for (const launchRaw of candidates) {
if (opened >= maxEntries || room <= 0) break;
+ if (decided.has(launchRaw.mint)) continue;
const launch = { ...launchRaw };
// Enrich creator history only when the strategy actually gates on it (one
@@ -343,22 +442,79 @@ async function evaluateEntries({ equip, agent, launches, nowMs, maxEntries = 3 }
`;
if (held) continue;
- const idem = `strategy:${equip.id}:entry:${launch.mint}`;
const strategyRef = {
strategy_id: equip.strategy_id, equip_id: equip.id, slug: equip.slug,
strategy_name: equip.strategy_name, action: 'entry',
};
+ const decisionBase = { equip, agentId: agent.id, network, mint: launch.mint };
+
+ // Research gates: build the cited report only when a gate is on or the owner
+ // will be asked (the approval card shows its risk notes).
+ let report = null;
+ let assessment = null;
+ if (gated || config.mode === 'ask') {
+ ({ report, assessment } = await buildGateReport({
+ config, launch, network, payer: agent.address, forApproval: config.mode === 'ask',
+ }));
+ const evaluation = evaluateResearchGates(config, report);
+ if (!evaluation.pass) {
+ const first = evaluation.blocked_by[0];
+ await recordCandidateDecision({
+ ...decisionBase, decision: 'blocked', check: first.check,
+ reason: evaluation.blocked_by.map((b) => b.reason).join(' '),
+ blockedBy: evaluation.blocked_by, report,
+ });
+ results.push({ mint: launch.mint, action: 'entry', status: 'skipped', code: 'research_blocked', check: first.check, blocked_by: evaluation.blocked_by, reasons: verdict.reasons });
+ continue;
+ }
+ report.evaluation = evaluation;
+ }
+
+ const idem = `strategy:${equip.id}:entry:${launch.mint}`;
+ const tradeArgs = {
+ agent, side: 'buy', mint: launch.mint, network,
+ solAmount: config.sizing.amount_sol, tokenAmountRaw: null,
+ slippageBps, idempotencyKey: idem, strategyRef, maxPriceImpactPct, preAssessment: assessment,
+ };
+
let result;
try {
- result = await runStrategyTrade({
- agent, side: 'buy', mint: launch.mint, network,
- solAmount: config.sizing.amount_sol, tokenAmountRaw: null,
- slippageBps, idempotencyKey: idem, strategyRef,
- });
+ result = await runStrategyTrade({ ...tradeArgs, dryRun: config.mode === 'ask' });
} catch (e) {
result = { status: 'failed', code: (e?.message || 'error').slice(0, 120) };
}
+ // Ask mode: the guards would allow this buy, so ask the owner instead of buying.
+ if (result.status === 'ready') {
+ const approval = await createStrategyApproval({
+ equip, agent, config, launch, network, quote: result.quote, usd: result.usd,
+ impactCap: result.impactCap, idempotencyKey: idem, report,
+ });
+ if (approval.ok) {
+ await recordCandidateDecision({
+ ...decisionBase, decision: 'approval', check: 'mode_ask',
+ reason: approval.created ? 'Ask mode: an approval request is waiting for the owner.' : 'Ask mode: already asked about this coin.',
+ report, approvalId: approval.id,
+ });
+ results.push({ mint: launch.mint, action: 'entry', status: 'approval', approval_id: approval.id, created: approval.created, reasons: verdict.reasons });
+ if (approval.created) room -= 1;
+ } else {
+ await recordCandidateDecision({
+ ...decisionBase, decision: 'failed', check: 'approval_unavailable',
+ reason: 'Ask mode could not file an approval request, so nothing was bought.', report,
+ });
+ results.push({ mint: launch.mint, action: 'entry', status: 'failed', code: 'approval_unavailable', reasons: verdict.reasons });
+ }
+ continue;
+ }
+
+ await recordCandidateDecision({
+ ...decisionBase, decision: guardDecision(result), check: result.code || (result.status === 'executed' ? 'mode_auto' : null),
+ reason: result.status === 'executed' || result.status === 'unconfirmed'
+ ? 'Auto mode: bought within the agent’s caps.'
+ : (STRATEGY_SKIP_LABELS[result.code] || result.message || result.code || 'trade did not complete'),
+ report, signature: result.signature || null,
+ });
results.push({ mint: launch.mint, action: 'entry', ...result, reasons: verdict.reasons });
// Surface a SAFETY refusal (mayhem coin, rug/honeypot firewall) on the
@@ -372,39 +528,7 @@ async function evaluateEntries({ equip, agent, launches, nowMs, maxEntries = 3 }
}
if (result.status === 'executed' || result.status === 'unconfirmed') {
- const entryLamports = result.quote ? result.quote.inAtomics : null;
- const baseAmount = result.quote ? result.quote.outAtomics : null;
- // Upsert: a fresh open position, OR revive a previously-CLOSED row for the
- // same mint (re-entry after a take-profit/stop). The WHERE guard means an
- // already-open row (another strategy) is never clobbered — the held-check
- // above already skipped this buy in that case.
- await sql`
- INSERT INTO agent_strategy_positions
- (equip_id, strategy_id, agent_id, owner_id, network, mint, symbol, name, status,
- entry_sig, entry_lamports, base_amount, entry_price_impact_pct,
- peak_value_lamports, last_value_lamports, last_quoted_at)
- VALUES (
- ${equip.id}, ${equip.strategy_id}, ${agent.id}, ${equip.owner_id}, ${network},
- ${launch.mint}, ${launch.symbol || null}, ${launch.name || null}, 'open',
- ${result.signature || null}, ${entryLamports}, ${baseAmount}, ${result.priceImpact ?? null},
- ${entryLamports}, ${entryLamports}, now()
- )
- ON CONFLICT (agent_id, mint, network) DO UPDATE SET
- equip_id = excluded.equip_id, strategy_id = excluded.strategy_id, owner_id = excluded.owner_id,
- symbol = excluded.symbol, name = excluded.name, status = 'open', exit_reason = NULL,
- entry_sig = excluded.entry_sig, entry_lamports = excluded.entry_lamports,
- base_amount = excluded.base_amount, entry_price_impact_pct = excluded.entry_price_impact_pct,
- peak_value_lamports = excluded.peak_value_lamports, last_value_lamports = excluded.last_value_lamports,
- last_quoted_at = now(), exit_sig = NULL, exit_lamports = NULL,
- realized_pnl_lamports = NULL, realized_pnl_pct = NULL, error = NULL,
- opened_at = now(), closed_at = NULL
- WHERE agent_strategy_positions.status = 'closed'
- `.catch(() => {});
- await sql`
- UPDATE agent_strategy_equips
- SET last_fired_at = now(), fires_count = fires_count + 1, last_eval_at = now(), updated_at = now()
- WHERE id = ${equip.id}
- `.catch(() => {});
+ await recordEntryPosition({ equip, agentId: agent.id, network, mint: launch.mint, symbol: launch.symbol || null, name: launch.name || null, result });
opened += 1;
room -= 1;
}
@@ -620,6 +744,172 @@ export async function closeStrategyPositionNow({ positionId, ownerId, agentId })
return { ok: false, status: 502, code: 'sell_failed', message: `the sell did not complete (${result.code || result.status}) — the position is still open` };
}
+// ── ask mode: run or refuse an approved strategy buy ──────────────────────────
+// The owner approved exactly the buy in `row.payload`. Re-check that the strategy
+// can still trade (equip active, strategy not deleted, owner kill switch off, coin
+// not already held), then run it through the SAME guarded path an auto-mode buy
+// takes, with the same idempotency key, so every cap, the price-impact breaker,
+// and the firewall apply at the moment of execution, not at the moment of asking.
+// Exported so the shared approval inbox can dispatch action_type 'strategy_buy'.
+export async function runApprovedStrategyBuy(row) {
+ const p = row.payload || {};
+ const [equip] = await sql`
+ SELECT e.id, e.strategy_id, e.agent_id, e.owner_id, e.active, e.network, s.slug, s.name AS strategy_name
+ FROM agent_strategy_equips e
+ JOIN agent_strategies s ON s.id = e.strategy_id AND s.deleted_at IS NULL
+ WHERE e.id = ${p.equip_id} AND e.agent_id = ${p.agent_id}
+ LIMIT 1
+ `;
+ if (!equip) return { status: 'failed', code: 'strategy_gone' };
+ if (!equip.active) return { status: 'failed', code: 'equip_inactive' };
+ const killed = await engagedKillOwners();
+ if (killed.has(equip.owner_id)) return { status: 'skipped', code: 'owner_kill' };
+
+ const agent = await loadAgent(p.agent_id);
+ if (!agent || agent.ownerId !== row.user_id) return { status: 'failed', code: 'agent_missing' };
+ const network = netOf(p.network);
+ const [held] = await sql`
+ SELECT 1 FROM agent_strategy_positions
+ WHERE agent_id = ${agent.id} AND mint = ${p.mint} AND network = ${network} AND status IN ('open','closing') LIMIT 1
+ `;
+ if (held) return { status: 'skipped', code: 'already_held' };
+
+ const result = await runStrategyTrade({
+ agent, side: 'buy', mint: p.mint, network,
+ solAmount: Number(p.amount_sol), tokenAmountRaw: null,
+ slippageBps: Number(p.slippage_bps), idempotencyKey: p.idempotency_key,
+ maxPriceImpactPct: p.max_price_impact_pct == null ? null : Number(p.max_price_impact_pct),
+ strategyRef: {
+ strategy_id: equip.strategy_id, equip_id: equip.id, slug: equip.slug,
+ strategy_name: equip.strategy_name, action: 'entry', approval_id: row.id,
+ },
+ });
+ if (result.status === 'executed' || result.status === 'unconfirmed') {
+ await recordEntryPosition({ equip, agentId: agent.id, network, mint: p.mint, result });
+ }
+ await recordCandidateDecision({
+ equip, agentId: agent.id, network, mint: p.mint,
+ decision: guardDecision(result), check: result.code || 'owner_approved',
+ reason: result.status === 'executed' || result.status === 'unconfirmed'
+ ? 'Approved by the owner and bought within the agent’s caps.'
+ : `Approved, but ${STRATEGY_SKIP_LABELS[result.code] || result.code || 'the trade did not complete'}.`,
+ approvalId: row.id, signature: result.signature || null,
+ });
+ return result;
+}
+
+/**
+ * The shared approval inbox's executor contract (api/_lib/approvals.js):
+ * executor(row) -> { status: 'ok'|'error'|'skipped', signature?, note?, usd? }.
+ * Approving a strategy buy from /approvals runs the same guarded path as
+ * approving it from the agent's strategy panel.
+ */
+export async function executeApprovedStrategyAction(row) {
+ const r = await runApprovedStrategyBuy(row);
+ const done = r.status === 'executed' || r.status === 'unconfirmed';
+ const label = r.code ? (STRATEGY_SKIP_LABELS[r.code] || r.code) : null;
+ return {
+ status: done ? 'ok' : r.status === 'skipped' ? 'skipped' : 'error',
+ signature: r.signature || null,
+ usd: r.usd ?? null,
+ note: done ? (r.status === 'unconfirmed' ? 'Sent; confirmation is still pending on-chain.' : 'Bought within the agent’s caps.') : `Nothing was bought: ${label || 'the trade did not complete'}.`,
+ };
+}
+
+/**
+ * Approve one strategy approval request and execute it once.
+ * The caller must echo the payload hash it showed the owner.
+ * Returns { ok, status, code?, approval } with an HTTP-ready `http` status.
+ */
+export async function approveStrategyRequest({ id, ownerId, agentId, shownHash, via = 'web' }) {
+ const [row] = await sql`
+ SELECT * FROM approval_requests
+ WHERE id = ${id} AND user_id = ${ownerId} AND agent_id = ${agentId} AND source = ${STRATEGY_APPROVAL_SOURCE}
+ LIMIT 1
+ `;
+ if (!row) return { ok: false, http: 404, code: 'not_found', message: 'approval request not found' };
+ // Already decided: a second tap (push plus web, a double click) is a no-op that
+ // reports the outcome of the first.
+ if (row.status !== 'pending') return { ok: true, http: 200, already: true, approval: publicApproval(row) };
+ if (!shownHash || shownHash !== row.payload_hash) {
+ return { ok: false, http: 409, code: 'payload_mismatch', message: 'This request changed since you opened it. Reload and review it again.' };
+ }
+ if (payloadHash(row.payload) !== row.payload_hash) {
+ await sql`UPDATE approval_requests SET status = 'failed', result = ${JSON.stringify({ code: 'payload_tampered' })}::jsonb, updated_at = now() WHERE id = ${id} AND status = 'pending'`;
+ return { ok: false, http: 409, code: 'payload_tampered', message: 'The stored request does not match its signature, so it was refused.' };
+ }
+ if (new Date(row.expires_at).getTime() <= Date.now()) {
+ await sql`UPDATE approval_requests SET status = 'expired', updated_at = now() WHERE id = ${id} AND status = 'pending'`;
+ return { ok: false, http: 410, code: 'expired', message: 'This request expired before it was approved. Nothing was bought.' };
+ }
+
+ // The single conditional step: exactly one caller moves pending -> approved.
+ const claimed = await sql`
+ UPDATE approval_requests
+ SET status = 'executing', decided_by = ${ownerId}, decided_at = now(), decided_via = ${via}, updated_at = now()
+ WHERE id = ${id} AND status = 'pending' AND expires_at > now()
+ RETURNING *
+ `;
+ if (!claimed.length) {
+ const [now] = await sql`SELECT * FROM approval_requests WHERE id = ${id}`;
+ return { ok: true, http: 200, already: true, approval: publicApproval(now) };
+ }
+
+ let result;
+ try {
+ result = await runApprovedStrategyBuy(claimed[0]);
+ } catch (e) {
+ result = { status: 'failed', code: (e?.message || 'error').slice(0, 120) };
+ }
+ const done = result.status === 'executed' || result.status === 'unconfirmed';
+ const summary = { status: result.status, code: result.code || null, label: result.code ? (STRATEGY_SKIP_LABELS[result.code] || null) : null, price_impact_pct: result.priceImpact ?? null, usd: result.usd ?? null };
+ const [final] = await sql`
+ UPDATE approval_requests
+ SET status = ${done ? 'executed' : 'failed'}, executed_at = ${done ? new Date().toISOString() : null},
+ signature = ${result.signature || null}, result = ${JSON.stringify(summary)}::jsonb, updated_at = now()
+ WHERE id = ${id}
+ RETURNING *
+ `;
+ logAudit({ userId: ownerId, action: 'strategy.approval_approved', resourceId: agentId, meta: { approval_id: id, mint: row.payload?.mint, status: result.status, code: result.code || null, signature: result.signature || null, via } });
+ return { ok: done, http: done ? 200 : 422, code: done ? null : result.code, message: done ? null : (STRATEGY_SKIP_LABELS[result.code] || 'the buy did not complete'), approval: publicApproval(final) };
+}
+
+/** Deny one pending strategy approval. Nothing is bought; the coin is not asked about again. */
+export async function denyStrategyRequest({ id, ownerId, agentId, via = 'web' }) {
+ const denied = await sql`
+ UPDATE approval_requests
+ SET status = 'denied', decided_by = ${ownerId}, decided_at = now(), decided_via = ${via}, updated_at = now()
+ WHERE id = ${id} AND user_id = ${ownerId} AND agent_id = ${agentId} AND source = ${STRATEGY_APPROVAL_SOURCE} AND status = 'pending'
+ RETURNING *
+ `;
+ if (!denied.length) {
+ const [row] = await sql`SELECT * FROM approval_requests WHERE id = ${id} AND user_id = ${ownerId} AND agent_id = ${agentId} AND source = ${STRATEGY_APPROVAL_SOURCE}`;
+ if (!row) return { ok: false, http: 404, code: 'not_found', message: 'approval request not found' };
+ return { ok: true, http: 200, already: true, approval: publicApproval(row) };
+ }
+ const row = denied[0];
+ const [equip] = await sql`SELECT id, strategy_id, owner_id FROM agent_strategy_equips WHERE id = ${row.payload?.equip_id}`.catch(() => []);
+ if (equip) {
+ await recordCandidateDecision({
+ equip, agentId, network: netOf(row.network), mint: row.payload?.mint,
+ decision: 'skipped', check: 'owner_denied', reason: 'The owner denied this buy.', approvalId: row.id,
+ });
+ }
+ logAudit({ userId: ownerId, action: 'strategy.approval_denied', resourceId: agentId, meta: { approval_id: id, mint: row.payload?.mint, via } });
+ return { ok: true, http: 200, approval: publicApproval(row) };
+}
+
+function publicApproval(row) {
+ if (!row) return null;
+ return {
+ id: row.id, status: row.status, summary: row.summary, payload: row.payload, payload_hash: row.payload_hash,
+ amount: row.amount != null ? Number(row.amount) : null, amount_usd: row.amount_usd != null ? Number(row.amount_usd) : null,
+ asset: row.asset, chain: row.chain, network: row.network, recipient: row.recipient, recipient_label: row.recipient_label,
+ risk_notes: row.risk_notes || [], expires_at: row.expires_at, decided_at: row.decided_at,
+ executed_at: row.executed_at, signature: row.signature, result: row.result, created_at: row.created_at,
+ };
+}
+
// ── public: evaluate one equip (exits first, then entries) ────────────────────
export async function evaluateEquip(equip, { launches = null, nowMs = null, killed = false, maxEntries = 3 } = {}) {
const now = nowMs ?? Date.now();
@@ -683,7 +973,7 @@ export async function sweepStrategies({ network = 'mainnet', maxEquips = 200, ma
const killed = await engagedKillOwners();
const launches = net === 'mainnet' ? await recentPumpLaunches({ network: net, limit: 50 }).catch(() => []) : [];
- const stats = { executed: 0, skipped: 0, failed: 0, unconfirmed: 0, closed: 0 };
+ const stats = { executed: 0, skipped: 0, failed: 0, unconfirmed: 0, closed: 0, approval: 0 };
let evaluated = 0;
for (const equip of equips) {
try {
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.js
index fb36234a6..558787973 100644
--- a/api/_lib/agent-trade-guards.js
+++ b/api/_lib/agent-trade-guards.js
@@ -749,7 +749,7 @@ export async function getCounterpartySpendUsd(
* the `counterparty_seen_before` signal ("only pay services you've used before").
* Best-effort: any error reports "not seen", and the rule itself decides what that
* means (a `is false` rule then fires — fail-safe-to-block for that intent). */
-async function countPriorSpendsTo(agentId, destination, network = 'mainnet') {
+export async function countPriorSpendsTo(agentId, destination, network = 'mainnet') {
if (!destination) return 0;
const [row] = await sql`
SELECT COUNT(*)::int AS n
@@ -806,7 +806,7 @@ async function freezeWalletFromPolicy(agentId, userId, rule, network) {
* @param {string} [o.network]
* @throws {SpendLimitError} when the policy denies the spend
*/
-async function enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits, policyContext = {}, userId, network = 'mainnet' }) {
+async function enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits, policyContext = {}, userId, network = 'mainnet', stepUpApproved = false }) {
if (!policy || !Array.isArray(policy.rules) || !policy.rules.length) return;
const autonomous = category !== 'withdraw';
@@ -847,6 +847,10 @@ async function enforcePolicyRules({ agentId, policy, category, usdValue, asset,
const verdict = evaluatePolicy(policy, ctx);
if (!isDenied(verdict.decision)) return;
+ // The owner already answered this step-up in the approval inbox
+ // (api/_lib/approvals.js). Only the "ask me" verdict is lifted: a block or a
+ // freeze rule still stops the spend, and every numeric cap below still runs.
+ if (verdict.decision === 'step_up' && stepUpApproved) return;
// Audit: every block records which rule fired (deliverable). A 'failed' spend
// row is excluded from the daily-cap sum and the backtest history, so it never
@@ -1030,6 +1034,7 @@ export async function enforceSpendLimit({
ownerInitiated,
now,
network = 'mainnet',
+ stepUpApproved = false,
}) {
// Fail closed: a caller that named neither the limits nor the meta gets the
// agent's REAL policy read from the row, never an empty default policy.
@@ -1067,7 +1072,7 @@ export async function enforceSpendLimit({
// must pass `policyRules` to opt the path in; the autonomous trade/snipe/x402/
// withdraw paths all do (or pass `meta`).
const policy = policyRules || (meta ? getPolicyRules(meta) : null);
- await enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits: lim, policyContext, userId, network });
+ await enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits: lim, policyContext, userId, network, stepUpApproved });
const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;
diff --git a/api/_lib/approvals.js b/api/_lib/approvals.js
new file mode 100644
index 000000000..508b0e8b7
--- /dev/null
+++ b/api/_lib/approvals.js
@@ -0,0 +1,720 @@
+// Approval inbox: the queue every gated agent action waits in for its owner's yes.
+//
+// A gated action (a spend the owner's policy marked "needs my approval", and
+// later anything a team member wants to do above its mandate) becomes one
+// approval_requests row holding the EXACT action to run as canonical JSON plus
+// its sha256. Every surface (the /approvals page, a push notification's Approve
+// button, Telegram, the iOS app, the email fallback) renders the same
+// confirmation table from that row: recipient, amount, asset, chain, and the
+// risk notes. Approving:
+//
+// 1. requires the payload hash the owner was shown, so a screen that went
+// stale (or a link someone edited) can never approve a different action;
+// 2. flips pending -> approved in ONE conditional UPDATE that also checks the
+// expiry, so a double tap, a push tap racing a web click, or an approval
+// after the deadline cannot execute twice or late;
+// 3. recomputes the hash from the stored payload before the executor runs,
+// so an edited row fails closed instead of executing;
+// 4. runs the executor registered for the request's source, which signs
+// through the same spend-policy-gated custody path the action would have
+// used unattended. The executor never widens anything: only the step-up
+// the owner just answered is lifted, every numeric cap still applies.
+//
+// Deny and expiry are terminal and fail closed. Auto-approve policies are the
+// owner's explicit, revocable "don't ask me for this", capped by size and venue;
+// with none, every gated action asks. Transfers to an address the wallet has
+// never paid are never auto-approved.
+//
+// Schema: api/_lib/migrations/20261010120000_approval_requests.sql
+// Doc: docs/approvals.md
+
+import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
+import { sql } from './db.js';
+import { env } from './env.js';
+import { logAudit } from './audit.js';
+
+export const APPROVAL_STATUSES = Object.freeze(['pending', 'approved', 'executing', 'executed', 'failed', 'denied', 'expired']);
+export const DECISIONS = Object.freeze(['approve', 'deny']);
+export const DECISION_VIAS = Object.freeze(['web', 'push', 'telegram', 'mobile', 'email']);
+
+// Status groups the inbox filters by.
+export const STATUS_GROUPS = Object.freeze({
+ pending: ['pending'],
+ done: ['approved', 'executing', 'executed', 'failed'],
+ denied: ['denied'],
+ expired: ['expired'],
+});
+
+// Venues an auto-approve policy can name. A venue is where the money goes, so a
+// policy for swaps never silently covers transfers.
+export const VENUES = Object.freeze({
+ jupiter: { label: 'Token swaps (Jupiter)', auto: true },
+ wallet_transfer: { label: 'Transfers to addresses this wallet has paid before', auto: true },
+});
+
+// Ceiling on a single auto-approve policy. Anything bigger is a decision the
+// owner should make each time.
+export const AUTO_POLICY_MAX_USD = 1000;
+
+// How long a request stays answerable. Prices move fast, so a swap waits
+// minutes; a transfer's amount is fixed in SOL, so it can wait hours.
+export const TTL_MS = Object.freeze({ swap: 15 * 60 * 1000, transfer: 6 * 60 * 60 * 1000 });
+
+const TERMINAL = new Set(['executed', 'failed', 'denied', 'expired']);
+const APPROVED_FAMILY = new Set(['approved', 'executing', 'executed', 'failed']);
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export class ApprovalError extends Error {
+ constructor(status, code, message, extra = {}) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ this.extra = extra;
+ }
+}
+
+export function isUuid(v) {
+ return typeof v === 'string' && UUID_RE.test(v);
+}
+
+// ── canonical payload + hash ────────────────────────────────────────────────────
+
+/**
+ * Deterministic JSON: object keys sorted at every depth, undefined dropped. The
+ * payload round-trips through Postgres jsonb (which reorders keys), so the hash
+ * has to be order-independent to be recomputable from the stored row.
+ */
+export function canonicalJson(value) {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);
+ if (Array.isArray(value)) return `[${value.map((v) => canonicalJson(v === undefined ? null : v)).join(',')}]`;
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
+}
+
+export function payloadHash(payload) {
+ return createHash('sha256').update(canonicalJson(payload)).digest('hex');
+}
+
+// ── signed deep links ───────────────────────────────────────────────────────────
+// Every delivery carries /approvals/<id>?t=<token>. The token binds the request
+// id, its owner, the payload hash and the request's expiry under JWT_SECRET, so
+// the page can prove the action it renders is the one that was sent, and an
+// approval arriving through a link is rejected if the row no longer matches it.
+
+function linkSign(body) {
+ return createHmac('sha256', env.JWT_SECRET).update(`approval-link:${body}`).digest('base64url');
+}
+
+export function signApprovalLink({ id, userId, hash, expiresAt }) {
+ const exp = Math.floor(new Date(expiresAt).getTime() / 1000);
+ const body = Buffer.from(JSON.stringify({ i: id, u: String(userId), h: hash, e: exp }), 'utf8').toString('base64url');
+ return `a1.${body}.${linkSign(body)}`;
+}
+
+/** @returns {{ ok: true } | { ok: false, reason: string }} */
+export function verifyApprovalLink(token, { id, userId, hash, now = Date.now() }) {
+ if (typeof token !== 'string' || !token.startsWith('a1.')) return { ok: false, reason: 'malformed' };
+ const parts = token.split('.');
+ if (parts.length !== 3 || !parts[1] || !parts[2]) return { ok: false, reason: 'malformed' };
+ const expected = Buffer.from(linkSign(parts[1]), 'utf8');
+ const actual = Buffer.from(parts[2], 'utf8');
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return { ok: false, reason: 'bad_signature' };
+ let claims;
+ try {
+ claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
+ } catch {
+ return { ok: false, reason: 'malformed' };
+ }
+ if (claims.i !== id || claims.u !== String(userId)) return { ok: false, reason: 'wrong_request' };
+ if (claims.h !== hash) return { ok: false, reason: 'payload_changed' };
+ if (!Number.isFinite(claims.e) || claims.e * 1000 <= now) return { ok: false, reason: 'expired' };
+ return { ok: true };
+}
+
+export function approvalPath(row) {
+ const token = signApprovalLink({ id: row.id, userId: row.user_id, hash: row.payload_hash, expiresAt: row.expires_at });
+ return `/approvals/${row.id}?t=${encodeURIComponent(token)}`;
+}
+
+// ── rendering: the confirmation table every surface shows ───────────────────────
+
+function shortAddr(a) {
+ const s = String(a || '');
+ return s.length > 12 ? `${s.slice(0, 4)}...${s.slice(-4)}` : s;
+}
+
+function fmtAmount(amount, asset) {
+ const n = Number(amount);
+ if (!Number.isFinite(n)) return '';
+ const digits = n >= 1 ? 4 : 6;
+ return `${n.toLocaleString('en-US', { maximumFractionDigits: digits })}${asset ? ` ${asset}` : ''}`;
+}
+
+export function chainLabel(chain, network) {
+ const c = String(chain || 'solana');
+ const name = c.charAt(0).toUpperCase() + c.slice(1);
+ return network && network !== 'mainnet' ? `${name} ${network}` : name;
+}
+
+/**
+ * The CLAUDE.md confirmation table for one request, as ordered rows. Rendered
+ * identically by the page, the email and the chat text.
+ */
+export function confirmationTable(row) {
+ const usd = row.amount_usd != null && Number.isFinite(Number(row.amount_usd)) ? ` (~$${Number(row.amount_usd).toFixed(2)})` : '';
+ return [
+ { key: 'recipient', label: 'Recipient', value: row.recipient_label ? `${row.recipient_label} (${shortAddr(row.recipient)})` : (row.recipient || 'n/a'), full: row.recipient || null },
+ { key: 'amount', label: 'Amount', value: `${fmtAmount(row.amount, row.asset)}${usd}` },
+ { key: 'asset', label: 'Asset', value: row.asset || 'n/a' },
+ { key: 'chain', label: 'Chain', value: chainLabel(row.chain, row.network) },
+ ];
+}
+
+/** One plain-text block for chat surfaces and the email text part. */
+export function confirmationText(row) {
+ return confirmationTable(row).map((r) => `${r.label}: ${r.value}`).join('\n');
+}
+
+function explorerUrl(signature, network) {
+ if (!signature) return null;
+ const cluster = network && network !== 'mainnet' ? `?cluster=${encodeURIComponent(network)}` : '';
+ return `https://solscan.io/tx/${encodeURIComponent(signature)}${cluster}`;
+}
+
+/** Effective status: a pending row past its deadline reads as expired even before the sweep writes it. */
+export function effectiveStatus(row, now = Date.now()) {
+ if (row.status === 'pending' && new Date(row.expires_at).getTime() <= now) return 'expired';
+ return row.status;
+}
+
+/** The API shape of one request. */
+export function publicApproval(row, { now = Date.now(), withLink = true } = {}) {
+ const status = effectiveStatus(row, now);
+ return {
+ id: row.id,
+ status,
+ summary: row.summary,
+ agent: row.agent_id ? { id: row.agent_id, name: row.agent_name || null } : null,
+ team_id: row.team_id || null,
+ requester_role: row.requester_role,
+ source: row.source,
+ action_type: row.action_type,
+ venue: row.venue,
+ venue_label: VENUES[row.venue]?.label || row.venue,
+ confirmation: confirmationTable(row),
+ risk_notes: Array.isArray(row.risk_notes) ? row.risk_notes : [],
+ gate_reason: row.gate_reason || null,
+ amount: row.amount != null ? Number(row.amount) : null,
+ amount_usd: row.amount_usd != null ? Number(row.amount_usd) : null,
+ asset: row.asset,
+ chain: row.chain,
+ network: row.network,
+ recipient: row.recipient,
+ recipient_label: row.recipient_label || null,
+ payload_hash: row.payload_hash,
+ expires_at: row.expires_at,
+ created_at: row.created_at,
+ decided_at: row.decided_at || null,
+ decided_via: row.decided_via || null,
+ auto_policy_id: row.auto_policy_id || null,
+ executed_at: row.executed_at || null,
+ signature: row.signature || null,
+ explorer: explorerUrl(row.signature, row.network),
+ result: row.result || null,
+ link: withLink && status === 'pending' ? approvalPath(row) : `/approvals/${row.id}`,
+ };
+}
+
+// ── executors ───────────────────────────────────────────────────────────────────
+// One per source. Lazy imports keep this module free of Solana/web3 weight and
+// break the cycle with the engines that create requests.
+//
+// Contract: executor(row) -> { status: 'ok'|'error'|'paused'|'skipped', signature?, note?, usd? }.
+// It receives the stored row and must execute ONLY row.payload.
+
+const EXECUTORS = {
+ wallet_intent: async () => (await import('./wallet-intents.js')).executeApprovedIntentAction,
+ strategy: async () => (await import('./agent-strategy-runtime.js')).executeApprovedStrategyAction,
+};
+
+export function hasExecutor(source) {
+ return Object.prototype.hasOwnProperty.call(EXECUTORS, source);
+}
+
+// ── auto-approve policies ───────────────────────────────────────────────────────
+
+/**
+ * The cheapest live policy that covers this request, or null. Never matches a
+ * request that is not auto-approvable (a first transfer to a new address), an
+ * unknown USD value, or a venue the policy does not name.
+ */
+export async function matchAutoPolicy({ userId, agentId = null, teamId = null, venue, amountUsd, autoApprovable = true }) {
+ if (!autoApprovable || !VENUES[venue]?.auto) return null;
+ // Number(null) is 0, which would slip under every cap: an unpriced action asks.
+ if (amountUsd == null || amountUsd === '') return null;
+ const usd = Number(amountUsd);
+ if (!Number.isFinite(usd) || usd < 0) return null;
+ const [row] = await sql`
+ SELECT * FROM approval_auto_policies
+ WHERE user_id = ${userId}
+ AND revoked_at IS NULL
+ AND (expires_at IS NULL OR expires_at > now())
+ AND ${venue} = ANY(venues)
+ AND max_usd >= ${usd}
+ AND (agent_id IS NULL OR agent_id = ${agentId})
+ AND (team_id IS NULL OR team_id = ${teamId})
+ ORDER BY max_usd ASC, created_at ASC
+ LIMIT 1
+ `;
+ return row || null;
+}
+
+function publicPolicy(row, now = Date.now()) {
+ const expired = row.expires_at && new Date(row.expires_at).getTime() <= now;
+ return {
+ id: row.id,
+ label: row.label,
+ agent: row.agent_id ? { id: row.agent_id, name: row.agent_name || null } : null,
+ team_id: row.team_id || null,
+ venues: row.venues,
+ max_usd: Number(row.max_usd),
+ expires_at: row.expires_at || null,
+ revoked_at: row.revoked_at || null,
+ created_at: row.created_at,
+ active: !row.revoked_at && !expired,
+ };
+}
+
+export async function listAutoPolicies(userId) {
+ const rows = await sql`
+ SELECT p.*, a.name AS agent_name
+ FROM approval_auto_policies p
+ LEFT JOIN agent_identities a ON a.id = p.agent_id
+ WHERE p.user_id = ${userId}
+ ORDER BY (p.revoked_at IS NULL) DESC, p.created_at DESC
+ LIMIT 100
+ `;
+ return rows.map((r) => publicPolicy(r));
+}
+
+export async function createAutoPolicy(userId, input, { req = null } = {}) {
+ const venues = [...new Set(Array.isArray(input.venues) ? input.venues : [])];
+ if (!venues.length || venues.some((v) => !VENUES[v]?.auto)) {
+ throw new ApprovalError(400, 'invalid_venue', `venues must be one or more of: ${Object.keys(VENUES).join(', ')}`);
+ }
+ const maxUsd = Number(input.max_usd);
+ if (!Number.isFinite(maxUsd) || maxUsd <= 0 || maxUsd > AUTO_POLICY_MAX_USD) {
+ throw new ApprovalError(400, 'invalid_max_usd', `max_usd must be above 0 and at most ${AUTO_POLICY_MAX_USD}`);
+ }
+ const agentId = input.agent_id || null;
+ if (agentId) {
+ if (!isUuid(agentId)) throw new ApprovalError(400, 'invalid_agent', 'agent_id must be a uuid');
+ const [own] = await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL`;
+ if (!own) throw new ApprovalError(404, 'agent_not_found', 'You do not own that agent.');
+ }
+ const teamId = input.team_id ? String(input.team_id).slice(0, 80) : null;
+ let expiresAt = null;
+ if (input.expires_at) {
+ const t = new Date(input.expires_at);
+ if (Number.isNaN(t.getTime()) || t.getTime() <= Date.now()) throw new ApprovalError(400, 'invalid_expiry', 'expires_at must be a future date');
+ expiresAt = t.toISOString();
+ }
+ const label = String(input.label || '').trim().slice(0, 120)
+ || `Auto-approve ${venues.map((v) => VENUES[v].label.toLowerCase()).join(' and ')} up to $${maxUsd}`;
+ const [row] = await sql`
+ INSERT INTO approval_auto_policies (user_id, agent_id, team_id, label, venues, max_usd, expires_at)
+ VALUES (${userId}, ${agentId}, ${teamId}, ${label}, ${venues}, ${maxUsd}, ${expiresAt})
+ RETURNING *
+ `;
+ logAudit({ userId, action: 'approval_policy_created', resourceId: row.id, meta: { venues, max_usd: maxUsd, agent_id: agentId, team_id: teamId }, req });
+ return publicPolicy(row);
+}
+
+export async function revokeAutoPolicy(userId, policyId, { req = null } = {}) {
+ if (!isUuid(policyId)) throw new ApprovalError(400, 'invalid_id', 'policy id must be a uuid');
+ const [row] = await sql`
+ UPDATE approval_auto_policies SET revoked_at = now()
+ WHERE id = ${policyId} AND user_id = ${userId} AND revoked_at IS NULL
+ RETURNING *
+ `;
+ if (!row) {
+ const [existing] = await sql`SELECT * FROM approval_auto_policies WHERE id = ${policyId} AND user_id = ${userId}`;
+ if (!existing) throw new ApprovalError(404, 'not_found', 'No such auto-approve policy.');
+ return publicPolicy(existing);
+ }
+ logAudit({ userId, action: 'approval_policy_revoked', resourceId: row.id, meta: { venues: row.venues, max_usd: Number(row.max_usd) }, req });
+ return publicPolicy(row);
+}
+
+// ── create + deliver ────────────────────────────────────────────────────────────
+
+/**
+ * Queue a gated action for its owner. Idempotent on `idempotencyKey`, and at
+ * most one pending request per (source, sourceRef): a rule that keeps firing
+ * while the owner has not answered waits on the request already in the inbox.
+ *
+ * Returns { request, created, autoApproved, policy }. When autoApproved is true
+ * the row is already `approved` by a policy and the CALLER executes it inline
+ * through runApproved, which records the outcome.
+ */
+export async function createApprovalRequest({
+ userId,
+ agentId = null,
+ teamId = null,
+ requesterRole = 'agent',
+ source,
+ sourceRef = null,
+ actionType,
+ venue,
+ payload,
+ summary,
+ amount = null,
+ amountUsd = null,
+ asset = null,
+ chain = 'solana',
+ network = 'mainnet',
+ recipient = null,
+ recipientLabel = null,
+ riskNotes = [],
+ gateReason = null,
+ idempotencyKey,
+ ttlMs = TTL_MS.transfer,
+ autoApprovable = true,
+ deliver = true,
+}) {
+ if (!userId) throw new ApprovalError(400, 'no_owner', 'An approval request needs an owner to ask.');
+ if (!hasExecutor(source)) throw new ApprovalError(400, 'unknown_source', `No executor is registered for source "${source}".`);
+ if (!VENUES[venue]) throw new ApprovalError(400, 'invalid_venue', `Unknown venue "${venue}".`);
+ if (!idempotencyKey) throw new ApprovalError(400, 'no_idempotency_key', 'idempotencyKey is required');
+
+ if (sourceRef) {
+ const [open] = await sql`
+ SELECT * FROM approval_requests
+ WHERE source = ${source} AND source_ref = ${sourceRef} AND user_id = ${userId}
+ AND status = 'pending' AND expires_at > now()
+ ORDER BY created_at DESC LIMIT 1
+ `;
+ if (open) return { request: open, created: false, autoApproved: false, policy: null };
+ }
+
+ const hash = payloadHash(payload);
+ const policy = await matchAutoPolicy({ userId, agentId, teamId, venue, amountUsd, autoApprovable });
+ const expiresAt = new Date(Date.now() + Math.max(60_000, Number(ttlMs) || TTL_MS.transfer)).toISOString();
+ const notes = (Array.isArray(riskNotes) ? riskNotes : []).filter(Boolean).slice(0, 12).map((n) => String(n).slice(0, 280));
+
+ const [row] = await sql`
+ INSERT INTO approval_requests (
+ user_id, agent_id, team_id, requester_role, source, source_ref, action_type, venue,
+ payload, payload_hash, summary, amount, amount_usd, asset, chain, network,
+ recipient, recipient_label, risk_notes, gate_reason, idempotency_key, status, expires_at,
+ decided_at, decided_via, auto_policy_id
+ ) VALUES (
+ ${userId}, ${agentId}, ${teamId}, ${String(requesterRole).slice(0, 40)}, ${source}, ${sourceRef}, ${actionType}, ${venue},
+ ${JSON.stringify(payload)}::jsonb, ${hash}, ${String(summary).slice(0, 400)}, ${amount}, ${amountUsd}, ${asset}, ${chain}, ${network},
+ ${recipient}, ${recipientLabel ? String(recipientLabel).slice(0, 80) : null}, ${JSON.stringify(notes)}::jsonb,
+ ${gateReason ? String(gateReason).slice(0, 400) : null}, ${idempotencyKey}, ${policy ? 'approved' : 'pending'}, ${expiresAt},
+ ${policy ? new Date().toISOString() : null}, ${policy ? 'auto_policy' : null}, ${policy ? policy.id : null}
+ )
+ ON CONFLICT (idempotency_key) DO NOTHING
+ RETURNING *
+ `;
+ if (!row) {
+ const [existing] = await sql`SELECT * FROM approval_requests WHERE idempotency_key = ${idempotencyKey}`;
+ return { request: existing, created: false, autoApproved: false, policy: null };
+ }
+
+ if (policy) {
+ logAudit({ userId, action: 'approval_auto_approved', resourceId: row.id, meta: { policy_id: policy.id, venue, amount_usd: amountUsd, summary: row.summary } });
+ return { request: row, created: true, autoApproved: true, policy };
+ }
+
+ logAudit({ userId, action: 'approval_requested', resourceId: row.id, meta: { source, action_type: actionType, venue, amount_usd: amountUsd, summary: row.summary } });
+ if (deliver) await deliverApproval(row).catch((e) => console.warn('[approvals] delivery failed', e?.message));
+ return { request: row, created: true, autoApproved: false, policy: null };
+}
+
+/**
+ * Fan the request out: bell, web push (with Approve/Deny actions), the iOS app,
+ * paired Telegram/Discord chats, all through insertNotification, then email
+ * when none of the out-of-app channels reached the owner.
+ */
+export async function deliverApproval(row) {
+ const { insertNotification, emailAllowedForType } = await import('./notify.js');
+ const [agent] = row.agent_id ? await sql`SELECT name FROM agent_identities WHERE id = ${row.agent_id}` : [null];
+ const link = approvalPath(row);
+ const token = new URL(link, 'https://x').searchParams.get('t');
+ const out = await insertNotification(row.user_id, 'approval_requested', {
+ approval_id: row.id,
+ agent_id: row.agent_id,
+ agent_name: agent?.name || null,
+ summary: row.summary,
+ confirmation: confirmationText(row),
+ payload_hash: row.payload_hash,
+ link_token: token,
+ link,
+ amount_usd: row.amount_usd != null ? Number(row.amount_usd) : null,
+ expires_at: row.expires_at,
+ });
+ const reached = out?.delivered || {};
+ const outOfApp = (reached.push || 0) + (reached.telegram || 0) + (reached.discord || 0);
+ if (outOfApp > 0) return { ...reached, email: 0 };
+ if (!(await emailAllowedForType(row.user_id, 'approval_requested'))) return { ...reached, email: 0 };
+ const [u] = await sql`SELECT email FROM users WHERE id = ${row.user_id}`;
+ if (!u?.email) return { ...reached, email: 0 };
+ const { sendApprovalRequestEmail } = await import('./email.js');
+ const sent = await sendApprovalRequestEmail({
+ to: u.email,
+ agentName: agent?.name || null,
+ summary: row.summary,
+ table: confirmationTable(row),
+ riskNotes: Array.isArray(row.risk_notes) ? row.risk_notes : [],
+ link,
+ expiresAt: row.expires_at,
+ }).catch((e) => ({ error: e?.message }));
+ return { ...reached, email: sent && !sent.skipped && !sent.error ? 1 : 0 };
+}
+
+// ── read ────────────────────────────────────────────────────────────────────────
+
+/** Write `expired` onto every pending row past its deadline. Returns how many. */
+export async function expireStale(userId = null) {
+ const rows = userId
+ ? await sql`UPDATE approval_requests SET status = 'expired', updated_at = now()
+ WHERE user_id = ${userId} AND status = 'pending' AND expires_at <= now() RETURNING id`
+ : await sql`UPDATE approval_requests SET status = 'expired', updated_at = now()
+ WHERE status = 'pending' AND expires_at <= now() RETURNING id`;
+ return rows.length;
+}
+
+function encodeCursor(createdAt, id) {
+ return Buffer.from(`${new Date(createdAt).toISOString()}|${id}`, 'utf8').toString('base64url');
+}
+
+function decodeCursor(cursor) {
+ if (!cursor) return null;
+ try {
+ const [iso, id] = Buffer.from(String(cursor), 'base64url').toString('utf8').split('|');
+ if (!iso || Number.isNaN(Date.parse(iso)) || !isUuid(id)) return null;
+ return { iso, id };
+ } catch {
+ return null;
+ }
+}
+
+export async function listApprovals(userId, { group = 'pending', agentId = null, limit = 30, cursor = null } = {}) {
+ await expireStale(userId);
+ const statuses = group === 'all' ? APPROVAL_STATUSES : STATUS_GROUPS[group];
+ if (!statuses) throw new ApprovalError(400, 'invalid_status', `status must be one of: ${[...Object.keys(STATUS_GROUPS), 'all'].join(', ')}`);
+ if (agentId && !isUuid(agentId)) throw new ApprovalError(400, 'invalid_agent', 'agent must be a uuid');
+ const lim = Math.min(100, Math.max(1, Number(limit) || 30));
+ const cur = decodeCursor(cursor);
+ const rows = await sql`
+ SELECT r.*, a.name AS agent_name
+ FROM approval_requests r
+ LEFT JOIN agent_identities a ON a.id = r.agent_id
+ WHERE r.user_id = ${userId}
+ AND r.status = ANY(${statuses})
+ AND (${agentId}::uuid IS NULL OR r.agent_id = ${agentId}::uuid)
+ AND (${cur ? cur.iso : null}::timestamptz IS NULL OR (r.created_at, r.id) < (${cur ? cur.iso : null}::timestamptz, ${cur ? cur.id : null}::uuid))
+ ORDER BY r.created_at DESC, r.id DESC
+ LIMIT ${lim + 1}
+ `;
+ const page = rows.slice(0, lim);
+ const last = page[page.length - 1];
+ const counts = await sql`
+ SELECT status, count(*)::int AS n FROM approval_requests
+ WHERE user_id = ${userId} GROUP BY status
+ `;
+ const byStatus = Object.fromEntries(counts.map((c) => [c.status, c.n]));
+ const tally = Object.fromEntries(Object.entries(STATUS_GROUPS).map(([g, ss]) => [g, ss.reduce((s, x) => s + (byStatus[x] || 0), 0)]));
+ tally.all = Object.values(byStatus).reduce((s, n) => s + n, 0);
+ const agents = await sql`
+ SELECT DISTINCT r.agent_id AS id, a.name
+ FROM approval_requests r JOIN agent_identities a ON a.id = r.agent_id
+ WHERE r.user_id = ${userId}
+ ORDER BY a.name
+ LIMIT 100
+ `;
+ return {
+ items: page.map((r) => publicApproval(r)),
+ next_cursor: rows.length > lim && last ? encodeCursor(last.created_at, last.id) : null,
+ counts: tally,
+ agents: agents.map((a) => ({ id: a.id, name: a.name })),
+ };
+}
+
+async function loadRow(userId, id) {
+ if (!isUuid(id)) throw new ApprovalError(400, 'invalid_id', 'approval id must be a uuid');
+ const [row] = await sql`
+ SELECT r.*, a.name AS agent_name
+ FROM approval_requests r
+ LEFT JOIN agent_identities a ON a.id = r.agent_id
+ WHERE r.id = ${id} AND r.user_id = ${userId}
+ `;
+ if (!row) throw new ApprovalError(404, 'not_found', 'No such approval request on your account.');
+ return row;
+}
+
+export async function getApproval(userId, id, { token = null } = {}) {
+ const row = await loadRow(userId, id);
+ const out = publicApproval(row);
+ if (token) {
+ const v = verifyApprovalLink(token, { id: row.id, userId: row.user_id, hash: row.payload_hash });
+ out.link_verified = v.ok;
+ if (!v.ok) out.link_problem = v.reason;
+ }
+ return out;
+}
+
+// ── decide ──────────────────────────────────────────────────────────────────────
+
+/**
+ * Approve or deny one request.
+ *
+ * Approve requires `payloadHash` (what the owner was shown). A repeat approve of
+ * a request that is already approved, executing or done returns its current
+ * state with `idempotent: true` and never runs the executor again.
+ *
+ * @returns {Promise<{ request: object, idempotent: boolean }>}
+ */
+export async function decideApproval({ userId, id, decision, payloadHash: shownHash = null, token = null, via = 'web', req = null }) {
+ if (!DECISIONS.includes(decision)) throw new ApprovalError(400, 'invalid_decision', 'decision must be "approve" or "deny"');
+ const channel = DECISION_VIAS.includes(via) ? via : 'web';
+ const row = await loadRow(userId, id);
+
+ if (token) {
+ const v = verifyApprovalLink(token, { id: row.id, userId: row.user_id, hash: row.payload_hash });
+ if (!v.ok && v.reason !== 'expired') {
+ throw new ApprovalError(409, 'link_mismatch', 'This approval link does not match the request on file, so nothing was executed. Open /approvals to review it.', { reason: v.reason });
+ }
+ }
+
+ if (decision === 'deny') return deny(row, { userId, via: channel, req });
+ return approve(row, { userId, shownHash, via: channel, req });
+}
+
+async function deny(row, { userId, via, req }) {
+ const [updated] = await sql`
+ UPDATE approval_requests
+ SET status = 'denied', decided_by = ${userId}, decided_at = now(), decided_via = ${via}, updated_at = now()
+ WHERE id = ${row.id} AND user_id = ${userId} AND status = 'pending'
+ RETURNING *
+ `;
+ if (updated) {
+ logAudit({ userId, action: 'approval_denied', resourceId: row.id, meta: { via, summary: row.summary }, req });
+ return { request: publicApproval({ ...updated, agent_name: row.agent_name }), idempotent: false };
+ }
+ const current = await loadRow(userId, row.id);
+ if (current.status === 'denied' || current.status === 'expired') return { request: publicApproval(current), idempotent: true };
+ throw new ApprovalError(409, 'already_decided', `This request was already ${current.status}; it can no longer be denied.`, { status: current.status });
+}
+
+async function approve(row, { userId, shownHash, via, req }) {
+ if (typeof shownHash !== 'string' || !/^[0-9a-f]{64}$/.test(shownHash)) {
+ throw new ApprovalError(400, 'payload_hash_required', 'Approving needs the payload_hash of the action you were shown.');
+ }
+ if (shownHash !== row.payload_hash) {
+ throw new ApprovalError(409, 'payload_mismatch', 'The action on file differs from the one you approved, so nothing was executed. Reload and review it again.');
+ }
+
+ const [claimed] = await sql`
+ UPDATE approval_requests
+ SET status = 'approved', decided_by = ${userId}, decided_at = now(), decided_via = ${via}, updated_at = now()
+ WHERE id = ${row.id} AND user_id = ${userId} AND status = 'pending'
+ AND expires_at > now() AND payload_hash = ${shownHash}
+ RETURNING *
+ `;
+ if (!claimed) {
+ const current = await loadRow(userId, row.id);
+ if (APPROVED_FAMILY.has(current.status)) return { request: publicApproval(current), idempotent: true };
+ if (current.status === 'denied') throw new ApprovalError(409, 'already_denied', 'This request was denied; it can no longer be approved.');
+ if (current.status === 'pending' || current.status === 'expired') {
+ await sql`UPDATE approval_requests SET status = 'expired', updated_at = now() WHERE id = ${row.id} AND status = 'pending'`;
+ throw new ApprovalError(410, 'expired', 'This request expired before it was approved, so nothing was executed. The agent will ask again if the action is still wanted.');
+ }
+ throw new ApprovalError(409, 'not_pending', `This request is ${current.status}.`);
+ }
+
+ logAudit({ userId, action: 'approval_approved', resourceId: row.id, meta: { via, summary: row.summary, payload_hash: shownHash }, req });
+ const done = await executeApproved({ ...claimed, agent_name: row.agent_name }, { userId, req });
+ return { request: done, idempotent: false };
+}
+
+/**
+ * Run an approved row exactly once through `run(claimedRow)`. The approved ->
+ * executing step is a conditional UPDATE, so a second caller finds nothing to
+ * claim and gets `outcome: null`. The payload is re-hashed first: a row whose
+ * payload no longer matches its hash never runs.
+ *
+ * Engines that hold an auto-approved request call this with their own inline
+ * runner; the inbox calls it (via executeApproved) with the source's executor.
+ *
+ * @returns {Promise<{ request: object, outcome: object|null }>}
+ */
+export async function runApproved(row, run, { userId = row.user_id, req = null } = {}) {
+ const [claim] = await sql`
+ UPDATE approval_requests SET status = 'executing', updated_at = now()
+ WHERE id = ${row.id} AND status = 'approved'
+ RETURNING *
+ `;
+ if (!claim) return { request: publicApproval(await loadRow(row.user_id, row.id)), outcome: null };
+
+ let outcome;
+ if (payloadHash(claim.payload) !== claim.payload_hash) {
+ outcome = { status: 'error', note: 'The stored action no longer matches what was approved. Nothing was executed.', integrity: false };
+ } else {
+ try {
+ outcome = await run(claim);
+ } catch (e) {
+ outcome = { status: 'error', note: (e?.message || 'execution failed').slice(0, 240) };
+ }
+ }
+ const request = await recordApprovalOutcome(claim.id, outcome, { userId, req });
+ return { request, outcome };
+}
+
+/** Run an approved row through its source's registered executor, once. */
+export async function executeApproved(row, opts = {}) {
+ const { request } = await runApproved(row, async (claim) => (await EXECUTORS[claim.source]())(claim), opts);
+ return request;
+}
+
+/** Finalize a request with its executor's outcome. Returns the public shape. */
+export async function recordApprovalOutcome(id, outcome, { userId = null, req = null } = {}) {
+ const ok = outcome?.status === 'ok';
+ const status = ok ? 'executed' : 'failed';
+ const result = {
+ status: outcome?.status || 'error',
+ note: outcome?.note ? String(outcome.note).slice(0, 280) : null,
+ usd: Number.isFinite(Number(outcome?.usd)) ? Number(outcome.usd) : null,
+ ...(outcome?.integrity === false ? { integrity: false } : {}),
+ };
+ const [row] = await sql`
+ UPDATE approval_requests
+ SET status = ${status}, executed_at = ${ok ? new Date().toISOString() : null},
+ signature = ${outcome?.signature || null}, result = ${JSON.stringify(result)}::jsonb, updated_at = now()
+ WHERE id = ${id}
+ RETURNING *
+ `;
+ if (!row) return null;
+ logAudit({ userId: userId || row.user_id, action: ok ? 'approval_executed' : 'approval_failed', resourceId: id, meta: { signature: row.signature, note: result.note, via: row.decided_via }, req });
+ const [named] = await sql`SELECT name FROM agent_identities WHERE id = ${row.agent_id}`;
+ return publicApproval({ ...row, agent_name: named?.name || null });
+}
+
+/** Deny many pending requests at once. Returns the ids that were denied. */
+export async function bulkDeny(userId, ids, { via = 'web', req = null } = {}) {
+ const list = [...new Set((Array.isArray(ids) ? ids : []).filter(isUuid))].slice(0, 200);
+ if (!list.length) throw new ApprovalError(400, 'no_ids', 'Pass one or more approval ids to deny.');
+ const channel = DECISION_VIAS.includes(via) ? via : 'web';
+ const rows = await sql`
+ UPDATE approval_requests
+ SET status = 'denied', decided_by = ${userId}, decided_at = now(), decided_via = ${channel}, updated_at = now()
+ WHERE user_id = ${userId} AND id = ANY(${list}) AND status = 'pending'
+ RETURNING id, summary
+ `;
+ for (const r of rows) logAudit({ userId, action: 'approval_denied', resourceId: r.id, meta: { via: channel, bulk: true, summary: r.summary }, req });
+ return { denied: rows.map((r) => r.id), skipped: list.filter((id) => !rows.some((r) => r.id === id)) };
+}
+
+export { TERMINAL as TERMINAL_STATUSES };
diff --git a/api/_lib/email.js b/api/_lib/email.js
index 5769d2a2c..d4c59292e 100644
--- a/api/_lib/email.js
+++ b/api/_lib/email.js
@@ -212,6 +212,37 @@ export function sendForgeCompleteEmail({ to, prompt, creationPath, previewImageU
return sendEmail({ to, ...renderForgeComplete({ prompt, creationPath, previewImageUrl }) });
}
+// Approval inbox fallback (api/_lib/approvals.js): sent only when no push device
+// or paired chat reached the owner. Carries the full confirmation table so the
+// owner sees exactly what they would approve, and a signed deep link to it. The
+// email never approves anything itself: the decision happens on the page.
+export function renderApprovalRequest({ agentName, summary, table, riskNotes = [], link, expiresAt }) {
+ const url = `${APP_URL}${link}`;
+ const who = agentName || 'Your agent';
+ const until = new Date(expiresAt).toUTCString();
+ const rows = (table || []).map((r) => `<tr><td style="padding:6px 12px 6px 0;color:#9a9ab0;white-space:nowrap">${esc(r.label)}</td><td style="padding:6px 0;font-family:ui-monospace,Menlo,monospace;word-break:break-all">${esc(r.full && r.full !== r.value ? `${r.value}: ${r.full}` : r.value)}</td></tr>`).join('');
+ const notes = riskNotes.length ? `<ul style="padding-left:18px;margin:0 0 16px">${riskNotes.map((n) => `<li style="margin:4px 0">${esc(n)}</li>`).join('')}</ul>` : '';
+ return {
+ subject: `Approval needed: ${summary.length > 80 ? `${summary.slice(0, 77)}...` : summary}`,
+ html: layout('Approval needed', `
+ <p class="brand">three.ws</p>
+ <h1>${esc(who)} is waiting for your approval</h1>
+ <p>${esc(summary)}</p>
+ <table style="border-collapse:collapse;margin:0 0 16px;font-size:14px">${rows}</table>
+ ${notes}
+ <a class="btn" href="${esc(url)}">Review and decide</a>
+ <p class="muted">Nothing happens unless you approve. This request expires ${esc(until)}; after that it can never execute.</p>
+ <hr>
+ <p class="muted">You're getting this email because no push device or paired chat reached you. Turn on push at <a href="${APP_URL}/approvals" style="color:#6a5cff">three.ws/approvals</a> to approve in one tap.</p>
+ `),
+ text: `${who} is waiting for your approval\n\n${summary}\n\n${(table || []).map((r) => `${r.label}: ${r.full || r.value}`).join('\n')}\n${riskNotes.length ? `\n${riskNotes.map((n) => `- ${n}`).join('\n')}\n` : ''}\nReview and decide: ${url}\n\nNothing happens unless you approve. Expires ${until}.`,
+ };
+}
+
+export function sendApprovalRequestEmail({ to, ...rest }) {
+ return sendEmail({ to, ...renderApprovalRequest(rest) });
+}
+
// Double opt-in newsletter confirmation. Minimal localization (prompt 38) so a
// subscriber confirms in their own language; unknown locales fall back to en.
const NEWSLETTER_I18N = {
diff --git a/api/_lib/migrations/20261010120000_approval_requests.sql b/api/_lib/migrations/20261010120000_approval_requests.sql
new file mode 100644
index 000000000..d707d6cc9
--- /dev/null
+++ b/api/_lib/migrations/20261010120000_approval_requests.sql
@@ -0,0 +1,86 @@
+-- Migration: the approval inbox. Every gated agent action that needs the owner's
+-- explicit yes becomes one row here, and an approval executes exactly the action
+-- that was shown, once.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261010120000_approval_requests.sql
+-- Idempotent.
+--
+-- approval_requests
+-- payload the exact action the executor will run, canonical JSON.
+-- payload_hash sha256 of the canonical payload. The approve call must echo
+-- the hash the owner was shown, and the executor recomputes it
+-- from `payload` before running, so neither a stale screen nor
+-- an edited row can execute something different.
+-- idempotency_key one request per gated event (an intent firing on one
+-- schedule bucket asks once, not once per sweep).
+-- status pending, then exactly one of: denied, expired, or approved,
+-- executing, executed | failed. The pending -> approved step is
+-- a single conditional UPDATE, so two taps on "Approve" (push
+-- plus web, or a double click) run the action once.
+-- decided_via which surface the decision came from: web, push, telegram,
+-- mobile, email, or auto_policy.
+-- team_id the specialist team the requester belongs to, when the
+-- request came from a team member (team runtime). Text, not a
+-- foreign key, so this table stands on its own.
+--
+-- approval_auto_policies
+-- The owner's explicit "don't ask me for this" rules. Default is no row, which
+-- means ask every time. Each policy is capped by size (max_usd per action) and
+-- venue, scoped to all agents, one agent, or one team, and revocable at any
+-- time; a revoked policy keeps its row so the audit trail stays readable.
+
+create table if not exists approval_requests (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid references agent_identities(id) on delete cascade,
+ team_id text,
+ requester_role text not null default 'agent',
+ source text not null,
+ source_ref text,
+ action_type text not null,
+ venue text not null,
+ payload jsonb not null,
+ payload_hash text not null check (payload_hash ~ '^[0-9a-f]{64}$'),
+ summary text not null,
+ amount numeric,
+ amount_usd numeric,
+ asset text,
+ chain text not null default 'solana',
+ network text not null default 'mainnet',
+ recipient text,
+ recipient_label text,
+ risk_notes jsonb not null default '[]'::jsonb,
+ gate_reason text,
+ idempotency_key text not null,
+ status text not null default 'pending'
+ check (status in ('pending', 'approved', 'executing', 'executed', 'failed', 'denied', 'expired')),
+ expires_at timestamptz not null,
+ decided_by uuid references users(id) on delete set null,
+ decided_at timestamptz,
+ decided_via text,
+ auto_policy_id uuid,
+ executed_at timestamptz,
+ signature text,
+ result jsonb,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create unique index if not exists approval_requests_idem_idx on approval_requests (idempotency_key);
+create index if not exists approval_requests_user_created_idx on approval_requests (user_id, created_at desc, id desc);
+create index if not exists approval_requests_pending_idx on approval_requests (user_id, expires_at) where status = 'pending';
+create index if not exists approval_requests_source_idx on approval_requests (source, source_ref) where status = 'pending';
+
+create table if not exists approval_auto_policies (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid references agent_identities(id) on delete cascade,
+ team_id text,
+ label text not null,
+ venues text[] not null check (cardinality(venues) > 0),
+ max_usd numeric not null check (max_usd > 0),
+ expires_at timestamptz,
+ revoked_at timestamptz,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists approval_auto_policies_user_idx on approval_auto_policies (user_id) where revoked_at is null;
diff --git a/api/_lib/migrations/20261010140000_strategy_research_gates.sql b/api/_lib/migrations/20261010140000_strategy_research_gates.sql
new file mode 100644
index 000000000..d8b6a06c5
--- /dev/null
+++ b/api/_lib/migrations/20261010140000_strategy_research_gates.sql
@@ -0,0 +1,55 @@
+-- Migration: Strategy Object v2 settings (research gates, price impact, ask mode).
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261010140000_strategy_research_gates.sql
+-- Idempotent.
+--
+-- strategy_candidate_decisions
+-- One row per (equip, mint): the latest verdict the equipped-strategy runtime
+-- reached for a candidate that passed the entry filter. `decision` is
+-- blocked (a research gate refused it), approval (ask mode filed an approval
+-- request), executed, skipped (a spend guard refused it), or failed.
+-- `check_name` is the gate or guard that decided it and `reason` says why in
+-- plain language; `report` is the cited gate report the decision was made on.
+-- A coin re-evaluated on a later sweep updates its row (seen_count counts the
+-- sweeps), so the log stays bounded while a coin that later clears a gate shows
+-- its newest verdict.
+--
+-- Backfill: every stored Strategy Object config and every equip snapshot that
+-- has no `mode` becomes version 2 in ask mode. Ask is the conservative default:
+-- an existing strategy now files an approval request for each buy until its
+-- owner explicitly switches it to auto. Configs that already carry a mode are
+-- left untouched.
+
+create table if not exists strategy_candidate_decisions (
+ id bigserial primary key,
+ equip_id uuid not null references agent_strategy_equips(id) on delete cascade,
+ strategy_id uuid,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ owner_id uuid not null references users(id) on delete cascade,
+ network text not null default 'mainnet',
+ mint text not null,
+ decision text not null check (decision in ('blocked', 'approval', 'executed', 'skipped', 'failed')),
+ check_name text,
+ reason text,
+ blocked_by jsonb not null default '[]'::jsonb,
+ report jsonb,
+ approval_id uuid,
+ signature text,
+ seen_count int not null default 1,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create unique index if not exists strategy_candidate_decisions_equip_mint_idx
+ on strategy_candidate_decisions (equip_id, mint);
+create index if not exists strategy_candidate_decisions_agent_idx
+ on strategy_candidate_decisions (agent_id, updated_at desc);
+create index if not exists strategy_candidate_decisions_owner_idx
+ on strategy_candidate_decisions (owner_id, updated_at desc);
+
+update agent_strategies
+ set config = config || '{"version": 2, "mode": "ask"}'::jsonb
+ where not (config ? 'mode');
+
+update agent_strategy_equips
+ set config_snapshot = config_snapshot || '{"version": 2, "mode": "ask"}'::jsonb
+ where config_snapshot is not null and not (config_snapshot ? 'mode');
diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.js
index 1fc94c05a..c344d7bcd 100644
--- a/api/_lib/notify-prefs.js
+++ b/api/_lib/notify-prefs.js
@@ -62,6 +62,15 @@ export const CATEGORIES = [
label: 'Agent mail',
description: 'An email arrived in one of your agents\' inboxes (spam is held back and never notifies).',
},
+ {
+ key: 'approvals',
+ label: 'Approvals',
+ description: 'An agent is waiting for your yes before it moves funds. Approve or deny from the notification, chat, or /approvals.',
+ // A pending approval is a decision the owner owes; the bell row is the
+ // one surface that always carries it, so it cannot be muted. Push, email
+ // and chats stay togglable.
+ lockedChannels: ['in_app'],
+ },
{
key: 'account',
label: 'Account & security',
@@ -143,6 +152,7 @@ const TYPE_CATEGORY = {
skill_payment_mismatch: 'account',
security_alert: 'account',
wallet_anomaly_frozen: 'account',
+ approval_requested: 'approvals',
};
export function categoryForType(type) {
@@ -189,6 +199,11 @@ const DEFAULTS = {
knock: { in_app: true, push: true, email: true, telegram: false, discord: false, avatar: true },
mail: { in_app: true, push: true, email: false, telegram: false, discord: false, avatar: false },
account: { in_app: true, push: true, email: true, telegram: false, discord: false, avatar: true },
+ // Approvals reach for every paired surface by default: an unanswered request
+ // expires and the action never runs, so being reached is the feature. Email
+ // is only the fallback (api/_lib/approvals.js sends it when no push device or
+ // paired chat got the request).
+ approvals: { in_app: true, push: true, email: true, telegram: true, discord: true, avatar: true },
};
/** The full default matrix, used to seed the preference-center UI. */
@@ -312,6 +327,7 @@ const PUSH_COPY = {
skill_payment_mismatch: () => ['Payment mismatch ⚠️', 'Check your agent payment settings'],
security_alert: (p) => ['Security alert 🔒', p.message || 'A security-sensitive change was made to your account'],
wallet_anomaly_frozen: (p) => ['Wallet auto-frozen 🛡️', p.summary || 'Your agent wallet was frozen after an unusual action — tap to approve or keep frozen'],
+ approval_requested: (p) => ['Approval needed', [p.summary || 'An agent is waiting for your approval', p.confirmation].filter(Boolean).join('\n')],
};
export function pushPayloadFor(type, payload, notificationId) {
@@ -319,7 +335,7 @@ export function pushPayloadFor(type, payload, notificationId) {
const fn = PUSH_COPY[type];
const [title, body] = fn ? fn(p) : ['three.ws', String(type).replace(/_/g, ' ')];
const url = pushUrlFor(p);
- return {
+ const out = {
title,
body,
url,
@@ -328,6 +344,15 @@ export function pushPayloadFor(type, payload, notificationId) {
// Used by the SW to attribute the 'returned' funnel event.
category: categoryForType(type),
};
+ // An approval push carries what the service worker needs to answer it in
+ // place (Approve / Deny action buttons, public/push-sw.js): the request id,
+ // the payload hash the owner is approving, and the signed link token. One
+ // tag per request so two pending approvals never replace each other.
+ if (type === 'approval_requested' && p.approval_id) {
+ out.tag = `approval:${p.approval_id}`;
+ out.approval = { id: p.approval_id, hash: p.payload_hash || null, token: p.link_token || null };
+ }
+ return out;
}
function pushUrlFor(p) {
diff --git a/api/_lib/notify.js b/api/_lib/notify.js
index cd18ea2f4..2b0b777bc 100644
--- a/api/_lib/notify.js
+++ b/api/_lib/notify.js
@@ -61,6 +61,9 @@ async function deliver(userId, type, payload) {
// unread count are both derived from user_notifications, so skipping the
// insert is what keeps the two consistent.
let id = null;
+ // What reached the user outside the bell, so a caller with an email
+ // fallback (the approval inbox) can tell "nobody was reached" apart.
+ const delivered = { push: 0 };
if (wantsInApp) {
try {
const [row] = await sql`
@@ -91,8 +94,8 @@ async function deliver(userId, type, payload) {
sendPushToUser(userId, push).catch(() => 0),
sendApnsToUser(userId, push).catch(() => 0),
]);
- const delivered = web + ios;
- if (delivered > 0) recordEvent(id, userId, 'push', 'sent', { count: delivered, web, ios });
+ delivered.push = web + ios;
+ if (delivered.push > 0) recordEvent(id, userId, 'push', 'sent', { count: delivered.push, web, ios });
}
} catch (err) {
console.error('[notify] push fan-out failed:', err.message);
@@ -101,12 +104,15 @@ async function deliver(userId, type, payload) {
// 6: paired chats. Queued for the gateway worker, gated per channel.
try {
const queued = await queueChatNotifications({ userId, type, payload, notificationId: id, prefs });
- for (const [channel, count] of Object.entries(queued)) recordEvent(id, userId, channel, 'sent', { count });
+ for (const [channel, count] of Object.entries(queued)) {
+ delivered[channel] = count;
+ recordEvent(id, userId, channel, 'sent', { count });
+ }
} catch (err) {
console.error('[notify] chat fan-out failed:', err.message);
}
- return { id, in_app: wantsInApp };
+ return { id, in_app: wantsInApp, delivered };
}
/**
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 8018e2383..479108fc0 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -719,6 +719,9 @@ export const limits = {
// Strategy backtest (api/sniper/backtest.js) is a read-only replay over captured
// history; cached by strategy hash, so this only gates cache-miss origin work.
sniperBacktestIp: (ip) => getLimiter('sniper:backtest:ip', { limit: 40, window: '5 m' }).limit(ip),
+ // Strategy Lab live match preview (api/strategies.js preview). Fires on slider
+ // changes (debounced client side) and replays a cached history window in memory.
+ strategyPreviewIp: (ip) => getLimiter('strategy:preview:ip', { limit: 120, window: '5 m', local: true }).limit(ip),
// pump.fun coin metadata upload (name/symbol/image → R2 JSON). Cheap and
// idempotent, so it gets its own bucket instead of draining the strict
// `authIp` budget shared by on-chain buy/sell/launch actions. Iterating in
@@ -1595,6 +1598,10 @@ export const limits = {
previewAgent: (agentId) =>
getLimiter('preview:agent', { limit: 200, window: '1 h' }).limit(agentId),
widgetWrite: (userId) => getLimiter('widget:write', { limit: 60, window: '1 m' }).limit(userId),
+ // Specialist teams: creating/editing a team provisions agents (write), and a
+ // role run fans out to RPC, the intel store and the trade engine (run).
+ teamWrite: (userId) => getLimiter('team:write', { limit: 20, window: '1 h' }).limit(userId),
+ teamRun: (userId) => getLimiter('team:run', { limit: 60, window: '10 m' }).limit(userId),
// local: embedded-widget read fetch — flood protection only, no side effects.
// Widgets on third-party pages poll continuously, so a Redis command per read
// at 600/min is pure burn; a per-instance cap bounds throughput just as well.
@@ -2256,6 +2263,10 @@ export const limits = {
// (the June 2026 Upstash quota outage), and a per-instance count can only
// ever be more generous than the published number, never stricter.
planApi: (planId, key, { limit, windowSeconds }) => planWindowLimit(`${planId}\u0000${key}`, limit, windowSeconds * 1000),
+ // Approval inbox (api/approvals/*): list, read, decide. Generous because an
+ // owner clearing a backlog taps fast; it exists so a stuck client loop cannot
+ // hammer the decide path. Local: a decision is already idempotent in the DB.
+ approvalsUser: (userId) => getLimiter('approvals:user', { limit: 240, window: '5 m', local: true }).limit(userId),
};
// Fixed-window counters for limits.planApi. One small record per principal, so
diff --git a/api/_lib/strategy-approvals.js b/api/_lib/strategy-approvals.js
new file mode 100644
index 000000000..2d03e90ff
--- /dev/null
+++ b/api/_lib/strategy-approvals.js
@@ -0,0 +1,215 @@
+// Strategy ask mode and the candidate decision log.
+//
+// A Strategy Object in `mode: 'ask'` never buys on its own. When a candidate
+// clears the entry filter, the research gates, and a dry run of every spend
+// guard, the runtime files an approval request here instead, in the platform's
+// shared `approval_requests` inbox (one row per gated action, shared with every
+// other surface that asks the owner first). The request carries the exact buy
+// that will run (`payload`) and its sha256 (`payload_hash`): approving must echo
+// the hash the owner was shown, and the executor recomputes it from the stored
+// payload, so neither a stale screen nor an edited row can buy something else.
+// Expiry and deny fail closed: nothing is bought.
+//
+// The decision log (`strategy_candidate_decisions`) records, per equip and coin,
+// the latest verdict and the check that decided it, with the cited gate report.
+//
+// Pure DB helpers only. The executor that runs an approved buy lives with the
+// rest of the trading path in api/_lib/agent-strategy-runtime.js.
+
+import { createHash } from 'node:crypto';
+import { sql } from './db.js';
+import { riskNotesFromReport } from './strategy-research.js';
+
+// Meme-coin windows are short: an unanswered request expires rather than buying
+// a coin at a price nobody looked at.
+export const STRATEGY_APPROVAL_TTL_MINUTES = 15;
+// A blocked or skipped candidate is re-checked after this pause, not every sweep.
+export const DECISION_RECHECK_MINUTES = 5;
+export const STRATEGY_APPROVAL_SOURCE = 'strategy';
+export const STRATEGY_APPROVAL_ACTION = 'strategy_buy';
+
+/**
+ * Deterministic JSON: object keys sorted recursively, no whitespace. For the
+ * flat string/number/boolean/null payloads hashed here this is byte-identical to
+ * RFC 8785 (JCS) output, so any JCS implementation reproduces the same hash.
+ */
+export function canonicalJson(value) {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
+}
+
+export function payloadHash(payload) {
+ return createHash('sha256').update(canonicalJson(payload)).digest('hex');
+}
+
+/** The exact buy an approval will run. Everything the executor needs, nothing it doesn't. */
+export function buildStrategyBuyPayload({ equip, agentId, config, network, mint, idempotencyKey }) {
+ return {
+ kind: STRATEGY_APPROVAL_ACTION,
+ agent_id: agentId,
+ equip_id: equip.id,
+ strategy_id: equip.strategy_id,
+ network,
+ mint,
+ side: 'buy',
+ amount_sol: config.sizing.amount_sol,
+ slippage_bps: config.sizing.max_slippage_bps,
+ max_price_impact_pct: config.sizing.max_price_impact_bps == null ? null : config.sizing.max_price_impact_bps / 100,
+ idempotency_key: idempotencyKey,
+ };
+}
+
+const shortMint = (m) => (m && m.length > 12 ? `${m.slice(0, 4)}...${m.slice(-4)}` : m || '');
+
+/**
+ * File an approval request for one strategy buy. Deduped per (equip, coin): a
+ * coin is asked about once, and a denied or expired request is never re-filed.
+ * Returns { ok, id, created } or { ok:false, code } when the inbox is unreachable
+ * (the caller then buys nothing).
+ */
+export async function createStrategyApproval({ equip, agent, config, launch, network, quote, usd, impactCap, idempotencyKey, report }) {
+ const payload = buildStrategyBuyPayload({ equip, agentId: agent.id, config, network, mint: launch.mint, idempotencyKey });
+ const hash = payloadHash(payload);
+ const approvalKey = `strategy-approval:${equip.id}:${launch.mint}`;
+ const expiresAt = new Date(Date.now() + STRATEGY_APPROVAL_TTL_MINUTES * 60_000).toISOString();
+ // Token names and symbols are untrusted data, so the summary names the coin by
+ // its address only. The strategy name is the owner's own text.
+ const summary = `Buy ${config.sizing.amount_sol} SOL of ${shortMint(launch.mint)} for strategy "${String(equip.strategy_name || equip.slug || 'strategy').slice(0, 60)}"`;
+ const notes = riskNotesFromReport(report, report?.evaluation);
+ if (quote?.priceImpactPct != null) notes.unshift(`Quoted price impact ${Number(quote.priceImpactPct).toFixed(2)}% (limit ${impactCap ?? 'none'}%).`);
+ try {
+ const inserted = await sql`
+ INSERT INTO approval_requests
+ (user_id, agent_id, requester_role, source, source_ref, action_type, venue,
+ payload, payload_hash, summary, amount, amount_usd, asset, chain, network,
+ recipient, recipient_label, risk_notes, gate_reason, idempotency_key, expires_at)
+ VALUES (
+ ${agent.ownerId}, ${agent.id}, 'strategy', ${STRATEGY_APPROVAL_SOURCE}, ${String(equip.id)},
+ ${STRATEGY_APPROVAL_ACTION}, 'pumpfun',
+ ${JSON.stringify(payload)}::jsonb, ${hash}, ${summary},
+ ${config.sizing.amount_sol}, ${usd ?? null}, 'SOL', 'solana', ${network},
+ ${launch.mint}, 'pump.fun bonding curve buy',
+ ${JSON.stringify(notes)}::jsonb,
+ 'This strategy is in ask mode: every buy waits for your approval.',
+ ${approvalKey}, ${expiresAt}
+ )
+ ON CONFLICT (idempotency_key) DO NOTHING
+ RETURNING id
+ `;
+ if (inserted.length) return { ok: true, id: inserted[0].id, created: true };
+ const [existing] = await sql`SELECT id FROM approval_requests WHERE idempotency_key = ${approvalKey} LIMIT 1`;
+ return existing ? { ok: true, id: existing.id, created: false } : { ok: false, code: 'approval_conflict' };
+ } catch (err) {
+ console.warn('[strategy-approvals] could not file approval:', err?.message);
+ return { ok: false, code: 'approval_unavailable' };
+ }
+}
+
+/** Pending, unexpired approvals holding a slot for one equip. */
+export async function pendingApprovalCount(equipId) {
+ try {
+ const [r] = await sql`
+ SELECT count(*)::int AS n FROM approval_requests
+ WHERE source = ${STRATEGY_APPROVAL_SOURCE} AND source_ref = ${String(equipId)}
+ AND status = 'pending' AND expires_at > now()
+ `;
+ return Number(r?.n || 0);
+ } catch {
+ return 0;
+ }
+}
+
+/**
+ * Mints this equip decided recently enough to skip this sweep: an approval or a
+ * buy is final for that coin; a block, skip, or failure is re-checked after
+ * DECISION_RECHECK_MINUTES.
+ */
+export async function recentDecisions(equipId, mints) {
+ if (!mints.length) return new Set();
+ try {
+ const rows = await sql`
+ SELECT mint FROM strategy_candidate_decisions
+ WHERE equip_id = ${equipId} AND mint = ANY(${mints})
+ AND (decision IN ('approval', 'executed')
+ OR updated_at > now() - (${DECISION_RECHECK_MINUTES} || ' minutes')::interval)
+ `;
+ return new Set(rows.map((r) => r.mint));
+ } catch {
+ return new Set();
+ }
+}
+
+/** Upsert the latest verdict for (equip, coin). Never throws: the log must not stop a sweep. */
+export async function recordCandidateDecision({
+ equip, agentId, network, mint, decision, check = null, reason = null,
+ blockedBy = [], report = null, approvalId = null, signature = null,
+}) {
+ try {
+ await sql`
+ INSERT INTO strategy_candidate_decisions
+ (equip_id, strategy_id, agent_id, owner_id, network, mint, decision, check_name, reason,
+ blocked_by, report, approval_id, signature)
+ VALUES (
+ ${equip.id}, ${equip.strategy_id || null}, ${agentId}, ${equip.owner_id}, ${network}, ${mint},
+ ${decision}, ${check}, ${reason ? String(reason).slice(0, 600) : null},
+ ${JSON.stringify(blockedBy || [])}::jsonb, ${report ? JSON.stringify(report) : null}::jsonb,
+ ${approvalId}, ${signature}
+ )
+ ON CONFLICT (equip_id, mint) DO UPDATE SET
+ decision = excluded.decision, check_name = excluded.check_name, reason = excluded.reason,
+ blocked_by = excluded.blocked_by, report = coalesce(excluded.report, strategy_candidate_decisions.report),
+ approval_id = coalesce(excluded.approval_id, strategy_candidate_decisions.approval_id),
+ signature = coalesce(excluded.signature, strategy_candidate_decisions.signature),
+ seen_count = strategy_candidate_decisions.seen_count + 1, updated_at = now()
+ `;
+ } catch (err) {
+ console.warn('[strategy-approvals] decision log write failed:', err?.message);
+ }
+}
+
+/** The decision log for one agent, newest first. */
+export async function listCandidateDecisions({ agentId, ownerId, decision = null, limit = 50 }) {
+ const lim = Math.min(200, Math.max(1, Number(limit) || 50));
+ const rows = await sql`
+ SELECT d.id, d.equip_id, d.strategy_id, d.network, d.mint, d.decision, d.check_name, d.reason,
+ d.blocked_by, d.report, d.approval_id, d.signature, d.seen_count, d.created_at, d.updated_at,
+ s.name AS strategy_name, s.slug AS strategy_slug
+ FROM strategy_candidate_decisions d
+ LEFT JOIN agent_strategies s ON s.id = d.strategy_id
+ WHERE d.agent_id = ${agentId} AND d.owner_id = ${ownerId}
+ AND (${decision}::text IS NULL OR d.decision = ${decision})
+ ORDER BY d.updated_at DESC
+ LIMIT ${lim}
+ `;
+ return rows;
+}
+
+/**
+ * Strategy approval requests for one agent. A pending row past its expiry is
+ * marked expired first, so the list never shows an approvable request that the
+ * executor would refuse.
+ */
+export async function listStrategyApprovals({ agentId, ownerId, status = null, limit = 50 }) {
+ const lim = Math.min(200, Math.max(1, Number(limit) || 50));
+ await expireStaleStrategyApprovals(ownerId);
+ return sql`
+ SELECT id, agent_id, source_ref AS equip_id, action_type, venue, payload, payload_hash, summary,
+ amount, amount_usd, asset, chain, network, recipient, recipient_label, risk_notes,
+ gate_reason, status, expires_at, decided_at, decided_via, executed_at, signature, result, created_at
+ FROM approval_requests
+ WHERE user_id = ${ownerId} AND agent_id = ${agentId} AND source = ${STRATEGY_APPROVAL_SOURCE}
+ AND (${status}::text IS NULL OR status = ${status})
+ ORDER BY created_at DESC
+ LIMIT ${lim}
+ `;
+}
+
+export async function expireStaleStrategyApprovals(ownerId) {
+ await sql`
+ UPDATE approval_requests SET status = 'expired', updated_at = now()
+ WHERE user_id = ${ownerId} AND source = ${STRATEGY_APPROVAL_SOURCE}
+ AND status = 'pending' AND expires_at <= now()
+ `.catch(() => {});
+}
diff --git a/api/_lib/strategy-backtest.js b/api/_lib/strategy-backtest.js
index eb49da839..a4e8271cb 100644
--- a/api/_lib/strategy-backtest.js
+++ b/api/_lib/strategy-backtest.js
@@ -21,6 +21,8 @@ import { sql } from './db.js';
import { scoreMint, scoreIntel } from '../../workers/agent-sniper/scorer.js';
import { decideExit } from '../../workers/agent-sniper/exit-logic.js';
import { getLearnedWeights } from '../../workers/agent-sniper/intel/store.js';
+import { normalizeStrategyConfig, researchGatesActive } from './strategy-schema.js';
+import { historicalGateReport, judgeHistoricalGates } from './strategy-preview.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
const MAX_CANDIDATES = 6000;
@@ -35,8 +37,19 @@ const HASH_FIELDS = [
'require_socials', 'require_sol_quote',
'take_profit_pct', 'stop_loss_pct', 'trailing_stop_pct', 'max_hold_seconds',
'min_quality_score', 'max_bundle_score', 'max_concentration_top1', 'avoid_dev_dump', 'allowed_categories',
+ 'research',
];
+/**
+ * A Strategy Object `research` block, normalized, or null when no gate is on (so
+ * a strategy without research gates keeps its existing cache hash).
+ */
+export function sanitizeResearch(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const config = normalizeStrategyConfig({ research: raw });
+ return researchGatesActive(config) ? config.research : null;
+}
+
/** Stable hash of the trade-determining strategy fields + window + network. */
export function strategyHash(strategy, windowDays, network) {
const norm = {};
@@ -80,7 +93,7 @@ function toMintEvent(row, entryMcUsd) {
// Build the object scoreIntel() expects. smart_money is intentionally absent —
// it's a live graph read we did not capture historically, so scoreIntel skips
// the smart-money gate (computed:false), exactly as it does for a brand-new coin.
-function toIntelRecord(row) {
+export function toIntelRecord(row) {
const s = { ...(row.signals || {}) };
if (s.bundle_score == null && row.bundle_score != null) s.bundle_score = Number(row.bundle_score);
if (s.organic_score == null && row.organic_score != null) s.organic_score = Number(row.organic_score);
@@ -161,7 +174,7 @@ export async function runBacktest(strategy, { windowDays = 30, network = 'mainne
SELECT
i.mint, i.symbol, i.name, i.creator, i.first_seen_at,
i.twitter, i.telegram, i.website,
- i.dev_buy_lamports, i.dev_sold, i.buy_volume_lamports,
+ i.dev_buy_lamports, i.dev_sold, i.buy_volume_lamports, i.sell_volume_lamports, i.unique_buyers,
i.signals, i.bundle_score, i.organic_score, i.quality_score,
i.category, i.risk_flags,
o.graduated, o.outcome, o.ath_multiple, o.ath_market_cap_usd, o.last_market_cap_usd,
@@ -186,7 +199,12 @@ export async function runBacktest(strategy, { windowDays = 30, network = 'mainne
const perTradeLamports = stakeSol * LAMPORTS_PER_SOL;
const entries = [];
- const skip = { gate: 0, no_price: 0, impact: 0 };
+ const skip = { gate: 0, research: 0, no_price: 0, impact: 0 };
+ // Research gates: the same evaluator the live runtime runs before a buy,
+ // judged on what was recorded. Gates history cannot replay are counted, not faked.
+ const researchConfig = strategy.research ? { research: strategy.research } : null;
+ const researchBlockedBy = {};
+ let researchLive = 0;
const outcomeCounts = { graduated: 0, pumped: 0, flat: 0, rugged: 0 };
for (const row of rows) {
@@ -199,6 +217,15 @@ export async function runBacktest(strategy, { windowDays = 30, network = 'mainne
? scoreIntel(toIntelRecord(row), strategy, weights)
: scoreMint(toMintEvent(row, entryMcUsd), strategy);
if (!verdict.pass) { skip.gate++; continue; }
+ if (researchConfig) {
+ const gate = judgeHistoricalGates(researchConfig, historicalGateReport(row));
+ if (gate.blocked) {
+ skip.research++;
+ researchBlockedBy[gate.blocked] = (researchBlockedBy[gate.blocked] || 0) + 1;
+ continue;
+ }
+ if (gate.live) researchLive++;
+ }
// Need a real peak multiple to simulate; without it we cannot honestly model a fill.
if (athMult == null || athMult <= 0) { skip.no_price++; continue; }
@@ -239,7 +266,7 @@ export async function runBacktest(strategy, { windowDays = 30, network = 'mainne
}
const taken = entries.length;
- const caveats = buildCaveats({ universeSize, taken, days, network, useIntel });
+ const caveats = buildCaveats({ universeSize, taken, days, network, useIntel, researchLive, research: !!researchConfig });
if (taken === 0) {
return {
@@ -254,6 +281,7 @@ export async function runBacktest(strategy, { windowDays = 30, network = 'mainne
? `No labeled launch history captured for ${network} in the last ${days} days yet. Backtest will sharpen as the intel engine logs more outcomes.`
: `None of the ${universeSize.toLocaleString()} labeled launches in the last ${days} days passed these filters. They may be too strict — loosen one and re-run.`,
skipped: skip,
+ research_blocked_by: researchBlockedBy,
caveats,
};
}
@@ -293,6 +321,8 @@ export async function runBacktest(strategy, { windowDays = 30, network = 'mainne
sample_size: taken,
universe_size: universeSize,
skipped: skip,
+ research_blocked_by: researchBlockedBy,
+ research_live_checked: researchLive,
stake_sol: Number(stakeSol.toFixed(4)),
stake_assumed: perTradeSol <= 0,
metrics: {
@@ -320,10 +350,12 @@ export async function runBacktest(strategy, { windowDays = 30, network = 'mainne
};
}
-function buildCaveats({ universeSize, taken, days, network, useIntel }) {
+function buildCaveats({ universeSize, taken, days, network, useIntel, researchLive = 0, research = false }) {
const c = [];
c.push('Replayed over real captured launches only — no synthetic data. Exits are modeled at the recorded peak and final price, not a full tick-by-tick path.');
c.push('Survivorship/labeling: only coins observed long enough to be labeled are included, and outcomes lag launch by design, so very recent launches are excluded.');
+ if (researchLive > 0) c.push(`${researchLive} entered launches had no recorded firewall decision, so the security and authority gates could not be replayed for them; live, the firewall checks every buy.`);
+ if (research) c.push('Research gates are judged on evidence recorded over the whole observation window (holders are unique buyers seen, liquidity is net SOL bought into the curve), which includes buying after an early entry. Live, a gate only sees what exists at buy time, so treat gated results as optimistic.');
if (useIntel) c.push('Smart-money gates are skipped in backtest (the live wallet-graph read was not captured historically); all other gates match live exactly.');
let confidence = 'high';
if (taken < 10) { confidence = 'low'; c.push(`Only ${taken} matching launches — treat these numbers as directional, not predictive. Widen the window or loosen filters for a stronger read.`); }
diff --git a/api/_lib/strategy-compiler.js b/api/_lib/strategy-compiler.js
index 53844ebd5..a008d0ac5 100644
--- a/api/_lib/strategy-compiler.js
+++ b/api/_lib/strategy-compiler.js
@@ -11,10 +11,17 @@
// explicit list of every value we assumed or clamped — so the owner sees the
// truth before arming, never a silent unsafe config.
//
+// It also emits the same intent as a Strategy Object v2 config
+// (`strategy_object`, api/_lib/strategy-schema.js): research gates, a price-
+// impact ceiling, the trade size in SOL, source filters, and the run mode, with
+// a per-field `explanations` list saying where each value came from. Mode is
+// 'ask' unless the owner explicitly asked for unattended buying.
+//
// Prefers the platform LLM (free-first chain in llm.js); falls back to a real
// deterministic intent parser so the feature always compiles, model or not.
import { llmComplete, llmConfigured } from './llm.js';
+import { normalizeStrategyConfig, STRATEGY_CONFIG_DEFAULTS } from './strategy-schema.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
@@ -46,9 +53,17 @@ Schema (omit a field or use null when the user didn't specify it — do NOT inve
"max_concentration_top1": number|null, // 0-100, top holder share cap (intel_confirmed)
"avoid_dev_dump": boolean|null, // skip coins where dev already sold
"allowed_categories": [string]|null, // subset of: ${KNOWN_CATEGORIES.join(', ')}
+ "min_holders": integer|null, // research gate: at least N holders before buying
+ "min_liquidity_sol": number|null, // research gate: at least N SOL of curve liquidity
+ "security_min_score": number|null, // research gate: rug/honeypot firewall score floor, 0-100
+ "require_no_mint_authority": boolean|null, // research gate: mint authority must be renounced
+ "require_no_freeze_authority": boolean|null, // research gate: freeze authority must be renounced
+ "sources": ["pump_curve"|"three_ws_launch"]|null, // launch sources; ["three_ws_launch"] = coins launched through three.ws only
+ "mode": "auto" | "ask" | null, // "auto" ONLY when the user explicitly says buy automatically / without asking; otherwise "ask"
"summary": string, // one plain-language sentence describing what this strategy does
"assumptions": [string] // anything you defaulted or could not parse
}
+Research: "at least 50 holders" => min_holders 50; "top holder under 20%" / "no whales over 20%" => max_concentration_top1 20; "renounced mint" => require_no_mint_authority true; "no freeze" => require_no_freeze_authority true; "safety score 70+" => security_min_score 70.
Conversions: "3x"/"triple" => take_profit_pct 200; "2x" => 100. "graduated at least two" => min_creator_graduated 2. "organic" / "no bundles" => trigger intel_confirmed with a low max_bundle_score (~0.3) and decent min_quality_score (~55). "smart money" => trigger intel_confirmed. Percentages stay percentages. Never reference any coin other than $THREE.`;
function num(v) {
@@ -251,12 +266,15 @@ export async function compileStrategyFromText(text, { tradeLimits = null, networ
}
const summary = str(parsed.summary, 400) || describeStrategy(strategy);
+ const { config: strategyObject, explanations } = toStrategyObject(parsed, strategy, { network, perTradeSol, assumptions });
return {
ok: true,
via,
source_text: source,
strategy,
+ strategy_object: strategyObject,
+ explanations,
summary,
assumptions: [...new Set(assumptions)],
clamped: [...new Set(clamped)],
@@ -264,6 +282,102 @@ export async function compileStrategyFromText(text, { tradeLimits = null, networ
};
}
+const RESEARCH_SOURCES = ['pump_curve', 'three_ws_launch'];
+
+/**
+ * The same compiled intent as a Strategy Object v2 config, plus one explanation
+ * per setting that is not a schema default. `strategy` is the already clamped
+ * sniper row, so every money knob carries the same spend-guard clamp.
+ */
+export function toStrategyObject(parsed, strategy, { network = 'mainnet', perTradeSol = null, assumptions = [] } = {}) {
+ const p = parsed || {};
+ const explanations = [];
+ const explain = (field, value, why) => explanations.push({ field, value, why });
+ const D = STRATEGY_CONFIG_DEFAULTS;
+
+ const explicitAuto = p.mode === 'auto';
+ const mode = explicitAuto ? 'auto' : 'ask';
+ explain('mode', mode, explicitAuto
+ ? 'You asked for unattended buying: every buy still passes the research gates and your spend caps.'
+ : 'Ask mode: each buy waits for your approval. Switch to auto once you trust the gates.');
+
+ let sources = Array.isArray(p.sources) ? [...new Set(p.sources.map((x) => String(x).toLowerCase()).filter((x) => RESEARCH_SOURCES.includes(x)))] : [];
+ if (sources.length === RESEARCH_SOURCES.length) sources = [];
+ if (sources.length) explain('entry.sources', sources, sources.includes('three_ws_launch') && sources.length === 1
+ ? 'Only coins launched through three.ws are considered.'
+ : 'Only live pump.fun bonding-curve launches are considered.');
+
+ const amountSol = perTradeSol != null && perTradeSol > 0
+ ? Number(BigInt(strategy.per_trade_lamports)) / LAMPORTS_PER_SOL
+ : D.sizing.amount_sol;
+ explain('sizing.amount_sol', amountSol, perTradeSol != null && perTradeSol > 0
+ ? `${amountSol} SOL per buy, within your trade cap.`
+ : `No trade size given, so the ${D.sizing.amount_sol} SOL default is used.`);
+ const impactBps = Math.max(1, Math.round(strategy.max_price_impact_pct * 100));
+ explain('sizing.max_price_impact_bps', impactBps, `A buy whose quote moves the price more than ${strategy.max_price_impact_pct}% is skipped. It can only tighten your agent's own breaker.`);
+
+ const g = {
+ min_holders: intOrNull(p.min_holders),
+ max_top_holder_pct: strategy.max_concentration_top1,
+ min_liquidity_sol: num(p.min_liquidity_sol),
+ security_min_score: num(p.security_min_score),
+ require_no_mint_authority: p.require_no_mint_authority === true,
+ require_no_freeze_authority: p.require_no_freeze_authority === true,
+ dev_history: {
+ max_launches: strategy.max_creator_launches,
+ min_graduated: strategy.min_creator_graduated,
+ block_dev_sold: strategy.avoid_dev_dump === true,
+ },
+ };
+ if (g.min_holders != null) g.min_holders = clamp(g.min_holders, 0, 10_000_000);
+ if (g.min_liquidity_sol != null) g.min_liquidity_sol = clamp(g.min_liquidity_sol, 0, 1e9);
+ if (g.security_min_score != null) g.security_min_score = clamp(Math.round(g.security_min_score), 0, 100);
+ if (g.min_holders != null) explain('research.min_holders', g.min_holders, `Skip coins with fewer than ${g.min_holders} holders.`);
+ if (g.max_top_holder_pct != null) explain('research.max_top_holder_pct', g.max_top_holder_pct, `Skip coins whose largest holder owns more than ${g.max_top_holder_pct}% (the bonding curve is not counted as a holder).`);
+ if (g.min_liquidity_sol != null) explain('research.min_liquidity_sol', g.min_liquidity_sol, `Skip coins with less than ${g.min_liquidity_sol} SOL of curve liquidity.`);
+ if (g.security_min_score != null) explain('research.security_min_score', g.security_min_score, `Skip coins the rug and honeypot firewall scores below ${g.security_min_score}/100.`);
+ if (g.require_no_mint_authority) explain('research.require_no_mint_authority', true, 'Skip coins whose creator can still mint new supply.');
+ if (g.require_no_freeze_authority) explain('research.require_no_freeze_authority', true, 'Skip coins whose creator can freeze holder accounts.');
+ if (g.dev_history.max_launches != null) explain('research.dev_history.max_launches', g.dev_history.max_launches, `Skip creators with more than ${g.dev_history.max_launches} launches.`);
+ if (g.dev_history.min_graduated != null) explain('research.dev_history.min_graduated', g.dev_history.min_graduated, `Only buy from creators with at least ${g.dev_history.min_graduated} graduated coins.`);
+ if (g.dev_history.block_dev_sold) explain('research.dev_history.block_dev_sold', true, 'Skip coins whose creator has already sold.');
+
+ const raw = {
+ version: 2,
+ mode,
+ network,
+ entry: {
+ trigger: 'new_launch',
+ sources,
+ max_age_minutes: D.entry.max_age_minutes,
+ min_market_cap_usd: strategy.min_market_cap_usd,
+ max_market_cap_usd: strategy.max_market_cap_usd,
+ require_socials: strategy.require_socials,
+ require_sol_quote: strategy.require_sol_quote,
+ },
+ sizing: { amount_sol: amountSol, max_slippage_bps: strategy.slippage_bps, max_price_impact_bps: impactBps },
+ exits: {
+ take_profit_pct: strategy.take_profit_pct,
+ stop_loss_pct: strategy.stop_loss_pct,
+ trailing_stop_pct: strategy.trailing_stop_pct,
+ max_hold_minutes: strategy.max_hold_seconds != null ? Math.max(1, Math.round(strategy.max_hold_seconds / 60)) : null,
+ },
+ risk: { max_concurrent_positions: strategy.max_concurrent_positions, cooldown_minutes: 0 },
+ research: g,
+ };
+ if (strategy.min_market_cap_usd != null || strategy.max_market_cap_usd != null) {
+ explain('entry.market_cap_usd', [strategy.min_market_cap_usd, strategy.max_market_cap_usd], `Market cap band ${strategy.min_market_cap_usd != null ? `$${strategy.min_market_cap_usd}` : 'any'} to ${strategy.max_market_cap_usd != null ? `$${strategy.max_market_cap_usd}` : 'any'}.`);
+ }
+ if (strategy.take_profit_pct == null && strategy.trailing_stop_pct == null && raw.exits.max_hold_minutes == null) {
+ raw.exits.take_profit_pct = D.exits.take_profit_pct;
+ assumptions.push(`No upside exit given for the Strategy Object, so take-profit defaults to +${D.exits.take_profit_pct}%.`);
+ }
+ if ((strategy.min_quality_score != null || strategy.max_bundle_score != null || strategy.allowed_categories) && Array.isArray(assumptions)) {
+ assumptions.push('Quality, bundle, and category filters apply to the sniper rule set only; the Strategy Object enforces the research gates listed in the explanations.');
+ }
+ return { config: normalizeStrategyConfig(raw), explanations };
+}
+
// Plain-language fallback description, in case the model didn't return a summary.
function describeStrategy(s) {
const parts = [];
@@ -336,6 +450,9 @@ function heuristicCompile(text) {
out.max_hold_seconds = Math.round(s);
}
+ const impact = t.match(/(\d+(?:\.\d+)?)\s*%\s*(?:max(?:imum)?\s*)?(?:price\s*)?impact|(?:price\s*)?impact\D{0,12}?(\d+(?:\.\d+)?)\s*%/);
+ if (impact) out.max_price_impact_pct = parseFloat(impact[1] || impact[2]);
+
const slip = t.match(/(\d+(?:\.\d+)?)\s*%?\s*slippage|slippage\D{0,8}(\d+(?:\.\d+)?)\s*%/);
if (slip) out.slippage_pct = parseFloat(slip[1] || slip[2]);
@@ -358,5 +475,18 @@ function heuristicCompile(text) {
}
if (out.allowed_categories) out.trigger = 'intel_confirmed';
+ // research gates (Strategy Object): these don't need the intel trigger
+ const holders = t.match(/(?:at least|min(?:imum)?|>=?|over|more than)\s*(\d[\d,]*)\s*holders?|(\d[\d,]*)\+\s*holders?/);
+ if (holders) out.min_holders = parseInt((holders[1] || holders[2]).replace(/,/g, ''), 10);
+ const liq = t.match(/(\d+(?:\.\d+)?)\s*sol\s*(?:of\s*)?liquidity|liquidity\D{0,16}?(\d+(?:\.\d+)?)\s*sol/);
+ if (liq) out.min_liquidity_sol = parseFloat(liq[1] || liq[2]);
+ const secScore = t.match(/(?:security|safety|firewall|rug)\s*score\D{0,10}?(\d+)/);
+ if (secScore) out.security_min_score = parseInt(secScore[1], 10);
+ if (/(?:renounced|revoked|no)\s*mint(?:\s*authority)?|mint\s*authority\s*(?:renounced|revoked|disabled)/.test(t)) out.require_no_mint_authority = true;
+ if (/(?:renounced|revoked|no)\s*freeze(?:\s*authority)?|freeze\s*authority\s*(?:renounced|revoked|disabled)/.test(t)) out.require_no_freeze_authority = true;
+ if (/(?:three\.ws|threews|platform)\s*launch/.test(t)) out.sources = ['three_ws_launch'];
+ if (/\bauto(?:matically)?\b|without asking|no approval|don'?t ask/.test(t)) out.mode = 'auto';
+ else if (/\bask (?:me|first)|approval|approve each|confirm each/.test(t)) out.mode = 'ask';
+
return out;
}
diff --git a/api/_lib/strategy-preview.js b/api/_lib/strategy-preview.js
new file mode 100644
index 000000000..a071cc71d
--- /dev/null
+++ b/api/_lib/strategy-preview.js
@@ -0,0 +1,264 @@
+// Strategy match preview: "how many recent launches would this strategy have
+// bought?" answered from real recorded history, never a guess.
+//
+// The Strategy Lab calls this on every slider change. It replays the launches
+// the intel engine recorded over the last 1, 6, or 24 hours through the SAME two
+// pure functions the live equipped-strategy runtime runs before a buy:
+// `matchesEntry` (entry filter) and `evaluateResearchGates` (research gates), and
+// counts how many coins each check removed.
+//
+// The history is read once per (network, window) and cached for a short TTL, so
+// dragging a slider re-evaluates in memory instead of re-querying.
+//
+// Where history stands in for a live reading, the substitution is explicit:
+// holders unique buyers recorded during the intel observation window
+// largest holder intel concentration_top1 (share of net buys, curve excluded)
+// liquidity net SOL bought into the curve during observation
+// market cap derived from that liquidity with the pump.fun curve constants
+// dev history the creator's launches recorded before this coin (+1 for the
+// coin itself, matching the live count), and how many graduated
+// dev sold intel dev_sold
+// security score, the latest recorded firewall decision for the coin, when one
+// authorities exists. Most coins were never assessed, so those coins are
+// counted as "checked live at buy time" rather than matched or
+// blocked: the runtime runs the firewall fresh on every buy.
+// Coins are observed at the end of their intel window, not at the strategy's
+// entry age, so the preview is a calibration aid, not a fill simulation.
+
+import { sql } from './db.js';
+import { solPriceUsd } from './sol-price.js';
+import { matchesEntry, evaluateResearchGates, normalizeStrategyConfig } from './strategy-schema.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+// pump.fun bonding curve: 30 SOL virtual reserve, 1.073B virtual tokens, 1B supply.
+const CURVE_VIRTUAL_SOL = 30;
+const CURVE_K = CURVE_VIRTUAL_SOL * 1_073_000_000;
+const SUPPLY = 1_000_000_000;
+
+export const PREVIEW_WINDOWS = [1, 6, 24];
+const CACHE_TTL_MS = 120_000;
+const MAX_ROWS = 60_000;
+const SAMPLE_SIZE = 8;
+// Checks whose evidence history mostly lacks: an unknown here means "the
+// firewall decides at buy time", not "blocked".
+const LIVE_CHECKS = new Set(['security_min_score', 'require_no_mint_authority', 'require_no_freeze_authority']);
+
+const _cache = new Map();
+
+function num(v) {
+ if (v === null || v === undefined || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+/** Market cap in SOL of a pump.fun curve holding `realSol` SOL of net buys. */
+export function curveMarketCapSol(realSol) {
+ const vSol = CURVE_VIRTUAL_SOL + Math.max(0, realSol);
+ return (vSol * vSol * SUPPLY) / CURVE_K;
+}
+
+/** Estimated price impact (percent) of a `amountSol` buy into a curve holding `realSol`. */
+export function curveImpactPct(amountSol, realSol) {
+ const vSol = CURVE_VIRTUAL_SOL + Math.max(0, realSol);
+ return (amountSol / vSol) * 100;
+}
+
+async function loadHistory(network, hours) {
+ const key = `${network}:${hours}`;
+ const hit = _cache.get(key);
+ if (hit && Date.now() - hit.t < CACHE_TTL_MS) return hit.v;
+ const rows = await sql`
+ WITH recent AS (
+ SELECT mint, creator, first_seen_at, twitter, telegram, website, dev_sold, unique_buyers,
+ buy_volume_lamports, sell_volume_lamports, signals->>'concentration_top1' AS top1
+ FROM pump_coin_intel
+ WHERE network = ${network} AND first_seen_at >= now() - (${hours} || ' hours')::interval
+ ORDER BY first_seen_at DESC
+ LIMIT ${MAX_ROWS}
+ ),
+ hist AS (
+ SELECT i.mint,
+ COUNT(*) OVER w AS launches_prior,
+ COUNT(*) FILTER (WHERE o.graduated) OVER w AS graduated_prior
+ FROM pump_coin_intel i
+ LEFT JOIN pump_coin_outcomes o ON o.mint = i.mint
+ WHERE i.network = ${network}
+ AND i.creator IN (SELECT DISTINCT creator FROM recent WHERE creator IS NOT NULL)
+ WINDOW w AS (PARTITION BY i.creator ORDER BY i.first_seen_at ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
+ ),
+ fw AS (
+ SELECT DISTINCT ON (f.mint) f.mint, f.score,
+ (SELECT c->'detail' FROM jsonb_array_elements(CASE WHEN jsonb_typeof(f.checks) = 'array' THEN f.checks ELSE '[]'::jsonb END) c
+ WHERE c->>'name' = 'mint_authority' LIMIT 1) AS fw_authority
+ FROM firewall_decisions f
+ WHERE f.network = ${network} AND f.side = 'buy' AND f.mint IN (SELECT mint FROM recent)
+ ORDER BY f.mint, f.created_at DESC
+ )
+ SELECT r.*, h.launches_prior, h.graduated_prior, fw.score AS fw_score, fw.fw_authority,
+ (m.mint IS NOT NULL) AS three_ws_launch
+ FROM recent r
+ LEFT JOIN hist h ON h.mint = r.mint
+ LEFT JOIN fw ON fw.mint = r.mint
+ LEFT JOIN pump_agent_mints m ON m.mint = r.mint AND m.network = ${network}
+ `;
+ const solUsd = await solPriceUsd().catch(() => null);
+ const v = { rows, solUsd: num(solUsd), at: new Date().toISOString() };
+ _cache.set(key, { t: Date.now(), v });
+ return v;
+}
+
+// The firewall's mint_authority check detail: { mint_authority, freeze_authority }.
+function authorityFromDetail(detail) {
+ if (!detail || typeof detail !== 'object' || !('mint_authority' in detail) || !('freeze_authority' in detail)) return { known: false };
+ return { known: true, mint_authority: detail.mint_authority, freeze_authority: detail.freeze_authority };
+}
+
+/** Turn one recorded intel row into the (launch, report) pair the live evaluators read. */
+export function historyToCandidate(row, solUsd) {
+ const netSol = Math.max(0, (num(row.buy_volume_lamports) || 0) - (num(row.sell_volume_lamports) || 0)) / LAMPORTS_PER_SOL;
+ const mcSol = curveMarketCapSol(netSol);
+ const launchesPrior = num(row.launches_prior);
+ const graduatedPrior = num(row.graduated_prior);
+ const launch = {
+ mint: row.mint,
+ creator: row.creator,
+ created_at: row.first_seen_at ? new Date(row.first_seen_at).getTime() : null,
+ liquidity_sol: netSol,
+ market_cap_usd: solUsd ? mcSol * solUsd : null,
+ twitter: row.twitter, telegram: row.telegram, website: row.website,
+ creator_launches: launchesPrior == null ? null : launchesPrior + 1,
+ creator_graduated: graduatedPrior,
+ is_usdc_pair: false,
+ three_ws_launch: row.three_ws_launch === true,
+ };
+ const report = historicalGateReport(row, { netSol, marketCapUsd: launch.market_cap_usd });
+ return { launch, report, netSol };
+}
+
+/**
+ * Judge recorded evidence with the live research-gate evaluator. A gate whose
+ * evidence history lacks (security score, authorities) is not a block: the live
+ * runtime runs the firewall fresh at buy time, so it is reported as `live`.
+ * Any other unknown fails closed exactly as it does live.
+ * @returns {{ blocked: string|null, live: boolean, evaluation: object }}
+ */
+export function judgeHistoricalGates(config, report) {
+ const evaluation = evaluateResearchGates(config, report);
+ const hard = evaluation.checks.find((c) => c.status === 'fail' || (c.status === 'unknown' && !LIVE_CHECKS.has(c.check)));
+ return {
+ blocked: hard ? hard.check : null,
+ live: !hard && evaluation.checks.some((c) => c.status === 'unknown'),
+ evaluation,
+ };
+}
+
+/** The research-gate report for a recorded intel row (backtest and preview share it). */
+export function historicalGateReport(row, { netSol, marketCapUsd = null } = {}) {
+ const top1 = num(row.top1 ?? row.signals?.concentration_top1);
+ const launchesPrior = num(row.launches_prior ?? row.creator_launches_prior);
+ const graduatedPrior = num(row.graduated_prior ?? row.creator_graduated_prior);
+ const sol = netSol ?? Math.max(0, (num(row.buy_volume_lamports) || 0) - (num(row.sell_volume_lamports) || 0)) / LAMPORTS_PER_SOL;
+ return {
+ mint: row.mint,
+ liquidity: { sol, market_cap_usd: marketCapUsd },
+ holders: { count: num(row.unique_buyers), top_holder_pct: top1 == null ? null : top1 * 100 },
+ authority: authorityFromDetail(row.fw_authority),
+ security: { score: num(row.fw_score) },
+ dev: {
+ creator: row.creator,
+ launches: launchesPrior == null ? null : launchesPrior + 1,
+ graduated: graduatedPrior,
+ sold: typeof row.dev_sold === 'boolean' ? row.dev_sold : null,
+ },
+ };
+}
+
+const entryReasonKey = (reasons) => String(reasons?.[0] || 'filtered').split(':')[0];
+
+/**
+ * Count how many recorded launches a strategy config would have bought.
+ *
+ * @param {object} rawConfig any Strategy Object config (normalized here)
+ * @param {{ hours?: number, network?: string }} [opts]
+ */
+export async function previewStrategyMatches(rawConfig, { hours = 6, network = 'mainnet' } = {}) {
+ const config = normalizeStrategyConfig(rawConfig);
+ const h = PREVIEW_WINDOWS.includes(Number(hours)) ? Number(hours) : 6;
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const { rows, solUsd, at } = await loadHistory(net, h);
+
+ const amountSol = config.sizing.amount_sol;
+ const impactCap = config.sizing.max_price_impact_bps == null ? null : config.sizing.max_price_impact_bps / 100;
+ const entryRejects = {};
+ const blockedBy = {};
+ let passedEntry = 0;
+ let passedResearch = 0;
+ let liveCheck = 0;
+ let impactBlocked = 0;
+ let matched = 0;
+ const sample = [];
+
+ for (const row of rows) {
+ const { launch, report, netSol } = historyToCandidate(row, solUsd);
+ // Evaluate as if seen the moment it launched: the age gate is a live-timing
+ // rule, and every recorded coin was young when the runtime would have seen it.
+ const entry = matchesEntry(config, launch, launch.created_at ?? Date.now());
+ if (!entry.pass) {
+ const k = entryReasonKey(entry.reasons);
+ entryRejects[k] = (entryRejects[k] || 0) + 1;
+ continue;
+ }
+ passedEntry++;
+ const gate = judgeHistoricalGates(config, report);
+ if (gate.blocked) {
+ blockedBy[gate.blocked] = (blockedBy[gate.blocked] || 0) + 1;
+ continue;
+ }
+ passedResearch++;
+ if (impactCap != null && curveImpactPct(amountSol, netSol) > impactCap) {
+ impactBlocked++;
+ continue;
+ }
+ const pendingLive = gate.live;
+ if (pendingLive) liveCheck++;
+ else matched++;
+ if (sample.length < SAMPLE_SIZE) {
+ sample.push({
+ mint: row.mint,
+ seen_at: row.first_seen_at,
+ holders: report.holders.count,
+ top_holder_pct: report.holders.top_holder_pct == null ? null : Number(report.holders.top_holder_pct.toFixed(1)),
+ liquidity_sol: Number(netSol.toFixed(2)),
+ live_check: pendingLive,
+ });
+ }
+ }
+
+ const caveats = [
+ 'Coins are scored as they stood at the end of their intel observation window, not at your entry age.',
+ 'Holders are unique buyers recorded during observation; the live gate reads the indexer holder count.',
+ 'Liquidity and market cap are derived from net SOL bought into the curve.',
+ ];
+ if (config.research.security_min_score != null || config.research.require_no_mint_authority || config.research.require_no_freeze_authority) {
+ caveats.push('Most coins have no recorded firewall decision, so security and authority gates are counted as checked live at buy time.');
+ }
+ if (rows.length >= MAX_ROWS) caveats.push(`Only the newest ${MAX_ROWS} launches in the window were scanned.`);
+
+ return {
+ network: net,
+ window_hours: h,
+ universe: rows.length,
+ passed_entry: passedEntry,
+ passed_research: passedResearch,
+ impact_blocked: impactBlocked,
+ matched,
+ live_check: liveCheck,
+ would_buy: matched + liveCheck,
+ entry_rejects: entryRejects,
+ blocked_by: blockedBy,
+ sample,
+ sol_usd: solUsd,
+ history_at: at,
+ caveats,
+ };
+}
diff --git a/api/_lib/strategy-research.js b/api/_lib/strategy-research.js
new file mode 100644
index 000000000..540a64e7b
--- /dev/null
+++ b/api/_lib/strategy-research.js
@@ -0,0 +1,253 @@
+// Strategy research gates: the gate report a strategy reads before any buy.
+//
+// A Strategy Object's `research` block (api/_lib/strategy-schema.js) asks real
+// questions about a candidate coin: how many holders, how much does the largest
+// one own, how deep is the liquidity, what does the rug/honeypot firewall score
+// it, are the mint and freeze authorities renounced, and what has the creator
+// done before. This module answers them from the platform's existing readers,
+// never from a guess:
+//
+// identity the launch feed row (name, symbol, creator)
+// liquidity the pump.fun feed's live curve liquidity
+// holders pump_coin_intel (largest holder share of bought supply, recorded
+// by the intel engine) and composeTokenHolders (holder count from
+// the indexer; on-chain top holders with the bonding curve's own
+// token account excluded when intel has no row yet)
+// authority the firewall's SPL mint-account read (authoritative on chain)
+// security assessTradeSafety, the same firewall every buy already passes,
+// run with the agent's real wallet and the strategy's real size
+// dev the creator's launch history (enrichCreatorStats) and whether the
+// dev has sold (pump_coin_intel)
+//
+// Every section carries `source` and `at` so a blocked buy always cites where
+// its numbers came from. The section names match the token report schema
+// (identity, liquidity, holders, authority, security, dev) so a fuller token
+// report can stand in for this one without changing the gate evaluator.
+//
+// Only the sections a strategy actually gates on are fetched, so a strategy with
+// no holder gate never pays for a holder walk.
+
+import { PublicKey } from '@solana/web3.js';
+import { sql } from './db.js';
+import { assessTradeSafety } from './trade-firewall.js';
+import { composeTokenHolders } from './crypto-token-holders.js';
+import { enrichCreatorStats } from './pump-launch-feed.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+
+function num(v) {
+ if (v === null || v === undefined || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+/** Which report sections a normalized config needs, so nothing unused is fetched. */
+export function sectionsNeeded(config, { forApproval = false } = {}) {
+ const g = config?.research || {};
+ const dv = g.dev_history || {};
+ return {
+ holders: g.min_holders != null || g.max_top_holder_pct != null || forApproval,
+ security: g.security_min_score != null || g.require_no_mint_authority || g.require_no_freeze_authority || forApproval,
+ dev: dv.max_launches != null || dv.min_graduated != null || dv.block_dev_sold === true || forApproval,
+ };
+}
+
+async function readIntel(mint, network) {
+ try {
+ const [row] = await sql`
+ SELECT name, symbol, creator, dev_sold, unique_buyers, signals, concentration_top10
+ FROM pump_coin_intel
+ WHERE mint = ${mint} AND network = ${network}
+ LIMIT 1
+ `;
+ return row || null;
+ } catch {
+ return null;
+ }
+}
+
+// The pump.fun bonding curve PDA owns the token account that holds the unsold
+// curve supply. It is the program, not a holder, so it must never count as the
+// "largest holder". Heavy SDK import deferred to the one path that needs it.
+async function bondingCurveOwner(mint) {
+ try {
+ const { bondingCurvePda } = await import('@pump-fun/pump-sdk');
+ return bondingCurvePda(new PublicKey(mint)).toBase58();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Largest-holder share of circulating supply from an on-chain holder list,
+ * excluding the bonding curve. `pct` on each row is share of TOTAL supply, so the
+ * curve's share is removed from the denominator too.
+ */
+export function topHolderPctExcluding(top, excludedOwner) {
+ if (!Array.isArray(top) || !top.length) return null;
+ let curvePct = 0;
+ let best = null;
+ for (const h of top) {
+ const pct = num(h?.pct);
+ if (pct == null) continue;
+ if (excludedOwner && (h.owner === excludedOwner || h.address === excludedOwner)) { curvePct += pct; continue; }
+ if (best == null || pct > best) best = pct;
+ }
+ if (best == null) return null;
+ const circulating = 100 - curvePct;
+ if (!(circulating > 0)) return null;
+ return Math.min(100, (best / circulating) * 100);
+}
+
+async function holdersSection({ mint, intel, deps }) {
+ const at = new Date().toISOString();
+ const fromIntel = num(intel?.signals?.concentration_top1);
+ let count = null;
+ let countSource = null;
+ let topPct = fromIntel != null ? fromIntel * 100 : null;
+ let topSource = fromIntel != null ? 'pump_coin_intel' : null;
+ try {
+ const h = await deps.composeTokenHolders({ address: mint, limit: 20 });
+ if (h?.status === 'ok') {
+ if (h.holderCount != null) { count = h.holderCount; countSource = (h.sources || []).join('+') || 'indexer'; }
+ if (topPct == null) {
+ const curve = await deps.bondingCurveOwner(mint);
+ const pct = topHolderPctExcluding(h.top, curve);
+ if (pct != null) { topPct = pct; topSource = `${(h.sources || []).join('+') || 'solana-rpc'} (bonding curve excluded)`; }
+ }
+ }
+ } catch { /* holder readers down: the fields stay unknown and a holder gate fails closed */ }
+ return {
+ count,
+ top_holder_pct: topPct == null ? null : Number(topPct.toFixed(2)),
+ source: { count: countSource, top_holder_pct: topSource },
+ at,
+ };
+}
+
+async function securitySection({ mint, network, payer, quoteLamports, deps }) {
+ const at = new Date().toISOString();
+ let assessment = null;
+ try {
+ assessment = await deps.assessTradeSafety({
+ network,
+ mint: new PublicKey(mint),
+ side: 'buy',
+ payer: payer ? new PublicKey(payer) : null,
+ quoteAmount: quoteLamports,
+ });
+ } catch {
+ assessment = null;
+ }
+ const authCheck = assessment?.checks?.find((c) => c.name === 'mint_authority');
+ const known = !!authCheck && authCheck.detail && 'mint_authority' in authCheck.detail && 'freeze_authority' in authCheck.detail;
+ return {
+ assessment,
+ authority: {
+ known,
+ mint_authority: known ? authCheck.detail.mint_authority : null,
+ freeze_authority: known ? authCheck.detail.freeze_authority : null,
+ source: 'spl mint account (trade firewall)',
+ at,
+ },
+ security: {
+ score: assessment ? num(assessment.score) : null,
+ verdict: assessment?.verdict || null,
+ simulated: assessment?.simulated === true,
+ reasons: Array.isArray(assessment?.reasons) ? assessment.reasons.slice(0, 5) : [],
+ source: 'trade firewall',
+ at,
+ },
+ };
+}
+
+async function devSection({ launch, intel, deps }) {
+ const at = new Date().toISOString();
+ const l = launch ? { ...launch } : {};
+ if (l.creator && l.creator_launches == null) await deps.enrichCreatorStats(l).catch(() => {});
+ return {
+ creator: l.creator || intel?.creator || null,
+ launches: num(l.creator_launches),
+ graduated: num(l.creator_graduated),
+ sold: intel && typeof intel.dev_sold === 'boolean' ? intel.dev_sold : null,
+ source: { history: l.creator_launches != null ? 'pump.fun creator history' : null, sold: intel ? 'pump_coin_intel' : null },
+ at,
+ };
+}
+
+export function realResearchDeps() {
+ return { composeTokenHolders, assessTradeSafety, enrichCreatorStats, readIntel, bondingCurveOwner };
+}
+
+/**
+ * Build the gate report for one candidate. Never throws: an unreachable reader
+ * leaves its fields null, and the evaluator fails a gate on unknown data closed.
+ *
+ * @param {object} o
+ * @param {object} o.config normalized strategy config
+ * @param {object} o.launch feed launch ({ mint, name, symbol, creator, liquidity_sol, market_cap_usd, creator_launches, creator_graduated })
+ * @param {string} [o.network]
+ * @param {string} [o.payer] the agent wallet address (firewall round trip runs as it)
+ * @param {boolean} [o.forApproval] ask mode: fetch every section so the approval card shows full risk notes
+ * @returns {Promise<{ report: object, assessment: object|null }>}
+ */
+export async function buildGateReport({ config, launch, network = 'mainnet', payer = null, forApproval = false }, deps = realResearchDeps()) {
+ const mint = launch.mint;
+ const need = sectionsNeeded(config, { forApproval });
+ const quoteLamports = BigInt(Math.floor((config?.sizing?.amount_sol || 0) * LAMPORTS_PER_SOL));
+ const intel = await deps.readIntel(mint, network);
+ const at = new Date().toISOString();
+
+ const [holders, sec, dev] = await Promise.all([
+ need.holders ? holdersSection({ mint, intel, deps }) : null,
+ need.security ? securitySection({ mint, network, payer, quoteLamports, deps }) : null,
+ need.dev ? devSection({ launch, intel, deps }) : null,
+ ]);
+
+ const report = {
+ mint,
+ network,
+ generated_at: at,
+ identity: {
+ mint,
+ name: launch.name || intel?.name || null,
+ symbol: launch.symbol || intel?.symbol || null,
+ creator: launch.creator || intel?.creator || null,
+ source: 'pump.fun launch feed',
+ at,
+ },
+ liquidity: {
+ sol: num(launch.liquidity_sol),
+ market_cap_usd: num(launch.market_cap_usd),
+ source: 'pump.fun launch feed',
+ at,
+ },
+ holders: holders || { count: null, top_holder_pct: null, source: null, at: null, skipped: true },
+ authority: sec?.authority || { known: false, mint_authority: null, freeze_authority: null, source: null, at: null, skipped: true },
+ security: sec?.security || { score: null, verdict: null, reasons: [], source: null, at: null, skipped: true },
+ dev: dev || { creator: launch.creator || null, launches: null, graduated: null, sold: null, source: null, at: null, skipped: true },
+ };
+ return { report, assessment: sec?.assessment || null };
+}
+
+/**
+ * Short, owner-facing risk notes for an approval card, built from a gate report
+ * and its evaluation. Plain text only: token names and symbols are untrusted
+ * data, so they never appear in a note.
+ */
+export function riskNotesFromReport(report, evaluation) {
+ const notes = [];
+ const sec = report?.security;
+ if (sec?.score != null) notes.push(`Firewall score ${Math.round(sec.score)}/100 (${sec.verdict || 'unrated'}).`);
+ for (const r of (sec?.reasons || []).slice(0, 3)) notes.push(String(r).slice(0, 160));
+ if (report?.holders?.top_holder_pct != null) notes.push(`Largest holder owns ${report.holders.top_holder_pct}% of bought supply.`);
+ if (report?.holders?.count != null) notes.push(`${report.holders.count} holders.`);
+ if (report?.liquidity?.sol != null) notes.push(`${Number(report.liquidity.sol).toFixed(2)} SOL liquidity on the curve.`);
+ if (report?.dev?.sold === true) notes.push('The creator has already sold.');
+ if (report?.authority?.known && report.authority.mint_authority) notes.push('Mint authority is still active.');
+ if (report?.authority?.known && report.authority.freeze_authority) notes.push('Freeze authority is still active.');
+ for (const c of evaluation?.checks || []) {
+ if (c.status === 'unknown') notes.push(c.reason);
+ }
+ return notes.slice(0, 10);
+}
diff --git a/api/_lib/strategy-schema.js b/api/_lib/strategy-schema.js
index ba669346a..aad7193bb 100644
--- a/api/_lib/strategy-schema.js
+++ b/api/_lib/strategy-schema.js
@@ -12,14 +12,36 @@
// policy — never a way around it. The runtime sizes a buy from `sizing.amount_sol`
// but the trade still passes through the full guard + custody path, so a strategy
// can never exceed the spend leash. Ever.
+//
+// Version 2 adds the strategy settings an owner tunes in the Strategy Lab:
+// entry.sources which launch venues a candidate may come from
+// sizing.max_price_impact_bps a per-strategy price-impact ceiling, applied
+// as min(this, the agent's own breaker)
+// research pre-buy research gates evaluated against a real
+// gate report (holders, top holder, liquidity,
+// firewall security score, authorities, dev history)
+// mode 'auto' buys within caps; 'ask' files an approval
+// request and waits for the owner's explicit yes
+// A v1 config normalizes to v2 losslessly; a config with no mode becomes 'ask',
+// the conservative default (the migration backfills stored rows the same way).
const ENTRY_TRIGGERS = ['new_launch'];
const NETWORKS = ['mainnet', 'devnet'];
+const STRATEGY_MODES = ['auto', 'ask'];
+// Where a candidate can come from. `pump_curve` is any live pump.fun bonding-curve
+// launch; `three_ws_launch` is a coin an agent launched through three.ws
+// (pump_agent_mints), which is also on the curve. An empty list means every
+// source; ['three_ws_launch'] means platform launches only.
+const ENTRY_SOURCES = ['pump_curve', 'three_ws_launch'];
+export const STRATEGY_CONFIG_VERSION = 2;
export const STRATEGY_CONFIG_DEFAULTS = Object.freeze({
+ version: STRATEGY_CONFIG_VERSION,
+ mode: 'ask',
network: 'mainnet',
entry: {
trigger: 'new_launch',
+ sources: [],
max_age_minutes: 60,
min_market_cap_usd: null,
max_market_cap_usd: null,
@@ -32,6 +54,7 @@ export const STRATEGY_CONFIG_DEFAULTS = Object.freeze({
sizing: {
amount_sol: 0.1,
max_slippage_bps: 500,
+ max_price_impact_bps: null,
},
exits: {
take_profit_pct: 100, // +100% = 2x
@@ -43,6 +66,19 @@ export const STRATEGY_CONFIG_DEFAULTS = Object.freeze({
max_concurrent_positions: 3,
cooldown_minutes: 0,
},
+ research: {
+ min_holders: null,
+ max_top_holder_pct: null,
+ min_liquidity_sol: null,
+ security_min_score: null,
+ require_no_mint_authority: false,
+ require_no_freeze_authority: false,
+ dev_history: {
+ max_launches: null,
+ min_graduated: null,
+ block_dev_sold: false,
+ },
+ },
});
// Hard ceilings the schema enforces regardless of input — defensive bounds so a
@@ -60,8 +96,29 @@ const BOUNDS = Object.freeze({
market_cap_usd: { min: 0, max: 1e12 },
liquidity_sol: { min: 0, max: 1e9 },
creator_count: { min: 0, max: 100000 },
+ price_impact_bps: { min: 1, max: 10000 },
+ holders: { min: 0, max: 10000000 },
+ pct: { min: 0, max: 100 },
+ score: { min: 0, max: 100 },
});
+// Owners and the natural-language compiler may write camelCase; the stored
+// shape is snake_case like every other config key. First present key wins.
+function pick(obj, ...keys) {
+ for (const k of keys) if (obj && obj[k] !== undefined) return obj[k];
+ return undefined;
+}
+
+function normalizeSources(v) {
+ if (!Array.isArray(v)) return [];
+ const out = [];
+ for (const raw of v) {
+ const s = String(raw || '').trim().toLowerCase();
+ if (ENTRY_SOURCES.includes(s) && !out.includes(s)) out.push(s);
+ }
+ return out.length === ENTRY_SOURCES.length ? [] : out;
+}
+
function numOrNull(v, { min = -Infinity, max = Infinity } = {}) {
if (v === null || v === undefined || v === '') return null;
const n = Number(v);
@@ -102,27 +159,43 @@ export function normalizeStrategyConfig(raw) {
const s = r.sizing && typeof r.sizing === 'object' ? r.sizing : {};
const x = r.exits && typeof r.exits === 'object' ? r.exits : {};
const k = r.risk && typeof r.risk === 'object' ? r.risk : {};
+ const q = r.research && typeof r.research === 'object' ? r.research : {};
+ const dvRaw = pick(q, 'dev_history', 'devHistory');
+ const dv = dvRaw && typeof dvRaw === 'object' ? dvRaw : {};
const d = STRATEGY_CONFIG_DEFAULTS;
const trigger = ENTRY_TRIGGERS.includes(e.trigger) ? e.trigger : d.entry.trigger;
const network = NETWORKS.includes(r.network) ? r.network : d.network;
+ const mode = STRATEGY_MODES.includes(r.mode) ? r.mode : d.mode;
+
+ // Creator history and liquidity exist both as cheap entry pre-filters (v1)
+ // and as research gates (v2). They are one setting: the research value wins
+ // when present, the legacy entry value fills it otherwise, and both halves are
+ // written back identical so the two evaluators can never disagree.
+ const maxLaunches = intOrNull(pick(dv, 'max_launches', 'maxLaunches') ?? e.max_creator_launches, BOUNDS.creator_count);
+ const minGraduated = intOrNull(pick(dv, 'min_graduated', 'minGraduated') ?? e.min_creator_graduated, BOUNDS.creator_count);
+ const minLiq = numOrNull(pick(q, 'min_liquidity_sol', 'minLiquiditySol') ?? e.min_liquidity_sol, BOUNDS.liquidity_sol);
return {
+ version: STRATEGY_CONFIG_VERSION,
+ mode,
network,
entry: {
trigger,
+ sources: normalizeSources(e.sources),
max_age_minutes: clampNum(e.max_age_minutes, d.entry.max_age_minutes, { ...BOUNDS.max_age_minutes, round: true }),
min_market_cap_usd: numOrNull(e.min_market_cap_usd, BOUNDS.market_cap_usd),
max_market_cap_usd: numOrNull(e.max_market_cap_usd, BOUNDS.market_cap_usd),
- min_liquidity_sol: numOrNull(e.min_liquidity_sol, BOUNDS.liquidity_sol),
+ min_liquidity_sol: minLiq,
require_socials: e.require_socials === true,
- max_creator_launches: intOrNull(e.max_creator_launches, BOUNDS.creator_count),
- min_creator_graduated: intOrNull(e.min_creator_graduated, BOUNDS.creator_count),
+ max_creator_launches: maxLaunches,
+ min_creator_graduated: minGraduated,
require_sol_quote: e.require_sol_quote !== false,
},
sizing: {
amount_sol: clampNum(s.amount_sol, d.sizing.amount_sol, BOUNDS.amount_sol),
max_slippage_bps: clampNum(s.max_slippage_bps, d.sizing.max_slippage_bps, { ...BOUNDS.max_slippage_bps, round: true }),
+ max_price_impact_bps: intOrNull(pick(s, 'max_price_impact_bps', 'maxPriceImpactBps'), BOUNDS.price_impact_bps),
},
exits: {
take_profit_pct: numOrNull(x.take_profit_pct, BOUNDS.take_profit_pct),
@@ -135,9 +208,57 @@ export function normalizeStrategyConfig(raw) {
max_concurrent_positions: clampNum(k.max_concurrent_positions, d.risk.max_concurrent_positions, { ...BOUNDS.max_concurrent_positions, round: true }),
cooldown_minutes: clampNum(k.cooldown_minutes, d.risk.cooldown_minutes, { ...BOUNDS.cooldown_minutes, round: true }),
},
+ research: {
+ min_holders: intOrNull(pick(q, 'min_holders', 'minHolders'), BOUNDS.holders),
+ max_top_holder_pct: numOrNull(pick(q, 'max_top_holder_pct', 'maxTopHolderPct'), BOUNDS.pct),
+ min_liquidity_sol: minLiq,
+ security_min_score: intOrNull(pick(q, 'security_min_score', 'securityMinScore'), BOUNDS.score),
+ require_no_mint_authority: pick(q, 'require_no_mint_authority', 'requireNoMintAuthority') === true,
+ require_no_freeze_authority: pick(q, 'require_no_freeze_authority', 'requireNoFreezeAuthority') === true,
+ dev_history: {
+ max_launches: maxLaunches,
+ min_graduated: minGraduated,
+ block_dev_sold: pick(dv, 'block_dev_sold', 'blockDevSold') === true,
+ },
+ },
};
}
+/** True when any research gate is switched on (the runtime skips the report otherwise). */
+export function researchGatesActive(config) {
+ const g = config?.research;
+ if (!g) return false;
+ const dv = g.dev_history || {};
+ return g.min_holders != null || g.max_top_holder_pct != null || g.min_liquidity_sol != null
+ || g.security_min_score != null || g.require_no_mint_authority || g.require_no_freeze_authority
+ || dv.max_launches != null || dv.min_graduated != null || dv.block_dev_sold === true;
+}
+
+/**
+ * The effective price-impact ceiling in percent for one strategy trade: the
+ * tighter of the agent's breaker and the strategy's own max_price_impact_bps.
+ * A strategy can only tighten the agent's limit, never loosen it.
+ */
+export function effectivePriceImpactPct(config, agentMaxPct) {
+ const own = config?.sizing?.max_price_impact_bps;
+ const ownPct = own == null ? null : own / 100;
+ const agent = agentMaxPct == null || !Number.isFinite(Number(agentMaxPct)) ? null : Number(agentMaxPct);
+ if (ownPct == null) return agent;
+ if (agent == null) return ownPct;
+ return Math.min(ownPct, agent);
+}
+
+/**
+ * The sources one launch belongs to, for the entry.sources filter. The live feed
+ * only carries bonding-curve coins (graduated ones are dropped upstream), so
+ * every candidate is `pump_curve`; a three.ws agent launch is also tagged.
+ */
+export function launchSources(launch) {
+ const out = ['pump_curve'];
+ if (launch?.three_ws_launch === true) out.push('three_ws_launch');
+ return out;
+}
+
/**
* Validate a strategy config. Returns { valid, errors:[{field,message}], config }.
* `config` is the normalized form (safe to persist). Errors are human-readable
@@ -163,6 +284,15 @@ export function validateStrategyConfig(raw) {
if (config.exits.take_profit_pct == null && config.exits.trailing_stop_pct == null && config.exits.max_hold_minutes == null) {
errors.push({ field: 'exits', message: 'Define at least one upside exit: take-profit, trailing stop, or max hold.' });
}
+ const rawMode = raw && typeof raw === 'object' ? raw.mode : undefined;
+ if (rawMode !== undefined && rawMode !== null && !STRATEGY_MODES.includes(rawMode)) {
+ errors.push({ field: 'mode', message: 'Mode must be "auto" (buy within caps) or "ask" (request approval for each buy).' });
+ }
+ const rawSources = raw?.entry?.sources;
+ if (Array.isArray(rawSources)) {
+ const bad = rawSources.filter((x) => !ENTRY_SOURCES.includes(String(x || '').trim().toLowerCase()));
+ if (bad.length) errors.push({ field: 'entry.sources', message: `Unknown source: ${bad.map(String).join(', ')}. Use ${ENTRY_SOURCES.join(', ')}.` });
+ }
return { valid: errors.length === 0, errors, config };
}
@@ -201,6 +331,14 @@ export function matchesEntry(config, launch, nowMs) {
return { pass: false, reasons: ['quote_not_sol'] };
}
+ // Source filter: the candidate must come from at least one allowed venue.
+ if (Array.isArray(e.sources) && e.sources.length) {
+ const have = launchSources(launch);
+ if (!have.some((src) => e.sources.includes(src))) {
+ return { pass: false, reasons: [`source_excluded:${have.join('+')}`] };
+ }
+ }
+
const mc = numOrNull(launch.market_cap_usd);
if (e.min_market_cap_usd != null) {
if (mc == null || mc < e.min_market_cap_usd) return { pass: false, reasons: [`mc_below_min:${mc ?? 'n/a'}`] };
@@ -235,6 +373,103 @@ export function matchesEntry(config, launch, nowMs) {
return { pass: true, reasons };
}
+// Plain-language labels for each research check, shared by the runtime's
+// decision log, the Lab's block breakdown, and the compiler's explanations.
+export const RESEARCH_CHECK_LABELS = Object.freeze({
+ min_holders: 'Minimum holders',
+ max_top_holder_pct: 'Largest holder share',
+ min_liquidity_sol: 'Minimum liquidity',
+ security_min_score: 'Firewall security score',
+ require_no_mint_authority: 'Mint authority renounced',
+ require_no_freeze_authority: 'Freeze authority renounced',
+ dev_max_launches: 'Creator launch count',
+ dev_min_graduated: 'Creator graduations',
+ dev_block_sold: 'Creator has not sold',
+});
+
+const NUMBER_FORMATS = new Map();
+function fmt(v, digits = 2) {
+ if (v == null) return 'unknown';
+ let f = NUMBER_FORMATS.get(digits);
+ if (!f) NUMBER_FORMATS.set(digits, (f = new Intl.NumberFormat('en-US', { maximumFractionDigits: digits })));
+ return f.format(Number(v));
+}
+
+/**
+ * Evaluate a strategy's research gates against a gate report. Pure + sync.
+ *
+ * Fail closed: a gate the owner switched on whose data the report could not
+ * establish blocks the buy with an "unknown" reason. A research gate exists to
+ * prove something about a coin before money moves, so "could not check" is
+ * never treated as "passed". Gates left off are reported with status 'off'.
+ *
+ * @param {object} config normalized strategy config
+ * @param {object} report gate report (api/_lib/strategy-research.js#buildGateReport):
+ * { holders:{count, top_holder_pct}, liquidity:{sol}, security:{score},
+ * authority:{known, mint_authority, freeze_authority},
+ * dev:{launches, graduated, sold} }
+ * @returns {{ pass:boolean, blocked_by:Array, checks:Array }}
+ * each check: { check, label, status:'pass'|'fail'|'unknown'|'off', actual, required, reason }
+ */
+export function evaluateResearchGates(config, report) {
+ const g = config?.research || STRATEGY_CONFIG_DEFAULTS.research;
+ const dv = g.dev_history || {};
+ const r = report || {};
+ const checks = [];
+
+ const add = (check, required, actual, ok, reason) => {
+ let status;
+ if (required == null || required === false) status = 'off';
+ else if (actual == null) status = 'unknown';
+ else status = ok ? 'pass' : 'fail';
+ // Reasons are built only for checks that ran: the match preview replays tens
+ // of thousands of coins through this function, and number formatting is slow.
+ let why = null;
+ if (status === 'unknown') why = `${RESEARCH_CHECK_LABELS[check]} could not be verified, so the buy is held back.`;
+ else if (status !== 'off') why = reason();
+ checks.push({ check, label: RESEARCH_CHECK_LABELS[check], status, actual: actual ?? null, required: required === false ? null : required, reason: why });
+ };
+
+ const holders = numOrNull(r.holders?.count);
+ add('min_holders', g.min_holders, holders, holders != null && holders >= g.min_holders,
+ () => `${fmt(holders, 0)} holders against a minimum of ${fmt(g.min_holders, 0)}.`);
+
+ const top = numOrNull(r.holders?.top_holder_pct);
+ add('max_top_holder_pct', g.max_top_holder_pct, top, top != null && top <= g.max_top_holder_pct,
+ () => `The largest holder owns ${fmt(top, 1)}% against a ceiling of ${fmt(g.max_top_holder_pct, 1)}%.`);
+
+ const liq = numOrNull(r.liquidity?.sol);
+ add('min_liquidity_sol', g.min_liquidity_sol, liq, liq != null && liq >= g.min_liquidity_sol,
+ () => `${fmt(liq)} SOL of liquidity against a minimum of ${fmt(g.min_liquidity_sol)} SOL.`);
+
+ const score = numOrNull(r.security?.score);
+ add('security_min_score', g.security_min_score, score, score != null && score >= g.security_min_score,
+ () => `Firewall score ${fmt(score, 0)}/100 against a minimum of ${fmt(g.security_min_score, 0)}.`);
+
+ const authKnown = r.authority?.known === true;
+ const mintAuth = authKnown ? (r.authority.mint_authority ? 'active' : 'renounced') : null;
+ add('require_no_mint_authority', g.require_no_mint_authority || null, mintAuth, mintAuth === 'renounced',
+ () => mintAuth === 'active' ? 'The creator can still mint new supply.' : 'Mint authority is renounced.');
+ const freezeAuth = authKnown ? (r.authority.freeze_authority ? 'active' : 'renounced') : null;
+ add('require_no_freeze_authority', g.require_no_freeze_authority || null, freezeAuth, freezeAuth === 'renounced',
+ () => freezeAuth === 'active' ? 'The creator can freeze holder accounts, so a buy might never sell.' : 'Freeze authority is renounced.');
+
+ const launches = numOrNull(r.dev?.launches);
+ add('dev_max_launches', dv.max_launches, launches, launches != null && launches <= dv.max_launches,
+ () => `The creator has launched ${fmt(launches, 0)} coins against a ceiling of ${fmt(dv.max_launches, 0)}.`);
+ const grads = numOrNull(r.dev?.graduated);
+ add('dev_min_graduated', dv.min_graduated, grads, grads != null && grads >= dv.min_graduated,
+ () => `The creator has graduated ${fmt(grads, 0)} coins against a minimum of ${fmt(dv.min_graduated, 0)}.`);
+ const sold = typeof r.dev?.sold === 'boolean' ? (r.dev.sold ? 'sold' : 'holding') : null;
+ add('dev_block_sold', dv.block_dev_sold || null, sold, sold === 'holding',
+ () => sold === 'sold' ? 'The creator has already sold their own allocation.' : 'The creator has not sold.');
+
+ const blocked_by = checks
+ .filter((c) => c.status === 'fail' || c.status === 'unknown')
+ .map(({ check, label, status, actual, required, reason }) => ({ check, label, status, actual, required, reason }));
+ return { pass: blocked_by.length === 0, blocked_by, checks };
+}
+
/**
* Decide whether an open position should exit, given a live re-quote. Pure.
* Returns { exit, reason } — reason ∈ take_profit|stop_loss|trailing_stop|timeout.
@@ -274,4 +509,4 @@ export function shouldExit(config, pos, currentValueLamports, nowMs) {
return { exit: false, reason: null };
}
-export { ENTRY_TRIGGERS, NETWORKS };
+export { ENTRY_TRIGGERS, NETWORKS, STRATEGY_MODES, ENTRY_SOURCES };
diff --git a/api/_lib/wallet-intents.js b/api/_lib/wallet-intents.js
index 0a09ecccf..d240212ce 100644
--- a/api/_lib/wallet-intents.js
+++ b/api/_lib/wallet-intents.js
@@ -38,6 +38,7 @@ import {
updateCustodyEvent,
validateSolanaAddress,
lamportsToUsd,
+ countPriorSpendsTo,
SOL_FEE_HEADROOM_LAMPORTS,
} from './agent-trade-guards.js';
import { THREE_MINT } from './networth-model.js';
@@ -45,6 +46,7 @@ import { XAI_CHAT_COMPLETIONS_URL, GROK_BUDGET_MODEL, GROK_BUDGET_EXTRA_BODY } f
import { resolveSolanaRecipient } from '../../src/solana/sns.js';
import { recentPumpLaunches, enrichCreatorStats } from './pump-launch-feed.js';
import { logAudit } from './audit.js';
+import { createApprovalRequest, runApproved, TTL_MS } from './approvals.js';
import { getCreditAccount } from './credits.js';
import { topupFromIntent, normalizeTopupAmount, TopupError } from './inference-topup.js';
@@ -844,10 +846,24 @@ async function gatedSpend({ ctx, intent, discriminator, category, usd, lamports,
// ceiling, anomaly, capability) and gives a fast, specific pause message. Its
// daily-cap read is advisory only; the binding daily check is the atomic claim
// below, which reserves headroom in the same statement that writes the row.
+ //
+ // A policy step-up ("ask me first") does not dead-end here: it queues the
+ // exact action in the owner's approval inbox (api/_lib/approvals.js), and an
+ // approval re-enters this function with ctx.approval set, which lifts only that
+ // step-up. Every cap in this function still applies on the approved run.
try {
- await enforceSpendLimit({ agentId, meta: ctx.meta, category: 'intent', usdValue: usd, network });
+ await enforceSpendLimit({
+ agentId, meta: ctx.meta, category: 'intent', usdValue: usd, network,
+ destination: rowMeta.destination || undefined,
+ stepUpApproved: Boolean(ctx.approval),
+ });
} catch (e) {
- if (e instanceof SpendLimitError) return { status: 'paused', note: e.message, usd };
+ if (e instanceof SpendLimitError) {
+ if (e.code === 'policy_step_up' && !dryRun && !ctx.approval) {
+ return requestIntentApproval({ ctx, intent, discriminator, category, usd, lamports, rowMeta, gateReason: e.message, doSpend });
+ }
+ return { status: 'paused', note: e.message, usd };
+ }
throw e;
}
@@ -898,7 +914,7 @@ async function gatedSpend({ ctx, intent, discriminator, category, usd, lamports,
(agent_id, user_id, event_type, category, network, asset, amount_lamports, usd, status, idempotency_key, meta)
SELECT ${agentId}, ${userId ?? ownerId ?? null}, 'spend', ${category}, ${network}, 'SOL',
${lamports != null ? String(lamports) : null}, ${usd ?? null}, 'pending', ${idemKey},
- ${JSON.stringify({ ...rowMeta, intent_id: intent.id, intent_title: intent.title, trigger: intent.trigger?.type, action: intent.action?.type })}::jsonb
+ ${JSON.stringify({ ...rowMeta, intent_id: intent.id, intent_title: intent.title, trigger: intent.trigger?.type, action: intent.action?.type, ...(ctx.approval ? { approval_id: ctx.approval.id } : {}) })}::jsonb
FROM wallet_day, rule_day, rule_life, locked
WHERE NOT EXISTS (SELECT 1 FROM agent_custody_events WHERE agent_id = ${agentId} AND idempotency_key = ${idemKey})
AND (${dailyUsd}::float8 IS NULL OR wallet_day.s + ${usd}::float8 <= ${dailyUsd}::float8 + 1e-9)
@@ -919,6 +935,111 @@ async function gatedSpend({ ctx, intent, discriminator, category, usd, lamports,
}
}
+function shortKey(a) {
+ const s = String(a || '');
+ return s.length > 12 ? `${s.slice(0, 4)}...${s.slice(-4)}` : s;
+}
+
+// Queue a step-up-gated spend in the owner's approval inbox. The payload is
+// everything executeApprovedIntentAction needs to run THIS action and nothing
+// else; its hash is what the owner approves. An auto-approve policy that covers
+// it runs it inline, under the same caps, without asking.
+async function requestIntentApproval({ ctx, intent, discriminator, category, usd, lamports, rowMeta, gateReason, doSpend }) {
+ const isSwap = Boolean(rowMeta.mint);
+ const sol = Number(lamports) / 1e9;
+ const solText = sol.toLocaleString('en-US', { maximumFractionDigits: 6 });
+ const who = ctx.agentName || 'Your agent';
+ const destination = rowMeta.destination || null;
+ const payload = {
+ v: 1,
+ source: 'wallet_intent',
+ agent_id: ctx.agentId,
+ intent_id: intent.id,
+ action_type: intent.action.type,
+ category,
+ network: ctx.network,
+ discriminator,
+ lamports: String(lamports),
+ destination,
+ destination_label: rowMeta.destination_label || null,
+ mint: rowMeta.mint || null,
+ slippage_bps: rowMeta.slippage_bps ?? null,
+ };
+ const riskNotes = [`Rule: "${intent.title}"`];
+ let autoApprovable = true;
+ if (isSwap) {
+ riskNotes.push(`Swaps SOL into token ${rowMeta.mint}. Check the mint before approving.`);
+ if (rowMeta.slippage_bps != null) riskNotes.push(`Max slippage ${(rowMeta.slippage_bps / 100).toFixed(1)}%. The price is re-quoted when you approve.`);
+ } else {
+ const priors = await countPriorSpendsTo(ctx.agentId, destination, ctx.network).catch(() => 0);
+ if (priors === 0) {
+ autoApprovable = false;
+ riskNotes.push('This wallet has never paid this address before. Payments on Solana cannot be reversed.');
+ } else {
+ riskNotes.push(`This wallet has paid this address ${priors} time${priors === 1 ? '' : 's'} before.`);
+ }
+ }
+ if (ctx.network !== 'mainnet') riskNotes.push(`Runs on Solana ${ctx.network}.`);
+
+ const ref = `${intent.id}:${destination || rowMeta.mint || 'self'}`;
+ let created;
+ try {
+ created = await createApprovalRequest({
+ userId: ctx.ownerId,
+ agentId: ctx.agentId,
+ source: 'wallet_intent',
+ sourceRef: ref,
+ actionType: intent.action.type,
+ venue: isSwap ? 'jupiter' : 'wallet_transfer',
+ payload,
+ summary: isSwap
+ ? `${who} wants to buy ${shortKey(rowMeta.mint)} with ${solText} SOL`
+ : `${who} wants to send ${solText} SOL to ${rowMeta.destination_label || shortKey(destination)}`,
+ amount: sol,
+ amountUsd: Number.isFinite(usd) ? Math.round(usd * 100) / 100 : null,
+ asset: 'SOL',
+ chain: 'solana',
+ network: ctx.network,
+ recipient: isSwap ? ctx.address : destination,
+ recipientLabel: isSwap ? `${who}'s own wallet (swap)` : (rowMeta.destination_label || null),
+ riskNotes,
+ gateReason,
+ idempotencyKey: `wallet_intent:${intent.id}:${discriminator}`,
+ ttlMs: isSwap ? TTL_MS.swap : TTL_MS.transfer,
+ autoApprovable,
+ });
+ } catch (e) {
+ return { status: 'paused', note: `${gateReason} (could not queue the approval: ${(e?.message || 'error').slice(0, 120)})`, usd };
+ }
+ const req = created.request;
+
+ if (created.autoApproved) {
+ const { outcome } = await runApproved(req, () => gatedSpend({
+ ctx: { ...ctx, approval: { id: req.id, auto: true } },
+ intent, discriminator, category, usd, lamports, rowMeta, doSpend,
+ }));
+ return outcome || { status: 'skipped', note: 'already handled through the approval inbox', usd };
+ }
+
+ switch (req.status) {
+ case 'pending':
+ return {
+ status: 'awaiting_approval',
+ note: created.created
+ ? `Waiting for your approval: ${req.summary}. Approve or deny it at /approvals.`
+ : 'Waiting on your answer to an earlier approval request for this rule at /approvals.',
+ usd,
+ approval_id: req.id,
+ };
+ case 'denied':
+ return { status: 'paused', note: 'You denied this action in the approval inbox.', usd, approval_id: req.id };
+ case 'expired':
+ return { status: 'paused', note: 'The approval request for this action expired unanswered, so nothing was sent.', usd, approval_id: req.id };
+ default:
+ return { status: 'skipped', note: 'already handled through the approval inbox', usd, approval_id: req.id };
+ }
+}
+
// Real SOL transfer from the agent's wallet → destination.
async function transferSol({ ctx, intent, discriminator, category, lamports, rowMeta }) {
if (lamports <= 0n) return { status: 'skipped', note: 'amount rounds to zero' };
@@ -934,16 +1055,17 @@ async function transferSol({ ctx, intent, discriminator, category, lamports, row
}
// Real SOL → token swap (Jupiter, mainnet) for buy/snipe.
-async function buyToken({ ctx, intent, discriminator, mint, lamports, slippagePct }) {
+async function buyToken({ ctx, intent, discriminator, mint, lamports, slippagePct, slippageBps: fixedBps = null }) {
if (ctx.network !== 'mainnet') return { status: 'skipped', note: 'buys/snipes are mainnet-only — this wallet is on devnet' };
if (lamports <= 0n) return { status: 'skipped', note: 'amount rounds to zero' };
if ((ctx.balanceLamports - SOL_FEE_HEADROOM_LAMPORTS) < lamports) return { status: 'skipped', note: 'not enough SOL after the fee buffer' };
const usd = await lamportsToUsd(lamports).catch(() => null);
if (usd == null) return { status: 'paused', note: 'SOL/USD price feed unavailable — will retry' };
- const slippageBps = Math.round(clamp(slippagePct ?? 5, 0, 50) * 100);
+ // An approved request replays the exact slippage the owner was shown.
+ const slippageBps = fixedBps != null ? Math.round(clamp(Number(fixedBps), 0, 5000)) : Math.round(clamp(slippagePct ?? 5, 0, 50) * 100);
return gatedSpend({
ctx, intent, discriminator, category: intent.action.type === 'snipe' ? 'snipe' : 'trade', usd, lamports,
- rowMeta: { action: intent.action.type, mint },
+ rowMeta: { action: intent.action.type, mint, slippage_bps: slippageBps },
doSpend: async (lams) => {
const res = await swapSolToToken({ keypair: ctx.keypair, lamports: lams, outputMint: mint, slippageBps, network: ctx.network, conn: ctx.conn });
return { signature: res.signature };
@@ -1153,6 +1275,50 @@ async function stampFire(intent, res, now = new Date()) {
`;
}
+// ── approval inbox executor ─────────────────────────────────────────────────────
+
+/**
+ * Run the exact action an owner approved in the inbox (api/_lib/approvals.js
+ * registers this as the `wallet_intent` executor). Only the stored payload is
+ * executed: the same amount in lamports, the same recipient or mint, the same
+ * slippage, under the same custody idempotency key the gated fire would have
+ * used, so an approval can never move funds twice for one event. The intent's
+ * own caps and every wallet ceiling still apply; only the step-up the owner
+ * answered is lifted.
+ *
+ * @param {object} row the approval_requests row, already claimed as executing
+ * @returns {Promise<{ status: string, note?: string, signature?: string, usd?: number }>}
+ */
+export async function executeApprovedIntentAction(row) {
+ const p = row.payload || {};
+ const intent = await getIntent(p.agent_id, p.intent_id);
+ if (!intent) return { status: 'error', note: 'The rule behind this request was deleted, so nothing was executed.' };
+ if (intent.action.type !== p.action_type) return { status: 'error', note: 'The rule changed after this request was made, so nothing was executed.' };
+ let lamports;
+ try { lamports = BigInt(p.lamports); } catch { return { status: 'error', note: 'The approved amount is unreadable, so nothing was executed.' }; }
+
+ const built = await buildExecContext({ agentId: p.agent_id, userId: row.user_id, network: p.network || 'mainnet', dryRun: false, needsKey: true });
+ if (built.error) return { status: 'error', note: `Could not execute: ${built.detail || built.error}` };
+ const ctx = built.ctx;
+ if (String(ctx.ownerId) !== String(row.user_id)) return { status: 'error', note: 'This agent is no longer owned by the account that approved it, so nothing was executed.' };
+ ctx.discriminator = p.discriminator;
+ ctx.approval = { id: row.id };
+
+ let res;
+ try {
+ res = p.mint
+ ? await buyToken({ ctx, intent, discriminator: p.discriminator, mint: p.mint, lamports, slippageBps: p.slippage_bps })
+ : await transferSol({
+ ctx, intent, discriminator: p.discriminator, category: p.category, lamports,
+ rowMeta: { action: p.action_type, destination: p.destination, destination_label: p.destination_label || undefined },
+ });
+ } catch (e) {
+ res = { status: 'error', note: (e?.message || 'failed').slice(0, 240) };
+ }
+ await stampFire(intent, res, ctx.now).catch(() => {});
+ return res;
+}
+
// ── public entrypoints ─────────────────────────────────────────────────────────────
/**
diff --git a/api/agents/agent-strategy-objects.js b/api/agents/agent-strategy-objects.js
index 02cb296cb..1d614ba67 100644
--- a/api/agents/agent-strategy-objects.js
+++ b/api/agents/agent-strategy-objects.js
@@ -11,6 +11,11 @@
// POST /api/agents/:id/strategies/kill toggle the per-owner global kill switch (owner)
// POST /api/agents/:id/strategies/sweep evaluate this agent's equips now (owner "Run now")
// POST /api/agents/:id/strategies/close force-close ONE open position now { position_id } (owner "Sell now")
+// POST /api/agents/:id/strategies/mode switch one equip between auto and ask { equip_id, mode } (owner)
+// GET /api/agents/:id/strategies/decisions candidate decision log: which check blocked or bought what (owner)
+// GET /api/agents/:id/strategies/approvals ask-mode approval requests (owner) ?status=pending
+// POST /api/agents/:id/strategies/approve approve one request { approval_id, payload_hash } (owner, executes once)
+// POST /api/agents/:id/strategies/deny deny one request { approval_id } (owner)
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { assertBearerMaySpend } from '../_lib/spend-scope.js';
@@ -22,7 +27,13 @@ import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { isUuid } from '../_lib/validate.js';
import { logAudit } from '../_lib/audit.js';
import { normalizeStrategyConfig } from '../_lib/strategy-schema.js';
-import { evaluateEquip, recentPumpLaunchesSafe, closeStrategyPositionNow } from '../_lib/agent-strategy-runtime.js';
+import {
+ evaluateEquip, recentPumpLaunchesSafe, closeStrategyPositionNow, approveStrategyRequest, denyStrategyRequest,
+} from '../_lib/agent-strategy-runtime.js';
+import { listCandidateDecisions, listStrategyApprovals } from '../_lib/strategy-approvals.js';
+
+const DECISIONS = new Set(['blocked', 'approval', 'executed', 'skipped', 'failed']);
+const APPROVAL_STATUSES = new Set(['pending', 'executing', 'executed', 'failed', 'denied', 'expired']);
const NETWORKS = new Set(['mainnet', 'devnet']);
const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');
@@ -298,6 +309,86 @@ async function handleClose(req, res, id) {
return json(res, 200, { data: result.data });
}
+// POST mode — switch one equipped strategy between auto (buy within caps) and ask
+// (file an approval for every buy). Going to auto arms autonomous buying, so it
+// needs the real-funds agreement; going to ask never does.
+async function handleMode(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ const body = await readJson(req).catch(() => ({}));
+ if (!isUuid(body?.equip_id)) return error(res, 400, 'validation_error', 'equip_id required');
+ if (body.mode !== 'auto' && body.mode !== 'ask') return error(res, 400, 'validation_error', 'mode must be "auto" or "ask"');
+ const [target] = await sql`SELECT network, config_snapshot FROM agent_strategy_equips WHERE id = ${body.equip_id} AND agent_id = ${id}`;
+ if (!target) return error(res, 404, 'not_found', 'equip not found');
+ if (body.mode === 'auto') {
+ if (!(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(target.network), context: 'strategy' }))) return;
+ }
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const snapshot = normalizeStrategyConfig({ ...(target.config_snapshot || {}), mode: body.mode });
+ await sql`UPDATE agent_strategy_equips SET config_snapshot = ${JSON.stringify(snapshot)}::jsonb, updated_at = now() WHERE id = ${body.equip_id} AND agent_id = ${id}`;
+ logAudit({ userId: owned.auth.userId, action: 'strategy.mode', resourceId: id, meta: { equip_id: body.equip_id, mode: body.mode } });
+ return json(res, 200, { data: { equip_id: body.equip_id, mode: body.mode } });
+}
+
+async function handleDecisions(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const url = new URL(req.url, 'http://x');
+ const decision = DECISIONS.has(url.searchParams.get('decision')) ? url.searchParams.get('decision') : null;
+ const rows = await listCandidateDecisions({ agentId: id, ownerId: owned.auth.userId, decision, limit: url.searchParams.get('limit') });
+ return json(res, 200, { data: { decisions: rows } });
+}
+
+async function handleApprovals(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const url = new URL(req.url, 'http://x');
+ const status = APPROVAL_STATUSES.has(url.searchParams.get('status')) ? url.searchParams.get('status') : null;
+ const rows = await listStrategyApprovals({ agentId: id, ownerId: owned.auth.userId, status, limit: url.searchParams.get('limit') });
+ return json(res, 200, { data: { approvals: rows } });
+}
+
+// POST approve — the owner's explicit yes for one ask-mode buy. Executes the exact
+// stored payload once, through every spend guard, at the moment of approval.
+async function handleApprove(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ const rl = await limits.tradePerUser(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+ const body = await readJson(req).catch(() => ({}));
+ if (!isUuid(body?.approval_id)) return error(res, 400, 'validation_error', 'a valid approval_id is required');
+ const shownHash = typeof body.payload_hash === 'string' ? body.payload_hash : '';
+ if (!/^[0-9a-f]{64}$/.test(shownHash)) return error(res, 400, 'validation_error', 'payload_hash (the hash of the request you reviewed) is required');
+ const [target] = await sql`SELECT network FROM approval_requests WHERE id = ${body.approval_id} AND user_id = ${owned.auth.userId} AND agent_id = ${id}`.catch(() => []);
+ if (!target) return error(res, 404, 'not_found', 'approval request not found');
+ if (!(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(target.network), context: 'strategy' }))) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ let result;
+ try {
+ result = await approveStrategyRequest({ id: body.approval_id, ownerId: owned.auth.userId, agentId: id, shownHash, via: 'web' });
+ } catch (err) {
+ console.error('[agents/strategies] approve failed', body.approval_id, err?.message || err);
+ return error(res, 500, 'internal_error', 'unexpected error executing the approved buy');
+ }
+ if (!result.ok && result.http !== 422) return error(res, result.http || 500, result.code || 'error', result.message || 'could not approve');
+ return json(res, result.http || 200, { data: { approval: result.approval, already: !!result.already, executed: result.ok, code: result.code || null, message: result.message || null } });
+}
+
+async function handleDeny(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const body = await readJson(req).catch(() => ({}));
+ if (!isUuid(body?.approval_id)) return error(res, 400, 'validation_error', 'a valid approval_id is required');
+ const result = await denyStrategyRequest({ id: body.approval_id, ownerId: owned.auth.userId, agentId: id, via: 'web' });
+ if (!result.ok) return error(res, result.http || 500, result.code || 'error', result.message || 'could not deny');
+ return json(res, 200, { data: { approval: result.approval, already: !!result.already } });
+}
+
export default async function handler(req, res, id, action) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
@@ -310,5 +401,10 @@ export default async function handler(req, res, id, action) {
if (req.method === 'POST' && action === 'kill') return handleKill(req, res, id);
if (req.method === 'POST' && action === 'sweep') return handleSweep(req, res, id);
if (req.method === 'POST' && action === 'close') return handleClose(req, res, id);
+ if (req.method === 'POST' && action === 'mode') return handleMode(req, res, id);
+ if (req.method === 'GET' && action === 'decisions') return handleDecisions(req, res, id);
+ if (req.method === 'GET' && action === 'approvals') return handleApprovals(req, res, id);
+ if (req.method === 'POST' && action === 'approve') return handleApprove(req, res, id);
+ if (req.method === 'POST' && action === 'deny') return handleDeny(req, res, id);
return error(res, 404, 'not_found', `unknown strategies route: ${action || req.method}`);
}
diff --git a/api/approvals/[id].js b/api/approvals/[id].js
new file mode 100644
index 000000000..a00d55910
--- /dev/null
+++ b/api/approvals/[id].js
@@ -0,0 +1,60 @@
+// /api/approvals/:id: one approval request.
+//
+// GET ?t=<link token>
+// The request with its confirmation table. With ?t= (the signed deep link
+// every delivery carries) the response also says whether the link still
+// matches the request on file (link_verified / link_problem).
+// POST { decision: 'approve'|'deny', payload_hash, token?, via? }
+// Decide. Approve needs the payload_hash the owner was shown; a mismatch
+// is 409 and nothing runs, an expired request is 410. A repeat approve
+// returns the request's current state with idempotent: true.
+// Session only + CSRF. `via` records the surface: 'web' (default) or
+// 'push' (the service worker's Approve/Deny buttons). Chat and mobile
+// decisions are made server-side by their own gateways.
+//
+// Library + semantics: api/_lib/approvals.js. Doc: docs/approvals.md.
+
+import { getRequestUser, 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 { getApproval, decideApproval, ApprovalError } from '../_lib/approvals.js';
+
+const BROWSER_VIAS = new Set(['web', 'push']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const user = req.method === 'GET' ? await getRequestUser(req) : await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.approvalsUser(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const id = String(req.query?.id || '');
+ try {
+ if (req.method === 'GET') {
+ const token = new URL(req.url, 'http://x').searchParams.get('t');
+ const request = await getApproval(user.id, id, { token });
+ return json(res, 200, { request }, { 'cache-control': 'no-store' });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const body = await readJson(req);
+ const via = BROWSER_VIAS.has(body?.via) ? body.via : 'web';
+ const out = await decideApproval({
+ userId: user.id,
+ id,
+ decision: body?.decision,
+ payloadHash: body?.payload_hash ?? null,
+ token: body?.token || null,
+ via,
+ req,
+ });
+ return json(res, 200, out);
+ } catch (e) {
+ if (e instanceof ApprovalError) return error(res, e.status, e.code, e.message, e.extra);
+ throw e;
+ }
+});
diff --git a/api/approvals/index.js b/api/approvals/index.js
new file mode 100644
index 000000000..54e031d33
--- /dev/null
+++ b/api/approvals/index.js
@@ -0,0 +1,50 @@
+// /api/approvals: the owner's approval inbox.
+//
+// GET ?status=pending|done|denied|expired|all&agent=<uuid>&cursor=&limit=
+// One page of requests, newest first, with per-status counts and the
+// agents that have asked. Session or bearer (read-only).
+// POST { action: 'bulk_deny', ids: [uuid, ...] }
+// Deny many pending requests at once. Session only + CSRF: a decision
+// about the owner's money is never made by a machine credential, which
+// an agent could hold.
+//
+// Library + semantics: api/_lib/approvals.js. Doc: docs/approvals.md.
+
+import { getRequestUser, 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 { listApprovals, bulkDeny, ApprovalError } from '../_lib/approvals.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const user = req.method === 'GET' ? await getRequestUser(req) : await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.approvalsUser(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ try {
+ if (req.method === 'GET') {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const out = await listApprovals(user.id, {
+ group: params.get('status') || 'pending',
+ agentId: params.get('agent') || null,
+ limit: Number.parseInt(params.get('limit') || '30', 10),
+ cursor: params.get('cursor') || null,
+ });
+ return json(res, 200, out, { 'cache-control': 'no-store' });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+ const body = await readJson(req);
+ if (body?.action !== 'bulk_deny') return error(res, 400, 'invalid_action', 'action must be "bulk_deny"');
+ const out = await bulkDeny(user.id, body.ids, { via: 'web', req });
+ return json(res, 200, out);
+ } catch (e) {
+ if (e instanceof ApprovalError) return error(res, e.status, e.code, e.message, e.extra);
+ throw e;
+ }
+});
diff --git a/api/approvals/policies.js b/api/approvals/policies.js
new file mode 100644
index 000000000..24b41d345
--- /dev/null
+++ b/api/approvals/policies.js
@@ -0,0 +1,58 @@
+// /api/approvals/policies: the owner's explicit auto-approve rules.
+//
+// GET every policy on the account, live first.
+// POST { venues, max_usd, agent_id?, team_id?, expires_at?, label? }
+// create one. venues from VENUES in
+// api/_lib/approvals.js; max_usd capped at
+// AUTO_POLICY_MAX_USD.
+// DELETE ?id=<uuid> revoke one (the row stays for the audit trail).
+//
+// With no policy, every gated action asks. Writes are session only + CSRF.
+// Doc: docs/approvals.md.
+
+import { getRequestUser, 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 {
+ listAutoPolicies,
+ createAutoPolicy,
+ revokeAutoPolicy,
+ ApprovalError,
+ VENUES,
+ AUTO_POLICY_MAX_USD,
+} from '../_lib/approvals.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const user = req.method === 'GET' ? await getRequestUser(req) : await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.approvalsUser(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ try {
+ if (req.method === 'GET') {
+ const policies = await listAutoPolicies(user.id);
+ const venues = Object.entries(VENUES).filter(([, v]) => v.auto).map(([key, v]) => ({ key, label: v.label }));
+ return json(res, 200, { policies, venues, max_usd_cap: AUTO_POLICY_MAX_USD }, { 'cache-control': 'no-store' });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ if (req.method === 'POST') {
+ const body = await readJson(req);
+ const policy = await createAutoPolicy(user.id, body || {}, { req });
+ return json(res, 201, { policy });
+ }
+
+ const id = new URL(req.url, 'http://x').searchParams.get('id') || '';
+ const policy = await revokeAutoPolicy(user.id, id, { req });
+ return json(res, 200, { policy });
+ } catch (e) {
+ if (e instanceof ApprovalError) return error(res, e.status, e.code, e.message, e.extra);
+ throw e;
+ }
+});
diff --git a/api/audit-log.js b/api/audit-log.js
index 10f9de9fc..82d792de5 100644
--- a/api/audit-log.js
+++ b/api/audit-log.js
@@ -1,5 +1,7 @@
// GET /api/audit-log — JSON list of the caller's audit events
// GET /api/audit-log?format=csv — CSV download (same data, last 90 days)
+// GET /api/audit-log?action_prefix=approval_ — only actions starting with the
+// prefix (the /approvals page's audit panel). Lowercase letters and _ only.
//
// Backs the "Action log" panel on /dashboard-next/account. Reads from the
// audit_log table populated by api/_lib/audit.js. JSON form is cursor-
@@ -69,12 +71,16 @@ async function handleList(userId, url, res) {
Math.max(1, Number.isFinite(rawLimit) ? rawLimit : DEFAULT_LIMIT),
);
const cursor = decodeCursor(url.searchParams.get('cursor'));
+ // Strict shape, compared with left() rather than LIKE so `_` is literal.
+ const prefixRaw = (url.searchParams.get('action_prefix') || '').trim();
+ const prefix = /^[a-z_]{1,40}$/.test(prefixRaw) ? prefixRaw : null;
const rows = cursor
? await sql`
select id, action, resource_id, meta, ip, user_agent, created_at
from audit_log
where user_id = ${userId}
+ and (${prefix}::text is null or left(action, ${prefix ? prefix.length : 0}) = ${prefix}::text)
and (created_at, id) < (${cursor.iso}::timestamptz, ${cursor.id}::uuid)
order by created_at desc, id desc
limit ${limit + 1}
@@ -83,6 +89,7 @@ async function handleList(userId, url, res) {
select id, action, resource_id, meta, ip, user_agent, created_at
from audit_log
where user_id = ${userId}
+ and (${prefix}::text is null or left(action, ${prefix ? prefix.length : 0}) = ${prefix}::text)
order by created_at desc, id desc
limit ${limit + 1}
`;
diff --git a/api/sniper/backtest.js b/api/sniper/backtest.js
index c6610e03d..10225a288 100644
--- a/api/sniper/backtest.js
+++ b/api/sniper/backtest.js
@@ -2,6 +2,7 @@
* Agent Sniper — historical strategy backtester.
*
* POST /api/sniper/backtest { agent_id, strategy, window_days?, network? }
+ * strategy.research (optional) applies Strategy Object research gates too.
* → honest projected metrics computed from REAL captured history
* (pump_coin_intel ⋈ pump_coin_outcomes), using the same entry gate and
* exit priority the live worker runs. Cached by strategy hash; the snapshot
@@ -20,7 +21,7 @@ import { requireCsrf } from '../_lib/csrf.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { isUuid } from '../_lib/validate.js';
-import { runBacktest, strategyHash, getCachedBacktest, saveBacktest } from '../_lib/strategy-backtest.js';
+import { runBacktest, strategyHash, getCachedBacktest, saveBacktest, sanitizeResearch } from '../_lib/strategy-backtest.js';
const numOrNull = (v) => {
if (v == null || v === '') return null;
@@ -65,6 +66,9 @@ function sanitizeStrategy(raw) {
allowed_categories: Array.isArray(s.allowed_categories)
? s.allowed_categories.map((c) => String(c).toLowerCase()).filter(Boolean)
: null,
+ // Strategy Object v2 research gates (min holders, largest-holder cap,
+ // liquidity, dev history, security), judged by the live evaluator.
+ research: sanitizeResearch(s.research),
};
}
diff --git a/api/strategies.js b/api/strategies.js
index e7eae22c7..7a0805ef4 100644
--- a/api/strategies.js
+++ b/api/strategies.js
@@ -9,6 +9,8 @@
// DELETE /api/strategies/:id soft-delete (owner)
// POST /api/strategies/:id/fork fork into the caller's library (lineage, no wallet access)
// POST /api/strategies/:id/publish toggle published (owner)
+// POST /api/strategies/preview live match preview: how many recent launches a config
+// would have bought, and which check removed the rest
//
// Strategies are NOT free text — every config passes validateStrategyConfig before
// it persists. Performance shown is REAL live performance aggregated from real
@@ -25,6 +27,7 @@ import { limits, clientIp } from './_lib/rate-limit.js';
import { isUuid } from './_lib/validate.js';
import { logAudit } from './_lib/audit.js';
import { validateStrategyConfig, slugifyStrategy } from './_lib/strategy-schema.js';
+import { previewStrategyMatches, PREVIEW_WINDOWS } from './_lib/strategy-preview.js';
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -352,6 +355,27 @@ async function handlePublish(req, res, auth, id) {
return json(res, 200, { data: publicStrategy(updated, perf.get(id), names.get(auth.userId)) });
}
+// POST /api/strategies/preview { config, hours?, network? } — public and read-only:
+// replays recorded launches through the live entry filter and research gates.
+async function handlePreview(req, res) {
+ const rl = await limits.strategyPreviewIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const body = await readJson(req).catch(() => null);
+ if (!body || typeof body !== 'object') return error(res, 400, 'validation_error', 'a JSON body with a config is required');
+ // The preview normalizes (clamps) rather than validates: a half-edited config
+ // in the Lab still previews, and saving runs the full validator.
+ const config = body.config && typeof body.config === 'object' ? body.config : {};
+ const hours = PREVIEW_WINDOWS.includes(Number(body.hours)) ? Number(body.hours) : 6;
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+ try {
+ const data = await previewStrategyMatches(config, { hours, network });
+ return json(res, 200, { data }, { 'cache-control': 'no-store' });
+ } catch (err) {
+ console.error('[strategies] preview failed', err?.message || err);
+ return error(res, 502, 'preview_unavailable', 'The launch history could not be read right now. Try again in a moment.');
+ }
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST', 'PATCH', 'DELETE'])) return;
@@ -371,6 +395,10 @@ export default wrap(async (req, res) => {
return error(res, 405, 'method_not_allowed', 'unsupported method');
}
if (seg === 'leaderboard') return handleLeaderboard(req, res);
+ if (seg === 'preview') {
+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST a config to preview');
+ return handlePreview(req, res);
+ }
if (!isUuid(seg)) return error(res, 404, 'not_found', 'strategy not found');
const id = seg;
diff --git a/data/changelog.json b/data/changelog.json
index 16e10c4d7..6bcdb84e9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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": "Approve your agents' payments from a notification",
+ "summary": "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.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/approvals"
+ },
{
"date": "2026-10-10",
"title": "Live agent payments keep running when fee sponsorship pauses",
diff --git a/data/pages.json b/data/pages.json
index 21d71b827..e39c14051 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -374,6 +374,15 @@
"added": "2026-07-12",
"indexable": false
},
+ {
+ "path": "/approvals",
+ "title": "Approvals",
+ "description": "Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.",
+ "priority": 0.5,
+ "changefreq": "daily",
+ "added": "2026-10-10",
+ "indexable": false
+ },
{
"path": "/skills",
"title": "Skills Marketplace",
@@ -4808,6 +4817,13 @@
"priority": 0.7,
"changefreq": "monthly"
},
+ {
+ "path": "/docs/approvals",
+ "title": "Docs: Approvals",
+ "description": "How agents pause for your yes before moving funds: the /approvals inbox, push Approve and Deny, signed deep links, payload-hash checks, auto-approve rules, and the API.",
+ "priority": 0.7,
+ "changefreq": "monthly"
+ },
{
"path": "/docs/checkout-companion",
"title": "Docs: Checkout companion",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index e78d8c694..81cc1ebed 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -4700,7 +4700,7 @@ GET /api/notifications/preferences
PATCH /api/notifications/preferences
```
-The bell inbox and its per-user preference matrix. Session required. Event types include `remix`, `dm_received`, `pump_launch_filled` (bonding-curve graduation), and `follow`. Preferences are a category × channel matrix: categories `sales`, `purchases`, `social`, `irl`, `market`, `account`; channels `in_app`, `push`, `email`, `telegram`. The `in_app` channel is always on and cannot be disabled.
+The bell inbox and its per-user preference matrix. Session required. Event types include `remix`, `dm_received`, `pump_launch_filled` (bonding-curve graduation), and `follow`. Preferences are a category × channel matrix: categories `sales`, `purchases`, `social`, `irl`, `market`, `approvals`, `account`; channels `in_app`, `push`, `email`, `telegram`. The `in_app` channel is always on and cannot be disabled.
### Push devices
@@ -4715,6 +4715,20 @@ Where a notification's `push` channel is delivered. Session and CSRF token requi
`previous` marks a silent refresh (the app re-sending its token on launch). It succeeds only if `previous` is already registered to the caller, and answers `409 not_owner` otherwise, so a phone never enrols for whichever account happens to be signed in now. `GET /api/config` reports `nativePush.ios: true` once APNs is configured on the server (`APNS_KEY_ID`, `APNS_AUTH_KEY`, and `APNS_TEAM_ID` or `APPLE_TEAM_ID`).
+
+### Approvals
+
+```
+GET /api/approvals?status=pending|done|denied|expired|all&agent=<uuid>&limit=&cursor=
+POST /api/approvals { action: "bulk_deny", ids }
+GET /api/approvals/:id?t=<link token>
+POST /api/approvals/:id { decision: "approve"|"deny", payload_hash, token?, via? }
+GET /api/approvals/policies
+POST /api/approvals/policies { venues, max_usd, agent_id?, team_id?, expires_at?, label? }
+DELETE /api/approvals/policies?id=<uuid>
+```
+
+The owner's inbox for actions an agent paused on because a spend rule is set to "Ask me". Reads take a session or bearer; every decision and rule change needs a session plus CSRF, so an agent credential can never approve its own request. Approve must carry the `payload_hash` of the action shown: a mismatch is `409 payload_mismatch`, a deep link that no longer matches is `409 link_mismatch`, a passed deadline is `410 expired`, and nothing runs in any of those cases. A repeat approve returns the current state with `idempotent: true` and never executes twice. Auto-approve rules name venues (`jupiter`, `wallet_transfer`) and a per-action cap of at most $1,000; first transfers to a new address and unpriced actions always ask. Full guide: [approvals.md](approvals.md).
---
## IRL API — presence, pins, money drops, world lines
diff --git a/docs/approvals.md b/docs/approvals.md
new file mode 100644
index 000000000..53a498a2f
--- /dev/null
+++ b/docs/approvals.md
@@ -0,0 +1,201 @@
+# Approvals: the inbox for actions your agents pause to ask about
+
+Some actions are yours to decide. When you set an agent's spend policy to
+**Ask me** (the Policy tab at `/agent/<id>/wallet`), the agent no longer moves
+funds on its own for that rule: it writes an **approval request**, tells you
+on every channel you have connected, and waits. You answer from a push
+notification's Approve or Deny button, from the email, or from the inbox at
+[/approvals](https://three.ws/approvals). Approving runs exactly the action you
+were shown, once. Denying, ignoring it, or letting it expire runs nothing.
+
+| Piece | Where | Source |
+|---|---|---|
+| Inbox page | [/approvals](https://three.ws/approvals), deep links `/approvals/<id>?t=<token>` | [pages/approvals.html](../pages/approvals.html), [src/approvals-page.js](../src/approvals-page.js) |
+| Library (lifecycle, hashing, links, policies) | server | [api/_lib/approvals.js](../api/_lib/approvals.js) |
+| Inbox API | `GET/POST /api/approvals`, `GET/POST /api/approvals/:id`, `GET/POST/DELETE /api/approvals/policies` | [api/approvals/](../api/approvals) |
+| Wallet intent wiring | where a gated transfer or swap becomes a request, and where an approved one executes | [api/_lib/wallet-intents.js](../api/_lib/wallet-intents.js), [api/_lib/agent-trade-guards.js](../api/_lib/agent-trade-guards.js) |
+| Push Approve/Deny buttons | the browser service worker | [public/push-sw.js](../public/push-sw.js) |
+| Schema | `approval_requests`, `approval_auto_policies` | [api/_lib/migrations/20261010120000_approval_requests.sql](../api/_lib/migrations/20261010120000_approval_requests.sql) |
+| Tests | tamper, expiry, idempotency, policy matching | [tests/approvals.test.js](../tests/approvals.test.js) |
+
+---
+
+## What triggers a request
+
+A spend rule set to **Ask me** makes the spend-limit check raise
+`policy_step_up` instead of letting the action through. The wallet intent
+engine catches that and calls `createApprovalRequest()` with the exact action
+it was about to take. Approving lifts only that step-up rule. Your numeric
+caps, block rules, and any wallet freeze still apply when the approved action
+runs, so an approval can never push an action past a limit you set elsewhere.
+
+Each request stores:
+
+- the **payload**: the exact action the executor will run, nothing more;
+- a **confirmation table** built from it: action, amount, asset and chain,
+ recipient (with a label when the address is known), the USD value when it
+ can be priced, the venue, and the expiry;
+- **risk notes**, such as "first transfer to this address";
+- the **gate reason**: which rule asked you;
+- an **idempotency key** (and a `source_ref`), so an agent retrying the same
+ action never stacks duplicate requests.
+
+## Lifecycle
+
+```
+pending ──approve──> approved ──> executing ──> executed
+ │ └────> failed
+ ├──deny──────────> denied
+ └──deadline──────> expired
+```
+
+- **pending**: waiting on you. A swap waits 15 minutes, because prices move;
+ a transfer of a fixed amount waits 6 hours.
+- **approved / executing**: claimed by your decision. The move from
+ `approved` to `executing` is a conditional update, so even two decisions
+ arriving at the same instant (push on your phone, click on your laptop) run
+ the action once. The second caller gets the request's current state back
+ with `idempotent: true`.
+- **executed**: done, with the transaction signature and an explorer link.
+- **failed**: the executor ran and refused or errored (for example, a cap
+ you set later now blocks it). A failed request is never retried
+ automatically; the agent asks again if the action is still wanted.
+- **denied / expired**: terminal, nothing ran. Expiry is lazy: a request
+ past its deadline is written as `expired` the next time anything reads or
+ decides it, so no cron is involved, and an expired request can never be
+ approved.
+
+## Why approving is safe
+
+**The payload hash.** Every request carries the SHA-256 of its payload in
+canonical JSON (keys sorted). The inbox shows the action and sends that hash
+back with your approval. If the stored action differs from the one you were
+shown, the approval answers `409 payload_mismatch` and nothing runs. The
+executor re-hashes the stored payload once more right before it runs, so an
+edit to the row after approval also fails closed.
+
+**Signed deep links.** Every delivery carries a link of the form
+`/approvals/<id>?t=a1.<claims>.<hmac>`. The claims bind the request id, its
+owner, its payload hash, and its expiry, signed with the server secret. The
+page shows "This link matches the request on file" when it verifies, or says
+why it does not (`payload_changed`, `wrong_request`, `bad_signature`,
+`malformed`). A decision made through a link that does not match is refused
+with `409 link_mismatch`.
+
+**Your session, not a key.** Reading the inbox works with a session or a
+read-only bearer. Deciding needs a signed-in browser session plus a CSRF
+token. A machine credential, which an agent could hold, can never approve
+its own request.
+
+## Delivery
+
+A new request goes out through the same fan-out as every notification, in
+the **Approvals** category (on by default for every channel):
+
+| Channel | What you get |
+|---|---|
+| Bell and [/notifications](https://three.ws/notifications) | A row that opens the request's deep link. |
+| Web push | A notification with **Approve** and **Deny** buttons. Each request has its own tag, so two pending approvals never replace each other. The Approve button sends the request's payload hash, so it executes exactly what the notification described. |
+| iOS app | An APNs alert that opens the deep link. |
+| Telegram and Discord | A message with the summary, the confirmation lines, and the deep link, through your paired chat. |
+| Email | The fallback. Sent only when no push device or chat received the request, and only if email is on for Approvals in `/dashboard/settings`. It carries the full confirmation table, the risk notes, and the deep link. |
+
+Turn browser push on from the **Turn on push** button in the inbox header.
+Change channels from **Delivery settings**, which opens `/dashboard/settings`.
+
+## The inbox
+
+[/approvals](https://three.ws/approvals) has:
+
+- **Status tabs**: Pending, Done, Denied, Expired, All, each with a live count.
+- **An agent filter** listing only the agents that have asked you something.
+- **Cards** with the confirmation table, copy buttons for the recipient and
+ amounts, risk notes, and a countdown to the deadline. Approve is two steps
+ (click, then **Confirm approve**; Escape cancels) so a stray click never
+ moves money.
+- **Bulk deny**: select pending requests, or select all, and deny them in
+ one action.
+- **Auto-approve rules** (below).
+- **An activity log** of every request, approval, denial, execution,
+ failure, and rule change, read from the account audit log.
+
+Opening a deep link pins that request on top of the list with its payload
+fingerprint and the link check result.
+
+## Auto-approve rules
+
+The default is that every gated action asks you. An auto-approve rule is an
+explicit exception you create:
+
+- **venues**: which kinds of action it covers. `jupiter` (token swaps) and
+ `wallet_transfer` (transfers). A rule for swaps never covers transfers.
+- **max_usd**: the largest single action it covers, capped at $1,000 per
+ action. Anything larger always asks.
+- **agent_id** (optional): limit it to one agent. **team_id** (optional):
+ limit it to one team.
+- **expires_at** (optional): the inbox offers 1 day, 7 days, 30 days, or no
+ expiry.
+
+Three kinds of request are never auto-approved, whatever rules exist: a
+transfer to an address this wallet has never paid before, an action whose
+USD value cannot be priced, and anything outside the rule's venues or size.
+When several rules match, the one with the smallest cap wins. An
+auto-approved request is recorded as `approved` via `auto_policy` with the
+rule id, and shows up in the inbox and the activity log like any other.
+Revoking a rule stops it immediately; the row stays for the audit trail.
+
+## API
+
+All endpoints answer `{ error, error_description }` on failure. Reads accept
+a session or bearer; writes need a session plus `x-csrf-token`.
+
+```
+GET /api/approvals?status=pending|done|denied|expired|all&agent=<uuid>&limit=&cursor=
+POST /api/approvals { action: "bulk_deny", ids: [uuid, ...] }
+GET /api/approvals/:id?t=<link token>
+POST /api/approvals/:id { decision: "approve"|"deny", payload_hash, token?, via? }
+GET /api/approvals/policies
+POST /api/approvals/policies { venues, max_usd, agent_id?, team_id?, expires_at?, label? }
+DELETE /api/approvals/policies?id=<uuid>
+```
+
+`GET /api/approvals` returns `{ items, counts, agents, next_cursor }`.
+`POST /api/approvals/:id` returns `{ request, idempotent }`. Errors worth
+handling:
+
+| Status | Code | Meaning |
+|---|---|---|
+| 400 | `payload_hash_required` | Approve was sent without the hash of the action shown. |
+| 404 | `not_found` | No such request on your account. |
+| 409 | `payload_mismatch` | The stored action differs from the one you approved. Nothing ran. |
+| 409 | `link_mismatch` | The deep link does not match the request on file. Nothing ran. |
+| 409 | `already_denied` / `already_decided` | The request is already terminal. |
+| 410 | `expired` | The deadline passed. Nothing ran. |
+
+Example: approve the request you just read.
+
+```js
+const { request } = await fetch(`/api/approvals/${id}`, { credentials: 'include' }).then((r) => r.json());
+const csrf = await fetch('/api/csrf-token', { credentials: 'include' }).then((r) => r.json());
+const res = await fetch(`/api/approvals/${id}`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf.token },
+ body: JSON.stringify({ decision: 'approve', payload_hash: request.payload_hash }),
+});
+```
+
+## Adding a new kind of request
+
+A source registers an executor in the `EXECUTORS` map in
+[api/_lib/approvals.js](../api/_lib/approvals.js). The contract:
+`executor(row)` receives the stored row, executes only `row.payload`, and
+returns `{ status: 'ok'|'error'|'paused'|'skipped', signature?, note?, usd? }`.
+Today the registered source is `wallet_intent` (agent transfers and swaps from
+wallet intents). Then call `createApprovalRequest()` where the source hits
+its step-up gate, with an idempotency key derived from the action. Engines
+that execute inline (an auto-approved request) call `runApproved(row, run)`,
+which provides the same once-only and integrity guarantees.
+
+Related: [Notifications](./notifications.md) for the delivery fan-out and the
+preference matrix, [STRUCTURE.md](../STRUCTURE.md) for where everything lives.
diff --git a/docs/notifications.md b/docs/notifications.md
index 30dc70e68..5eb8a4b7d 100644
--- a/docs/notifications.md
+++ b/docs/notifications.md
@@ -72,6 +72,7 @@ category; the mapping (`TYPE_CATEGORY`) lives in
| Market alerts | `alerts` | `pump_alert` |
| Creations | `creations` | `forge_complete`, `forge_failed` |
| Companion | `companion` | `companion_delivery` |
+| Approvals | `approvals` | `approval_requested` (see [Approvals](./approvals.md)) |
| (no tab yet) | `knock` | `knock_received` |
| (no tab yet) | `mail` | `mail_received` |
| Account | `account` | `withdrawal_completed`, `withdrawal_failed`, `payment_mismatch`, `asset_payment_mismatch`, `skill_payment_mismatch`, `security_alert`, `wallet_anomaly_frozen`, plus any type not in the map (the agent-inference `inference_topup` and `inference_budget_exhausted` land here this way) |
diff --git a/docs/start-here.md b/docs/start-here.md
index 03462256e..6954bb1d4 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -175,6 +175,7 @@ Want the model in your hands rather than on a screen? [Materialize](./materializ
- **Following Solana traders?** → [KOL Tracker](./kol-tracker.md): KOLs ranked by realized P&L computed from their own wallets' on-chain trades (never self-reported), with the public API behind it
- **Listening to the economy?** → [Agent Symphony](./agent-symphony.md): /symphony plays the live agent economy as generative music; every event type has a voice, and solo mode isolates one agent by ear
- **Catching up on your inbox?** → [Notifications](./notifications.md): the bell, the /notifications center, category filters, and the full inbox API
+- **An agent waiting on your yes?** → [Approvals](./approvals.md): the /approvals inbox, push Approve/Deny, signed deep links, payload-hash checks, and auto-approve rules
- **Something too important for a badge?** → [Herald](./herald.md): the open SDK behind /herald, where a 3D character walks onto the page and says it out loud, with an interrupt budget (importance floor, quiet hours, dedupe, batching), an accessible card for machines with no GPU, a rail so CI or an AI agent can reach the tab you have open, and a CLI that announces when your build finishes
- **Want strangers to be able to reach you, but not for free?** → [Knock](./knock.md): a priced door at /knock/<username> that anyone, human or agent, can pay to get one message through; the USDC settles straight to your wallet, your companion delivers it in person, and every refusal happens before the payment
- **About to pay for something?** → [Checkout companion](./checkout-companion.md): the browser extension that reads a payment page before you pay, why the arithmetic is never a model's job, and why it never reads a form field
diff --git a/pages/approvals.html b/pages/approvals.html
new file mode 100644
index 000000000..d46c26554
--- /dev/null
+++ b/pages/approvals.html
@@ -0,0 +1,330 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <style>/* three.ws hidden-guard: make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>
+ <script>/* three.ws theme boot */(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" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Approvals · three.ws</title>
+ <meta name="description" content="Review, approve, or deny every action your agents need your yes for. Nothing moves until you approve it." />
+ <meta name="robots" content="noindex" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ :root {
+ --bg: #0d0d0d;
+ --bg-2: #141414;
+ --card: #181818;
+ --line: rgba(255,255,255,0.07);
+ --line-2: rgba(255,255,255,0.12);
+ --line-3: rgba(255,255,255,0.3);
+ --text: #e7e9ee;
+ --muted: rgba(231,233,238,0.6);
+ --dim: rgba(231,233,238,0.4);
+ --blue: #3b82f6;
+ --green: #22c55e;
+ --green-ink: #052e16;
+ --red: #ef4444;
+ --amber: #f59e0b;
+ --radius: 12px;
+ --skeleton-base: rgba(255,255,255,0.04);
+ --skeleton-sheen: rgba(255,255,255,0.08);
+ --mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
+ }
+ [data-theme="light"] {
+ --bg: #f5f5f5;
+ --bg-2: #ffffff;
+ --card: #ffffff;
+ --line: rgba(0,0,0,0.07);
+ --line-2: rgba(0,0,0,0.12);
+ --line-3: rgba(0,0,0,0.3);
+ --text: #111;
+ --muted: rgba(0,0,0,0.6);
+ --dim: rgba(0,0,0,0.42);
+ --green: #15803d;
+ --green-ink: #ffffff;
+ --red: #dc2626;
+ --amber: #b45309;
+ --skeleton-base: rgba(0,0,0,0.04);
+ --skeleton-sheen: rgba(0,0,0,0.08);
+ }
+ *{box-sizing:border-box;margin:0;padding:0;}
+ html,body{background:var(--bg);color:var(--text);font-family:'Inter',system-ui,sans-serif;min-height:100vh;}
+ a{color:inherit;}
+ .page-shell{max-width:820px;margin:0 auto;padding:0 16px 100px;}
+ .page-hero{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;padding:48px 0 24px;flex-wrap:wrap;}
+ .page-hero h1{font-size:28px;font-weight:700;letter-spacing:-0.02em;}
+ .page-hero p{color:var(--muted);margin-top:8px;font-size:14px;line-height:1.5;max-width:520px;}
+ .page-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;font-size:13px;font-weight:500;padding:8px 14px;border-radius:8px;background:var(--card);color:var(--text);border:1px solid var(--line-2);cursor:pointer;transition:border-color .15s,background .15s,transform .08s,opacity .15s;font-family:inherit;text-decoration:none;min-height:36px;}
+ .btn:hover{border-color:var(--line-3);}
+ .btn:active{transform:translateY(1px);}
+ .btn:disabled{opacity:.45;cursor:default;transform:none;}
+ .btn:focus-visible,.ap-tab:focus-visible,select:focus-visible,input:focus-visible,.ap-copy:focus-visible,summary:focus-visible{outline:2px solid var(--blue);outline-offset:2px;}
+ .btn-approve{background:var(--green);border-color:var(--green);color:var(--green-ink);font-weight:600;}
+ .btn-approve:hover{border-color:var(--green);filter:brightness(1.08);}
+ .btn-approve.is-armed{box-shadow:0 0 0 3px color-mix(in srgb,var(--green) 35%,transparent);}
+ .btn-deny{color:var(--red);}
+ .btn-deny:hover{border-color:var(--red);background:color-mix(in srgb,var(--red) 8%,transparent);}
+ .btn-sm{padding:6px 10px;font-size:12px;min-height:30px;}
+
+ /* Notices */
+ .notice{border-radius:10px;padding:14px 16px;font-size:13px;line-height:1.5;margin-bottom:16px;border:1px solid;}
+ .notice strong{font-weight:600;}
+ .notice-error{background:color-mix(in srgb,var(--red) 8%,transparent);border-color:color-mix(in srgb,var(--red) 30%,transparent);color:var(--red);}
+ .notice-ok{background:color-mix(in srgb,var(--green) 8%,transparent);border-color:color-mix(in srgb,var(--green) 30%,transparent);color:var(--green);}
+ .notice-warn{background:color-mix(in srgb,var(--amber) 9%,transparent);border-color:color-mix(in srgb,var(--amber) 32%,transparent);color:var(--amber);}
+ .notice-info{background:var(--bg-2);border-color:var(--line-2);color:var(--muted);}
+ .notice .btn{margin-top:10px;}
+
+ /* Toolbar */
+ .ap-tabs{display:flex;gap:2px;border-bottom:1px solid var(--line-2);overflow-x:auto;scrollbar-width:none;}
+ .ap-tabs::-webkit-scrollbar{display:none;}
+ .ap-tab{display:inline-flex;align-items:center;gap:6px;padding:10px 14px;font-size:13px;font-weight:500;color:var(--muted);cursor:pointer;border:0;border-bottom:2px solid transparent;background:none;white-space:nowrap;font-family:inherit;transition:color .15s,border-color .15s;}
+ .ap-tab:hover{color:var(--text);}
+ .ap-tab[aria-selected="true"]{color:var(--text);border-bottom-color:var(--blue);}
+ .ap-count{font-size:11px;font-weight:600;padding:1px 7px;border-radius:999px;background:var(--line-2);color:var(--muted);font-variant-numeric:tabular-nums;}
+ .ap-tab[data-group="pending"] .ap-count.has{background:var(--amber);color:#111;}
+ .ap-bar{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;padding:12px 0;}
+ .ap-bar-left,.ap-bar-right{display:flex;align-items:center;gap:10px;flex-wrap:wrap;}
+ .ap-check{display:inline-flex;align-items:center;gap:8px;font-size:13px;color:var(--muted);cursor:pointer;user-select:none;}
+ .ap-check input{width:16px;height:16px;accent-color:var(--blue);cursor:pointer;}
+ select,input[type="number"]{font-family:inherit;font-size:13px;color:var(--text);background:var(--card);border:1px solid var(--line-2);border-radius:8px;padding:7px 10px;min-height:36px;}
+ select:hover,input[type="number"]:hover{border-color:var(--line-3);}
+
+ /* Cards */
+ .ap-list{display:flex;flex-direction:column;gap:12px;}
+ .ap-card{background:var(--card);border:1px solid var(--line-2);border-radius:var(--radius);padding:16px;transition:border-color .2s,box-shadow .2s,opacity .25s,transform .25s;animation:enter .25s ease both;}
+ .ap-card.is-focus{border-color:var(--blue);box-shadow:0 0 0 3px color-mix(in srgb,var(--blue) 22%,transparent);}
+ .ap-card.is-leaving{opacity:0;transform:translateY(-4px);}
+ @keyframes enter{from{opacity:0;transform:translateY(4px);}to{opacity:1;transform:none;}}
+ .ap-head{display:flex;align-items:flex-start;gap:12px;}
+ .ap-head .ap-check{margin-top:3px;}
+ .ap-title{flex:1;min-width:0;}
+ .ap-summary{font-size:15px;font-weight:600;line-height:1.4;word-break:break-word;}
+ .ap-meta{display:flex;flex-wrap:wrap;gap:6px 12px;font-size:12px;color:var(--dim);margin-top:4px;}
+ .ap-meta a{color:var(--muted);text-decoration:underline;text-decoration-color:var(--line-2);text-underline-offset:2px;}
+ .ap-meta a:hover{color:var(--text);}
+ .pill{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px;white-space:nowrap;border:1px solid var(--line-2);color:var(--muted);text-transform:capitalize;}
+ .pill::before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor;}
+ .pill-pending{color:var(--amber);border-color:color-mix(in srgb,var(--amber) 40%,transparent);}
+ .pill-executed,.pill-approved{color:var(--green);border-color:color-mix(in srgb,var(--green) 40%,transparent);}
+ .pill-executing{color:var(--blue);border-color:color-mix(in srgb,var(--blue) 40%,transparent);}
+ .pill-failed,.pill-denied{color:var(--red);border-color:color-mix(in srgb,var(--red) 40%,transparent);}
+ .ap-table{width:100%;border-collapse:collapse;margin-top:14px;font-size:13px;border:1px solid var(--line);border-radius:10px;overflow:hidden;}
+ .ap-table th{width:110px;text-align:left;font-weight:500;color:var(--muted);padding:9px 12px;background:var(--bg-2);border-bottom:1px solid var(--line);vertical-align:top;}
+ .ap-table td{padding:9px 12px;border-bottom:1px solid var(--line);word-break:break-all;font-variant-numeric:tabular-nums;}
+ .ap-table tr:last-child th,.ap-table tr:last-child td{border-bottom:0;}
+ .ap-table .mono{font-family:var(--mono);font-size:12px;}
+ .ap-copy{margin-left:8px;font-size:11px;color:var(--muted);background:none;border:1px solid var(--line-2);border-radius:6px;padding:1px 7px;cursor:pointer;font-family:inherit;transition:color .15s,border-color .15s;}
+ .ap-copy:hover{color:var(--text);border-color:var(--line-3);}
+ .ap-risks{list-style:none;margin-top:12px;display:flex;flex-direction:column;gap:6px;}
+ .ap-risks li{font-size:13px;line-height:1.45;color:var(--amber);padding-left:22px;position:relative;}
+ .ap-risks li::before{content:"!";position:absolute;left:0;top:1px;width:15px;height:15px;border-radius:50%;border:1.5px solid currentColor;font-size:10px;font-weight:700;display:flex;align-items:center;justify-content:center;}
+ .ap-gate{font-size:12px;color:var(--muted);margin-top:10px;line-height:1.45;}
+ .ap-outcome{font-size:13px;margin-top:12px;padding:10px 12px;border-radius:8px;background:var(--bg-2);border:1px solid var(--line);line-height:1.5;}
+ .ap-outcome a{color:var(--blue);}
+ .ap-foot{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-top:14px;}
+ .ap-expiry{font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums;}
+ .ap-expiry.is-soon{color:var(--amber);font-weight:600;}
+ .ap-actions{display:flex;gap:8px;margin-left:auto;}
+ .ap-hash{font-family:var(--mono);font-size:11px;color:var(--dim);margin-top:10px;word-break:break-all;}
+ .ap-card-msg{font-size:13px;margin-top:10px;line-height:1.45;}
+ .ap-card-msg.err{color:var(--red);}
+ .ap-card-msg.ok{color:var(--green);}
+
+ /* Empty / auth / skeleton */
+ .ap-empty{text-align:center;padding:72px 20px;color:var(--muted);border:1px dashed var(--line-2);border-radius:var(--radius);}
+ .ap-empty-icon{font-size:34px;margin-bottom:12px;}
+ .ap-empty h3{font-size:17px;font-weight:600;color:var(--text);margin-bottom:8px;}
+ .ap-empty p{font-size:14px;line-height:1.55;max-width:420px;margin:0 auto;}
+ .ap-empty .btn{margin-top:18px;}
+ .ap-auth{text-align:center;padding:110px 20px;}
+ .ap-auth h2{font-size:22px;font-weight:700;margin-bottom:12px;}
+ .ap-auth p{color:var(--muted);font-size:14px;margin:0 auto 24px;max-width:440px;line-height:1.55;}
+ .skeleton{background:var(--skeleton-base);background-image:linear-gradient(90deg,var(--skeleton-base) 0%,var(--skeleton-sheen) 50%,var(--skeleton-base) 100%);background-size:200% 100%;border-radius:6px;animation:shimmer 1.4s ease-in-out infinite;}
+ @keyframes shimmer{0%{background-position:200% 0;}100%{background-position:-200% 0;}}
+ .ap-skel{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;display:flex;flex-direction:column;gap:10px;}
+ .ap-more{display:flex;justify-content:center;padding:18px 0 0;}
+
+ /* Panels */
+ .ap-panel{margin-top:40px;}
+ .ap-panel > h2{font-size:18px;font-weight:700;letter-spacing:-0.01em;}
+ .ap-panel > p{font-size:13px;color:var(--muted);margin-top:6px;line-height:1.55;}
+ .ap-policies{display:flex;flex-direction:column;gap:8px;margin-top:14px;}
+ .ap-policy{display:flex;align-items:center;gap:12px;padding:12px 14px;background:var(--card);border:1px solid var(--line-2);border-radius:10px;}
+ .ap-policy.is-off{opacity:.6;}
+ .ap-policy-body{flex:1;min-width:0;}
+ .ap-policy-label{font-size:14px;font-weight:500;word-break:break-word;}
+ .ap-policy-meta{font-size:12px;color:var(--dim);margin-top:3px;}
+ .ap-form{margin-top:14px;padding:16px;background:var(--card);border:1px solid var(--line-2);border-radius:var(--radius);display:grid;grid-template-columns:1fr 1fr;gap:14px;}
+ .ap-form fieldset{border:0;grid-column:1/-1;display:flex;flex-direction:column;gap:8px;}
+ .ap-form legend,.ap-form label.lbl{font-size:12px;font-weight:600;color:var(--muted);margin-bottom:6px;display:block;}
+ .ap-field{display:flex;flex-direction:column;}
+ .ap-field select,.ap-field input{width:100%;}
+ .ap-field small{font-size:11px;color:var(--dim);margin-top:5px;line-height:1.4;}
+ .ap-form-foot{grid-column:1/-1;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;}
+ .ap-form-msg{font-size:12px;color:var(--muted);}
+ .ap-form-msg.err{color:var(--red);}
+ .ap-audit{margin-top:14px;border:1px solid var(--line-2);border-radius:var(--radius);overflow:hidden;background:var(--card);}
+ .ap-audit-row{display:grid;grid-template-columns:150px 1fr auto;gap:12px;padding:10px 14px;border-bottom:1px solid var(--line);font-size:13px;align-items:baseline;}
+ .ap-audit-row:last-child{border-bottom:0;}
+ .ap-audit-act{font-weight:600;}
+ .ap-audit-act.ok{color:var(--green);}
+ .ap-audit-act.bad{color:var(--red);}
+ .ap-audit-act.warn{color:var(--amber);}
+ .ap-audit-detail{color:var(--muted);word-break:break-word;min-width:0;}
+ .ap-audit-time{font-size:12px;color:var(--dim);white-space:nowrap;}
+ .ap-audit-empty{padding:28px 14px;text-align:center;color:var(--muted);font-size:13px;}
+ .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0;}
+
+ @media(max-width:600px){
+ .page-hero{padding:32px 0 20px;}
+ .page-hero h1{font-size:24px;}
+ .ap-table th{width:88px;padding:8px 10px;}
+ .ap-table td{padding:8px 10px;}
+ .ap-actions{width:100%;margin-left:0;}
+ .ap-actions .btn{flex:1;min-height:42px;}
+ .ap-form{grid-template-columns:1fr;}
+ .ap-audit-row{grid-template-columns:1fr auto;}
+ .ap-audit-detail{grid-column:1/-1;grid-row:2;}
+ }
+ @media(prefers-reduced-motion:reduce){
+ .ap-card,.skeleton{animation:none;}
+ .ap-card{transition:none;}
+ }
+ </style>
+
+ <link rel="canonical" href="https://three.ws/approvals">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Approvals · three.ws">
+ <meta property="og:description" content="Review, approve, or deny every action your agents need your yes for. Nothing moves until you approve it.">
+ <meta property="og:url" content="https://three.ws/approvals">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Approvals&amp;d=Review%2C+approve%2C+or+deny+every+action+your+agents+need+your+yes+for.&amp;p=%2Fapprovals">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="Approvals on three.ws">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="twitter:title" content="Approvals · three.ws">
+ <meta name="twitter:description" content="Review, approve, or deny every action your agents need your yes for. Nothing moves until you approve it.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Approvals&amp;d=Review%2C+approve%2C+or+deny+every+action+your+agents+need+your+yes+for.&amp;p=%2Fapprovals">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Approvals","description":"Review, approve, or deny every action your agents need your yes for.","url":"https://three.ws/approvals","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="page-shell">
+ <div class="page-hero">
+ <div>
+ <h1>Approvals</h1>
+ <p>Every action your agents need your yes for. Nothing moves until you approve exactly what is shown here.</p>
+ </div>
+ <div class="page-actions">
+ <button type="button" id="ap-push" class="btn" hidden>Enable push</button>
+ <a href="/dashboard/settings" class="btn" aria-label="Approval notification preferences">Delivery settings</a>
+ </div>
+ </div>
+
+ <div id="ap-auth" class="ap-auth" hidden>
+ <h2>Sign in to review approvals</h2>
+ <p>When an agent's action needs your sign-off, it waits here with the recipient, amount, asset and chain spelled out.</p>
+ <a href="/login?next=/approvals" id="ap-login" class="btn">Sign in</a>
+ </div>
+
+ <div id="ap-error" class="notice notice-error" role="alert" hidden></div>
+ <div id="ap-live" class="sr-only" aria-live="polite"></div>
+
+ <div id="ap-main" hidden>
+ <section id="ap-focus" aria-label="Linked approval request" hidden></section>
+
+ <div class="ap-tabs" id="ap-tabs" role="tablist" aria-label="Filter by status">
+ <button class="ap-tab" role="tab" aria-selected="true" data-group="pending">Pending <span class="ap-count" data-count="pending">0</span></button>
+ <button class="ap-tab" role="tab" aria-selected="false" data-group="done">Approved <span class="ap-count" data-count="done">0</span></button>
+ <button class="ap-tab" role="tab" aria-selected="false" data-group="denied">Denied <span class="ap-count" data-count="denied">0</span></button>
+ <button class="ap-tab" role="tab" aria-selected="false" data-group="expired">Expired <span class="ap-count" data-count="expired">0</span></button>
+ <button class="ap-tab" role="tab" aria-selected="false" data-group="all">All <span class="ap-count" data-count="all">0</span></button>
+ </div>
+
+ <div class="ap-bar">
+ <div class="ap-bar-left">
+ <label class="ap-check" id="ap-select-all-wrap" hidden>
+ <input type="checkbox" id="ap-select-all" />
+ <span>Select all</span>
+ </label>
+ <button type="button" id="ap-bulk-deny" class="btn btn-deny btn-sm" hidden disabled>Deny selected</button>
+ </div>
+ <div class="ap-bar-right">
+ <label class="sr-only" for="ap-agent">Filter by agent</label>
+ <select id="ap-agent" hidden>
+ <option value="">All agents</option>
+ </select>
+ </div>
+ </div>
+
+ <div id="ap-list" class="ap-list" role="tabpanel" aria-labelledby="ap-tabs"></div>
+ <div id="ap-more" class="ap-more" hidden>
+ <button type="button" id="ap-more-btn" class="btn">Load more</button>
+ </div>
+
+ <section class="ap-panel" aria-labelledby="ap-policies-h">
+ <h2 id="ap-policies-h">Auto-approve rules</h2>
+ <p>By default every gated action asks you. A rule lets small, routine actions through on their own, capped by size and venue. A transfer to an address the wallet has never paid always asks. Revoking a rule takes effect on the next request.</p>
+ <div id="ap-policies" class="ap-policies"></div>
+ <form id="ap-policy-form" class="ap-form" novalidate>
+ <fieldset>
+ <legend>Venues</legend>
+ <div id="ap-venues"></div>
+ </fieldset>
+ <div class="ap-field">
+ <label class="lbl" for="ap-max">Max per action (USD)</label>
+ <input type="number" id="ap-max" min="1" step="1" inputmode="decimal" required />
+ <small id="ap-max-hint"></small>
+ </div>
+ <div class="ap-field">
+ <label class="lbl" for="ap-policy-agent">Agent</label>
+ <select id="ap-policy-agent">
+ <option value="">Every agent I own</option>
+ </select>
+ </div>
+ <div class="ap-field">
+ <label class="lbl" for="ap-policy-expiry">Rule expires</label>
+ <select id="ap-policy-expiry">
+ <option value="1">In 24 hours</option>
+ <option value="7" selected>In 7 days</option>
+ <option value="30">In 30 days</option>
+ <option value="">Never (revoke by hand)</option>
+ </select>
+ </div>
+ <div class="ap-form-foot">
+ <span id="ap-form-msg" class="ap-form-msg" role="status"></span>
+ <button type="submit" class="btn" id="ap-policy-submit">Add rule</button>
+ </div>
+ </form>
+ </section>
+
+ <section class="ap-panel" aria-labelledby="ap-audit-h">
+ <h2 id="ap-audit-h">Audit log</h2>
+ <p>Every request, decision, execution and rule change on your account, newest first.</p>
+ <div id="ap-audit" class="ap-audit"></div>
+ <div id="ap-audit-more" class="ap-more" hidden>
+ <button type="button" id="ap-audit-more-btn" class="btn btn-sm">Older events</button>
+ </div>
+ </section>
+ </div>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/src/approvals-page.js"></script>
+ </body>
+</html>
diff --git a/pages/notifications.html b/pages/notifications.html
index 5c9591b33..034d49b19 100644
--- a/pages/notifications.html
+++ b/pages/notifications.html
@@ -153,6 +153,7 @@
<button class="n-tab" role="tab" aria-selected="false" data-type="alerts" data-i18n="notifications.market_alerts">Market alerts</button>
<button class="n-tab" role="tab" aria-selected="false" data-type="creations" data-i18n="notifications.creations">Creations</button>
<button class="n-tab" role="tab" aria-selected="false" data-type="companion" data-i18n="notifications.companion">Companion</button>
+ <button class="n-tab" role="tab" aria-selected="false" data-type="approvals">Approvals</button>
<button class="n-tab" role="tab" aria-selected="false" data-type="account" data-i18n="notifications.account">Account</button>
</div>
<div id="n-list" class="n-list"></div>
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 70cc0a187..74f27d6dc 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,14 +1,34 @@
{
- "generated_at": "2026-10-10T05:09:34.226Z",
+ "generated_at": "2026-10-10T05:45:10.412Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3887,
+ "total": 3889,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
+ {
+ "date": "2026-10-10",
+ "type": "launch",
+ "title": "Approvals",
+ "summary": "Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.",
+ "link": "/approvals",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-10-10",
+ "type": "update",
+ "title": "Approve your agents' payments from a notification",
+ "summary": "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.",
+ "link": "/approvals",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-10-10",
"type": "update",
@@ -1519,28 +1539,6 @@
"tags": [
"fix"
]
- },
- {
- "date": "2026-09-21",
- "type": "update",
- "title": "The club no longer runs your computer hot on the way in",
- "summary": "While you walked the alley and stood at the door, the club was secretly drawing the whole dance floor behind it at full quality, so your graphics card was rendering two complete 3D scenes at once. The hidden stage now pauses its drawing until the alley fades away, roughly halving the graphics work for the entire walk-in. For a cooler machine inside the club too, turn on Power saver in the club controls.",
- "link": "/club",
- "tags": [
- "fix",
- "improvement"
- ]
- },
- {
- "date": "2026-09-21",
- "type": "update",
- "title": "Three SDKs now report the version you actually installed",
- "summary": "The walk, tour and assistant SDKs each export a VERSION constant, and a release earlier this month bumped all three packages without updating it. Code that read the constant got the previous release's number: 0.3.0 from walk 0.3.1, 0.5.1 from tour 0.5.2, 1.0.0 from assistant 1.0.1. The constants now match the packages, and the tour builder's copy-paste embed snippet points at tour 0.5.2. Only the tour SDK had a test comparing the two, which is how this was found; the other two were caught by checking every package from that release for the same mistake. Copies already installed from npm keep the old number until the next release of each package.",
- "link": "/tour-builder",
- "tags": [
- "sdk",
- "fix"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 90b1d51f7..6d0845bfb 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,31 @@
{
- "generated_at": "2026-10-10T05:09:34.204Z",
+ "generated_at": "2026-10-10T05:45:10.378Z",
"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": "Approvals",
+ "summary": "Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.",
+ "link": "/approvals",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-10-10",
+ "type": "update",
+ "title": "Approve your agents' payments from a notification",
+ "summary": "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.",
+ "link": "/approvals",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-10-10",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 98cc12338..3842b7fb3 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<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>Approvals</title>
+ <link>https://three.ws/approvals</link>
+ <guid isPermaLink="false">2026-10-10:Approvals</guid>
+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.</description>
+ </item>
+ <item>
+ <title>Approve your agents' payments from a notification</title>
+ <link>https://three.ws/approvals</link>
+ <guid isPermaLink="false">2026-10-10:Approve your agents' payments from a notification</guid>
+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>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.</description>
+ </item>
<item>
<title>Coin logos, agent art and IPFS images load again</title>
<link>https://three.ws/launches</link>
diff --git a/public/features.json b/public/features.json
index 9847eb388..c6ffcdddf 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-10-10T04:59:19.973Z",
+ "generated_at": "2026-10-10T05:45:10.365Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -487,6 +487,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/approvals",
+ "title": "Approvals",
+ "description": "Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.",
+ "added": "2026-10-10",
+ "auth": null,
+ "indexable": false,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/skills",
"title": "Skills Marketplace",
@@ -6149,6 +6159,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/approvals",
+ "title": "Docs: Approvals",
+ "description": "How agents pause for your yes before moving funds: the /approvals inbox, push Approve and Deny, signed deep links, payload-hash checks, auto-approve rules, and the API.",
+ "added": null,
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/checkout-companion",
"title": "Docs: Checkout companion",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index ea144e8d3..5b3871899 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -256,6 +256,13 @@ Indexable: no (excluded from sitemap)
Every payment, sale, remix, follow, quest, and royalty notification on three.ws: all in one place, filterable by category.
+### Approvals
+
+URL: https://three.ws/approvals
+Indexable: no (excluded from sitemap)
+
+Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.
+
### Skills Marketplace
URL: https://three.ws/skills
@@ -3695,6 +3702,12 @@ URL: https://three.ws/docs/notifications
Everything that happens to your work on three.ws (a payment lands, a skill sells, someone remixes your model, follows you, a quest finishes, a royalty arrives) becomes a row in one per-user inbox.
+### Docs: Approvals
+
+URL: https://three.ws/docs/approvals
+
+How agents pause for your yes before moving funds: the /approvals inbox, push Approve and Deny, signed deep links, payload-hash checks, auto-approve rules, and the API.
+
### Docs: Checkout companion
URL: https://three.ws/docs/checkout-companion
diff --git a/public/llms.txt b/public/llms.txt
index 5ddb88f4b..2b736a98c 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -98,6 +98,6 @@ Machine-readable entry points. Fetch these instead of scraping HTML.
## Optional
-- [llms-full.txt](https://three.ws/llms-full.txt): Every public page (946), grouped by section, with full descriptions.
+- [llms-full.txt](https://three.ws/llms-full.txt): Every public page (947), grouped by section, with full descriptions.
- [Sitemap](https://three.ws/sitemap): The same index for people, with search.
- [sitemap.xml](https://three.ws/sitemap.xml): XML sitemap for crawlers, including every agent and avatar page.
diff --git a/public/nav-data.js b/public/nav-data.js
index 792370411..19849c71c 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -532,6 +532,11 @@ export const NAV_GROUPS = [
badgeTone: 'live',
desc: 'Start here: live fleet vitals, the agent scoreboard, and every trading surface in one map',
},
+ {
+ title: 'Approvals',
+ href: '/approvals',
+ desc: 'Approve or deny the actions your agents paused to ask you about',
+ },
{
title: 'Exit Lab',
href: '/exit-lab',
diff --git a/public/push-sw.js b/public/push-sw.js
index bd2b9e1a4..e5ddce54d 100644
--- a/public/push-sw.js
+++ b/public/push-sw.js
@@ -9,6 +9,11 @@
// • notificationclick — focus or open the target URL (tagged ?source=push so
// the app records a `returned` funnel event), and beacon a
// `opened` event so sent→opened→returned is measurable.
+// • approvals — an approval push (api/_lib/approvals.js) gets Approve
+// and Deny buttons. Tapping one posts the decision with the
+// payload hash the notification showed, so the server only
+// executes that exact action, then shows the outcome. A
+// signed-out browser or any failure opens /approvals instead.
self.addEventListener('push', (event) => {
let data = {};
@@ -31,8 +36,18 @@ self.addEventListener('push', (event) => {
url: data.url || '/dashboard/',
notificationId: data.notificationId || null,
category: data.category || null,
+ approval: data.approval && data.approval.id ? data.approval : null,
},
};
+ if (options.data.approval) {
+ // A decision is owed: keep it on screen until it is answered, and offer
+ // the answer right on the notification where the platform supports it.
+ options.requireInteraction = true;
+ options.actions = [
+ { action: 'approve', title: 'Approve' },
+ { action: 'deny', title: 'Deny' },
+ ];
+ }
event.waitUntil(self.registration.showNotification(title, options));
});
@@ -42,6 +57,11 @@ self.addEventListener('notificationclick', (event) => {
const d = event.notification.data || {};
const rawUrl = typeof d.url === 'string' && d.url ? d.url : '/dashboard/';
+ if (d.approval && (event.action === 'approve' || event.action === 'deny')) {
+ event.waitUntil(answerApproval(d, event.action, rawUrl));
+ return;
+ }
+
event.waitUntil((async () => {
// Record the open before navigating so the beacon isn't cut off.
await trackOpen(d.notificationId);
@@ -91,3 +111,57 @@ async function trackOpen(notificationId) {
/* offline / blocked — the open still proceeds */
}
}
+
+// Answer an approval straight from the notification. The decision carries the
+// payload hash and signed link token the push was built with, so the server
+// rejects it if the request changed since. Any answer the server does not
+// accept falls back to opening the request so the owner can see why.
+async function answerApproval(d, action, url) {
+ const a = d.approval;
+ const decision = action === 'approve' ? 'approve' : 'deny';
+ try {
+ const tokRes = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!tokRes.ok) throw new Error('signed_out');
+ const tok = await tokRes.json();
+ const csrf = (tok && (tok.token || (tok.data && tok.data.token))) || '';
+ const res = await fetch(`/api/approvals/${encodeURIComponent(a.id)}`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },
+ body: JSON.stringify({ decision, payload_hash: a.hash, token: a.token, via: 'push' }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error((body && body.error_description) || (body && body.error) || `HTTP ${res.status}`);
+ const r = body.request || {};
+ await trackOpen(d.notificationId);
+ await self.registration.showNotification(outcomeTitle(decision, r.status), {
+ body: outcomeBody(r),
+ tag: `approval:${a.id}`,
+ icon: '/pwa-192x192.png',
+ badge: '/pwa-192x192.png',
+ data: { url: `/approvals/${a.id}`, notificationId: d.notificationId || null, category: d.category || null },
+ });
+ } catch (err) {
+ await self.registration.showNotification('Could not answer from the notification', {
+ body: `${err && err.message ? err.message : 'Something went wrong'}. Tap to review it on three.ws.`,
+ tag: `approval:${a.id}`,
+ icon: '/pwa-192x192.png',
+ badge: '/pwa-192x192.png',
+ data: { url, notificationId: d.notificationId || null, category: d.category || null },
+ });
+ }
+}
+
+function outcomeTitle(decision, status) {
+ if (decision === 'deny') return 'Denied. Nothing was sent.';
+ if (status === 'executed') return 'Approved and executed';
+ if (status === 'failed') return 'Approved, but it did not execute';
+ return 'Approved';
+}
+
+function outcomeBody(r) {
+ const parts = [r.summary || ''];
+ if (r.status === 'failed' && r.result && r.result.note) parts.push(r.result.note);
+ if (r.signature) parts.push(`Tx ${String(r.signature).slice(0, 8)}...`);
+ return parts.filter(Boolean).join('\n');
+}
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 29338265d..23cb2d94f 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -3,16 +3,16 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
-<title>Sitemap · three.ws</title>
-<meta name="description" content="Human-readable index of every page on three.ws." />
+<title data-i18n="sitemap_index.meta_title">Sitemap · three.ws</title>
+<meta name="description" content="Human-readable index of every page on three.ws." data-i18n-attr="content:sitemap_index.meta_description"/>
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
<link rel="canonical" href="https://three.ws/sitemap" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
<meta property="og:locale" content="en_US" />
<meta property="og:url" content="https://three.ws/sitemap" />
-<meta property="og:title" content="Sitemap · three.ws" />
-<meta property="og:description" content="Human-readable index of every page on three.ws." />
+<meta property="og:title" content="Sitemap · three.ws" data-i18n-attr="content:sitemap_index.meta_og_title"/>
+<meta property="og:description" content="Human-readable index of every page on three.ws." data-i18n-attr="content:sitemap_index.meta_og_description"/>
<meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@@ -20,8 +20,8 @@
<meta property="og:image:alt" content="Sitemap - three.ws" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@trythreews" />
-<meta name="twitter:title" content="Sitemap · three.ws" />
-<meta name="twitter:description" content="Human-readable index of every page on three.ws." />
+<meta name="twitter:title" content="Sitemap · three.ws" data-i18n-attr="content:sitemap_index.meta_twitter_title"/>
+<meta name="twitter:description" content="Human-readable index of every page on three.ws." data-i18n-attr="content:sitemap_index.meta_twitter_description"/>
<meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap" />
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
<link rel="alternate" type="application/xml" title="XML sitemap" href="/sitemap.xml" />
@@ -95,26 +95,26 @@
<header><div id="nav-container"></div></header>
<main class="sm-wrap">
<div class="sm-hero">
- <h1>Sitemap</h1>
- <p><span>997</span> <span data-i18n="sitemap_index.pages_grouped">pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</span></p>
+ <h1 data-i18n="sitemap_index.sitemap">Sitemap</h1>
+ <p><span>999</span> <span data-i18n="sitemap_index.pages_grouped">pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</span></p>
<div class="sm-formats">
- <a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
- <a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
- <a href="/llms-full.txt"><code>llms-full.txt</code> · long form</a>
- <a href="/api/features.json"><code>features.json</code> · machine manifest</a>
- <a href="/changelog"><code>changelog</code> · what's new</a>
- <a href="/openapi.json"><code>openapi.json</code> · HTTP API</a>
+ <a href="/sitemap.xml" data-i18n-html="sitemap_index.for_search_engines"><code>sitemap.xml</code> · for search engines</a>
+ <a href="/llms.txt" data-i18n-html="sitemap_index.for_ai_agents"><code>llms.txt</code> · for AI agents</a>
+ <a href="/llms-full.txt" data-i18n-html="sitemap_index.long_form"><code>llms-full.txt</code> · long form</a>
+ <a href="/api/features.json" data-i18n-html="sitemap_index.machine_manifest"><code>features.json</code> · machine manifest</a>
+ <a href="/changelog" data-i18n-html="sitemap_index.what_s_new"><code>changelog</code> · what's new</a>
+ <a href="/openapi.json" data-i18n-html="sitemap_index.http_api"><code>openapi.json</code> · HTTP API</a>
</div>
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 997 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 999 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd id="sm-filter-kbd" aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" role="status" aria-live="polite"><span id="sm-filter-count"></span><span id="sm-filter-hint" aria-hidden="true"></span></p>
<section class="sm-new" id="sm-new" aria-labelledby="sm-new-title">
- <h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
- <p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
+ <h2 id="sm-new-title" data-i18n-html="sitemap_index.newestfull_changelog">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
+ <p class="sm-section-desc" data-i18n="sitemap_index.the_9_most_recently_launched_pages_straight">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
<li>
<a href="/cad">
@@ -191,22 +191,22 @@
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
- <a href="#main">Main</a>
- <a href="#build">Build</a>
- <a href="#labs">Labs</a>
- <a href="#crypto">Crypto</a>
- <a href="#agent-tools">Agent Tools</a>
- <a href="#account">Account</a>
- <a href="#learn">Learn</a>
- <a href="#blog">Blog</a>
- <a href="#legal">Legal</a>
- <a href="#machine">Machine-readable</a>
- <a href="#news">News</a>
+ <a href="#main" data-i18n="sitemap_index.main">Main</a>
+ <a href="#build" data-i18n="sitemap_index.build">Build</a>
+ <a href="#labs" data-i18n="sitemap_index.labs">Labs</a>
+ <a href="#crypto" data-i18n="sitemap_index.crypto">Crypto</a>
+ <a href="#agent-tools" data-i18n="sitemap_index.agent_tools">Agent Tools</a>
+ <a href="#account" data-i18n="sitemap_index.account">Account</a>
+ <a href="#learn" data-i18n="sitemap_index.learn">Learn</a>
+ <a href="#blog" data-i18n="sitemap_index.blog">Blog</a>
+ <a href="#legal" data-i18n="sitemap_index.legal">Legal</a>
+ <a href="#machine" data-i18n="sitemap_index.machine_readable">Machine-readable</a>
+ <a href="#news" data-i18n="sitemap_index.news">News</a>
</nav>
<section class="sm-section" id="main">
<header>
- <h2><span data-i18n="sitemap_index.section_main">Main</span><span class="sm-count" data-count>65</span></h2>
- <p class="sm-section-desc">Entry points into the product.</p>
+ <h2><span data-i18n="sitemap_index.section_main">Main</span><span class="sm-count" data-count>66</span></h2>
+ <p class="sm-section-desc" data-i18n="sitemap_index.entry_points_into_the_product">Entry points into the product.</p>
</header>
<ul class="sm-list">
<li>
@@ -475,6 +475,13 @@
<span class="sm-desc" data-i18n="sitemap_index.d_notifications">Every payment, sale, remix, follow, quest, and royalty notification on three.ws: all in one place, filterable by category.</span>
</a>
</li>
+ <li>
+ <a href="/approvals">
+ <span class="sm-title"><span data-i18n="sitemap_index.t_approvals">Approvals</span><span class="sm-badge sm-badge-internal" data-i18n="sitemap_index.badge_internal">internal</span></span>
+ <span class="sm-path" translate="no">/approvals</span>
+ <span class="sm-desc" data-i18n="sitemap_index.d_approvals">Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.</span>
+ </a>
+ </li>
<li>
<a href="/skills">
<span class="sm-title"><span data-i18n="sitemap_index.t_skills">Skills Marketplace</span><span class="sm-badge sm-badge-internal" data-i18n="sitemap_index.badge_internal">internal</span></span>
@@ -670,7 +677,7 @@
<section class="sm-section" id="build">
<header>
<h2><span data-i18n="sitemap_index.section_build">Build</span><span class="sm-count" data-count>85</span></h2>
- <p class="sm-section-desc">Create and customize an agent.</p>
+ <p class="sm-section-desc" data-i18n="sitemap_index.create_and_customize_an_agent">Create and customize an agent.</p>
</header>
<ul class="sm-list">
<li>
@@ -1274,7 +1281,7 @@
<section class="sm-section" id="labs">
<header>
<h2><span data-i18n="sitemap_index.section_labs">Labs</span><span class="sm-count" data-count>25</span></h2>
- <p class="sm-section-desc">Experimental features actively shipping. Expect fast iteration.</p>
+ <p class="sm-section-desc" data-i18n="sitemap_index.experimental_features_actively_shipping_expe">Experimental features actively shipping. Expect fast iteration.</p>
</header>
<ul class="sm-list">
<li>
@@ -1458,7 +1465,7 @@
<section class="sm-section" id="crypto">
<header>
<h2><span data-i18n="sitemap_index.section_crypto">Crypto</span><span class="sm-count" data-count>159</span></h2>
- <p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
+ <p class="sm-section-desc" data-i18n="sitemap_index.on_chain_features_pay_per_call_token">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
<li>
@@ -2580,7 +2587,7 @@
<section class="sm-section" id="agent-tools">
<header>
<h2><span data-i18n="sitemap_index.section_agent-tools">Agent Tools</span><span class="sm-count" data-count>10</span></h2>
- <p class="sm-section-desc">Manage, talk to, and deploy individual agents.</p>
+ <p class="sm-section-desc" data-i18n="sitemap_index.manage_talk_to_and_deploy_individual_agents">Manage, talk to, and deploy individual agents.</p>
</header>
<ul class="sm-list">
<li>
@@ -2659,7 +2666,7 @@
<section class="sm-section" id="account">
<header>
<h2><span data-i18n="sitemap_index.section_account">Account</span><span class="sm-count" data-count>14</span></h2>
- <p class="sm-section-desc">Sign-in, dashboard, billing.</p>
+ <p class="sm-section-desc" data-i18n="sitemap_index.sign_in_dashboard_billing">Sign-in, dashboard, billing.</p>
</header>
<ul class="sm-list">
<li>
@@ -2765,8 +2772,8 @@
<section class="sm-section" id="learn">
<header>
- <h2><span data-i18n="sitemap_index.section_learn">Learn</span><span class="sm-count" data-count>461</span></h2>
- <p class="sm-section-desc">Docs, tutorials, and reference.</p>
+ <h2><span data-i18n="sitemap_index.section_learn">Learn</span><span class="sm-count" data-count>462</span></h2>
+ <p class="sm-section-desc" data-i18n="sitemap_index.docs_tutorials_and_reference">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
<li>
@@ -4463,6 +4470,13 @@
<span class="sm-desc" data-i18n="sitemap_index.d_docs_notifications">Everything that happens to your work on three.ws (a payment lands, a skill sells, someone remixes your model, follows you, a quest finishes, a royalty arrives) becomes a row in one per-user inbox.</span>
</a>
</li>
+ <li>
+ <a href="/docs/approvals">
+ <span class="sm-title"><span data-i18n="sitemap_index.t_docs_approvals">Docs: Approvals</span></span>
+ <span class="sm-path" translate="no">/docs/approvals</span>
+ <span class="sm-desc" data-i18n="sitemap_index.d_docs_approvals">How agents pause for your yes before moving funds: the /approvals inbox, push Approve and Deny, signed deep links, payload-hash checks, auto-approve rules, and the API.</span>
+ </a>
+ </li>
<li>
<a href="/docs/checkout-companion">
<span class="sm-title"><span data-i18n="sitemap_index.t_docs_checkout_companion">Docs: Checkout companion</span></span>
@@ -6002,7 +6016,7 @@
<section class="sm-section" id="blog">
<header>
<h2><span data-i18n="sitemap_index.section_blog">Blog</span><span class="sm-count" data-count>39</span></h2>
- <p class="sm-section-desc">Long-form announcements, launches, and writing from three.ws.</p>
+ <p class="sm-section-desc" data-i18n="sitemap_index.long_form_announcements_launches_and_writing">Long-form announcements, launches, and writing from three.ws.</p>
</header>
<ul class="sm-list">
<li>
@@ -6356,7 +6370,7 @@
<section class="sm-section" id="machine">
<header>
<h2><span data-i18n="sitemap_index.section_machine">Machine-readable</span><span class="sm-count" data-count>18</span></h2>
- <p class="sm-section-desc">Indexes and well-known files for crawlers and AI agents.</p>
+ <p class="sm-section-desc" data-i18n="sitemap_index.indexes_and_well_known_files_for_crawlers">Indexes and well-known files for crawlers and AI agents.</p>
</header>
<ul class="sm-list">
<li>
@@ -6491,7 +6505,7 @@
<section class="sm-section" id="news">
<header>
<h2><span data-i18n="sitemap_index.section_news">News</span><span class="sm-count" data-count>112</span></h2>
- <p class="sm-section-desc">Product launches, integrations, and announcements from three.ws.</p>
+ <p class="sm-section-desc" data-i18n="sitemap_index.product_launches_integrations_and_announceme">Product launches, integrations, and announcements from three.ws.</p>
</header>
<ul class="sm-list">
<li>
@@ -7282,10 +7296,10 @@
</section>
<div class="sm-empty" id="sm-empty" hidden>
<p><span data-i18n="sitemap_index.no_pages_match">No pages match</span> &ldquo;<span id="sm-empty-q"></span>&rdquo;.</p>
- <p class="sm-empty-hint">Try a shorter word, or search everything: global search covers agents, coins, and skills too.</p>
+ <p class="sm-empty-hint" data-i18n="sitemap_index.try_a_shorter_word_or_search_everything">Try a shorter word, or search everything: global search covers agents, coins, and skills too.</p>
<div class="sm-empty-actions">
- <button type="button" id="sm-empty-clear">Clear filter</button>
- <a id="sm-empty-search" href="/search">Search all of three.ws</a>
+ <button type="button" id="sm-empty-clear" data-i18n="sitemap_index.clear_filter">Clear filter</button>
+ <a id="sm-empty-search" href="/search" data-i18n="sitemap_index.search_all_of_three_ws">Search all of three.ws</a>
</div>
</div>
</main>
diff --git a/src/approvals-page.js b/src/approvals-page.js
new file mode 100644
index 000000000..63c42f07b
--- /dev/null
+++ b/src/approvals-page.js
@@ -0,0 +1,808 @@
+// Approval inbox (pages/approvals.html, routes /approvals and /approvals/:id).
+//
+// Every gated agent action that needs the owner's yes lands here as a card with
+// the confirmation table (recipient, amount, asset, chain) and its risk notes.
+// Approve posts the payload_hash the owner is looking at, so the server refuses
+// to run anything that differs from what was shown; a deep link from a push,
+// email or chat message carries a signed token (?t=) that the server verifies
+// against the request on file before the card is trusted.
+//
+// Also hosts the per-account auto-approve rules and the approval audit log.
+// API: api/approvals/*.js, api/audit-log.js. Doc: docs/approvals.md.
+
+import { apiFetch } from './api.js';
+import { escNotif as esc, relTime } from './notifications.js';
+import { isPushSupported, getPushState, enablePush } from './push-notifications.js';
+
+const PAGE_SIZE = 20;
+const TICK_MS = 10_000;
+const SOON_MS = 3 * 60_000;
+
+const GROUP_OF = {
+ pending: 'pending',
+ approved: 'done', executing: 'done', executed: 'done', failed: 'done',
+ denied: 'denied',
+ expired: 'expired',
+};
+
+const STATUS_LABEL = {
+ pending: 'Pending', approved: 'Approved', executing: 'Executing', executed: 'Executed',
+ failed: 'Failed', denied: 'Denied', expired: 'Expired',
+};
+
+const VIA_LABEL = {
+ web: 'on the web', push: 'from a push notification', telegram: 'in Telegram', mobile: 'in the app',
+ email: 'from email', auto_policy: 'by an auto-approve rule', bulk: 'in a bulk deny',
+};
+
+const LINK_PROBLEM = {
+ malformed: 'This link is incomplete. Review the request below before deciding.',
+ bad_signature: 'This link was not issued by three.ws. Do not trust where it came from; review the request below.',
+ wrong_request: 'This link belongs to a different request. Review the request below before deciding.',
+ payload_changed: 'The action on file no longer matches the one in your link, so the link will not approve it. Review what is on file below.',
+ expired: 'This link has expired.',
+};
+
+const EMPTY_COPY = {
+ pending: ['✅', 'Nothing waiting on you', 'When an agent wants to do something that crosses one of your guardrails, it pauses here and asks. You will get a push, chat message or email with a link straight to it.'],
+ done: ['🗂', 'No approved actions yet', 'Actions you approve, and what happened when they ran, show up here.'],
+ denied: ['🛑', 'Nothing denied', 'Requests you turn down are kept here so you can see what your agents tried.'],
+ expired: ['⏳', 'Nothing expired', 'A request you do not answer in time expires and never runs. Those land here.'],
+ all: ['🛂', 'No approval requests yet', 'Set guardrails on an agent wallet and any action that trips one will wait here for your yes.'],
+};
+
+const AUDIT_LABEL = {
+ approval_requested: ['Requested', 'warn'],
+ approval_auto_approved: ['Auto-approved', 'ok'],
+ approval_approved: ['Approved', 'ok'],
+ approval_denied: ['Denied', 'bad'],
+ approval_executed: ['Executed', 'ok'],
+ approval_failed: ['Failed', 'bad'],
+ approval_policy_created: ['Rule added', ''],
+ approval_policy_revoked: ['Rule revoked', ''],
+};
+
+const state = {
+ group: 'pending',
+ agent: '',
+ items: [],
+ cursor: null,
+ counts: {},
+ agents: [],
+ selected: new Set(),
+ focus: null,
+ focusToken: null,
+ loading: false,
+ auditCursor: null,
+ venues: [],
+ maxCap: 0,
+ ownAgents: [],
+};
+
+const $ = (id) => document.getElementById(id);
+const els = {};
+
+// ── API ─────────────────────────────────────────────────────────────────────────
+
+async function call(path, { method = 'GET', body } = {}) {
+ const res = await apiFetch(path, {
+ method,
+ allowAnonymous: method === 'GET',
+ headers: body ? { 'content-type': 'application/json' } : undefined,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const data = await res.json().catch(() => ({}));
+ return { ok: res.ok, status: res.status, data };
+}
+
+function errText(r, fallback) {
+ return r.data?.error_description || r.data?.error || fallback;
+}
+
+function announce(msg) {
+ els.live.textContent = '';
+ requestAnimationFrame(() => { els.live.textContent = msg; });
+}
+
+function showError(msg, retry) {
+ els.error.innerHTML = `<strong>${esc(msg)}</strong>${retry ? '<br><button type="button" class="btn btn-sm" data-retry>Try again</button>' : ''}`;
+ els.error.hidden = false;
+ if (retry) els.error.querySelector('[data-retry]').addEventListener('click', () => { els.error.hidden = true; retry(); }, { once: true });
+}
+
+// ── formatting ──────────────────────────────────────────────────────────────────
+
+function timeLeft(iso) {
+ return new Date(iso).getTime() - Date.now();
+}
+
+function fmtLeft(ms) {
+ if (ms <= 0) return 'Expired';
+ const m = Math.floor(ms / 60_000);
+ if (m < 1) return 'Expires in under a minute';
+ if (m < 60) return `Expires in ${m} min`;
+ const h = Math.floor(m / 60);
+ return `Expires in ${h}h ${m % 60}m`;
+}
+
+function fmtDate(iso) {
+ return new Date(iso).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
+}
+
+function liveStatus(item) {
+ return item.status === 'pending' && timeLeft(item.expires_at) <= 0 ? 'expired' : item.status;
+}
+
+// ── cards ───────────────────────────────────────────────────────────────────────
+
+function tableHtml(item) {
+ const rows = (item.confirmation || []).map((r) => {
+ const mono = r.key === 'recipient' && r.full;
+ const copy = r.full ? `<button type="button" class="ap-copy" data-copy="${esc(r.full)}" aria-label="Copy full ${esc(r.label.toLowerCase())}">Copy</button>` : '';
+ return `<tr><th scope="row">${esc(r.label)}</th><td${mono ? ' class="mono"' : ''} title="${esc(r.full || r.value)}">${esc(r.value)}${copy}</td></tr>`;
+ }).join('');
+ return `<table class="ap-table"><caption class="sr-only">${item.status === 'pending' ? 'What approving will do' : 'The action this request covered'}</caption><tbody>${rows}</tbody></table>`;
+}
+
+function outcomeHtml(item) {
+ const s = liveStatus(item);
+ const decided = item.decided_at ? `${STATUS_LABEL[item.status === 'denied' ? 'denied' : 'approved']} ${VIA_LABEL[item.decided_via] || ''} ${relTime(item.decided_at)}.` : '';
+ if (s === 'executed') {
+ const tx = item.explorer ? ` <a href="${esc(item.explorer)}" target="_blank" rel="noopener">View transaction</a>` : '';
+ return `<div class="ap-outcome">${esc(decided)} Executed${item.executed_at ? ` ${esc(relTime(item.executed_at))}` : ''}.${item.result?.note ? ` ${esc(item.result.note)}` : ''}${tx}</div>`;
+ }
+ if (s === 'failed') {
+ return `<div class="ap-outcome">${esc(decided)} <strong>It did not execute:</strong> ${esc(item.result?.note || 'the action failed when it ran.')} Nothing else will be attempted for this request.</div>`;
+ }
+ if (s === 'approved' || s === 'executing') {
+ return `<div class="ap-outcome">${esc(decided)} Executing now. This page updates when it settles.</div>`;
+ }
+ if (s === 'denied') return `<div class="ap-outcome">${esc(decided)} Nothing was executed.</div>`;
+ if (s === 'expired') return '<div class="ap-outcome">Expired without an answer. Nothing was executed; the agent will ask again if the action is still wanted.</div>';
+ return '';
+}
+
+function cardHtml(item, { focus = false } = {}) {
+ const s = liveStatus(item);
+ const pending = s === 'pending';
+ const agent = item.agent?.name
+ ? `<a href="/agent/${esc(item.agent.id)}">${esc(item.agent.name)}</a>`
+ : (item.agent ? 'An agent' : 'Your account');
+ const risks = item.risk_notes?.length
+ ? `<ul class="ap-risks" aria-label="Risk notes">${item.risk_notes.map((n) => `<li>${esc(n)}</li>`).join('')}</ul>`
+ : '';
+ const gate = item.gate_reason ? `<p class="ap-gate">Why it asked: ${esc(item.gate_reason)}</p>` : '';
+ const left = timeLeft(item.expires_at);
+ const check = pending && !focus
+ ? `<label class="ap-check"><input type="checkbox" data-select="${esc(item.id)}"${state.selected.has(item.id) ? ' checked' : ''} /><span class="sr-only">Select for bulk deny</span></label>`
+ : '';
+ const foot = pending
+ ? `<div class="ap-foot">
+ <span class="ap-expiry${left < SOON_MS ? ' is-soon' : ''}" data-expiry="${esc(item.expires_at)}">${esc(fmtLeft(left))}</span>
+ <div class="ap-actions">
+ <button type="button" class="btn btn-deny" data-deny="${esc(item.id)}">Deny</button>
+ <button type="button" class="btn btn-approve" data-approve="${esc(item.id)}">Approve</button>
+ </div>
+ </div>`
+ : outcomeHtml(item);
+ return `<article class="ap-card${focus ? ' is-focus' : ''}" data-id="${esc(item.id)}" aria-label="${esc(item.summary)}">
+ <div class="ap-head">
+ ${check}
+ <div class="ap-title">
+ <div class="ap-summary">${esc(item.summary)}</div>
+ <div class="ap-meta"><span>${agent}</span><span>${esc(item.venue_label || item.action_type)}</span><span title="${esc(fmtDate(item.created_at))}">${esc(relTime(item.created_at))}</span></div>
+ </div>
+ <span class="pill pill-${esc(s)}">${esc(STATUS_LABEL[s] || s)}</span>
+ </div>
+ ${tableHtml(item)}
+ ${risks}
+ ${gate}
+ ${foot}
+ <div class="ap-card-msg" data-msg role="status"></div>
+ ${focus ? `<p class="ap-hash" title="The exact action approving will run is pinned to this fingerprint">Action fingerprint ${esc(item.payload_hash)}</p>` : ''}
+ </article>`;
+}
+
+function skeletonHtml(n = 3) {
+ return Array.from({ length: n }, () => `
+ <div class="ap-skel" aria-hidden="true">
+ <div class="skeleton" style="height:16px;width:62%"></div>
+ <div class="skeleton" style="height:11px;width:34%"></div>
+ <div class="skeleton" style="height:120px;width:100%;border-radius:10px"></div>
+ </div>`).join('');
+}
+
+function emptyHtml() {
+ const [icon, title, body] = EMPTY_COPY[state.group];
+ const filtered = state.agent ? '<button type="button" class="btn" data-clear-agent>Show every agent</button>' : '';
+ const cta = !filtered && state.group === 'pending' ? '<a class="btn" href="/dashboard/wallets">Review wallet guardrails</a>' : filtered;
+ return `<div class="ap-empty"><div class="ap-empty-icon" aria-hidden="true">${icon}</div><h3>${esc(title)}</h3><p>${esc(body)}</p>${cta}</div>`;
+}
+
+// ── list ────────────────────────────────────────────────────────────────────────
+
+function visibleItems() {
+ return state.focus ? state.items.filter((i) => i.id !== state.focus.id) : state.items;
+}
+
+function renderList() {
+ const items = visibleItems();
+ els.list.innerHTML = items.length ? items.map((i) => cardHtml(i)).join('') : emptyHtml();
+ els.more.hidden = !state.cursor;
+ renderToolbar();
+}
+
+function renderCounts() {
+ for (const el of document.querySelectorAll('[data-count]')) {
+ const n = state.counts[el.dataset.count] || 0;
+ el.textContent = n > 99 ? '99+' : String(n);
+ el.classList.toggle('has', n > 0);
+ }
+ document.title = state.counts.pending ? `(${state.counts.pending}) Approvals · three.ws` : 'Approvals · three.ws';
+}
+
+function renderToolbar() {
+ const pendingIds = visibleItems().filter((i) => liveStatus(i) === 'pending').map((i) => i.id);
+ for (const id of [...state.selected]) if (!pendingIds.includes(id)) state.selected.delete(id);
+ els.selectAllWrap.hidden = pendingIds.length < 2;
+ els.selectAll.checked = pendingIds.length > 0 && pendingIds.every((id) => state.selected.has(id));
+ els.selectAll.indeterminate = state.selected.size > 0 && !els.selectAll.checked;
+ els.bulk.hidden = pendingIds.length < 1;
+ els.bulk.disabled = state.selected.size === 0;
+ els.bulk.textContent = state.selected.size ? `Deny selected (${state.selected.size})` : 'Deny selected';
+
+ const options = ['<option value="">All agents</option>', ...state.agents.map((a) => `<option value="${esc(a.id)}">${esc(a.name || 'Unnamed agent')}</option>`)];
+ els.agent.innerHTML = options.join('');
+ els.agent.value = state.agent;
+ els.agent.hidden = state.agents.length < 2 && !state.agent;
+}
+
+async function loadList({ reset = true } = {}) {
+ if (state.loading) return;
+ state.loading = true;
+ if (reset) {
+ state.cursor = null;
+ state.items = [];
+ els.list.innerHTML = skeletonHtml();
+ els.list.setAttribute('aria-busy', 'true');
+ }
+ els.moreBtn.disabled = true;
+ const qs = new URLSearchParams({ status: state.group, limit: String(PAGE_SIZE) });
+ if (state.agent) qs.set('agent', state.agent);
+ if (!reset && state.cursor) qs.set('cursor', state.cursor);
+ try {
+ const r = await call(`/api/approvals?${qs}`);
+ if (r.status === 401) return showAuthWall();
+ if (!r.ok) {
+ if (reset) els.list.innerHTML = '';
+ return showError(`Could not load your approvals. ${errText(r, '')}`.trim(), () => loadList({ reset }));
+ }
+ els.error.hidden = true;
+ state.items = reset ? r.data.items : [...state.items, ...r.data.items];
+ state.cursor = r.data.next_cursor;
+ state.counts = r.data.counts || {};
+ state.agents = r.data.agents || [];
+ els.main.hidden = false;
+ renderCounts();
+ renderList();
+ } catch {
+ if (reset) els.list.innerHTML = '';
+ showError('Could not reach three.ws. Check your connection.', () => loadList({ reset }));
+ } finally {
+ state.loading = false;
+ els.moreBtn.disabled = false;
+ els.list.removeAttribute('aria-busy');
+ }
+}
+
+function setGroup(group) {
+ if (group === state.group) return;
+ state.group = group;
+ state.selected.clear();
+ for (const t of els.tabs.querySelectorAll('.ap-tab')) t.setAttribute('aria-selected', String(t.dataset.group === group));
+ loadList();
+}
+
+// ── decisions ───────────────────────────────────────────────────────────────────
+
+function findItem(id) {
+ if (state.focus?.id === id) return state.focus;
+ return state.items.find((i) => i.id === id) || null;
+}
+
+function cardMsg(card, text, kind = '') {
+ const el = card?.querySelector('[data-msg]');
+ if (!el) return;
+ el.className = `ap-card-msg${kind ? ` ${kind}` : ''}`;
+ el.innerHTML = text;
+}
+
+function moveCount(fromStatus, toStatus) {
+ const from = GROUP_OF[fromStatus];
+ const to = GROUP_OF[toStatus];
+ if (!from || !to || from === to) return;
+ state.counts[from] = Math.max(0, (state.counts[from] || 0) - 1);
+ state.counts[to] = (state.counts[to] || 0) + 1;
+ renderCounts();
+}
+
+function replaceItem(next) {
+ const prev = findItem(next.id);
+ if (prev) moveCount(liveStatus(prev), next.status);
+ if (state.focus?.id === next.id) state.focus = { ...state.focus, ...next };
+ state.items = state.items.map((i) => (i.id === next.id ? { ...i, ...next } : i));
+}
+
+function rerenderCard(id, msg, kind) {
+ const item = findItem(id);
+ for (const card of document.querySelectorAll(`.ap-card[data-id="${CSS.escape(id)}"]`)) {
+ const focus = card.classList.contains('is-focus');
+ card.outerHTML = cardHtml(item, { focus });
+ }
+ if (msg) for (const card of document.querySelectorAll(`.ap-card[data-id="${CSS.escape(id)}"]`)) cardMsg(card, msg, kind);
+ renderToolbar();
+}
+
+function outcomeMessage(req, idempotent) {
+ if (idempotent) return ['This was already decided earlier. Nothing ran twice.', ''];
+ if (req.status === 'executed') return ['Approved and executed.', 'ok'];
+ if (req.status === 'failed') return [`Approved, but it did not execute: ${esc((req.result?.note || 'the action failed').replace(/\.$/, ''))}.`, 'err'];
+ if (req.status === 'denied') return ['Denied. Nothing was executed.', ''];
+ return ['Approved. Executing now.', 'ok'];
+}
+
+async function decide(id, decision) {
+ const item = findItem(id);
+ if (!item) return;
+ const cards = document.querySelectorAll(`.ap-card[data-id="${CSS.escape(id)}"]`);
+ for (const c of cards) for (const b of c.querySelectorAll('[data-approve],[data-deny]')) b.disabled = true;
+ const btn = document.querySelector(`.ap-card[data-id="${CSS.escape(id)}"] [data-${decision}]`);
+ if (btn) btn.textContent = decision === 'approve' ? 'Approving…' : 'Denying…';
+
+ const body = { decision, via: 'web' };
+ if (decision === 'approve') body.payload_hash = item.payload_hash;
+ if (state.focus?.id === id && state.focusToken) body.token = state.focusToken;
+
+ let r;
+ try {
+ r = await call(`/api/approvals/${encodeURIComponent(id)}`, { method: 'POST', body });
+ } catch {
+ rerenderCard(id, 'Could not reach three.ws, so nothing was decided. Try again.', 'err');
+ return;
+ }
+ if (r.ok) {
+ const [msg, kind] = outcomeMessage(r.data.request, r.data.idempotent);
+ replaceItem(r.data.request);
+ rerenderCard(id, msg, kind);
+ announce(msg.replace(/<[^>]+>/g, ''));
+ loadAudit();
+ if (r.data.request.status === 'approved' || r.data.request.status === 'executing') pollUntilSettled(id);
+ return;
+ }
+ if (r.status === 410) {
+ replaceItem({ ...item, status: 'expired' });
+ rerenderCard(id, esc(errText(r, 'This request expired. Nothing was executed.')), 'err');
+ return;
+ }
+ if (r.data?.error === 'payload_mismatch' || r.data?.error === 'link_mismatch') {
+ await refreshOne(id);
+ rerenderCard(id, `${esc(errText(r, 'The action changed.'))} The card now shows what is on file.`, 'err');
+ return;
+ }
+ if (r.data?.error === 'already_denied' || r.data?.error === 'already_decided') {
+ await refreshOne(id);
+ rerenderCard(id, esc(errText(r, 'Already decided.')), 'err');
+ return;
+ }
+ rerenderCard(id, esc(errText(r, 'That did not go through. Nothing was decided.')), 'err');
+}
+
+async function refreshOne(id) {
+ const r = await call(`/api/approvals/${encodeURIComponent(id)}`).catch(() => null);
+ if (r?.ok) replaceItem(r.data.request);
+}
+
+// An approved action executes inside the decision request, so this only runs
+// when the server answered before the chain settled.
+async function pollUntilSettled(id, attempt = 0) {
+ if (attempt >= 6) return;
+ await new Promise((resolve) => setTimeout(resolve, 2_000 * (attempt + 1)));
+ await refreshOne(id);
+ const item = findItem(id);
+ if (!item) return;
+ if (item.status === 'approved' || item.status === 'executing') return pollUntilSettled(id, attempt + 1);
+ const [msg, kind] = outcomeMessage(item, false);
+ rerenderCard(id, msg, kind);
+}
+
+function armApprove(btn) {
+ if (btn.classList.contains('is-armed')) {
+ decide(btn.dataset.approve, 'approve');
+ return;
+ }
+ disarmAll();
+ btn.classList.add('is-armed');
+ btn.textContent = 'Confirm approve';
+ announce('Press approve again to confirm. Escape cancels.');
+}
+
+function disarmAll() {
+ for (const b of document.querySelectorAll('.btn-approve.is-armed')) {
+ b.classList.remove('is-armed');
+ b.textContent = 'Approve';
+ }
+}
+
+async function bulkDeny() {
+ const ids = [...state.selected];
+ if (!ids.length) return;
+ els.bulk.disabled = true;
+ els.bulk.textContent = `Denying ${ids.length}…`;
+ try {
+ const r = await call('/api/approvals', { method: 'POST', body: { action: 'bulk_deny', ids } });
+ if (!r.ok) {
+ showError(`Bulk deny failed: ${errText(r, 'unknown error')}. Nothing was denied.`);
+ return;
+ }
+ const denied = new Set(r.data.denied);
+ for (const id of denied) {
+ const card = els.list.querySelector(`.ap-card[data-id="${CSS.escape(id)}"]`);
+ if (card) card.classList.add('is-leaving');
+ const item = findItem(id);
+ if (item) moveCount(liveStatus(item), 'denied');
+ state.selected.delete(id);
+ }
+ const skipped = r.data.skipped?.length || 0;
+ announce(`Denied ${denied.size}${skipped ? `, ${skipped} were already decided` : ''}.`);
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ if (state.group === 'pending') state.items = state.items.filter((i) => !denied.has(i.id));
+ else state.items = state.items.map((i) => (denied.has(i.id) ? { ...i, status: 'denied' } : i));
+ if (state.focus && denied.has(state.focus.id)) state.focus = { ...state.focus, status: 'denied' };
+ renderList();
+ if (state.focus) renderFocus();
+ loadAudit();
+ } catch {
+ showError('Could not reach three.ws. Nothing was denied.');
+ } finally {
+ renderToolbar();
+ }
+}
+
+// ── deep link ───────────────────────────────────────────────────────────────────
+
+function renderFocus(banner = '') {
+ if (!state.focus) { els.focus.hidden = true; return; }
+ els.focus.innerHTML = `${banner || els.focus.dataset.banner || ''}${cardHtml(state.focus, { focus: true })}<div class="ap-bar"><a class="btn btn-sm" href="/approvals">Back to all approvals</a></div>`;
+ if (banner) els.focus.dataset.banner = banner;
+ els.focus.hidden = false;
+}
+
+async function loadFocus(id) {
+ els.focus.hidden = false;
+ els.focus.innerHTML = skeletonHtml(1);
+ const qs = state.focusToken ? `?t=${encodeURIComponent(state.focusToken)}` : '';
+ let r;
+ try {
+ r = await call(`/api/approvals/${encodeURIComponent(id)}${qs}`);
+ } catch {
+ els.focus.innerHTML = '<div class="notice notice-error">Could not load this request. Check your connection and reload.</div>';
+ return;
+ }
+ if (r.status === 401) return showAuthWall();
+ if (!r.ok) {
+ const nf = r.status === 404 || r.status === 400;
+ els.focus.innerHTML = `<div class="notice notice-warn"><strong>${nf ? 'This request is not on your account.' : esc(errText(r, 'Could not load this request.'))}</strong>${nf ? ' It may belong to a different sign-in. Your other approvals are below.' : ''}</div>`;
+ return;
+ }
+ const req = r.data.request;
+ state.focus = req;
+ let banner = '';
+ if (state.focusToken && req.link_verified) {
+ banner = '<div class="notice notice-ok"><strong>Link verified.</strong> This matches the request on file, signed by three.ws. Check the table, then decide.</div>';
+ } else if (state.focusToken && req.link_problem) {
+ banner = `<div class="notice notice-warn"><strong>Check this carefully.</strong> ${esc(LINK_PROBLEM[req.link_problem] || 'This link could not be verified.')}</div>`;
+ if (req.link_problem !== 'expired') state.focusToken = null;
+ }
+ renderFocus(banner);
+ els.focus.querySelector('.ap-card')?.scrollIntoView({ block: 'center', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
+}
+
+// ── auto-approve rules ──────────────────────────────────────────────────────────
+
+function policyHtml(p) {
+ const venues = p.venues.map((v) => state.venues.find((x) => x.key === v)?.label || v).join(', ');
+ const scope = p.agent ? `Only ${esc(p.agent.name || 'one agent')}` : 'Every agent';
+ let when = `added ${relTime(p.created_at)}`;
+ if (p.revoked_at) when = `revoked ${relTime(p.revoked_at)}`;
+ else if (!p.active) when = 'expired';
+ else if (p.expires_at) when += `, ends ${fmtDate(p.expires_at)}`;
+ return `<div class="ap-policy${p.active ? '' : ' is-off'}">
+ <div class="ap-policy-body">
+ <div class="ap-policy-label">Up to $${esc(p.max_usd.toLocaleString())} per action: ${esc(venues)}</div>
+ <div class="ap-policy-meta">${scope} · ${esc(when)}</div>
+ </div>
+ ${p.active ? `<button type="button" class="btn btn-deny btn-sm" data-revoke="${esc(p.id)}">Revoke</button>` : ''}
+ </div>`;
+}
+
+function renderPolicies(policies) {
+ const live = policies.filter((p) => p.active);
+ els.policies.innerHTML = policies.length
+ ? policies.map(policyHtml).join('')
+ : '<div class="notice notice-info"><strong>No rules: every gated action asks you.</strong> That is the safest setting. Add a rule only for small actions you would always say yes to.</div>';
+ if (live.length === 0 && policies.length) {
+ els.policies.insertAdjacentHTML('afterbegin', '<div class="notice notice-info">No rule is active, so every gated action asks you.</div>');
+ }
+}
+
+async function loadPolicies() {
+ const [r, agents] = await Promise.all([
+ call('/api/approvals/policies').catch(() => null),
+ call('/api/agents').catch(() => null),
+ ]);
+ if (!r?.ok) {
+ els.policies.innerHTML = '<div class="notice notice-error">Could not load your auto-approve rules. <button type="button" class="btn btn-sm" data-reload-policies>Try again</button></div>';
+ return;
+ }
+ state.venues = r.data.venues || [];
+ state.maxCap = r.data.max_usd_cap || 0;
+ els.venues.innerHTML = state.venues.map((v, i) => `<label class="ap-check"><input type="checkbox" name="venue" value="${esc(v.key)}"${i === 0 ? ' checked' : ''} /><span>${esc(v.label)}</span></label>`).join('');
+ els.max.max = String(state.maxCap);
+ els.max.placeholder = `e.g. ${Math.min(25, state.maxCap)}`;
+ els.maxHint.textContent = `Anything above this, or above $${state.maxCap.toLocaleString()} in any case, still asks.`;
+ state.ownAgents = agents?.ok ? (agents.data.agents || []) : [];
+ els.policyAgent.innerHTML = ['<option value="">Every agent I own</option>', ...state.ownAgents.map((a) => `<option value="${esc(a.id)}">${esc(a.name || 'Unnamed agent')}</option>`)].join('');
+ renderPolicies(r.data.policies || []);
+}
+
+async function createPolicy(e) {
+ e.preventDefault();
+ const venues = [...els.venues.querySelectorAll('input[name="venue"]:checked')].map((i) => i.value);
+ const max = Number(els.max.value);
+ const msg = (t, err = false) => { els.formMsg.textContent = t; els.formMsg.className = `ap-form-msg${err ? ' err' : ''}`; };
+ if (!venues.length) return msg('Pick at least one venue.', true);
+ if (!Number.isFinite(max) || max <= 0 || max > state.maxCap) {
+ els.max.focus();
+ return msg(`Enter a dollar amount between 1 and ${state.maxCap.toLocaleString()}.`, true);
+ }
+ const body = { venues, max_usd: max };
+ if (els.policyAgent.value) body.agent_id = els.policyAgent.value;
+ const days = Number(els.policyExpiry.value);
+ if (days) body.expires_at = new Date(Date.now() + days * 86_400_000).toISOString();
+ els.policySubmit.disabled = true;
+ msg('Saving…');
+ try {
+ const r = await call('/api/approvals/policies', { method: 'POST', body });
+ if (!r.ok) return msg(errText(r, 'Could not save the rule.'), true);
+ msg('Rule added. It applies to the next request.');
+ els.max.value = '';
+ await loadPolicies();
+ loadAudit();
+ } catch {
+ msg('Could not reach three.ws. The rule was not saved.', true);
+ } finally {
+ els.policySubmit.disabled = false;
+ }
+}
+
+async function revokePolicy(btn) {
+ btn.disabled = true;
+ btn.textContent = 'Revoking…';
+ try {
+ const r = await call(`/api/approvals/policies?id=${encodeURIComponent(btn.dataset.revoke)}`, { method: 'DELETE' });
+ if (!r.ok) {
+ btn.disabled = false;
+ btn.textContent = 'Revoke';
+ showError(`Could not revoke the rule: ${errText(r, 'unknown error')}. It is still active.`);
+ return;
+ }
+ announce('Rule revoked. Every matching action asks you again.');
+ await loadPolicies();
+ loadAudit();
+ } catch {
+ btn.disabled = false;
+ btn.textContent = 'Revoke';
+ showError('Could not reach three.ws. The rule is still active.');
+ }
+}
+
+// ── audit log ───────────────────────────────────────────────────────────────────
+
+function auditDetail(ev) {
+ const m = ev.meta || {};
+ const parts = [];
+ if (m.summary) parts.push(m.summary);
+ else if (m.venues) parts.push(`${m.venues.map((v) => state.venues.find((x) => x.key === v)?.label || v).join(', ')} up to $${m.max_usd}`);
+ if (m.note) parts.push(m.note);
+ if (m.bulk) parts.push(VIA_LABEL.bulk);
+ else if (m.via && VIA_LABEL[m.via]) parts.push(VIA_LABEL[m.via]);
+ return parts.join(' · ');
+}
+
+function auditRowHtml(ev) {
+ const [label, kind] = AUDIT_LABEL[ev.action] || [ev.action.replace(/^approval_/, '').replace(/_/g, ' '), ''];
+ const isRequest = !ev.action.startsWith('approval_policy_') && ev.resource_id;
+ const detail = esc(auditDetail(ev));
+ const linked = isRequest ? `<a href="/approvals/${esc(ev.resource_id)}">${detail || 'View request'}</a>` : detail;
+ return `<div class="ap-audit-row">
+ <span class="ap-audit-act ${kind}">${esc(label)}</span>
+ <span class="ap-audit-detail">${linked}</span>
+ <span class="ap-audit-time" title="${esc(fmtDate(ev.created_at))}">${esc(relTime(ev.created_at))}</span>
+ </div>`;
+}
+
+async function loadAudit({ more = false } = {}) {
+ if (!more) state.auditCursor = null;
+ const qs = new URLSearchParams({ action_prefix: 'approval_', limit: '15' });
+ if (more && state.auditCursor) qs.set('cursor', state.auditCursor);
+ els.auditMoreBtn.disabled = true;
+ try {
+ const r = await call(`/api/audit-log?${qs}`);
+ if (!r.ok) {
+ if (!more) els.audit.innerHTML = '<div class="ap-audit-empty">Could not load the audit log. Reload the page to try again.</div>';
+ return;
+ }
+ const rows = r.data.items || [];
+ const html = rows.map(auditRowHtml).join('');
+ if (more) els.audit.insertAdjacentHTML('beforeend', html);
+ else els.audit.innerHTML = html || '<div class="ap-audit-empty">No approval activity yet. Requests, decisions and rule changes will be recorded here.</div>';
+ state.auditCursor = r.data.next_cursor || null;
+ els.auditMore.hidden = !state.auditCursor;
+ } catch {
+ if (!more) els.audit.innerHTML = '<div class="ap-audit-empty">Could not reach three.ws to load the audit log.</div>';
+ } finally {
+ els.auditMoreBtn.disabled = false;
+ }
+}
+
+// ── push ────────────────────────────────────────────────────────────────────────
+
+async function initPush() {
+ if (!isPushSupported()) return;
+ const s = await getPushState();
+ els.push.hidden = false;
+ if (s.subscribed) {
+ els.push.textContent = 'Push on';
+ els.push.disabled = true;
+ els.push.title = 'Approval requests arrive as push notifications with Approve and Deny buttons.';
+ } else if (s.permission === 'denied') {
+ els.push.textContent = 'Push blocked';
+ els.push.disabled = true;
+ els.push.title = 'Notifications are blocked for three.ws in this browser. Allow them in site settings to get approval pushes.';
+ } else {
+ els.push.textContent = 'Enable push';
+ els.push.title = 'Get each approval request as a notification you can approve or deny from your lock screen.';
+ }
+}
+
+async function onEnablePush() {
+ els.push.disabled = true;
+ els.push.textContent = 'Enabling…';
+ const r = await enablePush();
+ if (r.ok) {
+ announce('Push enabled. Approval requests will reach this device.');
+ } else {
+ const why = {
+ unconfigured: 'Push is not available on this deployment yet; requests still reach you by chat and email.',
+ denied: 'Notifications are blocked in this browser. Allow them in site settings, then try again.',
+ dismissed: 'Push was not enabled. You can turn it on any time.',
+ unsupported: 'This browser does not support push.',
+ }[r.reason] || 'Could not enable push. Try again.';
+ showError(why);
+ }
+ initPush();
+}
+
+// ── boot ────────────────────────────────────────────────────────────────────────
+
+function showAuthWall() {
+ els.main.hidden = true;
+ els.error.hidden = true;
+ els.auth.hidden = false;
+ els.login.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;
+}
+
+function tick() {
+ let changed = false;
+ for (const el of document.querySelectorAll('[data-expiry]')) {
+ const left = timeLeft(el.dataset.expiry);
+ el.textContent = fmtLeft(left);
+ el.classList.toggle('is-soon', left < SOON_MS);
+ if (left <= 0) changed = true;
+ }
+ if (changed) {
+ for (const item of [...state.items, state.focus].filter(Boolean)) {
+ if (item.status === 'pending' && timeLeft(item.expires_at) <= 0) {
+ const card = document.querySelector(`.ap-card[data-id="${CSS.escape(item.id)}"]`);
+ if (card) rerenderCard(item.id, 'Expired without an answer. Nothing was executed.', 'err');
+ }
+ }
+ }
+}
+
+function bind() {
+ els.tabs.addEventListener('click', (e) => {
+ const t = e.target.closest('.ap-tab');
+ if (t) setGroup(t.dataset.group);
+ });
+ els.tabs.addEventListener('keydown', (e) => {
+ if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
+ const tabs = [...els.tabs.querySelectorAll('.ap-tab')];
+ const i = tabs.indexOf(document.activeElement);
+ if (i < 0) return;
+ const next = tabs[(i + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
+ next.focus();
+ setGroup(next.dataset.group);
+ });
+ els.agent.addEventListener('change', () => { state.agent = els.agent.value; state.selected.clear(); loadList(); });
+ els.moreBtn.addEventListener('click', () => loadList({ reset: false }));
+ els.bulk.addEventListener('click', bulkDeny);
+ els.selectAll.addEventListener('change', () => {
+ const ids = visibleItems().filter((i) => liveStatus(i) === 'pending').map((i) => i.id);
+ if (els.selectAll.checked) ids.forEach((id) => state.selected.add(id));
+ else state.selected.clear();
+ for (const cb of els.list.querySelectorAll('[data-select]')) cb.checked = state.selected.has(cb.dataset.select);
+ renderToolbar();
+ });
+ els.main.addEventListener('change', (e) => {
+ const cb = e.target.closest('[data-select]');
+ if (!cb) return;
+ if (cb.checked) state.selected.add(cb.dataset.select);
+ else state.selected.delete(cb.dataset.select);
+ renderToolbar();
+ });
+ els.main.addEventListener('click', (e) => {
+ const t = e.target;
+ const approve = t.closest('[data-approve]');
+ if (approve) return armApprove(approve);
+ const deny = t.closest('[data-deny]');
+ if (deny) { disarmAll(); return decide(deny.dataset.deny, 'deny'); }
+ const copy = t.closest('[data-copy]');
+ if (copy) {
+ navigator.clipboard?.writeText(copy.dataset.copy).then(() => { copy.textContent = 'Copied'; announce('Copied.'); }, () => { copy.textContent = 'Select to copy'; });
+ return;
+ }
+ const revoke = t.closest('[data-revoke]');
+ if (revoke) return revokePolicy(revoke);
+ if (t.closest('[data-clear-agent]')) { state.agent = ''; loadList(); return; }
+ if (t.closest('[data-reload-policies]')) { loadPolicies(); return; }
+ if (!t.closest('.btn-approve')) disarmAll();
+ });
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape') disarmAll(); });
+ els.form.addEventListener('submit', createPolicy);
+ els.auditMoreBtn.addEventListener('click', () => loadAudit({ more: true }));
+ els.push.addEventListener('click', onEnablePush);
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'visible' && !els.main.hidden && !state.loading) loadList();
+ });
+ setInterval(tick, TICK_MS);
+}
+
+async function boot() {
+ Object.assign(els, {
+ main: $('ap-main'), auth: $('ap-auth'), login: $('ap-login'), error: $('ap-error'), live: $('ap-live'),
+ focus: $('ap-focus'), tabs: $('ap-tabs'), list: $('ap-list'), more: $('ap-more'), moreBtn: $('ap-more-btn'),
+ agent: $('ap-agent'), bulk: $('ap-bulk-deny'), selectAll: $('ap-select-all'), selectAllWrap: $('ap-select-all-wrap'),
+ policies: $('ap-policies'), form: $('ap-policy-form'), venues: $('ap-venues'), max: $('ap-max'), maxHint: $('ap-max-hint'),
+ policyAgent: $('ap-policy-agent'), policyExpiry: $('ap-policy-expiry'), policySubmit: $('ap-policy-submit'), formMsg: $('ap-form-msg'),
+ audit: $('ap-audit'), auditMore: $('ap-audit-more'), auditMoreBtn: $('ap-audit-more-btn'), push: $('ap-push'),
+ });
+ bind();
+
+ const m = location.pathname.match(/^\/approvals\/([0-9a-f-]{36})\/?$/i);
+ state.focusToken = new URLSearchParams(location.search).get('t');
+ els.main.hidden = false;
+ els.list.innerHTML = skeletonHtml();
+ els.audit.innerHTML = skeletonHtml(1);
+
+ await loadList();
+ if (!els.auth.hidden) return;
+ if (m) await loadFocus(m[1].toLowerCase());
+ if (!els.auth.hidden) return;
+ renderList();
+ // The log names venues by the labels the policies call returns.
+ loadPolicies().finally(() => loadAudit());
+ initPush();
+}
+
+boot();
diff --git a/src/notifications-page.js b/src/notifications-page.js
index d67d8a498..5b2b870a9 100644
--- a/src/notifications-page.js
+++ b/src/notifications-page.js
@@ -30,6 +30,7 @@ const TYPE_CATEGORY = {
asset_payment_mismatch: 'account', skill_payment_mismatch: 'account', security_alert: 'account',
wallet_anomaly_frozen: 'account',
inference_topup: 'account', inference_budget_exhausted: 'account',
+ approval_requested: 'approvals',
};
function categoryOf(type) { return TYPE_CATEGORY[type] || 'account'; }
diff --git a/src/notifications.js b/src/notifications.js
index 578015cb2..1ceca05dd 100644
--- a/src/notifications.js
+++ b/src/notifications.js
@@ -94,6 +94,7 @@ export const TYPE_ICON = {
print_update: '📦',
inference_topup: '⚡',
inference_budget_exhausted: '⏸️',
+ approval_requested: '🛂',
};
export function notifLabel(n) {
@@ -181,6 +182,8 @@ export function notifLabel(n) {
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':
return `${p.agent_name || 'Your agent'} used its ${p.window === 'monthly' ? 'monthly' : 'daily'} inference budget${p.automations_stopped ? ' and was stopped' : ''}. Raise it to resume`;
+ case 'approval_requested':
+ return `Approval needed: ${p.summary || `${p.agent_name || 'Your agent'} is waiting for your yes`}`;
case 'royalty_paid':
return p.usd
? `${p.actor || 'A fork of your avatar'} paid you $${Number(p.usd).toFixed(3)} in royalties`
diff --git a/tests/approvals.test.js b/tests/approvals.test.js
new file mode 100644
index 000000000..c065f8b90
--- /dev/null
+++ b/tests/approvals.test.js
@@ -0,0 +1,356 @@
+// The approval inbox, against the REAL approval_requests migration in an
+// in-process Postgres (PGlite). Pins the contracts the inbox exists for:
+// - an approval executes exactly the action that was shown, once: a stale or
+// tampered payload hash is refused, and a row edited after it was shown
+// fails the executor's integrity check without running anything;
+// - an expired request can never execute, even with the right hash;
+// - a double approve (push tap racing a web click) runs the executor once;
+// - deny and bulk deny are terminal and fail closed;
+// - signed deep links verify against the request on file;
+// - auto-approve rules are explicit, capped by size and venue, revocable, and
+// never cover a transfer to a never-paid address.
+
+import { readFileSync } from 'node:fs';
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+import { PGlite } from '@electric-sql/pglite';
+
+process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';
+
+const dbState = { pg: null };
+
+vi.mock('../api/_lib/db.js', () => {
+ const sql = async (strings, ...values) => {
+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');
+ const out = await dbState.pg.query(text, values);
+ return out.rows;
+ };
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+const audit = vi.hoisted(() => ({ logAudit: vi.fn() }));
+vi.mock('../api/_lib/audit.js', () => audit);
+
+const notify = vi.hoisted(() => ({
+ insertNotification: vi.fn(async () => ({ id: 1, in_app: true, delivered: { push: 1 } })),
+ emailAllowedForType: vi.fn(async () => true),
+}));
+vi.mock('../api/_lib/notify.js', () => notify);
+
+const email = vi.hoisted(() => ({ sendApprovalRequestEmail: vi.fn(async () => ({ id: 'email-1' })) }));
+vi.mock('../api/_lib/email.js', () => email);
+
+const executor = vi.hoisted(() => ({ executeApprovedIntentAction: vi.fn(async () => ({ status: 'ok', signature: 'SIGtest1111', usd: 12 })) }));
+vi.mock('../api/_lib/wallet-intents.js', () => executor);
+
+const A = await import('../api/_lib/approvals.js');
+
+const MIGRATION = readFileSync(new URL('../api/_lib/migrations/20261010120000_approval_requests.sql', import.meta.url), 'utf8');
+
+const OWNER = '11111111-1111-4111-8111-111111111111';
+const STRANGER = '22222222-2222-4222-8222-222222222222';
+const AGENT = '33333333-3333-4333-8333-333333333333';
+const RECIPIENT = 'THREEsynthetic1111111111111111111111111111';
+
+let seq = 0;
+function request(overrides = {}) {
+ seq += 1;
+ return {
+ userId: OWNER,
+ agentId: AGENT,
+ source: 'wallet_intent',
+ sourceRef: `intent-${seq}:${RECIPIENT}`,
+ actionType: 'transfer_sol',
+ venue: 'wallet_transfer',
+ payload: { v: 1, source: 'wallet_intent', intent_id: `intent-${seq}`, lamports: '250000000', destination: RECIPIENT },
+ summary: 'Send 0.25 SOL to a saved address',
+ amount: 0.25,
+ amountUsd: 40,
+ asset: 'SOL',
+ recipient: RECIPIENT,
+ riskNotes: ['Your rule "Ask me above $25" asked for approval.'],
+ gateReason: 'Ask me above $25',
+ idempotencyKey: `wallet_intent:intent-${seq}:bucket`,
+ ...overrides,
+ };
+}
+
+beforeAll(async () => {
+ dbState.pg = new PGlite();
+ await dbState.pg.exec(`
+ create table users (id uuid primary key, email text);
+ create table agent_identities (id uuid primary key, user_id uuid, name text, deleted_at timestamptz);
+ insert into users (id, email) values ('${OWNER}', '[email protected]'), ('${STRANGER}', '[email protected]');
+ insert into agent_identities (id, user_id, name) values ('${AGENT}', '${OWNER}', 'Scout');
+ `);
+ await dbState.pg.exec(MIGRATION);
+});
+
+beforeEach(async () => {
+ await dbState.pg.exec('delete from approval_requests; delete from approval_auto_policies;');
+ vi.clearAllMocks();
+ notify.insertNotification.mockResolvedValue({ id: 1, in_app: true, delivered: { push: 1 } });
+ executor.executeApprovedIntentAction.mockResolvedValue({ status: 'ok', signature: 'SIGtest1111', usd: 12 });
+});
+
+describe('payload hash', () => {
+ it('is stable across key order and changes with any field', () => {
+ const a = A.payloadHash({ b: 1, a: { y: 2, x: '3' } });
+ expect(a).toMatch(/^[0-9a-f]{64}$/);
+ expect(A.payloadHash({ a: { x: '3', y: 2 }, b: 1 })).toBe(a);
+ expect(A.payloadHash({ a: { x: '3', y: 2 }, b: 2 })).not.toBe(a);
+ });
+});
+
+describe('createApprovalRequest', () => {
+ it('stores a pending request with the confirmation table and delivers it', async () => {
+ const { request: row, created, autoApproved } = await A.createApprovalRequest(request());
+ expect(created).toBe(true);
+ expect(autoApproved).toBe(false);
+ expect(row.status).toBe('pending');
+ expect(row.payload_hash).toBe(A.payloadHash(row.payload));
+ expect(notify.insertNotification).toHaveBeenCalledWith(OWNER, 'approval_requested', expect.objectContaining({ approval_id: row.id, payload_hash: row.payload_hash }));
+
+ const table = A.confirmationTable(row);
+ expect(table.map((r) => r.label)).toEqual(['Recipient', 'Amount', 'Asset', 'Chain']);
+ expect(table[0].full).toBe(RECIPIENT);
+ expect(table[1].value).toContain('0.25 SOL');
+ expect(table[3].value).toBe('Solana');
+ });
+
+ it('asks once per gated event: the same idempotency key or open source ref returns the first request', async () => {
+ const input = request();
+ const first = await A.createApprovalRequest(input);
+ const again = await A.createApprovalRequest(input);
+ const sameRef = await A.createApprovalRequest({ ...input, idempotencyKey: 'another-bucket' });
+ expect(again.created).toBe(false);
+ expect(again.request.id).toBe(first.request.id);
+ expect(sameRef.request.id).toBe(first.request.id);
+ expect(notify.insertNotification).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to email when no out-of-app channel reached the owner', async () => {
+ notify.insertNotification.mockResolvedValueOnce({ id: 1, in_app: true, delivered: { push: 0 } });
+ await A.createApprovalRequest(request());
+ expect(email.sendApprovalRequestEmail).toHaveBeenCalledTimes(1);
+ const arg = email.sendApprovalRequestEmail.mock.calls[0][0];
+ expect(arg.to).toBe('[email protected]');
+ expect(arg.link).toMatch(/^\/approvals\/[0-9a-f-]{36}\?t=a1\./);
+ });
+
+ it('refuses a source with no registered executor', async () => {
+ await expect(A.createApprovalRequest(request({ source: 'nowhere' }))).rejects.toMatchObject({ code: 'unknown_source' });
+ });
+});
+
+describe('signed deep links', () => {
+ it('verify against the request on file and reject any edit', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ const token = new URL(A.approvalPath(row), 'https://x').searchParams.get('t');
+ const facts = { id: row.id, userId: OWNER, hash: row.payload_hash };
+ expect(A.verifyApprovalLink(token, facts)).toEqual({ ok: true });
+ expect(A.verifyApprovalLink(token, { ...facts, hash: 'f'.repeat(64) })).toMatchObject({ reason: 'payload_changed' });
+ expect(A.verifyApprovalLink(token, { ...facts, userId: STRANGER })).toMatchObject({ reason: 'wrong_request' });
+ const [head, body, sig] = token.split('.');
+ expect(A.verifyApprovalLink(`${head}.${body}.${sig.slice(0, -2)}xx`, facts)).toMatchObject({ reason: 'bad_signature' });
+ expect(A.verifyApprovalLink('nonsense', facts)).toMatchObject({ reason: 'malformed' });
+
+ const viewed = await A.getApproval(OWNER, row.id, { token });
+ expect(viewed.link_verified).toBe(true);
+ });
+
+ it('a link that does not match blocks the decision', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ const { request: other } = await A.createApprovalRequest(request());
+ const otherToken = new URL(A.approvalPath(other), 'https://x').searchParams.get('t');
+ await expect(A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash, token: otherToken }))
+ .rejects.toMatchObject({ status: 409, code: 'link_mismatch' });
+ expect(executor.executeApprovedIntentAction).not.toHaveBeenCalled();
+ });
+});
+
+describe('approve', () => {
+ it('executes exactly the shown action once and records the signature', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ const out = await A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash, via: 'push' });
+ expect(out.idempotent).toBe(false);
+ expect(out.request.status).toBe('executed');
+ expect(out.request.signature).toBe('SIGtest1111');
+ expect(out.request.decided_via).toBe('push');
+ expect(executor.executeApprovedIntentAction).toHaveBeenCalledTimes(1);
+ expect(executor.executeApprovedIntentAction.mock.calls[0][0].payload).toEqual(row.payload);
+ });
+
+ it('rejects a tampered payload hash and runs nothing', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ const tampered = A.payloadHash({ ...row.payload, destination: 'THREEsyntheticAttacker1111111111111111111' });
+ await expect(A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: tampered }))
+ .rejects.toMatchObject({ status: 409, code: 'payload_mismatch' });
+ await expect(A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: null }))
+ .rejects.toMatchObject({ status: 400, code: 'payload_hash_required' });
+ expect(executor.executeApprovedIntentAction).not.toHaveBeenCalled();
+ const [still] = (await dbState.pg.query('select status from approval_requests where id = $1', [row.id])).rows;
+ expect(still.status).toBe('pending');
+ });
+
+ it('fails closed when the stored payload was edited after it was shown', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ // Someone rewrites the destination in the row but leaves the hash the owner saw.
+ await dbState.pg.query(`update approval_requests set payload = jsonb_set(payload, '{destination}', '"THREEsyntheticAttacker1111111111111111111"') where id = $1`, [row.id]);
+ const out = await A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash });
+ expect(out.request.status).toBe('failed');
+ expect(out.request.result.integrity).toBe(false);
+ expect(executor.executeApprovedIntentAction).not.toHaveBeenCalled();
+ });
+
+ it('an expired request cannot execute, even with the right hash', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ await dbState.pg.query(`update approval_requests set expires_at = now() - interval '1 second' where id = $1`, [row.id]);
+ await expect(A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash }))
+ .rejects.toMatchObject({ status: 410, code: 'expired' });
+ expect(executor.executeApprovedIntentAction).not.toHaveBeenCalled();
+ const [after] = (await dbState.pg.query('select status from approval_requests where id = $1', [row.id])).rows;
+ expect(after.status).toBe('expired');
+ await expect(A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash }))
+ .rejects.toMatchObject({ status: 410 });
+ });
+
+ it('double approve is idempotent: concurrent and repeated taps run the executor once', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ const args = { userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash };
+ const [a, b] = await Promise.all([A.decideApproval({ ...args, via: 'push' }), A.decideApproval({ ...args, via: 'web' })]);
+ const third = await A.decideApproval(args);
+ expect([a.idempotent, b.idempotent].filter(Boolean)).toHaveLength(1);
+ expect(third.idempotent).toBe(true);
+ expect(third.request.status).toBe('executed');
+ expect(executor.executeApprovedIntentAction).toHaveBeenCalledTimes(1);
+ });
+
+ it('records a failed execution without retrying it', async () => {
+ executor.executeApprovedIntentAction.mockResolvedValueOnce({ status: 'error', note: 'insufficient balance' });
+ const { request: row } = await A.createApprovalRequest(request());
+ const out = await A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash });
+ expect(out.request.status).toBe('failed');
+ expect(out.request.result.note).toBe('insufficient balance');
+ const again = await A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash });
+ expect(again.idempotent).toBe(true);
+ expect(executor.executeApprovedIntentAction).toHaveBeenCalledTimes(1);
+ });
+
+ it('another account cannot see or decide the request', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ await expect(A.decideApproval({ userId: STRANGER, id: row.id, decision: 'approve', payloadHash: row.payload_hash }))
+ .rejects.toMatchObject({ status: 404 });
+ await expect(A.getApproval(STRANGER, row.id)).rejects.toMatchObject({ status: 404 });
+ });
+});
+
+describe('deny', () => {
+ it('is terminal: a denied request can never be approved', async () => {
+ const { request: row } = await A.createApprovalRequest(request());
+ const out = await A.decideApproval({ userId: OWNER, id: row.id, decision: 'deny' });
+ expect(out.request.status).toBe('denied');
+ const repeat = await A.decideApproval({ userId: OWNER, id: row.id, decision: 'deny' });
+ expect(repeat.idempotent).toBe(true);
+ await expect(A.decideApproval({ userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash }))
+ .rejects.toMatchObject({ status: 409, code: 'already_denied' });
+ expect(executor.executeApprovedIntentAction).not.toHaveBeenCalled();
+ });
+
+ it('bulk deny denies only pending requests on the caller account', async () => {
+ const { request: one } = await A.createApprovalRequest(request());
+ const { request: two } = await A.createApprovalRequest(request());
+ const { request: done } = await A.createApprovalRequest(request());
+ await A.decideApproval({ userId: OWNER, id: done.id, decision: 'approve', payloadHash: done.payload_hash });
+
+ const foreign = await A.bulkDeny(STRANGER, [one.id]);
+ expect(foreign.denied).toEqual([]);
+
+ const out = await A.bulkDeny(OWNER, [one.id, two.id, done.id]);
+ expect(out.denied.sort()).toEqual([one.id, two.id].sort());
+ expect(out.skipped).toEqual([done.id]);
+ await expect(A.bulkDeny(OWNER, ['not-a-uuid'])).rejects.toMatchObject({ code: 'no_ids' });
+ });
+});
+
+describe('inbox listing', () => {
+ it('groups by status, counts every group, and expires stale requests on read', async () => {
+ const { request: live } = await A.createApprovalRequest(request());
+ const { request: stale } = await A.createApprovalRequest(request());
+ await dbState.pg.query(`update approval_requests set expires_at = now() - interval '1 minute' where id = $1`, [stale.id]);
+
+ const pending = await A.listApprovals(OWNER, { group: 'pending' });
+ expect(pending.items.map((i) => i.id)).toEqual([live.id]);
+ expect(pending.counts).toMatchObject({ pending: 1, expired: 1, all: 2 });
+ expect(pending.agents).toEqual([{ id: AGENT, name: 'Scout' }]);
+ expect(pending.items[0].link).toMatch(/\?t=a1\./);
+
+ const expired = await A.listApprovals(OWNER, { group: 'expired' });
+ expect(expired.items.map((i) => i.id)).toEqual([stale.id]);
+ await expect(A.listApprovals(OWNER, { group: 'bogus' })).rejects.toMatchObject({ code: 'invalid_status' });
+ });
+
+ it('paginates with a cursor', async () => {
+ for (let i = 0; i < 3; i += 1) await A.createApprovalRequest(request());
+ const first = await A.listApprovals(OWNER, { group: 'all', limit: 2 });
+ expect(first.items).toHaveLength(2);
+ expect(first.next_cursor).toBeTruthy();
+ const second = await A.listApprovals(OWNER, { group: 'all', limit: 2, cursor: first.next_cursor });
+ expect(second.items).toHaveLength(1);
+ expect(second.next_cursor).toBeNull();
+ expect(new Set([...first.items, ...second.items].map((i) => i.id)).size).toBe(3);
+ });
+});
+
+describe('auto-approve rules', () => {
+ it('default is ask every time', async () => {
+ const { autoApproved, request: row } = await A.createApprovalRequest(request());
+ expect(autoApproved).toBe(false);
+ expect(row.status).toBe('pending');
+ });
+
+ it('a rule covers only its venue and size, and never a never-paid address', async () => {
+ const policy = await A.createAutoPolicy(OWNER, { venues: ['wallet_transfer'], max_usd: 50 });
+ expect(policy.active).toBe(true);
+
+ const covered = await A.matchAutoPolicy({ userId: OWNER, agentId: AGENT, venue: 'wallet_transfer', amountUsd: 40 });
+ expect(covered?.id).toBe(policy.id);
+ expect(await A.matchAutoPolicy({ userId: OWNER, agentId: AGENT, venue: 'wallet_transfer', amountUsd: 51 })).toBeNull();
+ expect(await A.matchAutoPolicy({ userId: OWNER, agentId: AGENT, venue: 'jupiter', amountUsd: 5 })).toBeNull();
+ expect(await A.matchAutoPolicy({ userId: OWNER, agentId: AGENT, venue: 'wallet_transfer', amountUsd: null })).toBeNull();
+ expect(await A.matchAutoPolicy({ userId: OWNER, agentId: AGENT, venue: 'wallet_transfer', amountUsd: 5, autoApprovable: false })).toBeNull();
+ expect(await A.matchAutoPolicy({ userId: STRANGER, venue: 'wallet_transfer', amountUsd: 5 })).toBeNull();
+ });
+
+ it('a covered request is created approved and still executes through runApproved once', async () => {
+ await A.createAutoPolicy(OWNER, { venues: ['wallet_transfer'], max_usd: 50 });
+ const { autoApproved, request: row } = await A.createApprovalRequest(request());
+ expect(autoApproved).toBe(true);
+ expect(row.status).toBe('approved');
+ expect(row.decided_via).toBe('auto_policy');
+ expect(notify.insertNotification).not.toHaveBeenCalled();
+
+ const run = vi.fn(async () => ({ status: 'ok', signature: 'SIGauto1111' }));
+ const first = await A.runApproved(row, run);
+ const second = await A.runApproved(row, run);
+ expect(first.request.status).toBe('executed');
+ expect(second.outcome).toBeNull();
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+
+ it('revoking a rule takes effect on the next request', async () => {
+ const policy = await A.createAutoPolicy(OWNER, { venues: ['wallet_transfer'], max_usd: 50 });
+ const revoked = await A.revokeAutoPolicy(OWNER, policy.id);
+ expect(revoked.active).toBe(false);
+ const { autoApproved } = await A.createApprovalRequest(request());
+ expect(autoApproved).toBe(false);
+ await expect(A.revokeAutoPolicy(STRANGER, policy.id)).rejects.toMatchObject({ status: 404 });
+ });
+
+ it('rules are capped and validated', async () => {
+ await expect(A.createAutoPolicy(OWNER, { venues: ['wallet_transfer'], max_usd: A.AUTO_POLICY_MAX_USD + 1 })).rejects.toMatchObject({ code: 'invalid_max_usd' });
+ await expect(A.createAutoPolicy(OWNER, { venues: ['somewhere'], max_usd: 10 })).rejects.toMatchObject({ code: 'invalid_venue' });
+ await expect(A.createAutoPolicy(OWNER, { venues: [], max_usd: 10 })).rejects.toMatchObject({ code: 'invalid_venue' });
+ await expect(A.createAutoPolicy(OWNER, { venues: ['jupiter'], max_usd: 10, agent_id: '44444444-4444-4444-8444-444444444444' })).rejects.toMatchObject({ code: 'agent_not_found' });
+ await expect(A.createAutoPolicy(OWNER, { venues: ['jupiter'], max_usd: 10, expires_at: '2000-01-01' })).rejects.toMatchObject({ code: 'invalid_expiry' });
+ });
+});
diff --git a/vercel.json b/vercel.json
index e813c707f..5f72bb8f9 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1287,6 +1287,14 @@
"src": "/quests/?",
"dest": "/quests.html"
},
+ {
+ "src": "/approvals/?",
+ "dest": "/approvals.html"
+ },
+ {
+ "src": "/approvals/([^/.]+)/?",
+ "dest": "/approvals.html"
+ },
{
"src": "/duels/?",
"dest": "/duels.html"
diff --git a/vite.config.js b/vite.config.js
index 1e6d86b0e..d74a611d6 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -874,6 +874,7 @@ const appConfig = {
syndicates: resolve(__dirname, 'pages/syndicates.html'),
syndicate: resolve(__dirname, 'pages/syndicate.html'),
quests: resolve(__dirname, 'pages/quests.html'),
+ approvals: resolve(__dirname, 'pages/approvals.html'),
duels: resolve(__dirname, 'pages/duels.html'),
duel: resolve(__dirname, 'pages/duel.html'),
fade: resolve(__dirname, 'pages/fade.html'),
@@ -2354,6 +2355,11 @@ const appConfig = {
// `/duels/([^/.]+)/?`; the board itself is /duels.
else if (!filePath && /^\/duels\/[^/.]+\/?$/.test(path))
filePath = resolve(root, 'pages/duel.html');
+ // /approvals/:id → the approval inbox focused on one request (the
+ // signed deep link every approval delivery carries). Mirrors
+ // vercel.json's `/approvals/([^/.]+)/?`.
+ else if (!filePath && /^\/approvals(\/[^/.]+)?\/?$/.test(path))
+ filePath = resolve(root, 'pages/approvals.html');
// /trade-rooms/:agentId → one leader's live trade room. Mirrors
// vercel.json's `/trade-rooms/([^/.]+)/?`.
else if (!filePath && /^\/trade-rooms\/[^/.]+\/?$/.test(path))