Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310// LSP bridge: spawns a language server via `docker exec` and pipes stdio to a// WebSocket, reframing LSP `Content-Length` stdio into per-message WS frames.// One server per WS; kill on disconnect so clients can hold many without leaks.
import net from 'net';import http from 'http';import { WebSocket } from 'ws';import { log } from './logger';
const DOCKER_SOCKET = '/var/run/docker.sock';const LSP_MAX_MESSAGE_BYTES = 256 * 1024;
// Registry of supported language servers. Commands run inside the workspace// container (which has node/python/go/rust base images depending on config).// `check` verifies the server is installed; `install` tries to auto-install it.interface LspServerSpec { id: string; cmd: string[]; check: string[]; install?: string[];}
// Pinned versions close the "ambient install at first use" supply-chain window.// Bump deliberately; CI should alert when these drift far from upstream.// Override per-deployment via env (e.g. LSP_TYPESCRIPT_VERSION=4.3.4).const LSP_VERSIONS = { typescriptLanguageServer: process.env.LSP_TYPESCRIPT_VERSION || '4.3.4', typescript: process.env.LSP_TYPESCRIPT_LANG_VERSION || '5.6.3', pyright: process.env.LSP_PYRIGHT_VERSION || '1.1.389', gopls: process.env.LSP_GOPLS_VERSION || 'v0.16.2',};
const SERVERS: Record<string, LspServerSpec> = { typescript: { id: 'typescript', cmd: ['typescript-language-server', '--stdio'], check: ['sh', '-c', 'command -v typescript-language-server >/dev/null'], install: ['npm', 'install', '-g', '--', `typescript-language-server@${LSP_VERSIONS.typescriptLanguageServer}`, `typescript@${LSP_VERSIONS.typescript}`, ], }, javascript: { id: 'javascript', cmd: ['typescript-language-server', '--stdio'], check: ['sh', '-c', 'command -v typescript-language-server >/dev/null'], install: ['npm', 'install', '-g', '--', `typescript-language-server@${LSP_VERSIONS.typescriptLanguageServer}`, `typescript@${LSP_VERSIONS.typescript}`, ], }, python: { id: 'python', cmd: ['pyright-langserver', '--stdio'], check: ['sh', '-c', 'command -v pyright-langserver >/dev/null'], // Prefer pip with a pinned version; fall back to npm with the same pin // via `sh -c` since we need an `||` shell operator here. install: ['sh', '-c', `pip install --no-cache-dir "pyright==${LSP_VERSIONS.pyright}" || npm install -g -- "pyright@${LSP_VERSIONS.pyright}"`, ], }, go: { id: 'go', cmd: ['gopls', 'serve'], check: ['sh', '-c', 'command -v gopls >/dev/null'], install: ['go', 'install', `golang.org/x/tools/gopls@${LSP_VERSIONS.gopls}`], }, rust: { id: 'rust', cmd: ['rust-analyzer'], check: ['sh', '-c', 'command -v rust-analyzer >/dev/null'], // rust-analyzer ships with the Rust toolchain; no runtime install. },};
function dockerRequest(method: string, path: string, body?: any): Promise<{ statusCode: number; data: any }> { return new Promise((resolve, reject) => { const req = http.request( { socketPath: DOCKER_SOCKET, path, method, headers: { 'Content-Type': 'application/json' } }, (res) => { const chunks: Buffer[] = []; res.on('data', (c) => chunks.push(c)); res.on('end', () => { const raw = Buffer.concat(chunks).toString(); let data: any; try { data = JSON.parse(raw); } catch { data = raw; } resolve({ statusCode: res.statusCode ?? 0, data }); }); }, ); req.on('error', reject); if (body) req.write(JSON.stringify(body)); req.end(); });}
function rawDockerUpgrade(method: string, path: string, body?: any): Promise<net.Socket> { return new Promise((resolve, reject) => { const req = http.request({ socketPath: DOCKER_SOCKET, path, method, headers: { 'Content-Type': 'application/json', Upgrade: 'tcp', Connection: 'Upgrade' }, }); req.on('upgrade', (_res, socket) => resolve(socket as net.Socket)); req.on('response', (res) => { const chunks: Buffer[] = []; res.on('data', (c) => chunks.push(c)); res.on('end', () => reject(new Error(`Expected upgrade; got ${res.statusCode}: ${Buffer.concat(chunks).toString()}`))); }); req.on('error', reject); if (body) req.write(JSON.stringify(body)); req.end(); });}
async function runOneShot(containerId: string, cmd: string[]): Promise<{ ok: boolean; stdout: string }> { const create = await dockerRequest('POST', `/containers/${containerId}/exec`, { AttachStdout: true, AttachStderr: true, Cmd: cmd, WorkingDir: '/workspace', }); if (create.statusCode !== 201) return { ok: false, stdout: '' }; const socket = await rawDockerUpgrade('POST', `/exec/${create.data.Id}/start`, { Detach: false, Tty: false }); const chunks: Buffer[] = []; await new Promise<void>((resolve) => { socket.on('data', (d: Buffer) => chunks.push(d)); socket.on('end', resolve); socket.on('close', resolve); socket.on('error', resolve); }); const inspect = await dockerRequest('GET', `/exec/${create.data.Id}/json`); const exitCode = inspect.data?.ExitCode; return { ok: exitCode === 0, stdout: Buffer.concat(chunks).toString() };}
async function ensureServerInstalled(containerId: string, spec: LspServerSpec): Promise<boolean> { const check = await runOneShot(containerId, spec.check); if (check.ok) return true; if (!spec.install) return false; log.info({ server: spec.id }, 'lsp: installing language server'); const install = await runOneShot(containerId, spec.install); if (!install.ok) { log.warn({ server: spec.id }, 'lsp: install failed'); return false; } const recheck = await runOneShot(containerId, spec.check); return recheck.ok;}
function frameLspMessage(payload: string): Buffer { const body = Buffer.from(payload, 'utf8'); const header = Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, 'ascii'); return Buffer.concat([header, body]);}
// Parse LSP stdio into discrete JSON-RPC payloads. Streams can deliver partial// headers/bodies so we buffer until a full message is available.class LspFrameDecoder { private buffer = Buffer.alloc(0); private contentLength = -1;
push(chunk: Buffer): string[] { this.buffer = Buffer.concat([this.buffer, chunk]); const messages: string[] = [];
while (true) { if (this.contentLength < 0) { // Locate end of headers. const headerEnd = this.buffer.indexOf('\r\n\r\n'); if (headerEnd < 0) break; const header = this.buffer.slice(0, headerEnd).toString('ascii'); const match = header.match(/Content-Length:\s*(\d+)/i); if (!match) { // Malformed header — drop up to the separator and keep trying. this.buffer = this.buffer.slice(headerEnd + 4); continue; } this.contentLength = parseInt(match[1], 10); this.buffer = this.buffer.slice(headerEnd + 4); } if (this.buffer.length < this.contentLength) break; const body = this.buffer.slice(0, this.contentLength).toString('utf8'); this.buffer = this.buffer.slice(this.contentLength); this.contentLength = -1; messages.push(body); } return messages; }}
export interface LspBridgeOptions { containerId: string; language: string; ws: WebSocket;}
// Allow only lowercase language identifiers we explicitly registered. Anything// else would be an arbitrary shell invocation — reject loudly.export async function createLspBridge(opts: LspBridgeOptions): Promise<void> { const { containerId, language, ws } = opts; const spec = SERVERS[language.toLowerCase()]; if (!spec) { ws.send(JSON.stringify({ type: 'error', message: `Unsupported language: ${language}` })); ws.close(1008, 'Unsupported language'); return; }
try { const installed = await ensureServerInstalled(containerId, spec); if (!installed) { ws.send(JSON.stringify({ type: 'error', message: `${spec.id} language server not available` })); ws.close(1011, 'Server not available'); return; }
// Create exec with attached stdin/stdout/stderr. No TTY — we need clean // binary framing for Content-Length headers. const execCreate = await dockerRequest('POST', `/containers/${containerId}/exec`, { AttachStdin: true, AttachStdout: true, AttachStderr: true, Tty: false, WorkingDir: '/workspace', Env: ['TERM=dumb'], Cmd: spec.cmd, }); if (execCreate.statusCode !== 201) { ws.send(JSON.stringify({ type: 'error', message: 'Failed to create LSP exec' })); ws.close(1011, 'Exec create failed'); return; }
const socket = await rawDockerUpgrade('POST', `/exec/${execCreate.data.Id}/start`, { Detach: false, Tty: false, });
const decoder = new LspFrameDecoder(); let closed = false;
const cleanup = () => { if (closed) return; closed = true; try { socket.destroy(); } catch { /* ignore */ } try { if (ws.readyState === WebSocket.OPEN) ws.close(1000, 'LSP session ended'); } catch { /* ignore */ } };
// Docker multiplexes stdout/stderr on non-TTY execs with an 8-byte header: // [stream(1), 0, 0, 0, size(4 BE)] then size bytes. // stderr is stream=2; drop those (they're server logs, not JSON-RPC). let demuxBuffer = Buffer.alloc(0); socket.on('data', (chunk: Buffer) => { demuxBuffer = Buffer.concat([demuxBuffer, chunk]); while (demuxBuffer.length >= 8) { const stream = demuxBuffer[0]; const size = demuxBuffer.readUInt32BE(4); if (demuxBuffer.length < 8 + size) break; const payload = demuxBuffer.slice(8, 8 + size); demuxBuffer = demuxBuffer.slice(8 + size); if (stream === 1) { const messages = decoder.push(payload); for (const msg of messages) { if (ws.readyState === WebSocket.OPEN) ws.send(msg); } } else if (stream === 2) { // Surface first stderr line at debug; most are noise. const text = payload.toString('utf8').trim(); if (text) log.debug({ lang: spec.id, text: text.slice(0, 200) }, 'lsp stderr'); } } });
socket.on('error', () => cleanup()); socket.on('end', () => cleanup()); socket.on('close', () => cleanup());
ws.on('message', (msg: Buffer | string) => { if (closed) return; const text = typeof msg === 'string' ? msg : msg.toString('utf8'); if (Buffer.byteLength(text) > LSP_MAX_MESSAGE_BYTES) { try { ws.send(JSON.stringify({ type: 'error', message: 'LSP message too large' })); } catch { /* ignore */ } try { ws.close(1009, 'Message too large'); } catch { /* ignore */ } cleanup(); return; } // Frame with Content-Length and write to the server's stdin. try { socket.write(frameLspMessage(text)); } catch { cleanup(); } });
ws.on('close', () => cleanup()); ws.on('error', () => cleanup());
ws.send(JSON.stringify({ jsonrpc: '2.0', method: '$/ready', params: { language: spec.id } })); } catch (err) { log.error({ err: (err as Error).message }, 'lsp bridge failed'); try { ws.send(JSON.stringify({ type: 'error', message: 'LSP bridge failed' })); } catch { /* ignore */ } try { ws.close(1011, 'Bridge error'); } catch { /* ignore */ } }}
export function lspSupportedLanguages(): string[] { return Object.keys(SERVERS);}