Compare commits

..
Author SHA1 Message Date
Xu Kang fb32ab924f fix(server): contain Codex app-server stdin errors (#11847) 2026-12-03 05:12:39 +00:00
4 changed files with 75 additions and 42 deletions
@@ -3668,13 +3668,6 @@ describe("Codex app-server provider", () => {
requires_openai_auth: false,
wire_api: "responses",
},
"codex-iisb": {
name: "Custom Codex",
base_url: "https://custom-relay.example.com/v1",
env_key: "OPENAI_API_KEY",
requires_openai_auth: false,
wire_api: "responses",
},
},
});
});
@@ -3691,9 +3684,6 @@ describe("Codex app-server provider", () => {
"paseo:codex-custom": expect.objectContaining({
base_url: "https://custom-relay.example.com/v1",
}),
"codex-custom": expect.objectContaining({
base_url: "https://custom-relay.example.com/v1",
}),
},
});
});
@@ -3775,10 +3775,6 @@ function buildCodexCustomProviderConfig(
model_provider: providerKey,
model_providers: {
[providerKey]: providerConfig,
// Codex resolves existing threads using the provider key saved on the thread.
...(!CODEX_BUILTIN_MODEL_PROVIDER_IDS.has(customProvider.id)
? { [customProvider.id]: providerConfig }
: {}),
},
};
}
@@ -4604,6 +4600,11 @@ export class CodexAppServerAgentSession implements AgentSession {
cwd: this.config.cwd ?? null,
excludeTurns: true,
};
if (this.deps.customCodexConfig) {
// Resume otherwise prefers the provider stored on the thread, including
// the unnamespaced key emitted by earlier Paseo versions.
params.modelProvider = this.deps.customCodexConfig.model_provider;
}
const developerInstructions = this.threadDeveloperInstructions();
if (developerInstructions) {
params.developerInstructions = developerInstructions;
@@ -4616,25 +4617,6 @@ export class CodexAppServerAgentSession implements AgentSession {
const loaded = toObjectRecord(await this.client.request("thread/loaded/list", {}));
const ids = Array.isArray(loaded?.data) ? loaded.data : [];
if (!ids.includes(this.currentThreadId)) {
const customConfig = this.deps.customCodexConfig;
if (customConfig && codexConfig) {
const metadata = toObjectRecord(
await this.client.request("thread/read", {
threadId: this.currentThreadId,
includeTurns: false,
}),
);
const savedProvider = toObjectRecord(metadata?.thread)?.modelProvider;
// Use the thread's provider when it belongs to this custom provider.
// Keep the explicit selection for other threads so Codex can reject a mismatch.
const provider =
typeof savedProvider === "string" &&
Object.hasOwn(customConfig.model_providers, savedProvider)
? savedProvider
: customConfig.model_provider;
params.modelProvider = provider;
codexConfig.model_provider = provider;
}
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
this.rememberRestoredCollaborationMode(response);
@@ -8573,9 +8555,13 @@ export class CodexAppServerAgentClient implements AgentClient {
// unless told otherwise, lists only the provider its own config selects.
// Include legacy custom ids, but keep Codex built-in sessions separate.
const customProviderConfig = this.customProviderConfig();
const modelProviders = customProviderConfig
? Object.keys(customProviderConfig.model_providers)
: undefined;
let modelProviders: string[] | undefined;
if (customProviderConfig && this.deps.customProvider) {
modelProviders = [customProviderConfig.model_provider];
if (!CODEX_BUILTIN_MODEL_PROVIDER_IDS.has(this.deps.customProvider.id)) {
modelProviders.push(this.deps.customProvider.id);
}
}
const allThreads = await readCodexThreadWindow(client, this.logger, {
limit: listLimit,
cwd: options?.cwd,
@@ -1,3 +1,5 @@
import { spawn } from "node:child_process";
import { errorMonitor, once } from "node:events";
import { describe, expect, test, vi } from "vitest";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
@@ -8,6 +10,52 @@ import {
import { CodexAppServerClient, CodexAppServerExitError } from "./app-server-transport.js";
describe("Codex app-server transport", () => {
test.skipIf(process.platform === "win32")(
"keeps the provider exit diagnostic when initialization hits a closed stdin",
async () => {
const child = spawn(
process.execPath,
[
"-e",
[
'process.on("message", () => process.exit(86));',
'require("node:fs").closeSync(0);',
'process.stdout.write("ready");',
].join("\n"),
],
{ stdio: ["pipe", "pipe", "pipe", "ipc"] },
);
const client = new CodexAppServerClient(child, createTestLogger());
try {
await once(child.stdout, "data");
// errorMonitor observes EPIPE without handling it on the transport's behalf.
child.stdin.once(errorMonitor, () => child.send("exit"));
await expect(client.request("initialize", {}, 2_000)).rejects.toMatchObject({
name: "CodexAppServerExitError",
exitCode: 86,
});
} finally {
await client.dispose();
}
},
);
test("closes an active transport once when stdin fails before the child exits", async () => {
const child = createCodexAppServerChildProcess();
const client = new CodexAppServerClient(child, createTestLogger());
const terminated = vi.fn();
client.setUnexpectedTerminationHandler(terminated);
const failure = new Error("write EPIPE");
const first = expect(client.request("thread/read", {})).rejects.toBe(failure);
const second = expect(client.request("thread/loaded/list", {})).rejects.toBe(failure);
child.stdin.emit("error", failure);
child.stdin.emit("error", failure);
await Promise.all([first, second]);
expect(client.hasPendingRequests()).toBe(false);
expect(terminated).toHaveBeenCalledExactlyOnceWith(failure);
await expect(client.request("thread/read", {})).rejects.toThrow("client is closed");
});
test("classifies startup diagnostics delivered after the child exits", async () => {
const child = createCodexAppServerChildProcess();
const client = new CodexAppServerClient(child, createTestLogger());
@@ -268,6 +268,14 @@ export class CodexAppServerClient {
this.handleUnexpectedTermination(err);
});
const isInitializing = () =>
Array.from(this.pending.values()).some((request) => request.method === "initialize");
child.stdin.on("error", (error) => {
// During startup, close owns the final stderr and exit reason. The startup
// coordinator's deadline also covers a child that closes stdin and stays alive.
if (!isInitializing()) this.terminateAfterStreamFailure(error);
});
const reportExit = (code: number | null, signal: NodeJS.Signals | null) => {
this.handleUnexpectedTermination(
new CodexAppServerExitError({
@@ -280,10 +288,7 @@ export class CodexAppServerClient {
child.on("exit", (code, signal) => {
// Startup retries need complete diagnostics. Node drains the child's
// stdio before close, but exit can precede the final stderr data.
const initializing = Array.from(this.pending.values()).some(
(request) => request.method === "initialize",
);
if (!initializing) reportExit(code, signal);
if (!isInitializing()) reportExit(code, signal);
});
child.on("close", reportExit);
}
@@ -381,10 +386,14 @@ export class CodexAppServerClient {
}
// A lost notification or server request cannot be replayed. Fail the session,
// including live turns with no pending RPC, rather than dropping a stream unit.
this.stdoutLineReader.close();
this.terminateAfterStreamFailure(failure);
}
private terminateAfterStreamFailure(failure: Error): void {
if (this.disposed) return;
this.handleUnexpectedTermination(failure);
void this.dispose().catch((err) => {
this.logger.warn({ err }, "Failed to terminate oversized Codex stdout producer");
this.logger.warn({ err }, "Failed to terminate Codex app-server after stream failure");
});
}