import { WebSocketServer } from "ws"; import { randomUUID } from "node:crypto"; import { execSync } from "node:child_process"; import { readdirSync, readFileSync, statSync } from "node:fs"; import { createServer } from "node:http"; import { extname, join, normalize } from "node:path"; import { createOpencodeBackend } from "./backends/opencode.mjs"; import { createPiBackend } from "./backends/pi.mjs"; import { loadChatTokens, resolveHandle, userForChatToken } from "./auth.mjs"; const PORT = Number(process.env.PORT ?? 8000); const ROOM = process.env.ROOM ?? "shared"; const BACKEND = process.env.BACKEND ?? "pi"; const CHAT_TOKENS = process.env.CHAT_TOKENS ?? "data/chat/tokens.json"; const PI_SESSION_DIR = process.env.PI_SESSION_DIR ?? "data/pi/sessions"; const PI_SESSION_ID = process.env.PI_SESSION_ID ?? "pi-collab"; const WEB_DIR = process.env.WEB_DIR ?? "web"; const GATE_URL = (process.env.GATE_URL ?? "http://127.0.0.1:8443").replace(/\/$/, ""); const backend = BACKEND === "pi" ? createPiBackend(process.env) : createOpencodeBackend(process.env); // Which commit is running — shown by the web client so the deployed version is // identifiable at a glance. Captured at startup. function gitCommit() { try { return execSync("git rev-parse --short HEAD", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { return "unknown"; } } const VERSION = gitCommit(); // ---- static web client ------------------------------------------------------ // The bridge also serves the web chat client (web/). The WebSocket upgrade and // the static files share the same port, so opening http://localhost:8000 just works. const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".mjs": "text/javascript", ".css": "text/css", ".json": "application/json", ".map": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", }; const webRoot = normalize(join(process.cwd(), WEB_DIR)); // Auth is reverse-proxied through the bridge so the web client is same-origin // with its session cookie. The OAuth callback (sidecar PROXY_URL) points at the // bridge, which relays it — and every auth route's Set-Cookie/Location — to the // gate. The browser never talks cross-origin, which is what SameSite/Lax cookies // require. const AUTH_PATHS = new Set(["/oauth/login", "/oauth/callback", "/oauth/logout", "/me", "/chat/token"]); async function proxyToGate(req, res) { let resp; try { resp = await fetch(GATE_URL + req.url, { method: req.method, headers: req.headers.cookie ? { cookie: req.headers.cookie } : {}, redirect: "manual", signal: AbortSignal.timeout(30_000), }); } catch (err) { res.writeHead(502, { "Content-Type": "text/plain" }); res.end("gate unreachable: " + err.message); return; } const headers = { "Content-Type": resp.headers.get("content-type") || "text/plain" }; const loc = resp.headers.get("location"); if (loc) headers["Location"] = loc; const setCookies = resp.headers.getSetCookie ? resp.headers.getSetCookie() : []; if (setCookies.length) headers["Set-Cookie"] = setCookies; const body = Buffer.from(await resp.arrayBuffer()); res.writeHead(resp.status, headers); res.end(body); } const httpServer = createServer(async (req, res) => { let urlPath; try { urlPath = decodeURIComponent(new URL(req.url, `http://${req.headers.host}`).pathname); } catch { res.writeHead(400); res.end("bad request"); return; } if (AUTH_PATHS.has(urlPath)) { await proxyToGate(req, res); return; } if (urlPath === "/version") { res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify({ commit: VERSION })); return; } if (urlPath === "/auth/shell") { res.writeHead(302, { Location: GATE_URL + "/auth/shell" }); res.end(); return; } const filePath = urlPath === "/" ? "index.html" : urlPath.slice(1); const full = normalize(join(webRoot, filePath)); if (!full.startsWith(webRoot) || req.method !== "GET" && req.method !== "HEAD") { res.writeHead(403); res.end("forbidden"); return; } try { const data = readFileSync(full); res.writeHead(200, { "Content-Type": MIME[extname(full)] ?? "application/octet-stream" }); res.end(req.method === "HEAD" ? undefined : data); } catch { res.writeHead(404); res.end("not found"); } }); // Registered before the WebSocketServer: ws forwards server 'error' events onto // itself, so a listener here must exist first or an EADDRINUSE becomes an // unhandled throw instead of the friendly message below. httpServer.on("error", (err) => { if (err.code === "EADDRINUSE") { console.error(`\n✗ Port ${PORT} is already in use.`); console.error(" Another pi-collab bridge is probably already running."); console.error(` Stop it, or start on another port: PORT=${PORT + 1} node server.mjs\n`); process.exit(1); } throw err; }); const wss = new WebSocketServer({ server: httpServer }); const clients = new Map(); const history = []; const toolState = new Map(); const agentTs = new Map(); let thinkingActive = false; function users() { return [...clients.values()].map((c) => displayOf(c)); } function displayOf(c) { return c.nick || c.handle || c.did || "anon"; } function send(ws, obj) { if (ws.readyState === 1) ws.send(JSON.stringify(obj)); } function broadcast(obj) { const data = JSON.stringify(obj); for (const ws of clients.keys()) { if (ws.readyState === 1) ws.send(data); } } function pushHistory(entry) { history.push(entry); if (history.length > 500) history.shift(); } // ---- history persistence ---------------------------------------------------- // The conversation lives in the pi session JSONL (inside the repo, committed // to git). On restart the in-memory history is rebuilt from the newest session // file so rejoining clients see the full conversation. function sessionFiles() { try { return readdirSync(PI_SESSION_DIR) .filter((n) => n.endsWith(".jsonl")) .sort((a, b) => statSync(join(PI_SESSION_DIR, a)).mtimeMs - statSync(join(PI_SESSION_DIR, b)).mtimeMs); } catch { return []; } } function parseDid(text) { const m = /^\[(did:[^\]]+)\]\s*(.*)$/.exec(text ?? ""); return m ? { did: m[1], rest: m[2] } : { did: null, rest: text ?? "" }; } function loadHistoryFromSessions() { const files = sessionFiles(); const matching = files.filter((n) => n.endsWith(`_${PI_SESSION_ID}.jsonl`)); const pool = matching.length ? matching : files; if (!pool.length) return; let lines; try { lines = readFileSync(join(PI_SESSION_DIR, pool[pool.length - 1]), "utf8").split("\n"); } catch { return; } for (const line of lines) { let entry; try { entry = JSON.parse(line); } catch { continue; } if (entry.type !== "message") continue; const msg = entry.message ?? {}; const ts = new Date(entry.timestamp ?? msg.timestamp).getTime() || Date.now(); const text = (msg.content ?? []) .filter((c) => c.type === "text") .map((c) => c.text ?? "") .join("\n"); if (msg.role === "user") { const { did, rest } = parseDid(text); pushHistory({ id: "hist_" + randomUUID().replace(/-/g, ""), did, user: did ?? "user", kind: "user", text: rest, ts }); } else if (msg.role === "assistant") { pushHistory({ id: "hist_" + randomUUID().replace(/-/g, ""), user: "agent", kind: "agent", text, ts, final: true }); } } console.log(`[bridge] loaded ${history.length} history entries from ${pool[pool.length - 1]}`); } function emitAgent(id, text, { final = false } = {}) { if (!agentTs.has(id)) agentTs.set(id, Date.now()); broadcast({ type: "message", id, user: "agent", kind: "agent", text, ts: agentTs.get(id), final }); } function relayTool({ id, tool, detail, status }) { const ts = Date.now(); const prev = toolState.get(id); if (!prev) { toolState.set(id, { tool, detail, status }); broadcast({ type: "tool", id, tool, detail, status, ts }); return; } if (detail && !prev.detail) { prev.detail = detail; broadcast({ type: "tool", id, tool, detail, status, ts }); } if (prev.status !== status) { prev.status = status; if (detail) prev.detail = detail; broadcast({ type: "tool", id, tool: prev.tool, detail: prev.detail, status, ts }); if (status === "completed" || status === "error") { pushHistory({ kind: "tool", tool: prev.tool, detail: prev.detail, status, ts }); } } } backend.onEvent((ev) => { switch (ev.type) { case "text": if (process.env.DEBUG) console.error(`[BRIDGE text] ${ev.messageID} ${JSON.stringify(ev.text).slice(0, 60)}`); emitAgent(ev.messageID, ev.text); break; case "final": { emitAgent(ev.messageID, ev.text, { final: true }); pushHistory({ id: ev.messageID, user: "agent", kind: "agent", text: ev.text, ts: Date.now() }); agentTs.delete(ev.messageID); break; } case "error": { const id = "msg_" + randomUUID().replace(/-/g, ""); const entry = { id, user: "agent", kind: "agent", text: `**error:** ${ev.text}`, ts: Date.now(), final: true }; pushHistory(entry); broadcast({ type: "message", ...entry }); break; } case "thinking": if (ev.active !== thinkingActive) { thinkingActive = ev.active; broadcast({ type: "thinking", active: thinkingActive }); } break; case "tool": relayTool(ev); break; case "idle": break; } }); function resetBridgeState() { history.length = 0; toolState.clear(); agentTs.clear(); thinkingActive = false; } async function handleCommand(client, id, text) { const user = displayOf(client); const parts = text.slice(1).trim().split(/\s+/); const name = (parts[0] ?? "").toLowerCase(); const arg = text.slice(1).trim().slice(name.length).trim(); switch (name) { case "help": return [ "**Commands:**", "- `/new` — start a fresh shared session", "- `/compact` — compact the session context", "- `/model ` — switch model (e.g. `deepseek-v4-flash`, `kimi-k2.7-code`)", "- `/users` — who's online", "- `/whoami` — your DID and handle", "- `/help` — this list", ].join("\n"); case "users": return `Online: ${users().join(", ") || "nobody"}.`; case "whoami": return `You are \`${client.did}\`${client.handle && client.handle !== client.did ? ` (\`${client.handle}\`)` : ""}${client.nick ? `, showing as \`${client.nick}\`` : ""}.`; case "new": { await backend.newSession(); resetBridgeState(); return `${user} started a new session — fresh start.`; } case "compact": return await backend.compact(); case "model": { if (!arg) return `Usage: \`/model \`. Current: \`${backend.getModel()}\``; return await backend.setModel(arg); } default: // Not a bridge command — forward to the agent so extension // commands, prompt templates, and skills can handle it. backend.prompt({ messageID: id, did: client.did, user, text }); return null; } } function pushCommandResult(client, id, text) { handleCommand(client, id, text) .then((reply) => { if (reply == null) return; const id = "msg_" + randomUUID().replace(/-/g, ""); const entry = { id, user: "agent", kind: "agent", text: reply, ts: Date.now(), final: true }; pushHistory(entry); broadcast({ type: "message", ...entry }); }) .catch((err) => { const id = "msg_" + randomUUID().replace(/-/g, ""); const entry = { id, user: "agent", kind: "agent", text: `**error:** ${err.message}`, ts: Date.now(), final: true }; pushHistory(entry); broadcast({ type: "message", ...entry }); }); } wss.on("connection", (ws) => { ws.on("message", (raw) => { let msg; try { msg = JSON.parse(String(raw)); } catch { return; } if (msg.type === "join") { const token = String(msg.token ?? "").trim(); const did = userForChatToken(token, loadChatTokens(CHAT_TOKENS)); if (!did) { send(ws, { type: "error", text: "invalid or missing chat token" }); ws.close(4001, "invalid token"); return; } const nick = String(msg.nick ?? "").trim().slice(0, 24) || ""; resolveHandle(did).then((handle) => { const client = { did, handle, nick }; clients.set(ws, client); send(ws, { type: "joined", room: ROOM, did, handle, user: displayOf(client), messages: history, users: users() }); broadcast({ type: "presence", users: users() }); }); } else if (msg.type === "chat") { const client = clients.get(ws); if (!client) return; const text = String(msg.text ?? "").trim(); if (!text) return; const id = "msg_" + randomUUID().replace(/-/g, ""); const entry = { id, user: displayOf(client), did: client.did, kind: "user", text, ts: Date.now() }; pushHistory(entry); broadcast({ type: "message", ...entry }); if (text.startsWith("/")) { pushCommandResult(client, id, text); return; } backend.prompt({ messageID: id, did: client.did, user: displayOf(client), text }); } }); ws.on("close", () => { clients.delete(ws); broadcast({ type: "presence", users: users() }); }); }); try { await backend.connect(); } catch (err) { console.error(`\n✗ Backend ${backend.name} failed to start: ${err.message}`); console.error(" Check that it is installed and reachable, then retry.\n"); process.exit(1); } loadHistoryFromSessions(); httpServer.listen(PORT, "0.0.0.0"); console.log( `pi-collab bridge -> ws://localhost:${PORT} (room: ${ROOM}) | backend ${backend.name} | model ${backend.getModel()}`, ); console.log(` web client -> http://localhost:${PORT}/`);