fix: refuse to start a session when Claude Code skipped an invalid settings file (#1719)

## Problem

When a Claude Code settings file (for example `~/.claude/settings.json`)
has a JSON syntax error or fails validation, Claude Code skips the whole
file. Its permission allow/deny rules, sandbox settings and hooks are
not applied. The `claude` CLI warns about this at startup, but an ACP
session started silently without those settings, and nothing told the
user.

## Fix

The adapter already sends `get_settings` at every session start (for the
ultracode state). Its response lists the skipped files in `errors`
(`SDKSettingsParseError[]`), which the adapter ignored.

- `readUltracodeSettings` is renamed to `readSettingsReport` and also
returns those errors from the same request. There is no second round
trip.
- `rejectSkippedSettings` (in `startup-failure.ts`, next to the other
start failures) throws a `RequestError` when the list is not empty, for
example:
> Claude Code skipped the invalid settings file
/home/u/.claude/settings.json (Invalid or malformed JSON), so its
permission rules, sandbox settings and hooks would not apply. Fix the
file and start the session again.

  `data.settingsErrors` carries the entries as the CLI reported them.
- v1 `createSession` and v2 `SessionConfig.start` call it. The existing
catch blocks close the query, and no session is registered. This applies
to `session/new`, `load`, `resume`, `fork` and `session/options` on both
protocol versions.
- v2: the `SessionConfig.start` catch also ends the session's auth and
subscription-guard entries when no live session holds that id.

## Notes

- A restart inside a session (provider switch, sign-out respawn, fresh
context after plan mode) is refused the same way when a file broke after
the session started.
- These already happen on any start failure and are unchanged here: a
refused `session/fork` leaves its copied transcript behind, and the v2
`sessionModels` catch does not end the auth and guard entries.

## Tests

- Unit tests for `rejectSkippedSettings` and for the reader's handling
of `errors`.
- v1 and v2: `session/new` and `session/options` reject with the error,
close the query and register no session.
- `npm run check` and `npm run build` pass. `npm run test:run` has 31
failures in `v1/create-session-options`, `v1/providers` and `v2/acp-v2`.
They are the same tests, by name, that fail on `main` at 9918571.
This commit is contained in:
Mark Tkachenko
2026-11-27 15:59:40 +01:00
committed by GitHub
parent 9918571ebf
commit e28b50d4f4
8 changed files with 229 additions and 40 deletions

View File

@@ -3,7 +3,7 @@ import type {
SessionConfigOption,
SetSessionConfigOptionRequest,
} from "@agentclientprotocol/sdk/unstable";
import type { ModelInfo, Query } from "@anthropic-ai/claude-agent-sdk";
import type { ModelInfo, Query, SDKSettingsParseError } from "@anthropic-ai/claude-agent-sdk";
import { ULTRACODE_CONFIG_ID } from "./session-config-ids.js";
export { ULTRACODE_CONFIG_ID } from "./session-config-ids.js";
@@ -24,33 +24,58 @@ export type UltracodeSettingsReport = {
requested?: boolean;
};
// `Query.getSettings()` exists at runtime (sdk.mjs) but is missing from the
// SDK's type declarations as of 0.3.319.
type GetSettingsQuery = Query & {
getSettings?: () => Promise<{
applied?: { ultracodeAvailable?: unknown; ultracodeRequested?: unknown };
}>;
/** The CLI's `get_settings` control response, as far as the adapter reads it. */
type GetSettingsResponse = {
applied?: { ultracodeAvailable?: unknown; ultracodeRequested?: unknown };
errors?: SDKSettingsParseError[];
};
/** Ask the CLI whether ultracode is available and requested for the session.
* Returns undefined when the SDK has no `getSettings` or the request fails;
* callers then fall back to {@link modelSupportsUltracode}. */
export async function readUltracodeSettings(
query: Query,
): Promise<UltracodeSettingsReport | undefined> {
// `Query.getSettings()` exists at runtime (sdk.mjs) but is missing from the
// SDK's type declarations as of 0.3.319.
type GetSettingsQuery = Query & { getSettings?: () => Promise<GetSettingsResponse | undefined> };
/** What the CLI's `get_settings` control response says about the session. */
export type SettingsReport = {
/** Undefined when the SDK has no `getSettings` or the request fails; callers
* then fall back to {@link modelSupportsUltracode}. */
ultracode: UltracodeSettingsReport | undefined;
/** Settings files that the CLI skipped, e.g. `{ file: "/home/u/.claude/settings.json",
* path: "", message: "Invalid or malformed JSON" }`. Empty when the CLI
* reports none or cannot be asked. */
settingsErrors: SDKSettingsParseError[];
};
const NO_REPORT: SettingsReport = { ultracode: undefined, settingsErrors: [] };
/** Ask the CLI whether ultracode is available and requested for the session,
* and which settings files it skipped. */
export async function readSettingsReport(query: Query): Promise<SettingsReport> {
const getSettings = (query as GetSettingsQuery).getSettings;
if (typeof getSettings !== "function") return undefined;
if (typeof getSettings !== "function") return NO_REPORT;
let response: GetSettingsResponse | undefined;
try {
const applied = (await getSettings.call(query))?.applied;
return {
available:
typeof applied?.ultracodeAvailable === "boolean" ? applied.ultracodeAvailable : undefined,
requested:
typeof applied?.ultracodeRequested === "boolean" ? applied.ultracodeRequested : undefined,
};
response = await getSettings.call(query);
} catch {
return undefined;
return NO_REPORT;
}
return {
ultracode: { available: parseAvailable(response), requested: parseRequested(response) },
settingsErrors: parseSettingsErrors(response),
};
}
function parseAvailable(response: GetSettingsResponse | undefined): boolean | undefined {
const value = response?.applied?.ultracodeAvailable;
return typeof value === "boolean" ? value : undefined;
}
function parseRequested(response: GetSettingsResponse | undefined): boolean | undefined {
const value = response?.applied?.ultracodeRequested;
return typeof value === "boolean" ? value : undefined;
}
function parseSettingsErrors(response: GetSettingsResponse | undefined): SDKSettingsParseError[] {
return response?.errors ?? [];
}
/** The CLI supports ultracode on exactly the models that support `xhigh`

View File

@@ -1,5 +1,8 @@
import { RequestError } from "@agentclientprotocol/sdk/unstable";
import type { SDKStartupFailureReason } from "@anthropic-ai/claude-agent-sdk";
import type {
SDKSettingsParseError,
SDKStartupFailureReason,
} from "@anthropic-ai/claude-agent-sdk";
/** Makes the CLI write an `error_during_execution` result with a
* `startup_failure_reason` before it exits on a known startup failure. Without
@@ -48,3 +51,32 @@ export function startupFailureReasonOf(error: unknown): string | undefined {
?.startupFailureReason;
return typeof reason === "string" ? reason : undefined;
}
/** Throws the ACP error for a session whose settings files the CLI skipped,
* and does nothing for an empty list. A skipped file's permission rules,
* sandbox and hooks do not apply, so the session does not start. E.g. `Claude Code
* skipped the invalid settings file /home/u/.claude/settings.json (Invalid or
* malformed JSON), so its permission rules, sandbox settings and hooks would
* not apply. Fix the file and start the session again.` */
export function rejectSkippedSettings(errors: SDKSettingsParseError[]): void {
if (errors.length === 0) return;
throw RequestError.internalError({ settingsErrors: errors }, invalidSettingsMessage(errors));
}
function invalidSettingsMessage(errors: SDKSettingsParseError[]): string {
const skipped = errors.map(describeSkippedFile).join("; ");
if (errors.length === 1) {
return `Claude Code skipped ${skipped}, so its permission rules, sandbox settings and hooks would not apply. Fix the file and start the session again.`;
}
return `Claude Code skipped ${skipped}, so their permission rules, sandbox settings and hooks would not apply. Fix the files and start the session again.`;
}
/** E.g. `the invalid settings file /home/u/.claude/settings.json (permissions.deny: Expected array)`. */
function describeSkippedFile(error: SDKSettingsParseError): string {
const name =
error.file === undefined
? "an invalid settings file"
: `the invalid settings file ${error.file}`;
const detail = error.path === "" ? error.message : `${error.path}: ${error.message}`;
return `${name} (${detail})`;
}

View File

@@ -32,6 +32,8 @@ let initModels: Record<string, unknown>[] | undefined;
/** Holds the CLI initialization until the test resolves it. */
let initGate: Promise<void> | undefined;
let initError: Error | undefined;
/** The settings files that Claude Code reports as skipped (`get_settings` `errors`). */
let settingsErrors: Array<{ file?: string; path: string; message: string }> | undefined;
/** When set, Claude Code refuses a start that has MCP servers with it. */
let mcpServersRefusal: Error | undefined;
let missingConversation: string | undefined;
@@ -90,6 +92,7 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
contextUsageCalls.push(opts);
return contextUsageResult ? contextUsageResult() : Promise.resolve(DEFAULT_CONTEXT_USAGE);
},
getSettings: async () => ({ applied: {}, errors: settingsErrors }),
mcpServerStatus: () => mcpServerStatusResult(),
mcpAuthenticate: (serverName: string) => mcpAuthenticateImpl(serverName),
...(enableRemoteControlImpl ? { enableRemoteControl: enableRemoteControlImpl } : {}),
@@ -148,6 +151,7 @@ describe("createSession options merging", () => {
initModels = undefined;
initGate = undefined;
initError = undefined;
settingsErrors = undefined;
mcpServersRefusal = undefined;
missingConversation = undefined;
optionsRefusal = undefined;
@@ -1971,6 +1975,25 @@ describe("createSession options merging", () => {
expect(closeSpy).toHaveBeenCalled();
});
it.each([
["session/new", () => agent.newSession({ cwd: process.cwd(), mcpServers: [] })],
["session/options", () => agent.sessionOptions({ cwd: process.cwd() })],
])("refuses %s when Claude Code skipped a settings file", async (_method, request) => {
settingsErrors = [
{ file: "/home/u/.claude/settings.json", path: "", message: "Invalid or malformed JSON" },
];
await expect(request()).rejects.toMatchObject({
code: RequestError.internalError().code,
message:
"Internal error: Claude Code skipped the invalid settings file /home/u/.claude/settings.json " +
"(Invalid or malformed JSON), so its permission rules, sandbox settings and hooks would not apply. " +
"Fix the file and start the session again.",
data: { settingsErrors },
});
expect(closeSpy).toHaveBeenCalledOnce();
expect(Object.keys(agent.sessions)).toEqual([]);
});
it("starts a session without the MCP servers that Claude Code refuses", async () => {
mcpServersRefusal = sideloadRefusal();

View File

@@ -9,7 +9,7 @@ import type { AcpClient } from "../../acp-client.js";
import {
createUltracodeConfigOption,
modelSupportsUltracode,
readUltracodeSettings,
readSettingsReport,
resolveUltracodeEnabled,
ULTRACODE_CONFIG_ID,
ULTRACODE_OFF,
@@ -17,6 +17,7 @@ import {
ultracodeSupported,
ultracodeWorkflowsEnabled,
} from "../../session-ultracode.js";
import { rejectSkippedSettings } from "../../startup-failure.js";
import { makeMockQuery } from "../helpers.js";
const { querySpy } = vi.hoisted(() => ({ querySpy: vi.fn() }));
@@ -106,25 +107,47 @@ describe("ultracode helpers", () => {
expect(ultracodeSupported(true, OLD_OPUS)).toBe(false);
});
it("reads the CLI's ultracode report and tolerates CLIs without one", async () => {
it("reads the CLI's settings report and tolerates CLIs without one", async () => {
await expect(
readUltracodeSettings(
readSettingsReport(
getSettingsQuery(async () => ({
applied: { ultracodeAvailable: true, ultracodeRequested: false },
})),
),
).resolves.toEqual({ available: true, requested: false });
).resolves.toEqual({ ultracode: { available: true, requested: false }, settingsErrors: [] });
await expect(
readUltracodeSettings(getSettingsQuery(async () => ({ applied: {} }))),
).resolves.toEqual({ available: undefined, requested: undefined });
await expect(readUltracodeSettings(getSettingsQuery(undefined))).resolves.toBeUndefined();
readSettingsReport(getSettingsQuery(async () => ({ applied: {} }))),
).resolves.toEqual({
ultracode: { available: undefined, requested: undefined },
settingsErrors: [],
});
await expect(readSettingsReport(getSettingsQuery(undefined))).resolves.toEqual({
ultracode: undefined,
settingsErrors: [],
});
await expect(
readUltracodeSettings(
readSettingsReport(
getSettingsQuery(async () => {
throw new Error("unsupported control request");
}),
),
).resolves.toBeUndefined();
).resolves.toEqual({ ultracode: undefined, settingsErrors: [] });
});
it("reports the settings files that the CLI skipped", async () => {
const skipped = {
file: "/home/u/.claude/settings.json",
path: "",
message: "Invalid or malformed JSON",
};
await expect(
readSettingsReport(
getSettingsQuery(async () => ({
applied: {},
errors: [skipped],
})),
),
).resolves.toMatchObject({ settingsErrors: [skipped] });
});
});
@@ -294,3 +317,43 @@ describe("ultracode session config option", () => {
expect(ultracodeOption()).toEqual(createUltracodeConfigOption(false, true));
});
});
describe("rejectSkippedSettings", () => {
const USER = "/home/u/.claude/settings.json";
const PROJECT = "/work/.claude/settings.json";
const JSON_ERROR = { file: USER, path: "", message: "Invalid or malformed JSON" };
it("does nothing when the CLI skipped no file", () => {
expect(() => rejectSkippedSettings([])).not.toThrow();
});
it.each([
[
"a whole-file error",
[JSON_ERROR],
`Claude Code skipped the invalid settings file ${USER} (Invalid or malformed JSON), so its permission rules, sandbox settings and hooks would not apply. Fix the file and start the session again.`,
],
[
"a field path",
[{ file: USER, path: "permissions.deny", message: "Expected array" }],
`Claude Code skipped the invalid settings file ${USER} (permissions.deny: Expected array), so its permission rules, sandbox settings and hooks would not apply. Fix the file and start the session again.`,
],
[
"several files",
[JSON_ERROR, { file: PROJECT, path: "hooks", message: "Expected object" }],
`Claude Code skipped the invalid settings file ${USER} (Invalid or malformed JSON); the invalid settings file ${PROJECT} (hooks: Expected object), so their permission rules, sandbox settings and hooks would not apply. Fix the files and start the session again.`,
],
[
"no file",
[{ path: "", message: "Invalid or malformed JSON" }],
"Claude Code skipped an invalid settings file (Invalid or malformed JSON), so its permission rules, sandbox settings and hooks would not apply. Fix the file and start the session again.",
],
])("names the skipped files for %s", (_name, errors, message) => {
expect(() => rejectSkippedSettings(errors)).toThrow(
expect.objectContaining({
message: `Internal error: ${message}`,
data: { settingsErrors: errors },
}),
);
});
});

View File

@@ -91,6 +91,8 @@ const sdk = vi.hoisted(() => ({
}),
/** The query is closed, as `session/close` closes it. */
close: (): void => {},
/** What Claude Code answers to `get_settings`. */
getSettings: async (): Promise<Record<string, unknown>> => ({ applied: {} }),
initializationResult: async (): Promise<Record<string, unknown>> => ({
models: [
{
@@ -166,6 +168,7 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
stopTask: (taskId: string) => sdk.stopTask(taskId),
getTaskOutput: (taskId: string) => sdk.getTaskOutput(taskId),
close: () => sdk.close(),
getSettings: () => sdk.getSettings(),
accountInfo: () => sdk.accountInfo(),
setMcpServers: (servers: Record<string, unknown>) => sdk.setMcpServers(servers),
setModel: (model?: string) => sdk.setModel(model),
@@ -715,6 +718,33 @@ describe("ACP v2 sessions", () => {
});
});
it.each([
["session/new", v2.methods.agent.session.new],
["session/options", v2.methods.agent.session.options],
])("rejects %s when Claude Code skipped a settings file", async (_name, method) => {
const errors = [
{ file: "/home/u/.claude/settings.json", path: "", message: "Invalid or malformed JSON" },
];
sdk.getSettings = async () => ({ applied: {}, errors });
const close = vi.fn();
sdk.close = close;
const { app, authUpdate } = v2Client();
await app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
await expect(agent.request(method, { cwd })).rejects.toMatchObject({
code: -32603,
message:
"Internal error: Claude Code skipped the invalid settings file /home/u/.claude/settings.json " +
"(Invalid or malformed JSON), so its permission rules, sandbox settings and hooks would not apply. " +
"Fix the file and start the session again.",
data: { settingsErrors: errors },
});
expect(close).toHaveBeenCalledOnce();
expect((agents[0] as unknown as { sessions: Map<string, unknown> }).sessions.size).toBe(0);
await authUpdate(1);
});
});
it("rejects an MCP transport that v1 cannot express", async () => {
const { app, authUpdate } = v2Client();
await app.connectWith(connectRouter(), async (agent) => {

View File

@@ -437,7 +437,7 @@ import {
} from "../session-effort.js";
import {
createUltracodeConfigOption,
readUltracodeSettings,
readSettingsReport,
ULTRACODE_CONFIG_ID,
ultracodeSupported,
ultracodeWorkflowsEnabled,
@@ -470,7 +470,11 @@ import {
readContextWindow,
} from "../context-window.js";
import { isLoginRequiredText, resultEnd, turnErrorData } from "../result-end.js";
import { STARTUP_FAILURE_RESULTS_ENV, startupFailureError } from "../startup-failure.js";
import {
STARTUP_FAILURE_RESULTS_ENV,
rejectSkippedSettings,
startupFailureError,
} from "../startup-failure.js";
import { recordStreamedDelta, unstreamedRemainder, type StreamedBlock } from "../streamed-text.js";
import { subagentHookOptions } from "../subagent-configuration.js";
@@ -2075,7 +2079,8 @@ export class ClaudeAcpAgent {
* hooks in it, as in every query.
*
* It sends no update, and it creates, loads and changes no session. A
* `sessionId` that is neither held nor stored fails with `-32002`.
* `sessionId` that is neither held nor stored fails with `-32002`. It fails
* as the start would when Claude Code skipped an invalid settings file.
*/
async sessionOptions(params: SessionOptionsRequest): Promise<SessionOptionsResponse> {
while (this.providerUpdate) await this.providerUpdate;
@@ -11190,7 +11195,7 @@ export class ClaudeAcpAgent {
// The CLI reports whether ultracode can run (workflows enabled and a
// supporting model) and whether the session already requests it (an
// `ultracode: true` setting). Without a report, fall back to settings.
const ultracodeReport = await readUltracodeSettings(q);
const { ultracode: ultracodeReport, settingsErrors } = await readSettingsReport(q);
timing.phase("ultracode");
const ultracodeEnabled = ultracodeReport?.requested ?? effortSettings.ultracode === true;
const workflowsEnabled = ultracodeWorkflowsEnabled(ultracodeReport, currentModelInfo);
@@ -11215,6 +11220,7 @@ export class ClaudeAcpAgent {
},
ultracode,
);
rejectSkippedSettings(settingsErrors);
if (creationOpts.optionsOnly) {
this.discardUnregisteredQuery(q, input, settingsManager);
return { sessionId, modes, configOptions };

View File

@@ -725,7 +725,9 @@ class V2Agent implements AgentHandle, SessionConnection {
* hooks in it, as in every query.
*
* It sends no update, and it creates, resumes and changes no session. A
* `sessionId` without a stored conversation fails with `-32002`.
* `sessionId` without a stored conversation fails with `-32002`. A start
* that would fail fails it too, e.g. when Claude Code skipped an invalid
* settings file.
*/
async sessionOptions(params: v2.SessionOptionsRequest): Promise<v2.SessionOptionsResponse> {
const { sessionId } = params;
@@ -1402,7 +1404,8 @@ class V2Agent implements AgentHandle, SessionConnection {
}
// A failed sync of the mode is logged (`SessionModeManager.initialize`),
// and a failed read of the agents or of ultracode leaves them out. Only
// the effort that `recommendedValue` sets can fail the start.
// the effort that `recommendedValue` sets, and settings files that Claude
// Code skipped, can fail the start.
let config;
try {
config = await SessionConfig.start(
@@ -1429,6 +1432,11 @@ class V2Agent implements AgentHandle, SessionConnection {
} catch (error) {
q.close();
settings.dispose();
// A live session under this id keeps its entries.
if (!this.sessions.has(sessionId)) {
this.auth.sessionEnded(sessionId);
this.guard.sessionEnded(sessionId);
}
throw error;
}
return {

View File

@@ -90,10 +90,11 @@ import {
import { noticeUpdate } from "../session-notices.js";
import {
createUltracodeConfigOption,
readUltracodeSettings,
readSettingsReport,
ultracodeSupported,
ultracodeWorkflowsEnabled,
} from "../session-ultracode.js";
import { rejectSkippedSettings } from "../startup-failure.js";
import { v1SetSessionConfigOptionRequest, v2ConfigOptions } from "./session-requests.js";
type ConfigQuery = Pick<
@@ -252,7 +253,8 @@ export class SessionConfig {
? undefined
: normalizeFastModeDisabledReason(setup.fastMode.disabledReason);
const settings = setup.effortSettings();
const ultracodeReport = await readUltracodeSettings(query);
const { ultracode: ultracodeReport, settingsErrors } = await readSettingsReport(query);
rejectSkippedSettings(settingsErrors);
const ultracodeEnabled = ultracodeReport?.requested ?? settings.ultracode === true;
const workflowsEnabled = ultracodeWorkflowsEnabled(ultracodeReport, currentModelInfo);
const clientEffort = setup.client?.effort;