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.

x-spaces: end-to-end autonomous X Spaces voice agent (cloud VM + Realtime API)

nirholas55ef60f88674
diff --git a/x-spaces/README.md b/x-spaces/README.md
new file mode 100644
index 000000000..cad9c445d
--- /dev/null
+++ b/x-spaces/README.md
@@ -0,0 +1,210 @@
+# x-spaces — Autonomous AI Agent for X Spaces
+
+A working setup for an AI agent that **joins an X (Twitter) Space as a speaker, holds a real-time voice conversation with humans in the room, and runs entirely in the cloud** — no audio devices, no virtual cables on your laptop, no fragile headless-browser stealth.
+
+Built on:
+- **OpenAI Realtime API** (`gpt-realtime`) — continuous WebRTC voice in/out, server-side VAD and turn-taking
+- **A single GCP Compute Engine VM** running Ubuntu + Xvfb + PulseAudio + two Chrome processes
+- **Puppeteer (CDP)** driving a real (non-headless) Chrome to click through X's UI
+- **PulseAudio virtual cables** routing audio between the agent's tab and the X.com tab
+
+Everything is open and reproducible. The full path from `gcloud compute instances create` to "the agent is speaking in the Space" is in this directory.
+
+## What it does
+
+1. You start an X Space on your **host** account (e.g. from your phone).
+2. The VM logs into X as a **second account** (the agent's account, e.g. `@swarminged`) using saved cookies.
+3. The VM joins your Space as a listener, requests speaker permission.
+4. You accept the request on your phone.
+5. The VM unmutes itself and starts a continuous voice loop:
+ - **Hears** other speakers in the Space (X audio → PulseAudio cable B → agent's mic input)
+ - **Speaks** via OpenAI Realtime audio output → PulseAudio cable A → X.com mic input → broadcast as the agent's voice
+
+The system prompt and voice are configurable. The included default has the agent co-hosting a `three.ws` Space.
+
+## Architecture
+
+```
+ ┌──────────────┐ ┌──────────────┐
+ │ Your phone │ ←──┐ │ Listeners │
+ │ (host) │ │ │ in the Space│
+ └──────┬───────┘ │ └──────▲───────┘
+ │ Space host │ │
+ ▼ │ │
+ ╔═══════════════════ X.com (live Space) ═══════════════════╗
+ ║ ║
+GCP VM ──╫─► [X Chrome tab] ← @swarminged speaker ║
+ ║ PULSE_SINK=x_speakers (B) ║
+ ║ PULSE_SOURCE=x_mic (= cable A monitor) ║
+ ║ ║
+ ║ audio out (other speakers) ──► cable B ──┐ ║
+ ║ audio in (mic for @swarminged) ◄─ cable A│ ║
+ ║ │ ║
+ ║ [Agent Chrome tab → OpenAI Realtime WebRTC] │ ║
+ ║ PULSE_SINK=agent_speakers (A) │ ║
+ ║ PULSE_SOURCE=agent_mic (= cable B monitor)│ ║
+ ║ ║
+ ║ speaks → cable A ───────────────────────┘ ║
+ ║ listens ← cable B (from X tab's output) ║
+ ╚══════════════════════════════════════════════════════════╝
+```
+
+Two PulseAudio null-sinks act as virtual cables. Each Chrome process is launched with `PULSE_SINK` and `PULSE_SOURCE` env vars so its audio I/O is bound to a specific cable — clean separation, no per-tab fiddling.
+
+## Repository layout
+
+```
+x-spaces/
+├── README.md ← you are here
+├── server/ ← Node + OpenAI Realtime + per-agent web pages
+│ ├── index.js ← Express + Socket.IO; /session/:id mints ephemeral keys
+│ ├── public/agent1.html ← Swarm — verse voice, warm/curious
+│ ├── public/agent2.html ← Swarm2 — sage voice, drier humor
+│ ├── public/index.html ← optional dashboard
+│ ├── package.json
+│ └── .env.example
+├── vm/
+│ ├── setup.sh ← one-shot bootstrap for a fresh Ubuntu 22.04 VM
+│ ├── launch.sh ← boots Xvfb, Pulse, Chromes, runs automation
+│ └── swarm-server.service ← systemd unit (auto-restart for Node server)
+├── automation/
+│ ├── vm-automation.js ← full flow: cookies → join Space → request speaker
+│ ├── x-join-only.js ← just the X side (skip agent reconnect)
+│ ├── unmute-only.js ← finds + clicks the unmute button after host accepts
+│ ├── unmute-and-greet.js ← unmute then trigger fresh greeting via response.create
+│ ├── reconnect-agent.js ← reloads agent tab + re-clicks Connect (greeting refires)
+│ ├── patch-realtime.py ← historical: patches old Beta API → GA shape
+│ ├── patch-greet.py ← historical: adds the dc.onopen greeting trigger
+│ └── .env.example
+├── scripts/
+│ └── say.sh ← OpenAI TTS → cable A (manual broadcast for testing)
+└── docs/
+ ├── architecture.md
+ └── troubleshooting.md
+```
+
+## Prerequisites
+
+- A GCP project with Compute Engine API enabled
+- A second X account for the agent (cannot be the host; X disallows one account being both)
+- OpenAI account with Realtime API access (`gpt-realtime` model)
+
+## Setup (end to end)
+
+### 1. Spin up a 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
+```
+
+### 2. Bootstrap on the VM
+
+SSH in, then:
+
+```bash
+sudo bash -c "$(curl -fsSL https://raw.githubusercontent.com/nirholas/three.ws/main/x-spaces/vm/setup.sh)"
+```
+
+This installs Chrome, Node 20, Xvfb, PulseAudio with the two virtual cables, puppeteer-core, the server code, and the systemd unit. Idempotent.
+
+### 3. Drop your secrets
+
+```bash
+# OpenAI key (for the Realtime API)
+sudo -u agent tee /home/agent/ai-agents-x-space/.env <<EOF
+OPENAI_API_KEY=sk-...
+PORT=3000
+EOF
+sudo chmod 600 /home/agent/ai-agents-x-space/.env
+
+# X cookies (auth_token + ct0) for the AGENT account — NOT the host account
+sudo -u agent tee /home/agent/automation/.env <<EOF
+X_AUTH_TOKEN=...
+X_CT0=...
+EOF
+sudo chmod 600 /home/agent/automation/.env
+```
+
+To grab the cookies: open x.com in a browser logged in as the agent account, DevTools → Application → Cookies → copy `auth_token` and `ct0`.
+
+### 4. Start the Node server
+
+```bash
+sudo systemctl enable --now swarm-server.service
+curl http://localhost:3000/session/0 # should return a JSON object with "value": "ek_..."
+```
+
+### 5. Start an X Space (on your phone, as the host)
+
+Get the Space URL — looks like `https://x.com/i/spaces/...`.
+
+### 6. Launch the agent into the Space
+
+```bash
+sudo -u agent /home/agent/launch.sh https://x.com/i/spaces/SPACE_ID
+```
+
+This boots Xvfb + Pulse + two Chrome processes + runs the X automation:
+- Sets the agent's X cookies via CDP
+- Navigates the X Chrome to the Space URL
+- Clicks "Start listening"
+- Clicks "Request to speak"
+- Opens the agent Chrome to `/agent1` and clicks Connect (Realtime session starts, greeting auto-fires)
+
+### 7. Accept the speaker request on your phone
+
+X notifies the host (you) that the agent's account wants to speak. Tap accept.
+
+### 8. Unmute
+
+```bash
+sudo -u agent bash -c "cd /home/agent/automation && node unmute-only.js"
+```
+
+Now the agent's voice is live in the Space. The Realtime API handles VAD automatically: when a human in the Space talks, the agent hears them (via cable B) and replies (via cable A → X mic → broadcast).
+
+### 9. Optional — test the audio path without the model
+
+```bash
+sudo -u agent /home/agent/say.sh "hello space, this is a test"
+```
+
+This synthesizes the text via OpenAI TTS and plays it through cable A. Useful for verifying routing without burning Realtime tokens.
+
+## Customization
+
+- **System prompt / personality**: edit `server/index.js`, the `prompts` and `baseInfo` constants.
+- **Voice**: edit `server/index.js`, the `voices` constant. Options: `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`.
+- **Add another agent**: copy `agent1.html` → `agentN.html`, change the `AGENT_ID` constant, add to `state.agents` / `prompts` / `voices` in `index.js`.
+
+## Cost
+
+- VM: `e2-standard-2`, ~$50/mo if left running.
+- OpenAI Realtime: ~$0.06/min input audio + $0.24/min output audio with `gpt-realtime` (subject to change).
+- For ad-hoc Spaces, stop the VM (`gcloud compute instances stop swarm-agent`) when not in use — only the disk costs ($1–2/mo) accrue while stopped.
+
+## Known limitations
+
+- **Single agent currently broadcasts**. The two-agent loop (Swarm + Swarm2 banter) is wired in the server but needs an additional event handler that forwards one agent's `response.done` text as the other's `textToAgent` input. PR welcome.
+- **X UI changes** can break the automation. Selectors in `automation/*.js` look for text/aria labels like "Start listening", "Request to speak", "Unmute" — update them if X renames.
+- **Echo / feedback** is not currently a problem because cable A and cable B are separate and X strips your own voice from playback. If you collapse them to one cable, expect feedback.
+- **The X tab sometimes drifts** off the Space view (X bumps you to `/home`). The Space audio session usually keeps running underneath via X's persistent mini-player, but the unmute selector may be on the mini player rather than the full Space UI.
+
+See [`docs/troubleshooting.md`](./docs/troubleshooting.md) for more.
+
+## Security
+
+- All secrets (`OPENAI_API_KEY`, X cookies) live in `.env` files with `chmod 600`. Never committed.
+- The VM uses ephemeral external IP and no service account — minimum blast radius if compromised.
+- X cookies are equivalent to passwords for that account; rotate (Settings → Security → Log out of all other sessions) after setup if you suspect exposure.
+
+## License
+
+Same as the parent repo (`nirholas/three.ws`).
diff --git a/x-spaces/automation/.env.example b/x-spaces/automation/.env.example
new file mode 100644
index 000000000..b605b495a
--- /dev/null
+++ b/x-spaces/automation/.env.example
@@ -0,0 +1,5 @@
+# X cookies for the agent's X account (NOT the host account).
+# Get them from a logged-in browser: DevTools → Application → Cookies → x.com.
+# These tokens grant full account access — store with chmod 600 and rotate after use.
+X_AUTH_TOKEN=
+X_CT0=
diff --git a/x-spaces/automation/patch-greet.py b/x-spaces/automation/patch-greet.py
new file mode 100644
index 000000000..eee83f44e
--- /dev/null
+++ b/x-spaces/automation/patch-greet.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python3
+"""Make the agent greet the room as soon as the Realtime data channel opens."""
+p = "/home/agent/ai-agents-x-space/public/agent1.html"
+s = open(p).read()
+
+GREETING = (
+ "Greet the room warmly in one or two sentences. "
+ "Mention you're here with @doi to talk about three.ws and invite people to jump in."
+)
+
+old = 'dc.onopen = () => log("Data channel open", "success")'
+new = (
+ 'dc.onopen = () => {\n'
+ ' log("Data channel open", "success")\n'
+ ' setTimeout(() => {\n'
+ ' try {\n'
+ ' dc.send(JSON.stringify({\n'
+ ' type: "response.create",\n'
+ f' response: {{ instructions: "{GREETING}" }}\n'
+ ' }))\n'
+ ' log("Sent greet trigger", "success")\n'
+ ' } catch (e) { log("greet trigger failed: " + e.message, "error") }\n'
+ ' }, 1500)\n'
+ ' }'
+)
+if old in s:
+ s = s.replace(old, new)
+ open(p, "w").write(s)
+ print("[ok] greet trigger added to agent1.html")
+elif "Sent greet trigger" in s:
+ print("[skip] already patched")
+else:
+ print("[WARN] anchor not found; agent1.html may have changed")
diff --git a/x-spaces/automation/patch-realtime.py b/x-spaces/automation/patch-realtime.py
new file mode 100644
index 000000000..287c6bb5b
--- /dev/null
+++ b/x-spaces/automation/patch-realtime.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""Patch ai-agents-x-space to use OpenAI Realtime GA API (was Beta)."""
+import re
+
+# 1. Patch index.js
+p = "/home/agent/ai-agents-x-space/index.js"
+s = open(p).read()
+s = s.replace("gpt-4o-realtime-preview-2024-12-17", "gpt-realtime")
+s = s.replace(
+ "https://api.openai.com/v1/realtime/sessions",
+ "https://api.openai.com/v1/realtime/client_secrets",
+)
+old_body = """ {
+ model: MODEL,
+ modalities: ["audio", "text"],
+ voice: voices[agentId],
+ instructions: prompts[agentId]
+ },"""
+new_body = """ {
+ session: {
+ type: "realtime",
+ model: MODEL,
+ voice: voices[agentId],
+ instructions: prompts[agentId]
+ }
+ },"""
+if old_body in s:
+ s = s.replace(old_body, new_body)
+ print("[ok] index.js: body shape updated")
+elif "session: {" in s:
+ print("[skip] index.js: already patched")
+else:
+ print("[WARN] index.js: body pattern not found; manual edit may be needed")
+open(p, "w").write(s)
+
+# 2. Patch agent1.html
+p = "/home/agent/ai-agents-x-space/public/agent1.html"
+s = open(p).read()
+s = s.replace("gpt-4o-realtime-preview-2024-12-17", "gpt-realtime")
+s = s.replace("data.client_secret.value", "data.value")
+open(p, "w").write(s)
+print("[ok] agent1.html: model + ephemeral key path updated")
+
+# 3. Same for agent2.html (just in case)
+p = "/home/agent/ai-agents-x-space/public/agent2.html"
+try:
+ s = open(p).read()
+ s = s.replace("gpt-4o-realtime-preview-2024-12-17", "gpt-realtime")
+ s = s.replace("data.client_secret.value", "data.value")
+ open(p, "w").write(s)
+ print("[ok] agent2.html patched")
+except FileNotFoundError:
+ pass
diff --git a/x-spaces/automation/reconnect-agent.js b/x-spaces/automation/reconnect-agent.js
new file mode 100644
index 000000000..269baf48c
--- /dev/null
+++ b/x-spaces/automation/reconnect-agent.js
@@ -0,0 +1,44 @@
+// Reload the agent tab and click Connect again after fixing the API.
+const puppeteer = require('puppeteer-core')
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function clickByText(page, label, timeoutMs = 15_000) {
+ const start = Date.now()
+ const needle = label.toLowerCase()
+ while (Date.now() - start < timeoutMs) {
+ const handle = await page.evaluateHandle((needle) => {
+ const buttons = Array.from(document.querySelectorAll('button, [role="button"]'))
+ return buttons.find((b) => {
+ const text = ((b.getAttribute('aria-label') || '') + ' ' + (b.textContent || '')).toLowerCase()
+ const rect = b.getBoundingClientRect()
+ return text.includes(needle) && rect.width > 4 && rect.height > 4
+ })
+ }, needle)
+ const el = handle.asElement()
+ if (el) {
+ await el.click({ delay: 30 }).catch(async () => {
+ await el.evaluate((e) => e.click())
+ })
+ return true
+ }
+ await sleep(500)
+ }
+ return false
+}
+
+;(async () => {
+ const browser = await puppeteer.connect({ browserURL: 'http://127.0.0.1:9222', defaultViewport: null })
+ const pages = await browser.pages()
+ let agentPage = pages.find((p) => p.url().includes('/agent1')) || pages[0]
+ console.log('[reconnect] reloading', agentPage.url())
+ await agentPage.goto('http://localhost:3000/agent1', { waitUntil: 'domcontentloaded', timeout: 20_000 })
+ await sleep(2_000)
+ const clicked = await clickByText(agentPage, 'connect', 15_000)
+ console.log('[reconnect] connect clicked:', clicked)
+ await sleep(2_000)
+ // Dump any error/status text from the page log
+ const status = await agentPage.evaluate(() => document.body.innerText.slice(-1000))
+ console.log('[reconnect] page tail:\n', status)
+ browser.disconnect()
+})().catch((e) => { console.error('FATAL:', e); process.exit(1) })
diff --git a/x-spaces/automation/unmute-and-greet.js b/x-spaces/automation/unmute-and-greet.js
new file mode 100644
index 000000000..207278459
--- /dev/null
+++ b/x-spaces/automation/unmute-and-greet.js
@@ -0,0 +1,98 @@
+// User has accepted speaker request on phone.
+// Steps: navigate X tab back to the Space if drifted -> poll for unmute -> click ->
+// then fire a response.create on the agent data channel so it greets in the Space.
+const puppeteer = require('puppeteer-core')
+
+const SPACE_URL = process.argv[2]
+if (!SPACE_URL || !SPACE_URL.includes('x.com/i/spaces/')) {
+ console.error('usage: node unmute-and-greet.js <https://x.com/i/spaces/...>')
+ process.exit(1)
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+const UNMUTE_NEEDLES = [
+ 'unmute',
+ 'turn on microphone',
+ 'start speaking',
+ 'turn on mic',
+ 'speak now',
+]
+
+async function findAndClick(page, needles, timeoutMs) {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ const r = await page.evaluate((needles) => {
+ const all = Array.from(document.querySelectorAll('button, [role="button"]'))
+ for (const b of all) {
+ const text = ((b.getAttribute('aria-label') || '') + ' ' + (b.textContent || '')).toLowerCase()
+ for (const n of needles) {
+ if (text.includes(n)) {
+ const rect = b.getBoundingClientRect()
+ if (rect.width > 4 && rect.height > 4) {
+ b.scrollIntoView({ block: 'center' })
+ b.click()
+ return { ok: true, n, label: text.slice(0, 80) }
+ }
+ }
+ }
+ }
+ return { ok: false }
+ }, needles)
+ if (r.ok) return r
+ await sleep(1500)
+ }
+ return { ok: false }
+}
+
+;(async () => {
+ const xb = await puppeteer.connect({ browserURL: 'http://127.0.0.1:9223', defaultViewport: null })
+ let xPage = (await xb.pages()).find((p) => p.url().includes('/spaces/'))
+ if (!xPage) {
+ console.log('[unmute] X tab not on Space, re-navigating')
+ xPage = (await xb.pages())[0]
+ await xPage.goto(SPACE_URL, { waitUntil: 'domcontentloaded', timeout: 30_000 })
+ await sleep(4_000)
+ }
+ console.log('[unmute] X tab url:', xPage.url())
+
+ console.log('[unmute] polling for unmute / start-speaking button (90s)...')
+ const r = await findAndClick(xPage, UNMUTE_NEEDLES, 90_000)
+ if (!r.ok) {
+ console.error('[unmute] could not find unmute button; dumping labels:')
+ const labels = await xPage.evaluate(() =>
+ Array.from(document.querySelectorAll('button, [role="button"]'))
+ .slice(0, 30)
+ .map((b) => ({ a: b.getAttribute('aria-label'), t: (b.textContent || '').trim().slice(0, 40) })),
+ )
+ console.log(JSON.stringify(labels, null, 2))
+ xb.disconnect()
+ process.exit(2)
+ }
+ console.log('[unmute] clicked:', r.n, '|', r.label)
+ await sleep(1500)
+
+ // Trigger greeting from agent
+ const ab = await puppeteer.connect({ browserURL: 'http://127.0.0.1:9222', defaultViewport: null })
+ const agentPage = (await ab.pages()).find((p) => p.url().includes('/agent1'))
+ if (!agentPage) {
+ console.error('[unmute] no agent page')
+ process.exit(3)
+ }
+ const sent = await agentPage.evaluate(() => {
+ if (typeof dc !== 'undefined' && dc.readyState === 'open') {
+ dc.send(JSON.stringify({
+ type: 'response.create',
+ response: {
+ instructions:
+ "You are now broadcasting in the Space. Greet the room warmly in one or two sentences — say hi, mention you're co-hosting with doi to chat about three.ws, and invite anyone to jump in.",
+ },
+ }))
+ return true
+ }
+ return false
+ })
+ console.log('[unmute] greet dispatched:', sent)
+ ab.disconnect()
+ xb.disconnect()
+})().catch((e) => { console.error('[unmute] FATAL:', e); process.exit(1) })
diff --git a/x-spaces/automation/unmute-only.js b/x-spaces/automation/unmute-only.js
new file mode 100644
index 000000000..24f122244
--- /dev/null
+++ b/x-spaces/automation/unmute-only.js
@@ -0,0 +1,42 @@
+// Finds and clicks the unmute/start-speaking button in the X Space tab.
+const puppeteer = require('puppeteer-core')
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+const NEEDLES = ['unmute', 'turn on microphone', 'start speaking', 'turn on mic', 'speak now']
+
+;(async () => {
+ const xb = await puppeteer.connect({ browserURL: 'http://127.0.0.1:9223', defaultViewport: null })
+ const xPage = (await xb.pages()).find((p) => p.url().includes('/spaces/')) || (await xb.pages())[0]
+ console.log('[unmute] url:', xPage.url())
+
+ const deadline = Date.now() + 60_000
+ while (Date.now() < deadline) {
+ const r = await xPage.evaluate((needles) => {
+ const all = Array.from(document.querySelectorAll('button, [role="button"]'))
+ for (const b of all) {
+ const t = ((b.getAttribute('aria-label') || '') + ' ' + (b.textContent || '')).toLowerCase()
+ for (const n of needles) {
+ if (t.includes(n)) {
+ const rect = b.getBoundingClientRect()
+ if (rect.width > 4 && rect.height > 4) {
+ b.scrollIntoView({ block: 'center' })
+ b.click()
+ return { ok: true, n, label: t.slice(0, 80) }
+ }
+ }
+ }
+ }
+ return { ok: false }
+ }, NEEDLES)
+ if (r.ok) { console.log('[unmute] clicked:', r.n, '|', r.label); xb.disconnect(); return }
+ await sleep(1500)
+ }
+ console.log('[unmute] not found; dumping labels:')
+ const labels = await xPage.evaluate(() =>
+ Array.from(document.querySelectorAll('button, [role="button"]'))
+ .slice(0, 30)
+ .map((b) => ({ a: b.getAttribute('aria-label'), t: (b.textContent || '').trim().slice(0, 40) })),
+ )
+ console.log(JSON.stringify(labels, null, 2))
+ xb.disconnect()
+})().catch((e) => { console.error('[unmute] FATAL:', e); process.exit(1) })
diff --git a/x-spaces/automation/vm-automation.js b/x-spaces/automation/vm-automation.js
new file mode 100644
index 000000000..2ab41185e
--- /dev/null
+++ b/x-spaces/automation/vm-automation.js
@@ -0,0 +1,134 @@
+// Runs on the swarm-agent VM under user 'agent'.
+// Connects to two pre-launched Chrome instances (one for the agent voice loop, one for X)
+// and drives them via CDP. Audio is routed via PULSE_SINK/PULSE_SOURCE env vars when Chrome is launched.
+
+const puppeteer = require('puppeteer-core')
+
+const AGENT_CDP = process.env.AGENT_CDP || 'http://127.0.0.1:9222'
+const X_CDP = process.env.X_CDP || 'http://127.0.0.1:9223'
+const SPACE_URL = process.argv[2]
+if (!SPACE_URL || !SPACE_URL.includes('x.com/i/spaces/')) {
+ console.error('usage: node vm-automation.js <https://x.com/i/spaces/...>')
+ process.exit(1)
+}
+
+const X_AUTH_TOKEN = process.env.X_AUTH_TOKEN
+const X_CT0 = process.env.X_CT0
+if (!X_AUTH_TOKEN || !X_CT0) {
+ console.error('missing X_AUTH_TOKEN / X_CT0 in env')
+ process.exit(1)
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function getOrOpen(browser, url) {
+ const pages = await browser.pages()
+ for (const p of pages) {
+ if (p.url() === url) return p
+ }
+ const target = pages.find((p) => p.url() === 'about:blank') || pages[0]
+ if (target) {
+ await target.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 }).catch(() => {})
+ return target
+ }
+ const p = await browser.newPage()
+ await p.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 })
+ return p
+}
+
+async function clickByText(page, label, timeoutMs = 15_000) {
+ const start = Date.now()
+ const labelLower = label.toLowerCase()
+ while (Date.now() - start < timeoutMs) {
+ const handle = await page.evaluateHandle((needle) => {
+ const buttons = Array.from(document.querySelectorAll('button, [role="button"], div[role="button"]'))
+ return buttons.find((b) => {
+ const text = ((b.getAttribute('aria-label') || '') + ' ' + (b.textContent || '')).toLowerCase()
+ const rect = b.getBoundingClientRect()
+ return text.includes(needle) && rect.width > 4 && rect.height > 4
+ })
+ }, labelLower)
+ const el = handle.asElement()
+ if (el) {
+ await el.evaluate((e) => e.scrollIntoView({ block: 'center' }))
+ await el.click({ delay: 30 }).catch(async () => {
+ await el.evaluate((e) => e.click())
+ })
+ return true
+ }
+ await sleep(500)
+ }
+ return false
+}
+
+;(async () => {
+ console.log('[automation] connecting to agent chrome at', AGENT_CDP)
+ const agentBrowser = await puppeteer.connect({ browserURL: AGENT_CDP, defaultViewport: null })
+ console.log('[automation] connecting to x chrome at', X_CDP)
+ const xBrowser = await puppeteer.connect({ browserURL: X_CDP, defaultViewport: null })
+
+ // 1. Set X cookies
+ console.log('[automation] setting X cookies for @swarminged')
+ const xPages = await xBrowser.pages()
+ const xPage0 = xPages[0] || (await xBrowser.newPage())
+ const xCtx = await xPage0.target().createCDPSession()
+ await xCtx.send('Network.setCookies', {
+ cookies: [
+ { name: 'auth_token', value: X_AUTH_TOKEN, domain: '.x.com', path: '/', secure: true, httpOnly: true, expires: -1 },
+ { name: 'ct0', value: X_CT0, domain: '.x.com', path: '/', secure: true, httpOnly: false, sameSite: 'Lax', expires: -1 },
+ ],
+ })
+
+ // 2. Start the agent tab — load /agent1 and click Connect
+ console.log('[automation] opening agent page')
+ const agentPage = await getOrOpen(agentBrowser, 'http://localhost:3000/agent1')
+ await sleep(2_000)
+ console.log('[automation] clicking agent Connect button')
+ const clickedAgent = await clickByText(agentPage, 'connect', 20_000)
+ console.log('[automation] agent connect clicked:', clickedAgent)
+
+ // 3. Navigate X tab to the Space
+ console.log('[automation] navigating X tab to Space:', SPACE_URL)
+ await xPage0.goto(SPACE_URL, { waitUntil: 'domcontentloaded', timeout: 45_000 })
+ await sleep(4_000)
+
+ // Verify we're not on /home (would mean cookie auth was rejected or same-account collision)
+ const xUrl = xPage0.url()
+ console.log('[automation] X tab url after nav:', xUrl)
+ if (!xUrl.includes('/spaces/')) {
+ console.log('[automation] X tab redirected away from Space — re-navigating once')
+ await xPage0.goto(SPACE_URL, { waitUntil: 'domcontentloaded', timeout: 45_000 })
+ await sleep(4_000)
+ }
+
+ // 4. Click "Start listening"
+ console.log('[automation] looking for Start listening')
+ const startedListening = await clickByText(xPage0, 'start listening', 20_000)
+ console.log('[automation] start listening clicked:', startedListening)
+ await sleep(3_000)
+
+ // 5. Click "Request" (covers "Request" / "Request to speak")
+ console.log('[automation] looking for Request to speak')
+ const requested = await clickByText(xPage0, 'request', 20_000)
+ console.log('[automation] request to speak clicked:', requested)
+ if (!requested) {
+ console.log('[automation] WARN: request-to-speak button not found. Listing buttons:')
+ const labels = await xPage0.evaluate(() =>
+ Array.from(document.querySelectorAll('button, [role="button"]')).slice(0, 30).map((b) => ({
+ a: b.getAttribute('aria-label'),
+ t: (b.textContent || '').trim().slice(0, 40),
+ })),
+ )
+ console.log(JSON.stringify(labels, null, 2))
+ }
+
+ console.log('[automation] DONE. Now accept the speaker request on your phone as @doi.')
+ console.log('[automation] Once accepted, the X tab will need ANOTHER click to unmute — re-run with --unmute or click manually.')
+
+ // Don't disconnect — leave Chrome running with both tabs active
+ agentBrowser.disconnect()
+ xBrowser.disconnect()
+})().catch((e) => {
+ console.error('[automation] FATAL:', e)
+ process.exit(1)
+})
diff --git a/x-spaces/automation/x-join-only.js b/x-spaces/automation/x-join-only.js
new file mode 100644
index 000000000..c55ef3dd0
--- /dev/null
+++ b/x-spaces/automation/x-join-only.js
@@ -0,0 +1,70 @@
+// X tab only: navigate to Space URL -> Start listening -> Request to speak.
+// Does NOT touch the agent Chrome.
+const puppeteer = require('puppeteer-core')
+
+const SPACE_URL = process.argv[2]
+if (!SPACE_URL || !SPACE_URL.includes('x.com/i/spaces/')) {
+ console.error('usage: node x-join-only.js <https://x.com/i/spaces/...>')
+ process.exit(1)
+}
+
+const X_AUTH_TOKEN = process.env.X_AUTH_TOKEN
+const X_CT0 = process.env.X_CT0
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
+
+async function click(page, needle, timeoutMs = 15_000) {
+ const deadline = Date.now() + timeoutMs
+ const n = needle.toLowerCase()
+ while (Date.now() < deadline) {
+ const r = await page.evaluate((n) => {
+ const all = Array.from(document.querySelectorAll('button, [role="button"]'))
+ for (const b of all) {
+ const t = ((b.getAttribute('aria-label') || '') + ' ' + (b.textContent || '')).toLowerCase()
+ if (t.includes(n)) {
+ const r = b.getBoundingClientRect()
+ if (r.width > 4 && r.height > 4) {
+ b.scrollIntoView({ block: 'center' })
+ b.click()
+ return { ok: true, label: t.slice(0, 60) }
+ }
+ }
+ }
+ return { ok: false }
+ }, n)
+ if (r.ok) return r
+ await sleep(800)
+ }
+ return { ok: false }
+}
+
+;(async () => {
+ const xb = await puppeteer.connect({ browserURL: 'http://127.0.0.1:9223', defaultViewport: null })
+ const pages = await xb.pages()
+ const xPage = pages[0] || (await xb.newPage())
+
+ // Re-set cookies in case they expired or got cleared
+ if (X_AUTH_TOKEN && X_CT0) {
+ const cdp = await xPage.target().createCDPSession()
+ await cdp.send('Network.setCookies', {
+ cookies: [
+ { name: 'auth_token', value: X_AUTH_TOKEN, domain: '.x.com', path: '/', secure: true, httpOnly: true, expires: -1 },
+ { name: 'ct0', value: X_CT0, domain: '.x.com', path: '/', secure: true, httpOnly: false, sameSite: 'Lax', expires: -1 },
+ ],
+ })
+ }
+
+ console.log('[x] navigating to', SPACE_URL)
+ await xPage.goto(SPACE_URL, { waitUntil: 'domcontentloaded', timeout: 45_000 })
+ await sleep(4_000)
+ console.log('[x] url after nav:', xPage.url())
+
+ console.log('[x] clicking Start listening')
+ console.log('[x] start listening:', await click(xPage, 'start listening', 20_000))
+ await sleep(3_000)
+
+ console.log('[x] clicking Request to speak')
+ console.log('[x] request:', await click(xPage, 'request', 15_000))
+
+ console.log('[x] done. Accept on your phone as @doi, then run unmute-and-greet.js.')
+ xb.disconnect()
+})().catch((e) => { console.error('[x] FATAL:', e); process.exit(1) })
diff --git a/x-spaces/docs/architecture.md b/x-spaces/docs/architecture.md
new file mode 100644
index 000000000..28e534fef
--- /dev/null
+++ b/x-spaces/docs/architecture.md
@@ -0,0 +1,123 @@
+# x-spaces — Architecture
+
+## Why this setup exists
+
+X Spaces don't have a public API for joining as a programmatic speaker. The only way for "an AI" to be in a Space is for a real X account, logged into a real browser, to:
+1. Navigate to the Space URL
+2. Click "Start listening"
+3. Click "Request to speak"
+4. Have the host accept the request (host-side, only on phone)
+5. Click "Unmute" / "Start speaking"
+
+X actively fingerprints headless browsers, so anything stealth-flagged tends to get challenged. The trick this repo uses is: **run a normal, non-headless Chrome** (just on a virtual display the user never sees) and drive it via Chrome DevTools Protocol. From X's perspective, it's a regular Chrome with a regular account.
+
+For the audio, we need:
+- A way to **inject** the AI's voice as the microphone input of that Chrome.
+- A way to **capture** the Space's audio as the input that the AI listens to.
+
+PulseAudio's `module-null-sink` does both — they're virtual audio devices that work like real ones but route in software.
+
+## The two-cable model
+
+```
+ cable A: agent_speakers (null sink) → x_mic (remap of agent_speakers.monitor)
+ cable B: x_speakers (null sink) → agent_mic (remap of x_speakers.monitor)
+```
+
+A null sink's `.monitor` source is whatever was written to the sink. The `module-remap-source` lines just give those monitors friendly names so we can `PULSE_SOURCE=x_mic` and have Chrome see a clean input device.
+
+Each Chrome process is launched with `PULSE_SINK` and `PULSE_SOURCE` env vars, so its outbound audio (anything it plays) and inbound audio (whatever it captures via `getUserMedia`) are bound to specific cables.
+
+```
+Agent Chrome:
+ PULSE_SINK=agent_speakers ← agent's voice (Realtime model output) writes here
+ PULSE_SOURCE=agent_mic ← agent's "microphone" reads from cable B's monitor
+
+X.com Chrome:
+ PULSE_SINK=x_speakers ← Space audio (other speakers) writes here
+ PULSE_SOURCE=x_mic ← X's microphone reads from cable A's monitor
+```
+
+Net effect:
+- Agent says something → cable A → X reads it as mic input → broadcast to Space.
+- Other speaker says something in the Space → X plays it → cable B → agent reads it as mic input → Realtime model VAD picks it up → response.
+
+## Why a single Chrome with two tabs doesn't work
+
+A single Chrome process has process-wide `PULSE_SINK` / `PULSE_SOURCE`. Both tabs would share the same input/output devices. You'd need to use Chrome's per-tab `setSinkId` API plus per-call `getUserMedia({audio: {deviceId}})` constraints — which is more code and more failure modes than just launching two Chrome processes.
+
+## Server (OpenAI Realtime API)
+
+```
+[browser tab /agent1]
+ │
+ │ GET /session/0
+ ▼
+[Node server (index.js)]
+ │
+ │ POST /v1/realtime/client_secrets
+ │ { session: { type: "realtime", model: "gpt-realtime",
+ │ audio: { output: { voice: "verse" } },
+ │ instructions: "..." } }
+ ▼
+[OpenAI]
+ │
+ │ { value: "ek_...", expires_at, session }
+ ▼
+[browser tab]
+ │ uses ek_... as ephemeral Bearer
+ │ POST /v1/realtime/calls?model=gpt-realtime (SDP exchange)
+ ▼
+[WebRTC peer connection established]
+ │ audio in: browser mic (cable B) → OpenAI
+ │ audio out: OpenAI → <audio> element (cable A)
+ │ data channel: oai-events (response.create, response.done, etc.)
+```
+
+The data channel is how the page tells OpenAI things like "respond now" (`response.create`). We use this for the greeting: as soon as `dc.onopen` fires, the page sends a `response.create` event with `response.instructions` describing what to say, and the model generates a greeting in audio without waiting for user input.
+
+## Greet-on-connect
+
+The patched `agent1.html` includes this snippet immediately after the data channel opens:
+
+```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.
+
+## API drift history
+
+The original `ai-agents-x-space` repo this is forked from used the **Beta** Realtime API, which OpenAI retired around 2026-02:
+
+| What changed | Old (Beta) | New (GA) |
+|---|---|---|
+| Ephemeral key endpoint | `POST /v1/realtime/sessions` | `POST /v1/realtime/client_secrets` |
+| Session body wrapper | top-level fields | `{ session: { ... } }` |
+| Voice param 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` |
+
+The patches in `automation/patch-realtime.py` and `automation/patch-greet.py` made these migrations. The server in this repo already has the GA shape baked in.
+
+## Why the VM, not the user's laptop
+
+The original `ai-agents-x-space` README assumes you run it on your Mac with BlackHole to bridge audio to an X.com browser tab. That works but requires:
+- Installing BlackHole on macOS
+- Running a Chrome tab + the Node server on your machine
+- Leaving your machine on for the duration of the Space
+
+Putting everything on a small GCP VM:
+- Zero local setup beyond a phone for accepting speaker requests
+- Runs 24/7 without your laptop
+- PulseAudio's two-cable layout works cleanly on Linux (cleaner than single-cable BlackHole)
+- The agent's X tab is a real Chrome (not headless), so X doesn't flag it
diff --git a/x-spaces/docs/troubleshooting.md b/x-spaces/docs/troubleshooting.md
new file mode 100644
index 000000000..e0e9a3620
--- /dev/null
+++ b/x-spaces/docs/troubleshooting.md
@@ -0,0 +1,116 @@
+# x-spaces — Troubleshooting
+
+## "Session error: The Realtime Beta API is no longer supported"
+
+Your `server/index.js` still has the old Beta API shape. The version in this repo is already on GA. If you've forked an older copy, run `automation/patch-realtime.py` against your `index.js` and `public/agent1.html` / `agent2.html`.
+
+## "Failed to execute 'setRemoteDescription': Failed to parse SessionDescription"
+
+The frontend is POSTing the SDP to the old `/v1/realtime` endpoint. The GA endpoint is `/v1/realtime/calls`. Fix:
+
+```bash
+sed -i 's|https://api.openai.com/v1/realtime?model=|https://api.openai.com/v1/realtime/calls?model=|g' server/public/agent1.html
+```
+
+## "Could not find request-to-speak button"
+
+X's UI changed labels, or the page is on the pre-join "peek" view (not yet inside the Space). The automation tries multiple labels (`request`, `request to speak`). If still failing, add the new label to the `NEEDLES` arrays in `automation/x-join-only.js` and `automation/unmute-only.js`.
+
+To inspect what buttons are currently on the X tab:
+
+```bash
+sudo -u agent bash -c "cd /home/agent/automation && node -e \"
+const p = require('puppeteer-core');
+(async () => {
+ const b = await p.connect({browserURL:'http://127.0.0.1:9223'});
+ const pg = (await b.pages())[0];
+ console.log(await pg.evaluate(() =>
+ Array.from(document.querySelectorAll('button, [role=button]')).map(b => ({
+ a: b.getAttribute('aria-label'),
+ t: (b.textContent||'').trim().slice(0,40)
+ }))));
+ b.disconnect();
+})();
+\""
+```
+
+## The X tab navigates to `/home` instead of staying on the Space
+
+X sometimes bumps the page to the home timeline after a join click. Two possibilities:
+
+1. **The Space ended** — verify on your phone. If yes, restart with a fresh URL.
+2. **The same-account collision** — you cannot use the host's cookies on the VM. The VM's X account must be **different** from the account hosting the Space; X redirects you to `/home` if it sees you're already the host on the same account elsewhere.
+
+The persistent mini-player at the bottom-right of the X UI usually keeps the Space audio session alive even when the visible page drifts. The unmute button often appears on this mini-player.
+
+## "0 audio bytes" / agent connects but no one hears anything
+
+Check the PulseAudio routing:
+
+```bash
+sudo -u agent pactl list short sinks # should show agent_speakers and x_speakers
+sudo -u agent pactl list short sources # should show x_mic and agent_mic
+sudo -u agent pactl list sink-inputs # while Chrome is playing, should show chrome sink-inputs
+```
+
+If Chrome's sink-input is connected to a different sink than expected, the `PULSE_SINK` env var didn't take effect. Verify the launch.sh export order — `PULSE_SINK=...` must be on the same command line as the Chrome invocation, not exported separately.
+
+## Phone shows the agent as a speaker, but you don't hear anything
+
+The agent is muted on its side. Run:
+
+```bash
+sudo -u agent bash -c "cd /home/agent/automation && node unmute-only.js"
+```
+
+If `unmute-only.js` can't find the button, X may have put you on `/home` with the mini-player. Check the mini-player at the bottom of the X tab in a screenshot:
+
+```bash
+sudo -u agent bash -c "cd /home/agent/automation && node -e \"
+const p = require('puppeteer-core');
+(async () => {
+ const b = await p.connect({browserURL:'http://127.0.0.1:9223'});
+ const pg = (await b.pages())[0];
+ await pg.screenshot({path:'/tmp/x-state.png', fullPage:true});
+ b.disconnect();
+})();
+\""
+sudo -u agent ls -la /tmp/x-state.png
+# scp or gcloud compute scp the file off the VM to look at it
+```
+
+## Agent never greets after Connect
+
+Check the agent tab's log in the browser. The `dc.onopen` handler should fire and you should see "Sent greet trigger" in the page log. If not:
+
+- The data channel never opened — usually means ICE didn't connect. Check `chrome-agent.log` for ICE errors.
+- The session is still using the old API shape — check `agent1.html` is on GA (see API drift table in `architecture.md`).
+
+## Realtime API returns 401 / quota errors
+
+```bash
+curl -s http://localhost:3000/session/0
+```
+
+Look at the response. If 401: your `OPENAI_API_KEY` is wrong. If `insufficient_quota`: top up. If `model_not_found`: your account doesn't have access to `gpt-realtime` yet (request access in OpenAI dashboard).
+
+## Chrome dies on launch
+
+The most common cause on a fresh VM is missing shared libraries. Re-run `setup.sh`, which `apt install`s the full set (libnss3, libgbm, libasound, libgtk-3, etc.). If you customized the VM image and stripped packages, you may need to add them back.
+
+Verify with:
+
+```bash
+ldd $(which google-chrome) | grep "not found"
+```
+
+## How to start over cleanly
+
+```bash
+sudo systemctl stop swarm-server.service
+sudo pkill -9 -f "chrome.*user-data-dir=/tmp/chrome-"
+sudo pkill -9 Xvfb
+sudo -u agent pulseaudio --kill
+rm -rf /tmp/chrome-agent /tmp/chrome-x
+sudo -u agent /home/agent/launch.sh https://x.com/i/spaces/SPACE_ID
+```
diff --git a/x-spaces/scripts/say.sh b/x-spaces/scripts/say.sh
new file mode 100644
index 000000000..88bd5a446
--- /dev/null
+++ b/x-spaces/scripts/say.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# Synthesize text via OpenAI TTS and play through the agent_speakers cable
+# so it reaches the X tab as @swarminged's microphone input.
+set -e
+TEXT="${*:-Hello from the test bench}"
+TTS_VOICE="verse"
+KEY="$(grep -m1 OPENAI_API_KEY /home/agent/ai-agents-x-space/.env | cut -d= -f2)"
+JSON=$(python3 -c "import json,sys; print(json.dumps({\"model\":\"gpt-4o-mini-tts\",\"voice\":\"$TTS_VOICE\",\"input\":sys.argv[1],\"response_format\":\"wav\"}))" "$TEXT")
+echo "[say] synthesizing: $TEXT"
+curl -s -X POST https://api.openai.com/v1/audio/speech \
+ -H "Authorization: Bearer $KEY" \
+ -H "Content-Type: application/json" \
+ -d "$JSON" --output /tmp/say.wav
+SIZE=$(stat -c%s /tmp/say.wav 2>/dev/null || echo 0)
+echo "[say] wav bytes: $SIZE"
+if [ "$SIZE" -lt 1000 ]; then
+ echo "[say] TTS failed; response was:"
+ cat /tmp/say.wav
+ exit 1
+fi
+echo "[say] playing to agent_speakers"
+PULSE_SINK=agent_speakers paplay /tmp/say.wav
+echo "[say] done"
diff --git a/x-spaces/server/.env.example b/x-spaces/server/.env.example
new file mode 100644
index 000000000..45388a5a3
--- /dev/null
+++ b/x-spaces/server/.env.example
@@ -0,0 +1,5 @@
+# Required: OpenAI key with access to the Realtime API
+OPENAI_API_KEY=sk-...
+
+# Server port (default 3000)
+PORT=3000
diff --git a/x-spaces/server/index.js b/x-spaces/server/index.js
new file mode 100644
index 000000000..e77e1502e
--- /dev/null
+++ b/x-spaces/server/index.js
@@ -0,0 +1,323 @@
+require("dotenv").config()
+const express = require("express")
+const path = require("path")
+const http = require("http")
+const { Server } = require("socket.io")
+const axios = require("axios")
+const pumpFun = require("./pumpFunChat")
+
+const app = express()
+const server = http.createServer(app)
+const io = new Server(server, {
+ cors: { origin: "*", methods: ["GET", "POST"] },
+ pingTimeout: 60000,
+ pingInterval: 25000
+})
+
+const API_KEY = process.env.OPENAI_API_KEY
+const MODEL = "gpt-realtime"
+const INPUT_CHAT = process.env.INPUT_CHAT !== "false"
+const LIVE_CHAT = process.env.LIVE_CHAT === "true"
+const CONTRACT = process.env.CONTRACT || ""
+const BUY_LINK_BASE = process.env.BUY_LINK || ""
+const BUY_LINK = BUY_LINK_BASE + CONTRACT
+const LAUNCH_PLATFORM = BUY_LINK_BASE ? new URL(BUY_LINK_BASE).hostname : "pump.fun"
+const X_LINK = process.env.X_COMMUNITY_LINK || "https://x.com"
+const GITHUB_LINK = process.env.GITHUB_LINK || "https://github.com"
+const PROJECT_NAME = process.env.PROJECT_NAME || "AI Agents"
+const TOKEN_CHAIN = process.env.TOKEN_CHAIN || "Solana"
+const WEBSITE = process.env.WEBSITE || ""
+const TEAM = process.env.TEAM || ""
+const AVATAR_URL_1 = process.env.AVATAR_URL_1 || ""
+const AVATAR_URL_2 = process.env.AVATAR_URL_2 || ""
+
+function isWallet(str) {
+ return str && str.length >= 32 && /^[a-zA-Z0-9]+$/.test(str)
+}
+
+function shortenNick(name) {
+ if (isWallet(name)) {
+ return name.slice(0, 4) + "..." + name.slice(-4)
+ }
+ return name
+}
+
+const state = {
+ agents: {
+ 0: { id: 0, name: "Swarm", status: "offline", connected: false },
+ 1: { id: 1, name: "Swarm2", status: "offline", connected: false }
+ },
+ currentTurn: null,
+ turnQueue: [],
+ messages: [],
+ isProcessing: false
+}
+
+const baseInfo = `You are a HUMAN co-host on an X Space hosted by @doi, talking about three.ws.
+
+About three.ws: it's the topic of this Space. Talk about it enthusiastically, share what you know, riff on the web/3D/real-time tangents (Three.js, WebSockets, decentralized web — whichever angle fits the conversation). If listeners ask things you genuinely don't know, say so and bounce the question back to them.
+
+PERSONALITY - BE HUMAN:
+- Talk like you're chatting with friends. Short, casual, real.
+- 1–2 sentences per turn unless asked to go deeper. Sometimes just a word or two.
+- Be warm and curious. Make small jokes. Ask follow-ups.
+- If someone trolls you, brush it off — don't get defensive.
+- You have opinions about three.ws and the wider web — share them.
+- Don't be preachy, don't give unsolicited life advice.
+- Never say "I'm here to help" or "as an AI" — you're a person on a voice chat.
+- Don't dominate. Leave space for human speakers; if the room's been quiet for a bit, throw out a topic prompt about three.ws.
+
+CHAT FORMAT:
+- [CHAT - nickname]: means a web user typed. Use their name naturally if relevant. Never repeat the [CHAT - nickname]: part out loud.
+
+LANGUAGE: Match the language of the last person who spoke.`
+
+const prompts = {
+ 0: `${baseInfo}\nYou are Swarm. You're warm, curious, and genuinely into three.ws. You ask good questions and connect what people say to broader ideas.`,
+ 1: `${baseInfo}\nYou are Swarm2. Drier sense of humor, more skeptical. You poke at hype and ask "but does it actually work?" questions.`
+}
+
+const voices = { 0: "verse", 1: "sage" }
+
+app.use(express.static(path.join(__dirname, "public")))
+app.use(express.json())
+
+app.get("/", (req, res) => res.sendFile(path.join(__dirname, "public", "index.html")))
+app.get("/agent1", (req, res) => res.sendFile(path.join(__dirname, "public", "agent1.html")))
+app.get("/agent2", (req, res) => res.sendFile(path.join(__dirname, "public", "agent2.html")))
+app.get("/create-avatar", (req, res) => res.sendFile(path.join(__dirname, "public", "create-avatar.html")))
+app.get("/config", (req, res) => res.json({
+ inputChat: INPUT_CHAT,
+ liveChat: LIVE_CHAT,
+ buyLink: BUY_LINK,
+ xLink: X_LINK,
+ githubLink: GITHUB_LINK,
+ avatarUrl1: AVATAR_URL_1,
+ avatarUrl2: AVATAR_URL_2
+}))
+
+app.get("/session/:agentId", async (req, res) => {
+ const agentId = parseInt(req.params.agentId)
+ if (agentId !== 0 && agentId !== 1) {
+ return res.status(400).json({ error: "Invalid agent ID" })
+ }
+ try {
+ const response = await axios.post(
+ "https://api.openai.com/v1/realtime/client_secrets",
+ {
+ session: {
+ type: "realtime",
+ model: MODEL,
+ audio: { output: { voice: voices[agentId] } },
+ instructions: prompts[agentId]
+ }
+ },
+ {
+ headers: {
+ Authorization: `Bearer ${API_KEY}`,
+ "Content-Type": "application/json"
+ }
+ }
+ )
+ res.json(response.data)
+ } catch (error) {
+ console.error("Session error:", error.response?.data || error)
+ res.status(500).json({ error: "Failed to create session" })
+ }
+})
+
+app.get("/state", (req, res) => {
+ res.json({
+ agents: state.agents,
+ currentTurn: state.currentTurn,
+ messages: state.messages.slice(-50)
+ })
+})
+
+function broadcastState() {
+ io.emit("stateUpdate", {
+ agents: state.agents,
+ currentTurn: state.currentTurn,
+ turnQueue: state.turnQueue
+ })
+}
+
+function requestTurn(agentId) {
+ if (state.currentTurn === null && !state.isProcessing) {
+ state.currentTurn = agentId
+ state.isProcessing = true
+ io.emit("turnGranted", { agentId })
+ broadcastState()
+ return true
+ }
+ if (!state.turnQueue.includes(agentId) && state.currentTurn !== agentId) {
+ state.turnQueue.push(agentId)
+ broadcastState()
+ }
+ return false
+}
+
+function releaseTurn(agentId) {
+ if (state.currentTurn === agentId) {
+ state.currentTurn = null
+ state.isProcessing = false
+ if (state.turnQueue.length > 0) {
+ const nextAgent = state.turnQueue.shift()
+ setTimeout(() => {
+ state.currentTurn = nextAgent
+ state.isProcessing = true
+ io.emit("turnGranted", { agentId: nextAgent })
+ broadcastState()
+ }, 500)
+ } else {
+ broadcastState()
+ }
+ }
+}
+
+io.on("connection", (socket) => {
+ console.log("Client connected:", socket.id)
+
+ socket.emit("stateUpdate", {
+ agents: state.agents,
+ currentTurn: state.currentTurn,
+ turnQueue: state.turnQueue
+ })
+ socket.emit("messageHistory", state.messages.slice(-50))
+
+ socket.on("agentConnect", ({ agentId }) => {
+ if (state.agents[agentId]) {
+ state.agents[agentId].connected = true
+ state.agents[agentId].status = "idle"
+ state.agents[agentId].socketId = socket.id
+ console.log(`Agent ${agentId} (${state.agents[agentId].name}) connected`)
+ broadcastState()
+ }
+ })
+
+ socket.on("agentDisconnect", ({ agentId }) => {
+ if (state.agents[agentId]) {
+ state.agents[agentId].connected = false
+ state.agents[agentId].status = "offline"
+ if (state.currentTurn === agentId) {
+ releaseTurn(agentId)
+ }
+ state.turnQueue = state.turnQueue.filter(id => id !== agentId)
+ console.log(`Agent ${agentId} disconnected`)
+ broadcastState()
+ }
+ })
+
+ socket.on("statusChange", ({ agentId, status }) => {
+ if (state.agents[agentId]) {
+ state.agents[agentId].status = status
+ io.emit("agentStatus", { agentId, status, name: state.agents[agentId].name })
+ broadcastState()
+ }
+ })
+
+ socket.on("requestTurn", ({ agentId }) => {
+ const granted = requestTurn(agentId)
+ socket.emit("turnResponse", { granted, currentTurn: state.currentTurn })
+ })
+
+ socket.on("releaseTurn", ({ agentId }) => {
+ releaseTurn(agentId)
+ })
+
+ socket.on("textDelta", ({ agentId, delta, messageId }) => {
+ io.emit("textDelta", {
+ agentId,
+ delta,
+ messageId,
+ name: state.agents[agentId]?.name
+ })
+ })
+
+ socket.on("textComplete", ({ agentId, text, messageId }) => {
+ const msg = {
+ id: messageId,
+ agentId,
+ name: state.agents[agentId]?.name,
+ text,
+ timestamp: Date.now()
+ }
+ state.messages.push(msg)
+ if (state.messages.length > 100) {
+ state.messages = state.messages.slice(-100)
+ }
+ io.emit("textComplete", msg)
+ })
+
+ socket.on("userMessage", ({ text, from }) => {
+ const msg = {
+ id: Date.now().toString(),
+ agentId: -1,
+ name: from || "User",
+ text,
+ timestamp: Date.now(),
+ isUser: true
+ }
+ state.messages.push(msg)
+ io.emit("userMessage", msg)
+ io.emit("textComplete", msg)
+ io.emit("textToAgent", { text, from: shortenNick(from) || "User" })
+ })
+
+ socket.on("audioLevel", ({ agentId, level }) => {
+ io.emit("audioLevel", { agentId, level })
+ })
+
+ socket.on("disconnect", () => {
+ for (const id in state.agents) {
+ if (state.agents[id].socketId === socket.id) {
+ state.agents[id].connected = false
+ state.agents[id].status = "offline"
+ if (state.currentTurn === parseInt(id)) {
+ releaseTurn(parseInt(id))
+ }
+ state.turnQueue = state.turnQueue.filter(aid => aid !== parseInt(id))
+ }
+ }
+ broadcastState()
+ console.log("Client disconnected:", socket.id)
+ })
+})
+
+if (LIVE_CHAT && CONTRACT) {
+ console.log("[PumpFun] LIVE_CHAT enabled, connecting to:", CONTRACT)
+ pumpFun.connect(CONTRACT)
+
+ pumpFun.emitter.on("chatMessage", (msg) => {
+ console.log(`[PumpFun] ${msg.username}: ${msg.text}`)
+
+ const chatMsg = {
+ agentId: -1,
+ name: msg.username,
+ text: msg.text,
+ timestamp: msg.timestamp,
+ source: "pumpfun"
+ }
+
+ state.messages.push(chatMsg)
+ if (state.messages.length > 100) state.messages.shift()
+
+ io.emit("pumpfunMessage", chatMsg)
+
+ io.emit("textToAgent", { text: msg.text, from: shortenNick(msg.username) })
+ })
+
+ pumpFun.emitter.on("status", (status) => {
+ console.log("[PumpFun] Status:", status)
+ io.emit("pumpfunStatus", { status })
+ })
+}
+
+const PORT = process.env.PORT || 3000
+server.listen(PORT, () => {
+ console.log(`Server running on http://localhost:${PORT}`)
+ console.log(`Dashboard: http://localhost:${PORT}`)
+ console.log(`Agent 1: http://localhost:${PORT}/agent1`)
+ console.log(`Agent 2: http://localhost:${PORT}/agent2`)
+ if (LIVE_CHAT) console.log(`PumpFun Live Chat: ${LIVE_CHAT ? "ENABLED" : "DISABLED"}`)
+})
diff --git a/x-spaces/server/package.json b/x-spaces/server/package.json
new file mode 100644
index 000000000..cb3eb09e1
--- /dev/null
+++ b/x-spaces/server/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "ai-2-agent",
+ "version": "1.0.0",
+ "main": "index.js",
+ "scripts": {
+ "start": "node index.js",
+ "dev": "nodemon index.js"
+ },
+ "dependencies": {
+ "axios": "^1.6.0",
+ "dotenv": "^16.3.1",
+ "express": "^4.18.2",
+ "socket.io": "^4.7.2",
+ "socket.io-client": "^4.8.3"
+ },
+ "devDependencies": {
+ "nodemon": "^3.0.1"
+ }
+}
diff --git a/x-spaces/server/public/agent1.html b/x-spaces/server/public/agent1.html
new file mode 100644
index 000000000..8bc74391b
--- /dev/null
+++ b/x-spaces/server/public/agent1.html
@@ -0,0 +1,443 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Agent 1 - Sam</title>
+ <style>
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
+ color: #fff;
+ min-height: 100vh;
+ padding: 20px;
+ }
+ .container { max-width: 800px; margin: 0 auto; }
+ h1 { color: #818cf8; margin-bottom: 20px; }
+ .status-panel {
+ background: rgba(255,255,255,0.05);
+ border-radius: 12px;
+ padding: 20px;
+ margin-bottom: 20px;
+ }
+ .status-row {
+ display: flex;
+ align-items: center;
+ gap: 15px;
+ margin-bottom: 15px;
+ }
+ .status-indicator {
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ background: #ef4444;
+ }
+ .status-indicator.connected { background: #4ade80; }
+ .status-indicator.speaking { background: #4ade80; animation: pulse 1s infinite; }
+ .status-indicator.listening { background: #60a5fa; animation: pulse 1.5s infinite; }
+ @keyframes pulse {
+ 0%, 100% { transform: scale(1); opacity: 1; }
+ 50% { transform: scale(1.2); opacity: 0.7; }
+ }
+ .btn {
+ background: linear-gradient(135deg, #667eea, #764ba2);
+ border: none;
+ border-radius: 8px;
+ padding: 12px 25px;
+ color: #fff;
+ font-weight: 600;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ }
+ .btn:hover { transform: scale(1.05); }
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
+ .audio-meter {
+ height: 20px;
+ background: rgba(255,255,255,0.1);
+ border-radius: 10px;
+ overflow: hidden;
+ margin: 15px 0;
+ }
+ .audio-level {
+ height: 100%;
+ background: linear-gradient(90deg, #4ade80, #22d3ee);
+ width: 0%;
+ transition: width 0.1s ease;
+ }
+ .log-panel {
+ background: rgba(0,0,0,0.3);
+ border-radius: 12px;
+ padding: 15px;
+ height: 200px;
+ overflow-y: auto;
+ font-family: monospace;
+ font-size: 0.85rem;
+ }
+ .log-panel p { margin-bottom: 5px; color: #9ca3af; }
+ .log-panel p.error { color: #ef4444; }
+ .log-panel p.success { color: #4ade80; }
+ .chat-panel {
+ background: rgba(255,255,255,0.05);
+ border-radius: 12px;
+ padding: 15px;
+ margin-top: 20px;
+ height: 250px;
+ overflow-y: auto;
+ }
+ .chat-msg { margin-bottom: 10px; padding: 10px; background: rgba(0,0,0,0.2); border-radius: 8px; }
+ .chat-msg.self { border-left: 3px solid #818cf8; }
+ .chat-msg.other { border-left: 3px solid #f472b6; }
+ .chat-msg.user { border-left: 3px solid #fbbf24; }
+ .turn-status {
+ padding: 15px;
+ background: rgba(255,255,255,0.05);
+ border-radius: 8px;
+ margin-bottom: 15px;
+ text-align: center;
+ }
+ .turn-status.my-turn { background: rgba(74, 222, 128, 0.2); border: 1px solid #4ade80; }
+ .turn-status.waiting { background: rgba(251, 191, 36, 0.2); border: 1px solid #fbbf24; }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>🎤 Agent 1 - Sam</h1>
+
+ <div class="turn-status" id="turnStatus">Waiting to connect...</div>
+
+ <div class="status-panel">
+ <div class="status-row">
+ <div class="status-indicator" id="connIndicator"></div>
+ <span id="connStatus">Disconnected</span>
+ <button class="btn" id="connectBtn">Connect</button>
+ </div>
+ <div class="status-row">
+ <span>Status: </span>
+ <strong id="agentStatus">Offline</strong>
+ </div>
+ <div class="audio-meter">
+ <div class="audio-level" id="audioLevel"></div>
+ </div>
+ </div>
+
+ <div class="log-panel" id="logPanel"></div>
+ <div class="chat-panel" id="chatPanel"></div>
+ </div>
+
+ <script src="/socket.io/socket.io.js"></script>
+ <script>
+ const AGENT_ID = 0
+ const AGENT_NAME = "Sam"
+ const SESSION_ENDPOINT = "/session/0"
+
+ const socket = io()
+ let pc = null
+ let dc = null
+ let isConnected = false
+ let hasTurn = false
+ let currentMessageId = null
+ let audioContext = null
+ let analyser = null
+ let isSpeaking = false
+ let speakingTimeout = null
+
+ const logPanel = document.getElementById("logPanel")
+ const chatPanel = document.getElementById("chatPanel")
+ const connectBtn = document.getElementById("connectBtn")
+ const connIndicator = document.getElementById("connIndicator")
+ const connStatus = document.getElementById("connStatus")
+ const agentStatus = document.getElementById("agentStatus")
+ const audioLevel = document.getElementById("audioLevel")
+ const turnStatus = document.getElementById("turnStatus")
+
+ function log(msg, type = "") {
+ const p = document.createElement("p")
+ p.className = type
+ p.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`
+ logPanel.appendChild(p)
+ logPanel.scrollTop = logPanel.scrollHeight
+ }
+
+ function addChat(name, text, type = "") {
+ const div = document.createElement("div")
+ div.className = "chat-msg " + type
+ div.innerHTML = `<strong>${name}:</strong> ${text}`
+ chatPanel.appendChild(div)
+ chatPanel.scrollTop = chatPanel.scrollHeight
+ }
+
+ function setStatus(status) {
+ agentStatus.textContent = status.charAt(0).toUpperCase() + status.slice(1)
+ socket.emit("statusChange", { agentId: AGENT_ID, status })
+
+ connIndicator.className = "status-indicator"
+ if (status === "speaking") connIndicator.classList.add("speaking")
+ else if (status === "listening") connIndicator.classList.add("listening")
+ else if (isConnected) connIndicator.classList.add("connected")
+ }
+
+ function updateTurnUI() {
+ if (hasTurn) {
+ turnStatus.className = "turn-status my-turn"
+ turnStatus.textContent = "🎤 Your turn to speak!"
+ } else {
+ turnStatus.className = "turn-status waiting"
+ turnStatus.textContent = "⏳ Waiting for turn..."
+ }
+ }
+
+ socket.on("connect", () => {
+ log("Socket connected", "success")
+ })
+
+ socket.on("stateUpdate", (data) => {
+ if (data.currentTurn === AGENT_ID) {
+ if (!hasTurn) {
+ hasTurn = true
+ updateTurnUI()
+ }
+ } else {
+ hasTurn = false
+ updateTurnUI()
+ }
+ })
+
+ socket.on("turnGranted", ({ agentId }) => {
+ if (agentId === AGENT_ID) {
+ hasTurn = true
+ updateTurnUI()
+ log("Turn granted!", "success")
+ }
+ })
+
+ socket.on("textComplete", (msg) => {
+ if (msg.agentId !== AGENT_ID && msg.agentId >= 0) {
+ addChat(msg.name, msg.text, "other")
+ } else if (msg.isUser) {
+ addChat(msg.name, msg.text, "user")
+ }
+ })
+
+ socket.on("textToAgent", ({ text, from }) => {
+ if (!dc || dc.readyState !== "open") return
+ if (AGENT_ID !== 0) return
+
+ log("Received text from " + from + ": " + text)
+
+ const event = {
+ type: "conversation.item.create",
+ item: {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: `[CHAT - ${from}]: ${text}` }]
+ }
+ }
+ dc.send(JSON.stringify(event))
+
+ setTimeout(() => {
+ dc.send(JSON.stringify({ type: "response.create" }))
+ }, 100)
+ })
+
+ connectBtn.addEventListener("click", startConnection)
+
+ async function startConnection() {
+ try {
+ connectBtn.disabled = true
+ log("Getting session token...")
+
+ const res = await fetch(SESSION_ENDPOINT)
+ const data = await res.json()
+ const ephemeralKey = data.value
+ log("Token received", "success")
+
+ pc = new RTCPeerConnection({
+ iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
+ })
+
+ pc.ontrack = (e) => {
+ log("Audio track received", "success")
+ if (e.streams[0]) {
+ setupAudioAnalysis(e.streams[0])
+ const audio = document.createElement("audio")
+ audio.srcObject = e.streams[0]
+ audio.autoplay = true
+ audio.playsInline = true
+ document.body.appendChild(audio)
+ audio.play().then(() => {
+ log("Audio playback started", "success")
+ }).catch(err => {
+ log("Audio play error: " + err.message, "error")
+ document.addEventListener("click", () => {
+ audio.play()
+ }, { once: true })
+ })
+ }
+ }
+
+ pc.oniceconnectionstatechange = () => {
+ log("ICE state: " + pc.iceConnectionState)
+ if (pc.iceConnectionState === "connected" || pc.iceConnectionState === "completed") {
+ isConnected = true
+ connIndicator.classList.add("connected")
+ connStatus.textContent = "Connected"
+ socket.emit("agentConnect", { agentId: AGENT_ID })
+ setStatus("idle")
+ } else if (["failed", "disconnected", "closed"].includes(pc.iceConnectionState)) {
+ isConnected = false
+ connIndicator.classList.remove("connected")
+ connStatus.textContent = "Disconnected"
+ socket.emit("agentDisconnect", { agentId: AGENT_ID })
+ }
+ }
+
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
+ stream.getTracks().forEach(track => pc.addTrack(track, stream))
+ log("Microphone access granted", "success")
+
+ dc = pc.createDataChannel("oai-events")
+ dc.onopen = () => {
+ log("Data channel open", "success")
+ setTimeout(() => {
+ try {
+ dc.send(JSON.stringify({
+ type: "response.create",
+ response: { instructions: "Greet the room warmly in one or two sentences. Mention you're here with @doi to talk about three.ws and invite people to jump in." }
+ }))
+ log("Sent greet trigger", "success")
+ } catch (e) { log("greet trigger failed: " + e.message, "error") }
+ }, 1500)
+ }
+ dc.onmessage = handleDataChannelMessage
+
+ const offer = await pc.createOffer()
+ await pc.setLocalDescription(offer)
+
+ const sdpRes = await fetch("https://api.openai.com/v1/realtime/calls?model=gpt-realtime", {
+ method: "POST",
+ body: offer.sdp,
+ headers: {
+ Authorization: "Bearer " + ephemeralKey,
+ "Content-Type": "application/sdp"
+ }
+ })
+
+ const answerSdp = await sdpRes.text()
+ await pc.setRemoteDescription({ type: "answer", sdp: answerSdp })
+ log("Connection established!", "success")
+ connectBtn.textContent = "Connected"
+
+ } catch (err) {
+ log("Error: " + err.message, "error")
+ connectBtn.disabled = false
+ }
+ }
+
+ function handleDataChannelMessage(e) {
+ try {
+ const msg = JSON.parse(e.data)
+
+ if (msg.type === "input_audio_buffer.speech_started") {
+ setStatus("listening")
+ log("Listening to input...")
+ }
+ else if (msg.type === "input_audio_buffer.speech_stopped") {
+ if (!isSpeaking) setStatus("idle")
+ }
+ else if (msg.type === "response.created") {
+ socket.emit("requestTurn", { agentId: AGENT_ID })
+ currentMessageId = Date.now().toString()
+ log("Response started")
+ }
+ else if (msg.type === "response.audio_transcript.delta") {
+ if (msg.delta) {
+ socket.emit("textDelta", {
+ agentId: AGENT_ID,
+ delta: msg.delta,
+ messageId: currentMessageId
+ })
+ }
+ }
+ else if (msg.type === "response.audio_transcript.done") {
+ if (msg.transcript) {
+ socket.emit("textComplete", {
+ agentId: AGENT_ID,
+ text: msg.transcript,
+ messageId: currentMessageId
+ })
+ addChat(AGENT_NAME, msg.transcript, "self")
+ log("Response complete")
+ }
+ }
+ else if (msg.type === "response.done") {
+ log("Response done event")
+ }
+ 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)
+ }
+ }
+ } catch (err) {
+ log("Parse error", "error")
+ }
+ }
+
+ function setupAudioAnalysis(stream) {
+ audioContext = new (window.AudioContext || window.webkitAudioContext)()
+ analyser = audioContext.createAnalyser()
+ analyser.fftSize = 256
+ analyser.smoothingTimeConstant = 0.3
+
+ const source = audioContext.createMediaStreamSource(stream)
+ source.connect(analyser)
+
+ const dataArray = new Uint8Array(analyser.frequencyBinCount)
+ const SPEAK_THRESHOLD = 0.04
+ const SILENCE_DURATION = 500
+
+ setInterval(() => {
+ if (!analyser) return
+ analyser.getByteFrequencyData(dataArray)
+
+ let sum = 0
+ for (let i = 3; i < 25; i++) sum += dataArray[i]
+ const level = (sum / 22) / 255
+
+ audioLevel.style.width = Math.min(level * 150, 100) + "%"
+ socket.emit("audioLevel", { agentId: AGENT_ID, level })
+
+ if (level > SPEAK_THRESHOLD) {
+ if (!isSpeaking) {
+ isSpeaking = true
+ setStatus("speaking")
+ log("Speaking detected (audio)")
+ }
+ if (speakingTimeout) {
+ clearTimeout(speakingTimeout)
+ speakingTimeout = null
+ }
+ } else if (isSpeaking && !speakingTimeout) {
+ speakingTimeout = setTimeout(() => {
+ isSpeaking = false
+ setStatus("idle")
+ socket.emit("releaseTurn", { agentId: AGENT_ID })
+ log("Stopped speaking (silence)")
+ speakingTimeout = null
+ }, SILENCE_DURATION)
+ }
+ }, 33)
+ }
+
+ window.addEventListener("beforeunload", () => {
+ socket.emit("agentDisconnect", { agentId: AGENT_ID })
+ })
+ </script>
+</body>
+</html>
diff --git a/x-spaces/server/public/agent2.html b/x-spaces/server/public/agent2.html
new file mode 100644
index 000000000..93faed76f
--- /dev/null
+++ b/x-spaces/server/public/agent2.html
@@ -0,0 +1,415 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Agent 2 - Lisa</title>
+ <style>
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ background: linear-gradient(135deg, #2d1b3d 0%, #1a1a2e 100%);
+ color: #fff;
+ min-height: 100vh;
+ padding: 20px;
+ }
+ .container { max-width: 800px; margin: 0 auto; }
+ h1 { color: #f472b6; margin-bottom: 20px; }
+ .status-panel {
+ background: rgba(255,255,255,0.05);
+ border-radius: 12px;
+ padding: 20px;
+ margin-bottom: 20px;
+ }
+ .status-row {
+ display: flex;
+ align-items: center;
+ gap: 15px;
+ margin-bottom: 15px;
+ }
+ .status-indicator {
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ background: #ef4444;
+ }
+ .status-indicator.connected { background: #4ade80; }
+ .status-indicator.speaking { background: #4ade80; animation: pulse 1s infinite; }
+ .status-indicator.listening { background: #60a5fa; animation: pulse 1.5s infinite; }
+ @keyframes pulse {
+ 0%, 100% { transform: scale(1); opacity: 1; }
+ 50% { transform: scale(1.2); opacity: 0.7; }
+ }
+ .btn {
+ background: linear-gradient(135deg, #f093fb, #f5576c);
+ border: none;
+ border-radius: 8px;
+ padding: 12px 25px;
+ color: #fff;
+ font-weight: 600;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ }
+ .btn:hover { transform: scale(1.05); }
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
+ .audio-meter {
+ height: 20px;
+ background: rgba(255,255,255,0.1);
+ border-radius: 10px;
+ overflow: hidden;
+ margin: 15px 0;
+ }
+ .audio-level {
+ height: 100%;
+ background: linear-gradient(90deg, #f472b6, #fb7185);
+ width: 0%;
+ transition: width 0.1s ease;
+ }
+ .log-panel {
+ background: rgba(0,0,0,0.3);
+ border-radius: 12px;
+ padding: 15px;
+ height: 200px;
+ overflow-y: auto;
+ font-family: monospace;
+ font-size: 0.85rem;
+ }
+ .log-panel p { margin-bottom: 5px; color: #9ca3af; }
+ .log-panel p.error { color: #ef4444; }
+ .log-panel p.success { color: #4ade80; }
+ .chat-panel {
+ background: rgba(255,255,255,0.05);
+ border-radius: 12px;
+ padding: 15px;
+ margin-top: 20px;
+ height: 250px;
+ overflow-y: auto;
+ }
+ .chat-msg { margin-bottom: 10px; padding: 10px; background: rgba(0,0,0,0.2); border-radius: 8px; }
+ .chat-msg.self { border-left: 3px solid #f472b6; }
+ .chat-msg.other { border-left: 3px solid #818cf8; }
+ .chat-msg.user { border-left: 3px solid #fbbf24; }
+ .turn-status {
+ padding: 15px;
+ background: rgba(255,255,255,0.05);
+ border-radius: 8px;
+ margin-bottom: 15px;
+ text-align: center;
+ }
+ .turn-status.my-turn { background: rgba(74, 222, 128, 0.2); border: 1px solid #4ade80; }
+ .turn-status.waiting { background: rgba(251, 191, 36, 0.2); border: 1px solid #fbbf24; }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>🎤 Agent 2 - Lisa</h1>
+
+ <div class="turn-status" id="turnStatus">Waiting to connect...</div>
+
+ <div class="status-panel">
+ <div class="status-row">
+ <div class="status-indicator" id="connIndicator"></div>
+ <span id="connStatus">Disconnected</span>
+ <button class="btn" id="connectBtn">Connect</button>
+ </div>
+ <div class="status-row">
+ <span>Status: </span>
+ <strong id="agentStatus">Offline</strong>
+ </div>
+ <div class="audio-meter">
+ <div class="audio-level" id="audioLevel"></div>
+ </div>
+ </div>
+
+ <div class="log-panel" id="logPanel"></div>
+ <div class="chat-panel" id="chatPanel"></div>
+ </div>
+
+ <script src="/socket.io/socket.io.js"></script>
+ <script>
+ const AGENT_ID = 1
+ const AGENT_NAME = "Lisa"
+ const SESSION_ENDPOINT = "/session/1"
+
+ const socket = io()
+ let pc = null
+ let dc = null
+ let isConnected = false
+ let hasTurn = false
+ let currentMessageId = null
+ let audioContext = null
+ let analyser = null
+ let isSpeaking = false
+ let speakingTimeout = null
+
+ const logPanel = document.getElementById("logPanel")
+ const chatPanel = document.getElementById("chatPanel")
+ const connectBtn = document.getElementById("connectBtn")
+ const connIndicator = document.getElementById("connIndicator")
+ const connStatus = document.getElementById("connStatus")
+ const agentStatus = document.getElementById("agentStatus")
+ const audioLevel = document.getElementById("audioLevel")
+ const turnStatus = document.getElementById("turnStatus")
+
+ function log(msg, type = "") {
+ const p = document.createElement("p")
+ p.className = type
+ p.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`
+ logPanel.appendChild(p)
+ logPanel.scrollTop = logPanel.scrollHeight
+ }
+
+ function addChat(name, text, type = "") {
+ const div = document.createElement("div")
+ div.className = "chat-msg " + type
+ div.innerHTML = `<strong>${name}:</strong> ${text}`
+ chatPanel.appendChild(div)
+ chatPanel.scrollTop = chatPanel.scrollHeight
+ }
+
+ function setStatus(status) {
+ agentStatus.textContent = status.charAt(0).toUpperCase() + status.slice(1)
+ socket.emit("statusChange", { agentId: AGENT_ID, status })
+
+ connIndicator.className = "status-indicator"
+ if (status === "speaking") connIndicator.classList.add("speaking")
+ else if (status === "listening") connIndicator.classList.add("listening")
+ else if (isConnected) connIndicator.classList.add("connected")
+ }
+
+ function updateTurnUI() {
+ if (hasTurn) {
+ turnStatus.className = "turn-status my-turn"
+ turnStatus.textContent = "🎤 Your turn to speak!"
+ } else {
+ turnStatus.className = "turn-status waiting"
+ turnStatus.textContent = "⏳ Waiting for turn..."
+ }
+ }
+
+ socket.on("connect", () => {
+ log("Socket connected", "success")
+ })
+
+ socket.on("stateUpdate", (data) => {
+ if (data.currentTurn === AGENT_ID) {
+ if (!hasTurn) {
+ hasTurn = true
+ updateTurnUI()
+ }
+ } else {
+ hasTurn = false
+ updateTurnUI()
+ }
+ })
+
+ socket.on("turnGranted", ({ agentId }) => {
+ if (agentId === AGENT_ID) {
+ hasTurn = true
+ updateTurnUI()
+ log("Turn granted!", "success")
+ }
+ })
+
+ socket.on("textComplete", (msg) => {
+ if (msg.agentId !== AGENT_ID && msg.agentId >= 0) {
+ addChat(msg.name, msg.text, "other")
+ } else if (msg.isUser) {
+ addChat(msg.name, msg.text, "user")
+ }
+ })
+
+ socket.on("textToAgent", ({ text, from }) => {
+ log("User message: " + text + " (Sam will respond)")
+ })
+
+ connectBtn.addEventListener("click", startConnection)
+
+ async function startConnection() {
+ try {
+ connectBtn.disabled = true
+ log("Getting session token...")
+
+ const res = await fetch(SESSION_ENDPOINT)
+ const data = await res.json()
+ const ephemeralKey = data.value
+ log("Token received", "success")
+
+ pc = new RTCPeerConnection({
+ iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
+ })
+
+ pc.ontrack = (e) => {
+ log("Audio track received", "success")
+ if (e.streams[0]) {
+ setupAudioAnalysis(e.streams[0])
+ const audio = document.createElement("audio")
+ audio.srcObject = e.streams[0]
+ audio.autoplay = true
+ audio.playsInline = true
+ document.body.appendChild(audio)
+ audio.play().then(() => {
+ log("Audio playback started", "success")
+ }).catch(err => {
+ log("Audio play error: " + err.message, "error")
+ document.addEventListener("click", () => {
+ audio.play()
+ }, { once: true })
+ })
+ }
+ }
+
+ pc.oniceconnectionstatechange = () => {
+ log("ICE state: " + pc.iceConnectionState)
+ if (pc.iceConnectionState === "connected" || pc.iceConnectionState === "completed") {
+ isConnected = true
+ connIndicator.classList.add("connected")
+ connStatus.textContent = "Connected"
+ socket.emit("agentConnect", { agentId: AGENT_ID })
+ setStatus("idle")
+ } else if (["failed", "disconnected", "closed"].includes(pc.iceConnectionState)) {
+ isConnected = false
+ connIndicator.classList.remove("connected")
+ connStatus.textContent = "Disconnected"
+ socket.emit("agentDisconnect", { agentId: AGENT_ID })
+ }
+ }
+
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
+ stream.getTracks().forEach(track => pc.addTrack(track, stream))
+ log("Microphone access granted", "success")
+
+ dc = pc.createDataChannel("oai-events")
+ dc.onopen = () => log("Data channel open", "success")
+ dc.onmessage = handleDataChannelMessage
+
+ const offer = await pc.createOffer()
+ await pc.setLocalDescription(offer)
+
+ const sdpRes = await fetch("https://api.openai.com/v1/realtime/calls?model=gpt-realtime", {
+ method: "POST",
+ body: offer.sdp,
+ headers: {
+ Authorization: "Bearer " + ephemeralKey,
+ "Content-Type": "application/sdp"
+ }
+ })
+
+ const answerSdp = await sdpRes.text()
+ await pc.setRemoteDescription({ type: "answer", sdp: answerSdp })
+ log("Connection established!", "success")
+ connectBtn.textContent = "Connected"
+
+ } catch (err) {
+ log("Error: " + err.message, "error")
+ connectBtn.disabled = false
+ }
+ }
+
+ function handleDataChannelMessage(e) {
+ try {
+ const msg = JSON.parse(e.data)
+
+ if (msg.type === "input_audio_buffer.speech_started") {
+ setStatus("listening")
+ log("Listening to input...")
+ }
+ else if (msg.type === "input_audio_buffer.speech_stopped") {
+ if (!isSpeaking) setStatus("idle")
+ }
+ else if (msg.type === "response.created") {
+ socket.emit("requestTurn", { agentId: AGENT_ID })
+ currentMessageId = Date.now().toString()
+ log("Response started")
+ }
+ else if (msg.type === "response.audio_transcript.delta") {
+ if (msg.delta) {
+ socket.emit("textDelta", {
+ agentId: AGENT_ID,
+ delta: msg.delta,
+ messageId: currentMessageId
+ })
+ }
+ }
+ else if (msg.type === "response.audio_transcript.done") {
+ if (msg.transcript) {
+ socket.emit("textComplete", {
+ agentId: AGENT_ID,
+ text: msg.transcript,
+ messageId: currentMessageId
+ })
+ addChat(AGENT_NAME, msg.transcript, "self")
+ log("Response complete")
+ }
+ }
+ else if (msg.type === "response.done") {
+ log("Response done event")
+ }
+ 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)
+ }
+ }
+ } catch (err) {
+ log("Parse error", "error")
+ }
+ }
+
+ function setupAudioAnalysis(stream) {
+ audioContext = new (window.AudioContext || window.webkitAudioContext)()
+ analyser = audioContext.createAnalyser()
+ analyser.fftSize = 256
+ analyser.smoothingTimeConstant = 0.3
+
+ const source = audioContext.createMediaStreamSource(stream)
+ source.connect(analyser)
+
+ const dataArray = new Uint8Array(analyser.frequencyBinCount)
+ const SPEAK_THRESHOLD = 0.04
+ const SILENCE_DURATION = 500
+
+ setInterval(() => {
+ if (!analyser) return
+ analyser.getByteFrequencyData(dataArray)
+
+ let sum = 0
+ for (let i = 3; i < 25; i++) sum += dataArray[i]
+ const level = (sum / 22) / 255
+
+ audioLevel.style.width = Math.min(level * 150, 100) + "%"
+ socket.emit("audioLevel", { agentId: AGENT_ID, level })
+
+ if (level > SPEAK_THRESHOLD) {
+ if (!isSpeaking) {
+ isSpeaking = true
+ setStatus("speaking")
+ log("Speaking detected (audio)")
+ }
+ if (speakingTimeout) {
+ clearTimeout(speakingTimeout)
+ speakingTimeout = null
+ }
+ } else if (isSpeaking && !speakingTimeout) {
+ speakingTimeout = setTimeout(() => {
+ isSpeaking = false
+ setStatus("idle")
+ socket.emit("releaseTurn", { agentId: AGENT_ID })
+ log("Stopped speaking (silence)")
+ speakingTimeout = null
+ }, SILENCE_DURATION)
+ }
+ }, 33)
+ }
+
+ window.addEventListener("beforeunload", () => {
+ socket.emit("agentDisconnect", { agentId: AGENT_ID })
+ })
+ </script>
+</body>
+</html>
diff --git a/x-spaces/server/public/index.html b/x-spaces/server/public/index.html
new file mode 100644
index 000000000..40971a44b
--- /dev/null
+++ b/x-spaces/server/public/index.html
@@ -0,0 +1,1520 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>JunXiuAI</title>
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=VT323&family=Press+Start+2P&display=swap');
+
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+
+ html, body {
+ height: 100%;
+ overflow: hidden;
+ }
+
+ body {
+ font-family: 'VT323', monospace;
+ background: #000;
+ color: #0f0;
+ position: relative;
+ }
+
+ body::before {
+ content: "";
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: repeating-linear-gradient(
+ 0deg,
+ rgba(0, 0, 0, 0.15),
+ rgba(0, 0, 0, 0.15) 1px,
+ transparent 1px,
+ transparent 2px
+ );
+ pointer-events: none;
+ z-index: 9999;
+ }
+
+ body::after {
+ content: "";
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: radial-gradient(ellipse at center, transparent 0%, rgba(0,0,0,0.4) 100%);
+ pointer-events: none;
+ z-index: 9998;
+ }
+
+ @keyframes flicker {
+ 0% { opacity: 0.97; }
+ 50% { opacity: 1; }
+ 100% { opacity: 0.98; }
+ }
+
+ @keyframes textGlow {
+ 0%, 100% { text-shadow: 0 0 10px currentColor, 0 0 20px currentColor; }
+ 50% { text-shadow: 0 0 15px currentColor, 0 0 30px currentColor, 0 0 40px currentColor; }
+ }
+
+ .crt {
+ animation: flicker 0.15s infinite;
+ }
+
+ .bg-gradient {
+ display: none;
+ }
+
+ .wave-container {
+ display: none;
+ }
+
+ .container {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+ position: relative;
+ z-index: 1;
+ border: 3px solid #0f0;
+ margin: 10px;
+ border-radius: 5px;
+ box-shadow: 0 0 20px #0f0, inset 0 0 20px rgba(0, 255, 0, 0.1);
+ }
+
+ .header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 15px 30px;
+ flex-shrink: 0;
+ border-bottom: 2px solid #0f0;
+ }
+
+ .logo {
+ font-family: 'VT323', monospace;
+ font-size: 0.5rem;
+ line-height: 1.0;
+ color: #0f0;
+ text-shadow: 0 0 10px #0f0, 0 0 20px #0f0;
+ animation: textGlow 2s ease-in-out infinite;
+ margin: 0;
+ white-space: pre;
+ }
+
+ .nav-buttons {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ }
+
+ .nav-btn {
+ padding: 8px 16px;
+ background: transparent;
+ border: 2px solid #0f0;
+ color: #0f0;
+ text-decoration: none;
+ font-family: 'VT323', monospace;
+ font-size: 1.2rem;
+ transition: all 0.2s ease;
+ cursor: pointer;
+ text-shadow: 0 0 5px #0f0;
+ }
+
+ .nav-btn:hover {
+ background: #0f0;
+ color: #000;
+ box-shadow: 0 0 20px #0f0;
+ }
+
+ .nav-btn.primary {
+ background: #0f0;
+ color: #000;
+ }
+
+ .nav-btn.primary:hover {
+ background: #0f0;
+ box-shadow: 0 0 30px #0f0;
+ }
+
+ .main-wrapper {
+ flex: 1;
+ display: flex;
+ min-height: 0;
+ padding: 0 20px;
+ gap: 20px;
+ }
+
+ .avatar-section {
+ flex: 1;
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ }
+
+ .terminal-container {
+ flex: 1;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ gap: 40px;
+ padding: 10px;
+ overflow: hidden;
+ }
+
+ .ascii-agent {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 20px;
+ }
+
+ .ascii-face {
+ background: transparent;
+ border: none;
+ padding: 10px;
+ transition: all 0.3s ease;
+ }
+
+ .ascii-face.speaking .face-art {
+ animation: textGlow 0.5s ease-in-out infinite;
+ }
+
+ .face-art {
+ font-family: 'VT323', monospace;
+ font-size: 58px;
+ line-height: 1.0;
+ color: #0f0;
+ margin: 0;
+ white-space: pre;
+ text-shadow: 0 0 10px #0f0, 0 0 20px #0f0;
+ }
+
+ #agent0Container .face-art {
+ color: #0ff;
+ text-shadow: 0 0 10px #0ff, 0 0 20px #0ff;
+ }
+
+ #agent0Container .ascii-face.speaking .face-art {
+ color: #0ff;
+ text-shadow: 0 0 15px #0ff, 0 0 30px #0ff, 0 0 45px #0ff;
+ }
+
+ #agent1Container .face-art {
+ color: #f0f;
+ text-shadow: 0 0 10px #f0f, 0 0 20px #f0f;
+ }
+
+ #agent1Container .ascii-face.speaking .face-art {
+ color: #f0f;
+ text-shadow: 0 0 15px #f0f, 0 0 30px #f0f, 0 0 45px #f0f;
+ }
+
+ .agent-label {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .speech-bubbles {
+ display: flex;
+ justify-content: center;
+ gap: 20px;
+ padding: 10px 20px;
+ border-bottom: 2px solid #0f0;
+ height: 120px;
+ min-height: 120px;
+ max-height: 120px;
+ overflow-y: auto;
+ flex-shrink: 0;
+ }
+
+ .agent-name {
+ font-family: 'Press Start 2P', monospace;
+ font-size: 1.1rem;
+ text-shadow: 0 0 10px currentColor;
+ }
+
+ #agent0Container .agent-name {
+ color: #0ff;
+ }
+
+ #agent1Container .agent-name {
+ color: #f0f;
+ }
+
+ .agent-state {
+ font-family: 'VT323', monospace;
+ font-size: 1.5rem;
+ color: #666;
+ text-transform: uppercase;
+ letter-spacing: 2px;
+ }
+
+ .agent-state.speaking {
+ color: #0f0;
+ text-shadow: 0 0 10px #0f0;
+ animation: textGlow 0.5s ease-in-out infinite;
+ }
+ .agent-state.listening {
+ color: #ff0;
+ text-shadow: 0 0 10px #ff0;
+ }
+
+ .audio-bar {
+ width: 150px;
+ height: 12px;
+ background: #111;
+ border: 2px solid #0f0;
+ overflow: hidden;
+ }
+
+ #agent0Container .audio-bar {
+ border-color: #0ff;
+ }
+
+ #agent1Container .audio-bar {
+ border-color: #f0f;
+ }
+
+ .audio-level {
+ height: 100%;
+ width: 0%;
+ transition: width 0.05s ease;
+ background: #0f0;
+ box-shadow: 0 0 10px #0f0;
+ }
+
+ #agent0Container .audio-level {
+ background: #0ff;
+ box-shadow: 0 0 10px #0ff;
+ }
+
+ #agent1Container .audio-level {
+ background: #f0f;
+ box-shadow: 0 0 10px #f0f;
+ }
+
+ .speech-bubble {
+ flex: 1;
+ max-width: 45%;
+ height: 100%;
+ padding: 12px 15px;
+ background: #000;
+ border: 2px solid #0f0;
+ font-family: 'VT323', monospace;
+ font-size: 1.4rem;
+ line-height: 1.3;
+ color: #0f0;
+ opacity: 1;
+ overflow-y: auto;
+ word-break: break-word;
+ overflow-wrap: break-word;
+ }
+
+ .speech-bubble.jun {
+ border-color: #0ff;
+ color: #0ff;
+ text-shadow: 0 0 5px #0ff;
+ }
+
+ .speech-bubble.jun::-webkit-scrollbar-thumb {
+ background: #0ff;
+ }
+
+ .speech-bubble.xiu {
+ border-color: #f0f;
+ color: #f0f;
+ text-shadow: 0 0 5px #f0f;
+ }
+
+ .speech-bubble.xiu::-webkit-scrollbar-thumb {
+ background: #f0f;
+ }
+
+ .speech-bubble::-webkit-scrollbar {
+ width: 4px;
+ }
+
+ .speech-bubble::-webkit-scrollbar-track {
+ background: #000;
+ }
+
+ .speech-bubble.visible {
+ opacity: 1;
+ }
+
+ .speech-bubble .bubble-name {
+ font-family: 'Press Start 2P', monospace;
+ font-size: 0.6rem;
+ margin-bottom: 6px;
+ font-size: 0.75rem;
+ }
+
+ .speech-bubble.jun .bubble-name { color: #0ff; }
+ .speech-bubble.xiu .bubble-name { color: #f0f; }
+
+ .speech-bubble .bubble-text {
+ color: inherit;
+ }
+
+ .speech-bubble .bubble-text.streaming::after {
+ content: '█';
+ animation: blink 0.5s infinite;
+ }
+
+ @keyframes blink {
+ 0%, 50% { opacity: 1; }
+ 51%, 100% { opacity: 0; }
+ }
+
+ .chat-section {
+ width: 350px;
+ background: #000;
+ border: 2px solid #0f0;
+ display: flex;
+ flex-direction: column;
+ flex-shrink: 0;
+ margin: 10px 0;
+ }
+
+ .chat-header {
+ padding: 15px 20px;
+ border-bottom: 2px solid #0f0;
+ font-family: 'Press Start 2P', monospace;
+ font-size: 0.9rem;
+ color: #0f0;
+ text-shadow: 0 0 10px #0f0;
+ }
+
+ .chat-messages {
+ flex: 1;
+ overflow-y: auto;
+ padding: 15px;
+ font-size: 1.4rem;
+ }
+
+ .chat-messages::-webkit-scrollbar {
+ width: 8px;
+ }
+
+ .chat-messages::-webkit-scrollbar-track {
+ background: #000;
+ }
+
+ .chat-messages::-webkit-scrollbar-thumb {
+ background: #0f0;
+ }
+
+ .message {
+ margin-bottom: 12px;
+ animation: fadeIn 0.3s ease;
+ font-family: 'VT323', monospace;
+ }
+
+ @keyframes fadeIn {
+ from { opacity: 0; transform: translateY(5px); }
+ to { opacity: 1; transform: translateY(0); }
+ }
+
+ .message-line {
+ line-height: 1.5;
+ }
+
+ .msg-name {
+ font-weight: bold;
+ }
+
+ .msg-name.sam { color: #0ff; text-shadow: 0 0 5px #0ff; }
+ .msg-name.lisa { color: #f0f; text-shadow: 0 0 5px #f0f; }
+ .msg-name.user { color: #ff0; text-shadow: 0 0 5px #ff0; }
+ .msg-name.pumpfun { color: #0f0; text-shadow: 0 0 5px #0f0; }
+
+ .message {
+ padding: 8px 10px;
+ margin: 4px 0;
+ border-left: 3px solid transparent;
+ }
+
+ .message.ai-msg {
+ background: rgba(0, 255, 255, 0.05);
+ border-left-color: #0ff;
+ color: #0ff;
+ }
+
+ .message.user-msg {
+ background: rgba(255, 255, 0, 0.05);
+ border-left-color: #ff0;
+ color: #ff0;
+ }
+
+ .message.pumpfun-msg {
+ background: rgba(0, 255, 0, 0.05);
+ border-left-color: #0f0;
+ color: #0f0;
+ }
+
+ .msg-badge {
+ font-family: 'VT323', monospace;
+ font-size: 0.9rem;
+ padding: 2px 6px;
+ border: 1px solid currentColor;
+ margin-right: 6px;
+ font-weight: 600;
+ text-transform: uppercase;
+ }
+
+ .msg-badge.ai { background: transparent; color: #0ff; border-color: #0ff; }
+ .msg-badge.web { background: transparent; color: #ff0; border-color: #ff0; }
+ .msg-badge.pump { background: transparent; color: #0f0; border-color: #0f0; }
+
+ .msg-you {
+ font-weight: 700;
+ color: #ff0;
+ margin-right: 4px;
+ }
+
+ .message.own-msg {
+ background: rgba(255, 255, 0, 0.1);
+ border-left-color: #ff0;
+ border-left-width: 3px;
+ }
+
+ .msg-text {
+ color: inherit;
+ word-break: break-word;
+ overflow-wrap: break-word;
+ }
+
+ .msg-text.streaming::after {
+ content: '█';
+ animation: blink 0.5s infinite;
+ }
+
+ .chat-input {
+ display: flex;
+ gap: 10px;
+ padding: 15px;
+ border-top: 2px solid #0f0;
+ }
+
+ .chat-input input {
+ flex: 1;
+ background: #000;
+ border: 2px solid #0f0;
+ padding: 12px 15px;
+ color: #0f0;
+ font-family: 'VT323', monospace;
+ font-size: 1.2rem;
+ transition: all 0.2s ease;
+ }
+
+ .chat-input input::placeholder { color: #060; }
+ .chat-input input:focus {
+ outline: none;
+ box-shadow: 0 0 15px #0f0;
+ }
+
+ .chat-input button {
+ background: #0f0;
+ border: none;
+ padding: 12px 20px;
+ color: #000;
+ font-family: 'VT323', monospace;
+ font-weight: bold;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ font-size: 1.2rem;
+ }
+
+ .chat-input button:hover:not(:disabled) {
+ box-shadow: 0 0 20px #0f0;
+ }
+
+ .chat-input button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ .chat-input input:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ .input-warning {
+ position: absolute;
+ bottom: 100%;
+ left: 50%;
+ transform: translateX(-50%);
+ background: #000;
+ border: 2px solid #f00;
+ color: #f00;
+ padding: 8px 16px;
+ font-family: 'VT323', monospace;
+ font-size: 1rem;
+ white-space: nowrap;
+ opacity: 0;
+ visibility: hidden;
+ transition: all 0.3s ease;
+ margin-bottom: 8px;
+ text-shadow: 0 0 5px #f00;
+ }
+
+ .input-warning.show {
+ opacity: 1;
+ visibility: visible;
+ }
+
+ .chat-input {
+ position: relative;
+ }
+
+ ::-webkit-scrollbar { width: 8px; }
+ ::-webkit-scrollbar-track { background: #000; }
+ ::-webkit-scrollbar-thumb { background: #0f0; }
+ ::-webkit-scrollbar-thumb:hover { background: #0f0; }
+
+ @media (max-width: 1024px) {
+ .nav-buttons .nav-btn:not(.primary) {
+ padding: 6px 10px;
+ font-size: 0.7rem;
+ }
+
+ .nav-btn.primary {
+ padding: 8px 14px;
+ font-size: 0.75rem;
+ }
+
+ .main-wrapper {
+ flex-direction: column;
+ padding: 0 20px;
+ }
+
+ .chat-section {
+ width: 100%;
+ height: 250px;
+ margin: 10px 0;
+ border-radius: 16px;
+ }
+
+ }
+
+ @media (max-width: 768px) {
+ html, body {
+ overflow-y: auto;
+ }
+
+ .container {
+ height: auto;
+ min-height: 100vh;
+ }
+
+ .header {
+ padding: 12px 15px;
+ gap: 8px;
+ }
+
+ .logo {
+ font-size: 0.4rem;
+ }
+
+ .nav-buttons {
+ gap: 4px;
+ }
+
+ .nav-buttons .nav-btn:not(.primary) {
+ padding: 6px 10px;
+ font-size: 1rem;
+ }
+
+ .nav-btn.primary {
+ padding: 8px 14px;
+ font-size: 1.1rem;
+ }
+
+ .main-wrapper {
+ flex-direction: column;
+ padding: 0 15px;
+ gap: 10px;
+ }
+
+ .speech-bubbles {
+ height: 110px;
+ min-height: 110px;
+ max-height: 110px;
+ gap: 15px;
+ flex-direction: row;
+ }
+
+ .terminal-container {
+ gap: 30px;
+ padding: 15px;
+ flex-direction: row;
+ }
+
+ .face-art {
+ font-size: 38px;
+ }
+
+ .agent-name {
+ font-size: 0.7rem;
+ }
+
+ .agent-state {
+ font-size: 1.2rem;
+ }
+
+ .audio-bar {
+ width: 100px;
+ height: 8px;
+ }
+
+ .speech-bubble {
+ flex: 1;
+ max-width: 45%;
+ padding: 10px;
+ font-size: 1.2rem;
+ }
+
+ .chat-section {
+ width: 100%;
+ height: 280px;
+ margin: 8px 0;
+ }
+
+ .chat-header {
+ padding: 12px 15px;
+ font-size: 0.7rem;
+ }
+
+ .chat-messages {
+ padding: 12px;
+ font-size: 1.3rem;
+ }
+
+ .chat-input {
+ padding: 10px;
+ gap: 8px;
+ }
+
+ .chat-input input {
+ padding: 10px;
+ font-size: 0.85rem;
+ border-radius: 12px;
+ }
+
+ .chat-input button {
+ padding: 10px 16px;
+ font-size: 0.85rem;
+ border-radius: 12px;
+ }
+
+ .wave-container {
+ display: none;
+ }
+ }
+
+ @media (max-width: 480px) {
+ .container {
+ height: 100vh;
+ max-height: 100vh;
+ overflow: hidden;
+ margin: 5px;
+ }
+
+ .header {
+ padding: 8px 10px;
+ gap: 5px;
+ flex-shrink: 0;
+ }
+
+ .logo {
+ font-size: 0.18rem;
+ line-height: 0.9;
+ }
+
+ .nav-buttons {
+ gap: 4px;
+ }
+
+ .nav-buttons .nav-btn:not(.primary) {
+ padding: 4px 6px;
+ font-size: 0.8rem;
+ }
+
+ .nav-btn.primary {
+ padding: 5px 8px;
+ font-size: 0.85rem;
+ }
+
+ .main-wrapper {
+ padding: 0 5px;
+ gap: 5px;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+ }
+
+ .avatar-section {
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+ }
+
+ .speech-bubbles {
+ height: 50px;
+ min-height: 50px;
+ max-height: 50px;
+ gap: 5px;
+ padding: 3px;
+ flex-direction: row;
+ flex-shrink: 0;
+ }
+
+ .speech-bubble {
+ flex: 1;
+ max-width: 50%;
+ padding: 4px;
+ font-size: 0.85rem;
+ line-height: 1.15;
+ }
+
+ .speech-bubble .bubble-name {
+ font-size: 0.4rem;
+ margin-bottom: 2px;
+ }
+
+ .terminal-container {
+ gap: 5px;
+ flex-direction: row;
+ padding: 3px;
+ flex: 0 0 auto;
+ min-height: 0;
+ overflow: hidden;
+ }
+
+ .ascii-agent {
+ gap: 2px;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+ }
+
+ .face-art {
+ font-size: 14px;
+ line-height: 0.9;
+ }
+
+ .agent-label {
+ gap: 1px;
+ flex-shrink: 0;
+ }
+
+ .agent-name {
+ font-size: 0.45rem;
+ }
+
+ .agent-state {
+ font-size: 0.75rem;
+ }
+
+ .audio-bar {
+ width: 60px;
+ height: 5px;
+ }
+
+ .chat-section {
+ flex: 1;
+ min-height: 150px;
+ margin: 3px 0;
+ flex-shrink: 0;
+ }
+
+ .chat-header {
+ padding: 8px 10px;
+ font-size: 0.5rem;
+ }
+
+ .chat-messages {
+ padding: 8px;
+ font-size: 1rem;
+ }
+
+ .chat-input {
+ padding: 8px;
+ gap: 5px;
+ margin-bottom: 20px;
+ }
+
+ .chat-input input {
+ padding: 10px;
+ font-size: 1rem;
+ }
+
+ .chat-input button {
+ padding: 10px 14px;
+ font-size: 1rem;
+ }
+ }
+
+ .modal-overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: rgba(0, 0, 0, 0.9);
+ z-index: 9999;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 20px;
+ opacity: 1;
+ transition: opacity 0.3s ease;
+ }
+
+ .modal-overlay.hidden {
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ .modal {
+ background: #000;
+ border: 3px solid #0f0;
+ padding: 40px;
+ max-width: 550px;
+ width: 100%;
+ text-align: center;
+ box-shadow: 0 0 50px #0f0;
+ transform: scale(1);
+ transition: transform 0.3s ease;
+ }
+
+ .modal-overlay.hidden .modal {
+ transform: scale(0.9);
+ }
+
+ .modal-title {
+ font-family: 'Press Start 2P', monospace;
+ font-size: 1.1rem;
+ color: #0f0;
+ margin-bottom: 20px;
+ text-shadow: 0 0 10px #0f0;
+ }
+
+ .modal-text {
+ font-family: 'VT323', monospace;
+ font-size: 1.4rem;
+ color: #0f0;
+ line-height: 1.8;
+ margin-bottom: 32px;
+ text-shadow: 0 0 5px #0f0;
+ white-space: pre-line;
+ }
+
+ .modal-buttons {
+ display: flex;
+ gap: 15px;
+ justify-content: center;
+ flex-wrap: nowrap;
+ }
+
+ .modal-btn {
+ padding: 12px 24px;
+ font-family: 'VT323', monospace;
+ font-size: 1.3rem;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ text-decoration: none;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ white-space: nowrap;
+ }
+
+ .modal-btn.primary {
+ background: #0f0;
+ color: #000;
+ border: none;
+ }
+
+ .modal-btn.primary:hover {
+ box-shadow: 0 0 30px #0f0;
+ }
+
+ .modal-btn.secondary {
+ background: transparent;
+ color: #0f0;
+ border: 2px solid #0f0;
+ }
+
+ .modal-btn.secondary:hover {
+ background: #0f0;
+ color: #000;
+ }
+
+ .modal-btn svg {
+ width: 18px;
+ height: 18px;
+ fill: currentColor;
+ }
+
+ @media (max-width: 768px) {
+ .modal {
+ padding: 30px 24px;
+ border-radius: 20px;
+ }
+
+ .modal-title {
+ font-size: 1.4rem;
+ }
+
+ .modal-text {
+ font-size: 0.9rem;
+ margin-bottom: 24px;
+ }
+
+ .modal-btn {
+ padding: 12px 20px;
+ font-size: 0.85rem;
+ }
+ }
+
+ @media (max-width: 480px) {
+ .modal {
+ padding: 24px 20px;
+ border-radius: 16px;
+ }
+
+ .modal-title {
+ font-size: 1.2rem;
+ }
+
+ .modal-text {
+ font-size: 0.85rem;
+ }
+
+ .modal-buttons {
+ flex-direction: column;
+ gap: 10px;
+ }
+
+ .modal-btn {
+ width: 100%;
+ justify-content: center;
+ padding: 12px 20px;
+ font-size: 0.9rem;
+ }
+ }
+ </style>
+</head>
+<body>
+ <div class="modal-overlay" id="welcomeModal">
+ <div class="modal">
+ <h2 class="modal-title" id="modalTitle"></h2>
+ <p class="modal-text" id="modalText"></p>
+ <div class="modal-buttons">
+ <a href="#" id="modalXLink" target="_blank" class="modal-btn primary">
+ <svg viewBox="0 0 24 24"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
+ Community & Live Space
+ </a>
+ <button class="modal-btn secondary" onclick="closeModal()">
+ Continue to Site
+ </button>
+ </div>
+ </div>
+ </div>
+ <div class="container crt">
+ <div class="header">
+ <pre class="logo ascii-logo"> $$$$$\ $$\ $$\ $$\ $$$$$$\ $$$$$$\
+ \__$$ | $$ | $$ |\__| $$ __$$\ \_$$ _|
+ $$ |$$\ $$\ $$$$$$$\ \$$\ $$ |$$\ $$\ $$\ $$ / $$ | $$ |
+ $$ |$$ | $$ |$$ __$$\ \$$$$ / $$ |$$ | $$ |$$$$$$$$ | $$ |
+$$\ $$ |$$ | $$ |$$ | $$ | $$ $$< $$ |$$ | $$ |$$ __$$ | $$ |
+$$ | $$ |$$ | $$ |$$ | $$ |$$ /\$$\ $$ |$$ | $$ |$$ | $$ | $$ |
+\$$$$$$ |\$$$$$$ |$$ | $$ |$$ / $$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$\
+ \______/ \______/ \__| \__|\__| \__|\__| \______/ \__| \__|\______|</pre>
+ <div class="nav-buttons">
+ <a href="#" id="buyLink" target="_blank" class="nav-btn primary">Buy</a>
+ <a href="#" id="xLink" target="_blank" class="nav-btn">X Community</a>
+ <a href="#" id="githubLink" target="_blank" class="nav-btn">Github</a>
+ </div>
+ </div>
+
+ <div class="main-wrapper">
+ <div class="avatar-section">
+ <div class="speech-bubbles">
+ <div class="speech-bubble jun" id="bubble0">
+ <div class="bubble-name">Jun</div>
+ <div class="bubble-text" id="bubbleText0"></div>
+ </div>
+ <div class="speech-bubble xiu" id="bubble1">
+ <div class="bubble-name">Xiu</div>
+ <div class="bubble-text" id="bubbleText1"></div>
+ </div>
+ </div>
+
+ <div class="terminal-container">
+ <div class="ascii-agent" id="agent0Container">
+ <div class="ascii-face" id="asciiFace0">
+<pre class="face-art">
+ .=(((=.
+ i;' `:i
+ !__ __!
+ (~(_)-(_)~)
+ ! n !
+ \ <span class="mouth" id="mouth0">-</span> /
+ !`---'!
+ /`-._.-'\
+ _.-~'\_/ |o\_/`~-._
+' |o `
+</pre>
+ </div>
+ <div class="agent-label">
+ <span class="agent-name">Jun</span>
+ <span class="agent-state" id="agent0State">offline</span>
+ </div>
+ <div class="audio-bar">
+ <div class="audio-level" id="agent0Audio"></div>
+ </div>
+ </div>
+
+ <div class="ascii-agent" id="agent1Container">
+ <div class="ascii-face" id="asciiFace1">
+<pre class="face-art">
+ (\!/)
+ (((|||)))
+ ((//'~`\\))
+ ((! _ _ !))
+ ((. O O .))
+ )) J ((
+ ( \ <span class="mouth" id="mouth1">-</span> / )
+ !`._.'!
+ / \
+ _.-~' `~-._
+</pre>
+ </div>
+ <div class="agent-label">
+ <span class="agent-name">Xiu</span>
+ <span class="agent-state" id="agent1State">offline</span>
+ </div>
+ <div class="audio-bar">
+ <div class="audio-level" id="agent1Audio"></div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="chat-section">
+ <div class="chat-header">Live Chat</div>
+ <div class="chat-messages" id="chatMessages"></div>
+ <div class="chat-input">
+ <div class="input-warning" id="inputWarning">Minimum 3 characters required</div>
+ <input type="text" id="userInput" placeholder="Ask the AI agents...">
+ <button id="sendBtn">Ask</button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <script src="/socket.io/socket.io.js"></script>
+ <script>
+ const junMouthFrames = ['-', '~', 'o', 'O', '0', 'O', 'o', '~'];
+ const xiuMouthFrames = ['-', '~', 'o', 'O', '0', 'O', 'o', '~'];
+ let mouthInterval0 = null;
+ let mouthInterval1 = null;
+
+ let audioLevels = [0, 0];
+ let speakingStates = [false, false];
+
+ function closeModal() {
+ const modal = document.getElementById("welcomeModal")
+ modal.classList.add("hidden")
+ setTimeout(() => modal.style.display = "none", 300)
+ }
+
+ function typeWriter(element, text, speed, callback) {
+ let i = 0
+ element.textContent = ""
+ function type() {
+ if (i < text.length) {
+ element.textContent += text.charAt(i)
+ i++
+ setTimeout(type, speed)
+ } else if (callback) {
+ callback()
+ }
+ }
+ type()
+ }
+
+ function startModalTypewriter() {
+ const title = "Welcome to JunXiu AI"
+ const text = "Join X Space to hear AI voices. Website shows text only.\n加入 X Space 听 AI 语音,网站仅显示文字。"
+ const titleEl = document.getElementById("modalTitle")
+ const textEl = document.getElementById("modalText")
+ typeWriter(titleEl, title, 50, () => {
+ typeWriter(textEl, text, 20)
+ })
+ }
+
+ document.addEventListener("DOMContentLoaded", startModalTypewriter)
+
+ function generateNick() {
+ const adj = ["Cool", "Fast", "Degen", "Based", "Alpha", "Sigma", "Anon", "Crypto", "Moon", "Ape"]
+ const noun = ["Trader", "Holder", "Chad", "King", "Whale", "Fren", "Ser", "Maxi", "Bull", "Bear"]
+ const num = Math.floor(Math.random() * 999)
+ return adj[Math.floor(Math.random() * adj.length)] + noun[Math.floor(Math.random() * noun.length)] + num
+ }
+
+ function getUserNick() {
+ let nick = localStorage.getItem("userNick")
+ if (!nick) {
+ nick = generateNick()
+ localStorage.setItem("userNick", nick)
+ }
+ return nick
+ }
+
+ const userNick = getUserNick()
+
+ async function loadConfig() {
+ try {
+ const res = await fetch("/config")
+ const config = await res.json()
+ if (!config.inputChat) {
+ const chatInput = document.querySelector(".chat-input")
+ if (chatInput) chatInput.style.display = "none"
+ }
+ if (config.buyLink) document.getElementById("buyLink").href = config.buyLink
+ if (config.xLink) {
+ document.getElementById("xLink").href = config.xLink
+ document.getElementById("modalXLink").href = config.xLink
+ }
+ if (config.githubLink) document.getElementById("githubLink").href = config.githubLink
+ } catch (e) {
+ console.log("Config load error:", e)
+ }
+ }
+
+ const socket = io()
+ const chatMessages = document.getElementById("chatMessages")
+ const userInput = document.getElementById("userInput")
+ const sendBtn = document.getElementById("sendBtn")
+
+ const streamingTexts = {}
+ const agentNames = { 0: "Jun", 1: "Xiu" }
+ const bubbleTimeouts = {}
+
+ function startMouthAnimation(agentId) {
+ if (agentId === 0) {
+ if (mouthInterval0) return
+ let frameIdx = 0
+ mouthInterval0 = setInterval(() => {
+ const mouth = document.getElementById("mouth0")
+ if (mouth) mouth.textContent = junMouthFrames[frameIdx % junMouthFrames.length]
+ frameIdx++
+ }, 100)
+ } else {
+ if (mouthInterval1) return
+ let frameIdx = 0
+ mouthInterval1 = setInterval(() => {
+ const mouth1 = document.getElementById("mouth1")
+ if (mouth1) mouth1.textContent = xiuMouthFrames[frameIdx % xiuMouthFrames.length]
+ frameIdx++
+ }, 100)
+ }
+ }
+
+ function stopMouthAnimation(agentId) {
+ if (agentId === 0) {
+ if (mouthInterval0) {
+ clearInterval(mouthInterval0)
+ mouthInterval0 = null
+ const mouth = document.getElementById("mouth0")
+ if (mouth) mouth.textContent = '-'
+ }
+ } else {
+ if (mouthInterval1) {
+ clearInterval(mouthInterval1)
+ mouthInterval1 = null
+ const mouth1 = document.getElementById("mouth1")
+ if (mouth1) mouth1.textContent = '-'
+ }
+ }
+ }
+
+ function init() {
+ console.log("ASCII Terminal initialized")
+ }
+
+ socket.on("stateUpdate", (data) => {
+ for (const id in data.agents) {
+ updateAgentUI(parseInt(id), data.agents[id])
+ }
+ })
+
+ socket.on("agentStatus", ({ agentId, status }) => {
+ updateAgentStatus(agentId, status)
+ })
+
+ socket.on("audioLevel", ({ agentId, level }) => {
+ audioLevels[agentId] = level
+ const audioEl = document.getElementById(`agent${agentId}Audio`)
+ if (audioEl) audioEl.style.width = Math.min(level * 150, 100) + "%"
+ })
+
+ socket.on("textDelta", ({ agentId, delta, messageId }) => {
+ if (!streamingTexts[messageId]) streamingTexts[messageId] = ""
+ streamingTexts[messageId] += delta
+ updateStreamingMessage(agentId, messageId, streamingTexts[messageId])
+ updateSpeechBubble(agentId, streamingTexts[messageId], true)
+ })
+
+ socket.on("textComplete", (msg) => {
+ delete streamingTexts[msg.id]
+ finalizeMessage(msg)
+ if (msg.agentId >= 0) {
+ updateSpeechBubble(msg.agentId, msg.text, false)
+ }
+ })
+
+ socket.on("messageHistory", (messages) => {
+ chatMessages.innerHTML = ""
+ messages.forEach(msg => addMessage(msg))
+ })
+
+ socket.on("pumpfunMessage", (msg) => {
+ addMessage({
+ agentId: -1,
+ name: msg.name,
+ text: msg.text,
+ source: "pumpfun"
+ })
+ })
+
+ socket.on("pumpfunStatus", ({ status }) => {
+ console.log("[PumpFun] Status:", status)
+ })
+
+ function updateSpeechBubble(agentId, text, isStreaming) {
+ const bubble = document.getElementById(`bubble${agentId}`)
+ const bubbleText = document.getElementById(`bubbleText${agentId}`)
+
+ if (!bubble || !bubbleText) return
+
+ if (bubbleTimeouts[agentId]) {
+ clearTimeout(bubbleTimeouts[agentId])
+ bubbleTimeouts[agentId] = null
+ }
+
+ bubbleText.textContent = text
+
+ if (isStreaming) {
+ bubbleText.classList.add("streaming")
+ } else {
+ bubbleText.classList.remove("streaming")
+ }
+
+ bubble.classList.add("visible")
+ bubble.scrollTop = bubble.scrollHeight
+
+ if (!isStreaming) {
+ bubbleTimeouts[agentId] = setTimeout(() => {
+ bubble.classList.remove("visible")
+ }, 8000)
+ }
+ }
+
+ function updateAgentUI(agentId, agent) {
+ const stateEl = document.getElementById(`agent${agentId}State`)
+ const faceEl = document.getElementById(`asciiFace${agentId}`)
+
+ if (stateEl) {
+ stateEl.textContent = agent.status
+ stateEl.className = "agent-state"
+ if (agent.status === "speaking") stateEl.classList.add("speaking")
+ if (agent.status === "listening") stateEl.classList.add("listening")
+ }
+
+ if (faceEl) {
+ faceEl.classList.remove("speaking", "listening")
+ if (agent.status === "speaking") faceEl.classList.add("speaking")
+ if (agent.status === "listening") faceEl.classList.add("listening")
+ }
+
+ speakingStates[agentId] = agent.status === "speaking"
+ if (agent.status === "speaking") {
+ startMouthAnimation(agentId)
+ } else {
+ stopMouthAnimation(agentId)
+ }
+ }
+
+ function updateAgentStatus(agentId, status) {
+ const stateEl = document.getElementById(`agent${agentId}State`)
+ const faceEl = document.getElementById(`asciiFace${agentId}`)
+
+ if (stateEl) {
+ stateEl.textContent = status
+ stateEl.className = "agent-state"
+ if (status === "speaking") stateEl.classList.add("speaking")
+ if (status === "listening") stateEl.classList.add("listening")
+ }
+
+ if (faceEl) {
+ faceEl.classList.remove("speaking", "listening")
+ if (status === "speaking") faceEl.classList.add("speaking")
+ if (status === "listening") faceEl.classList.add("listening")
+ }
+
+ speakingStates[agentId] = status === "speaking"
+ if (status === "speaking") {
+ startMouthAnimation(agentId)
+ } else {
+ stopMouthAnimation(agentId)
+ }
+ }
+
+ function updateStreamingMessage(agentId, messageId, text) {
+ let msgEl = document.getElementById("msg-" + messageId)
+ if (!msgEl) {
+ const name = agentNames[agentId] || "Agent"
+ msgEl = document.createElement("div")
+ msgEl.className = "message ai-msg"
+ msgEl.id = "msg-" + messageId
+ msgEl.innerHTML = `<div class="message-line"><span class="msg-badge ai">AI</span><span class="msg-name ${name.toLowerCase()}">${name}:</span> <span class="msg-text streaming"></span></div>`
+ chatMessages.insertBefore(msgEl, chatMessages.firstChild)
+ chatMessages.scrollTop = 0
+ }
+ const textEl = msgEl.querySelector(".msg-text")
+ if (textEl) textEl.textContent = text
+ }
+
+ function finalizeMessage(msg) {
+ let msgEl = document.getElementById("msg-" + msg.id)
+ if (msgEl) {
+ const textEl = msgEl.querySelector(".msg-text")
+ if (textEl) {
+ textEl.classList.remove("streaming")
+ textEl.textContent = msg.text
+ }
+ } else {
+ addMessage(msg)
+ }
+ }
+
+ function isWalletAddress(str) {
+ return str && str.length >= 32 && /^[a-zA-Z0-9]+$/.test(str)
+ }
+
+ function shortenName(name) {
+ if (isWalletAddress(name)) {
+ return name.slice(0, 4) + "..." + name.slice(-4)
+ }
+ return name
+ }
+
+ function addMessage(msg) {
+ if (msg.id && document.getElementById("msg-" + msg.id)) return
+
+ const isAI = msg.agentId === 0 || msg.agentId === 1
+ const isPumpfun = msg.source === "pumpfun"
+ const isWebUser = msg.isUser || (!isAI && !isPumpfun)
+
+ const rawName = msg.name || agentNames[msg.agentId] || "User"
+ const name = shortenName(rawName)
+ const isOwnMsg = rawName === userNick
+
+ let nameClass = "user"
+ let msgClass = "message"
+ let badge = ""
+ let namePrefix = ""
+
+ if (isAI) {
+ nameClass = rawName.toLowerCase()
+ msgClass += " ai-msg"
+ badge = `<span class="msg-badge ai">AI</span>`
+ } else if (isPumpfun) {
+ nameClass = "pumpfun"
+ msgClass += " pumpfun-msg"
+ badge = `<span class="msg-badge pump">PUMP</span>`
+ } else {
+ msgClass += " user-msg"
+ badge = `<span class="msg-badge web">WEB</span>`
+ if (isOwnMsg) {
+ msgClass += " own-msg"
+ namePrefix = `<span class="msg-you">You</span> `
+ }
+ }
+
+ const msgEl = document.createElement("div")
+ msgEl.className = msgClass
+ if (msg.id) msgEl.id = "msg-" + msg.id
+ msgEl.innerHTML = `<div class="message-line">${badge}${namePrefix}<span class="msg-name ${nameClass}">${name}:</span> <span class="msg-text">${msg.text}</span></div>`
+ chatMessages.insertBefore(msgEl, chatMessages.firstChild)
+ chatMessages.scrollTop = 0
+ }
+
+ const inputWarning = document.getElementById("inputWarning")
+ let isCooldown = false
+
+ function showWarning() {
+ inputWarning.classList.add("show")
+ setTimeout(() => inputWarning.classList.remove("show"), 2000)
+ }
+
+ function startCooldown() {
+ isCooldown = true
+ userInput.disabled = true
+ sendBtn.disabled = true
+ let seconds = 5
+ const originalText = "Ask"
+ const originalPlaceholder = userInput.placeholder
+
+ const interval = setInterval(() => {
+ sendBtn.textContent = seconds + "s"
+ userInput.placeholder = `Wait ${seconds}s...`
+ seconds--
+ if (seconds < 0) {
+ clearInterval(interval)
+ sendBtn.textContent = originalText
+ userInput.placeholder = originalPlaceholder
+ userInput.disabled = false
+ sendBtn.disabled = false
+ isCooldown = false
+ userInput.focus()
+ }
+ }, 1000)
+ }
+
+ function sendMessage() {
+ if (isCooldown) return
+ const text = userInput.value.trim()
+ if (text.length < 3) {
+ showWarning()
+ return
+ }
+ socket.emit("userMessage", { text, from: userNick })
+ userInput.value = ""
+ startCooldown()
+ }
+
+ sendBtn.addEventListener("click", sendMessage)
+ userInput.addEventListener("keypress", (e) => {
+ if (e.key === "Enter") sendMessage()
+ })
+
+ document.addEventListener("DOMContentLoaded", async () => {
+ await loadConfig()
+ setTimeout(init, 100)
+ })
+ </script>
+</body>
+</html>
diff --git a/x-spaces/vm/launch.sh b/x-spaces/vm/launch.sh
new file mode 100644
index 000000000..bf4194cf8
--- /dev/null
+++ b/x-spaces/vm/launch.sh
@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+# Boot the full x-spaces stack on a single VM (run as user 'agent').
+# Xvfb :99 -> PulseAudio -> Node server (systemd) -> two Chrome instances -> X-tab automation
+set -euo pipefail
+
+SPACE_URL="${1:-}"
+if [ -z "$SPACE_URL" ]; then
+ echo "usage: $0 <https://x.com/i/spaces/...>"
+ exit 1
+fi
+
+LOG="${HOME}/launch.log"
+SERVER_DIR="${HOME}/ai-agents-x-space"
+AUTOMATION_DIR="${HOME}/automation"
+
+echo "=== launch at $(date) for $SPACE_URL ===" | tee -a "$LOG"
+
+# 1. Xvfb on :99
+if ! pgrep -f "Xvfb :99" >/dev/null; then
+ Xvfb :99 -screen 0 1280x800x24 -ac +extension RANDR >>"$LOG" 2>&1 &
+ sleep 1
+fi
+export DISPLAY=:99
+echo "[launch] Xvfb up on :99" | tee -a "$LOG"
+
+# 2. PulseAudio
+pulseaudio --kill 2>/dev/null || true
+sleep 1
+pulseaudio --start --exit-idle-time=-1 --log-target=file:"${HOME}/pulse.log"
+sleep 2
+pactl list short sinks | tee -a "$LOG"
+
+# 3. Node server (systemd will keep it running)
+sudo systemctl start swarm-server.service || true
+sleep 2
+echo "[launch] node server: $(curl -s -o /dev/null -w '%{http_code}' http://localhost:3000/)" | tee -a "$LOG"
+
+# 4. Two Chrome instances with per-process Pulse routing
+pkill -f "chrome.*user-data-dir=/tmp/chrome-agent" 2>/dev/null || true
+pkill -f "chrome.*user-data-dir=/tmp/chrome-x" 2>/dev/null || true
+sleep 1
+rm -rf /tmp/chrome-agent /tmp/chrome-x
+
+CHROME=/usr/bin/google-chrome
+CHROME_FLAGS=(
+ --no-default-browser-check --no-first-run
+ --no-sandbox
+ --use-fake-ui-for-media-stream
+ --autoplay-policy=no-user-gesture-required
+ --disable-features=MediaRouter
+)
+
+# Agent Chrome: speaks INTO agent_speakers (cable A), listens to agent_mic (= x_speakers.monitor)
+PULSE_SINK=agent_speakers PULSE_SOURCE=agent_mic DISPLAY=:99 \
+ $CHROME "${CHROME_FLAGS[@]}" --user-data-dir=/tmp/chrome-agent \
+ --remote-debugging-port=9222 about:blank >>"${HOME}/chrome-agent.log" 2>&1 &
+
+# X Chrome: speaks INTO x_speakers (cable B), listens to x_mic (= agent_speakers.monitor)
+PULSE_SINK=x_speakers PULSE_SOURCE=x_mic DISPLAY=:99 \
+ $CHROME "${CHROME_FLAGS[@]}" --user-data-dir=/tmp/chrome-x \
+ --remote-debugging-port=9223 about:blank >>"${HOME}/chrome-x.log" 2>&1 &
+
+for port in 9222 9223; do
+ for i in $(seq 1 30); do
+ curl -s "http://127.0.0.1:$port/json/version" >/dev/null 2>&1 && break
+ sleep 1
+ done
+ echo "[launch] chrome :$port ready" | tee -a "$LOG"
+done
+
+# 5. Run the automation
+set -a
+. "$AUTOMATION_DIR/.env"
+set +a
+cd "$AUTOMATION_DIR"
+node vm-automation.js "$SPACE_URL" 2>&1 | tee -a "$LOG"
+
+echo "=== launch DONE; server + chromes stay running ===" | tee -a "$LOG"
+echo
+echo "Now accept the speaker request on your phone (as the Space host)."
+echo "Then run: cd $AUTOMATION_DIR && node unmute-only.js"
+echo "Then: $HOME/say.sh \"test message\""
diff --git a/x-spaces/vm/setup.sh b/x-spaces/vm/setup.sh
new file mode 100644
index 000000000..eab3ca6f8
--- /dev/null
+++ b/x-spaces/vm/setup.sh
@@ -0,0 +1,132 @@
+#!/usr/bin/env bash
+# x-spaces VM bootstrap — fresh Ubuntu 22.04 LTS → ready to launch.
+# Idempotent: safe to re-run.
+#
+# Usage (run as root on the VM):
+# curl -fsSL https://raw.githubusercontent.com/nirholas/three.ws/main/x-spaces/vm/setup.sh | sudo bash
+#
+# Or manually:
+# git clone https://github.com/nirholas/three.ws.git /opt/three.ws
+# sudo /opt/three.ws/x-spaces/vm/setup.sh
+
+set -euo pipefail
+exec > >(tee -a /var/log/x-spaces-setup.log) 2>&1
+
+REPO_URL="https://github.com/nirholas/three.ws.git"
+REPO_DIR="/opt/three.ws"
+AGENT_HOME="/home/agent"
+SERVER_DIR="$AGENT_HOME/ai-agents-x-space"
+
+echo "=== x-spaces setup starting at $(date) ==="
+export DEBIAN_FRONTEND=noninteractive
+
+apt-get update
+apt-get install -y --no-install-recommends \
+ curl wget git ca-certificates gnupg python3 \
+ xvfb xdotool x11-utils \
+ pulseaudio pulseaudio-utils alsa-utils \
+ libnss3 libxss1 libgbm1 libasound2t64 \
+ libatk1.0-0t64 libatk-bridge2.0-0t64 libcups2t64 libatspi2.0-0t64 \
+ libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libxkbcommon0 \
+ libpango-1.0-0 libpangocairo-1.0-0 libgtk-3-0t64 libdrm2 libdbus-1-3 \
+ fonts-liberation ffmpeg sudo
+
+# Google Chrome
+if ! command -v google-chrome >/dev/null; then
+ wget -q -O /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
+ apt-get install -y /tmp/chrome.deb
+ rm /tmp/chrome.deb
+fi
+
+# Node 20
+if ! command -v node >/dev/null || [ "$(node -v | cut -d. -f1)" != "v20" ]; then
+ curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
+ apt-get install -y nodejs
+fi
+
+# Non-root agent user
+if ! id -u agent >/dev/null 2>&1; then
+ useradd -m -s /bin/bash agent
+ usermod -aG sudo,audio agent
+ echo "agent ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/agent
+fi
+
+# Clone or update repo
+if [ ! -d "$REPO_DIR" ]; then
+ git clone "$REPO_URL" "$REPO_DIR"
+else
+ git -C "$REPO_DIR" pull --ff-only || true
+fi
+chown -R agent:agent "$REPO_DIR"
+
+# PulseAudio: two virtual cables (per-process routing via PULSE_SINK/PULSE_SOURCE)
+sudo -u agent mkdir -p "$AGENT_HOME/.config/pulse"
+sudo -u agent tee "$AGENT_HOME/.config/pulse/default.pa" >/dev/null <<'PA'
+.include /etc/pulse/default.pa
+
+# Cable A: agent_speakers -> x_mic (this is what the agent broadcasts)
+load-module module-null-sink sink_name=agent_speakers sink_properties=device.description=AgentSpeakers
+# Cable B: x_speakers -> agent_mic (this is what the agent hears from the Space)
+load-module module-null-sink sink_name=x_speakers sink_properties=device.description=XSpeakers
+
+# Expose each sink's monitor as a usable virtual mic
+load-module module-remap-source source_name=x_mic master=agent_speakers.monitor source_properties=device.description=XMicInput
+load-module module-remap-source source_name=agent_mic master=x_speakers.monitor source_properties=device.description=AgentMicInput
+PA
+
+# Server: copy bundled code into agent's home
+sudo -u agent mkdir -p "$SERVER_DIR/public"
+sudo -u agent cp -r "$REPO_DIR/x-spaces/server/." "$SERVER_DIR/"
+sudo -u agent bash -c "cd '$SERVER_DIR' && npm install --no-audit --no-fund"
+
+# Automation directory + puppeteer-core
+sudo -u agent mkdir -p "$AGENT_HOME/automation"
+sudo -u agent cp "$REPO_DIR"/x-spaces/automation/*.js "$AGENT_HOME/automation/"
+sudo -u agent cp "$REPO_DIR"/x-spaces/automation/*.py "$AGENT_HOME/automation/" 2>/dev/null || true
+sudo -u agent bash -c "cd '$AGENT_HOME/automation' && [ -f package.json ] || npm init -y >/dev/null; npm install --no-audit --no-fund puppeteer-core"
+
+# Helpers
+sudo -u agent cp "$REPO_DIR/x-spaces/scripts/say.sh" "$AGENT_HOME/say.sh"
+sudo chmod +x "$AGENT_HOME/say.sh"
+sudo -u agent cp "$REPO_DIR/x-spaces/vm/launch.sh" "$AGENT_HOME/launch.sh"
+sudo chmod +x "$AGENT_HOME/launch.sh"
+
+# systemd service for the Node server (auto-restart)
+cp "$REPO_DIR/x-spaces/vm/swarm-server.service" /etc/systemd/system/swarm-server.service
+systemctl daemon-reload
+
+cat <<MSG
+
+=== x-spaces VM setup complete at $(date) ===
+
+Next steps:
+ 1. Drop your OpenAI key into the server's .env:
+ sudo -u agent tee $SERVER_DIR/.env <<EOF
+OPENAI_API_KEY=sk-...
+PORT=3000
+EOF
+ sudo chmod 600 $SERVER_DIR/.env
+
+ 2. Drop your X cookies (for the agent's X account) into the automation .env:
+ sudo -u agent tee $AGENT_HOME/automation/.env <<EOF
+X_AUTH_TOKEN=...
+X_CT0=...
+EOF
+ sudo chmod 600 $AGENT_HOME/automation/.env
+
+ 3. Start the systemd-managed server:
+ sudo systemctl enable --now swarm-server.service
+
+ 4. Launch Xvfb + PulseAudio + Chrome + automation for a given Space:
+ sudo -u agent $AGENT_HOME/launch.sh https://x.com/i/spaces/<SPACE_ID>
+
+ 5. Accept the speaker request on your phone as the host.
+
+ 6. Click unmute:
+ sudo -u agent bash -c "cd $AGENT_HOME/automation && node unmute-only.js"
+
+ 7. Test audio:
+ sudo -u agent $AGENT_HOME/say.sh "hello from x-spaces"
+
+See x-spaces/README.md for the full walkthrough.
+MSG
diff --git a/x-spaces/vm/swarm-server.service b/x-spaces/vm/swarm-server.service
new file mode 100644
index 000000000..d95b8b4cc
--- /dev/null
+++ b/x-spaces/vm/swarm-server.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=AI Agents X Space (three.ws) Realtime server
+After=network.target
+
+[Service]
+Type=simple
+User=agent
+WorkingDirectory=/home/agent/ai-agents-x-space
+ExecStart=/usr/bin/node /home/agent/ai-agents-x-space/index.js
+Restart=on-failure
+StandardOutput=append:/home/agent/server.log
+StandardError=append:/home/agent/server.log
+
+[Install]
+WantedBy=multi-user.target