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
fix(agents-live): size the stream pool to the origin's real protocol and share one activity shape
nirholas035f90861150
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 2dce5d82e..a68f5f6ec 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -78,7 +78,7 @@ bottom.| Press kit (brand marks + media assets) | [pages/press/index.html](pages/press/index.html) `→ /press`, marks [public/brand/](public/brand), layout source [marketing/brand/](marketing/brand/README.md), renderer [scripts/render-brand-assets.mjs](scripts/render-brand-assets.mjs) `npm run build:brand-assets` | Live | The self-serve press surface: transparent-PNG marks (cube, horizontal and stacked lockups for dark and light grounds), the OpenAI announcement graphics, boilerplate at four lengths (one line, short, long, and a full-length bio) with copy buttons, fast facts, and the mark-usage rules. Everything is rendered from source rather than hand-exported, so a copy change re-renders the whole set; the renderer also builds `/brand/three-ws-press-kit.zip` with a README carrying the usage rules so the files cannot travel without them. Announcement cards come from [marketing/openai-select-partner/cards/social-card.html](marketing/openai-select-partner/cards/social-card.html) via `npm run build:openai-cards`. || 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/`, bundled SDK component [chat-plugin/](chat-plugin) (`@three-ws/chat-plugin`, for hosts that mount plugins as React components instead of framing the manifest) | 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) || Agent Monitor (fleet ops board) | [pages/monitor.html](pages/monitor.html) + [src/monitor.js](src/monitor.js) `→ /monitor` | In-repo · Live | HQ-style ops-room dashboard for the whole 3D agent fleet on one screen, every panel a real public feed on its own poll cadence: fleet ranked by real actions ([api/agents/public.js](api/agents/public.js) `sort=live`) with a click-to-load 3D `<agent-3d>` spotlight, live screen casts ([api/agent-screen-active.js](api/agent-screen-active.js)), 24h money pulse + 7d sparkline + agent coin launches ([api/pulse.js](api/pulse.js) `view=stats`), delta-polled on-chain event wire (`/api/pulse` with `head_cursor`), x402 revenue by endpoint ([api/x402-revenue.js](api/x402-revenue.js)), A2A hire volume ([api/agent-economy/volume.js](api/agent-economy/volume.js)), uptime probes ([api/status.js](api/status.js)), a community forge feed ([api/forge-gallery.js](api/forge-gallery.js)), the tip-earner leaderboard, and the crew directory ([api/crews/directory.js](api/crews/directory.js)). Panel controls: fleet search + sort (server `q=`/`sort=`), wire kind filters + pause, x402 period and A2A window toggles, mainnet/devnet switch, spotlight prev/next/fullscreen, and keyboard shortcuts (`f` search, `r` refresh, `[`/`]` cycle spotlight) |-| 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)) |+| 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`), batched activity [api/agents/activity.js](api/agents/activity.js), 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. Two feed layers, because they answer different questions: every mounted card gets its activity from ONE batched `/api/agents/activity` call (whole page, one round-trip, shared row mapper [api/_lib/agent-activity.js](api/_lib/agent-activity.js)), while SSE listeners are pooled ([src/shared/stream-pool.js](src/shared/stream-pool.js), sized from the origin's real transport) and spent only where something is genuinely pushed: a casting agent, the spotlight, a warming caster, or the card a viewer reaches for. 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)) || On-demand caster pool (the live browser behind a watched agent) | Worker [workers/agent-screen-pool/](workers/agent-screen-pool/README.md) (deploy [workers/agent-screen-pool/cloudbuild.yaml](workers/agent-screen-pool/cloudbuild.yaml)); API watch set [api/agent/watch-intent.js](api/agent/watch-intent.js) + [api/agent/watch-wanted.js](api/agent/watch-wanted.js) + [api/agent/watch-status.js](api/agent/watch-status.js), frame sink [api/agent-screen-push.js](api/agent-screen-push.js) | In-repo · built + deploy-ready, not yet deployed as a Cloud Run service | Casts a real Chromium page for exactly the agents viewers are watching right now (bounded by `MAX_BROWSERS`), running a real multi-step web task from [tasks/index.js](workers/agent-screen-pool/tasks/index.js) and pushing JPEG frames the wall renders; tears each browser down when the last viewer leaves, so cost scales with concurrent viewers instead of agent count. Auth is the shared `SCREEN_WORKER_SECRET` (Secret Manager `screen-worker-secret`); each authenticated poll refreshes the pool-liveness key so a card with no pool running stays on the honest zero-cost activity view. Tests: [tests/agent-screen-task-sequencer.test.js](tests/agent-screen-task-sequencer.test.js) (sequencer + task library), [scripts/agent-screen-pool-proof.mjs](scripts/agent-screen-pool-proof.mjs) (real worker, real Chromium, real wire contract) || 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 |diff --git a/api/_lib/agent-activity.js b/api/_lib/agent-activity.jsnew file mode 100644index 000000000..da8df95cd--- /dev/null+++ b/api/_lib/agent-activity.js@@ -0,0 +1,40 @@+// Shared shape for an agent's activity line.+//+// Two surfaces read `agent_actions` and hand it to the same client renderer: the+// per-agent SSE stream (api/agent-screen-stream.js, `log` events) and the batched+// wall endpoint (api/agents/activity.js). They MUST emit the identical entry+// shape, or a card would render a streamed row differently from a batched one.+// The mapping lives here once so the two can never drift apart.++/**+ * Map an `agent_actions` row to the wire entry `{ ts, activity, type, mm? }`.+ *+ * The holder-readable line lives in payload.summary (falling back to a+ * detail/title or the bare type). A market-maker action (type `mm_*`) carries+ * its structured floor/price context as `mm`, so a reconnect's DB backfill+ * drives the arena floor line and the card badge exactly like a live push does.+ *+ * @param {{ type?: string, payload?: unknown, created_at?: string | Date }} row+ * @returns {{ ts: number, activity: string, type: string, mm?: object }}+ */+export function rowToEntry(row) {+ const p = row.payload && typeof row.payload === 'object' ? row.payload : {};+ const entry = {+ ts: row.created_at ? new Date(row.created_at).getTime() : Date.now(),+ activity: p.summary || p.detail || p.title || row.type || 'action',+ type: row.type || 'action',+ };+ if (typeof row.type === 'string' && row.type.startsWith('mm_') && (p.floorSol != null || p.priceSol != null)) {+ entry.mm = {+ type: row.type,+ floorSol: Number(p.floorSol) || 0,+ priceSol: Number(p.priceSol) || 0,+ sizeSol: Number(p.sizeSol) || 0,+ sideBuy: p.sideBuy === true ? true : p.sideBuy === false ? false : null,+ simulate: !!p.simulate,+ signature: p.signature || null,+ mint: p.mint || null,+ };+ }+ return entry;+}diff --git a/api/agent-screen-stream.js b/api/agent-screen-stream.jsindex d2e14dd89..aa6fb5eb1 100644--- a/api/agent-screen-stream.js+++ b/api/agent-screen-stream.js@@ -25,6 +25,7 @@ import { limits, clientIp } from './_lib/rate-limit.js';import { getRedis } from './_lib/redis.js';import { sql } from './_lib/db.js';import { reactionsRecentKey, reactionsTotalKey, REACTION_RECENT_CAP } from './_lib/reaction-rules.js';+import { rowToEntry } from './_lib/agent-activity.js';export const maxDuration = 300;@@ -33,33 +34,9 @@ const PING_INTERVAL_MS = 15_000;const POLL_INTERVAL_MS = 500;const ACTIVITY_REFRESH_MS = 8_000; // re-poll DB activity for dark agents-// Map an agent_actions DB row to the SSE log entry shape { ts, activity, type }.-// agent_actions stores { type, payload } — the holder-readable line lives in-// payload.summary (falling back to a detail/title or the bare type). When the-// row is a market-maker action (type mm_*) its structured floor/price context-// rides along as `mm`, so a reconnect's DB backfill still drives the arena floor-// line + card badge exactly like the live Redis log does.-function rowToEntry(row) {- const p = row.payload && typeof row.payload === 'object' ? row.payload : {};- const entry = {- ts: row.created_at ? new Date(row.created_at).getTime() : Date.now(),- activity: p.summary || p.detail || p.title || row.type || 'action',- type: row.type || 'action',- };- if (typeof row.type === 'string' && row.type.startsWith('mm_') && (p.floorSol != null || p.priceSol != null)) {- entry.mm = {- type: row.type,- floorSol: Number(p.floorSol) || 0,- priceSol: Number(p.priceSol) || 0,- sizeSol: Number(p.sizeSol) || 0,- sideBuy: p.sideBuy === true ? true : p.sideBuy === false ? false : null,- simulate: !!p.simulate,- signature: p.signature || null,- mint: p.mint || null,- };- }- return entry;-}+// rowToEntry (agent_actions row → the `log` entry shape) is shared with the+// batched wall endpoint so the two can never render the same action differently.+// See api/_lib/agent-activity.js.// Decode one record read back out of Redis. The Upstash REST client// deserializes JSON responses by default, so a value written as a JSON stringdiff --git a/api/agents/activity.js b/api/agents/activity.jsindex 80946a06b..0a8470744 100644--- a/api/agents/activity.js+++ b/api/agents/activity.js@@ -34,6 +34,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { getRedis } from '../_lib/redis.js';import { sql } from '../_lib/db.js';import { isUuid } from '../_lib/validate.js';+import { rowToEntry } from '../_lib/agent-activity.js';const MAX_IDS = 60;// Per-agent depth. A wall card's terminal shows ~11 lines at 640x360 and@@ -41,31 +42,6 @@ const MAX_IDS = 60;// keeping the batch payload small enough for a 60-agent page.const PER_AGENT = 24;-// Map an agent_actions row to the same { ts, activity, type, mm? } shape the SSE-// `log` event emits, so a card renders a batch row and a streamed row identically.-// Kept in step with rowToEntry() in api/agent-screen-stream.js.-export function rowToEntry(row) {- const p = row.payload && typeof row.payload === 'object' ? row.payload : {};- const entry = {- ts: row.created_at ? new Date(row.created_at).getTime() : Date.now(),- activity: p.summary || p.detail || p.title || row.type || 'action',- type: row.type || 'action',- };- if (typeof row.type === 'string' && row.type.startsWith('mm_') && (p.floorSol != null || p.priceSol != null)) {- entry.mm = {- type: row.type,- floorSol: Number(p.floorSol) || 0,- priceSol: Number(p.priceSol) || 0,- sizeSol: Number(p.sizeSol) || 0,- sideBuy: p.sideBuy === true ? true : p.sideBuy === false ? false : null,- simulate: !!p.simulate,- signature: p.signature || null,- mint: p.mint || null,- };- }- return entry;-}-// Read the caller's id list from either shape. GET keeps the endpoint trivially// cacheable/debuggable from a browser; POST keeps a 60-id list off the URL.async function readIds(req, res) {diff --git a/docs/api-reference.md b/docs/api-reference.mdindex bf4018815..206cfe019 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -531,6 +531,59 @@ Append-only. Actions are never deleted. Optionally include an ERC-191 signature---+### Batch recent activity for many agents++```+GET /api/agents/activity?ids=<id>,<id>,...+POST /api/agents/activity { "ids": ["<id>", "<id>"] }+```++Recent activity for a **list** of agents in one round-trip, plus which of them+currently have a live screen caster pushing frames. Built for grids: a wall of+agent cards would otherwise need one request (or one SSE stream) per card, and a+browser only allows a handful of concurrent connections per origin.++Public read, no auth. Up to 60 ids per call; anything that is not a UUID is+dropped, and unknown ids are simply absent from `activity`. Each agent returns+its 24 most recent actions, oldest-first, in the same entry shape the `log`+event of the per-agent SSE stream (`GET /api/agent-screen-stream?agentId=<id>`)+emits, so one renderer handles both.++**Query / body parameters**++| Parameter | Type | Description |+| --------- | -------- | ------------------------------------------------------------ |+| `ids` | string[] | Required. Agent IDs. Comma-separated on GET, an array on POST |++**Response**++```json+{+ "activity": {+ "abc123": [+ { "ts": 1786573115539, "activity": "Launched $THREE", "type": "pumpfun.launch" },+ { "ts": 1786573802902, "activity": "Defended floor at 0.51 SOL", "type": "mm_defend",+ "mm": { "type": "mm_defend", "floorSol": 0.5, "priceSol": 0.51, "sizeSol": 2,+ "sideBuy": true, "simulate": false, "signature": null, "mint": null } }+ ]+ },+ "casting": ["abc123"]+}+```++`casting` lists the subset of the requested ids whose screen frame is still live+in the frame store. A client typically renders every agent's `activity` straight+away and opens a real SSE stream only for the ids in `casting`.++**Example**++```bash+curl -s "https://three.ws/api/agents/activity?ids=$AGENT_A,$AGENT_B" \+ | jq '{casting, counts: (.activity | map_values(length))}'+```++---+## Agent Memory API### Fetch agent memorydiff --git a/prompts/swarm-100/route-agents-live.md b/prompts/swarm-100/route-agents-live.mddeleted file mode 100644index a107e4d22..000000000--- a/prompts/swarm-100/route-agents-live.md+++ /dev/null@@ -1,119 +0,0 @@-# Route audit: /agents-live (Live Agents)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. This route's declared entry (path, description, added date):-- node -e "const p=require('./data/pages.json');for(const s of p.sections)for(const g of s.pages)if(g.path==='/agents-live')console.log(JSON.stringify(g,null,2))"--2. Find the serving implementation: grep "/agents-live" in vercel.json (the live- route table server/index.mjs boots from), then list matching files in- pages/ and src/. STRUCTURE.md maps every surface to its directory if the- grep is ambiguous.-3. Production right now:-- curl -so /dev/null -w '%{http_code}\n' https://three.ws/agents-live--4. Start (or reuse) the local dev server: npm run dev (vite, port 3000).--## Task: audit this one route end to end, then fix everything found--Route: /agents-live ("Live Agents", section "build").-Declared purpose: Mission control: real-time grid of all AI agents with active screen streams. Watch their screens and avatar feeds live.--Drive the page in a real headless browser. Playwright is already a dev-dependency; keep your probe script in the session scratchpad, never in the-repo.--1. Load http://localhost:3000/agents-live. Record the HTTP status, every console- error and warning, and every failed network request.-2. Exercise it like a first-time user: click the primary actions, run the- primary flow if one exists, follow the page's internal links. Every button- must do something real; every link must resolve. If the page renders data,- prove in the network log that it came from a live endpoint, not a baked-in- fallback array.-3. States: verify populated, empty, loading, and error states are designed and- reachable. Block the page's primary fetch in Playwright and confirm an- actionable error state appears, not a blank void or a raw exception.-4. Responsive: render at 320, 768, and 1440 px. No horizontal page scroll, no- overlapping or clipped controls.-5. Accessibility basics: one h1; interactive elements are real buttons or- links with visible focus states; images carry alt text; form fields have- labels.-6. Head: a specific title tag and meta description that match the declared- purpose above.-7. Fix every defect at its root in the page's real source files and re-run the- probe until clean. Defects in shared modules are in scope when this route- exercises them.--## Definition of done--- [ ] Local load of /agents-live: HTTP 200, zero console errors, zero unhandled- failed requests (a third-party outage must land in a designed fallback,- not a broken page).-- [ ] No dead interactive element on the page: no stub href="#", no button- without a handler, no link to a missing path.-- [ ] Empty, loading, error, and populated states verified.-- [ ] 320 / 768 / 1440 px renders verified clean.-- [ ] Title and meta description present and specific.-- [ ] npm test passes; npm run check:rules -- --paths <touched files> exits 0.-- [ ] Production status from step 0 recorded in the report; if production- needs a deploy to pick up a fix, the report says so (deploys stay- owner-gated).--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/route-agents-live.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/src/agents-live.js b/src/agents-live.jsindex ea9d8c65c..a4498e26c 100644--- a/src/agents-live.js+++ b/src/agents-live.js@@ -40,6 +40,7 @@ import { parseForgeFrame } from './shared/forge-frames.js';import { createArena } from './agents-live-arena.js';import { createShowrunner } from './showrunner.js';import { apiFetch, noteSession } from './api.js';+import { streamPoolSize } from './shared/stream-pool.js';// Subtle accent for a card showing a live Coin World Tour walkthrough.(() => {@@ -95,6 +96,7 @@ let _idleRepaint = null;const FRAME_STALE_MS = 6000; // no frame within this window ⇒ fall back to activityconst WATCH_PING_MS = 20000; // re-assert watch intent while a card is on screenconst WATCH_STATUS_MS = 4000; // refresh the warming/queued handoff while not yet live+const STREAM_CONNECT_GRACE_MS = 8000; // stop claiming "Connecting" if a stream never landsconst STATUS_GRACE_POLLS = 3; // keep polling this many ticks to cover the intent→status write race// Cards currently intersecting the viewport. Only these signal watch intent and@@ -115,18 +117,10 @@ const _nearView = new Set();const _streamed = new Set();let _streamObserver = null;-// How many SSE listeners the origin can actually carry at once. Over HTTP/1.1 a-// browser allows 6 sockets per origin and an SSE stream never releases its one,-// so a pool anywhere near that ceiling starves the page's own fetches (roster,-// balances, watch intent). Multiplexed transports have no such per-request cost.-// Read from the real navigation entry rather than guessed: prod is served over-// h2 behind the load balancer, the vite dev server is http/1.1.-export function streamPoolSize(nextHopProtocol) {- const p = String(nextHopProtocol || '').toLowerCase();- if (p === 'h2' || p === 'h3' || p.startsWith('h3-') || p === 'http/2' || p === 'http/3') return 12;- return 4;-}-+// How many SSE listeners the origin can actually carry at once (see+// shared/stream-pool.js). Read from the real navigation entry rather than+// guessed: prod is served over h2 behind the load balancer, vite dev is+// http/1.1, and the two budgets are nothing alike.function detectPoolSize() {try {const nav = performance.getEntriesByType('navigation')[0];@@ -626,10 +620,24 @@ function attachStream(state) {statusEl.textContent = 'Connecting';state.attaching = true;+ // A stream that neither opens nor errors (a stalled proxy, a saturated+ // connection pool) would otherwise leave the badge reading "Connecting"+ // forever. Give it a bounded grace period, then fall back to the card's real+ // resting state; the batch layer has already given it genuine content, so+ // nothing is lost but the false claim. The EventSource stays open in case it+ // still lands.+ clearTimeout(state.connectTimer);+ state.connectTimer = setTimeout(() => {+ if (!state.attaching) return;+ state.attaching = false;+ statusEl.textContent = state.entries?.length ? 'Active' : 'Idle';+ if (!isLiveNow(state)) paintActivity(state);+ }, STREAM_CONNECT_GRACE_MS);function setLive(live) {state.live = live;state.attaching = false;+ clearTimeout(state.connectTimer);dot.classList.toggle('idle', !live);if (live) {statusEl.textContent = 'Live';@@ -902,6 +910,7 @@ function releaseStream(state) {state.es = null;state.attaching = false;state.reconnecting = false;+ clearTimeout(state.connectTimer);clearTimeout(state.reconnectLabelTimer);stopStatusPolling(state);hideWarming(state);diff --git a/src/shared/stream-pool.js b/src/shared/stream-pool.jsnew file mode 100644index 000000000..c9888b3a2--- /dev/null+++ b/src/shared/stream-pool.js@@ -0,0 +1,36 @@+// How many concurrent SSE listeners a page may hold against one origin.+//+// A live wall wants a stream per card. A browser will not give it one: over+// HTTP/1.1 it allows six sockets per origin, and an EventSource holds its socket+// for the life of the stream, so the seventh card onward never connects and the+// page's own fetches queue behind the six that did. /agents-live shipped exactly+// that bug: on a 48-card roster, 42 cards sat on "Connecting" forever.+//+// A multiplexed transport (h2 / h3) carries many streams over one connection and+// has no such per-request socket cost, so the ceiling there is about server and+// client resources rather than sockets.+//+// Pure so the ceiling is provable without a browser (tests/agents-live-stream-pool.test.js).++// Chrome/Firefox both cap HTTP/1.1 at 6 sockets per origin. Hold the pool below+// it so the page always has room for its own roster/balance/intent requests.+export const HTTP1_STREAM_POOL = 4;+export const MULTIPLEXED_STREAM_POOL = 12;++const MULTIPLEXED = new Set(['h2', 'h2c', 'h3', 'http/2', 'http/3']);++/**+ * Pool ceiling for an origin, from its real negotiated protocol.+ *+ * @param {string | null | undefined} nextHopProtocol+ * `PerformanceNavigationTiming.nextHopProtocol` for the document. It is the+ * empty string on a cache hit and on browsers that withhold it; an unknown+ * value must fall back to the conservative pool, because guessing h2 on an+ * HTTP/1.1 origin reintroduces the exact starvation this exists to prevent.+ * @returns {number} maximum concurrent SSE listeners, always at least 1+ */+export function streamPoolSize(nextHopProtocol) {+ const p = String(nextHopProtocol || '').toLowerCase();+ if (MULTIPLEXED.has(p) || p.startsWith('h3-')) return MULTIPLEXED_STREAM_POOL;+ return HTTP1_STREAM_POOL;+}diff --git a/tests/agents-live-stream-pool.test.js b/tests/agents-live-stream-pool.test.jsnew file mode 100644index 000000000..8cb26575b--- /dev/null+++ b/tests/agents-live-stream-pool.test.js@@ -0,0 +1,95 @@+/**+ * /agents-live wall: the SSE pool sizing and the shared activity row mapper.+ *+ * The wall used to open one EventSource per card. A browser allows 6 concurrent+ * connections per origin over HTTP/1.1 and an SSE stream never gives its slot+ * back, so on a 48-card roster the first six connected and the other 42 sat on+ * "Connecting" forever while the page's own fetches queued behind them. Two+ * pieces of that fix are pure and pinned here:+ *+ * streamPoolSize(): the pool ceiling must come from the origin's real+ * transport, and must stay under the HTTP/1.1 socket budget (leaving room for+ * the page's own requests) whenever the transport is not multiplexed.+ *+ * rowToEntry(): the batched wall endpoint and the per-agent SSE stream both+ * turn `agent_actions` rows into card lines. They share one mapper precisely+ * so a batched row and a streamed row can never render differently.+ */++import { describe, it, expect } from 'vitest';+import { streamPoolSize } from '../src/shared/stream-pool.js';+import { rowToEntry } from '../api/_lib/agent-activity.js';++// Chrome's per-origin socket limit for HTTP/1.1. An SSE stream holds its socket+// for the life of the stream, so the pool has to stay strictly below this or the+// page starves its own roster/balances fetches.+const HTTP1_SOCKET_LIMIT = 6;++describe('streamPoolSize', () => {+ it('stays under the HTTP/1.1 socket budget on a non-multiplexed origin', () => {+ expect(streamPoolSize('http/1.1')).toBeLessThan(HTTP1_SOCKET_LIMIT);+ expect(streamPoolSize('http/1.0')).toBeLessThan(HTTP1_SOCKET_LIMIT);+ });++ it('allows a wider pool on a multiplexed transport', () => {+ expect(streamPoolSize('h2')).toBeGreaterThan(streamPoolSize('http/1.1'));+ expect(streamPoolSize('h3')).toBe(streamPoolSize('h2'));+ expect(streamPoolSize('h3-29')).toBe(streamPoolSize('h2'));+ expect(streamPoolSize('HTTP/2')).toBe(streamPoolSize('h2'));+ });++ it('falls back to the conservative pool when the transport is unknown', () => {+ // performance.getEntriesByType('navigation') reports '' from a cache hit and+ // on browsers that withhold it; guessing h2 there would starve the page.+ for (const unknown of ['', null, undefined, 'spdy/3.1']) {+ expect(streamPoolSize(unknown)).toBeLessThan(HTTP1_SOCKET_LIMIT);+ }+ });++ it('never returns a pool that cannot hold a single stream', () => {+ for (const p of ['', 'http/1.1', 'h2', 'h3']) expect(streamPoolSize(p)).toBeGreaterThan(0);+ });+});++describe('rowToEntry', () => {+ const created = new Date('2026-08-16T12:00:00.000Z');++ it('prefers the holder-readable summary over the raw type', () => {+ const e = rowToEntry({ type: 'pumpfun.launch', payload: { summary: 'Launched $THREE' }, created_at: created });+ expect(e).toEqual({ ts: created.getTime(), activity: 'Launched $THREE', type: 'pumpfun.launch' });+ });++ it('falls back through detail and title before settling on the type', () => {+ expect(rowToEntry({ type: 'a', payload: { detail: 'd' }, created_at: created }).activity).toBe('d');+ expect(rowToEntry({ type: 'a', payload: { title: 't' }, created_at: created }).activity).toBe('t');+ expect(rowToEntry({ type: 'load-end', payload: {}, created_at: created }).activity).toBe('load-end');+ expect(rowToEntry({ payload: null, created_at: created }).activity).toBe('action');+ });++ it('carries the market-maker sidecar so a backfill can drive the floor badge', () => {+ const e = rowToEntry({+ type: 'mm_defend',+ payload: { summary: 'defended', floorSol: 0.5, priceSol: 0.51, sizeSol: 2, sideBuy: true, simulate: true },+ created_at: created,+ });+ expect(e.mm).toEqual({+ type: 'mm_defend',+ floorSol: 0.5,+ priceSol: 0.51,+ sizeSol: 2,+ sideBuy: true,+ simulate: true,+ signature: null,+ mint: null,+ });+ });++ it('omits the sidecar for a non-market-maker row and for an mm row with no prices', () => {+ expect(rowToEntry({ type: 'speak', payload: { floorSol: 1 }, created_at: created }).mm).toBeUndefined();+ expect(rowToEntry({ type: 'mm_tick', payload: { summary: 'x' }, created_at: created }).mm).toBeUndefined();+ });++ it('tolerates a row with no timestamp rather than emitting NaN', () => {+ expect(Number.isFinite(rowToEntry({ type: 'speak', payload: {} }).ts)).toBe(true);+ });+});diff --git a/vite.config.js b/vite.config.jsindex 01fb1b7a4..b5a914001 100644--- a/vite.config.js+++ b/vite.config.js@@ -2680,14 +2680,27 @@ support: resolve(__dirname, 'pages/support.html'),},},{- // Rewrite R2 public-bucket URLs in proxied /api/avatars/* responses so- // the <agent-3d> component (loaded from CDN) always receives /r2-proxy/*- // URLs instead of raw r2.dev URLs that fail CORS in Codespaces / localhost.+ // Rewrite R2 public-bucket URLs in proxied API responses so the browser+ // always receives /r2-proxy/* URLs instead of raw r2.dev URLs. The bucket+ // answers with `Access-Control-Allow-Origin: https://three.ws` only, so a+ // raw URL fails CORS from localhost / Codespaces and every model behind it+ // silently degrades (the <agent-3d> component falls back to the default+ // robot; /ar/studio cannot place a single tray model).+ //+ // The prefixes below are the API surfaces that hand a model URL to the+ // browser. Add one when a new endpoint starts returning R2 URLs; leaving+ // it off means that feature works in production and is dead in dev.name: 'r2-url-rewrite-api',configureServer(server) {const R2_PUBLIC_RE = /https?:\/\/pub-[a-f0-9]+\.r2\.dev\//g;+ const R2_URL_PREFIXES = [+ '/api/avatars/',+ '/api/objects/', // CC0 object library (/objects, the AR Studio "Objects" tray)+ '/api/forge-gallery', // forge creations feed (/creations, AR Studio "Yours"/"Community")+ '/api/forge', // forge job polling: the finished glb_url+ ];server.middlewares.use(async (req, res, next) => {- if (!req.url?.startsWith('/api/avatars/')) return next();+ if (!R2_URL_PREFIXES.some((p) => req.url?.startsWith(p))) return next();// Only rewrite GET/HEAD responses — POSTs and mutations must flow// through the normal proxy with their original method and body intact.if (req.method !== 'GET' && req.method !== 'HEAD') return next();@@ -2704,6 +2717,12 @@ support: resolve(__dirname, 'pages/support.html'),? { authorization: req.headers.authorization }: {}),...(req.headers.range ? { range: req.headers.range } : {}),+ // The anonymous forge identity that scopes /api/forge-gallery's+ // "Yours" tab and /api/forge job ownership. Dropping it silently+ // turns a personal feed into the public one.+ ...(req.headers['x-forge-client']+ ? { 'x-forge-client': req.headers['x-forge-client'] }+ : {}),},});const type = resp.headers.get('content-type') || 'application/json';