diff --git a/apps/server/src/codexAppServerManager.ts b/apps/server/src/codexAppServerManager.ts index fac4f2de8b..17db3ff181 100644 --- a/apps/server/src/codexAppServerManager.ts +++ b/apps/server/src/codexAppServerManager.ts @@ -1,7 +1,5 @@ -import { type ChildProcessWithoutNullStreams } from "node:child_process"; import { randomUUID } from "node:crypto"; import { EventEmitter } from "node:events"; -import readline from "node:readline"; import { ApprovalRequestId, @@ -18,7 +16,9 @@ import { type ProviderSessionStartInput, type ProviderTurnStartResult, } from "@t3tools/contracts"; -import { killProcessTree, spawnPipedProcess } from "./processRunner"; +import { Effect, Exit, ServiceMap, Scope, Stream } from "effect"; +import type { ChildProcessSpawner } from "effect/unstable/process"; +import { makeRuntimeCommand, spawnManagedCommand } from "./processRunner"; type PendingRequestKey = string; @@ -41,8 +41,8 @@ interface PendingApprovalRequest { interface CodexSessionContext { session: ProviderSession; - child: ChildProcessWithoutNullStreams; - output: readline.Interface; + child: ChildProcessSpawner.ChildProcessHandle; + scope: Scope.Closeable; pending: Map; pendingApprovals: Map; nextRequestId: number; @@ -158,6 +158,18 @@ export interface CodexAppServerManagerEvents { export class CodexAppServerManager extends EventEmitter { private readonly sessions = new Map(); + private readonly services: ServiceMap.ServiceMap | undefined; + + constructor(services?: ServiceMap.ServiceMap) { + super(); + this.services = services; + } + + private runPromise(effect: Effect.Effect): Promise { + return this.services + ? Effect.runPromiseWith(this.services as ServiceMap.ServiceMap)(effect) + : Effect.runPromise(effect as Effect.Effect); + } async startSession(input: ProviderSessionStartInput): Promise { const sessionId = ProviderSessionId.makeUnsafe(randomUUID()); @@ -179,19 +191,23 @@ export class CodexAppServerManager extends EventEmitter undefined); this.updateSession(context, { status: "closed", @@ -515,47 +526,76 @@ export class CodexAppServerManager extends EventEmitter { - this.handleStdoutLine(context, line); - }); + private async attachProcessListeners(context: CodexSessionContext): Promise { + await this.runPromise( + Effect.gen( + function* (this: CodexAppServerManager) { + yield* Effect.forkScoped( + Stream.runForEach( + Stream.splitLines(Stream.decodeText(context.child.stdout)), + (line) => + Effect.sync(() => { + this.handleStdoutLine(context, line); + }), + ), + ); - context.child.stderr.on("data", (chunk: Buffer) => { - const raw = chunk.toString(); - const lines = raw.split(/\r?\n/g); - for (const rawLine of lines) { - const classified = classifyCodexStderrLine(rawLine); - if (!classified) { - continue; - } + yield* Effect.forkScoped( + Stream.runForEach(Stream.decodeText(context.child.stderr), (raw) => + Effect.sync(() => { + const lines = raw.split(/\r?\n/g); + for (const rawLine of lines) { + const classified = classifyCodexStderrLine(rawLine); + if (!classified) { + continue; + } - this.emitErrorEvent(context, "process/stderr", classified.message); - } - }); + this.emitErrorEvent(context, "process/stderr", classified.message); + } + }), + ), + ); - context.child.on("error", (error) => { - const message = error.message || "codex app-server process errored."; - this.updateSession(context, { - status: "error", - lastError: message, - }); - this.emitErrorEvent(context, "process/error", message); - }); + yield* Effect.forkScoped( + Effect.matchCauseEffect(context.child.exitCode, { + onFailure: (cause) => + Effect.sync(() => { + if (context.stopping) { + return; + } - context.child.on("exit", (code, signal) => { - if (context.stopping) { - return; - } + const message = + cause instanceof Error + ? cause.message + : "codex app-server process errored."; + this.updateSession(context, { + status: "error", + activeTurnId: undefined, + lastError: message, + }); + this.emitErrorEvent(context, "process/error", message); + this.sessions.delete(context.session.sessionId); + }), + onSuccess: (code) => + Effect.sync(() => { + if (context.stopping) { + return; + } - const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`; - this.updateSession(context, { - status: "closed", - activeTurnId: undefined, - lastError: code === 0 ? context.session.lastError : message, - }); - this.emitLifecycleEvent(context, "session/exited", message); - this.sessions.delete(context.session.sessionId); - }); + const message = `codex app-server exited (code=${code}).`; + this.updateSession(context, { + status: "closed", + activeTurnId: undefined, + lastError: code === 0 ? context.session.lastError : message, + }); + this.emitLifecycleEvent(context, "session/exited", message); + this.sessions.delete(context.session.sessionId); + }), + }), + ); + }.bind(this), + ).pipe(Scope.provide(context.scope)), + ); } private handleStdoutLine(context: CodexSessionContext, line: string): void { @@ -711,19 +751,31 @@ export class CodexAppServerManager extends EventEmitter { + this.emitErrorEvent( + context, + "protocol/writeError", + error instanceof Error ? error.message : String(error), + ); }); return; } - this.writeMessage(context, { + void this.writeMessage(context, { id: request.id, error: { code: -32601, message: `Unsupported server request: ${request.method}`, }, + }).catch((error) => { + this.emitErrorEvent( + context, + "protocol/writeError", + error instanceof Error ? error.message : String(error), + ); }); } @@ -766,23 +818,30 @@ export class CodexAppServerManager extends EventEmitter { + clearTimeout(timeout); + context.pending.delete(String(id)); + reject(error instanceof Error ? error : new Error(String(error))); }); }); return result as TResponse; } - private writeMessage(context: CodexSessionContext, message: unknown): void { + private async writeMessage(context: CodexSessionContext, message: unknown): Promise { const encoded = JSON.stringify(message); - if (!context.child.stdin.writable) { + if (context.stopping) { throw new Error("Cannot write to codex app-server stdin."); } - - context.child.stdin.write(`${encoded}\n`); + await this.runPromise( + Stream.run(context.child.stdin)(Stream.make(new TextEncoder().encode(`${encoded}\n`))).pipe( + Scope.provide(context.scope), + ), + ); } private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void { diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index b522e8c6e6..63eac85805 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -7,6 +7,8 @@ import { } from "node:child_process"; import type { ServerRuntimeEnvironment } from "@t3tools/contracts"; +import { Effect, Exit, Scope } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { detectServerRuntimeEnvironment } from "./runtimeEnvironment"; @@ -17,11 +19,20 @@ interface ProcessSpawnBaseOptions { shell?: boolean | undefined; } +interface RuntimeShellOptions { + runtimeEnvironment?: ServerRuntimeEnvironment | undefined; + shell?: boolean | string | undefined; +} + export interface ProcessSpawnOptions extends ProcessSpawnBaseOptions { stdio?: StdioOptions | undefined; detached?: boolean | undefined; } +export interface RuntimeCommandOptions extends ChildProcess.CommandOptions { + runtimeEnvironment?: ServerRuntimeEnvironment | undefined; +} + export interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions { stdio?: StdioOptions | undefined; detached?: boolean | undefined; @@ -61,7 +72,7 @@ function resolveRuntimeEnvironment( return runtimeEnvironment ?? detectServerRuntimeEnvironment(); } -function shouldUseShell(options: ProcessSpawnBaseOptions): boolean { +function shouldUseShell(options: RuntimeShellOptions): boolean | string { if (options.shell !== undefined) { return options.shell; } @@ -79,6 +90,43 @@ function toSpawnOptions(options: ProcessSpawnOptions) { }; } +export function toRuntimeCommandOptions( + options: RuntimeCommandOptions = {}, +): ChildProcess.CommandOptions { + return { + ...options, + shell: options.shell ?? shouldUseShell(options), + }; +} + +export function makeRuntimeCommand( + command: string, + args: ReadonlyArray, + options: RuntimeCommandOptions = {}, +): ChildProcess.StandardCommand { + return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options)); +} + +export interface ManagedChildProcess { + readonly scope: Scope.Closeable; + readonly handle: ChildProcessSpawner.ChildProcessHandle; +} + +export const spawnManagedCommand = (command: ChildProcess.Command) => + Effect.gen(function* () { + const scope = yield* Scope.make("sequential"); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn(command).pipe( + Scope.provide(scope), + Effect.tapError(() => Scope.close(scope, Exit.void)), + ); + + return { + scope, + handle, + } satisfies ManagedChildProcess; + }); + export function spawnProcess( command: string, args: readonly string[], diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 8bec738893..23f46fa515 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -433,6 +433,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) => const fileSystem = yield* FileSystem.FileSystem; const serverConfig = yield* Effect.service(ServerConfig); const directory = yield* ProviderSessionDirectory; + const services = yield* Effect.services(); const nativeEventLogger = options?.nativeEventLogger ?? (options?.nativeEventLogPath !== undefined @@ -449,7 +450,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) => if (options?.makeManager) { return options.makeManager(); } - return new CodexAppServerManager(); + return new CodexAppServerManager(services); }), (manager) => Effect.sync(() => { @@ -587,7 +588,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) => const runtimeEventQueue = yield* Queue.unbounded(); yield* Effect.acquireRelease( - Effect.gen(function* () { + Effect.sync(() => { const writeNativeEvent = (event: ProviderEvent) => Effect.gen(function* () { if (!nativeEventLogger) { @@ -604,7 +605,6 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) => yield* nativeEventLogger.write(event, orchestrationThreadId); }); - const services = yield* Effect.services(); const listener = (event: ProviderEvent) => Effect.gen(function* () { yield* writeNativeEvent(event);