TypeScript
fix(codex): say why the Codex app-server exited (#23938)
Mantas Kantautas2ce31853d654
diff --git a/packages/effect-codex-app-server/src/_internal/stdio.test.ts b/packages/effect-codex-app-server/src/_internal/stdio.test.tsindex 4bf8c1cbbff..cde2150ff66 100644--- a/packages/effect-codex-app-server/src/_internal/stdio.test.ts+++ b/packages/effect-codex-app-server/src/_internal/stdio.test.ts@@ -1,12 +1,67 @@import { assert, describe, it } from "@effect/vitest";import * as Effect from "effect/Effect";+import * as Deferred from "effect/Deferred";+import * as Fiber from "effect/Fiber";+import * as Queue from "effect/Queue";+import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";import * as PlatformError from "effect/PlatformError";import { ChildProcessSpawner } from "effect/process";import * as CodexError from "../errors.ts";-import { makeTerminationError } from "./stdio.ts";+import * as CodexProtocol from "../protocol.ts";+import {+ appendStderrTail,+ makeTerminationError,+ stderrExcerpt,+ makeInMemoryStdio,+ makeStderrTail,+ makeChildStdio,+} from "./stdio.ts";describe("Codex App Server child process termination", () => {+ it.effect("retains exit diagnostics when stderr stays open after stdout ends", () =>+ Effect.gen(function* () {+ const { stdio, input, output } = yield* makeInMemoryStdio();+ const captured = yield* Deferred.make<void>();+ const stderr = Stream.make(new TextEncoder().encode("Error: invalid config\n")).pipe(+ Stream.concat(Stream.fromEffect(Deferred.succeed(captured, undefined)).pipe(Stream.drain)),+ Stream.concat(Stream.never),+ );+ const tail = yield* makeStderrTail(stderr);+ const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({+ stdio: makeChildStdio({ stdout: stdio.stdin, stdin: stdio.stdout() }, tail.awaitDrained),+ terminationError: makeTerminationError(+ {+ pid: ChildProcessSpawner.ProcessId(55),+ exitCode: Deferred.await(exited),+ },+ tail.read,+ ),+ });+ const pending = yield* transport.request("thread/read", {}).pipe(+ Effect.match({+ onFailure: (error) => error,+ onSuccess: () => assert.fail("Expected the pending request to fail"),+ }),+ Effect.forkScoped,+ );+ yield* Queue.take(output);+ yield* Deferred.await(captured);+ yield* Queue.end(input);+ yield* TestClock.adjust("100 millis");+ yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(1));+ yield* TestClock.adjust("250 millis");+ const error = yield* Fiber.join(pending);+ assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);+ assert.equal(+ error.message,+ "Codex App Server process exited with code 1: Error: invalid config",+ );+ }),+ );+it.effect("retains the process identifier and exact exit-status cause", () =>Effect.gen(function* () {const rootCause = new Error("private process diagnostics");@@ -16,10 +71,13 @@ describe("Codex App Server child process termination", () => {method: "exitCode",cause: rootCause,});- const error = yield* makeTerminationError({- pid: ChildProcessSpawner.ProcessId(52),- exitCode: Effect.fail(cause),- });+ const error = yield* makeTerminationError(+ {+ pid: ChildProcessSpawner.ProcessId(52),+ exitCode: Effect.fail(cause),+ },+ Effect.succeed(""),+ );assert.instanceOf(error, CodexError.CodexAppServerTransportError);assert.equal(error.pid, 52);@@ -31,4 +89,112 @@ describe("Codex App Server child process termination", () => {assert.notInclude(error.message, rootCause.message);}),);++ it.effect("names the stderr error line when the process exits", () =>+ Effect.gen(function* () {+ const error = yield* makeTerminationError(+ {+ pid: ChildProcessSpawner.ProcessId(53),+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),+ },+ Effect.succeed("Error: Missing optional dependency @openai/codex-darwin-arm64.\n"),+ );++ assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);+ assert.equal(error.stderr, "Error: Missing optional dependency @openai/codex-darwin-arm64.");+ assert.equal(+ error.message,+ "Codex App Server process exited with code 1: Error: Missing optional dependency @openai/codex-darwin-arm64.",+ );+ }),+ );++ it.effect("keeps the bare exit message when stderr is empty", () =>+ Effect.gen(function* () {+ const error = yield* makeTerminationError(+ {+ pid: ChildProcessSpawner.ProcessId(54),+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),+ },+ Effect.succeed(" \n\n"),+ );++ assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);+ assert.isUndefined(error.stderr);+ assert.equal(error.message, "Codex App Server process exited with code 1");+ }),+ );+});++describe("Codex App Server stderr excerpt", () => {+ it.each([+ {+ name: "Node launcher missing its platform package",+ stderr: [+ "file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:107",+ " throw new Error(",+ " ^",+ "",+ "Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",+ " at findCodexExecutable (file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:107:9)",+ " at file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:112:20",+ "",+ "Node.js v26.8.2",+ "",+ ].join("\n"),+ excerpt:+ "Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",+ },+ {+ name: "Node error with a code",+ stderr:+ "node:internal/modules/esm/resolve:873\n throw new ERR_MODULE_NOT_FOUND(\n\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'x'\n at packageResolve (node:internal/modules/esm/resolve:873:9)\n",+ excerpt: "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'x'",+ },+ {+ name: "Rust CLI error",+ stderr: "error: unexpected argument 'app-server' found\n\nUsage: codex [OPTIONS]\n",+ excerpt: "error: unexpected argument 'app-server' found",+ },+ {+ name: "uppercase error label",+ stderr: "ERROR: Missing dependency\nUsage: codex [OPTIONS]\n",+ excerpt: "ERROR: Missing dependency",+ },+ {+ name: "unlabelled message",+ stderr: "WARNING: proceeding without PATH aliases\nMissing OpenAI API key.\n",+ excerpt: "Missing OpenAI API key.",+ },+ {+ name: "ANSI color, carriage returns and repeated whitespace",+ stderr: "\u001b[31m Error:\t config.toml is invalid \u001b[0m\r\n",+ excerpt: "Error: config.toml is invalid",+ },+ {+ name: "C1 terminal controls",+ stderr: "\u009b31mError: invalid config\u009b0m\nUsage: codex [OPTIONS]\n",+ excerpt: "Error: invalid config",+ },+ {+ name: "oversized line",+ stderr: `Error: ${"x".repeat(1_000)}`,+ excerpt: `Error: ${"x".repeat(504)}…`,+ },+ ])("$name", ({ stderr, excerpt }) => {+ assert.equal(stderrExcerpt(stderr), excerpt);+ assert.isAtMost(excerpt.length, 512);+ });++ it("returns nothing for blank stderr", () => {+ assert.isUndefined(stderrExcerpt("\n \t\r\n\u001b[0m\n"));+ });++ it("keeps only the newest stderr", () => {+ const tail = appendStderrTail("a".repeat(8_000), `${"b".repeat(400)}\nError: last`);++ assert.equal(tail.length, 8_192);+ assert.isTrue(tail.endsWith("Error: last"));+ assert.equal(stderrExcerpt(tail), "Error: last");+ });});diff --git a/packages/effect-codex-app-server/src/_internal/stdio.ts b/packages/effect-codex-app-server/src/_internal/stdio.tsindex e77f53e4b5c..a25ac0e6124 100644--- a/packages/effect-codex-app-server/src/_internal/stdio.ts+++ b/packages/effect-codex-app-server/src/_internal/stdio.ts@@ -1,6 +1,10 @@+import * as NodeUtil from "node:util";+import * as Cause from "effect/Cause";+import * as Fiber from "effect/Fiber";import * as Effect from "effect/Effect";import * as Queue from "effect/Queue";+import * as Ref from "effect/Ref";import * as Sink from "effect/Sink";import * as Stdio from "effect/Stdio";import * as Stream from "effect/Stream";@@ -10,10 +14,14 @@ import * as CodexError from "../errors.ts";const encoder = new TextEncoder();-export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>+export const makeChildStdio = (+ handle: Pick<ChildProcessSpawner.ChildProcessHandle, "stdin" | "stdout">,+ stderrDrained: Effect.Effect<void>,+) =>Stdio.make({args: Effect.succeed([]),- stdin: handle.stdout,+ // Finish stderr separately from the protocol's exit-status deadline.+ stdin: handle.stdout.pipe(Stream.onEnd(stderrDrained)),stdout: () =>Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>typeof chunk === "string" ? encoder.encode(chunk) : chunk,@@ -44,6 +52,47 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {};});+const STDERR_TAIL_MAX_CHARS = 8_192;+const STDERR_EXCERPT_MAX_CHARS = 512;+// `Error: …`, `TypeError: …`, `Error [ERR_MODULE_NOT_FOUND]: …`, `error: …`, `ERROR: …`, `fatal: …`+const ERROR_LINE_PATTERN = /^(?:[a-z]*error|fatal)(?: ?\[[^\]]+\])?:\s*\S/i;++export const appendStderrTail = (current: string, chunk: string): string => {+ const next = `${current}${chunk}`;+ return next.length <= STDERR_TAIL_MAX_CHARS ? next : next.slice(-STDERR_TAIL_MAX_CHARS);+};++// Node launchers print the actionable error between a source excerpt and stack frames.+export const stderrExcerpt = (tail: string): string | undefined => {+ const lines = NodeUtil.stripVTControlCharacters(tail)+ .split(/\r?\n/)+ .map((line) => line.trim().replace(/\s+/g, " "))+ .filter((line) => line.length > 0);+ const line = lines.findLast((candidate) => ERROR_LINE_PATTERN.test(candidate)) ?? lines.at(-1);+ if (line === undefined) {+ return undefined;+ }+ return line.length <= STDERR_EXCERPT_MAX_CHARS+ ? line+ : `${line.slice(0, STDERR_EXCERPT_MAX_CHARS - 1)}…`;+};++export const makeStderrTail = Effect.fn("makeStderrTail")(function* (+ stderr: ChildProcessSpawner.ChildProcessHandle["stderr"],+) {+ const tail = yield* Ref.make("");+ const drain = yield* stderr.pipe(+ Stream.decodeText(),+ Stream.runForEach((chunk) => Ref.update(tail, (current) => appendStderrTail(current, chunk))),+ Effect.ignore,+ Effect.forkScoped,+ );+ return {+ read: Ref.get(tail),+ awaitDrained: Fiber.join(drain).pipe(Effect.timeout("250 millis"), Effect.ignore),+ };+});+type ChildProcessTerminationHandle = Pick<ChildProcessSpawner.ChildProcessHandle,"exitCode" | "pid"@@ -51,13 +100,24 @@ type ChildProcessTerminationHandle = Pick<export const makeTerminationError = (handle: ChildProcessTerminationHandle,+ stderrTail: Effect.Effect<string>,): Effect.Effect<CodexError.CodexAppServerError> =>- Effect.match(handle.exitCode, {+ Effect.matchEffect(handle.exitCode, {onFailure: (cause) =>- new CodexError.CodexAppServerTransportError({- operation: "read-process-exit-status",- pid: handle.pid,- cause,+ Effect.succeed(+ new CodexError.CodexAppServerTransportError({+ operation: "read-process-exit-status",+ pid: handle.pid,+ cause,+ }),+ ),+ onSuccess: (code) =>+ Effect.map(stderrTail, (tail) => {+ const stderr = stderrExcerpt(tail);+ return new CodexError.CodexAppServerProcessExitedError({+ code,+ pid: handle.pid,+ ...(stderr ? { stderr } : {}),+ });}),- onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code, pid: handle.pid }),});diff --git a/packages/effect-codex-app-server/src/client.test.ts b/packages/effect-codex-app-server/src/client.test.tsindex c5fb8fe9992..56d9dbcebfa 100644--- a/packages/effect-codex-app-server/src/client.test.ts+++ b/packages/effect-codex-app-server/src/client.test.ts@@ -15,6 +15,7 @@ import { assert, expect, it } from "@effect/vitest";import * as CodexClient from "./client.ts";import { makeInMemoryStdio } from "./_internal/stdio.ts";+import * as CodexError from "./errors.ts";const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),@@ -209,3 +210,38 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {}),);});++it.live("reports the stderr error when the process exits before initialize", () =>+ Effect.gen(function* () {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const handle = yield* spawner.spawn(+ ChildProcess.make(process.execPath, [+ "-e",+ 'throw new Error("Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest")',+ ]),+ );+ const scope = yield* Scope.make();+ const context = yield* Layer.buildWithScope(CodexClient.layerChildProcess(handle), scope);++ const error = yield* Effect.gen(function* () {+ const client = yield* CodexClient.CodexAppServerClient;+ return yield* client.request("initialize", {+ clientInfo: {+ name: "effect-codex-app-server-test",+ title: "Effect Codex App Server Test",+ version: "0.0.0",+ },+ capabilities: {+ experimentalApi: true,+ optOutNotificationMethods: null,+ },+ });+ }).pipe(Effect.flip, Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));++ assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);+ assert.equal(+ error.message,+ "Codex App Server process exited with code 1: Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",+ );+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+);diff --git a/packages/effect-codex-app-server/src/client.ts b/packages/effect-codex-app-server/src/client.tsindex 780196ffdaf..28f677e03ee 100644--- a/packages/effect-codex-app-server/src/client.ts+++ b/packages/effect-codex-app-server/src/client.ts@@ -5,7 +5,6 @@ import * as Layer from "effect/Layer";import * as Schema from "effect/Schema";import * as Scope from "effect/Scope";import * as Stdio from "effect/Stdio";-import * as Stream from "effect/Stream";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";import * as CodexRpc from "./_generated/meta.gen.ts";@@ -18,7 +17,7 @@ import {encodeOptionalPayload,runHandler,} from "./_internal/shared.ts";-import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";+import { makeChildStdio, makeStderrTail, makeTerminationError } from "./_internal/stdio.ts";export interface CodexAppServerClientOptions {readonly logIncoming?: boolean;@@ -311,6 +310,10 @@ export const layerChildProcess = (const makeChildProcessClient = Effect.fn("effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {- yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);- return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));+ const stderrTail = yield* makeStderrTail(handle.stderr);+ return yield* make(+ makeChildStdio(handle, stderrTail.awaitDrained),+ options,+ makeTerminationError(handle, stderrTail.read),+ );});diff --git a/packages/effect-codex-app-server/src/errors.ts b/packages/effect-codex-app-server/src/errors.tsindex aa18cd66084..33d8cf5c488 100644--- a/packages/effect-codex-app-server/src/errors.ts+++ b/packages/effect-codex-app-server/src/errors.ts@@ -138,13 +138,16 @@ export class CodexAppServerProcessExitedError extends Schema.TaggedError<CodexAp{code: Schema.optional(Schema.Number),pid: Schema.optionalKey(Schema.Int),+ stderr: Schema.optionalKey(Schema.String),cause: Schema.optional(Schema.Defect()),},) {override get message() {- return this.code === undefined- ? "Codex App Server process exited"- : `Codex App Server process exited with code ${this.code}`;+ const base =+ this.code === undefined+ ? "Codex App Server process exited"+ : `Codex App Server process exited with code ${this.code}`;+ return this.stderr ? `${base}: ${this.stderr}` : base;}}