Skip to content

Commit a636804

Browse files
authored
fix: explain Codex config load errors caused by a deleted working directory (#626)
## Problem When the agent's working directory is deleted while it runs, Codex fails every config load with a generic message (IJAI-2923, IJAI-3685): - `config/read` → `-32603 failed to resolve feature override precedence: No such file or directory (os error 2)` - `thread/start` → `-32600 failed to load configuration: No such file or directory (os error 2)` Codex loads project config from its process working directory, which it inherits from codex-acp, so the error says nothing about the real cause. ## Change New `src/CodexErrorExplanations.ts`: a single list of rules that every app-server request error goes through in `CodexAppServerClient.sendRequest`. A rule only rewrites the message; the error class, code and data stay, so `CodexThreadErrors` and app-server recovery work as before. - **Deleted working directory**: the agent records its working directory at start and checks whether the process still points at the directory at that path (a directory recreated at the same path counts as deleted). The message becomes: `Codex cannot read its configuration: its working directory <path> was deleted or replaced after the agent started. Restart the agent.` - **Config files hint**: moved here from `CodexAcpServer.handleError`, so it now applies to every request that fails to load config, not only session new/fork. "feature override precedence" is reworded to "failed to load configuration". Errors that require logout are skipped. `handleError` keeps only the logout action, via `requiresLogout()` from the module. ### Wire shape note Session new/fork config errors previously reached the client as `data: "<message>\n\nCheck…"` (a string, because the text was passed as the `data` argument of `RequestError.internalError`). They now take the SDK's default path like every other internal error: `data: {details: "<message>\n\nCheck…"}`. The logout error keeps its string `data`.
1 parent 13420d8 commit a636804

7 files changed

Lines changed: 266 additions & 18 deletions

File tree

‎src/CodexAcpServer.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
isNoActiveTurnError,
3030
parseExpectedActiveTurnMismatch,
3131
} from "./CodexThreadErrors";
32+
import {requiresLogout} from "./CodexErrorExplanations";
3233
import {type CodexConnection} from "./CodexJsonRpcConnection";
3334
import {AppServerRecovery, recoveryLimitsFromEnv} from "./app-server-recovery/AppServerRecovery";
3435
import {
@@ -933,15 +934,11 @@ export class CodexAcpServer {
933934
}
934935

935936
async handleError(e: Error){
936-
if (e.message.includes("log out") || e.message.includes("cloud requirements")) {
937+
if (requiresLogout(e)) {
937938
await this.runWithProcessCheck(() => this.codexAcpClient.logout());
938939
await this.refreshAuthState(null);
939940
throw RequestError.internalError(`${(e.message)}\n\nYou have been logged out. Please try again.`);
940941
}
941-
const configPath = this.codexAcpClient.getHomePath() ?? "global";
942-
if (e.message.includes("load config")) {
943-
throw RequestError.internalError(`${e.message}\n\nCheck ${configPath} and project .codex directories, especially their config.toml files, or any CODEX_CONFIG override.`);
944-
}
945942
}
946943

947944
private beginSessionOpen(sessionId: string): number {

‎src/CodexAppServerClient.ts‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {type MessageConnection, RequestType} from "vscode-jsonrpc/node";
22
import {AppServerConnectionLostError, ConnectionLoss} from "./app-server-recovery/ConnectionLoss";
3+
import {explainCodexError} from "./CodexErrorExplanations";
34
import {McpOauthCompletions} from "./mcp/McpOauthCompletions";
45
import {McpStartupTracker} from "./mcp/McpStartupTracker";
56
import type {
@@ -185,6 +186,8 @@ export class CodexAppServerClient {
185186
private readonly leakedReviewErrors = new Map<string, {error: TurnError, failedTurnIds: Set<string>}>();
186187
/** Ends the notification waits below when the connection is gone, see {@link waitWhileConnected}. */
187188
readonly connectionLoss: ConnectionLoss;
189+
/** The `$CODEX_HOME` of the app-server, for the error explanations. */
190+
private codexHome: string | null = null;
188191

189192
constructor(connection: MessageConnection) {
190193
this.connection = connection;
@@ -304,7 +307,9 @@ export class CodexAppServerClient {
304307
}
305308

306309
async initialize(params: InitializeParams): Promise<InitializeResponse> {
307-
return await this.sendRequest({ method: "initialize", params: params });
310+
const response: InitializeResponse = await this.sendRequest({ method: "initialize", params: params });
311+
this.codexHome = response?.codexHome ?? null;
312+
return response;
308313
}
309314

310315
async turnStart(params: TurnStartParams): Promise<TurnStartResponse> {
@@ -1281,15 +1286,19 @@ export class CodexAppServerClient {
12811286
}
12821287
const loadedThreadId = threadLoadOf(request);
12831288
let result: any;
1284-
if (loadedThreadId === null) {
1285-
if (request.params) {
1286-
result = await this.connection.sendRequest<R>(request.method, request.params)
1287-
}
1288-
else {
1289-
result = await this.connection.sendRequest<R>(request.method);
1289+
try {
1290+
if (loadedThreadId === null) {
1291+
if (request.params) {
1292+
result = await this.connection.sendRequest<R>(request.method, request.params)
1293+
}
1294+
else {
1295+
result = await this.connection.sendRequest<R>(request.method);
1296+
}
1297+
} else {
1298+
result = await this.threadLoadGate(loadedThreadId, () => this.sendThreadLoad<R>(loadedThreadId, request));
12901299
}
1291-
} else {
1292-
result = await this.threadLoadGate(loadedThreadId, () => this.sendThreadLoad<R>(loadedThreadId, request));
1300+
} catch (err) {
1301+
throw err instanceof Error ? explainCodexError(err, {codexHome: this.codexHome}) : err;
12931302
}
12941303
for (const callback of this.codexEventHandlers) {
12951304
callback({ eventType: "response", ...result});

‎src/CodexErrorExplanations.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/**
2+
* Adds the likely cause to app-server errors whose text is too generic to act on.
3+
*
4+
* Every app-server request error passes through {@link explainCodexError}. A rule only rewrites the message,
5+
* and the code and data stay. Other code matches the message text too (`CodexThreadErrors`), so a rule must not
6+
* match the errors that such code recognizes.
7+
*/
8+
9+
import {statSync} from "node:fs";
10+
import {ResponseError} from "vscode-jsonrpc/node";
11+
12+
export interface ExplanationContext {
13+
/** The `$CODEX_HOME` of the app-server, from its `initialize` answer. */
14+
readonly codexHome: string | null;
15+
}
16+
17+
/** Returns the error with the likely cause in its message, or the same error when no rule applies. */
18+
export function explainCodexError(err: Error, context: ExplanationContext): Error {
19+
for (const rule of RULES) {
20+
const message = rule(err, context);
21+
if (message !== null) return withMessage(err, message);
22+
}
23+
return err;
24+
}
25+
26+
/** True for an error that a new login fixes, so the agent logs out. */
27+
export function requiresLogout(err: Error): boolean {
28+
return err.message.includes("log out") || err.message.includes("cloud requirements");
29+
}
30+
31+
/** Returns the new message, or `null` when the rule does not apply. */
32+
type ExplanationRule = (err: Error, context: ExplanationContext) => string | null;
33+
34+
/**
35+
* `config/read` wraps every config load failure as "failed to resolve feature override precedence"
36+
* (codex-rs/app-server `config_processor.rs`), and `thread/start` wraps it as "failed to load configuration".
37+
*/
38+
const FEATURE_OVERRIDE_PRECEDENCE_PREFIX = "failed to resolve feature override precedence: ";
39+
const CONFIG_LOAD_FAILURE_PREFIX = "failed to load configuration: ";
40+
41+
/**
42+
* Codex loads the project config from its process working directory, even when the request has a `cwd`. The
43+
* app-server inherits that directory from this process, so a deleted directory fails every config load with a bare
44+
* "No such file or directory". The config files are not the cause, so the message does not point to them.
45+
*/
46+
const deletedWorkingDirectory: ExplanationRule = ({message}) => {
47+
const configLoadFailure = message.startsWith(FEATURE_OVERRIDE_PRECEDENCE_PREFIX)
48+
|| message.startsWith(CONFIG_LOAD_FAILURE_PREFIX);
49+
if (!configLoadFailure || !message.includes("No such file or directory") || !workingDirectoryDeleted()) {
50+
return null;
51+
}
52+
return `Codex cannot read its configuration: its working directory ${workingDirectory} `
53+
+ "was deleted or replaced after the agent started. Restart the agent.";
54+
};
55+
56+
/** Points a config load failure to the config files. A failure that needs a new login is not about them. */
57+
const configFiles: ExplanationRule = (err, {codexHome}) => {
58+
if (requiresLogout(err)) return null;
59+
const message = err.message.startsWith(FEATURE_OVERRIDE_PRECEDENCE_PREFIX)
60+
? CONFIG_LOAD_FAILURE_PREFIX + err.message.slice(FEATURE_OVERRIDE_PRECEDENCE_PREFIX.length)
61+
: err.message;
62+
if (!message.includes("load config")) return null;
63+
return `${message}\n\nCheck ${codexHome ?? "global"} and project .codex directories, `
64+
+ "especially their config.toml files, or any CODEX_CONFIG override.";
65+
};
66+
67+
const RULES: readonly ExplanationRule[] = [deletedWorkingDirectory, configFiles];
68+
69+
function withMessage(err: Error, message: string): Error {
70+
return err instanceof ResponseError ? new ResponseError(err.code, message, err.data) : new Error(message, {cause: err});
71+
}
72+
73+
// Read at start: the agent never changes it, and `process.cwd()` can fail once the directory is deleted.
74+
const workingDirectory = (() => {
75+
try {
76+
return process.cwd();
77+
} catch {
78+
return "";
79+
}
80+
})();
81+
82+
/** A directory created again at the same path is a new one: the process still points to the deleted directory. */
83+
function workingDirectoryDeleted(): boolean {
84+
try {
85+
const current = statSync(".");
86+
const atPath = statSync(workingDirectory);
87+
return current.ino !== atPath.ino || current.dev !== atPath.dev;
88+
} catch {
89+
return true;
90+
}
91+
}

‎src/__tests__/CodexACPAgent/mcp-config-merge.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ url = "https://example.com/mcp"
150150
cwd: "",
151151
mcpServers: [conflictingMcp],
152152
})).rejects.toMatchObject({
153-
data: expect.stringContaining("url is not supported for stdio"),
153+
message: expect.stringMatching(/url is not supported for stdio[\s\S]*config\.toml/),
154154
});
155155
});
156156
});

‎src/__tests__/CodexACPAgent/new-session-logout.test.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {describe, expect, it, vi} from "vitest";
22
import {createCodexMockTestFixture, createTestModel} from "../acp-test-utils";
33
import {ModelId} from "../../ModelId";
4+
import {ResponseError, type MessageConnection} from "vscode-jsonrpc/node";
45

56
describe("New session logout handling", () => {
67
it("logs out when newSession fails with an error containing log out", async () => {
@@ -50,13 +51,18 @@ describe("New session logout handling", () => {
5051
const logoutSpy = vi.spyOn(codexAcpClient, "logout").mockResolvedValue();
5152

5253
const errorMessage = 'Internal error: "failed to reload config: filesystem path `/tmp` must be absolute, use `~/...`, or start with `:`"';
53-
vi.spyOn(codexAppServerClient, "threadStart").mockRejectedValue(new Error(errorMessage));
54+
// The app-server answer goes through the error explanations of the client.
55+
const {connection} = codexAppServerClient as unknown as {connection: MessageConnection};
56+
vi.spyOn(connection, "sendRequest").mockImplementation((async (method: string) => {
57+
if (method === "thread/start") throw new ResponseError(-32603, errorMessage);
58+
return undefined;
59+
}) as never);
5460

55-
expect(logoutSpy).toHaveBeenCalledTimes(0);
5661
await expect(codexAcpAgent.newSession({cwd: "", mcpServers: []}))
5762
.rejects.toMatchObject({
58-
data: expect.stringContaining(`Check global and project .codex directories`),
63+
message: expect.stringContaining(`Check global and project .codex directories`),
5964
});
65+
expect(logoutSpy).toHaveBeenCalledTimes(0);
6066
});
6167

6268
it("refreshes OpenAI sessions when newSession error forces logout", async () => {
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import {afterEach, describe, expect, it, vi} from "vitest";
2+
import * as fs from "node:fs";
3+
import * as os from "node:os";
4+
import * as path from "node:path";
5+
import {ResponseError, type MessageConnection} from "vscode-jsonrpc/node";
6+
import {explainCodexError} from "../CodexErrorExplanations";
7+
import {CodexAppServerClient} from "../CodexAppServerClient";
8+
import {createMockConnections} from "./CodexACPAgent/test-utils";
9+
import {createCodexMockTestFixture} from "./acp-test-utils";
10+
11+
// The texts Codex 0.159.1 answers with when its working directory is gone (IJAI-2923).
12+
const configReadFailure = () => new ResponseError(
13+
-32603, "failed to resolve feature override precedence: No such file or directory (os error 2)", {extra: 1});
14+
const threadStartFailure = () => new ResponseError(
15+
-32600, "failed to load configuration: No such file or directory (os error 2)");
16+
17+
const context = {codexHome: "/home/codex"};
18+
const originalDirectory = process.cwd();
19+
const directories: string[] = [];
20+
21+
afterEach(() => {
22+
process.chdir(originalDirectory);
23+
directories.splice(0).forEach(directory => fs.rmSync(directory, {recursive: true, force: true}));
24+
});
25+
26+
/** Loads the module as in an agent started in a new directory, then runs `change` on that directory. */
27+
async function explainerStartedIn(change: (directory: string) => void = () => {}) {
28+
const directory = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "codex-cwd-")));
29+
directories.push(directory);
30+
process.chdir(directory);
31+
vi.resetModules();
32+
const {explainCodexError} = await import("../CodexErrorExplanations");
33+
change(directory);
34+
return (err: Error) => {
35+
const result = explainCodexError(err, context) as ResponseError<unknown>;
36+
return {
37+
code: result.code,
38+
message: result.message.replace(directory, "<working directory>"),
39+
data: result.data ?? null,
40+
};
41+
};
42+
}
43+
44+
describe("CodexErrorExplanations", () => {
45+
it.skipIf(process.platform === "win32")("explains config load failures", async () => {
46+
// Each explanation runs while the process is still in the directory of its agent.
47+
const deleted = await explainerStartedIn(fs.rmdirSync);
48+
const withDeletedDirectory = {
49+
configReadWithDeletedDirectory: deleted(configReadFailure()),
50+
threadStartWithDeletedDirectory: deleted(threadStartFailure()),
51+
otherConfigReadFailureWithDeletedDirectory: deleted(new ResponseError(
52+
-32603, "failed to resolve feature override precedence: invalid TOML in config.toml")),
53+
};
54+
const recreated = await explainerStartedIn(directory => {
55+
fs.rmdirSync(directory);
56+
fs.mkdirSync(directory);
57+
});
58+
const withRecreatedDirectory = {threadStartWithRecreatedDirectory: recreated(threadStartFailure())};
59+
const present = await explainerStartedIn();
60+
const results = {
61+
...withDeletedDirectory,
62+
...withRecreatedDirectory,
63+
configReadWithPresentDirectory: present(configReadFailure()),
64+
threadStartWithPresentDirectory: present(threadStartFailure()),
65+
reloadFailure: present(new Error("failed to reload config: filesystem path `/tmp` must be absolute")),
66+
reloadFailureThatNeedsLogout: present(new ResponseError(-32603, "failed to reload config: "
67+
+ "Your refresh token was already used. Please log out and sign in again.")),
68+
};
69+
await expect(`${JSON.stringify(results, null, 2)}\n`)
70+
.toMatchFileSnapshot("data/codex-error-explanations/config-load-failures.json");
71+
});
72+
73+
it("keeps other errors unchanged", () => {
74+
const unrelated = new ResponseError(-32600, "thread not found: thread-1");
75+
expect(explainCodexError(unrelated, context)).toBe(unrelated);
76+
});
77+
78+
it("explains the errors of app-server requests", async () => {
79+
const mocks = createMockConnections();
80+
mocks.mockCodexConnection.sendRequest.mockRejectedValue(configReadFailure());
81+
const client = new CodexAppServerClient(mocks.mockCodexConnection as unknown as MessageConnection);
82+
83+
await expect(client.configRead({includeLayers: false})).rejects.toMatchObject({
84+
code: -32603,
85+
message: expect.stringMatching(/^failed to load configuration: No such file or directory \(os error 2\)\n\nCheck global /),
86+
});
87+
});
88+
89+
it.skipIf(process.platform === "win32")("does not point to the config files when the working directory was deleted", async () => {
90+
const explain = await explainerStartedIn(fs.rmdirSync);
91+
const fixture = createCodexMockTestFixture();
92+
vi.spyOn(fixture.getCodexAcpClient(), "readAuthRequirement").mockResolvedValue({required: false, account: null});
93+
const {code, message} = explain(threadStartFailure());
94+
vi.spyOn(fixture.getCodexAppServerClient(), "threadStart").mockRejectedValue(new ResponseError(code, message));
95+
96+
const error = await fixture.getCodexAcpAgent().newSession({cwd: "", mcpServers: []}).catch(e => e);
97+
expect(error.message).toMatch(/was deleted or replaced after the agent started/);
98+
expect(error.message).not.toContain("config.toml");
99+
});
100+
});
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
{
2+
"configReadWithDeletedDirectory": {
3+
"code": -32603,
4+
"message": "Codex cannot read its configuration: its working directory <working directory> was deleted or replaced after the agent started. Restart the agent.",
5+
"data": {
6+
"extra": 1
7+
}
8+
},
9+
"threadStartWithDeletedDirectory": {
10+
"code": -32600,
11+
"message": "Codex cannot read its configuration: its working directory <working directory> was deleted or replaced after the agent started. Restart the agent.",
12+
"data": null
13+
},
14+
"otherConfigReadFailureWithDeletedDirectory": {
15+
"code": -32603,
16+
"message": "failed to load configuration: invalid TOML in config.toml\n\nCheck /home/codex and project .codex directories, especially their config.toml files, or any CODEX_CONFIG override.",
17+
"data": null
18+
},
19+
"threadStartWithRecreatedDirectory": {
20+
"code": -32600,
21+
"message": "Codex cannot read its configuration: its working directory <working directory> was deleted or replaced after the agent started. Restart the agent.",
22+
"data": null
23+
},
24+
"configReadWithPresentDirectory": {
25+
"code": -32603,
26+
"message": "failed to load configuration: No such file or directory (os error 2)\n\nCheck /home/codex and project .codex directories, especially their config.toml files, or any CODEX_CONFIG override.",
27+
"data": {
28+
"extra": 1
29+
}
30+
},
31+
"threadStartWithPresentDirectory": {
32+
"code": -32600,
33+
"message": "failed to load configuration: No such file or directory (os error 2)\n\nCheck /home/codex and project .codex directories, especially their config.toml files, or any CODEX_CONFIG override.",
34+
"data": null
35+
},
36+
"reloadFailure": {
37+
"message": "failed to reload config: filesystem path `/tmp` must be absolute\n\nCheck /home/codex and project .codex directories, especially their config.toml files, or any CODEX_CONFIG override.",
38+
"data": null
39+
},
40+
"reloadFailureThatNeedsLogout": {
41+
"code": -32603,
42+
"message": "failed to reload config: Your refresh token was already used. Please log out and sign in again.",
43+
"data": null
44+
}
45+
}

0 commit comments

Comments
 (0)