Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(agent-screen-pool): implement on-demand live browser caster with dynamic agent management
zprv415923fa66c7
diff --git a/.github/workflows/agent-screen-pool.yml b/.github/workflows/agent-screen-pool.ymlnew file mode 100644index 000000000..d9e265080--- /dev/null+++ b/.github/workflows/agent-screen-pool.yml@@ -0,0 +1,65 @@+name: agent-screen-pool++# On-demand live-browser caster for the agent wall (workers/agent-screen-pool).+#+# This is the BURST runner, not a 24/7 host: GitHub caps a job at 6h, so each run+# casts watched agents for ~5.4h then exits. The schedule re-launches it so it+# self-renews around the clock; trigger manually for events/demos. For a true+# always-on pool, run the Docker image on a small VM (see the worker README) —+# the platform's zero-cost activity view covers every agent regardless.+#+# Requires repo secret SCREEN_WORKER_SECRET (must match the value set on the API).++on:+ workflow_dispatch:+ inputs:+ max_browsers:+ description: 'Max concurrent live casts'+ required: false+ default: '6'+ runtime_minutes:+ description: 'How long this run should cast before exiting'+ required: false+ default: '320'+ schedule:+ # Every 5 hours — each run lasts ~5.4h, so coverage overlaps with no gap.+ - cron: '0 */5 * * *'++concurrency:+ group: agent-screen-pool+ cancel-in-progress: false++jobs:+ cast:+ runs-on: ubuntu-latest+ timeout-minutes: 350+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: '20'++ - name: Install dependencies+ working-directory: workers/agent-screen-pool+ run: npm install --omit=dev++ - name: Install Chromium+ working-directory: workers/agent-screen-pool+ run: npx playwright install --with-deps chromium++ - name: Run caster pool+ working-directory: workers/agent-screen-pool+ env:+ SCREEN_WORKER_SECRET: ${{ secrets.SCREEN_WORKER_SECRET }}+ BASE_URL: https://three.ws+ MAX_BROWSERS: ${{ github.event.inputs.max_browsers || '6' }}+ run: |+ if [ -z "$SCREEN_WORKER_SECRET" ]; then+ echo "SCREEN_WORKER_SECRET secret is not set on the repo — nothing to do."+ exit 0+ fi+ MINUTES="${{ github.event.inputs.runtime_minutes || '320' }}"+ timeout "${MINUTES}m" node index.js || code=$?+ # 124 = timeout fired (expected, clean renewal); 0 = clean exit.+ if [ "${code:-0}" -ne 0 ] && [ "${code:-0}" -ne 124 ]; then exit "${code}"; fidiff --git a/api/agent/watch-wanted.js b/api/agent/watch-wanted.jsnew file mode 100644index 000000000..edd471da0--- /dev/null+++ b/api/agent/watch-wanted.js@@ -0,0 +1,86 @@+// GET /api/agent/watch-wanted → { agents: [{ agentId, name, lastSeen }], ts }+//+// Read side of the on-demand caster pool. The pool worker polls this to learn+// which agents viewers are currently watching, then maintains a bounded pool of+// real Playwright browsers casting exactly those agents (see+// workers/agent-screen-pool). Agents fall out of the window automatically once+// nobody is watching, so the worker can tear their browsers down.+//+// Auth: the shared first-party worker secret (SCREEN_WORKER_SECRET) — the same+// secret the worker uses to push frames for any agent. Without it configured the+// endpoint reports the pool as disabled rather than leaking the watch set.++import { timingSafeEqual } from 'node:crypto';+import { cors, json, method, error, wrap } from '../_lib/http.js';+import { getRedis } from '../_lib/redis.js';+import { sql } from '../_lib/db.js';+import { extractBearer } from '../_lib/auth.js';++const WANTED_KEY = 'screen:wanted';+const WINDOW_MS = 90_000; // agents wanted within the last 90s are "live-watched"+const MAX_AGENTS = 48; // hard cap returned to the worker++const WORKER_SECRET = process.env.SCREEN_WORKER_SECRET || '';+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);+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ if (!WORKER_SECRET || WORKER_SECRET.length < 16) {+ return json(res, 200, { agents: [], disabled: true, reason: 'SCREEN_WORKER_SECRET not configured' });+ }+ if (!isPoolWorker(extractBearer(req))) {+ return error(res, 401, 'unauthorized', 'pool worker secret required');+ }++ const r = getRedis();+ if (!r) return json(res, 200, { agents: [], ts: Date.now() });++ const now = Date.now();+ let ids = [];+ try {+ // Most-recently-wanted first, capped.+ const raw = await r.zrange(WANTED_KEY, now, now - WINDOW_MS, {+ byScore: true,+ rev: true,+ offset: 0,+ count: MAX_AGENTS,+ });+ ids = Array.isArray(raw) ? raw.slice(0, MAX_AGENTS) : [];+ } catch {+ return json(res, 200, { agents: [], ts: now });+ }++ if (!ids.length) return json(res, 200, { agents: [], ts: now });++ // Resolve names + a coin-agnostic home so the worker knows where to point the+ // browser for each agent (its profile by default).+ let rows = [];+ try {+ rows = await sql`+ SELECT id, name, home_url+ FROM agent_identities+ WHERE id = ANY(${ids}) AND deleted_at IS NULL+ `;+ } catch { /* fall through with ids only */ }++ const byId = new Map(rows.map((x) => [x.id, x]));+ const agents = ids+ .filter((id) => byId.has(id))+ .map((id) => {+ const a = byId.get(id);+ return {+ agentId: id,+ name: a.name || 'Agent',+ homeUrl: a.home_url || `/agent/${id}`,+ };+ });++ return json(res, 200, { agents, ts: now }, { 'cache-control': 'no-store' });+});diff --git a/workers/agent-screen-pool/Dockerfile b/workers/agent-screen-pool/Dockerfilenew file mode 100644index 000000000..94589d35c--- /dev/null+++ b/workers/agent-screen-pool/Dockerfile@@ -0,0 +1,25 @@+# syntax=docker/dockerfile:1+# agent-screen-pool — on-demand Chromium caster pool.+# Base ships Chromium + all system deps. Pin to the playwright package version.+FROM mcr.microsoft.com/playwright:v1.49.0-jammy++WORKDIR /app++COPY package.json ./+RUN npm install --omit=dev++COPY . .++# Chromium is baked into the base image at /ms-playwright.+ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright+ENV NODE_ENV=production \+ BASE_URL=https://three.ws \+ MAX_BROWSERS=6 \+ POLL_MS=3000 \+ FRAME_MS=700 \+ JPEG_QUALITY=58++# SCREEN_WORKER_SECRET must be supplied at runtime (-e SCREEN_WORKER_SECRET=…).+USER pwuser++CMD ["node", "index.js"]diff --git a/workers/agent-screen-pool/README.md b/workers/agent-screen-pool/README.mdnew file mode 100644index 000000000..1edb16616--- /dev/null+++ b/workers/agent-screen-pool/README.md@@ -0,0 +1,69 @@+# agent-screen-pool++On-demand live-browser caster for the [agent wall](https://three.ws/agents-live).++## Why this exists++Every agent on three.ws has a **live screen 24/7 at zero cost** already: the wall+streams each agent's real `agent_actions` activity from the database and renders+it as a live terminal. No browser required.++This worker adds the *optional* layer on top: a **real Chromium browser feed** for+the agents people are **actively watching right now**. It does not run a browser+per agent forever (that doesn't scale and isn't free) — it casts only what's on+someone's screen, and tears each browser down when the last viewer leaves. Cost+scales with concurrent viewers, not with the number of agents.++## How it works++```+viewer (browser) this worker three.ws API+───────────────── ──────────── ────────────+POST /api/agent/watch-intent ──▶ GET /api/agent/watch-wanted ──▶ { agents:[…] }+ (every ~20s per card) (poll every POLL_MS)+ launch ≤ MAX_BROWSERS pages+ screenshot each every FRAME_MS+ POST /api/agent-screen-push ──▶ Redis frame+viewer SSE ◀── /api/agent-screen-stream ◀──────────────────────── live frames+```++Authentication is a single shared secret, `SCREEN_WORKER_SECRET`, set on both the+API (Vercel env) and this worker. With it the worker may push frames for **any**+agent (it casts on viewers' behalf, it doesn't own the agents).++## Run it++```bash+cd workers/agent-screen-pool+npm install+npx playwright install chromium # local only; the Docker image bakes it in+SCREEN_WORKER_SECRET=<same-as-api> node index.js+```++Docker:++```bash+docker build -t three-ws/agent-screen-pool .+docker run --rm -e SCREEN_WORKER_SECRET=<secret> three-ws/agent-screen-pool+```++## Config (env)++| Var | Default | Notes |+| --- | --- | --- |+| `SCREEN_WORKER_SECRET` | — | **Required.** Must match the API. ≥16 chars. |+| `BASE_URL` | `https://three.ws` | API + page origin. |+| `WANTED_URL` | `$BASE_URL/api/agent/watch-wanted` | Watch-set source. |+| `PUSH_URL` | `$BASE_URL/api/agent-screen-push` | Frame sink (wall convention). |+| `MAX_BROWSERS` | `6` | Concurrency cap = max simultaneous casts. |+| `POLL_MS` | `3000` | How often to reconcile the watch set. |+| `FRAME_MS` | `700` | Screenshot cadence per page (~1.4 fps). |+| `JPEG_QUALITY` | `58` | Frame quality vs. bandwidth. |++## Where to run it++- **Best:** a small always-on VM / Fly.io / Railway container (one process is+ plenty; raise `MAX_BROWSERS` with RAM — budget ~350 MB per concurrent page).+- **Bursts:** the bundled GitHub Actions workflow+ (`.github/workflows/agent-screen-pool.yml`) runs it for up to ~5.5h per+ dispatch — fine for demos and events, not a 24/7 host (Actions caps job time).diff --git a/workers/agent-screen-pool/index.js b/workers/agent-screen-pool/index.jsnew file mode 100644index 000000000..55d0169f7--- /dev/null+++ b/workers/agent-screen-pool/index.js@@ -0,0 +1,180 @@+// agent-screen-pool — on-demand live browser caster for the agent wall.+//+// The problem: users want a live browser feed for ANY agent, 24/7, all of them.+// Running one Chromium per agent forever is economically impossible. So instead+// of casting every agent always, this worker casts exactly the agents people are+// *currently watching*:+//+// 1. Viewers on /agents-live (and any watch panel) POST /api/agent/watch-intent+// for the agents on their screen.+// 2. This worker polls /api/agent/watch-wanted to read that set.+// 3. It maintains a bounded pool of real Chromium pages — one per wanted agent,+// up to MAX_BROWSERS — screenshotting each and pushing frames to+// /api/agent-screen-push (which the wall + watch panel render live).+// 4. When nobody is watching an agent, its page is torn down and the slot frees+// up for another. The wall's zero-cost activity view takes over seamlessly.+//+// Cost scales with concurrent viewers, not with the number of agents. Deploy one+// of these anywhere a long-running Node process can live (a small VM, Fly.io,+// Railway, or the bundled GitHub Actions workflow for bursts).+//+// Required env:+// SCREEN_WORKER_SECRET shared secret; must match the value set on the API.+// Optional env (sensible defaults for production three.ws):+// BASE_URL=https://three.ws+// WANTED_URL=$BASE_URL/api/agent/watch-wanted+// PUSH_URL=$BASE_URL/api/agent-screen-push+// MAX_BROWSERS=6 POLL_MS=3000 FRAME_MS=700 JPEG_QUALITY=58+// VIEWPORT_W=1280 VIEWPORT_H=720++import { chromium } from 'playwright';++const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');+const WANTED_URL = process.env.WANTED_URL || `${BASE_URL}/api/agent/watch-wanted`;+const PUSH_URL = process.env.PUSH_URL || `${BASE_URL}/api/agent-screen-push`;+const SECRET = process.env.SCREEN_WORKER_SECRET || '';++const MAX_BROWSERS = Number(process.env.MAX_BROWSERS || 6);+const POLL_MS = Number(process.env.POLL_MS || 3000);+const FRAME_MS = Number(process.env.FRAME_MS || 700);+const JPEG_QUALITY = Number(process.env.JPEG_QUALITY || 58);+const VIEWPORT = { width: Number(process.env.VIEWPORT_W || 1280), height: Number(process.env.VIEWPORT_H || 720) };++if (!SECRET || SECRET.length < 16) {+ console.error('[pool] SCREEN_WORKER_SECRET is required (>= 16 chars) and must match the API. Exiting.');+ process.exit(1);+}++const log = (...a) => console.log(`[pool ${new Date().toISOString()}]`, ...a);++// agentId → { page, timer, name, pushing, lastErrorAt }+const pool = new Map();+let browser = null;+let context = null;+let stopping = false;++async function ensureBrowser() {+ if (browser) return;+ browser = await chromium.launch({+ headless: true,+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],+ });+ context = await browser.newContext({+ viewport: VIEWPORT,+ userAgent:+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',+ locale: 'en-US',+ });+ log('chromium launched');+}++async function fetchWanted() {+ try {+ const res = await fetch(WANTED_URL, { headers: { authorization: `Bearer ${SECRET}` } });+ if (!res.ok) { log('watch-wanted', res.status); return []; }+ const data = await res.json();+ if (data.disabled) { log('pool disabled by API:', data.reason); return []; }+ return Array.isArray(data.agents) ? data.agents : [];+ } catch (err) {+ log('watch-wanted error:', err?.message || err);+ return [];+ }+}++function resolveUrl(homeUrl, agentId) {+ const u = homeUrl || `/agent/${agentId}`;+ if (/^https?:\/\//.test(u)) return u;+ return `${BASE_URL}${u.startsWith('/') ? '' : '/'}${u}`;+}++async function pushFrame(entry) {+ if (entry.pushing || !entry.page || entry.page.isClosed()) return;+ entry.pushing = true;+ try {+ const buf = await entry.page.screenshot({ type: 'jpeg', quality: JPEG_QUALITY, fullPage: false });+ const data = `data:image/jpeg;base64,${buf.toString('base64')}`;+ const res = await fetch(PUSH_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${SECRET}` },+ body: JSON.stringify({+ agentId: entry.agentId,+ frame: { data, activity: `Live view · ${entry.name}`, type: 'screenshot' },+ }),+ });+ if (!res.ok && Date.now() - (entry.lastErrorAt || 0) > 30_000) {+ entry.lastErrorAt = Date.now();+ log('push failed', entry.agentId, res.status, (await res.text().catch(() => '')).slice(0, 120));+ }+ } catch (err) {+ if (Date.now() - (entry.lastErrorAt || 0) > 30_000) {+ entry.lastErrorAt = Date.now();+ log('frame error', entry.agentId, err?.message || err);+ }+ } finally {+ entry.pushing = false;+ }+}++async function startCasting(agent) {+ await ensureBrowser();+ const agentId = agent.agentId;+ const page = await context.newPage();+ const entry = { agentId, page, name: agent.name || 'Agent', timer: null, pushing: false, lastErrorAt: 0 };+ pool.set(agentId, entry);+ const url = resolveUrl(agent.homeUrl, agentId);+ try {+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });+ } catch (err) {+ log('goto failed', agentId, err?.message || err);+ }+ await pushFrame(entry);+ entry.timer = setInterval(() => pushFrame(entry), FRAME_MS);+ log('casting', agentId, agent.name, '→', url, `(${pool.size}/${MAX_BROWSERS})`);+}++async function stopCasting(agentId) {+ const entry = pool.get(agentId);+ if (!entry) return;+ pool.delete(agentId);+ if (entry.timer) clearInterval(entry.timer);+ try { await entry.page?.close(); } catch { /* */ }+ log('stopped', agentId, `(${pool.size}/${MAX_BROWSERS})`);+}++async function reconcile() {+ if (stopping) return;+ const wanted = await fetchWanted();+ const wantedIds = wanted.map((a) => a.agentId);+ const wantedSet = new Set(wantedIds);++ // Tear down agents nobody is watching anymore.+ for (const id of [...pool.keys()]) {+ if (!wantedSet.has(id)) await stopCasting(id);+ }++ // Spin up newly-watched agents, respecting the concurrency cap. Most-wanted+ // first (watch-wanted returns them in recency order).+ for (const agent of wanted) {+ if (pool.size >= MAX_BROWSERS) break;+ if (!pool.has(agent.agentId)) {+ try { await startCasting(agent); }+ catch (err) { log('startCasting failed', agent.agentId, err?.message || err); }+ }+ }+}++async function shutdown() {+ if (stopping) return;+ stopping = true;+ log('shutting down…');+ for (const id of [...pool.keys()]) await stopCasting(id);+ try { await browser?.close(); } catch { /* */ }+ process.exit(0);+}++process.on('SIGINT', shutdown);+process.on('SIGTERM', shutdown);++log(`starting · base=${BASE_URL} · max=${MAX_BROWSERS} · poll=${POLL_MS}ms · frame=${FRAME_MS}ms`);+await reconcile();+setInterval(reconcile, POLL_MS);diff --git a/workers/agent-screen-pool/package.json b/workers/agent-screen-pool/package.jsonnew file mode 100644index 000000000..6e12fe1fd--- /dev/null+++ b/workers/agent-screen-pool/package.json@@ -0,0 +1,14 @@+{+ "name": "agent-screen-pool",+ "version": "0.1.0",+ "private": true,+ "type": "module",+ "main": "index.js",+ "scripts": {+ "start": "node index.js"+ },+ "engines": { "node": ">=20" },+ "dependencies": {+ "playwright": "^1.49.0"+ }+}