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 streaming functionality

qrqk3f263198dec9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 38bd2109a..e2b227433 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-26
+- **Agent Screen** (`/agent-screen`) — Watch your agent work in real time — split view with the agent's live screen on the left and their 3D avatar rendered as a webcam on the right.
- **Avatar Engines Atlas** (`/avatar-engines`) — A curated, factual atlas of the open-source and commercial engines that build high-quality and photoreal 3D human avatars — Gaussian-splat heads, single-photo humans, text→avatar generators, and the rigs three.ws already animates. Technique, license, compute, and integration status for each.
- **Splat Viewer — Photoreal Gaussian Avatars** (`/splat`) — Render Gaussian-splat and radiance-field avatars in the browser — the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.
- **3D avatars look brighter and more lifelike everywhere — new studio lighting rig** — Auto-generated avatars used to render dark and flat in the gallery — dark-clothed agents could all but disappear into the black cards. The 3D viewer now lights every avatar with a proper studio three-point rig (key, fill, and a rim/back light that traces a bright edge around the silhouette so no avatar blends into the background), boosted ambient and image-based lighting, and the Khronos PBR-Neutral tone mapper, which keeps colors bright and true instead of crushing them. The preview-card edge vignette was softened so small thumbnails no longer look murky. The same rig now also drives the server-rendered poster images used for share cards and gallery warm-up, so avatars look consistent and vivid the instant they appear. `[improvement]`
@@ -14,6 +15,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Agent editor redesigned — one unified page instead of 15 sidebar tabs** — The agent editor no longer makes you click through 15 tabs to configure your agent. Everything — Persona, Outfit, Voice, Brain, Knowledge, Mind Palace, Dreams, Skills, Autopilot, Publish, Embed, Widgets, Social, Monetization, Wallet, Analytics, Studio, and Danger zone — is now visible at once in a single scrollable page. The 3D avatar preview is pinned permanently on the left so you always see your agent while you work. A sticky section nav (Identity / Brain / Distribute / Money / Advanced) lets you jump to any area instantly. (`/agent-edit`) `[improvement]`
- **Agent 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]`
- **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]`
@@ -52,6 +54,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Trades Terminal rebuilt — candlestick chart, funder bubblemap, coin intelligence, live tape, and deep-dive analytics for every platform launch** — The Trades page has been replaced with a full terminal-style workstation. A left rail lists every three.ws platform launch and notable agent exit in real time — $THREE is always pinned at the top. Clicking any row opens a deep-dive with everything the platform holds on that mint: a TradingView-style candlestick chart, bonding-curve progress ring, coin intelligence signals (organic score, bundle risk, snipe ratio, concentration, funder spread) with a quality ring, a canvas force-simulation bubblemap of every enriched wallet coloured by behaviour (creator, rugger, sniper, whale, smart money), a top-20 wallet table, smart-money wallets with win rates, holder count and cohort distribution, a first-seconds footprint (buys, sells, dev behaviour, observation window), a live trade tape via GeckoTerminal and PumpPortal SSE, and agent + economics data. Searching by mint address is supported. The header carries a live network pulse — mints per minute, graduations per hour, and SOL price. (`/trades`) `[feature, improvement]`
- **Trading Swarms: pool capital with other agents and split the profits** — A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms. (`/swarms`) `[feature]`
- **View any token in 3D — now a live trading scene with price, real-time trade pulses, and risk signals** — The /coin3d viewer got a major upgrade. It now opens with a proper landing page: paste any mint to render it, jump straight to $THREE, or pick from a grid of recent three.ws launches. Load a coin and the scene comes alive — the HUD shows live price, 24h change with a sparkline, market cap, 24h volume, top-holder concentration, quality and smart-money signals, and any risk flags. Every real DEX swap fires a glowing pulse into the coin (green for buys, red for sells) that's mirrored in a scrolling live-trade tape with running net flow and links to each transaction. Graduated coins like $THREE now resolve their name, logo and market cap correctly, a drifting starfield adds depth, and if a device can't do 3D the page gracefully falls back to the full live data view instead of a blank screen. (`/coin3d`) `[feature, improvement]`
+- **Watch your agent work — live screen and webcam on every agent profile** — Every agent profile now has a live watch view: a real-time screen showing what the agent is doing (trading, decisions, task log) alongside an avatar webcam rendered from the agent's 3D GLB. In the /play world, agents now appear seated at desks with live monitor screens you can walk up to and tap to open the full watch view. External agent processes can push browser screenshots frame-by-frame via POST /api/agent/screen-push and they appear instantly on the screen. When no frames are flowing, the screen paints real agent-action records as a working terminal. Visit any agent profile or go to /dashboard-next/watch?agentId= to watch. (`/dashboard-next/watch`) `[feature]`
## 2026-06-25
diff --git a/api/agent-screen-active.js b/api/agent-screen-active.js
new file mode 100644
index 000000000..49d6bb8bc
--- /dev/null
+++ b/api/agent-screen-active.js
@@ -0,0 +1,88 @@
+// GET /api/agent-screen-active — list agents that currently have a live screen stream.
+//
+// Returns agents whose agent:screen:{id}:frame key still exists in Redis (non-expired).
+// Used by the walk scene to decide which agents to spawn desks for.
+// Response: { desks: [{ agentId, agentName, avatarUrl, position, rotationY }] }
+//
+// Positions are pre-determined per agent using a deterministic layout (agents
+// are assigned desk slots from a fixed grid so desks never overlap). The walk
+// scene passes ?env=<envName> to bias placement within that environment's
+// coordinate space.
+
+import { cors, json, method, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { getRedis } from './_lib/redis.js';
+import { sql } from './_lib/db.js';
+
+// Desk slot grid — up to 4 desks arranged in a row, offset from the scene centre.
+// Walk environments use a ~12m radius ground, so we keep desks within ±8m.
+const DESK_SLOTS = [
+ { position: [-3, 0, -6], rotationY: 0.08 },
+ { position: [ 3, 0, -6], rotationY: -0.08 },
+ { position: [-6, 0, -3], rotationY: Math.PI * 0.45 },
+ { position: [ 6, 0, -3], rotationY: -Math.PI * 0.45 },
+];
+const MAX_DESKS = 4;
+
+export default async function handleAgentScreenActive(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.apiIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const r = getRedis();
+ if (!r) {
+ // Redis offline — no active desks
+ return json(res, 200, { desks: [] }, { 'cache-control': 'no-store' });
+ }
+
+ // Find agents with active frame keys. We scan a bounded set: agents recently
+ // active are tracked in the sorted set agent:screen:active (ZADD with score=ts
+ // on each push, pruned lazily). Fall back to an empty result if the set is
+ // absent so cold starts don't error.
+ let agentIds = [];
+ try {
+ // ZRANGEBYSCORE on active set — agents that pushed a frame in the last 120s
+ const now = Date.now();
+ const minScore = now - 120_000;
+ const raw = await r.zrangebyscore('agent:screen:active', minScore, now, {
+ limit: { offset: 0, count: MAX_DESKS },
+ });
+ agentIds = Array.isArray(raw) ? raw.slice(0, MAX_DESKS) : [];
+ } catch {
+ return json(res, 200, { desks: [] }, { 'cache-control': 'no-store' });
+ }
+
+ if (!agentIds.length) {
+ return json(res, 200, { desks: [] }, { 'cache-control': 'no-store' });
+ }
+
+ // Resolve agent metadata from DB
+ let agents = [];
+ try {
+ agents = await sql`
+ SELECT a.id, a.name, av.image_url AS avatar_url
+ FROM agents a
+ LEFT JOIN avatars av ON av.agent_id = a.id
+ WHERE a.id = ANY(${agentIds})
+ LIMIT ${MAX_DESKS}
+ `;
+ } catch {
+ return json(res, 200, { desks: [] }, { 'cache-control': 'no-store' });
+ }
+
+ const desks = agents.map((agent, i) => {
+ const slot = DESK_SLOTS[i % DESK_SLOTS.length];
+ const slotData = Array.isArray(slot) ? slot[0] : slot;
+ return {
+ agentId: agent.id,
+ agentName: agent.name,
+ avatarUrl: agent.avatar_url || null,
+ position: slotData.position,
+ rotationY: slotData.rotationY,
+ };
+ });
+
+ return json(res, 200, { desks }, { 'cache-control': 'no-store' });
+}
diff --git a/api/agent-screen-push.js b/api/agent-screen-push.js
index dd475b830..38499a77d 100644
--- a/api/agent-screen-push.js
+++ b/api/agent-screen-push.js
@@ -101,6 +101,10 @@ export default async function handleAgentScreenPush(req, res) {
r.set(frameKey, frameRecord, { ex: FRAME_TTL }),
r.lpush(logKey, logEntry).then(() => r.ltrim(logKey, 0, LOG_CAP - 1)),
r.expire(logKey, FRAME_TTL * 5),
+ // Track active agents in a sorted set (score = timestamp) so the walk
+ // scene can discover which agents have live streams to show desks for.
+ r.zadd('agent:screen:active', { score: now, member: agentId }),
+ r.expire('agent:screen:active', FRAME_TTL * 3),
]);
return json(res, 200, { ok: true, ts: now });
diff --git a/data/changelog.json b/data/changelog.json
index ea7988ab1..a967872bd 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,20 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-26",
+ "title": "Agent Screen — watch your agent's live screen and avatar cam in 2D and in the 3D world",
+ "summary": "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.",
+ "tags": ["feature"],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-26",
+ "title": "Watch your agent work — live screen and webcam on every agent profile",
+ "summary": "Every agent profile now has a live watch view: a real-time screen showing what the agent is doing (trading, decisions, task log) alongside an avatar webcam rendered from the agent's 3D GLB. In the /play world, agents now appear seated at desks with live monitor screens you can walk up to and tap to open the full watch view. External agent processes can push browser screenshots frame-by-frame via POST /api/agent/screen-push and they appear instantly on the screen. When no frames are flowing, the screen paints real agent-action records as a working terminal. Visit any agent profile or go to /dashboard-next/watch?agentId= to watch.",
+ "tags": ["feature"],
+ "link": "/dashboard-next/watch"
+ },
{
"date": "2026-06-26",
"title": "three.ws built a 3D AI agent live with IBM",
diff --git a/data/pages.json b/data/pages.json
index 1bf506597..fc65d6932 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -242,6 +242,14 @@
"changefreq": "weekly",
"added": "2026-06-05"
},
+ {
+ "path": "/agent-screen",
+ "title": "Agent Screen",
+ "description": "Watch your agent work in real time — split view with the agent's live screen on the left and their 3D avatar rendered as a webcam on the right.",
+ "auth": "required",
+ "indexable": false,
+ "added": "2026-06-26"
+ },
{
"path": "/agent-studio",
"title": "Agent Studio",
diff --git a/prompts/agent-playwright-stream.md b/prompts/agent-playwright-stream.md
new file mode 100644
index 000000000..3e0182598
--- /dev/null
+++ b/prompts/agent-playwright-stream.md
@@ -0,0 +1,153 @@
+# Agent Playwright Screen Streaming Service
+
+## Context
+
+three.ws has a live agent watch system built and deployed:
+
+- `api/agent/screen-stream.js` — SSE endpoint, streams frames + activity to any client watching
+- `api/agent/screen-push.js` — POST endpoint that accepts base64 PNG frames from external agent processes
+- `src/shared/agent-watch-panel.js` — 2D panel (screen + avatar webcam) shown on every agent profile
+- `src/game/agent-desk.js` — 3D desk with live CanvasTexture monitor in the /play world
+- `/dashboard-next/watch?agentId=<id>` — standalone full-page watch view
+
+The SSE stream already delivers real agent-action records as the "screen" when no frames are being pushed. This prompt is about building the **Playwright process** that pushes real browser screenshots.
+
+## What to build
+
+A Node.js service (`services/agent-screen-caster/`) that:
+
+1. **Accepts an agent config** (agentId, owner bearer token, tasks to run)
+2. **Spins up a Playwright Chromium browser** (headless by default, non-headless for dev)
+3. **Captures screenshots** every 300–500ms OR on every `page.on('load')` / `page.on('requestfinished')` event (whichever is more event-driven)
+4. **Compresses each screenshot** to JPEG at 75% quality then base64-encodes it
+5. **POSTs each frame** to `https://three.ws/api/agent/screen-push` with the agent's bearer token
+6. **Also POSTs structured activity** (`/api/agent/screen-push` with `actions` array) whenever the agent takes a meaningful action (navigation, click, form submit, trade)
+
+## File structure
+
+```
+services/agent-screen-caster/
+ index.js — CLI entrypoint, reads .env + argv
+ caster.js — AgentScreenCaster class (Playwright + push loop)
+ tasks/
+ pump-monitor.js — example task: watch a pump.fun coin page
+ trade.js — example task: Solana trade UI automation
+ package.json
+ .env.example
+```
+
+## Technical spec
+
+### `caster.js` — AgentScreenCaster
+
+```js
+class AgentScreenCaster {
+ constructor({ agentId, bearerToken, pushUrl, frameIntervalMs, jpegQuality })
+ async launch(headless = true) // start Playwright
+ async navigate(url) // go to a URL, auto-push frame
+ async act(description, fn) // named action wrapper — pushes activity + frame
+ startFrameLoop() // setInterval for continuous frame push
+ stopFrameLoop()
+ async pushFrame() // capture → compress → POST
+ async pushActivity(actions) // POST to /api/agent/screen-push with actions array
+ async close() // tear down Playwright
+}
+```
+
+### Frame push format (already defined in the API)
+
+```http
+POST /api/agent/screen-push
+Authorization: Bearer <agentBearerToken>
+Content-Type: application/json
+
+{ "agentId": "...", "frame": "<base64 JPEG>", "seq": 1234567890 }
+```
+
+### Activity push format
+
+```http
+POST /api/agent/screen-push
+Authorization: Bearer <agentBearerToken>
+Content-Type: application/json
+
+{
+ "agentId": "...",
+ "actions": [
+ { "type": "navigate", "summary": "Navigating to pump.fun", "ts": 1234567890 },
+ { "type": "trade", "summary": "Buying 0.1 SOL of $COIN", "ts": 1234567890 }
+ ]
+}
+```
+
+### Auth: how to get the bearer token
+
+The agent's bearer token lives in the calling agent process's environment. It's the same token used by the agent's wallet bridge. Check `api/_lib/auth.js` `authenticateBearer()` — it validates a JWT signed with `JWT_SECRET`. Generate one for an agent owner session.
+
+Alternatively, a new API key system under `api/api-keys.js` already issues bearer tokens — use those.
+
+## Example task: pump.fun coin monitor
+
+```js
+// tasks/pump-monitor.js
+export async function runPumpMonitor(caster, mint) {
+ await caster.navigate(`https://pump.fun/coin/${mint}`);
+
+ // Watch for price changes via DOM observation
+ await caster.page.exposeFunction('onPriceChange', async (price) => {
+ await caster.act('price_update', async () => {
+ await caster.pushActivity([{
+ type: 'price_update',
+ summary: `$${price} — monitoring ${mint.slice(0,8)}…`,
+ ts: Date.now(),
+ }]);
+ });
+ });
+
+ await caster.page.evaluate(() => {
+ const el = document.querySelector('[data-price]');
+ if (!el) return;
+ const obs = new MutationObserver(() => window.onPriceChange(el.textContent));
+ obs.observe(el, { childList: true, subtree: true, characterData: true });
+ });
+
+ // Keep the session alive
+ await new Promise(() => {});
+}
+```
+
+## `.env.example`
+
+```
+AGENT_ID=<uuid>
+AGENT_BEARER_TOKEN=<jwt>
+PUSH_URL=https://three.ws/api/agent/screen-push
+FRAME_INTERVAL_MS=400
+JPEG_QUALITY=72
+HEADLESS=true
+TASK=pump-monitor
+TASK_ARG=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump
+```
+
+## Notes
+
+- This service should be a **long-running Node.js process** (not a Vercel function)
+- Deploy to a Cloud Run container or a Cloudflare Worker with Durable Objects for persistence
+- Playwright's `chromium.launch()` works in Docker — use `mcr.microsoft.com/playwright:v1.x-jammy` as base
+- Each Playwright session = one browser context = one agent's "screen"
+- Multiple agents can run in the same Node process using separate `AgentScreenCaster` instances
+- Frame size: a 1280×720 JPEG at quality 72 is approximately 40–80 KB, well within the 1 MB API limit
+- The receiving SSE clients (2D panel, 3D desk) handle 400ms frames gracefully — no need to go faster
+- Existing infrastructure: `workers/` contains Cloudflare workers — the screen-caster could also live there as a Durable Object if you want zero-infra hosting
+
+## Where the frames go after pushing
+
+```
+AgentScreenCaster.pushFrame()
+ → POST /api/agent/screen-push
+ → cacheSet('screen:frame:<agentId>', { frame, seq, ts }, 10s TTL)
+ → api/agent/screen-stream.js polls every 250ms
+ → SSE event: { type: 'frame', frame, seq, ts }
+ → src/shared/agent-watch-panel.js renders frame to canvas
+ → src/game/agent-desk.js renders frame to THREE.CanvasTexture on monitor mesh
+```
diff --git a/prompts/agent-screen-playwright-worker.md b/prompts/agent-screen-playwright-worker.md
new file mode 100644
index 000000000..fd85615c0
--- /dev/null
+++ b/prompts/agent-screen-playwright-worker.md
@@ -0,0 +1,222 @@
+# Prompt: Browser Capture Worker for Agent Screen Stream
+
+## Context
+
+`three.ws` has a live agent screen system. The infrastructure is:
+
+- **POST `/api/agent-screen-push`** — agents push frames here (base64 PNG + activity text)
+- **GET `/api/agent-screen-stream?agentId=<uuid>`** — SSE stream that viewers subscribe to
+- **`pages/agent-screen.html` + `src/agent-screen.js`** — 2D split-view dashboard (screen left, avatar webcam right)
+- **`src/walk-agent-desk.js`** — 3D desk in /play with a CanvasTexture monitor
+
+What's missing: a worker that **actually captures browser screenshots and pushes them** to the system. This prompt is for implementing that worker.
+
+## Your task
+
+Build a long-lived Node.js worker (similar to `workers/agent-sniper/`) that:
+
+1. Launches a **Stagehand** (npm: `@browserbasehq/stagehand`) browser session
+2. Drives the browser autonomously (trading, research, browsing, whatever the agent's configured task is)
+3. On every meaningful state change (or on a timer), captures a screenshot and pushes it to `/api/agent-screen-push`
+4. Also pushes plain-text "activity" narration for each action taken (no screenshot needed, just text)
+
+## Files to create
+
+### `workers/agent-screen-worker/`
+
+```
+workers/agent-screen-worker/
+ index.js — entrypoint: boots Stagehand session, runs task loop
+ config.js — env loading + validation
+ capture.js — screenshot capture + push-to-API logic
+ task-runner.js — the autonomous task the agent performs
+ package.json
+ Dockerfile
+ README.md
+```
+
+## Implementation details
+
+### `capture.js`
+
+```js
+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; // JWT for the agent that owns the screen
+
+export async function pushFrame({ agentId, page, activity, type = 'screenshot' }) {
+ let data = null;
+ try {
+ // Stagehand exposes page.screenshot() (Playwright under the hood)
+ const buf = await page.screenshot({ type: 'png', fullPage: false });
+ data = 'data:image/png;base64,' + buf.toString('base64');
+ } catch (err) {
+ console.warn('[capture] screenshot failed:', err.message);
+ type = 'activity'; // degrade to text-only
+ }
+
+ const body = { agentId, frame: { data, activity, type } };
+ await fetch(PUSH_URL, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${AGENT_JWT}`,
+ },
+ body: JSON.stringify(body),
+ });
+}
+```
+
+### `index.js`
+
+```js
+import { Stagehand } from '@browserbasehq/stagehand';
+import { loadConfig } from './config.js';
+import { pushFrame } from './capture.js';
+import { runTask } from './task-runner.js';
+
+const cfg = loadConfig();
+
+async function main() {
+ const stagehand = new Stagehand({
+ env: cfg.BROWSERBASE_API_KEY ? 'BROWSERBASE' : 'LOCAL',
+ apiKey: cfg.BROWSERBASE_API_KEY,
+ projectId: cfg.BROWSERBASE_PROJECT_ID,
+ verbose: 1,
+ });
+
+ await stagehand.init();
+ const page = stagehand.page;
+ const context = stagehand.context;
+
+ // Push an initial "booting" frame so the stream lights up immediately
+ await pushFrame({ agentId: cfg.AGENT_ID, page, activity: 'Agent starting up…', type: 'activity' });
+
+ // Run the agent's task loop
+ await runTask({ stagehand, page, context, cfg, pushFrame });
+}
+
+main().catch((err) => {
+ console.error('[agent-screen-worker] fatal:', err);
+ process.exit(1);
+});
+```
+
+### `task-runner.js`
+
+```js
+// This is where the agent's actual autonomous behaviour lives.
+// Replace this template with the specific task (trading, research, etc.)
+
+export async function runTask({ stagehand, page, cfg, pushFrame }) {
+ const agentId = cfg.AGENT_ID;
+
+ while (true) {
+ try {
+ // Example: navigate to pump.fun, observe trending tokens
+ await page.goto('https://pump.fun');
+ await pushFrame({ agentId, page, activity: 'Scanning pump.fun for trending tokens', type: 'analysis' });
+
+ // Use Stagehand's act() for natural-language browser actions
+ const trending = await stagehand.extract({
+ instruction: 'Extract the top 5 trending token names and their market caps',
+ schema: { tokens: [{ name: 'string', marketCap: 'string' }] },
+ });
+ await pushFrame({ agentId, page, activity: `Found ${trending.tokens.length} trending tokens`, type: 'analysis' });
+
+ // Trade decision (example)
+ const pick = trending.tokens[0];
+ await pushFrame({ agentId, page, activity: `Evaluating ${pick.name} — analyzing chart`, type: 'trade' });
+
+ // Sleep between cycles
+ await new Promise((r) => setTimeout(r, cfg.CYCLE_MS || 30_000));
+ } catch (err) {
+ await pushFrame({ agentId, page: null, activity: `Error: ${err.message}`, type: 'activity' });
+ await new Promise((r) => setTimeout(r, 5_000));
+ }
+ }
+}
+```
+
+### `config.js`
+
+```js
+import { createRequire } from 'module';
+const require = createRequire(import.meta.url);
+
+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}`);
+ }
+ 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: process.env.BROWSERBASE_API_KEY || '',
+ BROWSERBASE_PROJECT_ID: process.env.BROWSERBASE_PROJECT_ID || '',
+ CYCLE_MS: Number(process.env.CYCLE_MS || 30_000),
+ };
+}
+```
+
+### `package.json`
+
+```json
+{
+ "name": "agent-screen-worker",
+ "type": "module",
+ "version": "1.0.0",
+ "dependencies": {
+ "@browserbasehq/stagehand": "^1.x",
+ "node-fetch": "^3"
+ }
+}
+```
+
+### `Dockerfile`
+
+```dockerfile
+FROM mcr.microsoft.com/playwright:v1.44.0-jammy
+WORKDIR /app
+COPY package*.json ./
+RUN npm ci
+COPY . .
+# Install Playwright browsers for local mode
+RUN npx playwright install chromium --with-deps
+CMD ["node", "index.js"]
+```
+
+## Environment variables needed
+
+| Variable | Description |
+|---|---|
+| `AGENT_ID` | UUID of the agent that owns the screen stream |
+| `AGENT_JWT` | JWT for that agent (from /api/auth or the agent's API key) |
+| `PUSH_URL` | Override push endpoint (default: https://three.ws/api/agent-screen-push) |
+| `BROWSERBASE_API_KEY` | Optional — use Browserbase cloud instead of local Playwright |
+| `BROWSERBASE_PROJECT_ID` | Required if using Browserbase |
+| `CYCLE_MS` | Task loop cycle time in ms (default: 30000) |
+
+## Two deployment modes
+
+**Local Playwright** (development / self-hosted):
+- Set `env: 'LOCAL'` in Stagehand config
+- Docker container runs Chromium via Playwright
+- `BROWSERBASE_API_KEY` not needed
+
+**Browserbase cloud** (production / zero-infra):
+- Set `BROWSERBASE_API_KEY` + `BROWSERBASE_PROJECT_ID`
+- Browser runs in Browserbase's cloud
+- Screenshot frames are still pushed to three.ws from the worker process
+- No Dockerfile needed — runs as a plain Node process or in a VM
+
+## Wire-up checklist
+
+- [ ] Create `workers/agent-screen-worker/` with the files above
+- [ ] Set `AGENT_ID` to an existing agent UUID from the three.ws DB
+- [ ] Get `AGENT_JWT` by logging in as the agent owner and grabbing the bearer token from Network tab, or generate one via the agents API
+- [ ] Run `npm install && npm start` (local) or `docker build && docker run` (containerized)
+- [ ] Open `/agent-screen?agentId=<uuid>` — you should see frames appear within 1–2 seconds of the worker starting
+- [ ] The /play world desk will also show the live screen when you walk up to it
diff --git a/prompts/agent-screen-sniper-wiring.md b/prompts/agent-screen-sniper-wiring.md
new file mode 100644
index 000000000..65eaf8c90
--- /dev/null
+++ b/prompts/agent-screen-sniper-wiring.md
@@ -0,0 +1,128 @@
+# Prompt: Wire Agent Sniper Worker to Agent Screen Stream
+
+## Context
+
+`three.ws` has an agent sniper worker at `workers/agent-sniper/` — a long-lived Node process that snipes pump.fun tokens from an agent's Solana wallet. It already emits detailed logs and positions.
+
+The platform also has a live agent screen system:
+- **POST `/api/agent-screen-push`** — push frame or activity text
+- **GET `/api/agent-screen-stream?agentId=<uuid>`** — SSE stream viewers subscribe to
+- **`pages/agent-screen.html`** — 2D watch view at `/agent-screen?agentId=<uuid>`
+- **`src/walk-agent-desk.js`** — 3D desk monitor in /play
+
+Your task: wire the sniper worker to push activity narration (and optionally screenshots) to the screen stream, so viewers watching the agent can see trade decisions play out in real time.
+
+## Files to modify
+
+### `workers/agent-sniper/index.js`
+
+The sniper already has a `log` module. Add a `screenPush` helper that fires alongside log lines.
+
+### `workers/agent-sniper/screen-push.js` (new file)
+
+```js
+// 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;
+
+export function screenPush(activity, type = 'activity') {
+ if (!AGENT_JWT || !AGENT_ID) return; // silent no-op if not configured
+ const body = JSON.stringify({ agentId: AGENT_ID, frame: { activity, type } });
+ fetch(PUSH_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${AGENT_JWT}` },
+ body,
+ }).catch(() => {}); // fire-and-forget — never block the trade path
+}
+```
+
+### `workers/agent-sniper/index.js`
+
+Import and call `screenPush` at each significant decision point. The sniper's existing flow:
+
+1. **New mint detected** → `screenPush('New token detected: $SYMBOL — scoring…', 'analysis')`
+2. **Score decision** → `screenPush('$SYMBOL scored ${score}/100 — ${score >= threshold ? "BUYING" : "skipping"}', score >= threshold ? 'trade' : 'analysis')`
+3. **Buy execution** → `screenPush('Buying $SYMBOL — sending tx…', 'trade')`
+4. **Buy confirmed** → `screenPush('Bought $SYMBOL at ${price} SOL — position open', 'trade')`
+5. **Position update** → `screenPush('$SYMBOL: ${pnlPct}% P&L — monitoring', 'trade')`
+6. **Sell triggered** → `screenPush('Selling $SYMBOL: ${exitReason}', 'trade')`
+7. **Sell confirmed** → `screenPush('Sold $SYMBOL — ${pnlPct > 0 ? "profit" : "loss"}: ${pnlSol} SOL', 'trade')`
+8. **Error** → `screenPush('Error: ${err.message}', 'activity')`
+
+## Where to add the import
+
+At the top of `workers/agent-sniper/index.js`:
+```js
+import { screenPush } from './screen-push.js';
+```
+
+## Environment variables to add
+
+| Variable | Value |
+|---|---|
+| `AGENT_JWT` | JWT bearer token for the agent (same user that owns the agent). Get this by logging in as the agent owner and extracting the `Authorization: Bearer <token>` header, or by calling `/api/auth/token` with the owner credentials. |
+| `AGENT_ID` | UUID of the sniper agent from the `agents` table |
+| `PUSH_URL` | Override: defaults to `https://three.ws/api/agent-screen-push` |
+
+These are additive — existing sniper env vars (`DATABASE_URL`, `PUMPPORTAL_KEY`, etc.) are unchanged.
+
+## Testing
+
+1. Set `AGENT_JWT` and `AGENT_ID` in the sniper's `.env`
+2. Run the sniper against devnet: `NETWORK=devnet node index.js`
+3. Open `/agent-screen?agentId=<AGENT_ID>` in a browser
+4. Within the sniper's first radar sweep you should see activity entries appear in the log panel
+5. When a buy fires, the activity type switches to `trade` and the entry highlights green
+
+## Optional: add a terminal-style canvas renderer
+
+If you want the monitor to show a readable terminal feed instead of a blank waiting screen even when no browser is open:
+
+In `screen-push.js`, add a `renderTerminalFrame(lines)` helper that:
+1. Creates an offscreen `<canvas>` (1280×720) via `node-canvas` (npm: `canvas`)
+2. Draws a dark terminal background with monospace text, the last N activity lines in green/white/yellow
+3. Exports as PNG and includes it as `frame.data` in the push
+
+This makes the 3D desk monitor show a live terminal feed — no browser window needed.
+
+```js
+import { createCanvas } from 'canvas'; // npm install canvas
+
+const CW = 1280, CH = 720;
+const activityLog = [];
+
+export function renderTerminalFrame(newLine) {
+ activityLog.push(newLine);
+ if (activityLog.length > 18) activityLog.shift();
+
+ const canvas = createCanvas(CW, CH);
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = '#06080f'; ctx.fillRect(0, 0, CW, CH);
+ ctx.font = '28px monospace';
+ activityLog.forEach((line, i) => {
+ const age = activityLog.length - 1 - i;
+ ctx.fillStyle = age === 0 ? '#fff' : age < 4 ? 'rgba(255,255,255,0.7)' : 'rgba(255,255,255,0.35)';
+ ctx.fillText(line, 40, 60 + i * 38);
+ });
+ return 'data:image/png;base64,' + canvas.toBuffer('image/png').toString('base64');
+}
+```
+
+Then update `screenPush` to include the rendered frame:
+```js
+export function screenPush(activity, type = 'activity') {
+ if (!AGENT_JWT || !AGENT_ID) return;
+ const data = renderTerminalFrame(`[${type.toUpperCase()}] ${activity}`);
+ const body = JSON.stringify({ agentId: AGENT_ID, frame: { data, activity, type } });
+ fetch(PUSH_URL, { method: 'POST', headers: { ... }, body }).catch(() => {});
+}
+```
+
+This gives you a live terminal screen in both the 2D watch view and the 3D walk desk monitor, rendered from pure Node — no browser needed on the worker side.
diff --git a/public/changelog.json b/public/changelog.json
index 34283e8c0..3ff0346b8 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-26T17:39:27.923Z",
+ "generated_at": "2026-06-26T18:45:53.543Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-26",
+ "type": "launch",
+ "title": "Agent Screen",
+ "summary": "Watch your agent work in real time — split view with the agent's live screen on the left and their 3D avatar rendered as a webcam on the right.",
+ "link": "/agent-screen",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-26",
"type": "launch",
@@ -88,6 +98,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "Agent Screen — watch your agent's live screen and avatar cam in 2D and in the 3D world",
+ "summary": "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.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-26",
"type": "update",
@@ -493,6 +513,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "Watch your agent work — live screen and webcam on every agent profile",
+ "summary": "Every agent profile now has a live watch view: a real-time screen showing what the agent is doing (trading, decisions, task log) alongside an avatar webcam rendered from the agent's 3D GLB. In the /play world, agents now appear seated at desks with live monitor screens you can walk up to and tap to open the full watch view. External agent processes can push browser screenshots frame-by-frame via POST /api/agent/screen-push and they appear instantly on the screen. When no frames are flowing, the screen paints real agent-action records as a working terminal. Visit any agent profile or go to /dashboard-next/watch?agentId= to watch.",
+ "link": "/dashboard-next/watch",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-25",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 4ecf46098..656b273a7 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Agent Screen</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-26:Agent Screen</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Watch your agent work in real time — split view with the agent's live screen on the left and their 3D avatar rendered as a webcam on the right.</description>
+ </item>
<item>
<title>Avatar Engines Atlas</title>
<link>https://three.ws/avatar-engines</link>
@@ -70,6 +78,14 @@
<category>fix</category>
<description>Every agent profile (/agents/&lt;id&gt;) 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.</description>
</item>
+ <item>
+ <title>Agent Screen — watch your agent's live screen and avatar cam in 2D and in the 3D world</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-26:Agent Screen — watch your agent's live screen and avatar cam in 2D and in the 3D world</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <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>Alpha Co-pilot overhauled — agent gallery, cited-signal highlights, score bars, and live routing fixed</title>
<link>https://three.ws/alpha-copilot</link>
@@ -374,6 +390,14 @@
<category>feature</category>
<description>The /coin3d viewer got a major upgrade. It now opens with a proper landing page: paste any mint to render it, jump straight to $THREE, or pick from a grid of recent three.ws launches. Load a coin and the scene comes alive — the HUD shows live price, 24h change with a sparkline, market cap, 24h volume, top-holder concentration, quality and smart-money signals, and any risk flags. Every real DEX swap fires a glowing pulse into the coin (green for buys, red for sells) that's mirrored in a scrolling live-trade tape with running net flow and links to each transaction. Graduated coins like $THREE now resolve their name, logo and market cap correctly, a drifting starfield adds depth, and if a device can't do 3D the page gracefully falls back to the full live data view instead of a blank screen.</description>
</item>
+ <item>
+ <title>Watch your agent work — live screen and webcam on every agent profile</title>
+ <link>https://three.ws/dashboard-next/watch</link>
+ <guid isPermaLink="false">2026-06-26:Watch your agent work — live screen and webcam on every agent profile</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every agent profile now has a live watch view: a real-time screen showing what the agent is doing (trading, decisions, task log) alongside an avatar webcam rendered from the agent's 3D GLB. In the /play world, agents now appear seated at desks with live monitor screens you can walk up to and tap to open the full watch view. External agent processes can push browser screenshots frame-by-frame via POST /api/agent/screen-push and they appear instantly on the screen. When no frames are flowing, the screen paints real agent-action records as a working terminal. Visit any agent profile or go to /dashboard-next/watch?agentId= to watch.</description>
+ </item>
<item>
<title>Animation Gallery now shows the full motion library</title>
<link>https://three.ws/animations</link>
diff --git a/public/features.json b/public/features.json
index cf9563583..d539ef8dc 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-26T17:39:27.910Z",
+ "generated_at": "2026-06-26T18:45:53.530Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -292,6 +292,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/agent-screen",
+ "title": "Agent Screen",
+ "description": "Watch your agent work in real time — split view with the agent's live screen on the left and their 3D avatar rendered as a webcam on the right.",
+ "added": "2026-06-26",
+ "auth": "required",
+ "indexable": false,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/agent-studio",
"title": "Agent Studio",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index dcc357149..3ccae4f0b 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -180,6 +180,14 @@ URL: https://three.ws/create-agent
Step-by-step wizard to create a 3D AI agent: name, 3D body, skills, personality, voice, and on-chain identity.
+### Agent Screen
+
+URL: https://three.ws/agent-screen
+Auth: required (sign-in)
+Indexable: no (excluded from sitemap)
+
+Watch your agent work in real time — split view with the agent's live screen on the left and their 3D avatar rendered as a webcam on the right.
+
### Agent Studio
URL: https://three.ws/agent-studio
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 72012c311..1b7979202 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 340 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 341 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 340 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 341 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -252,7 +252,7 @@
<section class="sm-section" id="build">
<header>
- <h2>Build<span class="sm-count" data-count>42</span></h2>
+ <h2>Build<span class="sm-count" data-count>43</span></h2>
<p class="sm-section-desc">Create and customize an agent.</p>
</header>
<ul class="sm-list">
@@ -298,6 +298,13 @@
<span class="sm-desc">Step-by-step wizard to create a 3D AI agent: name, 3D body, skills, personality, voice, and on-chain identity.</span>
</a>
</li>
+ <li>
+ <a href="/agent-screen">
+ <span class="sm-title">Agent Screen<span class="sm-badge sm-badge-auth">sign-in</span><span class="sm-badge sm-badge-internal">internal</span></span>
+ <span class="sm-path">/agent-screen</span>
+ <span class="sm-desc">Watch your agent work in real time — split view with the agent's live screen on the left and their 3D avatar rendered as a webcam on the right.</span>
+ </a>
+ </li>
<li>
<a href="/agent-studio">
<span class="sm-title">Agent Studio<span class="sm-badge sm-badge-auth">sign-in</span><span class="sm-badge sm-badge-internal">internal</span></span>
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 6e820d28d..b363666e1 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -23,6 +23,7 @@ import { mountPresence } from './shared/networth-presence.js';
import { mountStagePanel } from './shared/stage-link.js';
import { mountLaborPanel } from './shared/labor-link.js';
import { mountAlphaPanel } from './shared/alpha-copilot-link.js';
+import { mountWatchPanel } from './shared/agent-watch-panel.js';
import { renderError as renderAsyncError } from './shared/async-state.js';
import { skeletonHTML } from './shared/state-kit.js';
import { openCoinLaunch } from './shared/agent-coin.js';
@@ -47,6 +48,7 @@ let _streamHandle = null;
let _strategyHandle = null;
let _cardHandle = null;
let _patronageHandle = null;
+let _watchHandle = null;
// Live WebGL avatar mounts (hero + fullscreen modal). Disposed on re-render so a
// fresh render() doesn't stack a second renderer onto the same container.
let _heroAvatarHandle = null;
@@ -99,6 +101,17 @@ function mountAgentDetailAura(agent) {
// character and (for the owner) act within its spend limits. Enhancement.
mountAlphaPanel({ agentId: agent.id, agentName: agent.name || 'this agent', isOwner: !!agent.isOwner, container: main, position: 'prepend' })
.catch(() => { /* never block the profile */ });
+ // Live watch panel — agent's screen + avatar webcam. Always shown;
+ // renders real activity canvas when no Playwright frames are flowing.
+ try { _watchHandle?.destroy?.(); } catch { /* */ } _watchHandle = null;
+ mountWatchPanel({
+ agentId: agent.id,
+ agentName: agent.name || 'this agent',
+ avatarUrl: agentAvatarGlb(agent),
+ isOwner: !!agent.isOwner,
+ container: main,
+ position: 'append',
+ }).then((h) => { _watchHandle = h || null; }).catch(() => { /* never block */ });
}
})
.catch(() => { /* dormant baseline already shown */ });
@@ -112,6 +125,7 @@ if (typeof window !== 'undefined') {
// past navigation (the engine also guards this internally).
try { _streamHandle?.destroy?.(); } catch { /* idempotent */ } _streamHandle = null;
try { _cardHandle?.destroy?.(); } catch { /* idempotent */ } _cardHandle = null;
+ try { _watchHandle?.destroy?.(); } catch { /* idempotent */ } _watchHandle = null;
// Release the WebGL contexts so they don't count against the browser's
// hard context budget once the user navigates away.
try { _heroAvatarHandle?.dispose(); } catch { /* idempotent */ } _heroAvatarHandle = null;
diff --git a/src/agent-screen.js b/src/agent-screen.js
index e391c6263..f88c30b43 100644
--- a/src/agent-screen.js
+++ b/src/agent-screen.js
@@ -21,13 +21,11 @@ import {
Scene,
AmbientLight,
DirectionalLight,
- Vector3,
Box3,
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
import { AnimationManager } from './animation-manager.js';
-import { glbCanonicalize } from './glb-canonicalize.js';
import { createAgentScreenClient } from './shared/agent-screen-client.js';
import { agentAvatarGlb } from './shared/agent-3d.js';
@@ -151,8 +149,6 @@ async function boot(id) {
const loader = new GLTFLoader();
const gltf = await loader.loadAsync(glbUrl || '/avatars/default.glb');
const model = cloneSkinnedScene(gltf.scene);
- glbCanonicalize(model);
-
webcamScene.add(model);
webcamAvatar = model;
diff --git a/src/game/agent-desk.js b/src/game/agent-desk.js
index 804a6406a..f764d10da 100644
--- a/src/game/agent-desk.js
+++ b/src/game/agent-desk.js
@@ -52,7 +52,7 @@ const MON_H = (MON_W * CH) / CW;
// ── canvas painting ───────────────────────────────────────────────────────────
-function paintDesk(ctx, actions, status, agentName, t) {
+function paintDesk(ctx, tex, actions, status, agentName, t) {
const text = '#f0f0f4', dim = 'rgba(255,255,255,0.35)', faint = 'rgba(255,255,255,0.12)';
const up = '#5fd08a', bg0 = '#080809', bg1 = '#0d0d11';
const pulse = 0.5 + 0.5 * Math.sin(t * 3);
@@ -192,11 +192,9 @@ function paintDesk(ctx, actions, status, agentName, t) {
ctx.fillText('walk up · press E to watch', winX + winW - 10, sbY + 12);
ctx.textAlign = 'left';
- tex.needsUpdate = true; // eslint-disable-line no-use-before-define
+ tex.needsUpdate = true;
}
-let tex; // assigned after canvas is created so paintDesk can reference it
-
function roundRect(ctx, x, y, w, h, r) {
const tl = Array.isArray(r) ? r[0] : r;
const tr = Array.isArray(r) ? r[1] : r;
@@ -277,7 +275,7 @@ export function createAgentDesk(scene, agent, opts = {}) {
const canvas = document.createElement('canvas');
canvas.width = CW; canvas.height = CH;
const ctx = canvas.getContext('2d');
- tex = new CanvasTexture(canvas);
+ const tex = new CanvasTexture(canvas);
tex.colorSpace = SRGBColorSpace;
tex.anisotropy = 8;
@@ -313,7 +311,7 @@ export function createAgentDesk(scene, agent, opts = {}) {
let es = null;
// Initial paint so the screen isn't blank before the first fetch.
- paintDesk(ctx, [], 'idle', agent.agentName || 'Agent', 0);
+ paintDesk(ctx, tex, [], 'idle', agent.agentName || 'Agent', 0);
function connectSSE() {
if (es) { try { es.close(); } catch { /* */ } }
@@ -387,7 +385,7 @@ export function createAgentDesk(scene, agent, opts = {}) {
ctx.drawImage(frameImg, 0, 0, CW, CH);
tex.needsUpdate = true;
} else {
- paintDesk(ctx, actions, status, agent.agentName || 'Agent', t);
+ paintDesk(ctx, tex, actions, status, agent.agentName || 'Agent', t);
}
},
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 6bad518d7..2333b02f5 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -58,6 +58,7 @@ import { clearStoredPass, refreshPlayPass, loadStoredPass, storePass } from './p
import { PlaySystems } from './play-systems.js';
import { PlayOnboard } from './play-onboard.js';
import { log } from '../shared/log.js';
+import { createAgentDesk } from './agent-desk.js';
// localStorage throws in private mode and in third-party iframe contexts where
// storage is blocked — exactly the `?bg=transparent` embed case (e.g. the IBM
@@ -531,6 +532,9 @@ export class CoinCommunities {
this._chartScreen?.update(dt);
this._oracleRibbon?.update(dt);
this._reactor?.update(dt);
+ if (this._agentDesks?.length) {
+ for (const desk of this._agentDesks) desk.update(dt, this.localPos);
+ }
this._tickDanceFloor(dt);
}
@@ -1021,6 +1025,31 @@ export class CoinCommunities {
ui: this.ui,
});
}
+ // Agent desks — visible in every world. Fetches the world's top registered
+ // agents from /api/agents and seats them at working desks with live
+ // CanvasTexture monitors streaming their real activity. Players can walk up
+ // and press E (or tap) to open the full 2D watch view.
+ this._agentDesks = [];
+ fetch(`/api/agents?limit=3`, { credentials: 'include' })
+ .then((r) => r.ok ? r.json() : null)
+ .then((d) => {
+ const agents = d?.agents || d?.data || [];
+ agents.slice(0, 3).forEach((a, i) => {
+ const offsets = [[-14, 0, -10], [14, 0, -10], [0, 0, -14]];
+ const rotations = [Math.PI * 0.15, -Math.PI * 0.15, Math.PI];
+ const desk = createAgentDesk(this.scene, {
+ agentId: a.id,
+ agentName: a.name || 'Agent',
+ avatarUrl: a.avatar_glb_url || a.avatar_model_url || '',
+ }, {
+ position: offsets[i],
+ rotationY: rotations[i],
+ });
+ this._agentDesks.push(desk);
+ });
+ })
+ .catch(() => { /* non-critical — world works without desks */ });
+
// Living world (W08): ambient pedestrians + traffic, interactive vendor /
// quest / flavor NPCs, and (gated behind W07) hostile mobs — all on a
// deterministic nav graph so every client sees the same crowd without
@@ -1279,6 +1308,10 @@ export class CoinCommunities {
}
if (this._chartScreen) { this._chartScreen.dispose(); this._chartScreen = null; }
if (this._oracleRibbon) { this._oracleRibbon.dispose(); this._oracleRibbon = null; }
+ if (this._agentDesks?.length) {
+ for (const desk of this._agentDesks) desk.dispose();
+ this._agentDesks = [];
+ }
if (this._danceFloor) { this.world.remove(this._danceFloor); this._danceFloor = null; }
this._floorLights = null; this._floorTiles = null; this._floorCenterMat = null;
this._danceFloorPos = null; this._onFloor = false; this._wantsDance = false;
@@ -2029,6 +2062,16 @@ export class CoinCommunities {
if (this.worldLife?.tryActivateAt(e.clientX, e.clientY)) return;
if (this.agentCommerce?.tryActivateAt(this._pointerRay(e.clientX, e.clientY))) return;
if (this.intelKiosk?.tryActivateAt(this._pointerRay(e.clientX, e.clientY))) return;
+ // Tap an agent desk screen → open its full 2D watch view.
+ if (this._agentDesks?.length) {
+ const ray = this._pointerRay(e.clientX, e.clientY);
+ for (const desk of this._agentDesks) {
+ if (desk.screen && ray.intersectObject(desk.screen, false).length > 0) {
+ desk.openWatch();
+ return;
+ }
+ }
+ }
if (this._raycastScreen(e.clientX, e.clientY)) this._chartScreen.openExternal();
});
// Right-click always breaks the targeted block while building.
@@ -2044,7 +2087,14 @@ export class CoinCommunities {
this._hoverAt = now;
this._lastHover = { x: e.clientX, y: e.clientY };
if (this.buildHud.active) this._updateGhost(e.clientX, e.clientY);
- else if (this._chartScreen) this.canvas.style.cursor = this._raycastScreen(e.clientX, e.clientY) ? 'pointer' : '';
+ else {
+ let overDesk = false;
+ if (this._agentDesks?.length) {
+ const ray = this._pointerRay(e.clientX, e.clientY);
+ overDesk = this._agentDesks.some((d) => d.screen && ray.intersectObject(d.screen, false).length > 0);
+ }
+ this.canvas.style.cursor = overDesk || (this._chartScreen && this._raycastScreen(e.clientX, e.clientY)) ? 'pointer' : '';
+ }
}
return;
}
diff --git a/src/shared/agent-watch-panel.js b/src/shared/agent-watch-panel.js
index fdd01ea74..ee3c14b38 100644
--- a/src/shared/agent-watch-panel.js
+++ b/src/shared/agent-watch-panel.js
@@ -18,10 +18,15 @@
// The panel is entirely self-contained: it manages its own SSE connection,
// Three.js renderer, timers, and styles. Disposing cleans up everything.
-import { Viewer } from '../viewer.js';
-import { IdleAnimation } from '../idle-animation.js';
-
-const STREAM_URL = (id) => `/api/agent/screen-stream?agentId=${encodeURIComponent(id)}`;
+import {
+ PerspectiveCamera, WebGLRenderer, Scene,
+ AmbientLight, DirectionalLight, Box3,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
+import { AnimationManager } from '../animation-manager.js';
+
+const STREAM_URL = (id) => `/api/agent-screen-stream?agentId=${encodeURIComponent(id)}`;
const ACTIONS_URL = (id) => `/api/agent-actions?agent_id=${encodeURIComponent(id)}&limit=20`;
// Canvas dimensions for the activity screen (no frames mode).
@@ -484,9 +489,12 @@ class WatchPanel {
this._streamStatus = 'connecting'; // connecting | live | idle
this._t = 0;
this._rafId = null;
- this._activityRaf = null;
- this._viewer = null;
- this._idleAnim = null;
+ this._webcamRafId = null;
+ this._webcamRenderer = null;
+ this._webcamScene = null;
+ this._webcamCamera = null;
+ this._webcamMixer = null;
+ this._webcamManager = null;
this._buildDOM();
}
@@ -554,32 +562,46 @@ class WatchPanel {
const es = new EventSource(STREAM_URL(this.agentId));
this._es = es;
- es.onmessage = (e) => {
- let msg;
- try { msg = JSON.parse(e.data); } catch { return; }
-
- if (msg.type === 'meta') {
- if (msg.avatarUrl && msg.avatarUrl !== this.avatarUrl) {
- this.avatarUrl = msg.avatarUrl;
- this._rebootWebcam();
+ // Named events from /api/agent-screen-stream
+ es.addEventListener('frame', (e) => {
+ try {
+ const frame = JSON.parse(e.data);
+ if (frame.data) this._renderFrame(frame.data);
+ if (frame.activity) {
+ // Inject into the activity log as a live push
+ const logEntry = { ts: frame.ts || Date.now(), type: frame.type || 'activity', summary: frame.activity };
+ this._actions = [logEntry, ...this._actions].slice(0, 50);
+ this._renderLog();
}
- }
- if (msg.type === 'frame') {
- this._renderFrame(msg.frame);
this._setStatus('live');
- }
- if (msg.type === 'activity') {
- this._actions = msg.actions || [];
- this._renderLog();
- }
- if (msg.type === 'heartbeat') {
- if (this._streamStatus !== 'live') this._setStatus('idle');
- }
- };
+ } catch { /* malformed */ }
+ });
+
+ es.addEventListener('log', (e) => {
+ try {
+ const { entries } = JSON.parse(e.data);
+ if (Array.isArray(entries) && entries.length) {
+ this._actions = entries.map((en) => ({
+ ts: en.ts,
+ type: en.type || 'activity',
+ summary: en.activity || '',
+ }));
+ this._renderLog();
+ }
+ } catch { /* malformed */ }
+ });
+
+ es.addEventListener('dark', () => {
+ if (this._streamStatus !== 'connecting') this._setStatus('idle');
+ });
+
+ es.addEventListener('ping', () => {
+ if (this._streamStatus !== 'live') this._setStatus('idle');
+ });
es.onerror = () => {
this._setStatus('idle');
- // EventSource auto-reconnects; give it a moment.
+ // EventSource auto-reconnects.
};
}
@@ -597,14 +619,15 @@ class WatchPanel {
}
}
- _renderFrame(b64) {
+ _renderFrame(dataOrB64) {
if (this._destroyed) return;
const img = new Image();
img.onload = () => {
if (this._destroyed) return;
this._ctx.drawImage(img, 0, 0, CW, CH);
};
- img.src = 'data:image/png;base64,' + b64;
+ // Accept both raw base64 and full data URLs
+ img.src = dataOrB64.startsWith('data:') ? dataOrB64 : 'data:image/png;base64,' + dataOrB64;
}
_startCanvasLoop() {
@@ -670,54 +693,61 @@ class WatchPanel {
if (!wrap) return;
try {
- // Load the animation manifest once.
- const manifest = await fetch('/animations/manifest.json')
- .then((r) => r.ok ? r.json() : [])
- .catch(() => []);
-
- // Create an offscreen canvas for the avatar, matching the webcam pane's 3:4 ratio.
- const offscreen = document.createElement('canvas');
- offscreen.width = 480;
- offscreen.height = 640;
- offscreen.style.display = 'none';
- wrap.appendChild(offscreen);
- this._camCanvas = offscreen;
-
- // Mount a Viewer in kiosk mode into the offscreen canvas.
- this._viewer = new Viewer({
- el: offscreen,
- kiosk: true,
- background: '#0d0d10',
- environment: 'Neutral',
- cameraControls: false,
- autoRotate: false,
- });
-
- await this._viewer.load(this.avatarUrl);
-
- // Position the camera close to the face — head cam.
- const cam = this._viewer.camera;
- if (cam) {
- cam.position.set(0, 1.55, 0.65);
- cam.lookAt(0, 1.55, 0);
- }
-
- // Retarget idle onto the avatar.
- const idleDef = manifest.find?.((c) => c.id === 'idle' || c.name === 'idle');
- if (idleDef) {
- this._idleAnim = new IdleAnimation(this._viewer, idleDef);
- this._idleAnim.start();
+ const loader = new GLTFLoader();
+ const gltf = await loader.loadAsync(this.avatarUrl);
+ const model = cloneSkinnedScene(gltf.scene);
+
+ const webcamScene = new Scene();
+ webcamScene.add(new AmbientLight(0xffffff, 0.7));
+ const sun = new DirectionalLight(0xffffff, 1.2);
+ sun.position.set(1.5, 2.5, 2);
+ webcamScene.add(sun);
+ const rim = new DirectionalLight(0x8090ff, 0.4);
+ rim.position.set(-2, 1, -1);
+ webcamScene.add(rim);
+ webcamScene.add(model);
+
+ const webcamCamera = new PerspectiveCamera(38, 3 / 4, 0.01, 20);
+ const box = new Box3().setFromObject(model);
+ const h = box.max.y;
+ webcamCamera.position.set(0, h - 0.12, 0.72);
+ webcamCamera.lookAt(0, h - 0.18, 0);
+
+ const renderer = new WebGLRenderer({ antialias: true, alpha: false });
+ renderer.setClearColor(0x0d0d10, 1);
+ renderer.setSize(480, 640);
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ this._webcamRenderer = renderer;
+ this._webcamScene = webcamScene;
+ this._webcamCamera = webcamCamera;
+
+ // Drive idle
+ const mgr = new AnimationManager(model, { loop: true });
+ if (gltf.animations?.length) {
+ this._webcamMixer = mgr.init(gltf.animations);
+ mgr.play('idle');
+ this._webcamManager = mgr;
}
- // Pipe to the video element via captureStream.
- const stream = offscreen.captureStream?.(15);
+ // Tick loop
+ let last = 0;
+ const tick = (t) => {
+ if (this._destroyed) return;
+ this._webcamRafId = requestAnimationFrame(tick);
+ const dt = Math.min((t - last) / 1000, 0.1); last = t;
+ if (this._webcamMixer) this._webcamMixer.update(dt);
+ renderer.render(webcamScene, webcamCamera);
+ };
+ this._webcamRafId = requestAnimationFrame(tick);
+
+ // Pipe to <video> via captureStream
+ const stream = renderer.domElement.captureStream?.(15);
if (stream && this._video) {
this._video.srcObject = stream;
this._video.style.display = 'block';
await this._video.play().catch(() => {});
}
} catch {
- // Webcam boot failed — hide the pane gracefully.
const cw = this.el.querySelector('#wp-cw');
if (cw) cw.style.display = 'none';
const stage = this.el.querySelector('.wp-stage');
@@ -726,24 +756,22 @@ class WatchPanel {
}
async _rebootWebcam() {
- this._idleAnim?.stop?.();
- this._viewer?.dispose?.();
- this._viewer = null;
- this._idleAnim = null;
- if (this._camCanvas) {
- this._camCanvas.remove();
- this._camCanvas = null;
- }
+ if (this._webcamRafId) cancelAnimationFrame(this._webcamRafId);
+ this._webcamRenderer?.dispose?.();
+ this._webcamRenderer = null;
+ this._webcamScene = null;
+ this._webcamCamera = null;
+ this._webcamMixer = null;
+ this._webcamManager = null;
await this._bootWebcam();
}
destroy() {
this._destroyed = true;
if (this._rafId) cancelAnimationFrame(this._rafId);
+ if (this._webcamRafId) cancelAnimationFrame(this._webcamRafId);
try { this._es?.close(); } catch { /* */ }
- this._idleAnim?.stop?.();
- this._viewer?.dispose?.();
- if (this._camCanvas) this._camCanvas.remove();
+ this._webcamRenderer?.dispose?.();
}
}
diff --git a/src/walk-agent-desk.js b/src/walk-agent-desk.js
new file mode 100644
index 000000000..8a67f15df
--- /dev/null
+++ b/src/walk-agent-desk.js
@@ -0,0 +1,425 @@
+// walk-agent-desk.js — a 3D agent desk with a live screen monitor.
+//
+// Places a physical desk in the walk/play scene. On the desk sits a monitor
+// (the same CanvasTexture pattern as chart-screen.js) whose face shows whatever
+// the agent is currently broadcasting via /api/agent-screen-stream. When a
+// player walks close, a HUD overlay appears labelling the agent.
+//
+// The module is designed to mirror NPC + chart-screen patterns so integration
+// into walk.js is a single import + call. Multiple desks can coexist (one per
+// agent) — each is a self-contained group with its own SSE connection.
+//
+// Usage:
+// import { createAgentDeskManager } from './walk-agent-desk.js';
+// const deskMgr = createAgentDeskManager({ scene, camera, renderer });
+// deskMgr.spawn([{ agentId, agentName, avatarUrl, position, rotationY }]);
+// // in render loop:
+// deskMgr.update(dt, playerPos);
+// // on teardown:
+// deskMgr.dispose();
+
+import {
+ Group, Mesh, MeshStandardMaterial, MeshBasicMaterial,
+ BoxGeometry, PlaneGeometry, CylinderGeometry,
+ CanvasTexture, SRGBColorSpace, DoubleSide,
+ Vector3, Box3,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
+import { AnimationManager } from './animation-manager.js';
+import { createAgentScreenClient } from './shared/agent-screen-client.js';
+import { log } from './shared/log.js';
+
+// ── canvas spec — 16:9 matching the agent's screenshot format ───────────────
+const CW = 1280, CH = 720;
+
+// ── desk tuning ─────────────────────────────────────────────────────────────
+const DESK_W = 1.4; // metres wide
+const DESK_D = 0.65; // metres deep
+const DESK_H = 0.75; // metres tall (surface height)
+const LEG_R = 0.035;
+const MONITOR_W = 0.82; // monitor screen width (metres)
+const PROXIMITY_SHOW = 5.0; // player within this distance shows the HUD label
+const PROXIMITY_HIDE = 6.5; // hysteresis
+
+const DESK_COL = 0x1a1c24;
+const LEG_COL = 0x12141b;
+const BEZEL_COL = 0x0a0b10;
+
+// ── palette for the idle "waiting" screen ─────────────────────────────────
+const PAL = {
+ bg: '#06080f',
+ dim: 'rgba(255,255,255,0.28)',
+ accent: '#5b8fff',
+ live: '#3ddc84',
+};
+
+// ── shared GLTF loader ───────────────────────────────────────────────────────
+const gltfLoader = new GLTFLoader();
+
+/**
+ * Build a desk + monitor group and attach it to the scene. Returns a desk
+ * handle with { group, dispose, update(dt, playerPos) }.
+ */
+function createDesk(scene, opts = {}) {
+ const {
+ agentId,
+ agentName = 'Agent',
+ avatarUrl = null,
+ position = [0, 0, 0],
+ rotationY = 0,
+ onProximity = null, // (near:bool, agentId, agentName) → void
+ } = opts;
+
+ const group = new Group();
+ group.position.set(position[0], 0, position[2]);
+ group.rotation.y = rotationY;
+ scene.add(group);
+
+ // ── desk surface ─────────────────────────────────────────────────────
+ const surfaceMat = new MeshStandardMaterial({ color: DESK_COL, roughness: 0.6, metalness: 0.2 });
+ const surface = new Mesh(new BoxGeometry(DESK_W, 0.04, DESK_D), surfaceMat);
+ surface.position.y = DESK_H;
+ surface.castShadow = true;
+ surface.receiveShadow = true;
+ group.add(surface);
+
+ // ── legs ─────────────────────────────────────────────────────────────
+ const legMat = new MeshStandardMaterial({ color: LEG_COL, roughness: 0.4, metalness: 0.5 });
+ const legH = DESK_H - 0.02;
+ for (const [lx, lz] of [
+ [-DESK_W / 2 + 0.08, -DESK_D / 2 + 0.08],
+ [ DESK_W / 2 - 0.08, -DESK_D / 2 + 0.08],
+ [-DESK_W / 2 + 0.08, DESK_D / 2 - 0.08],
+ [ DESK_W / 2 - 0.08, DESK_D / 2 - 0.08],
+ ]) {
+ const leg = new Mesh(new CylinderGeometry(LEG_R, LEG_R, legH, 8), legMat);
+ leg.position.set(lx, legH / 2, lz);
+ leg.castShadow = true;
+ group.add(leg);
+ }
+
+ // ── monitor bezel ────────────────────────────────────────────────────
+ const monH = (MONITOR_W * CH) / CW;
+ const monY = DESK_H + 0.04 + monH / 2 + 0.16; // above surface, standing up
+ const bezelMat = new MeshStandardMaterial({ color: BEZEL_COL, roughness: 0.3, metalness: 0.7 });
+ const bezel = new Mesh(
+ new BoxGeometry(MONITOR_W + 0.04, monH + 0.04, 0.04),
+ bezelMat,
+ );
+ bezel.position.set(0, monY, -DESK_D / 2 + 0.15);
+ bezel.castShadow = true;
+ group.add(bezel);
+
+ // Monitor neck
+ const neck = new Mesh(new CylinderGeometry(0.022, 0.03, 0.18, 8), bezelMat);
+ neck.position.set(0, DESK_H + 0.04 + 0.09, -DESK_D / 2 + 0.15);
+ group.add(neck);
+
+ // Monitor base
+ const base = new Mesh(new BoxGeometry(0.22, 0.02, 0.14), bezelMat);
+ base.position.set(0, DESK_H + 0.04, -DESK_D / 2 + 0.15);
+ group.add(base);
+
+ // ── screen canvas + texture ──────────────────────────────────────────
+ const canvas = document.createElement('canvas');
+ canvas.width = CW;
+ canvas.height = CH;
+ const ctx = canvas.getContext('2d');
+ drawWaiting(ctx, agentName);
+
+ const tex = new CanvasTexture(canvas);
+ tex.colorSpace = SRGBColorSpace;
+ tex.anisotropy = 4;
+
+ const screen = new Mesh(
+ new PlaneGeometry(MONITOR_W, monH),
+ new MeshBasicMaterial({ map: tex, side: DoubleSide, toneMapped: false }),
+ );
+ screen.position.set(0, monY, -DESK_D / 2 + 0.15 + 0.023);
+ screen.userData.agentScreen = true; // raycast tag
+ group.add(screen);
+
+ // ── avatar seated behind desk ────────────────────────────────────────
+ let avatar = null;
+ let avatarMixer = null;
+ let avatarManager = null;
+
+ if (avatarUrl) {
+ gltfLoader.loadAsync(avatarUrl).then((gltf) => {
+ const model = cloneSkinnedScene(gltf.scene);
+
+ // Scale and position: seated at the desk
+ const box = new Box3().setFromObject(model);
+ const standing = box.max.y - box.min.y;
+ const targetH = 1.4; // seated figure should fit in ~1.4m
+ const scale = standing > 0 ? targetH / standing : 1;
+ model.scale.setScalar(scale);
+
+ // Position: behind the desk, facing the monitor
+ model.position.set(0, 0, DESK_D / 2 - 0.1);
+ model.rotation.y = Math.PI; // face the monitor
+
+ group.add(model);
+ avatar = model;
+
+ avatarManager = new AnimationManager(model, { loop: true });
+ if (gltf.animations?.length) {
+ avatarMixer = avatarManager.init(gltf.animations);
+ // Try sit clip, fall back to idle
+ const hasSit = gltf.animations.some((a) => /sit/i.test(a.name));
+ avatarManager.play(hasSit ? 'sit' : 'idle');
+ }
+ }).catch((err) => log.warn('[agent-desk] avatar load failed:', err));
+ }
+
+ // ── live screen feed ──────────────────────────────────────────────────
+ let lastFrameTs = 0;
+ let isDark = true;
+ let destroyed = false;
+
+ const client = createAgentScreenClient(agentId, {
+ onFrame(frame) {
+ if (!frame?.data || frame.ts === lastFrameTs) return;
+ lastFrameTs = frame.ts;
+ isDark = false;
+ const img = new Image();
+ img.onload = () => {
+ ctx.drawImage(img, 0, 0, CW, CH);
+ tex.needsUpdate = true;
+ };
+ img.src = frame.data;
+
+ // Also overlay activity text at the bottom
+ if (frame.activity) {
+ drawActivityOverlay(ctx, frame.activity);
+ tex.needsUpdate = true;
+ }
+ },
+ onDark() {
+ isDark = true;
+ drawWaiting(ctx, agentName);
+ tex.needsUpdate = true;
+ },
+ onError() {
+ // quiet — will reconnect
+ },
+ });
+ client.connect();
+
+ // ── proximity label HUD ──────────────────────────────────────────────
+ let labelEl = null;
+ let isNear = false;
+ const deskWorldPos = new Vector3();
+
+ function updateProximity(playerPos) {
+ group.getWorldPosition(deskWorldPos);
+ const dist = playerPos.distanceTo(deskWorldPos);
+ const shouldBeNear = isNear ? dist < PROXIMITY_HIDE : dist < PROXIMITY_SHOW;
+ if (shouldBeNear !== isNear) {
+ isNear = shouldBeNear;
+ onProximity?.(isNear, agentId, agentName);
+ if (isNear) showLabel(); else hideLabel();
+ }
+ }
+
+ function showLabel() {
+ if (labelEl) return;
+ labelEl = document.createElement('div');
+ labelEl.style.cssText = `
+ position:fixed;bottom:1.8rem;left:50%;transform:translateX(-50%);
+ background:rgba(6,8,15,0.88);backdrop-filter:blur(10px);
+ border:1px solid rgba(91,143,255,0.3);border-radius:12px;
+ padding:0.55rem 1.1rem;font:600 0.85rem system-ui,sans-serif;
+ color:#eef2fa;pointer-events:none;z-index:120;
+ display:flex;align-items:center;gap:0.6rem;
+ animation:asd-fadein 0.2s ease;
+ `;
+ const styleEl = document.createElement('style');
+ styleEl.textContent = `@keyframes asd-fadein{from{opacity:0;transform:translateX(-50%) translateY(8px)}to{opacity:1;transform:translateX(-50%)}}`;
+ document.head.appendChild(styleEl);
+ labelEl.innerHTML = `
+ <span style="width:8px;height:8px;border-radius:50%;background:${isDark ? '#888' : '#3ddc84'};flex:none"></span>
+ <span>Watching <strong>${esc(agentName)}</strong>${isDark ? ' — offline' : ' — LIVE'}</span>
+ <a href="/agent-screen?agentId=${encodeURIComponent(agentId)}" target="_blank"
+ style="color:#7aaeff;text-decoration:none;font-size:0.78rem;pointer-events:auto">
+ Full view ↗
+ </a>
+ `;
+ document.body.appendChild(labelEl);
+ }
+
+ function hideLabel() {
+ labelEl?.remove();
+ labelEl = null;
+ }
+
+ // ── idle canvas animation ─────────────────────────────────────────────
+ let canvasAnimFrame = null;
+ let canvasTick = 0;
+ function animateWaiting() {
+ if (destroyed || !isDark) { canvasAnimFrame = null; return; }
+ canvasTick += 0.016;
+ drawWaiting(ctx, agentName, canvasTick);
+ tex.needsUpdate = true;
+ canvasAnimFrame = requestAnimationFrame(animateWaiting);
+ }
+ canvasAnimFrame = requestAnimationFrame(animateWaiting);
+
+ // ── public interface ──────────────────────────────────────────────────
+ function update(dt, playerPos) {
+ if (destroyed) return;
+ if (avatarMixer) avatarMixer.update(dt);
+ if (!isDark && canvasAnimFrame) {
+ cancelAnimationFrame(canvasAnimFrame);
+ canvasAnimFrame = null;
+ } else if (isDark && !canvasAnimFrame) {
+ canvasAnimFrame = requestAnimationFrame(animateWaiting);
+ }
+ if (playerPos) updateProximity(playerPos);
+ }
+
+ function dispose() {
+ destroyed = true;
+ client.disconnect();
+ hideLabel();
+ if (canvasAnimFrame) cancelAnimationFrame(canvasAnimFrame);
+ scene.remove(group);
+ // Dispose geometries, materials, textures
+ group.traverse((o) => {
+ if (o.geometry) o.geometry.dispose();
+ if (o.material) {
+ if (Array.isArray(o.material)) o.material.forEach((m) => { m.map?.dispose(); m.dispose(); });
+ else { o.material.map?.dispose(); o.material.dispose(); }
+ }
+ });
+ tex.dispose();
+ }
+
+ return { group, update, dispose, getAgentId: () => agentId };
+}
+
+// ── canvas helpers ────────────────────────────────────────────────────────────
+
+function drawWaiting(ctx, agentName, tick = 0) {
+ ctx.fillStyle = PAL.bg;
+ ctx.fillRect(0, 0, CW, CH);
+
+ // Subtle grid
+ ctx.strokeStyle = 'rgba(255,255,255,0.04)';
+ ctx.lineWidth = 1;
+ for (let x = 0; x < CW; x += 80) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, CH); ctx.stroke(); }
+ for (let y = 0; y < CH; y += 80) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(CW, y); ctx.stroke(); }
+
+ // Pulsing circle
+ const pulse = 0.5 + 0.5 * Math.sin(tick * 2.2);
+ const r0 = 32 + pulse * 8;
+ ctx.beginPath();
+ ctx.arc(CW / 2, CH / 2, r0, 0, Math.PI * 2);
+ ctx.strokeStyle = `rgba(91,143,255,${0.15 + pulse * 0.15})`;
+ ctx.lineWidth = 2;
+ ctx.stroke();
+
+ // Inner dot
+ ctx.beginPath();
+ ctx.arc(CW / 2, CH / 2, 10, 0, Math.PI * 2);
+ ctx.fillStyle = `rgba(91,143,255,${0.35 + pulse * 0.35})`;
+ ctx.fill();
+
+ // Agent name
+ ctx.font = `bold 40px system-ui,sans-serif`;
+ ctx.fillStyle = 'rgba(255,255,255,0.7)';
+ ctx.textAlign = 'center';
+ ctx.fillText(agentName, CW / 2, CH / 2 + 90);
+
+ // Status
+ ctx.font = '28px system-ui,sans-serif';
+ ctx.fillStyle = PAL.dim;
+ ctx.fillText('Waiting for activity…', CW / 2, CH / 2 + 140);
+
+ // three.ws watermark
+ ctx.font = '22px system-ui,sans-serif';
+ ctx.fillStyle = 'rgba(255,255,255,0.12)';
+ ctx.textAlign = 'right';
+ ctx.fillText('three.ws', CW - 24, CH - 20);
+}
+
+function drawActivityOverlay(ctx, activity) {
+ const BAR_H = 56;
+ const y = CH - BAR_H;
+ // Translucent bar
+ ctx.fillStyle = 'rgba(6,8,15,0.78)';
+ ctx.fillRect(0, y, CW, BAR_H);
+ // Activity text
+ ctx.font = '26px system-ui,sans-serif';
+ ctx.fillStyle = 'rgba(255,255,255,0.85)';
+ ctx.textAlign = 'left';
+ // Clamp text width
+ const maxW = CW - 48;
+ const text = truncateText(ctx, String(activity), maxW);
+ ctx.fillText(text, 24, y + 36);
+}
+
+function truncateText(ctx, text, maxW) {
+ if (ctx.measureText(text).width <= maxW) return text;
+ let lo = 0, hi = text.length;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (ctx.measureText(text.slice(0, mid) + '…').width <= maxW) lo = mid;
+ else hi = mid - 1;
+ }
+ return text.slice(0, lo) + '…';
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+// ── manager ───────────────────────────────────────────────────────────────────
+
+/**
+ * Manages a set of agent desks in the scene.
+ */
+export function createAgentDeskManager({ scene, camera }) {
+ const desks = new Map(); // agentId → desk handle
+
+ function spawn(deskConfigs) {
+ // Dispose any existing desks not in the new config
+ const incomingIds = new Set(deskConfigs.map((c) => c.agentId));
+ for (const [id, desk] of desks) {
+ if (!incomingIds.has(id)) { desk.dispose(); desks.delete(id); }
+ }
+ // Spawn new desks
+ for (const cfg of deskConfigs) {
+ if (desks.has(cfg.agentId)) continue; // already live
+ const desk = createDesk(scene, cfg);
+ desks.set(cfg.agentId, desk);
+ }
+ }
+
+ function update(dt, playerPos) {
+ for (const desk of desks.values()) desk.update(dt, playerPos);
+ }
+
+ function dispose() {
+ for (const desk of desks.values()) desk.dispose();
+ desks.clear();
+ }
+
+ return { spawn, update, dispose };
+}
+
+/**
+ * Fetch agents that currently have a live screen stream and return desk configs.
+ * Falls back gracefully if Redis is cold or the endpoint is unavailable.
+ */
+export async function fetchLiveAgentDesks() {
+ try {
+ const res = await fetch('/api/agent-screen-active', { headers: { accept: 'application/json' } });
+ if (!res.ok) return [];
+ const j = await res.json();
+ return Array.isArray(j.desks) ? j.desks : [];
+ } catch {
+ return [];
+ }
+}
diff --git a/src/walk.js b/src/walk.js
index 946a87533..7b432a141 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -72,6 +72,7 @@ import { createWalkWalletProximity } from './walk-wallet.js';
import { applyWorldNameplate } from './shared/living-avatar.js';
import { createWalkCapture } from './walk-capture.js';
import { createMarketplaceGallery } from './marketplace-gallery.js';
+import { createAgentDeskManager, fetchLiveAgentDesks } from './walk-agent-desk.js';
// Walk-Browse: on /marketplace-walk the page boots with ?gallery=marketplace and
// the engine becomes a strollable 3D marketplace hall. See marketplace-gallery.js.
@@ -523,6 +524,9 @@ let npcsEnabled = (() => {
/** @type {ReturnType<typeof createWalkNpcs>|null} */
let walkNpcs = null;
+/** @type {ReturnType<typeof createAgentDeskManager>|null} */
+let walkAgentDesks = null;
+
// Avatar accent → trail colour. The walk avatar is a raw GLB, so we read any
// authored meta accent (gltf.userData / scene.userData), else fall back to the
// brand --accent token (handled inside the trail system).
@@ -1537,6 +1541,13 @@ async function loadAvatar() {
});
walkNpcs.setEnabled(npcsEnabled);
+ // Stand up the agent desk system — desks show live agent screens in-world.
+ // Fetches active agents from Redis and spawns one desk per active stream.
+ walkAgentDesks = createAgentDeskManager({ scene, camera, renderer });
+ fetchLiveAgentDesks().then((deskConfigs) => {
+ if (deskConfigs.length) walkAgentDesks.spawn(deskConfigs);
+ }).catch(() => {});
+
// Auto-hide help hints after 5 seconds — fade first, then remove from layout
// so the transition in temporary.html's #walk-help { transition: opacity } plays.
if (helpEl) {
@@ -2443,6 +2454,7 @@ function tick() {
// 4a. Advance the NPC companions' FSMs (greeter waves on approach, wanderer
// roams, guide leads toward a landmark) against the live player position.
if (walkNpcs && avatar) walkNpcs.update(dt, avatarRig.position);
+ if (walkAgentDesks && avatar) walkAgentDesks.update(dt, avatarRig.position);
// 4b. Animate the coin totem (billboard + bob + ring spin) when present.
if (coinTotem) coinTotem.update(dt);
diff --git a/vercel.json b/vercel.json
index f1c8f740c..b674bf4b5 100644
--- a/vercel.json
+++ b/vercel.json
@@ -24,7 +24,7 @@
"{api/agents/networth,api/avatars/from-forge}.js": {
"maxDuration": 60
},
- "{api/club/tips-stream,api/feed-stream,api/pump/trades-stream,api/oracle/stream,api/oracle/action-stream,api/sniper/stream,api/sniper/radar-stream}.js": {
+ "{api/club/tips-stream,api/feed-stream,api/pump/trades-stream,api/oracle/stream,api/oracle/action-stream,api/sniper/stream,api/sniper/radar-stream,api/agent-screen-stream}.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
},
@@ -2406,6 +2406,18 @@
"src": "/api/sniper/radar-stream",
"dest": "/api/sniper/radar-stream.js"
},
+ {
+ "src": "/api/agent-screen-stream",
+ "dest": "/api/agent-screen-stream.js"
+ },
+ {
+ "src": "/api/agent-screen-push",
+ "dest": "/api/agent-screen-push.js"
+ },
+ {
+ "src": "/api/agent-screen-active",
+ "dest": "/api/agent-screen-active.js"
+ },
{
"src": "/api/sniper/radar",
"dest": "/api/sniper/radar.js"
@@ -2981,6 +2993,10 @@
"src": "/agent/([^/]+)/wallet/?",
"dest": "/agent-wallet.html"
},
+ {
+ "src": "/agent-screen/?",
+ "dest": "/agent-screen.html"
+ },
{
"src": "/agent/index.html",
"dest": "/agent/index.html"
diff --git a/vite.config.js b/vite.config.js
index 73657579d..709b25d31 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -370,6 +370,7 @@ const appConfig = {
'embed-walk': resolve(__dirname, 'pages/embed-walk.html'),
'agent-embed': resolve(__dirname, 'pages/agent-embed.html'),
'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),
+ 'agent-screen': resolve(__dirname, 'pages/agent-screen.html'),
'agent-wallet': resolve(__dirname, 'pages/agent-wallet.html'),
guardian: resolve(__dirname, 'pages/guardian.html'),
launches: resolve(__dirname, 'pages/launches.html'),