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: implement agent-screen control functionality with real-browser proofing

nirholasa4a50d96d3e1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9471b56d8..24705923f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,11 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-07-22
+
+- **Animation preview plays again on every clip page** — Opening an animation from the marketplace (Arm Flex, Facepalm, Superhero Jump, and the rest) showed an empty black stage where the moving avatar should be. Two things were wrong: the preview was pointed at a skeleton-only file with no body to draw, and the 3D canvas was collapsing to zero height inside its frame. Both are fixed, so every clip page now shows a real avatar performing the animation, framed and lit, with Replay to watch it again. (`/marketplace?tab=animations`) `[fix]`
+- **Take the wheel: drive your agent's computer** — Every agent already had a live screen you could watch. Now, if you own the agent, you can grab the wheel of its real browser and drive it yourself: mouse, click and drag, scroll, keyboard, and a URL bar to go anywhere. Open your agent's screen, wait for it to go live, and click Take control. Your agent steps aside while you drive and picks its task back up the moment you let go. It is owner-only, and the browser you drive holds no wallet or keys, so control can never sign a transaction or move funds. This is the first step toward giving every agent its own computer that you and the agent can both operate. (`/agent-screen`) `[feature]`
+
## 2026-07-21
- **Cookbook: self-correcting 3D with function calling** (`/cookbook`) — An executable tutorial: an AI art director turns a one-line brief into a themed set of real 3D props with parallel function calls, inspects each render with vision, and rebuilds what fails. Read it with interactive galleries, or download the notebook and run it.
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 9384380e1..d758936f0 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -55,6 +55,7 @@ bottom.
| Verifiable 3D provenance (content credentials) | Spec [specs/PROVENANCE_3D.md](specs/PROVENANCE_3D.md), pure core [api/_lib/provenance-3d.js](api/_lib/provenance-3d.js), Solana anchor [api/_lib/provenance-anchor.js](api/_lib/provenance-anchor.js), MCP tools [api/_mcp3d/tools/provenance.js](api/_mcp3d/tools/provenance.js) (`verify_provenance` free, `anchor_provenance` paid $0.05), free REST verify [api/provenance.js](api/provenance.js) `→ /api/provenance`, viewer badge [public/viewer.html](public/viewer.html), docs [docs/provenance.md](docs/provenance.md). | Live (verify) · anchor gated on issuer key + devnet funds | C2PA-style signed content credentials for AI 3D: creator, prompt, model/provider, lineage, timestamp, and the GLB's sha256, ed25519-signed by the three.ws issuer with the credential hash anchored on Solana. Free public `verify_provenance` / `GET /api/provenance?src=…` recompute the hash and return `verified | tampered | unknown` (a single changed byte → tampered); the verify path and response are coin-clean (both stores). `anchor_provenance` signs + writes the SPL Memo anchor + stores the credential in R2. Tests: [tests/provenance-3d.test.js](tests/provenance-3d.test.js). Evidence: [prompts/store-submissions/_generated/provenance/](prompts/store-submissions/_generated/provenance/). Store-submission prompt 19. |
| Sperax partnership + SperaxOS plugin | [pages/sperax.html](pages/sperax.html) `→ /sperax`, plugin [public/sperax/](public/sperax/README.md), manifest `→ /.well-known/sperax-plugin.json`, tools [api/chat-plugin/[tool].js](api/chat-plugin/%5Btool%5D.js) `→ /api/chat-plugin/*`, panel `→ /sperax/iframe/` | In-repo · Live | Partnership landing for the SperaxOS integration: three.ws ships as a standalone `plugin.delivery` plugin that gives a SperaxOS agent an embodied 3D avatar (speak/gesture/emote/render_agent), bound to an ERC-8004 identity, settling over Base x402. Launch offer: free AI credits for three.ws users on [chat.sperax.io](https://chat.sperax.io) — page explains what it is and how to claim. Blog: [/blog/three-ws-speraxusd-integration](blog/three-ws-speraxusd-integration.html) |
| Live Agents wall (mission control) | [pages/agents-live.html](pages/agents-live.html) + [src/agents-live.js](src/agents-live.js) `→ /agents-live` | In-repo · roster [api/agents/public.js](api/agents/public.js) (`sort=live`), per-agent SSE [api/agent-screen-stream.js](api/agent-screen-stream.js) | Real-time grid of every meaningful agent, ranked by most-recent on-chain/skill action (never-used placeholders suppressed). Each card streams a live caster feed when watched, else its real `agent_actions` as a terminal + an "active Nm ago" recency chip. Layers: showrunner spotlight ([src/showrunner.js](src/showrunner.js)), reputation arena ([src/agents-live-arena.js](src/agents-live-arena.js)), platform ticker ([src/theater-feed.js](src/theater-feed.js)) |
+| Take the wheel (owner drives the agent's computer) | Client [src/agent-screen-control.js](src/agent-screen-control.js) mounted in [src/agent-screen.js](src/agent-screen.js) `→ /agent-screen`; API [api/agent-screen-control.js](api/agent-screen-control.js) (lease + input) + [api/agent-screen-control-drain.js](api/agent-screen-control-drain.js) (caster read side); caster dispatch [workers/agent-screen-pool/control.js](workers/agent-screen-pool/control.js); shared sanitizer [src/shared/agent-screen-control.js](src/shared/agent-screen-control.js) | In-repo · Live · doc [docs/agent-screen-control.md](docs/agent-screen-control.md) | The reverse of the frame stream: an agent's OWNER can grab the wheel of its live cast browser and drive it, real mouse, drag, scroll, keyboard, and navigation. Owner-only (session ownership, not the public watch/react channel); acquiring mints a short-lived capability LEASE token used as a bearer for the high-frequency input stream (no per-event CSRF). Events travel normalized (0..1) and are sanitized + range-clamped on the API boundary; nav is SSRF-guarded (no loopback/private/metadata). The caster pool drains queued events into its real Playwright page and pauses its own autonomous task while a human holds the wheel so the two never fight over the cursor. The cast browser holds no wallet or keys, so driving it cannot move funds, that boundary is what makes remote control safe. Tests: [tests/agent-screen-control.test.js](tests/agent-screen-control.test.js) (21 unit), [scripts/agent-screen-control-proof.mjs](scripts/agent-screen-control-proof.mjs) (real Chromium dispatch) |
| X/Twitter automation toolkit | [nirholas/XActions](https://github.com/nirholas/XActions) (external repo, also on npm as `xactions`) | External | Formerly vendored in-repo; removed 2026-07-03 — install from npm or use the upstream repo |
| Agora — the Commons (living economy) | [pages/agora.html](pages/agora.html) + [src/agora/](src/agora) `→ /agora`, life engine [workers/agora-citizens/](workers/agora-citizens), read model [api/agora/[action].js](api/agora/[action].js) | In-repo · devnet AgenC | Watchable 3D world where agent + human citizens post, claim, work, prove and earn $THREE on-chain. **Play mode** ("Enter the Commons") makes it walkable GTA-style — your avatar walks the square among the working NPC citizens, other humans appear live over the `agora_world` Colyseus room, and walking up to a citizen (proximity → E) opens its passport: [src/agora/player-mode.js](src/agora/player-mode.js), pure math [src/agora/player-logic.js](src/agora/player-logic.js), room [multiplayer/src/rooms/AgoraRoom.js](multiplayer/src/rooms/AgoraRoom.js). Play mode also has an opt-in **"Record on-chain (BNB testnet)"** toggle (OFF by default) that gaslessly commits your moves to the `WorldMoves` contract every ~block via MegaFuel (self-pay fallback) and renders other on-chain players as lightweight ghost markers read back from real `Moved` events: [src/agora/onchain-presence.js](src/agora/onchain-presence.js), sender [src/bnb/move-sender.js](src/bnb/move-sender.js), event reader [src/bnb/world-presence-reader.js](src/bnb/world-presence-reader.js), pure ghost interpolation [src/bnb/onchain-ghosts.js](src/bnb/onchain-ghosts.js), server relay lib [api/_lib/bnb/world-moves.js](api/_lib/bnb/world-moves.js), config endpoint [api/bnb/world-config.js](api/bnb/world-config.js). WorldMoves contract: [contracts/src/WorldMoves.sol](contracts/src/WorldMoves.sol) (code-complete + anvil-fork-proven; public BSC testnet deploy pending a funded deployer key — see `contracts/DEPLOYMENTS.md`). **Arena** (Competitive tasks — citizens race, first valid proof wins the whole escrow) at [src/agora/arena.js](src/agora/arena.js); **Guilds** (Collaborative tasks — contributors split the reward) at [src/agora/guild.js](src/agora/guild.js), both live-driven by [api/agora/task](api/agora/[action].js). Spec: [docs/agora.md](docs/agora.md) |
| `/play` in-game economy (cash, bank/ATM, vendors, $THREE boutique) | Client: [src/game/coincommunities.js](src/game/coincommunities.js) `→ /play`, general-store/bank NPCs [src/game/npc/economy-npcs.js](src/game/npc/economy-npcs.js), store/bank UI [src/game/economy-ui.js](src/game/economy-ui.js), on-chain purchase flow [src/game/boutique-purchase.js](src/game/boutique-purchase.js), wardrobe [src/game/play-systems.js](src/game/play-systems.js). Server: [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) (store/bank/boutique handlers), price tables [multiplayer/src/shop.js](multiplayer/src/shop.js), purse/bank model [multiplayer/src/economy.js](multiplayer/src/economy.js), on-chain settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) | In-repo | The GTA-style open world's real economy (W04 of the World Online program, [prompts/agent-briefs/W-world-online/W00-program-overview.md](prompts/agent-briefs/W-world-online/W00-program-overview.md)). Walk up to a General Store clerk (E) to buy tools/consumables or sell gathered goods for cash, server-priced and validated every time; walk up to the Bank Teller to deposit cash into a protected balance (survives a death drop) or withdraw it. Premium wardrobe cosmetics unlock with a real on-chain `$THREE` payment from the player's connected Solana wallet — the server only grants the item after re-verifying the confirmed transaction on RPC. Distinct from the separate USDC/x402 avatar-shop rail ([api/x402/cosmetic-purchase.js](api/x402/cosmetic-purchase.js)), which sells a different catalog for the standalone character creator. |
diff --git a/api/agent-screen-control-drain.js b/api/agent-screen-control-drain.js
new file mode 100644
index 000000000..9cf83ddac
--- /dev/null
+++ b/api/agent-screen-control-drain.js
@@ -0,0 +1,80 @@
+// POST /api/agent-screen-control-drain, the caster pool's read side of the control
+// channel. The pool worker (workers/agent-screen-pool) calls this on a fast tick
+// for the agents it is currently casting; for each one it learns whether a human
+// holds the wheel (an active lease) and pops that agent's queued input events to
+// dispatch into the live Chromium page.
+//
+// Auth: the shared SCREEN_WORKER_SECRET (same bearer the pool uses to push frames).
+// This endpoint never touches user sessions, it is machine-to-machine only.
+//
+// Body: { agentIds: string[] } (bounded)
+// Reply: { agents: { [agentId]: { manual: boolean, events: object[] } } }
+// manual, a live control lease exists (pause the autonomous task)
+// events, sanitized input events in dispatch order (oldest first), drained
+
+import { timingSafeEqual } from 'node:crypto';
+import { cors, error, json, method, readJson } from './_lib/http.js';
+import { extractBearer } from './_lib/auth.js';
+import { getRedis } from './_lib/redis.js';
+
+const WORKER_SECRET = process.env.SCREEN_WORKER_SECRET || '';
+const MAX_AGENTS = 32; // the pool caps concurrent casters well below this
+const DRAIN_CAP = 200; // matches the producer's QUEUE_CAP
+
+function isPoolWorker(bearer) {
+ if (!bearer || !WORKER_SECRET || WORKER_SECRET.length < 16) return false;
+ const a = Buffer.from(bearer);
+ const b = Buffer.from(WORKER_SECRET);
+ return a.length === b.length && timingSafeEqual(a, b);
+}
+
+const leaseKey = (id) => `agent:screen:${id}:ctl:lease`;
+const queueKey = (id) => `agent:screen:${id}:ctl:q`;
+
+export default async function handleAgentScreenControlDrain(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ if (!isPoolWorker(extractBearer(req))) {
+ return error(res, 401, 'unauthorized', 'pool worker secret required');
+ }
+
+ let body;
+ try {
+ body = await readJson(req, 8_000);
+ } catch {
+ return error(res, 400, 'invalid_body', 'request body must be valid JSON');
+ }
+
+ const ids = Array.isArray(body?.agentIds)
+ ? [...new Set(body.agentIds.filter((s) => typeof s === 'string' && s))].slice(0, MAX_AGENTS)
+ : [];
+ if (!ids.length) return json(res, 200, { agents: {} });
+
+ const r = getRedis();
+ if (!r) return error(res, 503, 'redis_unavailable', 'control channel offline');
+
+ const agents = {};
+ await Promise.all(ids.map(async (id) => {
+ let manual = false;
+ let events = [];
+ try {
+ const lease = await r.get(leaseKey(id));
+ manual = !!lease;
+ if (manual) {
+ // Drain oldest-first (producer rpush → head is oldest). lpop with a
+ // count removes and returns them atomically.
+ const popped = await r.lpop(queueKey(id), DRAIN_CAP).catch(() => null);
+ const list = Array.isArray(popped) ? popped : popped != null ? [popped] : [];
+ events = list
+ .map((s) => { try { return typeof s === 'string' ? JSON.parse(s) : s; } catch { return null; } })
+ .filter(Boolean);
+ }
+ } catch {
+ /* a Redis blip for one agent must not fail the whole batch */
+ }
+ agents[id] = { manual, events };
+ }));
+
+ return json(res, 200, { agents });
+}
diff --git a/api/agent-screen-control.js b/api/agent-screen-control.js
new file mode 100644
index 000000000..7e80457ca
--- /dev/null
+++ b/api/agent-screen-control.js
@@ -0,0 +1,157 @@
+// POST /api/agent-screen-control, take the wheel of an agent's live cast browser.
+//
+// The frame stream (/api/agent-screen-stream) lets anyone WATCH an agent work.
+// This is the reverse channel: the agent's OWNER can drive its real cast browser
+// with mouse, scroll, keyboard, and navigation. Input events queue in Redis; the
+// caster pool (workers/agent-screen-pool) drains them and dispatches them into the
+// live Chromium page, and pauses its own autonomous task while a human holds the
+// wheel so the two never fight over the cursor.
+//
+// Security model:
+// • Owner-only. Watching is public; driving is not. Ownership is checked once,
+// at lease acquisition, against agent_identities.user_id.
+// • Capability lease. Acquiring returns a short-lived bearer LEASE TOKEN (not a
+// JWT) scoped to exactly one agent's control for LEASE_TTL seconds. Every
+// input POST authenticates with that token, so the high-frequency channel
+// needs no per-event CSRF round trip, and the capability expires on its own.
+// • The cast browser holds NO wallet or keys. Driving it cannot sign a
+// transaction or move funds, money stays behind the agent runtime and the
+// on-chain wall. This is the property that makes remote control safe to ship.
+// • Nav is host-guarded (no loopback / private / metadata) and every event is
+// sanitized + range-clamped on this boundary (see src/shared/agent-screen-control.js).
+//
+// Actions (JSON body { agentId, action, ... }):
+// acquire , session + CSRF + ownership → { leaseToken, viewport, holdMs }
+// input , bearer lease token; { events: [...] } → queues sanitized events
+// renew , bearer lease token; refreshes the lease TTL (idle hold)
+// release , bearer lease token; drops the lease immediately
+
+import crypto from 'node:crypto';
+import { cors, error, json, method, rateLimited, readJson } from './_lib/http.js';
+import { getSessionUser, extractBearer } from './_lib/auth.js';
+import { requireCsrf } from './_lib/csrf.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { getRedis } from './_lib/redis.js';
+import { sql } from './_lib/db.js';
+import { sanitizeEvents } from '../src/shared/agent-screen-control.js';
+
+const LEASE_TTL_S = 15; // lease dies this long after the last input/renew
+const QUEUE_TTL_S = 15; // queued events self-expire if the caster is gone
+const QUEUE_CAP = 200; // most-recent events kept if a driver outruns the drain
+// The streamed viewport the caster renders at (kept in sync with the pool's
+// VIEWPORT_W/H). The client needs it to label the URL bar / status; coordinates
+// travel normalized (0..1) so an exact match is not load-bearing.
+const VIEWPORT = { width: 1280, height: 720 };
+
+const leaseKey = (id) => `agent:screen:${id}:ctl:lease`;
+const queueKey = (id) => `agent:screen:${id}:ctl:q`;
+
+async function readLease(r, agentId) {
+ try {
+ const raw = await r.get(leaseKey(agentId));
+ if (!raw) return null;
+ return typeof raw === 'string' ? JSON.parse(raw) : raw;
+ } catch {
+ return null;
+ }
+}
+
+function timingEqual(a, b) {
+ if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false;
+ try {
+ return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
+ } catch {
+ return false;
+ }
+}
+
+export default async function handleAgentScreenControl(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.apiIp(clientIp(req), { limit: 1200, window: '60s' });
+ if (!rl.success) return rateLimited(res, rl, 'control rate limit exceeded');
+
+ let body;
+ try {
+ body = await readJson(req, 64_000);
+ } catch {
+ return error(res, 400, 'invalid_body', 'request body must be valid JSON under 64 KB');
+ }
+
+ const agentId = typeof body?.agentId === 'string' ? body.agentId.trim() : '';
+ const action = body?.action;
+ if (!agentId) return error(res, 400, 'missing_agent_id', 'agentId is required');
+ if (!['acquire', 'input', 'renew', 'release'].includes(action)) {
+ return error(res, 400, 'bad_action', 'action must be acquire | input | renew | release');
+ }
+
+ const r = getRedis();
+ if (!r) return error(res, 503, 'redis_unavailable', 'control channel offline');
+
+ // ── acquire: prove ownership (session + CSRF), mint a capability lease ───────
+ if (action === 'acquire') {
+ const auth = await getSessionUser(req, res);
+ const userId = auth?.id;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in to drive this agent');
+ if (!(await requireCsrf(req, res, userId))) return; // sends 403 on failure
+
+ const [own] = await sql`
+ SELECT id FROM agent_identities
+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
+ LIMIT 1
+ `.catch(() => []);
+ if (!own) return error(res, 403, 'forbidden', 'you do not own this agent');
+
+ // A different owner-session may already hold the wheel. Same user (another
+ // tab) is allowed to take over their own lease.
+ const existing = await readLease(r, agentId);
+ if (existing && existing.userId && existing.userId !== userId) {
+ return error(res, 409, 'in_use', 'another session is driving this agent');
+ }
+
+ const leaseToken = crypto.randomBytes(24).toString('base64url');
+ const record = JSON.stringify({ userId, token: leaseToken, ts: Date.now() });
+ await r.set(leaseKey(agentId), record, { ex: LEASE_TTL_S });
+ return json(res, 200, {
+ ok: true,
+ leaseToken,
+ viewport: VIEWPORT,
+ holdMs: LEASE_TTL_S * 1000,
+ });
+ }
+
+ // ── input / renew / release: authenticate with the lease token ──────────────
+ const token = extractBearer(req);
+ if (!token) return error(res, 401, 'no_lease', 'control lease token required');
+ const lease = await readLease(r, agentId);
+ if (!lease || !timingEqual(String(lease.token || ''), token)) {
+ return error(res, 401, 'lease_invalid', 'control lease expired or invalid, re-acquire the wheel');
+ }
+
+ if (action === 'release') {
+ await r.del(leaseKey(agentId)).catch(() => {});
+ return json(res, 200, { ok: true, released: true });
+ }
+
+ // Refresh the lease TTL on any input/renew so an active driver keeps the wheel.
+ const refreshed = JSON.stringify({ ...lease, ts: Date.now() });
+ await r.set(leaseKey(agentId), refreshed, { ex: LEASE_TTL_S });
+
+ if (action === 'renew') return json(res, 200, { ok: true, renewed: true });
+
+ // action === 'input'
+ const events = sanitizeEvents(body?.events);
+ if (!events.length) return json(res, 200, { ok: true, accepted: 0 });
+
+ // Per-agent input rate limit, bounds how fast one driver can drive one agent.
+ const arl = await limits.apiIp(`ctl:${agentId}`, { limit: 900, window: '60s' });
+ if (!arl.success) return rateLimited(res, arl, 'per-agent control rate limit exceeded');
+
+ const payload = events.map((e) => JSON.stringify(e));
+ await r.rpush(queueKey(agentId), ...payload);
+ await r.ltrim(queueKey(agentId), -QUEUE_CAP, -1);
+ await r.expire(queueKey(agentId), QUEUE_TTL_S);
+
+ return json(res, 200, { ok: true, accepted: events.length });
+}
diff --git a/data/changelog.json b/data/changelog.json
index e2185e3ab..ca9bba2f5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$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-07-22",
+ "title": "Animation preview plays again on every clip page",
+ "summary": "Opening an animation from the marketplace (Arm Flex, Facepalm, Superhero Jump, and the rest) showed an empty black stage where the moving avatar should be. Two things were wrong: the preview was pointed at a skeleton-only file with no body to draw, and the 3D canvas was collapsing to zero height inside its frame. Both are fixed, so every clip page now shows a real avatar performing the animation, framed and lit, with Replay to watch it again.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/marketplace?tab=animations"
+ },
+ {
+ "date": "2026-07-22",
+ "title": "Take the wheel: drive your agent's computer",
+ "summary": "Every agent already had a live screen you could watch. Now, if you own the agent, you can grab the wheel of its real browser and drive it yourself: mouse, click and drag, scroll, keyboard, and a URL bar to go anywhere. Open your agent's screen, wait for it to go live, and click Take control. Your agent steps aside while you drive and picks its task back up the moment you let go. It is owner-only, and the browser you drive holds no wallet or keys, so control can never sign a transaction or move funds. This is the first step toward giving every agent its own computer that you and the agent can both operate.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
{
"date": "2026-07-21",
"title": "Zen mode in Play: hide the whole interface with one key",
diff --git a/docs/agent-screen-control.md b/docs/agent-screen-control.md
new file mode 100644
index 000000000..376164fcf
--- /dev/null
+++ b/docs/agent-screen-control.md
@@ -0,0 +1,119 @@
+# Take the wheel: drive your agent's computer
+
+Every agent on three.ws has a live screen. On the [agent screen](https://three.ws/agent-screen) and the [live wall](https://three.ws/agents-live) you can *watch* an agent do real web work in a real browser: navigate to a site, type into a search box, read back the results. This page is about the other half, **driving it yourself**.
+
+If you own the agent, you can grab the wheel of its live cast browser and control it directly: real mouse, click and drag, scroll, keyboard, and navigation. The agent's autonomous task steps aside while you drive, and picks back up the moment you let go.
+
+This is the first slice of a larger idea, giving every agent its own computer that both the agent and its owner can operate. Today that computer is a cloud browser; the same control channel is what a full desktop will ride on next.
+
+---
+
+## Try it (no code)
+
+1. Open your agent's screen: `https://three.ws/agent-screen?agentId=<your-agent-id>`, or click through from the [live wall](https://three.ws/agents-live).
+2. Sign in as the agent's owner. A **Take control** button appears in the top-left of the screen (owners only, it is not shown to other viewers).
+3. Wait for the screen to go **LIVE** (a caster spins up a real browser for any agent someone is watching), then click **Take control**.
+4. The screen gets a green ring and you are driving:
+ - **Move / click / drag** anywhere on the screen.
+ - **Scroll** with your mouse wheel or trackpad.
+ - **Type** with your keyboard; use the on-screen **URL bar** to navigate anywhere, and the **←** / **⟳** buttons for back and reload.
+5. Click **Release control** (or just close the tab) to hand the browser back to the agent.
+
+While you hold the wheel the agent stops its own task so you are not fighting over the cursor. A line in the activity log records the handoff both ways.
+
+---
+
+## The safety model
+
+Remote-controlling a computer is exactly as dangerous as it sounds, so the design is safety-first.
+
+- **Owner-only.** Watching an agent is public. Driving is not. Control is gated on agent ownership (the same check that guards trading and wallet actions), verified when you take the wheel.
+- **The cast browser holds no wallet and no keys.** This is the property that makes remote control safe to ship: the browser you drive is a sandboxed, throwaway Chromium with no access to the agent's custodial wallet or signing keys. Driving it **cannot** sign a transaction, move funds, or touch the chain. Money stays behind the agent runtime and the on-chain wall, no matter what you (or a compromised session) do in the browser.
+- **A short-lived capability lease, not your session.** Taking the wheel mints a random **lease token** scoped to exactly one agent's control for a few seconds, renewed while you drive and dropped when you release. The high-frequency input stream authenticates with that token, so it never rides your login cookie, and the capability expires on its own if you walk away.
+- **Every event is sanitized at the boundary.** Coordinates are range-clamped, keys and typed text are whitelisted and length-bounded, and navigation is **SSRF-guarded**: the browser can never be steered to `localhost`, a private range, or a cloud metadata endpoint. Only public `http(s)` destinations are allowed.
+- **One driver at a time.** A live lease blocks a second session from grabbing the same agent's wheel.
+
+---
+
+## For developers: the control API
+
+Two endpoints back the feature. You will not normally call them by hand (the [/agent-screen](https://three.ws/agent-screen) UI does), but they are a clean, documented surface.
+
+### `POST /api/agent-screen-control`
+
+All calls take a JSON body with `agentId` and an `action`.
+
+**Acquire the wheel** (session cookie + `X-CSRF-Token`, owner only):
+
+```bash
+# 1. get a CSRF token (returns { token })
+curl -s https://three.ws/api/csrf-token -b cookies.txt
+
+# 2. acquire
+curl -s https://three.ws/api/agent-screen-control \
+ -b cookies.txt -H 'x-csrf-token: <token>' \
+ -H 'content-type: application/json' \
+ -d '{ "agentId": "<uuid>", "action": "acquire" }'
+# → { "ok": true, "leaseToken": "…", "viewport": { "width": 1280, "height": 720 }, "holdMs": 15000 }
+```
+
+**Send input** (bearer = the lease token; no CSRF needed):
+
+```bash
+curl -s https://three.ws/api/agent-screen-control \
+ -H 'authorization: Bearer <leaseToken>' \
+ -H 'content-type: application/json' \
+ -d '{ "agentId": "<uuid>", "action": "input", "events": [
+ { "t": "click", "x": 0.5, "y": 0.4, "button": "left" },
+ { "t": "text", "text": "hello" },
+ { "t": "key", "key": "Enter" }
+ ] }'
+# → { "ok": true, "accepted": 3 }
+```
+
+`renew` refreshes an idle lease; `release` drops it immediately. Both take the bearer lease token.
+
+**Event shapes** (coordinates are normalized `0..1` against the streamed viewport):
+
+| `t` | fields | meaning |
+|-----|--------|---------|
+| `move` | `x, y` | move the cursor |
+| `down` / `up` | `x, y, button` | press / release (drag = down, moves, up) |
+| `click` | `x, y, button` | click |
+| `scroll` | `x, y, dy` | wheel by `dy` px (clamped) |
+| `key` | `key` | one non-text key: `Enter`, `Backspace`, `Tab`, `Delete`, `Escape`, arrows, `Home`/`End`, `PageUp`/`PageDown` |
+| `text` | `text` | type literal characters (≤ 256) |
+| `nav` | `url` | navigate (public `http(s)` only) |
+| `back` / `forward` / `reload` | (none) | history / reload |
+
+`button` is `left` (default), `right`, or `middle`. Unknown event types, out-of-range values, non-whitelisted keys, and blocked nav targets are dropped silently; a fat-fingered event never fails the rest of the gesture.
+
+### `POST /api/agent-screen-control-drain`
+
+The caster pool's read side, machine-to-machine only (authenticated with `SCREEN_WORKER_SECRET`, the same secret the pool uses to push frames). It takes `{ agentIds: [...] }` and returns, per agent, whether a human holds the wheel and the queued input events to dispatch, popping them from the queue. Ordinary clients never call this.
+
+---
+
+## How it fits together
+
+```
+ you (owner) three.ws caster pool (Chromium)
+ ─────────── ──────── ──────────────────────
+ Take control ──acquire──▶ mint lease (Redis)
+ mouse/keys ───input(batch)─▶ sanitize → queue (Redis)
+ ◀─drain── poll every ~250ms
+ ──events─▶ dispatch into the real page
+ watch it move ◀──── frame stream (SSE) ◀──────── screenshot after each action
+```
+
+The frame stream ([how the live screen works](./agent-shell.md)) carries pixels out; this control channel carries input back. Same agent, same browser, opposite directions.
+
+---
+
+## Limits and what is next
+
+- **Latency** is a few hundred milliseconds (a queued, polled channel), which feels like a responsive remote desktop for browsing, not like a local mouse. A future WebRTC transport will tighten it for a full desktop.
+- **One browser tab** per agent today. Full app / shell / file access is the next slice, on the same control channel with a streamed Linux desktop.
+- **DNS-rebinding** on `nav` is out of scope for this version; the host guard checks the literal hostname, and the browser runs with no credentials to lose.
+
+Related: [the agent shell and live screen](./agent-shell.md), the [live agents wall](https://three.ws/agents-live).
diff --git a/docs/start-here.md b/docs/start-here.md
index 2b506fd05..5132fc4f8 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -72,6 +72,7 @@ Curious what happens between the prompt and the model? [How the Forge works](./h
- **Creating your first agent** → Go to [/start](/start) — a 5-step wizard walks you through it
- **Want your avatar to sign in ASL?** → [Sign language](./sign-language.md) — fingerspell any word in the Animation Studio, share it as a link (`/pose?spell=HELLO`), and turn on signed chat replies with the 🤟 toggle or the `sign-language` embed attribute
- **Wondering who the little character in the corner is?** → [The agent shell](./agent-shell.md) — every visitor gets a named agent in the first five seconds (claim it to make it real), the ⌘K palette runs real commands (`forge …`, `digest`, `price btc`, `ask …`), and shell pages navigate without ever unloading your agent
+- **Want to drive your agent's computer yourself?** → [Take the wheel](./agent-screen-control.md), every agent has a live screen you can watch on [/agent-screen](https://three.ws/agent-screen); if you own it, click **Take control** to grab the wheel of its real cast browser (mouse, scroll, keyboard, navigation). The agent stands aside while you drive, and the browser holds no wallet, so control can never move funds
- **Meeting avatars in the worlds?** → Press <kbd>I</kbd> on anyone in `/play`, `/city`, a coin world, or `/agora` to see who they are — the [avatar inspector](./avatar-inspector.md) shows their reputation, wallet, and profile
- **Following creators?** → [The social layer](./social-layer.md): follow anyone from their `/u/:username` portfolio, watch their work land on [/feed](/feed), climb the [/rankings](/rankings) leaderboards with streaks and badges, get bell notifications for remixes, DMs, and coin graduations, and search everything at once on [/search](/search)
- **Placing agents in the real world?** → [IRL](./irl.md): pin an agent at a real GPS spot from your phone, and anyone who physically walks up can see it, talk to it, and pay it. Real crypto can be escrowed at places ([Money Drops](./irl.md#money-drops)) and agents sign proofs that you were really there ([World Lines](./irl.md#world-lines))
diff --git a/pages/agent-screen.html b/pages/agent-screen.html
index d77e18586..57f62c3a6 100644
--- a/pages/agent-screen.html
+++ b/pages/agent-screen.html
@@ -262,6 +262,150 @@
border-radius: 0;
}
+ /* ── Take-the-wheel control (owner-only) ─────────────────────────── */
+ .asc-ctl-bar {
+ position: absolute;
+ top: 12px;
+ left: 12px;
+ z-index: 8;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ max-width: calc(100% - 24px);
+ transition: opacity 0.2s ease, transform 0.2s ease;
+ }
+ body.asc-zen .asc-ctl-bar {
+ opacity: 0;
+ pointer-events: none;
+ transform: translateY(-6px);
+ }
+ .asc-ctl-toggle {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ padding: 7px 12px;
+ border-radius: 12px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: rgba(10, 10, 14, 0.66);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ color: #e7e7ee;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.4);
+ transition: border-color 0.18s ease, background 0.18s ease, color 0.18s ease;
+ }
+ .asc-ctl-toggle:hover {
+ border-color: rgba(139, 92, 246, 0.5);
+ background: rgba(18, 16, 28, 0.82);
+ }
+ .asc-ctl-toggle:focus-visible {
+ outline: 2px solid rgba(139, 92, 246, 0.7);
+ outline-offset: 2px;
+ }
+ .asc-ctl-toggle:disabled {
+ opacity: 0.55;
+ cursor: progress;
+ }
+ .asc-ctl-toggle.driving {
+ border-color: rgba(52, 211, 153, 0.55);
+ background: rgba(6, 30, 24, 0.82);
+ color: #6ee7b7;
+ }
+ .asc-ctl-ico {
+ font-size: 14px;
+ line-height: 1;
+ }
+ .asc-ctl-drive {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 8px;
+ border-radius: 12px;
+ border: 1px solid rgba(52, 211, 153, 0.35);
+ background: rgba(8, 12, 12, 0.72);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.4);
+ min-width: 0;
+ }
+ .asc-ctl-drive[hidden] {
+ display: none;
+ }
+ .asc-ctl-nav {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 26px;
+ border-radius: 8px;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ background: rgba(255, 255, 255, 0.05);
+ color: #cbd5e1;
+ font-size: 14px;
+ line-height: 1;
+ cursor: pointer;
+ flex-shrink: 0;
+ transition: background 0.15s ease, color 0.15s ease;
+ }
+ .asc-ctl-nav:hover {
+ background: rgba(255, 255, 255, 0.12);
+ color: #fff;
+ }
+ .asc-ctl-urlform {
+ display: flex;
+ min-width: 0;
+ }
+ .asc-ctl-url {
+ width: clamp(140px, 32vw, 320px);
+ max-width: 100%;
+ padding: 5px 9px;
+ border-radius: 8px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: rgba(0, 0, 0, 0.32);
+ color: #e7e7ee;
+ font: inherit;
+ font-size: 12.5px;
+ }
+ .asc-ctl-url:focus {
+ outline: none;
+ border-color: rgba(52, 211, 153, 0.6);
+ }
+ .asc-ctl-hint {
+ font-size: 12px;
+ color: rgba(110, 231, 183, 0.85);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .asc-ctl-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 6;
+ cursor: crosshair;
+ touch-action: none;
+ background: transparent;
+ }
+ .asc-ctl-overlay[hidden] {
+ display: none;
+ }
+ /* A soft ring while driving signals the screen is now interactive. */
+ .asc-ctl-overlay:not([hidden]) {
+ box-shadow: inset 0 0 0 2px rgba(52, 211, 153, 0.45);
+ border-radius: 4px;
+ }
+ .asc-ctl-overlay:focus {
+ outline: none;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .asc-ctl-bar,
+ .asc-ctl-toggle {
+ transition: none;
+ }
+ }
+
.asc-screen-overlay {
position: absolute;
inset: 0;
diff --git a/pages/features.html b/pages/features.html
index a3b758eaf..d7601d81d 100644
--- a/pages/features.html
+++ b/pages/features.html
@@ -714,7 +714,7 @@
<div class="feat-embed-widget-bubble">
<span class="feat-embed-widget-name" data-i18n="features.3d_agent">3D Agent</span>
<model-viewer
- src="/animations/idle_female_jan25.glb"
+ src="/avatars/cz.glb"
auto-rotate
auto-rotate-delay="0"
rotation-per-second="16deg"
diff --git a/pages/marketplace.html b/pages/marketplace.html
index 963277fd2..70f4b069d 100644
--- a/pages/marketplace.html
+++ b/pages/marketplace.html
@@ -2651,8 +2651,12 @@
margin: 8px 0 4px;
}
.anim-detail-stage agent-3d {
- width: 100%;
- height: 100%;
+ /* Fill the stage via absolute positioning. The stage sizes itself
+ from min-height, so a percentage `height: 100%` on the child
+ resolves against an auto-height parent and collapses to 0 —
+ inset: 0 stretches to the stage's used height instead. */
+ position: absolute;
+ inset: 0;
display: block;
}
.anim-detail-stage-load {
diff --git a/public/changelog.json b/public/changelog.json
index aa59e8726..357370f4b 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,31 @@
{
- "generated_at": "2026-07-21T19:30:32.066Z",
+ "generated_at": "2026-07-22T04:40:10.177Z",
"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-07-22",
+ "type": "update",
+ "title": "Animation preview plays again on every clip page",
+ "summary": "Opening an animation from the marketplace (Arm Flex, Facepalm, Superhero Jump, and the rest) showed an empty black stage where the moving avatar should be. Two things were wrong: the preview was pointed at a skeleton-only file with no body to draw, and the 3D canvas was collapsing to zero height inside its frame. Both are fixed, so every clip page now shows a real avatar performing the animation, framed and lit, with Replay to watch it again.",
+ "link": "/marketplace?tab=animations",
+ "tags": [
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-07-22",
+ "type": "update",
+ "title": "Take the wheel: drive your agent's computer",
+ "summary": "Every agent already had a live screen you could watch. Now, if you own the agent, you can grab the wheel of its real browser and drive it yourself: mouse, click and drag, scroll, keyboard, and a URL bar to go anywhere. Open your agent's screen, wait for it to go live, and click Take control. Your agent steps aside while you drive and picks its task back up the moment you let go. It is owner-only, and the browser you drive holds no wallet or keys, so control can never sign a transaction or move funds. This is the first step toward giving every agent its own computer that you and the agent can both operate.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-21",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 6522facaf..543cf9bbf 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Animation preview plays again on every clip page</title>
+ <link>https://three.ws/marketplace?tab=animations</link>
+ <guid isPermaLink="false">2026-07-22:Animation preview plays again on every clip page</guid>
+ <pubDate>Wed, 22 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Opening an animation from the marketplace (Arm Flex, Facepalm, Superhero Jump, and the rest) showed an empty black stage where the moving avatar should be. Two things were wrong: the preview was pointed at a skeleton-only file with no body to draw, and the 3D canvas was collapsing to zero height inside its frame. Both are fixed, so every clip page now shows a real avatar performing the animation, framed and lit, with Replay to watch it again.</description>
+ </item>
+ <item>
+ <title>Take the wheel: drive your agent's computer</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-07-22:Take the wheel: drive your agent's computer</guid>
+ <pubDate>Wed, 22 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every agent already had a live screen you could watch. Now, if you own the agent, you can grab the wheel of its real browser and drive it yourself: mouse, click and drag, scroll, keyboard, and a URL bar to go anywhere. Open your agent's screen, wait for it to go live, and click Take control. Your agent steps aside while you drive and picks its task back up the moment you let go. It is owner-only, and the browser you drive holds no wallet or keys, so control can never sign a transaction or move funds. This is the first step toward giving every agent its own computer that you and the agent can both operate.</description>
+ </item>
<item>
<title>Cookbook: self-correcting 3D with function calling</title>
<link>https://three.ws/cookbook</link>
diff --git a/scripts/agent-screen-control-proof.mjs b/scripts/agent-screen-control-proof.mjs
new file mode 100644
index 000000000..acfda3495
--- /dev/null
+++ b/scripts/agent-screen-control-proof.mjs
@@ -0,0 +1,114 @@
+// Real-browser proof for the agent-screen control dispatcher.
+//
+// Launches an actual headless Chromium (the same engine the caster pool runs),
+// loads an interactive page, and drives it ONLY through workers/agent-screen-pool
+// /control.js applyEvents() using the exact normalized wire events the API emits.
+// Asserts each input truly landed: a click toggled state, coordinates mapped to
+// the right element, text typed into a field, a whitelisted key fired, a wheel
+// scrolled the page, a blocked nav was refused, and reload worked. No mocks.
+//
+// node scripts/agent-screen-control-proof.mjs
+//
+// Exit 0 = every assertion passed. Exit 1 = a failure (prints which).
+
+import { chromium } from 'playwright';
+import { applyEvents } from '../workers/agent-screen-pool/control.js';
+
+const VP = { width: 1280, height: 720 };
+const results = [];
+const ok = (name, cond, detail = '') => {
+ results.push({ name, pass: !!cond, detail });
+ console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${detail ? ` (${detail})` : ''}`);
+};
+
+// Normalized center of an element, in the same 0..1 space the client sends.
+async function centerOf(page, selector) {
+ const box = await page.locator(selector).boundingBox();
+ if (!box) throw new Error(`no box for ${selector}`);
+ return { x: (box.x + box.width / 2) / VP.width, y: (box.y + box.height / 2) / VP.height };
+}
+
+const PAGE = `<!doctype html><html><head><meta charset="utf-8"><style>
+ body{margin:0;font:16px system-ui;height:2400px}
+ #btn{position:absolute;left:200px;top:120px;width:180px;height:56px}
+ #field{position:absolute;left:200px;top:220px;width:320px;height:36px;font-size:16px}
+ #log{position:absolute;left:200px;top:300px}
+ #foot{position:absolute;left:200px;top:2300px}
+</style></head><body>
+ <button id="btn">click me</button>
+ <input id="field" placeholder="type here">
+ <div id="log">idle</div>
+ <div id="foot">bottom</div>
+ <script>
+ let clicks=0;
+ document.getElementById('btn').addEventListener('click',()=>{clicks++;document.getElementById('log').textContent='clicked:'+clicks;});
+ document.getElementById('field').addEventListener('keydown',e=>{if(e.key==='Enter')document.getElementById('log').textContent='submitted:'+e.target.value;});
+ </script>
+</body></html>`;
+
+async function main() {
+ const browser = await chromium.launch({
+ headless: true,
+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
+ });
+ const context = await browser.newContext({ viewport: VP });
+ const page = await context.newPage();
+
+ try {
+ await page.setContent(PAGE, { waitUntil: 'domcontentloaded' });
+
+ // 1. Click, coordinates map to the right element and the handler fires.
+ const btn = await centerOf(page, '#btn');
+ await applyEvents(page, [{ t: 'click', x: btn.x, y: btn.y, button: 'left' }], VP);
+ ok('click lands on the targeted element', (await page.locator('#log').textContent()) === 'clicked:1');
+
+ // 2. Focus the field by clicking it, then type via a coalesced text event.
+ const field = await centerOf(page, '#field');
+ await applyEvents(page, [
+ { t: 'click', x: field.x, y: field.y, button: 'left' },
+ { t: 'text', text: 'hello agent' },
+ ], VP);
+ ok('text event types into the focused field', (await page.locator('#field').inputValue()) === 'hello agent');
+
+ // 3. Whitelisted key (Enter) fires the field's keydown handler.
+ await applyEvents(page, [{ t: 'key', key: 'Enter' }], VP);
+ ok('Enter key reaches the page', (await page.locator('#log').textContent()) === 'submitted:hello agent');
+
+ // 4. Backspace edits the field (another whitelisted key).
+ await applyEvents(page, [{ t: 'key', key: 'Backspace' }], VP);
+ ok('Backspace edits the field', (await page.locator('#field').inputValue()) === 'hello agen');
+
+ // 5. Wheel scroll moves the page.
+ await applyEvents(page, [{ t: 'scroll', x: 0.5, y: 0.5, dy: 800 }], VP);
+ await page.waitForTimeout(80);
+ const scrolled = await page.evaluate(() => window.scrollY);
+ ok('wheel event scrolls the page', scrolled > 0, `scrollY=${scrolled}`);
+
+ // 6. A blocked nav (loopback) is refused, the page must NOT navigate.
+ const before = page.url();
+ await applyEvents(page, [{ t: 'nav', url: 'http://127.0.0.1:9/' }], VP);
+ await page.waitForTimeout(50);
+ ok('blocked nav is refused (SSRF guard)', page.url() === before, `url unchanged`);
+
+ // 7. Positive nav to a real public site (best-effort, needs egress).
+ let navPass = null;
+ try {
+ await applyEvents(page, [{ t: 'nav', url: 'https://example.com/' }], VP);
+ await page.waitForLoadState('domcontentloaded', { timeout: 15000 });
+ navPass = /example/i.test(await page.title());
+ } catch {
+ navPass = null; // no network egress in this environment
+ }
+ if (navPass === null) console.log('SKIP positive nav to example.com (no network egress)');
+ else ok('nav to a public site navigates', navPass, `title=${await page.title().catch(() => '?')}`);
+
+ } finally {
+ await browser.close();
+ }
+
+ const failed = results.filter((r) => !r.pass);
+ console.log(`\n${results.length - failed.length}/${results.length} assertions passed`);
+ if (failed.length) process.exit(1);
+}
+
+main().catch((e) => { console.error('proof crashed:', e); process.exit(1); });
diff --git a/src/agent-screen-control.js b/src/agent-screen-control.js
new file mode 100644
index 000000000..551694822
--- /dev/null
+++ b/src/agent-screen-control.js
@@ -0,0 +1,290 @@
+// Client controller for "take the wheel" on the agent screen. The owner of an
+// agent can drive its live cast browser: real mouse, drag, scroll, keyboard, and
+// navigation, dispatched to the caster's Chromium via the control channel.
+//
+// acquire → POST /api/agent-screen-control {action:'acquire'} (session + CSRF)
+// input → POST /api/agent-screen-control {action:'input'} (bearer lease)
+// renew → keeps an idle lease alive
+// release → drops the wheel
+//
+// Coordinates are sent NORMALIZED (0..1) against the rendered canvas, so the
+// caster maps them onto its real viewport no matter the display size here.
+
+const CTL_URL = '/api/agent-screen-control';
+const CSRF_URL = '/api/csrf-token';
+
+const MOVE_THROTTLE_MS = 55; // cap pointermove event rate on the wire
+const FLUSH_MS = 80; // batch outgoing input this often
+const RENEW_MS = 8_000; // refresh the lease while driving
+
+async function getCsrf() {
+ try {
+ const r = await fetch(CSRF_URL, { credentials: 'include' });
+ if (!r.ok) return null;
+ const j = await r.json().catch(() => null);
+ return j?.token || j?.csrfToken || null;
+ } catch {
+ return null;
+ }
+}
+
+const btnName = (n) => (n === 2 ? 'right' : n === 1 ? 'middle' : 'left');
+
+// Mount the control affordance onto the screen stage. `canvas` is the element the
+// frames render into; its bounding rect is the coordinate space. `isLive()` gates
+// engagement so a driver can't grab a wheel that isn't casting yet. Returns a
+// small handle with destroy() for teardown.
+export function mountScreenControl({ stage, canvas, agentId, isLive, onStatus }) {
+ if (!stage || !canvas || !agentId) return { destroy() {} };
+
+ // ── DOM: a toolbar with Take control / Release + a URL bar (shown when driving)
+ const bar = document.createElement('div');
+ bar.className = 'asc-ctl-bar';
+ bar.innerHTML = `
+ <button type="button" class="asc-ctl-toggle" aria-pressed="false">
+ <span class="asc-ctl-ico" aria-hidden="true">&#127918;</span>
+ <span class="asc-ctl-label">Take control</span>
+ </button>
+ <div class="asc-ctl-drive" hidden>
+ <button type="button" class="asc-ctl-nav asc-ctl-back" title="Back" aria-label="Back">&#8592;</button>
+ <button type="button" class="asc-ctl-nav asc-ctl-reload" title="Reload" aria-label="Reload">&#8635;</button>
+ <form class="asc-ctl-urlform">
+ <input class="asc-ctl-url" type="text" inputmode="url" spellcheck="false"
+ placeholder="Type a URL and press Enter" aria-label="Navigate the agent's browser" />
+ </form>
+ <span class="asc-ctl-hint" role="status"></span>
+ </div>`;
+ stage.appendChild(bar);
+
+ // Transparent capture layer over the canvas. Only present while driving.
+ const overlay = document.createElement('div');
+ overlay.className = 'asc-ctl-overlay';
+ overlay.tabIndex = 0;
+ overlay.hidden = true;
+ stage.appendChild(overlay);
+
+ const toggle = bar.querySelector('.asc-ctl-toggle');
+ const toggleLabel = bar.querySelector('.asc-ctl-label');
+ const drive = bar.querySelector('.asc-ctl-drive');
+ const urlForm = bar.querySelector('.asc-ctl-urlform');
+ const urlInput = bar.querySelector('.asc-ctl-url');
+ const hint = bar.querySelector('.asc-ctl-hint');
+ const backBtn = bar.querySelector('.asc-ctl-back');
+ const reloadBtn = bar.querySelector('.asc-ctl-reload');
+
+ let leaseToken = null;
+ let driving = false;
+ let queue = [];
+ let textBuf = '';
+ let lastMoveAt = 0;
+ let flushTimer = null;
+ let renewTimer = null;
+
+ const setHint = (msg) => { hint.textContent = msg || ''; };
+
+ function norm(e) {
+ const rect = canvas.getBoundingClientRect();
+ if (!rect.width || !rect.height) return { x: 0, y: 0 };
+ const x = (e.clientX - rect.left) / rect.width;
+ const y = (e.clientY - rect.top) / rect.height;
+ return { x: Math.max(0, Math.min(1, x)), y: Math.max(0, Math.min(1, y)) };
+ }
+
+ // Text is coalesced into one 'text' event per flush so a fast typist sends one
+ // call, not one per character. Any non-text event flushes the pending text
+ // first so ordering (type "abc" then Enter) is preserved.
+ function flushTextBuf() {
+ if (textBuf) { queue.push({ t: 'text', text: textBuf }); textBuf = ''; }
+ }
+ function enqueue(ev) { flushTextBuf(); queue.push(ev); }
+
+ async function flush() {
+ if (!driving || !leaseToken) return;
+ flushTextBuf();
+ if (!queue.length) return;
+ const batch = queue.splice(0, 40);
+ try {
+ const r = await fetch(CTL_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${leaseToken}` },
+ body: JSON.stringify({ agentId, action: 'input', events: batch }),
+ });
+ if (r.status === 401) { setHint('Lease expired'); await stop(false); }
+ } catch { /* transient; next flush retries the rest of the queue */ }
+ }
+
+ async function acquire() {
+ const csrf = await getCsrf();
+ if (!csrf) { onStatus?.('error', 'Sign in to drive this agent'); return false; }
+ try {
+ const r = await fetch(CTL_URL, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },
+ body: JSON.stringify({ agentId, action: 'acquire' }),
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ const msg = j?.error === 'in_use' ? 'Another session is already driving'
+ : r.status === 403 ? 'You do not own this agent'
+ : r.status === 401 ? 'Sign in to drive this agent'
+ : 'Could not take control';
+ onStatus?.('error', msg);
+ return false;
+ }
+ const j = await r.json();
+ leaseToken = j.leaseToken;
+ return !!leaseToken;
+ } catch {
+ onStatus?.('error', 'Could not reach the control channel');
+ return false;
+ }
+ }
+
+ async function renew() {
+ if (!driving || !leaseToken) return;
+ try {
+ await fetch(CTL_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${leaseToken}` },
+ body: JSON.stringify({ agentId, action: 'renew' }),
+ });
+ } catch { /* the flush loop will surface a dead lease */ }
+ }
+
+ async function start() {
+ if (driving) return;
+ if (isLive && !isLive()) { onStatus?.('error', 'The agent must be live to drive'); return; }
+ toggle.disabled = true;
+ const ok = await acquire();
+ toggle.disabled = false;
+ if (!ok) return;
+ driving = true;
+ overlay.hidden = false;
+ drive.hidden = false;
+ toggle.setAttribute('aria-pressed', 'true');
+ toggle.classList.add('driving');
+ toggleLabel.textContent = 'Release control';
+ setHint('You have the wheel');
+ onStatus?.('driving', 'You are driving');
+ attachInput();
+ overlay.focus();
+ flushTimer = setInterval(flush, FLUSH_MS);
+ renewTimer = setInterval(renew, RENEW_MS);
+ }
+
+ async function stop(release = true) {
+ if (!driving) return;
+ driving = false;
+ clearInterval(flushTimer); flushTimer = null;
+ clearInterval(renewTimer); renewTimer = null;
+ detachInput();
+ queue = []; textBuf = '';
+ overlay.hidden = true;
+ drive.hidden = true;
+ toggle.setAttribute('aria-pressed', 'false');
+ toggle.classList.remove('driving');
+ toggleLabel.textContent = 'Take control';
+ setHint('');
+ onStatus?.('idle', '');
+ if (release && leaseToken) {
+ try {
+ await fetch(CTL_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${leaseToken}` },
+ body: JSON.stringify({ agentId, action: 'release' }),
+ });
+ } catch { /* the lease TTL reclaims it regardless */ }
+ }
+ leaseToken = null;
+ }
+
+ // ── input capture (only wired while driving) ────────────────────────────────
+ const onPointerMove = (e) => {
+ const now = Date.now();
+ if (now - lastMoveAt < MOVE_THROTTLE_MS) return;
+ lastMoveAt = now;
+ const { x, y } = norm(e);
+ queue.push({ t: 'move', x, y }); // moves don't need to flush pending text
+ };
+ const onPointerDown = (e) => {
+ e.preventDefault();
+ overlay.focus();
+ overlay.setPointerCapture?.(e.pointerId);
+ enqueue({ t: 'down', ...norm(e), button: btnName(e.button) });
+ };
+ const onPointerUp = (e) => {
+ e.preventDefault();
+ overlay.releasePointerCapture?.(e.pointerId);
+ enqueue({ t: 'up', ...norm(e), button: btnName(e.button) });
+ };
+ const onWheel = (e) => {
+ e.preventDefault();
+ enqueue({ t: 'scroll', ...norm(e), dy: e.deltaY });
+ };
+ const onContextMenu = (e) => { e.preventDefault(); };
+ const SPECIAL = new Set([
+ 'Enter', 'Backspace', 'Tab', 'Delete', 'Escape',
+ 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
+ 'Home', 'End', 'PageUp', 'PageDown',
+ ]);
+ const onKeyDown = (e) => {
+ if (!driving) return;
+ if (e.target === urlInput) return; // let the URL bar type normally
+ if (e.metaKey || e.ctrlKey || e.altKey) return; // no chords in v1
+ if (SPECIAL.has(e.key)) {
+ e.preventDefault();
+ enqueue({ t: 'key', key: e.key });
+ } else if (e.key.length === 1) {
+ e.preventDefault();
+ textBuf += e.key; // coalesced, flushed as one text event
+ }
+ };
+
+ function attachInput() {
+ overlay.addEventListener('pointermove', onPointerMove);
+ overlay.addEventListener('pointerdown', onPointerDown);
+ overlay.addEventListener('pointerup', onPointerUp);
+ overlay.addEventListener('wheel', onWheel, { passive: false });
+ overlay.addEventListener('contextmenu', onContextMenu);
+ document.addEventListener('keydown', onKeyDown, true);
+ }
+ function detachInput() {
+ overlay.removeEventListener('pointermove', onPointerMove);
+ overlay.removeEventListener('pointerdown', onPointerDown);
+ overlay.removeEventListener('pointerup', onPointerUp);
+ overlay.removeEventListener('wheel', onWheel);
+ overlay.removeEventListener('contextmenu', onContextMenu);
+ document.removeEventListener('keydown', onKeyDown, true);
+ }
+
+ // ── toolbar wiring ──────────────────────────────────────────────────────────
+ toggle.addEventListener('click', () => { driving ? stop(true) : start(); });
+ backBtn.addEventListener('click', () => { if (driving) { enqueue({ t: 'back' }); flush(); } });
+ reloadBtn.addEventListener('click', () => { if (driving) { enqueue({ t: 'reload' }); flush(); } });
+ urlForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ if (!driving) return;
+ let url = (urlInput.value || '').trim();
+ if (!url) return;
+ if (!/^https?:\/\//i.test(url)) url = `https://${url}`;
+ enqueue({ t: 'nav', url });
+ flush();
+ urlInput.blur();
+ overlay.focus();
+ });
+
+ // Release the wheel if the tab is closed/hidden so a lease never dangles.
+ const onHide = () => { if (driving && document.visibilityState === 'hidden') stop(true); };
+ document.addEventListener('visibilitychange', onHide);
+ window.addEventListener('pagehide', () => { if (driving) stop(true); });
+
+ return {
+ destroy() {
+ stop(true);
+ document.removeEventListener('visibilitychange', onHide);
+ bar.remove();
+ overlay.remove();
+ },
+ };
+}
diff --git a/src/agent-screen.js b/src/agent-screen.js
index 5c7866b74..9c5df025a 100644
--- a/src/agent-screen.js
+++ b/src/agent-screen.js
@@ -69,6 +69,7 @@ import { createHeatmapPoller, buildNarrationContext } from './sentiment-heatmap-
import { createPnlHud } from './agent-screen-pnl-hud.js';
import { createAmbientWorld, phaseLabel } from './agent-screen-world.js';
import { createDjScript } from './agent-screen-dj.js';
+import { mountScreenControl } from './agent-screen-control.js';
import { LipSyncAnalyser } from './lip-sync-analyser.js';
import { createVisemeDriver } from './runtime/lipsync.js';
import { classifyTaskInput, ensureSessionId } from './shared/ask-routing.js';
@@ -1787,6 +1788,25 @@ async function boot(id) {
});
}
+ // Owner-only: take the wheel of the agent's live cast browser. Watching is
+ // public (above); driving is private. The controller drives the real Chromium
+ // through the control channel, and the caster pauses its own task while a human
+ // holds the wheel. The cast browser holds no wallet/keys, so this cannot move
+ // funds, that boundary is what makes remote control safe to ship.
+ let screenControl = null;
+ if (isOwner && screenStageEl && screenCanvas) {
+ screenControl = mountScreenControl({
+ stage: screenStageEl,
+ canvas: screenCanvas,
+ agentId: id,
+ isLive: () => liveNow,
+ onStatus: (kind, msg) => {
+ if (kind === 'error' && msg) toast(msg);
+ else if (kind === 'driving') toast('You have the wheel, drive the agent live');
+ },
+ });
+ }
+
const client = createAgentScreenClient(id, {
onOpen({ agentName: n }) {
if (n) { agentNameEl.textContent = n; agentName = n; webcamName.textContent = n; }
@@ -3433,6 +3453,7 @@ async function boot(id) {
heatmap?.dispose();
clearInterval(watchPingTimer);
stopWatchStatus();
+ screenControl?.destroy();
treasuryCockpit?.destroy();
mirrorPanel?.destroy();
pnlHud?.destroy();
diff --git a/src/marketplace.js b/src/marketplace.js
index 88f72cfba..34e77e27c 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -3866,7 +3866,10 @@ function triggerDownload(url, filename) {
// Rich, deep-linkable page at /marketplace/animations/:name. Plays the clip
// live on a preview avatar, shows clip metadata, and lists more animations.
-const PREVIEW_AVATAR_GLB = '/animations/idle_female_jan25.glb';
+// The preview body the clip is retargeted onto. Must be a real avatar with
+// meshes — the same one the /animations gallery preview uses — not a bare
+// animation-carrier rig (idle_female_jan25.glb is meshless: skeleton only).
+const PREVIEW_AVATAR_GLB = '/avatars/cz.glb';
let _animDetailId = null;
let _animDetailEl = null;
@@ -3927,7 +3930,10 @@ function playAnimOnStage(anim) {
const agentEl = document.createElement('agent-3d');
agentEl.setAttribute('src', PREVIEW_AVATAR_GLB);
agentEl.setAttribute('eager', '');
- agentEl.style.cssText = 'width:100%;height:100%;display:block;';
+ // Absolute-fill the stage (see the .anim-detail-stage agent-3d CSS): a
+ // percentage height on this child collapses to 0 against the stage's
+ // auto/min-height, which left the avatar unrendered (black stage).
+ agentEl.style.cssText = 'position:absolute;inset:0;display:block;';
agentEl.addEventListener('agent:ready', () => {
if (load) load.hidden = true;
agentEl.play?.(anim.name, { loop: isLoop, fade_ms: 300 });
diff --git a/src/shared/agent-screen-control.js b/src/shared/agent-screen-control.js
new file mode 100644
index 000000000..020a8ace5
--- /dev/null
+++ b/src/shared/agent-screen-control.js
@@ -0,0 +1,165 @@
+// Shared, pure helpers for the agent-screen CONTROL channel, the reverse of the
+// frame stream. Viewers who OWN an agent can take the wheel of its live cast
+// browser: mouse, scroll, keyboard, and navigation. These helpers sanitize the
+// wire events on the API boundary so only well-formed, in-range input ever
+// reaches the caster's real Chromium page. Pure and dependency-free so both the
+// API handler and the unit tests import the same logic.
+//
+// Wire event shapes (all coordinates NORMALIZED to the streamed viewport, 0..1,
+// so a client at any display size maps cleanly to the caster's real pixels):
+// { t: 'move', x, y }
+// { t: 'down', x, y, button }
+// { t: 'up', x, y, button }
+// { t: 'click', x, y, button }
+// { t: 'scroll', x, y, dy }
+// { t: 'key', key } , a single non-text key from KEY_WHITELIST
+// { t: 'text', text } , literal characters to type
+// { t: 'nav', url } , navigate the browser (host-guarded)
+// { t: 'back' } | { t: 'forward' } | { t: 'reload' }
+
+export const EVENT_TYPES = new Set([
+ 'move', 'down', 'up', 'click', 'scroll', 'key', 'text', 'nav', 'back', 'forward', 'reload',
+]);
+
+export const BUTTONS = new Set(['left', 'right', 'middle']);
+
+// Non-text keys a driver may press. Deliberately narrow: navigation, editing,
+// and submission keys only. Printable characters go through the 'text' event so
+// there is no ambiguity and no way to smuggle key chords. No modifiers in v1.
+export const KEY_WHITELIST = new Set([
+ 'Enter', 'Backspace', 'Tab', 'Delete', 'Escape',
+ 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
+ 'Home', 'End', 'PageUp', 'PageDown',
+]);
+
+export const MAX_EVENTS_PER_BATCH = 40;
+export const MAX_TEXT_LEN = 256;
+export const SCROLL_CLAMP = 1200; // px, per wheel event
+
+const clamp01 = (n) => {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return null;
+ return v < 0 ? 0 : v > 1 ? 1 : v;
+};
+
+const finiteClamp = (n, lo, hi) => {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return 0;
+ return v < lo ? lo : v > hi ? hi : v;
+};
+
+// Reject text that is only control characters or empty; keep printable content
+// (including spaces and unicode) but strip C0/C1 control chars that a keyboard
+// couldn't type as a character anyway (newlines included, use the Enter key).
+function cleanText(raw) {
+ if (typeof raw !== 'string') return null;
+ // Strip C0 controls (incl. newlines/tabs, use the Enter/Tab keys), DEL, and
+ // C1 controls; keep every printable character (spaces + unicode included).
+ const CONTROLS = new RegExp('[\\u0000-\\u001F\\u007F-\\u009F]', 'g');
+ const stripped = raw.replace(CONTROLS, '').slice(0, MAX_TEXT_LEN);
+ return stripped.length ? stripped : null;
+}
+
+// ── Navigation host guard (SSRF) ─────────────────────────────────────────────
+// The caster's browser runs inside our infrastructure. A driver-supplied nav URL
+// must never let it reach the cloud metadata endpoint, loopback, or any private
+// range. Only public http(s) destinations are allowed.
+
+function ipv4Parts(host) {
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
+ if (!m) return null;
+ const p = m.slice(1).map(Number);
+ if (p.some((n) => n > 255)) return null;
+ return p;
+}
+
+function isPrivateIpv4([a, b]) {
+ if (a === 0 || a === 127) return true; // this-host / loopback
+ if (a === 10) return true; // private
+ if (a === 172 && b >= 16 && b <= 31) return true; // private
+ if (a === 192 && b === 168) return true; // private
+ if (a === 169 && b === 254) return true; // link-local (incl. metadata)
+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
+ return false;
+}
+
+export function isNavAllowed(rawUrl) {
+ let u;
+ try {
+ u = new URL(String(rawUrl));
+ } catch {
+ return false;
+ }
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return false;
+ let host = u.hostname.toLowerCase();
+ if (!host) return false;
+ // Strip IPv6 brackets for literal checks.
+ if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);
+ if (host === 'localhost' || host.endsWith('.localhost')) return false;
+ if (host === 'metadata.google.internal' || host.endsWith('.internal')) return false;
+ // IPv6 loopback / unique-local / link-local.
+ if (host === '::1' || host === '::' ) return false;
+ if (/^fe80:/i.test(host)) return false; // link-local
+ if (/^f[cd][0-9a-f]{2}:/i.test(host)) return false; // fc00::/7 unique-local
+ // IPv4 literal ranges.
+ const v4 = ipv4Parts(host);
+ if (v4 && isPrivateIpv4(v4)) return false;
+ // An IPv4 literal that parsed but is public is fine; a hostname resolves at
+ // nav time (DNS-rebinding is out of scope for v1 and noted in the docs).
+ return true;
+}
+
+// Sanitize ONE raw event → a clean event or null (dropped). Coordinates are kept
+// normalized; the caster maps them to real pixels at dispatch time.
+export function sanitizeEvent(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const t = raw.t;
+ if (!EVENT_TYPES.has(t)) return null;
+
+ switch (t) {
+ case 'move':
+ case 'down':
+ case 'up':
+ case 'click': {
+ const x = clamp01(raw.x);
+ const y = clamp01(raw.y);
+ if (x === null || y === null) return null;
+ const ev = { t, x, y };
+ if (t !== 'move') ev.button = BUTTONS.has(raw.button) ? raw.button : 'left';
+ return ev;
+ }
+ case 'scroll': {
+ const x = clamp01(raw.x);
+ const y = clamp01(raw.y);
+ if (x === null || y === null) return null;
+ return { t, x, y, dy: finiteClamp(raw.dy, -SCROLL_CLAMP, SCROLL_CLAMP) };
+ }
+ case 'key':
+ return KEY_WHITELIST.has(raw.key) ? { t, key: raw.key } : null;
+ case 'text': {
+ const text = cleanText(raw.text);
+ return text ? { t, text } : null;
+ }
+ case 'nav':
+ return isNavAllowed(raw.url) ? { t, url: String(raw.url) } : null;
+ case 'back':
+ case 'forward':
+ case 'reload':
+ return { t };
+ default:
+ return null;
+ }
+}
+
+// Sanitize a batch. Drops invalid events silently (a fat-fingered event should
+// never fail the whole gesture) and caps the batch length.
+export function sanitizeEvents(rawList) {
+ if (!Array.isArray(rawList)) return [];
+ const out = [];
+ for (const raw of rawList) {
+ if (out.length >= MAX_EVENTS_PER_BATCH) break;
+ const clean = sanitizeEvent(raw);
+ if (clean) out.push(clean);
+ }
+ return out;
+}
diff --git a/tests/agent-screen-control.test.js b/tests/agent-screen-control.test.js
new file mode 100644
index 000000000..54638fd63
Binary files /dev/null and b/tests/agent-screen-control.test.js differ
diff --git a/vercel.json b/vercel.json
index 6537d96ca..5baf75766 100644
--- a/vercel.json
+++ b/vercel.json
@@ -3032,6 +3032,14 @@
"src": "/api/agent-screen-push",
"dest": "/api/agent-screen-push.js"
},
+ {
+ "src": "/api/agent-screen-control",
+ "dest": "/api/agent-screen-control.js"
+ },
+ {
+ "src": "/api/agent-screen-control-drain",
+ "dest": "/api/agent-screen-control-drain.js"
+ },
{
"src": "/api/agent-screen-active",
"dest": "/api/agent-screen-active.js"
diff --git a/workers/agent-screen-pool/README.md b/workers/agent-screen-pool/README.md
index 1fe030dea..6e1134c20 100644
--- a/workers/agent-screen-pool/README.md
+++ b/workers/agent-screen-pool/README.md
@@ -83,6 +83,22 @@ docker run --rm -e SCREEN_WORKER_SECRET=<secret> three-ws/agent-screen-pool
| `JPEG_QUALITY` | `58` | Frame quality vs. bandwidth. |
| `LEAD_MS` | `900` | How long a narration line leads its action. |
| `DWELL_MS` | `6000` | How long to hold on the result between task runs. |
+| `CONTROL_URL` | `$BASE_URL/api/agent-screen-control-drain` | Control-channel drain (owner input). |
+| `CONTROL_POLL_MS` | `250` | How often to drain queued owner input. |
+| `MANUAL_HOLD_MS` | `2500` | How long the autonomous task stays paused after the last manual signal. |
+
+## Take the wheel (owner control)
+
+The caster is not just an outbound screen: an agent's **owner** can drive its live
+browser. Each tick this worker also calls `CONTROL_URL` for the agents it is
+casting, learns whether a human holds the control lease, and dispatches their
+queued input (mouse, drag, scroll, keyboard, navigation) into the real page via
+[`control.js`](./control.js). While a human is driving, the autonomous task/tour
+stands down (`isManual`) so the two never fight over the cursor, and resumes once
+the lease lapses. Input is sanitized and SSRF-guarded on the API boundary; the
+dispatcher re-clamps coordinates and re-guards navigation as defense in depth. See
+[docs/agent-screen-control.md](../../docs/agent-screen-control.md) for the full
+channel and safety model.
## Where to run it
diff --git a/workers/agent-screen-pool/control.js b/workers/agent-screen-pool/control.js
new file mode 100644
index 000000000..0db2155cb
--- /dev/null
+++ b/workers/agent-screen-pool/control.js
@@ -0,0 +1,138 @@
+// control.js, the caster's input dispatcher. Turns sanitized wire events drained
+// from the control channel (/api/agent-screen-control-drain) into real input on
+// the live Chromium page via Playwright. Coordinates arrive NORMALIZED (0..1) so
+// they map cleanly onto the caster's real viewport regardless of the driver's
+// display size.
+//
+// The API already sanitizes every event, but this module re-clamps coordinates
+// and re-guards navigation as defense in depth, the caster never trusts the
+// queue blindly.
+
+const VP_DEFAULT = { width: 1280, height: 720 };
+
+const clamp01 = (n) => {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return 0;
+ return v < 0 ? 0 : v > 1 ? 1 : v;
+};
+
+// Mirror of the API-side nav guard (src/shared/agent-screen-control.js). The
+// worker is deployed standalone and cannot import repo-shared code, so the guard
+// is duplicated here on purpose, keep the two in sync.
+function ipv4Parts(host) {
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
+ if (!m) return null;
+ const p = m.slice(1).map(Number);
+ if (p.some((n) => n > 255)) return null;
+ return p;
+}
+function isPrivateIpv4([a, b]) {
+ if (a === 0 || a === 127 || a === 10) return true;
+ if (a === 172 && b >= 16 && b <= 31) return true;
+ if (a === 192 && b === 168) return true;
+ if (a === 169 && b === 254) return true;
+ if (a === 100 && b >= 64 && b <= 127) return true;
+ return false;
+}
+export function isNavAllowed(rawUrl) {
+ let u;
+ try { u = new URL(String(rawUrl)); } catch { return false; }
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return false;
+ let host = u.hostname.toLowerCase();
+ if (!host) return false;
+ if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);
+ if (host === 'localhost' || host.endsWith('.localhost')) return false;
+ if (host === 'metadata.google.internal' || host.endsWith('.internal')) return false;
+ if (host === '::1' || host === '::') return false;
+ if (/^fe80:/i.test(host)) return false;
+ if (/^f[cd][0-9a-f]{2}:/i.test(host)) return false;
+ const v4 = ipv4Parts(host);
+ if (v4 && isPrivateIpv4(v4)) return false;
+ return true;
+}
+
+// Map a normalized event's (x,y) to real pixels within the viewport.
+function toPixels(ev, vp) {
+ return [Math.round(clamp01(ev.x) * (vp.width - 1)), Math.round(clamp01(ev.y) * (vp.height - 1))];
+}
+
+// Apply ONE event to the page. Isolated try/catch so a click that lands mid
+// navigation (or any transient Playwright error) never aborts the rest of the
+// gesture. Returns true if the event likely changed the page enough to warrant an
+// immediate fresh frame (click / key / nav), so the driver sees feedback fast.
+async function applyOne(page, ev, vp) {
+ try {
+ switch (ev.t) {
+ case 'move': {
+ const [x, y] = toPixels(ev, vp);
+ await page.mouse.move(x, y);
+ return false;
+ }
+ case 'down': {
+ const [x, y] = toPixels(ev, vp);
+ await page.mouse.move(x, y);
+ await page.mouse.down({ button: ev.button || 'left' });
+ return false;
+ }
+ case 'up': {
+ const [x, y] = toPixels(ev, vp);
+ await page.mouse.move(x, y);
+ await page.mouse.up({ button: ev.button || 'left' });
+ return true;
+ }
+ case 'click': {
+ const [x, y] = toPixels(ev, vp);
+ await page.mouse.click(x, y, { button: ev.button || 'left' });
+ return true;
+ }
+ case 'scroll': {
+ const [x, y] = toPixels(ev, vp);
+ await page.mouse.move(x, y);
+ await page.mouse.wheel(0, Number(ev.dy) || 0);
+ return true;
+ }
+ case 'key':
+ await page.keyboard.press(String(ev.key));
+ return true;
+ case 'text':
+ await page.keyboard.type(String(ev.text), { delay: 12 });
+ return true;
+ case 'nav':
+ if (!isNavAllowed(ev.url)) return false;
+ await page.goto(String(ev.url), { waitUntil: 'domcontentloaded', timeout: 30_000 });
+ return true;
+ case 'back':
+ await page.goBack({ waitUntil: 'domcontentloaded', timeout: 20_000 }).catch(() => {});
+ return true;
+ case 'forward':
+ await page.goForward({ waitUntil: 'domcontentloaded', timeout: 20_000 }).catch(() => {});
+ return true;
+ case 'reload':
+ await page.reload({ waitUntil: 'domcontentloaded', timeout: 20_000 }).catch(() => {});
+ return true;
+ default:
+ return false;
+ }
+ } catch {
+ return false;
+ }
+}
+
+// Apply a batch of drained events in order. Returns { changed } where changed is
+// true if any event warrants an immediate frame push.
+export async function applyEvents(page, events, viewport = VP_DEFAULT) {
+ if (!page || page.isClosed?.() || !Array.isArray(events) || !events.length) {
+ return { changed: false };
+ }
+ const vp = {
+ width: Number(viewport?.width) || VP_DEFAULT.width,
+ height: Number(viewport?.height) || VP_DEFAULT.height,
+ };
+ let changed = false;
+ for (const ev of events) {
+ if (page.isClosed?.()) break;
+ const c = await applyOne(page, ev, vp);
+ changed = changed || c;
+ }
+ return { changed };
+}
diff --git a/workers/agent-screen-pool/index.js b/workers/agent-screen-pool/index.js
index c73e1ed1c..3f87372ba 100644
--- a/workers/agent-screen-pool/index.js
+++ b/workers/agent-screen-pool/index.js
@@ -30,12 +30,22 @@
import { chromium } from 'playwright';
import { pickTask } from './tasks/index.js';
import { generateNarration, runTaskSteps } from './task-runner.js';
+import { applyEvents } from './control.js';
const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');
const WANTED_URL = process.env.WANTED_URL || `${BASE_URL}/api/agent/watch-wanted`;
// Single frame convention: the live wall, 2D watch panel, AND the in-world 3D
// desk all read /api/agent-screen-push frames via /api/agent-screen-stream.
const PUSH_URL = process.env.PUSH_URL || `${BASE_URL}/api/agent-screen-push`;
+// Reverse channel: the owner drives the cast browser. This worker drains queued
+// input events (and the manual-mode flag) for every agent it is casting, then
+// dispatches them into the live page. Polled fast so control feels responsive.
+const CONTROL_URL = process.env.CONTROL_URL || `${BASE_URL}/api/agent-screen-control-drain`;
+const CONTROL_POLL_MS = Number(process.env.CONTROL_POLL_MS || 250);
+// How long after the last manual signal the autonomous task stays paused. Long
+// enough to bridge poll gaps and idle holds; short enough that the bot resumes
+// promptly once the human lets go.
+const MANUAL_HOLD_MS = Number(process.env.MANUAL_HOLD_MS || 2500);
const SECRET = process.env.SCREEN_WORKER_SECRET || '';
// Hard cap on concurrent Chromium casters. The API's /api/agent/watch-status
@@ -142,6 +152,60 @@ function resolveUrl(homeUrl, agentId) {
return `${BASE_URL}${u.startsWith('/') ? '' : '/'}${u}`;
}
+// ── control channel: the owner takes the wheel ──────────────────────────────
+// True while a human holds this agent's control lease (recently signalled by the
+// drain endpoint). The autonomous task/tour loops check this and stand down so
+// the two never fight over the cursor.
+function isManual(entry) {
+ return !!(entry && entry.manualUntil && entry.manualUntil > Date.now());
+}
+
+// Drain queued input events for every casting agent and dispatch them into the
+// live page. Best-effort: a blip never interrupts casting. Re-entrancy guarded so
+// a slow round can't stack on the next tick.
+let controlPolling = false;
+async function drainControl() {
+ if (controlPolling || stopping || pool.size === 0) return;
+ controlPolling = true;
+ try {
+ const ids = [...pool.keys()];
+ const res = await fetch(CONTROL_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${SECRET}` },
+ body: JSON.stringify({ agentIds: ids }),
+ });
+ if (!res.ok) return;
+ const body = await res.json().catch(() => null);
+ const agents = body?.agents || {};
+ await Promise.all(ids.map(async (id) => {
+ const entry = pool.get(id);
+ if (!entry || !entry.page || entry.page.isClosed()) return;
+ const info = agents[id];
+ if (!info) return;
+ const wasManual = isManual(entry);
+ if (info.manual) entry.manualUntil = Date.now() + MANUAL_HOLD_MS;
+ // Announce the handoff exactly once as control passes each way.
+ if (info.manual && !wasManual) {
+ await pushTaskFrame(entry, { activity: 'Owner took the wheel, driving live', type: 'activity' });
+ }
+ const events = Array.isArray(info.events) ? info.events : [];
+ if (events.length) {
+ const { changed } = await applyEvents(entry.page, events, VIEWPORT);
+ if (changed) await pushTaskFrame(entry, {}); // land the result immediately
+ } else if (isManual(entry)) {
+ await pushTaskFrame(entry, {}); // held wheel, no new input: keep pixels live
+ }
+ if (!isManual(entry) && wasManual) {
+ await pushTaskFrame(entry, { activity: 'Owner released the wheel, agent resumed', type: 'activity' });
+ }
+ }));
+ } catch {
+ /* control is best-effort; casting continues regardless */
+ } finally {
+ controlPolling = false;
+ }
+}
+
async function pushFrame(entry) {
if (entry.pushing || !entry.page || entry.page.isClosed()) return;
entry.pushing = true;
@@ -222,6 +286,8 @@ async function runTour(entry) {
let i = 0;
while (!stopping && pool.has(agentId) && !page.isClosed()) {
+ // Human has the wheel: pause the guided tour, the driver steers instead.
+ if (isManual(entry)) { await sleep(600); continue; }
const name = stops[i % stops.length];
i++;
try {
@@ -319,7 +385,7 @@ async function waitWithFrames(entry, selector, { timeout = 15_000, fallbackUrl =
async function dwellTask(entry, ms) {
const deadline = Date.now() + ms;
while (Date.now() < deadline) {
- if (entry.controller.signal.aborted) return;
+ if (entry.controller.signal.aborted || isManual(entry)) return; // yield to the driver
await pushTaskFrame(entry, {});
await sleep(FRAME_MS);
}
@@ -344,11 +410,13 @@ async function readText(entry, step) {
function makeExecutor(entry) {
return {
async narrate(line) {
+ if (isManual(entry)) return; // human is driving, do not narrate over them
await pushTaskFrame(entry, { activity: line, type: 'analysis' });
const deadline = Date.now() + LEAD_MS;
- while (Date.now() < deadline && !entry.controller.signal.aborted) await sleep(Math.min(LEAD_MS, 150));
+ while (Date.now() < deadline && !entry.controller.signal.aborted && !isManual(entry)) await sleep(Math.min(LEAD_MS, 150));
},
async perform(step) {
+ if (isManual(entry)) return null; // yield the page to the driver
const page = entry.page;
switch (step.kind) {
case 'goto': await page.goto(step.url, { waitUntil: 'domcontentloaded', timeout: 30_000 }); return null;
@@ -390,6 +458,9 @@ async function runCastTask(entry) {
const executor = makeExecutor(entry);
while (!entry.controller.signal.aborted && entry.page && !entry.page.isClosed()) {
+ // Human has the wheel: don't start a task sequence. The control loop drains
+ // their input and keeps pixels flowing; we just wait for them to let go.
+ if (isManual(entry)) { await sleep(FRAME_MS); continue; }
try {
const { aborted } = await runTaskSteps({ task, narration, executor, signal: entry.controller.signal });
if (aborted) break;
@@ -448,6 +519,7 @@ async function shutdown() {
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
-log(`starting · base=${BASE_URL} · max=${MAX_BROWSERS} · poll=${POLL_MS}ms · frame=${FRAME_MS}ms`);
+log(`starting · base=${BASE_URL} · max=${MAX_BROWSERS} · poll=${POLL_MS}ms · frame=${FRAME_MS}ms · control=${CONTROL_POLL_MS}ms`);
await reconcile();
setInterval(reconcile, POLL_MS);
+setInterval(drainControl, CONTROL_POLL_MS);