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.

agent-voice-chat: complete BUILD_LOG + dashboard / elevenlabs follow-up prompts

nirholasc14ccfaa04fe
diff --git a/agent-voice-chat/BUILD_LOG.md b/agent-voice-chat/BUILD_LOG.md
new file mode 100644
index 000000000..45a652a31
--- /dev/null
+++ b/agent-voice-chat/BUILD_LOG.md
@@ -0,0 +1,363 @@
+# Build Log — autonomous X Spaces voice agent
+
+Complete narrative of how this system was built on 2026-05-13. Includes every dead-end, every patch, and every recovery so anyone can pick up the work cold. Read alongside [`README.md`](./README.md), [`docs/architecture.md`](./docs/architecture.md), and [`docs/troubleshooting.md`](./docs/troubleshooting.md).
+
+The goal across all phases: have one or more AI agents join an X (Twitter) Space as speakers, hold a real-time voice conversation with each other and with humans in the room, and run entirely in the cloud with no operator audio routing required.
+
+---
+
+## Phase 1 — exploring the existing xspace-agent SDK
+
+The repo already contained an in-progress TypeScript SDK (`packages/core` — `xspace-agent` on npm) that automates X Spaces via Puppeteer. The plan: get its `xspace-agent join <url>` CLI working.
+
+What broke:
+- `pnpm turbo run build --filter=xspace-agent` failed in `packages/core`. Ten dynamic-import statements were missing `.js` extensions, an error blocked by `moduleResolution: nodenext`. Files: `src/auth/saml.ts:213`, `src/auth/service.ts:287,299,321`, `src/gateway/api-key-service.ts:136,137,185,186`, `src/queue/processors/usage-processor.ts:19`. Each fixed with the corresponding `.js` extension.
+- A second build failure surfaced: drizzle-orm dual-module type conflict (TS2741 / "Types have separate declarations of a private property 'shouldInlineParams'"). This was unfixable without restructuring the ORM imports, so we abandoned the full build and used the already-built `packages/core/dist/` (5.1 MB, from a prior build) plus a standalone tsx runner script (`run-join.ts`) that imports `XSpaceAgent` from the dist.
+- Puppeteer needed Chromium system libs the Codespace didn't have. Install: `sudo apt install libatk1.0-0t64 libatk-bridge2.0-0t64 libcups2t64 libxkbcommon0 libatspi2.0-0t64 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libnss3 libpangocairo-1.0-0 libpango-1.0-0 libgtk-3-0t64 libdrm2 libasound2t64 libdbus-1-3 fonts-liberation`. Note the `t64` suffix — Ubuntu 24.04 renamed several libs in the time_t transition; the old names (`libasound2`, `libgtk-3-0`) fail with "no installation candidate".
+
+The agent did successfully run end-to-end against a live Space at this point:
+- Cookie auth (`X_AUTH_TOKEN` + `X_CT0`) worked via `[X-Spaces] Login successful via auth_token`.
+- Audio hooks injected post-join.
+- Speaker request sent.
+
+But:
+- The post-join UI controls didn't appear within 20s. The page showed a "Start listening" button the SDK never clicked — it tried to find "Request to speak" before joining the audio room. The SDK's `space-ui.ts` selector engine matched a different button as "join" and force-clicked it; the page state never advanced.
+- "Aggressive unmute" fallback ran but couldn't find a mic button either.
+
+That dead-end is what triggered the next pivot.
+
+## Phase 2 — pivot to `ai-agents-x-space` (OpenAI Realtime API)
+
+The user pointed at https://github.com/devaiacc/ai-agents-x-space and https://github.com/devaiacc/MoltyTalky. The first one uses **OpenAI Realtime API** over WebRTC — a single continuous voice connection that does STT + LLM + TTS server-side, with ~600ms turn latency. Their X Spaces "integration" is hand-wavy ("create a Space and connect the agents as speakers") — they assume the operator manually routes audio through BlackHole on a Mac. No automation of X's UI.
+
+Decision: combine the two. Use Realtime for the voice loop, write our own X-UI automation, do everything on a Linux VM with PulseAudio virtual cables (cleaner than single-channel BlackHole on macOS).
+
+## Phase 3 — GCP VM provisioning
+
+Authed `gcloud` in the Codespace via the no-launch-browser flow, picked the user's existing project `aerial-vehicle-466722-p5`, enabled the Compute Engine API.
+
+Created the VM:
+
+```bash
+gcloud compute instances create swarm-agent \
+ --zone=us-central1-a --machine-type=e2-standard-2 \
+ --image-family=ubuntu-2204-lts --image-project=ubuntu-os-cloud \
+ --boot-disk-size=30GB \
+ --no-service-account --no-scopes \
+ --tags=swarm-agent
+```
+
+`--no-service-account` was forced because the default Compute Engine SA didn't exist on this fresh project. The agent doesn't need GCP APIs from inside the VM, so this is fine.
+
+External IP came back: `104.155.161.226`.
+
+## Phase 4 — VM startup script and its breakage
+
+Wrote `vm-setup.sh` to bootstrap the VM in one shot. The initial version tried to install Chrome Remote Desktop too (so the operator could see the desktop), but the CRD package failed to set up its `chrome-remote-desktop` Unix group, then `usermod -aG chrome-remote-desktop agent` failed with "group does not exist" and `set -e` aborted the whole script.
+
+Recovery:
+1. Dropped the CRD dependency entirely (we don't need a viewable desktop — Puppeteer/CDP drives Chrome over the network).
+2. Finished setup manually via SSH: created `agent` user without CRD group, installed remaining apt packages (xvfb, xdotool, pulseaudio, ffmpeg, all the Chromium runtime libs).
+3. Wrote a clean rewrite of `setup.sh` for the repo (the one in `vm/setup.sh` today) that doesn't include CRD and is fully idempotent.
+
+The clean PulseAudio config (per-user at `~/.config/pulse/default.pa`):
+
+```pa
+.include /etc/pulse/default.pa
+
+# Cable A: agent_speakers -> x_mic (agent broadcasts here, X mic captures)
+load-module module-null-sink sink_name=agent_speakers
+# Cable B: x_speakers -> agent_mic (X's Space audio goes here, agent hears it)
+load-module module-null-sink sink_name=x_speakers
+
+# Expose monitors as virtual mics with friendly names
+load-module module-remap-source source_name=x_mic master=agent_speakers.monitor
+load-module module-remap-source source_name=agent_mic master=x_speakers.monitor
+```
+
+Chrome processes are launched with `PULSE_SINK` and `PULSE_SOURCE` env vars so each process is bound to a specific cable — no per-tab fiddling needed.
+
+## Phase 5 — Realtime API migration (Beta → GA)
+
+`ai-agents-x-space` was written against the **Beta** Realtime API which OpenAI retired around 2026-02. First call to `/session/0` returned:
+
+> "The Realtime Beta API is no longer supported. Please use /v1/realtime for the GA API."
+
+The migrations required:
+
+| Layer | Before (Beta) | After (GA) |
+|---|---|---|
+| Ephemeral-key endpoint | `POST /v1/realtime/sessions` | `POST /v1/realtime/client_secrets` |
+| Request body wrapper | top-level fields | `{ session: { type: "realtime", ... } }` |
+| Voice location | `voice: "verse"` (top-level) | `audio: { output: { voice: "verse" } }` |
+| SDP exchange endpoint | `POST /v1/realtime?model=...` | `POST /v1/realtime/calls?model=...` |
+| Ephemeral-key field | `data.client_secret.value` | `data.value` |
+| Model name | `gpt-4o-realtime-preview-2024-12-17` | `gpt-realtime` |
+
+Each migration was discovered by hitting an error, testing a hypothesis via `curl https://api.openai.com/v1/realtime/client_secrets ...` from the Codespace, then patching. Scripts kept around for posterity: `automation/patch-realtime.py` and `automation/patch-greet.py`.
+
+After the migrations, the Realtime SDP exchange worked end-to-end:
+
+```
+Connection established!
+Audio track received
+Data channel open
+```
+
+## Phase 6 — first audio path verified (TTS test)
+
+To prove the audio routing worked without burning Realtime tokens, wrote `scripts/say.sh`:
+
+```bash
+# Synthesize text via OpenAI TTS and play through agent_speakers cable
+curl -X POST https://api.openai.com/v1/audio/speech \
+ -H "Authorization: Bearer $OPENAI_API_KEY" \
+ -d '{"model":"gpt-4o-mini-tts","voice":"verse","input":"...","response_format":"wav"}' \
+ --output /tmp/say.wav
+PULSE_SINK=agent_speakers paplay /tmp/say.wav
+```
+
+First test: 172 KB of audio synthesized, played into the cable. The operator confirmed they heard it in the Space on their phone via @swarminged. **The audio path was proven working.**
+
+## Phase 7 — X UI automation (the hard part)
+
+Wrote `automation/vm-automation.js` (driver) and `automation/x-join-only.js` (X-tab-only re-attach). Both use puppeteer-core to connect to a real Chrome via `--remote-debugging-port`. Cookies are injected via Chrome DevTools Protocol's `Network.setCookies` so the agent's X account is logged in without any visible login flow.
+
+The flow for joining a Space:
+1. CDP-connect to the X Chrome at `http://127.0.0.1:9223`.
+2. Set `auth_token` and `ct0` cookies for `.x.com`.
+3. `page.goto(SPACE_URL)`.
+4. Click any element whose label/text contains "start listening" (with bounding-box check to skip hidden elements).
+5. Wait, then click "request to speak".
+
+Quirks discovered:
+- X redirects the tab to `/home` after the join click. The Space session keeps running via X's persistent mini-player at the bottom of the page. The mini-player has its own Mute/Unmute buttons.
+- The peek URL form (`https://x.com/i/spaces/<id>/peek`) is what shows the "Start listening" interstitial. After the click X drops you on the full Space view, or sometimes on `/home`.
+- A second account requesting speaker after the first one works the same way, in a separate Chrome instance.
+
+## Phase 8 — accepting + unmuting
+
+The operator (host = `@doi`) accepts speaker requests on their phone. This is the only non-automatable step — X's mobile app surface only.
+
+Once accepted, the speaker is muted by default. `automation/unmute-only.js` polls every 1.5s for buttons matching `unmute`, `turn on microphone`, `start speaking`, `turn on mic`, or `speak now`, then clicks the first one. Works regardless of whether the X tab is showing the full Space view or just the mini-player (the mini-player's unmute button has the same `aria-label`).
+
+## Phase 9 — transcript event renaming (silent banter)
+
+Wired the two-agent loop: when agent A finishes a turn (emits `textComplete` over Socket.IO), the server forwards the transcript to agent B as a `textToAgent` event; agent B reads the message and generates a response.
+
+Symptom: the messages array stayed empty. `/state` showed both agents connected and "idle" but no transcripts.
+
+Cause: GA Realtime renamed `response.audio_transcript.delta`/`.done` → `response.output_audio_transcript.delta`/`.done`. The page only listened for the old name, so transcripts never accumulated, so `textComplete` never fired.
+
+Fix in `automation/patch-transcript-events.py`:
+
+```js
+// before
+else if (msg.type === "response.audio_transcript.done") { ... }
+// after
+else if (msg.type === "response.audio_transcript.done" ||
+ msg.type === "response.output_audio_transcript.done") { ... }
+```
+
+Both delta and done events. Both `agent1.html` and `agent2.html`.
+
+After this patch, banter worked. `/state` messages array filled up with alternating Swarm / Swarm2 entries.
+
+## Phase 10 — agent2 textToAgent was a no-op
+
+After the transcript fix, agent1 → agent2 forwarding fired but agent2 didn't actually generate a response. Cause: in the original `ai-agents-x-space` repo, only agent1.html's `textToAgent` handler dispatches a `conversation.item.create` + `response.create` to the data channel. agent2.html's handler was just a UI log (`log("User message: ..."); // (Sam will respond)`).
+
+Fix in `automation/patch-agent2-respond.py`: copy agent1's handler verbatim into agent2.html (with `if (AGENT_ID !== 0) return` removed, since agent2 has `AGENT_ID = 1`).
+
+## Phase 11 — turn-gating to prevent overlap
+
+Even with both agents now triggering on `textToAgent`, occasionally one would start before the other finished. The server forwarder fired on a fixed 1.5s delay regardless of who was speaking.
+
+Fix in `automation/patch-turn-gating.py`: replaced the forwarder with a `sendWhenIdle` poll. Server only emits `textToAgent` once both `state.agents[sender].status === "idle"` and `state.agents[other].status === "idle"`. Polls every 1.5s up to 10 times, drops the turn if the floor never clears.
+
+Status comes from each agent page emitting `statusChange` events to the server based on Web Audio API analysis of the agent's audio output: above the level threshold for ≥1 sample = "speaking", below threshold for ≥500ms = "idle".
+
+## Phase 12 — greet-on-connect
+
+The agents had nothing to say after connecting (no message had been forwarded yet, and they don't auto-respond to silence). Added a greeting trigger via `automation/patch-greet.py`:
+
+```js
+dc.onopen = () => {
+ log("Data channel open", "success")
+ setTimeout(() => {
+ dc.send(JSON.stringify({
+ type: "response.create",
+ response: { instructions: "Greet the room warmly..." }
+ }))
+ }, 1500)
+}
+```
+
+The 1.5s delay gives the WebRTC stream time to stabilize before the model starts speaking. Different prompt content for each agent so they introduce themselves with different vibes.
+
+## Phase 13 — voice swap to GA voices
+
+Original `voices = { 0: "verse", 1: "sage" }`. Newer GA voices `marin` (warm female, conversational) and `cedar` (warm male, dry) are dramatically more natural-sounding. One-line swap in `server/index.js`, plus a server restart and page reloads.
+
+## Phase 14 — live prompt updates via session.update
+
+Wrote `automation/update-prompts.js`. For each agent's Chrome tab, sends a `session.update` event with new `instructions` over the data channel. This changes the agent's personality without disconnecting the Realtime session or losing conversation state. Used to switch between "casual three.ws co-host", "always-positive enforcer", and ad-hoc battle modes.
+
+## Phase 15 — input audio transcription
+
+The agents *understood* humans speaking in the Space (the model is multimodal — audio in → text reasoning → audio out), but the operator couldn't see what was being said. Enabled `input_audio_transcription` via session.update:
+
+```js
+session.update {
+ audio: {
+ input: { transcription: { model: "gpt-4o-mini-transcribe" } }
+ }
+}
+```
+
+After this, `conversation.item.created` events with `role: user` arrive with populated `content[].transcript`. The agent pages log them as `User said: ...`.
+
+## Phase 16 — dual-account broadcast
+
+Up to this point, both agents shared the same X account (@swarminged) — they both spoke through the same Chrome → cable A → X tab → broadcast. From listeners' POV it sounded like one account with two voices.
+
+Restructure to make each agent broadcast through its own X account:
+
+**New cable topology (4 null-sinks, isolation per agent — no feedback loop):**
+- `agent1_speakers` — Swarm's audio output, fed to @swarminged's mic
+- `agent2_speakers` — Swarm2's audio output, fed to @eplus's mic
+- `swarming_playback` — what @swarminged's X tab plays (Space audio minus @swarminged's own voice; agent1 listens to its monitor)
+- `eplus_playback` — what @eplus's X tab plays (Space audio minus @eplus's own voice; agent2 listens)
+
+This means agents hear each other through the Space itself (each X tab's playback contains the OTHER agent's voice). No feedback because each agent's playback excludes its own voice (X strips that on the client side).
+
+**Four Chrome processes:**
+
+```bash
+# Agent 1
+PULSE_SINK=agent1_speakers PULSE_SOURCE=agent1_mic \
+ google-chrome --user-data-dir=/tmp/chrome-agent1 \
+ --remote-debugging-port=9222 http://localhost:3000/agent1 &
+
+# Agent 2
+PULSE_SINK=agent2_speakers PULSE_SOURCE=agent2_mic \
+ google-chrome --user-data-dir=/tmp/chrome-agent2 \
+ --remote-debugging-port=9224 http://localhost:3000/agent2 &
+
+# X tab for @swarminged
+PULSE_SINK=swarming_playback PULSE_SOURCE=x_swarming_mic \
+ google-chrome --user-data-dir=/tmp/chrome-x-swarming \
+ --remote-debugging-port=9223 about:blank &
+
+# X tab for @eplus
+PULSE_SINK=eplus_playback PULSE_SOURCE=x_eplus_mic \
+ google-chrome --user-data-dir=/tmp/chrome-x-eplus \
+ --remote-debugging-port=9225 about:blank &
+```
+
+Files: `vm-launch-dual.sh`, `automation/vm-automation-dual.js`, `automation/unmute-dual.js`. Second account's cookies in `automation/.env-eplus`.
+
+## Phase 17 — the dual-account overlap problem
+
+After dual-account went live, the two agents started talking *over* each other. Because each agent now hears the other through the Space (not just text relay), OpenAI Realtime's server-side VAD on each independent session triggered `response.create` simultaneously when both heard the same human or each other.
+
+Three considered fixes:
+
+1. **Disable auto-VAD-response.** Set `turn_detection.create_response: false` on both sessions. They only banter via the `textComplete` forwarder. Drawback: agents don't auto-reply to humans either.
+2. **Designate one human-responder.** Auto-VAD on for agent1 only; agent2 is text-only. Simple but asymmetric.
+3. **Claim-token coordination.** When one agent starts speaking (statusChange("speaking")), broadcast a `cancelResponse` to all other agents, who immediately send `response.cancel` to OpenAI.
+
+Implemented option 3 in `automation/patch-claim-token.py`. Server-side:
+
+```js
+socket.on("statusChange", ({ agentId, status }) => {
+ // ... existing handler ...
+ if (status === "speaking") {
+ Object.values(state.agents).forEach((other) => {
+ if (other.id !== agentId && other.connected && other.socketId) {
+ io.to(other.socketId).emit("cancelResponse", { reason: `agent ${agentId} took the floor` })
+ }
+ })
+ }
+})
+```
+
+Agent pages:
+
+```js
+socket.on("cancelResponse", ({ reason }) => {
+ if (dc?.readyState === "open") {
+ dc.send(JSON.stringify({ type: "response.cancel" }))
+ }
+})
+```
+
+This still has a ~100-300 ms overlap window (whoever triggered statusChange first wins; the loser's first audio buffer might already be on the wire), but eliminates persistent over-talking.
+
+## Phase 18 — Git operations
+
+The user maintained three repos that mirror each other: `nirholas/three.ws`, `nirholas/3D-Agent`, `nirholas/xspace-agent`. The dual-remote setup pushes the same code to all three.
+
+Pushed everything in this phase as a single branch first (`add-x-spaces-voice-agent` with the curated `x-spaces/` subdirectory), then merged to `main`, then re-pushed under `agent-voice-chat/` per the operator's preference. The full workspace (excluding `.git`, `node_modules`, `dist`, `.env`, `.cookies.json`, debug screenshots, logs) lives at `agent-voice-chat/` on `nirholas/three.ws` and `nirholas/3D-Agent`. Companion follow-up specs in the same folder: `dashboard-prompt.md` and `elevenlabs-prompt.md`.
+
+## Operational quick reference
+
+```bash
+# Re-bootstrap the VM after a fresh wipe
+gcloud compute instances create swarm-agent --zone=us-central1-a \
+ --machine-type=e2-standard-2 --image-family=ubuntu-2204-lts \
+ --image-project=ubuntu-os-cloud --boot-disk-size=30GB \
+ --no-service-account --no-scopes --tags=swarm-agent
+gcloud compute ssh swarm-agent --zone=us-central1-a -- \
+ 'sudo bash -c "$(curl -fsSL https://raw.githubusercontent.com/nirholas/three.ws/main/agent-voice-chat/vm/setup.sh)"'
+
+# Single-account (one X account broadcasts both agents):
+sudo -u agent /home/agent/launch.sh https://x.com/i/spaces/<id>
+sudo -u agent bash -c "cd /home/agent/automation && node unmute-only.js"
+
+# Dual-account (each agent broadcasts via its own account):
+sudo -u agent /home/agent/launch-dual.sh https://x.com/i/spaces/<id>
+# (host accepts BOTH requests on phone)
+sudo -u agent bash -c "cd /home/agent/automation && node unmute-dual.js"
+
+# One-off broadcast (no Realtime, just TTS):
+sudo -u agent /home/agent/say.sh "anything you want spoken"
+
+# Live prompt change without restart
+sudo -u agent bash -c "cd /home/agent/automation && node update-prompts.js"
+
+# Re-trigger the banter loop after silence
+sudo -u agent bash -c "cd /home/agent/automation && node kick-loop.js"
+
+# Inspect what people in the Space are saying
+sudo -u agent bash -c "cd /home/agent/automation && node -e '...'" # see troubleshooting.md
+```
+
+## Secrets handling
+
+All credentials live in `.env` files with `chmod 600`, never committed. Two files:
+
+- `/home/agent/ai-agents-x-space/.env` — `OPENAI_API_KEY`, `PORT`, optionally `ELEVENLABS_API_KEY` if you've done the EL swap.
+- `/home/agent/automation/.env` — `X_AUTH_TOKEN` and `X_CT0` for the primary X account.
+- `/home/agent/automation/.env-eplus` — `X_AUTH_TOKEN_EPLUS` and `X_CT0_EPLUS` for the second X account (used by dual-launch only).
+
+To get fresh X cookies: log into x.com as the target account in any browser → DevTools → Application → Cookies → x.com → copy `auth_token` and `ct0`. They expire when you "log out of all other sessions" on X.
+
+## Known limitations
+
+- **X UI changes break the automation.** When X renames a button (e.g. "Start listening" → "Listen now"), update the `NEEDLES` arrays in `automation/*.js`.
+- **Same-account collision.** The VM's X account must be different from the Space host account. X redirects to `/home` when it detects you trying to join your own Space as a listener.
+- **Realtime session expiration.** Ephemeral keys expire after ~60s. WebRTC connections persist past that, but if you let an agent sit disconnected for >60s and then click Connect, you need a fresh key — the page handles this automatically.
+- **The `add-x-spaces-voice-agent` branch was the original PR branch.** It's now merged but still present on the remotes. Safe to delete with `git push origin :add-x-spaces-voice-agent`.
+
+## Things that didn't work and why
+
+| Attempt | Why it failed | What we did instead |
+|---|---|---|
+| `xspace-agent` SDK + Puppeteer (Phase 1) | `space-ui.ts` selectors misidentified the join button; agent stalled at "Start listening" | Wrote our own thinner CDP automation in `vm-automation.js` |
+| Building `packages/core` cleanly | drizzle-orm type conflict, no clean fix | Used existing `dist/` + tsx runner |
+| Single BlackHole cable on a Mac | Echo loop (agent hears its own voice) | Two PulseAudio null-sinks with monitor sources — no shared cable |
+| Single-account dual-agent (both agents through @swarminged) | One account, one voice in the Space — listeners can't tell the agents apart | Dual-account: four Chromes, two cables per side |
+| Server-side `setTimeout(..., 1500)` forwarder | Two agents triggered on simultaneous human input | Server-side claim-token + agent-side `response.cancel` |
+| Beta Realtime API | OpenAI retired Beta around 2026-02 | Migrated all endpoints + payload shapes to GA |
+| Chrome Remote Desktop on the VM | CRD apt package didn't create its Unix group on Ubuntu 22.04 | Dropped CRD; use Xvfb + Puppeteer/CDP only (no human-viewable desktop needed) |
diff --git a/agent-voice-chat/dashboard-prompt.md b/agent-voice-chat/dashboard-prompt.md
new file mode 100644
index 000000000..c35395bf7
--- /dev/null
+++ b/agent-voice-chat/dashboard-prompt.md
@@ -0,0 +1,226 @@
+# Build a Real-Time Dashboard for the x-spaces Voice Agent
+
+You are picking up a working multi-agent voice system that broadcasts into X (Twitter) Spaces. Two AI agents (Swarm + Swarm2) connect to **OpenAI Realtime API** over WebRTC, talk to each other and to humans in the Space, and broadcast through a single X.com browser tab via PulseAudio virtual cables on a GCP VM.
+
+Your task is to build a **real-time dashboard** that surfaces everything happening in this system to a human operator.
+
+---
+
+## Stack you're working with
+
+- **Server**: Node + Express + Socket.IO at `nirholas/three.ws/agent-voice-chat/server/index.js`. Already exposes:
+ - `GET /` → static dashboard (currently a basic ASCII/terminal style page in `public/index.html`). You'll be modernizing this.
+ - `GET /state` → JSON: `{ agents, currentTurn, messages }` (last 50 messages)
+ - `GET /session/:agentId` → mints an OpenAI Realtime ephemeral key (don't touch)
+ - `GET /config` → frontend config dump
+ - Socket.IO with the events listed below
+- **Agent pages**: `public/agent1.html`, `public/agent2.html` — each renders one agent's WebRTC connection + status. **Do not modify these.** They are the source of truth for what each agent is doing.
+- **Run target**: served from `http://localhost:3000` on the same VM where the Node server runs.
+
+---
+
+## Socket.IO events emitted by the server (you SUBSCRIBE to these)
+
+| Event | Payload | When it fires |
+|---|---|---|
+| `stateUpdate` | `{ agents, currentTurn, turnQueue }` | Any agent connects/disconnects/changes status, turn granted/released |
+| `agentStatus` | `{ agentId, status, name }` | An agent's status changed (`idle` / `listening` / `speaking` / `offline`) |
+| `turnGranted` | `{ agentId }` | Server granted the floor to an agent |
+| `textDelta` | `{ agentId, delta, messageId, name }` | An agent's response is streaming (token by token) |
+| `textComplete` | `{ id, agentId, name, text, timestamp }` | An agent finished a turn (final transcript) |
+| `userMessage` | `{ id, agentId: -1, name, text, timestamp, isUser: true }` | A human typed a message in the dashboard |
+| `audioLevel` | `{ agentId, level }` | Agent's current audio output level (0.0–1.0), ~30 Hz |
+| `messageHistory` | `Array<message>` | Sent once on connection — backlog of the last 50 messages |
+| `pumpfunMessage` | `{ agentId: -1, name, text, timestamp, source: "pumpfun" }` | (optional) Live external chat feed if enabled |
+
+Plus the existing flow already wires `textComplete` → `textToAgent` on the *other* agent so the two agents banter when neither is busy.
+
+## Socket.IO events you can EMIT from the dashboard (the server is listening)
+
+| Event | Payload | Effect |
+|---|---|---|
+| `userMessage` | `{ text, from }` | Inject a user message — the active agent will respond to it |
+| `requestTurn` / `releaseTurn` | `{ agentId }` | Turn arbitration (you probably don't need these) |
+
+---
+
+## What the dashboard MUST show in real time
+
+1. **Top bar**:
+ - Server status indicator (Socket.IO connected/disconnected)
+ - Active X Space URL (you may need to add a `/space-info` endpoint to the server — read it from a config var like `process.env.SPACE_URL` and have the operator set it)
+ - "Two agents talking" indicator (`currentTurn` field) — show which agent has the floor right now
+
+2. **Agent panels** (one per agent, side by side):
+ - Name + voice
+ - Status badge with colors: `idle` (gray), `listening` (yellow), `speaking` (green pulsing), `offline` (red)
+ - Live audio meter (use `audioLevel` events, 0.0–1.0, animated bar)
+ - Current message being generated (use `textDelta` events — typewriter effect appending deltas as they arrive)
+ - System prompt for that agent (read once from `/state` or a new endpoint; display in a collapsible panel)
+ - Voice (from `voices` map in server — add a `/agent-config` endpoint if needed)
+
+3. **Live transcript feed** (main center panel, scrollable, auto-scroll to bottom):
+ - One entry per turn — agent name, color-coded, timestamp, text
+ - Stream `textDelta` events as a partial entry that finalizes on `textComplete`
+ - Distinguish humans in the X Space from agents — humans show up as `userMessage` (typed) OR via a NEW event you'll wire up: `humanTranscript`. To support that, also subscribe to a new event:
+ ```
+ socket.on("humanTranscript", ({ text, timestamp }) => { ... })
+ ```
+ Then ADD a server-side rebroadcast: when an agent page emits an internal `userTranscript` event (you'll need to patch agent1.html / agent2.html to emit this — see below), the server should rebroadcast as `humanTranscript`.
+
+4. **Input controls**:
+ - Text box → emits `userMessage` to inject a typed message
+ - "Kick Swarm" / "Kick Swarm2" buttons → call a NEW endpoint `POST /kick/:agentId` (add to server) that sends `response.create` to that agent's data channel. You'll need to coordinate with the agent page via Socket.IO since the data channel lives in the browser, not the server. The simplest path: emit a Socket.IO event `kickRequest` to the agent page and have the agent page (the agent's tab) call `dc.send(...)`.
+ - "Update prompt" button per agent → opens a textarea and emits `promptUpdate { agentId, instructions }` (server forwards to agent page, agent page calls `dc.send({ type: "session.update", ... })`)
+
+5. **System health panel**:
+ - PulseAudio sink-input counts (one for agent Chrome, one for X Chrome — query via a NEW `/health` endpoint that runs `pactl list short sink-inputs` on the VM)
+ - Realtime session ephemeral key expiration (mint a fresh key at `/session/0` and `/session/1` periodically to show "minutes until refresh")
+ - X tab URL (run a query via a NEW `/x-tab-url` endpoint that uses puppeteer-core to connect to `http://127.0.0.1:9223` and report the X.com Chrome's current URL)
+
+---
+
+## Patches you need to make to existing files
+
+### `public/agent1.html` and `public/agent2.html`
+
+Currently each agent's data channel `message` handler logs `User said: ...` to the page DOM but doesn't emit it to the server. Find this block (it exists in both files):
+
+```js
+else if (msg.type === "conversation.item.created" && msg.item?.role === "user") {
+ const content = msg.item.content || []
+ let text = ""
+ content.forEach(c => {
+ if (c.transcript) text += c.transcript
+ if (c.text) text += c.text
+ })
+ if (text.trim()) {
+ log("User said: " + text)
+ }
+}
+```
+
+Add `socket.emit("userTranscript", { agentId: AGENT_ID, text, timestamp: Date.now() })` inside the `if (text.trim())` block, immediately after the `log()` call. Do this in **both** agent files.
+
+### `server/index.js`
+
+Add a Socket.IO handler that rebroadcasts `userTranscript` events as `humanTranscript` to all clients (so dashboards see it):
+
+```js
+socket.on("userTranscript", ({ agentId, text, timestamp }) => {
+ io.emit("humanTranscript", { agentId, text, timestamp })
+})
+```
+
+Add the kick + prompt-update bridge:
+
+```js
+socket.on("kickRequest", ({ agentId, instructions }) => {
+ const target = state.agents[agentId]
+ if (!target || !target.socketId) return
+ io.to(target.socketId).emit("kickAgent", { instructions })
+})
+
+socket.on("promptUpdate", ({ agentId, instructions }) => {
+ const target = state.agents[agentId]
+ if (!target || !target.socketId) return
+ io.to(target.socketId).emit("updatePrompt", { instructions })
+})
+```
+
+In `agent1.html` and `agent2.html`, listen for these new events:
+
+```js
+socket.on("kickAgent", ({ instructions }) => {
+ if (!dc || dc.readyState !== "open") return
+ dc.send(JSON.stringify({ type: "response.create", response: { instructions } }))
+})
+
+socket.on("updatePrompt", ({ instructions }) => {
+ if (!dc || dc.readyState !== "open") return
+ dc.send(JSON.stringify({ type: "session.update", session: { type: "realtime", instructions } }))
+})
+```
+
+Add the health endpoint:
+
+```js
+const { exec } = require("child_process")
+app.get("/health", (req, res) => {
+ exec("pactl list short sink-inputs && pactl list short sources", (err, stdout) => {
+ if (err) return res.status(500).json({ error: err.message })
+ res.json({ pulse: stdout, uptime: process.uptime() })
+ })
+})
+```
+
+Add the X tab URL endpoint (requires puppeteer-core in the server's deps — `npm install puppeteer-core`):
+
+```js
+const puppeteer = require("puppeteer-core")
+app.get("/x-tab-url", async (req, res) => {
+ try {
+ const b = await puppeteer.connect({ browserURL: "http://127.0.0.1:9223", defaultViewport: null })
+ const pages = await b.pages()
+ const urls = pages.map(p => p.url())
+ b.disconnect()
+ res.json({ urls })
+ } catch (e) {
+ res.status(500).json({ error: e.message })
+ }
+})
+```
+
+---
+
+## Build constraints
+
+- **No build step.** This dashboard must be a single `dashboard.html` (or `index.html`) plus a CSS file and an inline `<script type="module">`. Operator wants to edit + reload without npm builds.
+- **Use Socket.IO client directly** via `<script src="/socket.io/socket.io.js">`.
+- **Light DOM updates only** — no React/Vue/Svelte. Plain JS or alpine.js if you really want reactivity.
+- **Dark theme**, modern, readable. Inspired by terminals but not strict ASCII. Use system fonts (`-apple-system, ui-sans-serif`).
+- **Responsive** — should work in a Chrome side-panel at 600 px wide as well as full screen.
+
+## Layout suggestion
+
+```
+┌────────────────────────────────────────────────────────────────┐
+│ ● Connected · Space: x.com/i/spaces/... · Now speaking: Swarm│
+├──────────────────┬──────────────────┬──────────────────────────┤
+│ SWARM (marin) │ SWARM2 (cedar) │ TRANSCRIPT │
+│ ● speaking │ ● idle │ [22:14] Swarm: ... │
+│ ▓▓▓▓░░░░░░ 47% │ ░░░░░░░░░░ 0% │ [22:14] Swarm2: ... │
+│ │ │ [22:14] HUMAN: hi! │
+│ current msg: │ last msg: │ [22:15] Swarm: ... │
+│ "yo three.ws is │ "no doubt..." │ ... │
+│ shipping..." │ │ (auto-scroll bottom) │
+│ ─────────────── │ ─────────────────│ │
+│ [kick] [prompt] │ [kick] [prompt] │ │
+└──────────────────┴──────────────────┴──────────────────────────┤
+│ Inject message: [____________________________________] [send] │
+├────────────────────────────────────────────────────────────────┤
+│ HEALTH: Pulse sinks: ok · X tab: /spaces/... · uptime: 14m │
+└────────────────────────────────────────────────────────────────┘
+```
+
+## File you should produce
+
+Replace (or sit alongside) `agent-voice-chat/server/public/index.html`. If you sit alongside, name it `dashboard.html` and update `index.js`'s `app.get("/")` to serve it instead.
+
+Also add `agent-voice-chat/server/public/dashboard.css` and any small `dashboard.js` you split out.
+
+## How to test
+
+1. SSH to the VM (`gcloud compute ssh swarm-agent --zone=us-central1-a`)
+2. `sudo systemctl restart swarm-server.service`
+3. From your laptop: `gcloud compute ssh swarm-agent --zone=us-central1-a -- -L 3000:localhost:3000` then open `http://localhost:3000` locally
+4. Open one of the agent pages too (`/agent1`, `/agent2`) so there's something to dashboard
+5. Verify status badges, audio meter, transcript stream, kick button, prompt update
+
+## Don'ts
+
+- Don't replace the agent pages. Don't refactor the server's existing flow (textComplete forwarder + Realtime session minter). Only add the new events/endpoints listed above.
+- Don't add a database. Keep transcript state in memory or `localStorage`.
+- Don't break the existing turn-queue / textComplete forwarder behavior.
+
+When you're done, the human operator should be able to open one tab and see everything: which agent is speaking, what humans are saying in the Space, the running transcript, agent voice levels, and have one-click kick / prompt-update controls.
diff --git a/agent-voice-chat/elevenlabs-prompt.md b/agent-voice-chat/elevenlabs-prompt.md
new file mode 100644
index 000000000..83064e9bd
--- /dev/null
+++ b/agent-voice-chat/elevenlabs-prompt.md
@@ -0,0 +1,229 @@
+# Swap OpenAI Realtime TTS → ElevenLabs Streaming TTS
+
+You are picking up a working two-agent X Spaces voice system. Right now each agent uses **OpenAI Realtime API** end-to-end (STT + LLM + TTS over a single WebRTC connection). The TTS voices are good but lack the prosody, emotion, and character of ElevenLabs voices.
+
+Your task: **keep OpenAI Realtime for STT + LLM, replace its TTS with ElevenLabs streaming TTS**, while preserving the existing real-time conversation feel (target end-to-end latency ≤ 1.5s).
+
+---
+
+## Current architecture (do not break)
+
+- Server: Node + Express + Socket.IO at `agent-voice-chat/server/index.js`.
+- Two agent pages: `public/agent1.html`, `public/agent2.html`. Each:
+ - Calls `GET /session/:id` to mint an OpenAI Realtime ephemeral key.
+ - Opens a WebRTC `RTCPeerConnection` to `https://api.openai.com/v1/realtime/calls?model=gpt-realtime`.
+ - Captures local mic via `getUserMedia` (routed through a PulseAudio virtual cable on a Linux VM).
+ - Plays remote audio (model's voice) via a `<audio>` element that streams to another PulseAudio cable.
+ - Uses a data channel `oai-events` for control events (`response.create`, `session.update`, etc.).
+- Two agents are talking to each other and to humans in a live X Space. The Realtime model handles VAD, transcription, response generation, and speech synthesis.
+
+You must not change:
+- The PulseAudio cable routing (the audio still has to leave through the same `<audio>` element / default output device).
+- The Socket.IO event flow between server and agent pages (status, textComplete, turn arbitration, etc.).
+- The `/session/:id` ephemeral-key endpoint shape.
+
+---
+
+## Required changes
+
+### 1. Server: add an ElevenLabs proxy endpoint
+
+`ELEVENLABS_API_KEY` is already in `.env` next to `OPENAI_API_KEY`. Add a streaming proxy so the browser never sees the ElevenLabs key.
+
+```js
+// server/index.js
+const ELEVEN_KEY = process.env.ELEVENLABS_API_KEY
+const ELEVEN_MODEL = process.env.ELEVENLABS_MODEL || "eleven_turbo_v2_5"
+const VOICE_IDS = {
+ 0: process.env.ELEVEN_VOICE_0 || "21m00Tcm4TlvDq8ikWAM", // Rachel — pick something else for Swarm
+ 1: process.env.ELEVEN_VOICE_1 || "AZnzlk1XvdvUeBnXmlld", // Domi — pick something else for Swarm2
+}
+
+// HTTP streaming proxy. The page POSTs full text (or a chunk) and we stream MP3/PCM back.
+app.post("/tts/:agentId/stream", express.json(), async (req, res) => {
+ const id = parseInt(req.params.agentId, 10)
+ const text = (req.body?.text || "").trim()
+ const voiceId = VOICE_IDS[id]
+ if (!text || !voiceId) return res.status(400).json({ error: "missing text or voice" })
+
+ const url = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream?optimize_streaming_latency=2&output_format=mp3_22050_32`
+ const r = await fetch(url, {
+ method: "POST",
+ headers: {
+ "xi-api-key": ELEVEN_KEY,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ text,
+ model_id: ELEVEN_MODEL,
+ voice_settings: { stability: 0.45, similarity_boost: 0.7, style: 0.2, use_speaker_boost: true },
+ }),
+ })
+ if (!r.ok) {
+ const err = await r.text()
+ return res.status(r.status).send(err)
+ }
+ res.setHeader("Content-Type", "audio/mpeg")
+ r.body.pipe(res)
+})
+```
+
+Add `node-fetch` (or use undici / global `fetch` in Node 20+) and `express.json()` if it's not already enabled. Stream response, don't buffer.
+
+### 2. Agent pages: switch Realtime to text-only output
+
+Find each agent's session config (currently set via `session.update` or in the `/session/:id` response). Update it so the model produces TEXT instead of audio:
+
+```js
+// in agent1.html / agent2.html — after the WebRTC connection is established
+dc.send(JSON.stringify({
+ type: "session.update",
+ session: {
+ type: "realtime",
+ output_modalities: ["text"], // <-- model emits text only, no audio
+ instructions: <existing system prompt>,
+ }
+}))
+```
+
+(If `output_modalities` doesn't work, the equivalent is `audio: { output: { modalities: ["text"] } }` — try `output_modalities` first.)
+
+Once you've switched to text-only output, you should stop receiving `response.output_audio_transcript.*` events (the model isn't speaking) and instead receive **`response.output_text.delta`** and **`response.output_text.done`** events.
+
+### 3. Pipe text to ElevenLabs as it streams
+
+Currently the page listens for `response.output_audio_transcript.done` and emits `textComplete` to the server. Now you have two choices:
+
+**Option A — simpler, slightly higher latency**: wait for `response.output_text.done`, send the full text to `/tts/:agentId/stream`, stream the MP3 into a fresh `<audio>` element.
+
+**Option B — lower latency**: as `response.output_text.delta` events arrive, batch tokens by sentence (split on `.`, `?`, `!`, `,`) and fire a fresh `/tts/:agentId/stream` POST for each sentence. Each call streams an MP3 chunk; queue and play sequentially.
+
+For X Spaces use, **Option A is good enough** (the model's text generation already streams faster than humans speak; whole sentences arrive in ~300–600ms after first token). Implement Option A first; Option B is an optimization.
+
+```js
+// in each agent page
+else if (msg.type === "response.output_text.done") {
+ if (msg.text) {
+ socket.emit("textComplete", { agentId: AGENT_ID, text: msg.text, messageId: currentMessageId })
+ addChat(AGENT_NAME, msg.text, "self")
+ // Synthesize via ElevenLabs and play
+ speakViaElevenLabs(msg.text)
+ }
+}
+
+async function speakViaElevenLabs(text) {
+ try {
+ const res = await fetch(`/tts/${AGENT_ID}/stream`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ text }),
+ })
+ if (!res.ok) { log("TTS error: " + res.status, "error"); return }
+ const blob = await res.blob()
+ const url = URL.createObjectURL(blob)
+ const audio = new Audio(url)
+ audio.onended = () => URL.revokeObjectURL(url)
+ audio.play()
+ setStatus("speaking")
+ audio.onended = () => { setStatus("idle"); socket.emit("releaseTurn", { agentId: AGENT_ID }) }
+ } catch (e) {
+ log("TTS exception: " + e.message, "error")
+ }
+}
+```
+
+If `setStatus("speaking")` was previously driven by the audio-level analyzer reading from the WebRTC remote audio track, that analyzer won't see anything now (the model isn't sending audio). The simplest fix is to set status explicitly in `speakViaElevenLabs` before/after, as above.
+
+### 4. Update the audio-level meter
+
+The existing meter reads the OpenAI Realtime audio stream. After this change, that stream is silent. Make the meter analyze the new ElevenLabs `<audio>` element instead:
+
+```js
+function attachMeter(audioEl) {
+ const ctx = audioContext || new (window.AudioContext || window.webkitAudioContext)()
+ audioContext = ctx
+ const src = ctx.createMediaElementSource(audioEl)
+ const analyser = ctx.createAnalyser()
+ analyser.fftSize = 256
+ src.connect(analyser)
+ src.connect(ctx.destination) // still play through speakers
+ // ... reuse the existing setInterval loop that emits audioLevel events
+}
+```
+
+Call `attachMeter(audio)` inside `speakViaElevenLabs` after creating the `Audio` element.
+
+### 5. Voice picker (optional but nice)
+
+Surface a tiny dropdown in each agent page that lets the operator change voice without redeploying:
+
+```js
+fetch("/voices").then(r => r.json()).then(voices => { /* populate select */ })
+// On change: socket.emit("setVoice", { agentId, voiceId })
+```
+
+Server-side:
+```js
+app.get("/voices", async (req, res) => {
+ const r = await fetch("https://api.elevenlabs.io/v1/voices", {
+ headers: { "xi-api-key": ELEVEN_KEY },
+ })
+ const data = await r.json()
+ res.json(data.voices.map(v => ({ id: v.voice_id, name: v.name, description: v.labels?.description })))
+})
+
+io.on("connection", socket => {
+ socket.on("setVoice", ({ agentId, voiceId }) => { VOICE_IDS[agentId] = voiceId })
+})
+```
+
+### 6. Suggested voice picks
+
+For two distinct, expressive, real-time-capable voices, start with:
+- **Swarm (agent 0)**: a warm, conversational female voice — try **Rachel** (`21m00Tcm4TlvDq8ikWAM`) or **Bella** (`EXAVITQu4vr4xnSDxMaL`)
+- **Swarm2 (agent 1)**: a drier, witty male voice — try **Adam** (`pNInz6obpgDQGcFmaJgB`) or **Antoni** (`ErXwobaYiN019PkySvjV`)
+
+Browse + audition voices at https://elevenlabs.io/app/voice-library before committing.
+
+Use the `eleven_turbo_v2_5` model — lowest latency, good quality, supports streaming. Avoid `eleven_multilingual_v2` unless you actually need other languages (slower).
+
+---
+
+## Latency budget (target ≤ 1.5s end to end)
+
+| Stage | Estimate |
+|---|---|
+| Human stops speaking → Realtime VAD detects → STT text | 200–400 ms |
+| LLM generates first sentence of response | 300–600 ms |
+| Sentence sent to ElevenLabs → first audio bytes arrive | 250–500 ms |
+| Audio decode + playback start | 50–150 ms |
+
+Optimizations if you blow past 1.5s:
+- Use `optimize_streaming_latency=3` or `4` in the EL URL (trades quality for speed).
+- Implement Option B (per-sentence streaming).
+- Use the WebSocket streaming endpoint (`/v1/text-to-speech/{voice_id}/stream-input`) instead of HTTP — slightly lower latency, more code.
+
+---
+
+## Test plan
+
+1. Start with one agent only (agent1). Verify it speaks via ElevenLabs.
+2. Check audio appears in the PulseAudio cable (`pactl list sink-inputs` on the VM should show audio active on `agent_speakers` while it speaks).
+3. Verify the meter still pulses while it speaks.
+4. Verify the `releaseTurn` fires after playback ends.
+5. Verify the textComplete → textToAgent forwarder still triggers the other agent.
+6. Then enable for both agents, run in a live X Space, listen.
+
+## Don'ts
+
+- Don't ship the ElevenLabs key to the browser. All EL calls go through the server proxy.
+- Don't replace OpenAI Realtime for STT — its server-side VAD + transcription is what makes the agents respond to humans in real time. Only swap TTS.
+- Don't try to use ElevenLabs Conversational AI as a drop-in replacement — that's a full agent stack and would require rewiring the two-agent coordination logic that lives in `index.js`.
+- Don't lyric-sing copyrighted songs. ElevenLabs' content policy applies; original lyrics only.
+
+## Files you'll touch
+
+- `agent-voice-chat/server/index.js` — add `/tts/:agentId/stream`, `/voices`, `setVoice` socket handler
+- `agent-voice-chat/server/public/agent1.html` and `agent2.html` — `session.update` to text-only, replace audio-out handling with ElevenLabs synth path, attach meter to new audio element
+- `agent-voice-chat/server/package.json` — no new deps if you use global `fetch` (Node 20+)
+- `agent-voice-chat/server/.env.example` — document the new env vars (`ELEVENLABS_API_KEY`, `ELEVEN_VOICE_0`, `ELEVEN_VOICE_1`, `ELEVENLABS_MODEL`)