// Minimal JSON-RPC client for `codex app-server` (protocol of codex-cli 0.167): over stdio for a // local process, or over a WebSocket to the reviewer container, which holds no GitLab token. import { spawn, type ChildProcess } from 'node:child_process'; import readline from 'node:readline'; export type TokenUsage = { totalTokens: number; inputTokens: number; cachedInputTokens: number; outputTokens: number; reasoningOutputTokens: number; }; export type CommandRequest = { command: string; cwd: string | null; reason: string | null }; export type CommandDecision = { allow: boolean; why: string }; export type TurnResult = { finalText: string; usage: TokenUsage | null; commands: Array<{ command: string; status: string }>; refused: Array<{ command: string; why: string }>; }; type Pending = { resolve: (v: any) => void; reject: (e: Error) => void }; // A reviewer container: `codex app-server --listen ws://… --ws-auth capability-token`. export type ReviewerServer = { url: string; token: string }; export class CodexClient { private proc: ChildProcess | null = null; private ws: WebSocket | null = null; private outbox: string[] | null = null; // In a container the container is the sandbox: Codex's own (bubblewrap) cannot run there. private sandbox: 'read-only' | 'danger-full-access'; private nextId = 0; private pending = new Map(); private turnWaiters = new Map(); private turnState = new Map(); private completed = new Set(); private decide: (req: CommandRequest) => CommandDecision; private log: (line: string) => void; constructor(opts: { bin: string; codexHome: string; server?: ReviewerServer | null; decide: (req: CommandRequest) => CommandDecision; log?: (line: string) => void }) { this.decide = opts.decide; this.log = opts.log ?? (() => {}); this.sandbox = opts.server ? 'danger-full-access' : 'read-only'; if (opts.server) { // Node's WebSocket (undici) takes request headers; the token never goes into the URL. const ws = new WebSocket(opts.server.url, { headers: { Authorization: `Bearer ${opts.server.token}` } } as any); this.ws = ws; this.outbox = []; ws.onopen = () => { for (const line of this.outbox ?? []) ws.send(line); this.outbox = null; }; ws.onmessage = (e) => this.onLine(String(e.data)); ws.onclose = () => this.fail(new Error(`reviewer server closed the connection (${opts.server!.url})`)); return; } const proc = spawn(opts.bin, ['app-server'], { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, CODEX_HOME: opts.codexHome, RUST_LOG: 'error' }, }); this.proc = proc; proc.stderr!.on('data', () => {}); proc.on('exit', (code) => this.fail(new Error(`codex app-server exited (${code})`))); readline.createInterface({ input: proc.stdout! }).on('line', (line) => this.onLine(line)); } private fail(err: Error) { for (const p of [...this.pending.values(), ...this.turnWaiters.values()]) p.reject(err); this.pending.clear(); this.turnWaiters.clear(); } private send(msg: object) { const line = JSON.stringify(msg); if (this.proc) this.proc.stdin!.write(line + '\n'); else if (this.outbox) this.outbox.push(line); else this.ws!.send(line); } request(method: string, params: object): Promise { const id = ++this.nextId; return new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); this.send({ id, method, params }); }); } private onLine(line: string) { let msg: any; try { msg = JSON.parse(line); } catch { return; } if (msg.id !== undefined && !msg.method) { const p = this.pending.get(msg.id); if (!p) return; this.pending.delete(msg.id); if (msg.error) p.reject(new Error(msg.error.message ?? JSON.stringify(msg.error))); else p.resolve(msg.result); return; } if (msg.id !== undefined && msg.method) return this.onServerRequest(msg); this.onNotification(msg.method, msg.params ?? {}); } // Every approval request is answered by our host, never by a person or the model. private onServerRequest(msg: any) { const p = msg.params ?? {}; const state = p.turnId ? this.state(p.turnId) : null; if (msg.method === 'item/commandExecution/requestApproval') { const req = { command: p.command ?? '', cwd: p.cwd ?? null, reason: p.reason ?? null }; const d = this.decide(req); if (!d.allow) state?.refused.push({ command: req.command, why: d.why }); this.log(`${d.allow ? 'allowed' : 'refused'}: ${req.command} (${d.why})`); this.send({ id: msg.id, result: { decision: d.allow ? 'accept' : 'decline' } }); return; } if (msg.method === 'item/fileChange/requestApproval' || msg.method === 'item/permissions/requestApproval') { state?.refused.push({ command: msg.method, why: 'reviewer is read-only' }); this.send({ id: msg.id, result: { decision: 'decline' } }); return; } this.send({ id: msg.id, error: { code: -32601, message: `Labuh does not handle ${msg.method}` } }); } private state(turnId: string): TurnResult { let s = this.turnState.get(turnId); if (!s) { s = { finalText: '', usage: null, commands: [], refused: [] }; this.turnState.set(turnId, s); } return s; } private onNotification(method: string, params: any) { if (method === 'item/completed' && params.turnId) { const s = this.state(params.turnId); const item = params.item; if (item.type === 'agentMessage' && item.phase !== 'commentary') s.finalText = item.text; if (item.type === 'commandExecution') s.commands.push({ command: item.command, status: item.status }); } else if (method === 'thread/tokenUsage/updated' && params.turnId) { this.state(params.turnId).usage = params.tokenUsage.total; } else if (method === 'turn/completed') { const turnId = params.turn.id; const s = this.state(turnId); if (!s.finalText) { const last = [...(params.turn.items ?? [])].reverse().find((i: any) => i.type === 'agentMessage'); if (last) s.finalText = last.text; } this.completed.add(turnId); const w = this.turnWaiters.get(turnId); if (w) { this.turnWaiters.delete(turnId); w.resolve(s); } } } async initialize() { await this.request('initialize', { clientInfo: { name: 'labuh', title: 'Labuh', version: '0.1.2' }, capabilities: { experimentalApi: false, requestAttestation: false }, }); this.send({ method: 'initialized' }); } async startThread(opts: { cwd: string; developerInstructions: string; model: string | null }) { const res = await this.request('thread/start', { cwd: opts.cwd, model: opts.model, sandbox: this.sandbox, approvalPolicy: 'untrusted', developerInstructions: opts.developerInstructions, ephemeral: false, }); return { threadId: res.thread.id as string, model: res.model as string, path: (res.thread.path ?? null) as string | null }; } // Reopens a stored thread after a restart, with the same lock and fresh instructions. async resumeThread(opts: { threadId: string; cwd: string; developerInstructions: string; model: string | null }) { const res = await this.request('thread/resume', { threadId: opts.threadId, cwd: opts.cwd, model: opts.model, sandbox: this.sandbox, approvalPolicy: 'untrusted', developerInstructions: opts.developerInstructions, excludeTurns: true, }); return { threadId: res.thread.id as string, model: res.model as string, path: (res.thread.path ?? null) as string | null }; } async runTurn(threadId: string, text: string, outputSchema: object | null, effort: string | null = null): Promise { const res = await this.request('turn/start', { threadId, input: [{ type: 'text', text, text_elements: [] }], outputSchema, effort, }); const turnId = res.turn.id as string; return new Promise((resolve, reject) => { // The turn may already have completed before turn/start was answered. if (this.completed.has(turnId)) resolve(this.state(turnId)); else this.turnWaiters.set(turnId, { resolve, reject }); }); } close() { if (this.proc) this.proc.kill(); else this.ws!.close(); } }