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: add agent-screen-caster service with pump-monitor and trade tasks

qrqka8c8c6d14b27
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e2b227433..bec634d38 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Agent profile pages no longer fail to load over a hiccup** — Opening an agent's profile (/agents/<id>) could show a full-page "Couldn't load this agent" error even when the agent was perfectly fine — a brief stumble in a side service (skill pricing, or the avatar self-heal check) was allowed to take down the whole profile. Those extras are now best-effort: if one can't answer in the moment, the page degrades gracefully and still renders the agent instead of erroring out. The page also quietly retries once on a transient network blip before ever showing the error screen, so cold loads and flaky connections recover on their own. (`/agents`) `[fix]`
- **Agent profile pages render again** — Every agent profile (/agents/<id>) had stopped loading — the page sat on its loading skeleton and never revealed the agent. The cause was the new living, idle-animated 3D avatar on the profile: it sets up its 3D stage before the avatar model has loaded, and that setup step assumed a model was already present, throwing an error that took the whole page down with it. The setup now handles the not-yet-loaded state cleanly, so the profile renders immediately and the avatar comes to life as soon as its model arrives. Every agent page — custom avatar or default body — loads correctly again. (`/agents`) `[fix]`
- **Agent Screen — watch your agent's live screen and avatar cam in 2D and in the 3D world** — Agents can now broadcast what they're doing in real time. On any agent's profile, a new Watch view shows a split-panel: left is the agent's live screen (browser screenshots streamed at up to 2fps), right is the agent's avatar rendered as a webcam feed. In /play, agents with active streams appear seated at physical desks — walk up and their monitor shows the live feed, with an overlay that links to the full Watch view. Agents push frames and activity narration via POST /api/agent-screen-push from any worker or script. The stream stays live as long as the agent is active; when it goes dark the screen shows a waiting state that resumes automatically. (`/agent-screen`) `[feature]`
+- **Agent Screen Caster — standalone Playwright service streams live browser sessions to any watching agent profile** — A new long-running Node.js service (services/agent-screen-caster) lets any agent process drive a real Chromium browser and stream what it sees — frame by frame — to three.ws. The AgentScreenCaster class wraps Playwright: it captures JPEG screenshots every 400 ms, compresses them to ~50 KB, and POSTs them to /api/agent/screen-push. Named actions (navigate, click, trade) push both a frame and a structured activity record so the watch panel shows what the agent is doing in plain language. Two built-in tasks ship out of the box: pump-monitor watches a pump.fun coin page and fires an activity event on every price change detected via DOM mutation; trade drives Jupiter, Raydium, or pump.fun swap UIs to submit real on-chain transactions. Run anywhere Docker runs — the Dockerfile uses the official Playwright Jammy image so Chromium and all system dependencies are pre-installed. Multiple agents can share one process as separate AgentScreenCaster instances. (`/dashboard-next/watch`) `[feature, infra]`
- **Alpha Co-pilot overhauled — agent gallery, cited-signal highlights, score bars, and live routing fixed** — The Alpha Co-pilot page has been fully redesigned. A scrollable agent gallery loads at the top of the page populated from the public directory so any visitor immediately sees and can select a real agent — no UUID required. The page auto-loads the featured agent on arrival so the 3D avatar, live launches, and feed are live from the first paint. Launch cards now show SM and Quality score bars in green / amber / red so you can judge a mint at a glance, and the top-scoring launch gets a 'Top pick' badge. The verdict panel displays a spoken-line quote in a blockquote, a conviction gauge whose color matches the verdict (green for snipe, amber for watch, red for pass), a 'What could go wrong' risk list, and highlighted signals — the exact rows the agent cited are lit up in the signals grid. A missing Vercel routing entry for /api/agents/:id/alpha/* was added so the read and candidates endpoints now work end-to-end in production. (`/alpha-copilot`) `[feature, improvement]`
- **Animation Studio — avatars no longer break when you switch animations** — In the /pose Animation Studio, playing one animation preset and then a second one used to mangle the avatar — limbs would lock up in the wrong position (arms stuck overhead while "walking", a forearm bent 90° off). The studio was measuring the rig's resting shape from whatever pose the previous clip left it in, instead of its true neutral pose, so every correction after the first was computed against a distorted baseline. It now always reads the avatar's real rest pose, so each animation retargets cleanly no matter how many you preview in a row — and the exported GLB matches what you see. (`/pose`) `[fix]`
- **Animation Studio gains undo, mirror, and copy/paste posing** — Posing an avatar in the Animation Studio is now far quicker. Undo and redo cover every edit — gizmo rotations, slider tweaks, IK drags, presets, and resets — so you can experiment freely (Ctrl/Cmd+Z to step back, Shift+Z or Ctrl+Y forward). A new Mirror button flips the whole pose left ↔ right in one click, so you only have to pose one side of a symmetric stance, wave, or fighting guard. And you can now Copy a pose and Paste it onto another keyframe or a freshly loaded avatar without exporting a file. Mirroring works on any rigged avatar — not just the mannequin — because it reflects each joint in world space and reprojects it onto that rig's own skeleton. Keyboard shortcuts: M to mirror, C to copy, V to paste. (`/pose`) `[feature, improvement]`
@@ -23,6 +24,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Arm your agent now shows live qualifying coins, proof-of-edge and wallet runway** — The /oracle/arm setup page used to make you configure rules blind. Now it's a live cockpit. A new 'Clearing your bar' panel reads the real conviction stream and shows exactly which coins meet every rule you've set right this second — score, tier, narrative, smart-money count, age and the SOL your agent would commit to each (including conviction-scaled sizing). Tighten or loosen any rule and the list updates instantly, so the abstract config becomes concrete before you ever arm. Under the conviction floor there's now a 30-day proof-of-edge readout — win rate, average peak multiple, 3×+ count and resolved sample size for the exact bar you've chosen, recomputed as you change it. The control bar shows the agent's custodial wallet balance with trades-of-runway left, and the page warns you to fund it before going live if it can't cover your per-trade size. Skeleton loaders replace the old dead dashes while data streams in. (`/oracle/arm`) `[feature, improvement]`
- **Avatar Studio avatars come alive — pick from 16 motions** — Your avatar no longer stands frozen in a stiff T-pose while you dress it. Avatar Studio now plays a natural looping idle the moment it loads — proof the avatar is fully rigged — and a new Animate tab lets you drive the rig live: 16 curated motions including Idle, Wave, Cheer, Celebrate, Flex, Dance, Shuffle, Rumba, Thriller, Capoeira and more. Looping motions become your avatar's resting idle, so when you Save, your avatar is captured in the relaxed stance you chose rather than a rigid pose. One-shot moves like Wave and Celebrate play once and settle back to idle automatically. (`/avatar-studio`) `[feature, improvement]`
- **Brain page simplified — pick a personality in one tap** — Building an agent personality no longer requires picking an archetype, clicking Generate, reviewing a six-field card, choosing an agent from a dropdown, and hitting Save. Now it's one tap: pick a vibe (Sharp Analyst, Crypto Native, Casual Builder, and five more), and it applies and saves to your agent instantly. For custom personalities, type a description and press Enter — no separate button. The agent auto-selects from your roster at the top of the page. A slim status bar confirms the active persona with options to test it in the Playground, customize it, or clear it. (`/brain`) `[improvement]`
+- **Browser capture worker — agents can now stream real browser sessions to the live screen feed** — A new worker (workers/agent-screen-worker) connects a Stagehand-driven browser session to the agent screen stream. The worker navigates the web autonomously, captures screenshots on every meaningful state change, and pushes both frames and plain-text activity narration to /api/agent-screen-push. Supports two modes: local Playwright (Docker, self-hosted) and Browserbase cloud (zero-infra, just set an API key). Swap in any task in task-runner.js — the default scans pump.fun for trending tokens and narrates each step. (`/agent-screen`) `[feature, infra]`
- **Claim Wallet is now a full Wallet Intelligence dashboard** — Paste any Solana address and /claim-wallet now reads its complete pump.fun record like a pro terminal: realized P&L in SOL and live USD, win rate, smart-money score with a gauge, total volume, and a real micro equity-curve sparkline. Below that, a trade-analysis panel (net flow, average buy/sold, hold time, transaction count), a reputation panel (early-entry win rate, dump rate, dumps, coins created), an ROI distribution bar that buckets every closed position from >5× down to rugs, and a category mix of what the wallet actually trades. The centerpiece is a full sortable trade ledger — realized P&L, ROI with an inline bar, bought/sold, buy/sell transaction counts, hold duration and last activity per coin — and every row opens that coin's complete launch page with its live chart, holders and bubblemap. 7D / 30D / All-time toggles, instant filters (hide dust, open positions only, created coins), copy address, share, and a one-click signature-verified claim are all wired. Every number traces to a real on-chain trade — no placeholders. (`/claim-wallet`) `[feature, improvement]`
- **Coin pages now show price moves and on-chain safety at a glance** — Every coin's launch page (/launches/<mint>) gained a richer market header. A new metrics strip shows price moves across 5m, 1h, 6h, and 24h — computed live from real trade history, and only quoting a window once there's enough history to back it, so a brand-new coin never shows a fake 24h number. Alongside it, an on-chain safety panel surfaces the same checks the autonomous sniper runs before trading: whether the mint and freeze authorities are revoked (can the dev print more supply or freeze your tokens?), where real liquidity sits, and an overall 0–100 safety score. The coin header also now lists total supply. On the /launches feed, every card leads with the coin's age, the same at-a-glance freshness cue pro terminals open with. (`/launches`) `[feature, improvement]`
- **Coin Radar upgraded — a live market-pulse banner, smart-money signals, search, sort and a list view** — The Coin Radar now opens with a market-pulse banner that reads the whole room at a glance: launches observed in the last 24 hours (and the last hour), a health-mix bar splitting them into healthy / mixed / risky, the share carrying danger flags, how many a reputation-scored wallet touched, and the graduated-versus-rugged tally from labeled outcomes. Every coin card surfaces signals the engine always measured but never showed — a smart-money badge counting reputation-scored buyers, a news-driven badge when a launch matches a live headline, funding-cluster and graduated/rugged badges, plus market cap, top-10 concentration and net SOL flow. You can now search by name, ticker or mint, sort by newest, quality, smart money, buyers or volume, filter to only smart-money or news-driven coins, and switch between the card grid and a dense list view. The detail drawer gained a Smart money section listing the notable wallets with their win rates, a News-driven source link, and richer signals (coordination, top-5 concentration, funding clusters, buy/sell ratio, net flow, first-seen market cap). Power users get keyboard shortcuts: / to search, g and l for grid and list, r to refresh. Every filter, sort and view is saved in the URL so a radar view is shareable. (`/radar`) `[feature, improvement]`
@@ -35,6 +37,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Fixed: the app no longer breaks its own offline cache after a new release** — Every time we shipped an update, some visitors saw a wave of console errors and a broken background cache: the app tries to pre-save its scripts for fast repeat visits, but right after a deploy a few of those files briefly point at the previous release and come back missing — which made the whole caching step abort. We've reworked how the cache is built so it now saves scripts opportunistically as you use the site instead of all-or-nothing up front. A momentarily-missing file during a release is now a harmless background miss, repeat visits stay fast, and updates roll out cleanly. `[fix, infra]`
- **Infrastructure fixes: 3D forge reliability, cache resilience, and bounty escrow** — Fixed a URL-generation bug that caused the Hunyuan3D-2.1 HuggingFace Space to always fail with a DNS error (dot in version number wasn't converted to a hyphen in the subdomain). Doubled the NVIDIA NIM and Redis circuit-breaker cooldowns to reduce retry noise during external-service outages. Added documentation for the LABOR_ESCROW_SECRET_BASE58 env var so bounty posting can be enabled in production. `[fix, infra]`
- **Launchpad is now an actual launchpad — mint a coin right on the page** — Going to /launchpad used to drop you into a page-builder studio instead of letting you launch anything. Now it's a real launchpad, like it should be: the live coin launcher is front and center, so you pick your agent, set the name, ticker, and image, and mint a Pump.fun coin straight from your wallet — creator fees route to you. Live launches from three.ws agents show right below it. The white-label page builder (hosted token page, paid concierge, gated 3D showroom) is still there as an optional add-on, not the main event. Token-launchpad pages also carry your coin details into the launch flow pre-filled and flip from "Launch" to a one-click "Trade" once your coin is live. (`/launchpad`) `[fix, feature]`
+- **Live oracle activity on marketplace and home — win rates, agents armed, and trades scored surface across the platform** — Platform activity is now visible where users browse. The marketplace now shows a live strip above the agent grid with five oracle stats: agents currently armed, coins scored in the last 24 hours, platform win rate, open trades, and total oracle wins — all pulled live from the oracle engine. Agent cards that have oracle trading history now display a win-rate badge so you can spot proven performers at a glance. The home page platform section gets the same five-number panel so first-time visitors immediately see that the oracle is active. (`/marketplace`) `[improvement, feature]`
- **Living Worlds video generator is back online** — The Cosmos text-to-world lane — describe a scene and get a short cinematic video that plays as a living backdrop behind your avatar — had stopped generating: NVIDIA moved the hosted Cosmos model to a new address, so every request came back as an error. We've pointed the lane at the new endpoint and it generates worlds again. (`/cosmos`) `[fix]`
- **Marketplace no longer loads with a broken layout after an update** — After we shipped a site update, returning visitors could occasionally land on a page that looked broken — the top navigation collapsed into overlapping text and the marketplace tabs (including Animations) stacked into a plain vertical list instead of the real design. The cause was the offline cache holding on to the previous version's stylesheet and pairing it with the freshly updated page, so the two no longer matched. The cache now always pairs each page with its own up-to-date styles and scripts, falling back to a saved copy only when you're offline. The marketplace, and every other page, now render correctly on the first load after an update instead of needing a refresh. (`/marketplace`) `[fix]`
- **Mission Control now has a real candlestick chart with live price updates** — The trading terminal's price panel is now a full candlestick chart instead of a flat line. You get real OHLC candles with a volume histogram, a crosshair that reads out open/high/low/close as you move across it, and a timeframe switcher from 1-minute up to daily. Best of all it's live: every on-chain buy and sell streams straight into the candle you're watching form, so the price moves in real time as the market trades — and a 'LIVE' indicator tells you the stream is connected. Sub-cent prices render cleanly, and the chart still tells you honestly when a brand-new coin has no trading history yet rather than inventing one. (`/terminal`) `[feature, improvement]`
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index dd9439afd..0da8176f5 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -475,12 +475,24 @@ async function handleList(req, res, url) {
ap.amount AS asset_price_amount,
ap.currency_mint AS asset_price_currency_mint,
ap.chain AS asset_price_chain,
- ap.mint_decimals AS asset_price_mint_decimals
+ ap.mint_decimals AS asset_price_mint_decimals,
+ os.oracle_total, os.oracle_wins, os.oracle_win_rate, os.oracle_pnl_sol
FROM agent_identities ai
LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
LEFT JOIN users u ON u.id = ai.user_id
LEFT JOIN asset_prices ap
ON ap.item_type = 'agent' AND ap.item_id = ai.id AND ap.is_active = true
+ LEFT JOIN (
+ SELECT agent_id,
+ COUNT(*)::int AS oracle_total,
+ COUNT(*) FILTER (WHERE outcome = 'win')::int AS oracle_wins,
+ ROUND(100.0 * COUNT(*) FILTER (WHERE outcome = 'win')
+ / NULLIF(COUNT(*) FILTER (WHERE outcome IN ('win','loss')), 0), 1) AS oracle_win_rate,
+ ROUND(COALESCE(SUM(realized_pnl_sol), 0)::numeric, 4) AS oracle_pnl_sol
+ FROM oracle_watch_actions
+ WHERE outcome IS NOT NULL
+ GROUP BY agent_id
+ ) os ON os.agent_id = ai.id
WHERE ai.is_published = true
AND ai.deleted_at IS NULL
AND ai.name !~* ${AGENT_AUTONAMED_RE_SQL}
@@ -1382,6 +1394,15 @@ function toCard(row) {
solana_vanity_suffix: row.solana_vanity_suffix || null,
// Agent Genome pedigree — drives the rare-pedigree badge on the card.
genome: genomeCardField(row),
+ // Oracle trading track record — null when agent has no oracle history.
+ oracle: row.oracle_total > 0
+ ? {
+ total: row.oracle_total,
+ wins: row.oracle_wins,
+ win_rate: Number(row.oracle_win_rate ?? 0),
+ pnl_sol: Number(row.oracle_pnl_sol ?? 0),
+ }
+ : null,
};
}
diff --git a/data/changelog.json b/data/changelog.json
index a967872bd..7e52d946e 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,27 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-26",
+ "title": "Live oracle activity on marketplace and home — win rates, agents armed, and trades scored surface across the platform",
+ "summary": "Platform activity is now visible where users browse. The marketplace now shows a live strip above the agent grid with five oracle stats: agents currently armed, coins scored in the last 24 hours, platform win rate, open trades, and total oracle wins — all pulled live from the oracle engine. Agent cards that have oracle trading history now display a win-rate badge so you can spot proven performers at a glance. The home page platform section gets the same five-number panel so first-time visitors immediately see that the oracle is active.",
+ "tags": ["improvement", "feature"],
+ "link": "/marketplace"
+ },
+ {
+ "date": "2026-06-26",
+ "title": "Agent Screen Caster — standalone Playwright service streams live browser sessions to any watching agent profile",
+ "summary": "A new long-running Node.js service (services/agent-screen-caster) lets any agent process drive a real Chromium browser and stream what it sees — frame by frame — to three.ws. The AgentScreenCaster class wraps Playwright: it captures JPEG screenshots every 400 ms, compresses them to ~50 KB, and POSTs them to /api/agent/screen-push. Named actions (navigate, click, trade) push both a frame and a structured activity record so the watch panel shows what the agent is doing in plain language. Two built-in tasks ship out of the box: pump-monitor watches a pump.fun coin page and fires an activity event on every price change detected via DOM mutation; trade drives Jupiter, Raydium, or pump.fun swap UIs to submit real on-chain transactions. Run anywhere Docker runs — the Dockerfile uses the official Playwright Jammy image so Chromium and all system dependencies are pre-installed. Multiple agents can share one process as separate AgentScreenCaster instances.",
+ "tags": ["feature", "infra"],
+ "link": "/dashboard-next/watch"
+ },
+ {
+ "date": "2026-06-26",
+ "title": "Browser capture worker — agents can now stream real browser sessions to the live screen feed",
+ "summary": "A new worker (workers/agent-screen-worker) connects a Stagehand-driven browser session to the agent screen stream. The worker navigates the web autonomously, captures screenshots on every meaningful state change, and pushes both frames and plain-text activity narration to /api/agent-screen-push. Supports two modes: local Playwright (Docker, self-hosted) and Browserbase cloud (zero-infra, just set an API key). Swap in any task in task-runner.js — the default scans pump.fun for trending tokens and narrates each step.",
+ "tags": ["feature", "infra"],
+ "link": "/agent-screen"
+ },
{
"date": "2026-06-26",
"title": "Agent Screen — watch your agent's live screen and avatar cam in 2D and in the 3D world",
diff --git a/docs/aws-partner-spotlight.md b/docs/aws-partner-spotlight.md
new file mode 100644
index 000000000..6b61d7045
--- /dev/null
+++ b/docs/aws-partner-spotlight.md
@@ -0,0 +1,89 @@
+---
+title: "three.ws on AWS: giving AI agents a body, a wallet, and an AWS bill"
+venue: AWS Builder Center / APN Partner Spotlight
+account: three.ws (official)
+description: "A look at three.ws, an AWS Technology Partner building browser-native 3D AI agents that you can buy through AWS Marketplace, govern before they act, embed like a video, and let pay for their own work, all on infrastructure that meters to your AWS bill."
+tags: [aws, marketplace, agentic-ai, generative-ai, 3d, open-source]
+canonical: https://three.ws/docs/aws-partner-spotlight.md
+---
+
+# three.ws on AWS: giving AI agents a body, a wallet, and an AWS bill
+
+Most enterprise AI agents live inside a chat box. For a lot of work that is exactly right. But for a growing class of experiences, including brand agents, product guides, tutors, training characters, storefront assistants, and in-world companions, a text box leaves most of the value on the table. A text box cannot be present. It cannot stand in a room, point at a product, walk a customer through a space, or carry a persistent identity that follows a user across a site and acts on their behalf.
+
+[three.ws](https://three.ws) is built on a simple thesis: the next interface for AI is spatial, embeddable, and able to act. The platform gives an AI agent a body. You describe an agent in a sentence, and in a few minutes it becomes a textured, rigged, talking 3D character. You give it a brain, optionally a wallet and an on-chain identity, and you drop it onto any web page with a single line of HTML, as easily as embedding a video. The agent renders right in the browser, holds a conversation, remembers across visits, reacts to the page around it, and when you let it, pays for the data and tools it needs to be useful.
+
+three.ws is an **AWS Technology Partner in the AWS Partner Network** and is **live on AWS Marketplace**, so an enterprise can adopt all of this through procurement it already trusts. This is a look at what the team has built, what they are building next, and why running it with AWS makes embodied agents something a business can actually buy, govern, and put into production.
+
+---
+
+## The idea: give AI a body
+
+Today's agents reply. three.ws agents are present. The difference sounds small and turns out to be enormous. An embodied agent can stand on your storefront and walk a shopper through a product. It can be a tutor that demonstrates rather than describes. It can be a brand character that greets every visitor and remembers the last conversation. It can be a guide inside a 3D space, or a companion that strolls alongside a user as they move through a site.
+
+Two problems have historically killed projects like these before they ship. The first is the sheer cost of building a 3D and games pipeline just to put a character on a page. The second is that even a beautiful agent is inert if it cannot act, if it cannot reach for a tool, pull live data, or pay for the thing that makes it useful. three.ws set out to remove both. Generating and rendering a 3D agent now takes a prompt and a browser, no games team required. And acting, including paying for what it consumes, is built into the runtime. What is left is the fun part: deciding what your agent should be and where it should live.
+
+---
+
+## What three.ws has built
+
+The platform is broad on purpose, because an agent with a body needs a great many things to feel real. The pieces fit together into one product.
+
+**From a sentence to a character.** The generation engine, Forge, turns a text prompt, a few reference photos, or even a hand-drawn sketch into a finished 3D model in minutes, at quality tiers that range from a quick draft to a high-fidelity, physically textured character. There is a free lane that needs no account, so anyone can try it.
+
+**A body that actually moves.** A generated or uploaded model is automatically rigged and brought to life with a deep library of motion, from idle and walk to gestures and a wide emote set. The clever part is that it works with almost any character you bring, rather than a short list of blessed formats, so an avatar walks and gestures and emotes instead of freezing into a lifeless pose. Faces lip-sync to speech, expressions shift with the conversation, and the agent can speak and listen out loud.
+
+**A real mind, not just a script.** Every agent gets a brain with memory and emotion. Builders choose the model behind it, with the latest Claude models as the default and IBM Granite among the first-class options. Emotion is a living blend rather than a set of canned states, and it reads out in the agent's face and posture. Memory persists across sessions and can be genuinely owned by the user, portable, exportable, and verifiable, so an agent's mind is not locked inside one vendor.
+
+**Awareness of where it lives.** A three.ws agent understands the page it is embedded in. It can move across the layout, react to what is happening, and politely cover its eyes when you type a password into a form. It is a participant on the page, not a widget bolted onto the corner of it.
+
+**One line to ship it.** When the agent is ready, it embeds anywhere as a simple web component, a single line of HTML, with a companion library for application teams. The same agent that took shape from a sentence drops into a marketing page, a storefront, a dashboard, or a documentation site without a rebuild. The proof is that these agents already run in production, including a finance dashboard where the avatar reacts with its body language as a position moves, and a live storefront.
+
+**A way to act and to pay.** Agents reach tools through an open standard, and when a tool costs money they can pay for it directly, by the call, with a verifiable receipt and a hard spending limit the owner sets. That last capability is what turns an agent from something that answers into something that does.
+
+**An identity and an economy.** Agents can carry a portable, on-chain identity, a stable name, a wallet, a reputation that cannot be forged, and they can participate in a working economy where agents and people post real work, claim it, deliver it, and get paid. Governance sits in front of the spending, deciding whether an action is allowed, and a tamper-evident record proves what actually happened.
+
+The throughline across all of it is a single, ambitious idea: an agent you can see, talk to, trust, and hand a budget, embedded as easily as a video.
+
+---
+
+## Why AWS
+
+three.ws runs across several clouds, each carrying the work it is best at, and AWS carries the parts where its strengths matter most: storage and delivery of the 3D assets, a slice of the rendering, the operational visibility a serious platform needs, and, most importantly for an enterprise, procurement.
+
+The platform is listed on **AWS Marketplace** as a usage-based product. That single fact changes how a business can adopt it. Instead of a separate vendor relationship and a new way to pay, an enterprise subscribes through the marketplace it already uses, and consumption shows up as one line item on the AWS bill, drawn from existing credits and counted toward existing commitments. No crypto and no card are required to get started. The finance and security teams see something familiar, and the builders get an agent platform without a procurement detour.
+
+What makes this genuinely novel is what sits underneath. three.ws agents can already pay for tools on their own, by the call, over an open payment rail. The team connected that same rail to AWS Marketplace, so one product now bills two ways through the very same door. A large enterprise pays through AWS and sees a clean line item. An independent developer pays per call with stablecoins and needs no account at all. Both are reaching the identical capability. The choice of how to pay is theirs, and the platform meters whichever world the caller comes from. That is a clean, pay-for-what-you-use model that fits how enterprises actually want to adopt agentic AI: autonomous where it helps, bounded by policy, and auditable end to end.
+
+Running on AWS also brings the operational posture an enterprise expects. The team manages its AWS footprint as code, so the environment is reproducible and reviewable rather than hand-assembled. Activity is centralized where an AWS-native operations team already looks, so the people responsible for uptime and security can watch the platform with the tools they already trust. And the whole thing is grouped as a single application in the AWS console, with cost and operational views in one place.
+
+---
+
+## Trust, because these agents hold real value
+
+An agent that can carry an identity and spend from a wallet has to be defensible, not just delightful. three.ws treats trust as a feature rather than an afterthought.
+
+Governance comes before action. When an agent proposes to spend or to act autonomously, that action is weighed against named risks and can be allowed, sent for review, or blocked outright, and a blocked action does not happen. Every one of those decisions is written into a record that cannot be quietly altered and that anyone can re-verify. Spending lives inside limits the owner sets in plain language. Wallets defend themselves, learning an agent's normal behavior and freezing anything that looks wrong. And custody is provable, with regular snapshots anyone can check for themselves, rather than a promise to be taken on faith.
+
+The principle is consistent: governance decides whether an agent may act, and an unforgeable record proves what it did. For an enterprise, that pairing is the difference between a fun demo and something you can put in front of customers.
+
+---
+
+## What three.ws is building next
+
+The platform ships at a pace that is hard to overstate, going from first public appearance to a live, on-stream build with a major partner in roughly two months, and the roadmap keeps widening.
+
+Voice and presence are getting deeper, with real-time spoken conversation, voice cloning, and autonomous voice agents that can join a live audio space, listen, and respond. The agents are stepping off the screen entirely through augmented and virtual reality, where a character can be placed on your real floor, hide behind real objects, and be seen by other people nearby. Whole 3D worlds are being built where agents and people share space, explore, and play together. The agent economy is growing into a genuine marketplace of work, with reputation, verification, and real payment at its core. And the team is helping write the open standards for all of this, so embodiment and agent-to-agent payment become part of the open web rather than one company's private interface. The bet, consistently, is on open rails over walled gardens.
+
+---
+
+## In short
+
+three.ws gives an AI agent a body, a memory, a personality, an identity, and the ability to act and pay, then makes it embeddable in a single line of HTML. AWS is what makes it adoptable at enterprise scale: a platform you can buy through AWS Marketplace, govern before it acts, watch with the tools you already run, and bill, by the call, to your AWS account, against the very same capability an independent developer reaches with no account at all.
+
+One product. Two ways to pay. One AWS bill.
+
+**Learn more**
+- Platform: [three.ws](https://three.ws)
+- AWS Marketplace and procurement: `three.ws/docs/aws-marketplace.md`
+- How agents reach and pay for tools: `three.ws/docs/x402.md`, `three.ws/docs/mcp.md`
diff --git a/pages/home.html b/pages/home.html
index 76999589b..378b13f47 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -394,6 +394,61 @@
}
/* ── THREE DOORS ─────────────────────────────────────────── */
+ /* ── Platform oracle activity strip ─────────────────────── */
+ .home-oracle-strip {
+ display: grid;
+ grid-template-columns: repeat(5, 1fr);
+ gap: 1px;
+ background: var(--hairline);
+ border: 1px solid var(--hairline);
+ border-radius: 12px;
+ overflow: hidden;
+ margin-bottom: 40px;
+ }
+ @media (max-width: 720px) {
+ .home-oracle-strip { grid-template-columns: repeat(3, 1fr); }
+ .home-oracle-strip .home-oracle-kpi:nth-child(n+4) { display: none; }
+ }
+ .home-oracle-kpi {
+ background: var(--surface-0);
+ padding: 18px 20px 16px;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 4px;
+ }
+ .home-oracle-kpi-value {
+ font-size: 22px;
+ font-weight: 700;
+ letter-spacing: -0.03em;
+ color: var(--text);
+ line-height: 1;
+ }
+ .home-oracle-kpi-value.accent { color: #34d399; }
+ .home-oracle-kpi-value.loading { color: var(--text-3); animation: home-oracle-pulse 1.4s ease-in-out infinite; }
+ @keyframes home-oracle-pulse { 0%,100% { opacity: 0.4; } 50% { opacity: 1; } }
+ .home-oracle-kpi-label {
+ font-size: 11px;
+ font-weight: 500;
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ color: var(--text-3);
+ }
+ .home-oracle-live-dot {
+ display: inline-block;
+ width: 6px; height: 6px;
+ border-radius: 50%;
+ background: #34d399;
+ margin-right: 4px;
+ vertical-align: middle;
+ animation: home-oracle-dot-blink 2s ease-out infinite;
+ }
+ @keyframes home-oracle-dot-blink {
+ 0% { box-shadow: 0 0 0 0 rgba(52,211,153,0.6); }
+ 70% { box-shadow: 0 0 0 5px transparent; }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+ }
+
.doors {
display: grid; grid-template-columns: repeat(3, 1fr);
gap: 1px; background: var(--hairline);
@@ -2725,6 +2780,29 @@
A full-stack platform for 3D AI agents: from selfie to published agent, from embed to earning.
</p>
</div>
+ <!-- Live platform oracle activity stats -->
+ <div class="home-oracle-strip reveal reveal-d1" id="home-oracle-strip" aria-label="Live platform activity">
+ <div class="home-oracle-kpi">
+ <span class="home-oracle-kpi-value loading" id="home-stat-agents">—</span>
+ <span class="home-oracle-kpi-label">Agents live</span>
+ </div>
+ <div class="home-oracle-kpi">
+ <span class="home-oracle-kpi-value loading" id="home-stat-scored">—</span>
+ <span class="home-oracle-kpi-label">Scored today</span>
+ </div>
+ <div class="home-oracle-kpi">
+ <span class="home-oracle-kpi-value accent loading" id="home-stat-winrate">—</span>
+ <span class="home-oracle-kpi-label"><span class="home-oracle-live-dot" aria-hidden="true"></span>Win rate</span>
+ </div>
+ <div class="home-oracle-kpi">
+ <span class="home-oracle-kpi-value loading" id="home-stat-wins">—</span>
+ <span class="home-oracle-kpi-label">Total wins</span>
+ </div>
+ <div class="home-oracle-kpi">
+ <span class="home-oracle-kpi-value loading" id="home-stat-pnl">—</span>
+ <span class="home-oracle-kpi-label">Best ATH</span>
+ </div>
+ </div>
<div class="doors reveal reveal-d1">
<a class="door" href="/create" data-cta="build_agent" data-cta-loc="doors">
<div class="door-num"><span>01</span><span class="lbl">Create</span></div>
@@ -7068,5 +7146,40 @@
</script>
<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
<script type="module" src="/src/i18n.js"></script>
+ <script>
+ // Live oracle activity stats for "The platform" section.
+ (function () {
+ var IDS = {
+ agents: 'home-stat-agents',
+ scored: 'home-stat-scored',
+ winrate: 'home-stat-winrate',
+ wins: 'home-stat-wins',
+ pnl: 'home-stat-pnl',
+ };
+ function fmt(n) {
+ if (n == null) return '—';
+ if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
+ return String(Math.round(n));
+ }
+ function set(id, val) {
+ var el = document.getElementById(id);
+ if (!el) return;
+ el.textContent = val;
+ el.classList.remove('loading');
+ }
+ fetch('/api/oracle/stats', { headers: { accept: 'application/json' } })
+ .then(function (r) { return r.ok ? r.json() : null; })
+ .then(function (d) {
+ if (!d) return;
+ set(IDS.agents, fmt(d.agents_armed));
+ set(IDS.scored, fmt(d.scored_24h));
+ set(IDS.winrate, d.win_rate != null ? Number(d.win_rate).toFixed(0) + '%' : '—');
+ set(IDS.wins, fmt(d.total_wins));
+ set(IDS.pnl, d.best_ath != null ? d.best_ath.toFixed(1) + 'x' : '—');
+ })
+ .catch(function () { /* non-fatal — placeholders stay */ });
+ })();
+ </script>
</body>
</html>
diff --git a/pages/marketplace.html b/pages/marketplace.html
index bd87f93cf..4eaa86c73 100644
--- a/pages/marketplace.html
+++ b/pages/marketplace.html
@@ -2259,6 +2259,80 @@
@media (max-width: 640px) {
.market-pulse-label span:not(.market-pulse-dot) { display: none; }
}
+
+ /* ── Platform activity strip ──────────────────────────────────── */
+ .market-activity-strip {
+ display: flex;
+ align-items: center;
+ gap: 0;
+ margin: 0 0 14px;
+ border: 1px solid var(--stroke);
+ border-radius: 12px;
+ overflow: hidden;
+ background: var(--surface-1);
+ }
+ .market-activity-kpi {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 10px 20px;
+ flex: 1 1 0;
+ min-width: 0;
+ border-right: 1px solid var(--stroke);
+ gap: 2px;
+ }
+ .market-activity-kpi:last-child { border-right: none; }
+ .market-activity-kpi-value {
+ font-size: 16px;
+ font-weight: 700;
+ color: var(--text);
+ letter-spacing: -0.02em;
+ white-space: nowrap;
+ }
+ .market-activity-kpi-value.positive { color: #34d399; }
+ .market-activity-kpi-value.loading { color: var(--text-3); }
+ .market-activity-kpi-label {
+ font-size: 10px;
+ font-weight: 500;
+ color: var(--text-3);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ white-space: nowrap;
+ }
+ .market-activity-kpi-dot {
+ display: inline-block;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--accent, #34d399);
+ margin-right: 5px;
+ animation: market-pulse-blink 2s ease-out infinite;
+ vertical-align: middle;
+ }
+ @media (max-width: 600px) {
+ .market-activity-strip { display: none; }
+ }
+
+ /* ── Oracle win-rate badge on agent cards ─────────────────────── */
+ .oracle-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 3px 8px;
+ border-radius: 999px;
+ font-size: 11px;
+ font-weight: 600;
+ background: color-mix(in srgb, #34d399 12%, transparent);
+ color: #34d399;
+ border: 1px solid color-mix(in srgb, #34d399 25%, transparent);
+ }
+ .oracle-badge.neutral {
+ background: color-mix(in srgb, #a1a1aa 10%, transparent);
+ color: #a1a1aa;
+ border-color: color-mix(in srgb, #a1a1aa 20%, transparent);
+ }
+
.market-anim-card {
background: var(--surface-1);
border: 1px solid var(--stroke);
@@ -3086,6 +3160,30 @@
<div class="market-tag-banner" id="market-tag-banner" role="status" hidden></div>
+ <!-- Platform activity strip — live oracle stats -->
+ <div class="market-activity-strip" id="market-activity-strip" hidden>
+ <div class="market-activity-kpi">
+ <span class="market-activity-kpi-value loading" id="mkt-stat-agents">—</span>
+ <span class="market-activity-kpi-label">Agents live</span>
+ </div>
+ <div class="market-activity-kpi">
+ <span class="market-activity-kpi-value loading" id="mkt-stat-scored">—</span>
+ <span class="market-activity-kpi-label">Scored today</span>
+ </div>
+ <div class="market-activity-kpi">
+ <span class="market-activity-kpi-value positive loading" id="mkt-stat-winrate">—</span>
+ <span class="market-activity-kpi-label"><span class="market-activity-kpi-dot" aria-hidden="true"></span>Win rate</span>
+ </div>
+ <div class="market-activity-kpi">
+ <span class="market-activity-kpi-value loading" id="mkt-stat-actions">—</span>
+ <span class="market-activity-kpi-label">Open trades</span>
+ </div>
+ <div class="market-activity-kpi">
+ <span class="market-activity-kpi-value loading" id="mkt-stat-wins">—</span>
+ <span class="market-activity-kpi-label">Total wins</span>
+ </div>
+ </div>
+
<aside
class="market-pulse"
id="market-pulse"
diff --git a/public/changelog.json b/public/changelog.json
index 3ff0346b8..70aeef341 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-26T18:45:53.543Z",
+ "generated_at": "2026-06-26T19:51:04.595Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -108,6 +108,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "Agent Screen Caster — standalone Playwright service streams live browser sessions to any watching agent profile",
+ "summary": "A new long-running Node.js service (services/agent-screen-caster) lets any agent process drive a real Chromium browser and stream what it sees — frame by frame — to three.ws. The AgentScreenCaster class wraps Playwright: it captures JPEG screenshots every 400 ms, compresses them to ~50 KB, and POSTs them to /api/agent/screen-push. Named actions (navigate, click, trade) push both a frame and a structured activity record so the watch panel shows what the agent is doing in plain language. Two built-in tasks ship out of the box: pump-monitor watches a pump.fun coin page and fires an activity event on every price change detected via DOM mutation; trade drives Jupiter, Raydium, or pump.fun swap UIs to submit real on-chain transactions. Run anywhere Docker runs — the Dockerfile uses the official Playwright Jammy image so Chromium and all system dependencies are pre-installed. Multiple agents can share one process as separate AgentScreenCaster instances.",
+ "link": "/dashboard-next/watch",
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-26",
"type": "update",
@@ -183,6 +194,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "Browser capture worker — agents can now stream real browser sessions to the live screen feed",
+ "summary": "A new worker (workers/agent-screen-worker) connects a Stagehand-driven browser session to the agent screen stream. The worker navigates the web autonomously, captures screenshots on every meaningful state change, and pushes both frames and plain-text activity narration to /api/agent-screen-push. Supports two modes: local Playwright (Docker, self-hosted) and Browserbase cloud (zero-infra, just set an API key). Swap in any task in task-runner.js — the default scans pump.fun for trending tokens and narrates each step.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-26",
"type": "update",
@@ -310,6 +332,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "Live oracle activity on marketplace and home — win rates, agents armed, and trades scored surface across the platform",
+ "summary": "Platform activity is now visible where users browse. The marketplace now shows a live strip above the agent grid with five oracle stats: agents currently armed, coins scored in the last 24 hours, platform win rate, open trades, and total oracle wins — all pulled live from the oracle engine. Agent cards that have oracle trading history now display a win-rate badge so you can spot proven performers at a glance. The home page platform section gets the same five-number panel so first-time visitors immediately see that the oracle is active.",
+ "link": "/marketplace",
+ "tags": [
+ "improvement",
+ "feature"
+ ]
+ },
{
"date": "2026-06-26",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 656b273a7..d82da5dec 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -86,6 +86,14 @@
<category>feature</category>
<description>Agents can now broadcast what they're doing in real time. On any agent's profile, a new Watch view shows a split-panel: left is the agent's live screen (browser screenshots streamed at up to 2fps), right is the agent's avatar rendered as a webcam feed. In /play, agents with active streams appear seated at physical desks — walk up and their monitor shows the live feed, with an overlay that links to the full Watch view. Agents push frames and activity narration via POST /api/agent-screen-push from any worker or script. The stream stays live as long as the agent is active; when it goes dark the screen shows a waiting state that resumes automatically.</description>
</item>
+ <item>
+ <title>Agent Screen Caster — standalone Playwright service streams live browser sessions to any watching agent profile</title>
+ <link>https://three.ws/dashboard-next/watch</link>
+ <guid isPermaLink="false">2026-06-26:Agent Screen Caster — standalone Playwright service streams live browser sessions to any watching agent profile</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>A new long-running Node.js service (services/agent-screen-caster) lets any agent process drive a real Chromium browser and stream what it sees — frame by frame — to three.ws. The AgentScreenCaster class wraps Playwright: it captures JPEG screenshots every 400 ms, compresses them to ~50 KB, and POSTs them to /api/agent/screen-push. Named actions (navigate, click, trade) push both a frame and a structured activity record so the watch panel shows what the agent is doing in plain language. Two built-in tasks ship out of the box: pump-monitor watches a pump.fun coin page and fires an activity event on every price change detected via DOM mutation; trade drives Jupiter, Raydium, or pump.fun swap UIs to submit real on-chain transactions. Run anywhere Docker runs — the Dockerfile uses the official Playwright Jammy image so Chromium and all system dependencies are pre-installed. Multiple agents can share one process as separate AgentScreenCaster instances.</description>
+ </item>
<item>
<title>Alpha Co-pilot overhauled — agent gallery, cited-signal highlights, score bars, and live routing fixed</title>
<link>https://three.ws/alpha-copilot</link>
@@ -142,6 +150,14 @@
<category>improvement</category>
<description>Building an agent personality no longer requires picking an archetype, clicking Generate, reviewing a six-field card, choosing an agent from a dropdown, and hitting Save. Now it's one tap: pick a vibe (Sharp Analyst, Crypto Native, Casual Builder, and five more), and it applies and saves to your agent instantly. For custom personalities, type a description and press Enter — no separate button. The agent auto-selects from your roster at the top of the page. A slim status bar confirms the active persona with options to test it in the Playground, customize it, or clear it.</description>
</item>
+ <item>
+ <title>Browser capture worker — agents can now stream real browser sessions to the live screen feed</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-26:Browser capture worker — agents can now stream real browser sessions to the live screen feed</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>A new worker (workers/agent-screen-worker) connects a Stagehand-driven browser session to the agent screen stream. The worker navigates the web autonomously, captures screenshots on every meaningful state change, and pushes both frames and plain-text activity narration to /api/agent-screen-push. Supports two modes: local Playwright (Docker, self-hosted) and Browserbase cloud (zero-infra, just set an API key). Swap in any task in task-runner.js — the default scans pump.fun for trending tokens and narrates each step.</description>
+ </item>
<item>
<title>Claim Wallet is now a full Wallet Intelligence dashboard</title>
<link>https://three.ws/claim-wallet</link>
@@ -238,6 +254,14 @@
<category>fix</category>
<description>Going to /launchpad used to drop you into a page-builder studio instead of letting you launch anything. Now it's a real launchpad, like it should be: the live coin launcher is front and center, so you pick your agent, set the name, ticker, and image, and mint a Pump.fun coin straight from your wallet — creator fees route to you. Live launches from three.ws agents show right below it. The white-label page builder (hosted token page, paid concierge, gated 3D showroom) is still there as an optional add-on, not the main event. Token-launchpad pages also carry your coin details into the launch flow pre-filled and flip from &quot;Launch&quot; to a one-click &quot;Trade&quot; once your coin is live.</description>
</item>
+ <item>
+ <title>Live oracle activity on marketplace and home — win rates, agents armed, and trades scored surface across the platform</title>
+ <link>https://three.ws/marketplace</link>
+ <guid isPermaLink="false">2026-06-26:Live oracle activity on marketplace and home — win rates, agents armed, and trades scored surface across the platform</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Platform activity is now visible where users browse. The marketplace now shows a live strip above the agent grid with five oracle stats: agents currently armed, coins scored in the last 24 hours, platform win rate, open trades, and total oracle wins — all pulled live from the oracle engine. Agent cards that have oracle trading history now display a win-rate badge so you can spot proven performers at a glance. The home page platform section gets the same five-number panel so first-time visitors immediately see that the oracle is active.</description>
+ </item>
<item>
<title>Living Worlds video generator is back online</title>
<link>https://three.ws/cosmos</link>
diff --git a/public/features.json b/public/features.json
index d539ef8dc..6fe5ab448 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-26T18:45:53.530Z",
+ "generated_at": "2026-06-26T19:51:04.575Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/services/agent-screen-caster/Dockerfile b/services/agent-screen-caster/Dockerfile
new file mode 100644
index 000000000..df9238cc5
--- /dev/null
+++ b/services/agent-screen-caster/Dockerfile
@@ -0,0 +1,30 @@
+# syntax=docker/dockerfile:1
+# Agent Screen Caster — Playwright Chromium runner
+# Base: official Playwright image ships Chromium + all system deps pre-installed.
+# Pin the version to match the playwright package version in package.json.
+FROM mcr.microsoft.com/playwright:v1.49.0-jammy
+
+WORKDIR /app
+
+# Install Node dependencies first (layer cached unless package.json changes).
+COPY package.json ./
+RUN npm install --omit=dev
+
+# Copy service source.
+COPY . .
+
+# Playwright browsers are already baked into the base image at /ms-playwright.
+# Tell playwright to use the system-installed Chromium rather than downloading.
+ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
+
+# Default env (override at runtime via --env or -e flags).
+ENV NODE_ENV=production \
+ HEADLESS=true \
+ FRAME_INTERVAL_MS=400 \
+ JPEG_QUALITY=72 \
+ TASK=pump-monitor
+
+# Run as non-root (the Playwright base image provides the pwuser account).
+USER pwuser
+
+CMD ["node", "index.js"]
diff --git a/services/agent-screen-caster/caster.js b/services/agent-screen-caster/caster.js
new file mode 100644
index 000000000..f19b7616f
--- /dev/null
+++ b/services/agent-screen-caster/caster.js
@@ -0,0 +1,189 @@
+/**
+ * AgentScreenCaster
+ * -----------------
+ * Wraps a Playwright Chromium session, captures JPEG frames, and pushes them
+ * to the three.ws screen-push endpoint so any connected watch-panel or 3D desk
+ * can render the agent's live screen.
+ *
+ * Usage:
+ * const caster = new AgentScreenCaster({ agentId, bearerToken, pushUrl });
+ * await caster.launch();
+ * await caster.navigate('https://pump.fun');
+ * await caster.act('buy', async () => { ... });
+ * caster.startFrameLoop();
+ * // … later …
+ * await caster.close();
+ */
+
+import { chromium } from 'playwright';
+
+const DEFAULT_PUSH_URL = 'https://three.ws/api/agent/screen-push';
+const DEFAULT_FRAME_INTERVAL = 400; // ms between periodic captures
+const DEFAULT_JPEG_QUALITY = 72;
+const DEFAULT_VIEWPORT = { width: 1280, height: 720 };
+
+export class AgentScreenCaster {
+ /**
+ * @param {object} opts
+ * @param {string} opts.agentId UUID of the agent identity
+ * @param {string} opts.bearerToken JWT or API key for /api/agent/screen-push
+ * @param {string} [opts.pushUrl] Override the push endpoint
+ * @param {number} [opts.frameIntervalMs] Milliseconds between frame captures
+ * @param {number} [opts.jpegQuality] JPEG quality 1-100
+ */
+ constructor({ agentId, bearerToken, pushUrl, frameIntervalMs, jpegQuality } = {}) {
+ if (!agentId) throw new Error('agentId required');
+ if (!bearerToken) throw new Error('bearerToken required');
+
+ this.agentId = agentId;
+ this.bearerToken = bearerToken;
+ this.pushUrl = pushUrl || DEFAULT_PUSH_URL;
+ this.frameMs = frameIntervalMs ?? DEFAULT_FRAME_INTERVAL;
+ this.jpegQuality = jpegQuality ?? DEFAULT_JPEG_QUALITY;
+
+ this.browser = null;
+ this.context = null;
+ this.page = null;
+ this._timer = null;
+ this._seq = 0;
+ this._pushing = false; // guard against overlapping push calls
+ }
+
+ // ── Lifecycle ──────────────────────────────────────────────────────────────
+
+ async launch(headless = true) {
+ this.browser = await chromium.launch({
+ headless,
+ args: [
+ '--no-sandbox',
+ '--disable-setuid-sandbox',
+ '--disable-dev-shm-usage',
+ '--disable-gpu',
+ ],
+ });
+
+ this.context = await this.browser.newContext({
+ viewport: DEFAULT_VIEWPORT,
+ userAgent:
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
+ '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ locale: 'en-US',
+ timezoneId: 'America/New_York',
+ });
+
+ this.page = await this.context.newPage();
+
+ // Push a frame on every finished navigation so the watcher sees transitions.
+ this.page.on('load', () => this._safePushFrame());
+ }
+
+ async close() {
+ this.stopFrameLoop();
+ try { await this.browser?.close(); } catch {}
+ this.browser = this.context = this.page = null;
+ }
+
+ // ── Navigation & actions ───────────────────────────────────────────────────
+
+ /**
+ * Navigate to a URL. Pushes a frame + activity entry automatically.
+ */
+ async navigate(url, { waitUntil = 'domcontentloaded' } = {}) {
+ await this.pushActivity([{
+ type: 'navigate',
+ summary: `Navigating to ${url}`,
+ ts: Date.now(),
+ }]);
+ await this.page.goto(url, { waitUntil });
+ await this._safePushFrame();
+ }
+
+ /**
+ * Named action wrapper. Runs fn(), then pushes a frame capturing the result.
+ *
+ * @param {string} type Action type token (e.g. 'click', 'trade')
+ * @param {string} summary Human-readable description shown in watch panel
+ * @param {Function} fn Async action body
+ */
+ async act(type, summary, fn) {
+ await this.pushActivity([{ type, summary, ts: Date.now() }]);
+ await fn();
+ await this._safePushFrame();
+ }
+
+ // ── Frame loop ─────────────────────────────────────────────────────────────
+
+ startFrameLoop() {
+ if (this._timer) return;
+ this._timer = setInterval(() => this._safePushFrame(), this.frameMs);
+ }
+
+ stopFrameLoop() {
+ if (this._timer) {
+ clearInterval(this._timer);
+ this._timer = null;
+ }
+ }
+
+ // ── Push primitives ────────────────────────────────────────────────────────
+
+ /**
+ * Capture the current page as JPEG, base64-encode, and POST to screen-push.
+ */
+ async pushFrame() {
+ if (!this.page) return;
+
+ const buf = await this.page.screenshot({
+ type: 'jpeg',
+ quality: this.jpegQuality,
+ fullPage: false,
+ });
+
+ const frame = buf.toString('base64');
+ const seq = ++this._seq;
+
+ await this._post({ agentId: this.agentId, frame, seq });
+ }
+
+ /**
+ * POST structured activity records to screen-push.
+ *
+ * @param {Array<{ type: string, summary: string, payload?: any, ts?: number }>} actions
+ */
+ async pushActivity(actions) {
+ await this._post({ agentId: this.agentId, actions });
+ }
+
+ // ── Internals ──────────────────────────────────────────────────────────────
+
+ /** Non-throwing frame push — safe to call from event handlers and timers. */
+ async _safePushFrame() {
+ if (this._pushing) return;
+ this._pushing = true;
+ try {
+ await this.pushFrame();
+ } catch (err) {
+ console.error('[caster] frame push failed:', err?.message || err);
+ } finally {
+ this._pushing = false;
+ }
+ }
+
+ async _post(body) {
+ const res = await fetch(this.pushUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${this.bearerToken}`,
+ },
+ body: JSON.stringify(body),
+ });
+
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ throw new Error(`screen-push ${res.status}: ${text}`);
+ }
+
+ return res.json();
+ }
+}
diff --git a/services/agent-screen-caster/index.js b/services/agent-screen-caster/index.js
new file mode 100644
index 000000000..72e8a6cdd
--- /dev/null
+++ b/services/agent-screen-caster/index.js
@@ -0,0 +1,135 @@
+/**
+ * agent-screen-caster — CLI entrypoint
+ * -------------------------------------
+ * Reads configuration from environment variables (or .env file via --env flag),
+ * resolves the requested task module, instantiates AgentScreenCaster, and runs.
+ *
+ * Usage:
+ * node index.js
+ * node index.js --env .env.local
+ * TASK=pump-monitor TASK_ARG=<mint> node index.js
+ *
+ * Multiple agents in one process:
+ * Spin up additional AgentScreenCaster instances (each with their own
+ * agentId/bearerToken) and run their task functions concurrently.
+ *
+ * Env vars (see .env.example for full list):
+ * AGENT_ID UUID of the agent identity (required)
+ * AGENT_BEARER_TOKEN JWT or API key (required)
+ * PUSH_URL Override push endpoint (default: https://three.ws/api/agent/screen-push)
+ * FRAME_INTERVAL_MS Milliseconds between frame captures (default: 400)
+ * JPEG_QUALITY JPEG quality 1-100 (default: 72)
+ * HEADLESS "true" (default) | "false" for visible browser window
+ * TASK Task module name: pump-monitor | trade (default: pump-monitor)
+ * TASK_ARG Primary argument passed to the task (e.g. mint address)
+ */
+
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { AgentScreenCaster } from './caster.js';
+
+const __dir = dirname(fileURLToPath(import.meta.url));
+
+// ── Parse --env flag ───────────────────────────────────────────────────────────
+const envFlagIdx = process.argv.indexOf('--env');
+if (envFlagIdx !== -1) {
+ const envFile = process.argv[envFlagIdx + 1];
+ if (!envFile) fatal('--env requires a file path');
+ loadEnvFile(resolve(process.cwd(), envFile));
+} else if (fileExists('.env')) {
+ loadEnvFile(resolve(__dir, '.env'));
+}
+
+// ── Read config ────────────────────────────────────────────────────────────────
+const agentId = required('AGENT_ID');
+const bearerToken = required('AGENT_BEARER_TOKEN');
+const pushUrl = process.env.PUSH_URL || 'https://three.ws/api/agent/screen-push';
+const frameMs = Number(process.env.FRAME_INTERVAL_MS || 400);
+const jpegQuality = Number(process.env.JPEG_QUALITY || 72);
+const headless = process.env.HEADLESS !== 'false';
+const task = process.env.TASK || 'pump-monitor';
+const taskArg = process.env.TASK_ARG || '';
+
+// ── Resolve task module ────────────────────────────────────────────────────────
+const TASK_MAP = {
+ 'pump-monitor': './tasks/pump-monitor.js',
+ 'trade': './tasks/trade.js',
+};
+
+const taskPath = TASK_MAP[task];
+if (!taskPath) fatal(`Unknown task "${task}". Valid tasks: ${Object.keys(TASK_MAP).join(', ')}`);
+
+// ── Boot ───────────────────────────────────────────────────────────────────────
+const caster = new AgentScreenCaster({ agentId, bearerToken, pushUrl, frameIntervalMs: frameMs, jpegQuality });
+
+console.log('[agent-screen-caster] starting');
+console.log(' agentId :', agentId);
+console.log(' pushUrl :', pushUrl);
+console.log(' task :', task, taskArg ? `(arg: ${taskArg})` : '');
+console.log(' headless :', headless);
+console.log(' frameMs :', frameMs, 'ms jpegQuality:', jpegQuality);
+
+await caster.launch(headless);
+
+console.log('[agent-screen-caster] browser launched — starting task');
+
+const { run } = await import(taskPath);
+
+// Push an initial activity so watchers see the agent is alive.
+await caster.pushActivity([{
+ type: 'start',
+ summary: `Agent starting task: ${task}${taskArg ? ` — ${taskArg}` : ''}`,
+ ts: Date.now(),
+}]);
+
+caster.startFrameLoop();
+
+try {
+ await run(caster, taskArg);
+} catch (err) {
+ console.error('[agent-screen-caster] task error:', err?.message || err);
+ await caster.pushActivity([{
+ type: 'error',
+ summary: `Task error: ${err?.message || String(err)}`,
+ ts: Date.now(),
+ }]);
+} finally {
+ await caster.close();
+ console.log('[agent-screen-caster] shut down');
+}
+
+// ── Helpers ────────────────────────────────────────────────────────────────────
+
+function required(name) {
+ const v = process.env[name];
+ if (!v) fatal(`Missing required env var: ${name}`);
+ return v;
+}
+
+function fatal(msg) {
+ console.error('[agent-screen-caster] fatal:', msg);
+ process.exit(1);
+}
+
+function fileExists(path) {
+ try { readFileSync(resolve(__dir, path)); return true; } catch { return false; }
+}
+
+function loadEnvFile(path) {
+ let raw;
+ try { raw = readFileSync(path, 'utf8'); } catch { fatal(`Cannot read env file: ${path}`); }
+
+ for (const line of raw.split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed.startsWith('#')) continue;
+ const eqIdx = trimmed.indexOf('=');
+ if (eqIdx === -1) continue;
+ const key = trimmed.slice(0, eqIdx).trim();
+ const val = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, '');
+ if (key && !(key in process.env)) process.env[key] = val;
+ }
+}
+
+process.on('SIGTERM', async () => { await caster.close(); process.exit(0); });
+process.on('SIGINT', async () => { await caster.close(); process.exit(0); });
diff --git a/services/agent-screen-caster/package.json b/services/agent-screen-caster/package.json
new file mode 100644
index 000000000..d538fadef
--- /dev/null
+++ b/services/agent-screen-caster/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "agent-screen-caster",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "main": "index.js",
+ "scripts": {
+ "start": "node index.js",
+ "dev": "HEADLESS=false node index.js"
+ },
+ "engines": { "node": ">=20" },
+ "dependencies": {
+ "playwright": "^1.49.0"
+ }
+}
diff --git a/services/agent-screen-caster/tasks/pump-monitor.js b/services/agent-screen-caster/tasks/pump-monitor.js
new file mode 100644
index 000000000..313b8852e
--- /dev/null
+++ b/services/agent-screen-caster/tasks/pump-monitor.js
@@ -0,0 +1,122 @@
+/**
+ * pump-monitor task
+ * -----------------
+ * Navigates to a pump.fun coin page, watches for price and holder changes
+ * via DOM mutation observation, and streams live frames + activity to the
+ * three.ws watch panel.
+ *
+ * Usage:
+ * TASK=pump-monitor TASK_ARG=<mint_address> node index.js
+ */
+
+// DOM selectors — pump.fun layout as of 2025. Update if selectors break.
+const SEL_PRICE = '[data-testid="token-price"], .token-price, [class*="price"]';
+const SEL_MARKET_CAP = '[data-testid="market-cap"], .market-cap, [class*="marketCap"]';
+const SEL_TX_ROW = '[data-testid="tx-row"], .tx-row, [class*="transaction"]';
+const POLL_INTERVAL_MS = 15_000; // fallback DOM poll when mutations miss
+
+/**
+ * @param {import('../caster.js').AgentScreenCaster} caster
+ * @param {string} mint Mint address of the coin to monitor
+ */
+export async function run(caster, mint) {
+ if (!mint) {
+ mint = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+ console.log('[pump-monitor] no mint provided, defaulting to $THREE');
+ }
+
+ const coinUrl = `https://pump.fun/coin/${mint}`;
+ await caster.navigate(coinUrl);
+
+ // Let the page settle before wiring observers.
+ await caster.page.waitForTimeout(2000);
+
+ // Expose a callback so the browser context can push activity back to us.
+ await caster.page.exposeFunction('__onPriceChange', async (price, marketCap) => {
+ try {
+ await caster.pushActivity([{
+ type: 'price_update',
+ summary: `Price: ${price}${marketCap ? ` • MCap: ${marketCap}` : ''} — ${mint.slice(0, 8)}…`,
+ ts: Date.now(),
+ payload: { price, marketCap, mint },
+ }]);
+ } catch {}
+ });
+
+ await caster.page.exposeFunction('__onNewTx', async (txSummary) => {
+ try {
+ await caster.pushActivity([{
+ type: 'transaction',
+ summary: txSummary,
+ ts: Date.now(),
+ payload: { mint },
+ }]);
+ } catch {}
+ });
+
+ // Wire DOM observers inside the page.
+ await caster.page.evaluate(({ selPrice, selMcap, selTx }) => {
+ let lastPrice = '';
+ let lastTxHtml = '';
+
+ function readText(sel) {
+ return document.querySelector(sel)?.textContent?.trim() || '';
+ }
+
+ function checkPrice() {
+ const price = readText(selPrice);
+ const mcap = readText(selMcap);
+ if (price && price !== lastPrice) {
+ lastPrice = price;
+ window.__onPriceChange(price, mcap);
+ }
+ }
+
+ function checkTxs() {
+ const rows = document.querySelectorAll(selTx);
+ if (!rows.length) return;
+ const firstHtml = rows[0]?.innerHTML || '';
+ if (firstHtml && firstHtml !== lastTxHtml) {
+ lastTxHtml = firstHtml;
+ const text = rows[0]?.textContent?.trim().slice(0, 120) || 'New transaction';
+ window.__onNewTx(text);
+ }
+ }
+
+ const obs = new MutationObserver(() => { checkPrice(); checkTxs(); });
+ obs.observe(document.body, { childList: true, subtree: true, characterData: true });
+
+ // Run once immediately in case data is already present.
+ checkPrice();
+ checkTxs();
+ }, { selPrice: SEL_PRICE, selMcap: SEL_MARKET_CAP, selTx: SEL_TX_ROW });
+
+ // Periodically scroll + screenshot to keep the feed alive even when
+ // mutations don't fire (e.g. infinite-scroll pagination).
+ const keepAlive = setInterval(async () => {
+ try {
+ await caster.page.evaluate(() => window.scrollBy(0, 50));
+ await caster.page.evaluate(() => window.scrollBy(0, -50));
+ } catch {}
+ }, POLL_INTERVAL_MS);
+
+ // Handle page navigations away (pump.fun is a SPA; re-anchor if needed).
+ caster.page.on('framenavigated', async (frame) => {
+ if (frame !== caster.page.mainFrame()) return;
+ const url = frame.url();
+ if (!url.includes('/coin/')) {
+ console.log('[pump-monitor] SPA nav away detected, returning to coin page');
+ try { await caster.navigate(coinUrl); } catch {}
+ }
+ });
+
+ console.log(`[pump-monitor] watching ${mint} — Ctrl-C to stop`);
+
+ // Run until the process is terminated.
+ await new Promise((_, reject) => {
+ process.once('SIGTERM', () => { clearInterval(keepAlive); reject(new Error('SIGTERM')); });
+ process.once('SIGINT', () => { clearInterval(keepAlive); reject(new Error('SIGINT')); });
+ }).catch(() => {});
+
+ clearInterval(keepAlive);
+}
diff --git a/services/agent-screen-caster/tasks/trade.js b/services/agent-screen-caster/tasks/trade.js
new file mode 100644
index 000000000..97a9cb050
--- /dev/null
+++ b/services/agent-screen-caster/tasks/trade.js
@@ -0,0 +1,199 @@
+/**
+ * trade task
+ * ----------
+ * Drives a Solana DEX/swap UI to execute trades on behalf of an agent.
+ * The task accepts a JSON-encoded trade spec as TASK_ARG:
+ *
+ * TASK=trade TASK_ARG='{"dex":"jup","inputMint":"So11...","outputMint":"<mint>","amountSol":0.1}' node index.js
+ *
+ * Supported DEX targets (controlled by spec.dex):
+ * jup — jup.ag (Jupiter aggregator)
+ * raydium — raydium.io swap UI
+ * pump — pump.fun coin page quick-buy
+ *
+ * The wallet must already be connected in the browser context (injected via
+ * storageState or by supplying a WALLET_STORAGE_STATE_PATH env that points to
+ * a Playwright storageState JSON exported from a prior authenticated session).
+ */
+
+const DEX_URLS = {
+ jup: 'https://jup.ag/swap',
+ raydium: 'https://raydium.io/swap/',
+ pump: 'https://pump.fun/coin',
+};
+
+// Selectors — update these if DEX UIs change their DOM structure.
+const JUP_SEL = {
+ inputAmount: 'input[placeholder*="0.00"], input[data-testid="from-amount"]',
+ swapBtn: 'button[data-testid="swap-button"], button:has-text("Swap")',
+ confirmBtn: 'button:has-text("Confirm"), button:has-text("Approve")',
+};
+
+const PUMP_SEL = {
+ buyTab: 'button:has-text("Buy")',
+ amountInput: 'input[placeholder*="SOL"], input[name="amount"]',
+ buyBtn: 'button:has-text("Place Trade"), button:has-text("Buy")',
+};
+
+const RAYDIUM_SEL = {
+ inputAmount: 'input[placeholder*="0.00"]',
+ swapBtn: 'button:has-text("Swap"), button[class*="swap-btn"]',
+};
+
+/**
+ * @param {import('../caster.js').AgentScreenCaster} caster
+ * @param {string} argStr JSON-encoded trade spec (see module JSDoc above)
+ */
+export async function run(caster, argStr) {
+ let spec;
+ try {
+ spec = argStr ? JSON.parse(argStr) : {};
+ } catch {
+ throw new Error(`TASK_ARG must be valid JSON trade spec, got: ${argStr}`);
+ }
+
+ const {
+ dex = 'pump',
+ outputMint = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ amountSol = 0.01,
+ slippageBps = 100,
+ } = spec;
+
+ if (!DEX_URLS[dex]) throw new Error(`Unknown dex "${dex}". Valid: ${Object.keys(DEX_URLS).join(', ')}`);
+
+ // Load wallet session state if provided.
+ const storagePath = process.env.WALLET_STORAGE_STATE_PATH;
+ if (storagePath) {
+ const { readFileSync } = await import('fs');
+ try {
+ const state = JSON.parse(readFileSync(storagePath, 'utf8'));
+ await caster.context.addCookies(state.cookies || []);
+ if (state.origins) {
+ for (const origin of state.origins) {
+ await caster.context.addInitScript(({ url, entries }) => {
+ if (window.location.origin !== url) return;
+ for (const { name, value } of entries) localStorage.setItem(name, value);
+ }, { url: origin.origin, entries: origin.localStorage || [] });
+ }
+ }
+ console.log('[trade] wallet storage state loaded from', storagePath);
+ } catch (err) {
+ console.warn('[trade] could not load wallet storage state:', err.message);
+ }
+ }
+
+ console.log(`[trade] executing ${dex} trade: ${amountSol} SOL → ${outputMint.slice(0, 8)}…`);
+
+ if (dex === 'pump') {
+ await executePumpTrade(caster, outputMint, amountSol);
+ } else if (dex === 'jup') {
+ await executeJupTrade(caster, outputMint, amountSol, slippageBps);
+ } else if (dex === 'raydium') {
+ await executeRaydiumTrade(caster, outputMint, amountSol, slippageBps);
+ }
+}
+
+// ── DEX-specific flows ─────────────────────────────────────────────────────────
+
+async function executePumpTrade(caster, mint, amountSol) {
+ const url = `${DEX_URLS.pump}/${mint}`;
+
+ await caster.act('navigate', `Opening pump.fun coin page for ${mint.slice(0, 8)}…`, async () => {
+ await caster.page.goto(url, { waitUntil: 'domcontentloaded' });
+ await caster.page.waitForTimeout(2500);
+ });
+
+ await caster.act('click', 'Switching to Buy tab', async () => {
+ const buyTab = await caster.page.$(PUMP_SEL.buyTab);
+ if (buyTab) await buyTab.click();
+ await caster.page.waitForTimeout(500);
+ });
+
+ await caster.act('input', `Entering trade amount: ${amountSol} SOL`, async () => {
+ const input = await caster.page.waitForSelector(PUMP_SEL.amountInput, { timeout: 8000 });
+ await input.triple_click?.() ?? await input.click({ clickCount: 3 });
+ await input.fill(String(amountSol));
+ await caster.page.waitForTimeout(300);
+ });
+
+ await caster.act('trade', `Submitting buy order: ${amountSol} SOL of ${mint.slice(0, 8)}…`, async () => {
+ const btn = await caster.page.waitForSelector(PUMP_SEL.buyBtn, { timeout: 8000 });
+ await btn.click();
+ await caster.page.waitForTimeout(3000);
+ });
+
+ await caster.pushActivity([{
+ type: 'trade_submitted',
+ summary: `Buy order submitted: ${amountSol} SOL → ${mint.slice(0, 8)}… on pump.fun`,
+ ts: Date.now(),
+ payload: { dex: 'pump', mint, amountSol },
+ }]);
+}
+
+async function executeJupTrade(caster, outputMint, amountSol, slippageBps) {
+ // SOL → output token on Jupiter. Input is native SOL (So11111...11112).
+ const SOL_MINT = 'So11111111111111111111111111111111111111112';
+ const url = `${DEX_URLS.jup}/${SOL_MINT}-${outputMint}`;
+
+ await caster.act('navigate', `Opening Jupiter swap: SOL → ${outputMint.slice(0, 8)}…`, async () => {
+ await caster.page.goto(url, { waitUntil: 'domcontentloaded' });
+ await caster.page.waitForTimeout(3000);
+ });
+
+ await caster.act('input', `Entering ${amountSol} SOL`, async () => {
+ const input = await caster.page.waitForSelector(JUP_SEL.inputAmount, { timeout: 10_000 });
+ await input.click({ clickCount: 3 });
+ await input.fill(String(amountSol));
+ await caster.page.waitForTimeout(1500); // let quote refresh
+ });
+
+ await caster.act('trade', `Initiating swap: ${amountSol} SOL → ${outputMint.slice(0, 8)}…`, async () => {
+ const btn = await caster.page.waitForSelector(JUP_SEL.swapBtn, { timeout: 10_000 });
+ await btn.click();
+ await caster.page.waitForTimeout(2000);
+
+ // Wallet confirmation dialog.
+ const confirm = await caster.page.$(JUP_SEL.confirmBtn);
+ if (confirm) await confirm.click();
+ await caster.page.waitForTimeout(4000);
+ });
+
+ await caster.pushActivity([{
+ type: 'trade_submitted',
+ summary: `Swap submitted: ${amountSol} SOL → ${outputMint.slice(0, 8)}… on Jupiter`,
+ ts: Date.now(),
+ payload: { dex: 'jup', outputMint, amountSol, slippageBps },
+ }]);
+}
+
+async function executeRaydiumTrade(caster, outputMint, amountSol, slippageBps) {
+ const SOL_MINT = 'So11111111111111111111111111111111111111112';
+ const url = `${DEX_URLS.raydium}?inputCurrency=${SOL_MINT}&outputCurrency=${outputMint}`;
+
+ await caster.act('navigate', `Opening Raydium swap: SOL → ${outputMint.slice(0, 8)}…`, async () => {
+ await caster.page.goto(url, { waitUntil: 'domcontentloaded' });
+ await caster.page.waitForTimeout(3000);
+ });
+
+ await caster.act('input', `Entering ${amountSol} SOL`, async () => {
+ const inputs = await caster.page.$$(RAYDIUM_SEL.inputAmount);
+ const input = inputs[0];
+ if (!input) throw new Error('Amount input not found on Raydium');
+ await input.click({ clickCount: 3 });
+ await input.fill(String(amountSol));
+ await caster.page.waitForTimeout(1500);
+ });
+
+ await caster.act('trade', `Initiating Raydium swap: ${amountSol} SOL → ${outputMint.slice(0, 8)}…`, async () => {
+ const btn = await caster.page.waitForSelector(RAYDIUM_SEL.swapBtn, { timeout: 10_000 });
+ await btn.click();
+ await caster.page.waitForTimeout(4000);
+ });
+
+ await caster.pushActivity([{
+ type: 'trade_submitted',
+ summary: `Swap submitted: ${amountSol} SOL → ${outputMint.slice(0, 8)}… on Raydium`,
+ ts: Date.now(),
+ payload: { dex: 'raydium', outputMint, amountSol, slippageBps },
+ }]);
+}
diff --git a/src/marketplace.js b/src/marketplace.js
index 7db66f324..a13830a78 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -4555,6 +4555,15 @@ function renderAvatarCard(a, spotlight = false) {
// Rare-pedigree badge — marks a bred agent by its lineage tier. Uncommon and up
// only, so the badge stays a genuine signal of scarcity (deep pedigree, emergent
// skills) rather than noise on every card. Links into the agent's lineage.
+function oracleBadgeHTML(oracle) {
+ if (!oracle || oracle.total < 3) return '';
+ const wr = oracle.win_rate;
+ if (wr == null) return '';
+ const isGood = wr >= 50;
+ const title = `Oracle: ${oracle.total} trades · ${oracle.wins} wins · ${wr.toFixed(1)}% win rate`;
+ return `<span class="oracle-badge${isGood ? '' : ' neutral'}" title="${escapeHtml(title)}">⚡ ${wr.toFixed(0)}% win rate</span>`;
+}
+
function pedigreeBadgeHTML(a) {
const g = a.genome;
if (!g || !g.bred || !g.pedigree_tier) return '';
@@ -4630,6 +4639,7 @@ function renderCard(a) {
${buyers > 0 ? `<span class="stat-pill" title="${buyers} confirmed purchase${buyers === 1 ? '' : 's'}${buyers24h ? `, ${buyers24h} in last 24h` : ''}">$ ${fmtNumber(buyers)}${buyers24h > 0 ? ` <em>(+${buyers24h}/24h)</em>` : ''}</span>` : ''}
${skillPriceBadge}
${!skillPriceBadge && paid ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}
+ ${oracleBadgeHTML(a.oracle)}
${walletChipHTML(a, { isOwner: false, showPending: false, link: true })}
</div>
<div class="footer">
@@ -7912,6 +7922,7 @@ function init() {
loadCategories();
loadList(true);
loadTheme();
+ loadOracleStats();
initPlugins();
fetchUserPurchases();
loadCurrentUser();
@@ -8521,6 +8532,35 @@ function showPluginUrlError(msg) {
// ── Plugin init / wiring ──────────────────────────────────────────────────────
+// ── Platform activity strip ────────────────────────────────────────────────
+
+async function loadOracleStats() {
+ const strip = $('market-activity-strip');
+ if (!strip) return;
+ try {
+ const r = await fetch('/api/oracle/stats', { headers: { accept: 'application/json' } });
+ if (!r.ok) return;
+ const d = await r.json();
+ if (!d) return;
+
+ const setKpi = (id, val) => {
+ const el = $(id);
+ if (!el) return;
+ el.textContent = val;
+ el.classList.remove('loading');
+ };
+
+ setKpi('mkt-stat-agents', fmtNumber(d.agents_armed ?? 0));
+ setKpi('mkt-stat-scored', fmtNumber(d.scored_24h ?? 0));
+ setKpi('mkt-stat-winrate', d.win_rate != null ? `${Number(d.win_rate).toFixed(0)}%` : '—');
+ setKpi('mkt-stat-actions', fmtNumber(d.open_actions ?? 0));
+ setKpi('mkt-stat-wins', fmtNumber(d.total_wins ?? 0));
+ strip.hidden = false;
+ } catch {
+ // non-fatal — strip stays hidden
+ }
+}
+
function initPlugins() {
// Add by URL button
const addBtn = $('plugin-add-url');
diff --git a/workers/agent-screen-worker/Dockerfile b/workers/agent-screen-worker/Dockerfile
new file mode 100644
index 000000000..10ecb7471
--- /dev/null
+++ b/workers/agent-screen-worker/Dockerfile
@@ -0,0 +1,27 @@
+# agent-screen-worker — long-lived browser capture worker.
+#
+# Build from the worker directory:
+#
+# docker build -t agent-screen-worker .
+# docker run --env-file .env agent-screen-worker
+#
+# For Browserbase cloud mode, omit the playwright install step and
+# set BROWSERBASE_API_KEY + BROWSERBASE_PROJECT_ID in your env.
+# The Playwright base image is only needed for LOCAL browser mode.
+
+FROM mcr.microsoft.com/playwright:v1.44.0-jammy
+
+WORKDIR /app
+
+COPY package.json ./
+RUN npm install --omit=dev
+
+COPY . .
+
+# Pre-install Chromium for LOCAL browser mode.
+# If you only use Browserbase, this layer can be skipped by building with
+# --build-arg SKIP_BROWSERS=1 and adjusting the RUN command below.
+ARG SKIP_BROWSERS=0
+RUN if [ "$SKIP_BROWSERS" = "0" ]; then npx playwright install chromium --with-deps; fi
+
+CMD ["node", "index.js"]
diff --git a/workers/agent-screen-worker/README.md b/workers/agent-screen-worker/README.md
new file mode 100644
index 000000000..3fbdfa0d0
--- /dev/null
+++ b/workers/agent-screen-worker/README.md
@@ -0,0 +1,78 @@
+# agent-screen-worker
+
+Long-lived Node.js worker that drives a real browser via [Stagehand](https://github.com/browserbasehq/stagehand), captures screenshots on every meaningful state change, and pushes frames to the three.ws live agent screen stream.
+
+## Architecture
+
+```
+index.js boot Stagehand, wire graceful shutdown, start task loop
+config.js env loading + validation
+capture.js screenshot + push-to-API with per-interval throttling
+task-runner.js autonomous task the agent performs (pump.fun scan by default)
+```
+
+Frames land at `/api/agent-screen-push` → Redis TTL key → SSE stream at `/api/agent-screen-stream` → rendered by `/agent-screen?agentId=<uuid>` and the 3D desk in `/play`.
+
+## Quick start
+
+### Local Playwright (development)
+
+```bash
+cd workers/agent-screen-worker
+npm install
+export AGENT_ID=<uuid-from-db>
+export AGENT_JWT=<bearer-token>
+npm start
+```
+
+Open `https://three.ws/agent-screen?agentId=<uuid>` — frames appear within seconds.
+
+### Docker (self-hosted)
+
+```bash
+docker build -t agent-screen-worker .
+docker run --env-file .env agent-screen-worker
+```
+
+### Browserbase cloud (production, zero-infra)
+
+No Docker needed. Run as a plain Node process or in any VM:
+
+```bash
+export BROWSERBASE_API_KEY=...
+export BROWSERBASE_PROJECT_ID=...
+export AGENT_ID=...
+export AGENT_JWT=...
+npm start
+```
+
+## Environment variables
+
+| Variable | Required | Default | Description |
+|---|---|---|---|
+| `AGENT_ID` | yes | — | UUID of the agent that owns this screen stream |
+| `AGENT_JWT` | yes | — | Bearer token for that agent |
+| `PUSH_URL` | no | `https://three.ws/api/agent-screen-push` | Push endpoint override |
+| `BROWSERBASE_API_KEY` | no | — | Browserbase API key (cloud mode) |
+| `BROWSERBASE_PROJECT_ID` | no | — | Required when `BROWSERBASE_API_KEY` is set |
+| `CYCLE_MS` | no | `30000` | Task loop cycle time in ms |
+| `SCREENSHOT_INTERVAL_MS` | no | `5000` | Minimum ms between full screenshots (text-only pushes fill the gap) |
+
+## Customising the task
+
+Edit `task-runner.js`. The default task scans pump.fun for trending tokens and narrates findings. Replace or extend `runTask()` for your agent's actual mission.
+
+The `push()` helper accepts `type` values that control how the dashboard styles the entry:
+
+| type | meaning |
+|---|---|
+| `screenshot` | Full frame — triggers a screenshot if interval has elapsed |
+| `activity` | Text-only log entry |
+| `trade` | Trade-related event (styled differently in the log) |
+| `analysis` | Research / analysis step |
+
+## Dockerfile build args
+
+| Arg | Default | Description |
+|---|---|---|
+| `SKIP_BROWSERS` | `0` | Set to `1` to skip `playwright install` (Browserbase-only deployments) |
diff --git a/workers/agent-screen-worker/capture.js b/workers/agent-screen-worker/capture.js
new file mode 100644
index 000000000..d721a850c
--- /dev/null
+++ b/workers/agent-screen-worker/capture.js
@@ -0,0 +1,65 @@
+import fetch from 'node-fetch';
+
+let lastScreenshotAt = 0;
+
+/**
+ * Push a frame (screenshot + activity text) to /api/agent-screen-push.
+ *
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {import('playwright').Page|null} opts.page — null for text-only pushes
+ * @param {string} opts.activity — human-readable narration
+ * @param {string} [opts.type] — screenshot | activity | trade | analysis
+ * @param {string} opts.pushUrl
+ * @param {string} opts.agentJwt
+ * @param {number} [opts.screenshotIntervalMs] — min ms between full screenshots
+ */
+export async function pushFrame({
+ agentId,
+ page,
+ activity,
+ type = 'screenshot',
+ pushUrl,
+ agentJwt,
+ screenshotIntervalMs = 5_000,
+}) {
+ let data = null;
+ const now = Date.now();
+ const wantScreenshot = type !== 'activity' && page !== null;
+ const screenshotDue = now - lastScreenshotAt >= screenshotIntervalMs;
+
+ if (wantScreenshot && screenshotDue) {
+ try {
+ const buf = await page.screenshot({ type: 'png', fullPage: false });
+ data = 'data:image/png;base64,' + buf.toString('base64');
+ lastScreenshotAt = now;
+ } catch (err) {
+ console.warn('[capture] screenshot failed:', err.message);
+ type = 'activity';
+ }
+ } else if (wantScreenshot && !screenshotDue) {
+ // Throttled — send as activity-only so the log still updates
+ type = 'activity';
+ }
+
+ const body = { agentId, frame: { data, activity, type } };
+
+ try {
+ const res = await fetch(pushUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${agentJwt}`,
+ },
+ body: JSON.stringify(body),
+ // 10 s timeout — worker should not stall on a slow push
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ console.warn(`[capture] push failed ${res.status}: ${text.slice(0, 120)}`);
+ }
+ } catch (err) {
+ console.warn('[capture] push error:', err.message);
+ }
+}
diff --git a/workers/agent-screen-worker/config.js b/workers/agent-screen-worker/config.js
new file mode 100644
index 000000000..181183e90
--- /dev/null
+++ b/workers/agent-screen-worker/config.js
@@ -0,0 +1,24 @@
+export function loadConfig() {
+ const required = ['AGENT_ID', 'AGENT_JWT'];
+ for (const k of required) {
+ if (!process.env[k]) throw new Error(`Missing required env var: ${k}`);
+ }
+
+ const BROWSERBASE_API_KEY = process.env.BROWSERBASE_API_KEY || '';
+ const BROWSERBASE_PROJECT_ID = process.env.BROWSERBASE_PROJECT_ID || '';
+
+ if (BROWSERBASE_API_KEY && !BROWSERBASE_PROJECT_ID) {
+ throw new Error('BROWSERBASE_PROJECT_ID is required when BROWSERBASE_API_KEY is set');
+ }
+
+ return {
+ AGENT_ID: process.env.AGENT_ID,
+ AGENT_JWT: process.env.AGENT_JWT,
+ PUSH_URL: process.env.PUSH_URL || 'https://three.ws/api/agent-screen-push',
+ BROWSERBASE_API_KEY,
+ BROWSERBASE_PROJECT_ID,
+ CYCLE_MS: Number(process.env.CYCLE_MS || 30_000),
+ // Whether to capture a screenshot on every pushFrame call (can be throttled)
+ SCREENSHOT_INTERVAL_MS: Number(process.env.SCREENSHOT_INTERVAL_MS || 5_000),
+ };
+}
diff --git a/workers/agent-screen-worker/index.js b/workers/agent-screen-worker/index.js
new file mode 100644
index 000000000..bc715857a
--- /dev/null
+++ b/workers/agent-screen-worker/index.js
@@ -0,0 +1,57 @@
+import { Stagehand } from '@browserbasehq/stagehand';
+import { loadConfig } from './config.js';
+import { pushFrame } from './capture.js';
+import { runTask } from './task-runner.js';
+
+const cfg = loadConfig();
+
+// Bind push() with the shared config so callers don't repeat it
+function push({ agentId, page, activity, type }) {
+ return pushFrame({
+ agentId,
+ page,
+ activity,
+ type,
+ pushUrl: cfg.PUSH_URL,
+ agentJwt: cfg.AGENT_JWT,
+ screenshotIntervalMs: cfg.SCREENSHOT_INTERVAL_MS,
+ });
+}
+
+async function main() {
+ console.log(`[agent-screen-worker] starting — agent ${cfg.AGENT_ID}`);
+
+ const env = cfg.BROWSERBASE_API_KEY ? 'BROWSERBASE' : 'LOCAL';
+ console.log(`[agent-screen-worker] browser env: ${env}`);
+
+ const stagehand = new Stagehand({
+ env,
+ apiKey: cfg.BROWSERBASE_API_KEY || undefined,
+ projectId: cfg.BROWSERBASE_PROJECT_ID || undefined,
+ verbose: 1,
+ });
+
+ await stagehand.init();
+ const { page, context } = stagehand;
+
+ // Signal the stream is alive immediately
+ await push({ agentId: cfg.AGENT_ID, page, activity: 'Agent starting up…', type: 'activity' });
+
+ // Graceful shutdown
+ const shutdown = async (signal) => {
+ console.log(`[agent-screen-worker] ${signal} — shutting down`);
+ await push({ agentId: cfg.AGENT_ID, page, activity: 'Agent shutting down', type: 'activity' }).catch(() => {});
+ await stagehand.close().catch(() => {});
+ process.exit(0);
+ };
+ process.once('SIGINT', () => shutdown('SIGINT'));
+ process.once('SIGTERM', () => shutdown('SIGTERM'));
+
+ // Stagehand v3: act/extract live on page; pass page directly
+ await runTask({ page, context, cfg, push });
+}
+
+main().catch((err) => {
+ console.error('[agent-screen-worker] fatal:', err);
+ process.exit(1);
+});
diff --git a/workers/agent-screen-worker/package.json b/workers/agent-screen-worker/package.json
new file mode 100644
index 000000000..e4fe28e18
--- /dev/null
+++ b/workers/agent-screen-worker/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@three-ws/agent-screen-worker",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "description": "Browser capture worker — drives Stagehand, screenshots the agent's live view, pushes frames to /api/agent-screen-push.",
+ "main": "index.js",
+ "scripts": {
+ "start": "node index.js",
+ "start:local": "BROWSERBASE_API_KEY= node index.js",
+ "start:bb": "node index.js"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "dependencies": {
+ "@browserbasehq/stagehand": "^3.6.0",
+ "node-fetch": "^3",
+ "zod": "^3"
+ }
+}
diff --git a/workers/agent-screen-worker/task-runner.js b/workers/agent-screen-worker/task-runner.js
new file mode 100644
index 000000000..ff7ccbdf4
--- /dev/null
+++ b/workers/agent-screen-worker/task-runner.js
@@ -0,0 +1,115 @@
+/**
+ * Default autonomous task: scan pump.fun for trending tokens, narrate findings.
+ *
+ * Swap this out (or extend it) for the agent's actual mission. The contract
+ * is simple: receive { stagehand, page, cfg, push } and run a loop forever.
+ * Call push() for every meaningful action so the screen stream stays live.
+ *
+ * Stagehand v3 API: page.act() and page.extract() (not stagehand.act/extract).
+ */
+import { z } from 'zod';
+
+const PUMP_FUN_URL = 'https://pump.fun';
+
+const TokenListSchema = z.object({
+ tokens: z.array(
+ z.object({
+ name: z.string(),
+ symbol: z.string().optional(),
+ marketCap: z.string().optional(),
+ })
+ ),
+});
+
+const TokenDetailSchema = z.object({
+ price: z.string().optional(),
+ holders: z.string().optional(),
+ volume: z.string().optional(),
+});
+
+export async function runTask({ page, cfg, push }) {
+ const { agentId, CYCLE_MS } = cfg;
+
+ while (true) {
+ try {
+ // ── Navigate ────────────────────────────────────────────────────────
+ await push({ agentId, page, activity: 'Navigating to pump.fun…', type: 'activity' });
+ await page.goto(PUMP_FUN_URL, { waitUntil: 'domcontentloaded', timeout: 30_000 });
+ await push({ agentId, page, activity: 'Scanning pump.fun for trending tokens', type: 'screenshot' });
+
+ // ── Extract trending tokens ─────────────────────────────────────────
+ let trending = { tokens: [] };
+ try {
+ trending = await page.extract({
+ instruction: 'Extract the top 5 trending token names, symbols, and market caps visible on this page',
+ schema: TokenListSchema,
+ });
+ } catch (err) {
+ console.warn('[task] extract failed:', err.message);
+ }
+
+ const count = trending.tokens?.length ?? 0;
+ await push({
+ agentId,
+ page,
+ activity:
+ count > 0
+ ? `Found ${count} trending token${count !== 1 ? 's' : ''}: ${trending.tokens
+ .slice(0, 3)
+ .map((t) => (t.symbol ? `$${t.symbol}` : t.name))
+ .join(', ')}`
+ : 'No trending tokens extracted — page may still be loading',
+ type: 'analysis',
+ });
+
+ // ── Evaluate top pick ───────────────────────────────────────────────
+ if (trending.tokens.length > 0) {
+ const pick = trending.tokens[0];
+ const label = pick.symbol ? `$${pick.symbol}` : pick.name;
+ await push({
+ agentId,
+ page,
+ activity: `Evaluating ${label} — market cap ${pick.marketCap || 'unknown'}`,
+ type: 'analysis',
+ });
+
+ try {
+ await page.act({ action: `Click on the token named "${pick.name}"` });
+ await push({ agentId, page, activity: `Opened ${label} detail page`, type: 'screenshot' });
+
+ const detail = await page.extract({
+ instruction: 'Extract price, holder count, and recent transaction volume if visible',
+ schema: TokenDetailSchema,
+ });
+
+ const parts = [];
+ if (detail.price) parts.push(`price ${detail.price}`);
+ if (detail.holders) parts.push(`${detail.holders} holders`);
+ if (detail.volume) parts.push(`vol ${detail.volume}`);
+ if (parts.length) {
+ await push({ agentId, page, activity: `${label}: ${parts.join(' · ')}`, type: 'trade' });
+ }
+ } catch {
+ await push({ agentId, page, activity: `Could not open ${label} detail page`, type: 'activity' });
+ }
+ }
+
+ // ── Sleep ───────────────────────────────────────────────────────────
+ await push({
+ agentId,
+ page,
+ activity: `Cycle complete — next scan in ${CYCLE_MS / 1000}s`,
+ type: 'activity',
+ });
+ await sleep(CYCLE_MS);
+ } catch (err) {
+ console.error('[task] cycle error:', err);
+ await push({ agentId, page: null, activity: `Error: ${err.message}`, type: 'activity' });
+ await sleep(5_000);
+ }
+ }
+}
+
+function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index 23b601106..ec5025237 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -21,6 +21,7 @@ import {
import { buildAmmSellInstructions } from './amm-exit.js';
import { assessTradeSafety, recordFirewallDecision } from '../../api/_lib/trade-firewall.js';
import { recordDecision } from '../../api/_lib/reasoning-ledger.js';
+import { screenPush } from './screen-push.js';
// Self-rated conviction for a snipe entry, 0..1. Lower price impact and a clean
// firewall verdict raise it; a warned verdict and heavy impact lower it. This is
@@ -331,6 +332,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
WHERE id = ${posId}
`;
log.warn('buy blocked by firewall', { ...tag, score: assessment.score, reasons: assessment.reasons });
+ screenPush(`$${(mint.symbol || mint.mint.slice(0, 6)).toUpperCase()} blocked by firewall: ${reason}`, 'analysis');
return { status: 'failed', reason: 'firewall_block' };
}
if (assessment.verdict !== 'allow') {
@@ -351,6 +353,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
// Execution telemetry — only set on a live broadcast; simulate keeps nulls
// (except a 'simulated' route marker so the UI can label paper fills).
let exec = { route: 'simulated', tipLamports: 0, priorityFeeMicroLamports: null, landedMs: null };
+ screenPush(`Buying $${(mint.symbol || mint.mint.slice(0, 6)).toUpperCase()} — sending tx`, 'trade');
if (cfg.mode === 'live') {
const tipMode = ['economy', 'turbo'].includes(strat.mev_tip_mode) ? strat.mev_tip_mode : 'off';
// The tip guard needs to know what's already committed today + this trade.
@@ -391,6 +394,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
WHERE id = ${posId}
`;
log.trade('buy', { ...tag, mode: cfg.mode, sig, sol: lamportsToSol(perTrade), base: baseAmount.toString(), impact: Number(quote.priceImpactPct).toFixed(2) });
+ screenPush(`Bought $${(mint.symbol || mint.mint.slice(0, 6)).toUpperCase()} at ${lamportsToSol(perTrade).toFixed(4)} SOL — position open`, 'trade');
notifyBuy({ agentName: strat.agent_name || strat.agent_id, symbol: mint.symbol, mint: mint.mint, solSpent: lamportsToSol(perTrade), mode: cfg.mode, sig, chatId: strat.telegram_chat_id || null });
await recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint, capabilityId: spendCapabilityId });
await recordSnipeDecision({
@@ -412,6 +416,7 @@ export async function executeSell({ cfg, position, reason }) {
return withAgentLock(position.agent_id, async () => {
const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol, reason };
await sql`UPDATE agent_sniper_positions SET status = 'closing' WHERE id = ${position.id} AND status = 'open'`;
+ screenPush(`Selling $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()}: ${reason}`, 'trade');
try {
const loaded = await loadAgentKeypair(position.agent_id, position.user_id, 'sniper_sell');
@@ -470,8 +475,10 @@ export async function executeSell({ cfg, position, reason }) {
closed_at = now()
WHERE id = ${position.id}
`;
- log.trade('sell', { ...tag, venue, mode: cfg.mode, sig, pnl_sol: lamportsToSol(pnl), pnl_pct: pnlPct.toFixed(1) });
- notifySell({ agentName: position.agent_name || position.agent_id, symbol: position.symbol, mint: position.mint, pnlSol: lamportsToSol(pnl), pnlPct, exitReason: reason, mode: cfg.mode, sig, chatId: position.telegram_chat_id || null });
+ const pnlSol = lamportsToSol(pnl);
+ log.trade('sell', { ...tag, venue, mode: cfg.mode, sig, pnl_sol: pnlSol, pnl_pct: pnlPct.toFixed(1) });
+ screenPush(`Sold $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()} — ${pnlPct >= 0 ? 'profit' : 'loss'}: ${pnlSol >= 0 ? '+' : ''}${pnlSol.toFixed(4)} SOL`, 'trade');
+ notifySell({ agentName: position.agent_name || position.agent_id, symbol: position.symbol, mint: position.mint, pnlSol, pnlPct, exitReason: reason, mode: cfg.mode, sig, chatId: position.telegram_chat_id || null });
return { status: 'closed', sig, pnl: pnl.toString(), venue };
} catch (err) {
// A failed sell must NOT terminate the position — leave it 'open' so the
@@ -482,6 +489,7 @@ export async function executeSell({ cfg, position, reason }) {
const errState = wasGraduated ? `graduated:amm_exit_retry:${errCode(err)}` : errCode(err);
await sql`UPDATE agent_sniper_positions SET status = 'open', error = ${errState}, last_quoted_at = now() WHERE id = ${position.id}`;
log.warn('sell failed (will retry)', { ...tag, code: errCode(err), graduated: wasGraduated, err: err?.message });
+ screenPush(`Error: sell $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()} failed (${errCode(err)}) — retrying`, 'activity');
return { status: 'retry', reason: errCode(err) };
}
});
diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.js
index 8d8dd814e..4edaf4560 100644
--- a/workers/agent-sniper/index.js
+++ b/workers/agent-sniper/index.js
@@ -31,6 +31,7 @@ import {
alertBoot,
alertShutdown,
} from './alerts.js';
+import { screenPush } from './screen-push.js';
const BOOT_AT = new Date().toISOString();
@@ -77,6 +78,7 @@ async function main() {
const cfg = loadConfig();
log.info('boot', { network: cfg.network, mode: cfg.mode, globalKill: cfg.globalKill, pollMs: cfg.pollMs });
if (cfg.announceLifecycle) alertBoot({ network: cfg.network, mode: cfg.mode, globalKill: cfg.globalKill });
+ screenPush(`Sniper online — ${cfg.network} / ${cfg.mode} mode`, 'activity');
const throttle = makeThrottle(cfg.maxGlobalBuysPerMin);
const errors = makeErrorTracker({ threshold: cfg.errorAlertThreshold, windowMs: cfg.errorAlertWindowMs });
@@ -100,17 +102,24 @@ async function main() {
lastEventAt = Date.now();
feedConnected = true; // an event is proof the subscription is live
if (kind !== 'mint' || draining || cfg.globalKill) return;
+ const sym = (data.symbol || data.mint.slice(0, 6)).toUpperCase();
+ screenPush(`New token: $${sym} — scoring`, 'analysis');
const strategies = cachedStrategies();
for (const strat of strategies) {
// The new-mint feed only drives new_mint strategies; first_claim
// strategies are driven by the on-chain claim poll loop below.
if ((strat.trigger || 'new_mint') !== 'new_mint') continue;
- const { pass, reasons } = scoreMint(data, strat);
+ const { pass, score, reasons } = scoreMint(data, strat);
if (!pass) continue;
- log.info('candidate', { agent: strat.agent_id, mint: data.mint, symbol: data.symbol, reasons });
+ log.info('candidate', { agent: strat.agent_id, mint: data.mint, symbol: data.symbol, score, reasons });
+ screenPush(`$${sym} scored ${score} — BUYING`, 'trade');
queue.push(async () => {
const og = await oracleGate(data.mint, cfg.network, strat);
- if (!og.pass) { log.info('oracle gate skip', { agent: strat.agent_id, mint: data.mint, reason: og.reason }); return; }
+ if (!og.pass) {
+ log.info('oracle gate skip', { agent: strat.agent_id, mint: data.mint, reason: og.reason });
+ screenPush(`$${sym} oracle blocked: ${og.reason}`, 'analysis');
+ return;
+ }
if (og.skipped) log.info('oracle unscored — proceeding', { agent: strat.agent_id, mint: data.mint });
await executeBuy({ cfg, strat, mint: data, throttle });
});
@@ -151,6 +160,7 @@ async function main() {
const { pass, score, reasons } = scoreIntel(rec, strat, weights);
if (!pass) return;
log.info('intel candidate', { agent: strat.agent_id, mint: rec.mint, symbol: rec.symbol, score, reasons });
+ screenPush(`$${(rec.symbol || rec.mint.slice(0, 6)).toUpperCase()} intel score ${score} — BUYING`, 'trade');
queue.push(async () => {
const og = await oracleGate(rec.mint, cfg.network, strat);
if (!og.pass) { log.info('oracle gate skip', { agent: strat.agent_id, mint: rec.mint, reason: og.reason }); return; }
@@ -247,6 +257,7 @@ async function main() {
reconnectCount++;
log.warn('feed silent — re-subscribing', { silentMs, reconnects: reconnectCount });
alertFeedSilent({ silentMs, network: cfg.network, mode: cfg.mode });
+ screenPush(`Feed silent ${Math.round(silentMs / 1000)}s — reconnecting`, 'activity');
try { stopFeed?.(); } catch {}
lastEventAt = Date.now();
const a2 = new AbortController();
@@ -307,6 +318,7 @@ async function main() {
process.on('unhandledRejection', (err) => {
log.error('unhandledRejection', { err: err?.message });
noteError('unhandledRejection', err?.message);
+ screenPush(`Error: ${err?.message || 'unhandled rejection'}`, 'activity');
});
}
diff --git a/workers/agent-sniper/package.json b/workers/agent-sniper/package.json
index 280de68a8..c86c85799 100644
--- a/workers/agent-sniper/package.json
+++ b/workers/agent-sniper/package.json
@@ -12,5 +12,8 @@
},
"engines": {
"node": ">=22"
+ },
+ "optionalDependencies": {
+ "canvas": "^2.11.2"
}
}
diff --git a/workers/agent-sniper/positions.js b/workers/agent-sniper/positions.js
index cd56da132..e2d1619a2 100644
--- a/workers/agent-sniper/positions.js
+++ b/workers/agent-sniper/positions.js
@@ -12,6 +12,7 @@ import { getOpenPositions } from './strategy-store.js';
import { executeSell } from './executor.js';
import { quoteAmmSell } from './amm-exit.js';
import { decideExit } from './exit-logic.js';
+import { screenPush } from './screen-push.js';
async function tickPosition(cfg, pos) {
// Kill-switch flipped while holding → exit at market now.
@@ -37,6 +38,11 @@ async function tickPosition(cfg, pos) {
WHERE id = ${pos.id}
`;
+ const entry = Number(pos.entry_quote_lamports || 0);
+ const pnlPct = entry > 0 ? ((value - entry) / entry) * 100 : 0;
+ const sym = (pos.symbol || pos.mint.slice(0, 6)).toUpperCase();
+ screenPush(`$${sym}: ${pnlPct >= 0 ? '+' : ''}${pnlPct.toFixed(1)}% P&L — monitoring`, 'trade');
+
const reason = decideExit(pos, value, peak);
if (reason) await executeSell({ cfg, position: pos, reason });
}
diff --git a/workers/agent-sniper/screen-push.js b/workers/agent-sniper/screen-push.js
new file mode 100644
index 000000000..f0f3c68bd
--- /dev/null
+++ b/workers/agent-sniper/screen-push.js
@@ -0,0 +1,74 @@
+// screen-push.js — fire-and-forget push to the agent screen stream.
+// All pushes are non-blocking: failures are swallowed so they never
+// interrupt trading. Import this in index.js and call screenPush()
+// alongside existing log() calls.
+
+import fetch from 'node-fetch';
+
+const PUSH_URL = process.env.PUSH_URL || 'https://three.ws/api/agent-screen-push';
+const AGENT_JWT = process.env.AGENT_JWT;
+const AGENT_ID = process.env.AGENT_ID;
+
+const CW = 1280, CH = 720;
+const activityLog = [];
+
+// Try to load node-canvas for rendered terminal frames. Falls back to
+// text-only pushes silently if the package isn't installed.
+let canvasCreate = false;
+(async () => {
+ try {
+ const mod = await import('canvas');
+ canvasCreate = mod.createCanvas;
+ } catch {}
+})();
+
+function renderTerminalFrame(newLine) {
+ if (!canvasCreate) return null;
+ activityLog.push(newLine);
+ if (activityLog.length > 18) activityLog.shift();
+
+ const canvas = canvasCreate(CW, CH);
+ const ctx = canvas.getContext('2d');
+
+ // Background
+ ctx.fillStyle = '#06080f';
+ ctx.fillRect(0, 0, CW, CH);
+
+ // Header bar
+ ctx.fillStyle = '#0d1117';
+ ctx.fillRect(0, 0, CW, 48);
+ ctx.fillStyle = 'rgba(255,255,255,0.4)';
+ ctx.font = '14px monospace';
+ ctx.fillText('▶ agent-sniper', 16, 30);
+ ctx.fillText(new Date().toISOString().slice(0, 19) + 'Z', CW - 220, 30);
+
+ // Terminal lines
+ ctx.font = '24px monospace';
+ activityLog.forEach((line, i) => {
+ const age = activityLog.length - 1 - i;
+ if (age === 0) {
+ ctx.fillStyle = '#fff';
+ } else if (age < 3) {
+ ctx.fillStyle = 'rgba(255,255,255,0.75)';
+ } else if (age < 7) {
+ ctx.fillStyle = 'rgba(255,255,255,0.45)';
+ } else {
+ ctx.fillStyle = 'rgba(255,255,255,0.2)';
+ }
+ ctx.fillText(line.slice(0, 90), 24, 72 + i * 36);
+ });
+
+ return 'data:image/png;base64,' + canvas.toBuffer('image/png').toString('base64');
+}
+
+export function screenPush(activity, type = 'activity') {
+ if (!AGENT_JWT || !AGENT_ID) return;
+ const label = `[${type.toUpperCase()}] ${activity}`;
+ const data = renderTerminalFrame(label);
+ const frame = data ? { data, activity, type } : { activity, type };
+ fetch(PUSH_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${AGENT_JWT}` },
+ body: JSON.stringify({ agentId: AGENT_ID, frame }),
+ }).catch(() => {});
+}