UNPKG

@bitkyc08/opencodex

Version:

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code

158 lines (155 loc) • 9.26 kB
import { linkSshSpawnEnv } from "../link/ssh-runner"; import { MessageBudget } from "./budget"; import { RemoteCapacity, remoteError, REMOTE_LIMITS } from "./remote-contract"; import { LocalMessagingError } from "./types"; import { remoteForwardFailure } from "./remote-forward-failure"; export interface RemoteHelper { readonly pid: number; readonly exited: Promise<number>; readonly output: Promise<string>; readonly forwardReady: Promise<void>; readonly forwardFailed?: boolean; /** After cleanup: intrinsic I/O or pre-cleanup exit failure, excluding cleanup-induced exits. */ readonly setupFailure?: Error; close(): Promise<void>; } /** Narrow subprocess seam for offline lifecycle tests; production always uses owned Bun children. */ export interface RemoteHelperProcess { readonly pid: number; readonly exitCode: number | null; readonly exited: Promise<number>; readonly stdout: ReadableStream<Uint8Array>; readonly stderr: ReadableStream<Uint8Array>; readonly stdin: Pick<Bun.FileSink, "write" | "end">; } export interface RemoteHelperOptions { purpose?: "persistent" | "transient"; spawn?: (argv: readonly string[], env: NodeJS.ProcessEnv | undefined) => RemoteHelperProcess; signalGroup?: (pid: number, kind: NodeJS.Signals) => void; successCodes?: readonly number[]; } /** Spawn only invocation-owned process groups; bounded drains and cleanup are shared by helpers/tunnels. */ export function spawnRemoteHelper(argv: readonly string[], capacity: RemoteCapacity, signal?: AbortSignal, stdin?: string, env = linkSshSpawnEnv(), options: RemoteHelperOptions = {}): RemoteHelper { if (signal?.aborted) throw remoteError("cancelled", "Messaging helper was cancelled before spawn."); const release = capacity.reserveHelper(options.purpose ?? "persistent"); let ready!: () => void, notReady!: (reason: unknown) => void; const forwardReady = new Promise<void>((resolve, reject) => { ready = resolve; notReady = reject; }); void forwardReady.catch(() => {}); const forwardFailure = remoteForwardFailure(argv, ready); if (!forwardFailure.enabled) ready(); // Command-line options are first-value-wins; only owned forwards request bounded token inspection. const spawnArgv = forwardFailure.enabled ? [argv[0]!, "-o", "LogLevel=DEBUG1", ...argv.slice(1)] : [...argv]; let child: RemoteHelperProcess; try { child = options.spawn ? options.spawn(spawnArgv, env) : Bun.spawn(spawnArgv, { stdin: "pipe", stdout: "pipe", stderr: "pipe", detached: true, env }); } catch { release(); throw remoteError("ssh_unavailable", "The messaging SSH helper could not start."); } const readers = [child.stdout.getReader(), child.stderr.getReader()]; let closing: Promise<void> | undefined; let failure: Error | undefined; let interrupted = false; const cancelledPipes = [false, false]; const pipeEnds: (() => void)[] = []; const naturalPipes = readers.map(() => new Promise<void>(resolve => { pipeEnds.push(resolve); })); const physicallyClosed = Promise.all([child.exited, ...naturalPipes]); void physicallyClosed.then(() => release()).catch(() => {}); let stopOutput!: (reason: unknown) => void; const stopped = new Promise<never>((_, reject) => { stopOutput = reject; }); const signalGroup = (kind: NodeJS.Signals) => { if (child.exitCode !== null) return; try { if (options.signalGroup) options.signalGroup(child.pid, kind); else process.kill(-child.pid, kind); } catch { /* Exit racing owned cleanup is harmless. */ } }; const close = (): Promise<void> => closing ??= (async () => { signal?.removeEventListener("abort", abort); interrupted = child.exitCode === null; signalGroup("SIGTERM"); const force = setTimeout(() => signalGroup("SIGKILL"), 500); let timer: ReturnType<typeof setTimeout> | undefined; let cleanupFailure: unknown; try { await Promise.race([physicallyClosed, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(remoteError("cleanup_incomplete", "An owned messaging helper or its pipes did not settle within cleanup budget.")), REMOTE_LIMITS.shutdownMs); })]); } catch (error) { cleanupFailure = error; if (error instanceof Error && failure) error.cause = failure; throw error; // Incomplete cleanup remains visible even when an earlier failure triggered it. } finally { clearTimeout(force); clearTimeout(timer); // Escaped descendants retaining a pipe cannot hold shutdown open forever. for (const [index, reader] of readers.entries()) { cancelledPipes[index] = true; void reader.cancel().catch(() => {}); } stopOutput(cleanupFailure ?? failure ?? remoteError("ssh_incomplete", "Messaging helper output capture was stopped.")); notReady(cleanupFailure ?? failure ?? remoteError(child.exitCode !== null && child.exitCode !== 0 && forwardFailure.failed ? "forward_port_lost" : "ssh_failed", "Messaging SSH forward was not confirmed.")); // Cancellation cannot prove natural EOF; unresolved ownership keeps its helper capacity charged. } })(); const abort = () => { void close().catch(() => {}); }; signal?.addEventListener("abort", abort, { once: true }); if (signal?.aborted) abort(); const drain = async (index: number): Promise<string> => { const chunks: Uint8Array[] = [], reservations: (() => void)[] = []; let bytes = 0, discarding = false; try { for (;;) { const next = await readers[index]!.read(); if (next.done) { if (!cancelledPipes[index]) pipeEnds[index]!(); break; } if (index === 1) { forwardFailure.write(next.value); continue; } // No diagnostic bytes are retained or returned. if (discarding) continue; try { bytes += next.value.byteLength; if (bytes > 64 * 1024) throw remoteError("ssh_output_limit", "Messaging helper output exceeded its limit."); reservations.push(capacity.reserve("outputBytes", next.value.byteLength || 1)); chunks.push(next.value); } catch (error) { failure ??= error instanceof LocalMessagingError ? error : remoteError("ssh_incomplete", "Messaging helper output could not be captured safely."); discarding = true; chunks.length = 0; for (const free of reservations.splice(0)) free(); abort(); // Continue discarding until natural EOF proves cleanup, rather than abandoning the reader. } } return index === 0 ? new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)) : ""; } catch { failure ??= remoteError("ssh_incomplete", "Messaging helper output could not be captured safely."); abort(); return ""; } finally { for (const free of reservations) free(); readers[index]!.releaseLock(); } }; const input = (async () => { if (stdin !== undefined) await child.stdin.write(stdin); await child.stdin.end(); })().catch(() => { failure ??= remoteError("ssh_incomplete", "Messaging control input could not be written."); abort(); throw failure; }); const output = Promise.race([stopped, Promise.all([drain(0), drain(1), input]).then(([out]) => { if (failure) throw failure; return out; })]); void output.catch(() => {}); void output.then(async () => { const code = await child.exited; if (!forwardFailure.ready) notReady(remoteError(code !== 0 && forwardFailure.failed ? "forward_port_lost" : "ssh_failed", "Messaging SSH forward was not confirmed.")); }, notReady).catch(notReady); void child.exited.then(() => { signal?.removeEventListener("abort", abort); }).catch(() => {}); return { pid: child.pid, exited: child.exited, output, forwardReady, get forwardFailed() { return forwardFailure.failed; }, get setupFailure() { if (failure) return failure; if (!interrupted && child.exitCode !== null && (child.exitCode !== 0 || !forwardFailure.ready)) { return remoteError(child.exitCode !== 0 && forwardFailure.failed ? "forward_port_lost" : "ssh_failed", "Messaging SSH forward setup failed."); } }, close }; } /** One bounded batch covers helper startup, stdin, exit and output; errors never include raw output. */ export async function runRemoteHelper(argv: readonly string[], budget: MessageBudget, capacity: RemoteCapacity, stdin?: string, env?: NodeJS.ProcessEnv, options: RemoteHelperOptions = {}): Promise<string> { budget.throwIfEnded(); const helper = spawnRemoteHelper(argv, capacity, budget.signal, stdin, env ?? linkSshSpawnEnv(), { ...options, purpose: "transient" }); let cancelled!: () => void; const cancellation = new Promise<never>((_, reject) => { cancelled = () => reject(budget.signal.reason); budget.signal.addEventListener("abort", cancelled, { once: true }); if (budget.signal.aborted) cancelled(); }); try { const [code, output] = await Promise.race([Promise.all([helper.exited, helper.output]), cancellation]); budget.throwIfEnded(); if (!(options.successCodes ?? [0]).includes(code)) throw remoteError(code === 127 ? "remote_ocx_missing" : "ssh_failed", "Messaging SSH command did not complete successfully."); return output; } finally { budget.signal.removeEventListener("abort", cancelled); await helper.close(); } }