diff --git a/src/session-ultracode.ts b/src/session-ultracode.ts index da2b99ba..adc84cc3 100644 --- a/src/session-ultracode.ts +++ b/src/session-ultracode.ts @@ -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 { +// `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 }; + +/** 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 { 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` diff --git a/src/startup-failure.ts b/src/startup-failure.ts index 085571f4..326fbd2d 100644 --- a/src/startup-failure.ts +++ b/src/startup-failure.ts @@ -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})`; +} diff --git a/src/tests/v1/create-session-options.test.ts b/src/tests/v1/create-session-options.test.ts index 75ef1536..a70f9b68 100644 --- a/src/tests/v1/create-session-options.test.ts +++ b/src/tests/v1/create-session-options.test.ts @@ -32,6 +32,8 @@ let initModels: Record[] | undefined; /** Holds the CLI initialization until the test resolves it. */ let initGate: Promise | 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(); diff --git a/src/tests/v1/ultracode-config.test.ts b/src/tests/v1/ultracode-config.test.ts index aafcbe5d..286b5746 100644 --- a/src/tests/v1/ultracode-config.test.ts +++ b/src/tests/v1/ultracode-config.test.ts @@ -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 }, + }), + ); + }); +}); diff --git a/src/tests/v2/acp-v2.test.ts b/src/tests/v2/acp-v2.test.ts index 5fb754e2..ba448986 100644 --- a/src/tests/v2/acp-v2.test.ts +++ b/src/tests/v2/acp-v2.test.ts @@ -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> => ({ applied: {} }), initializationResult: async (): Promise> => ({ 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) => 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 }).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) => { diff --git a/src/v1/acp-agent.ts b/src/v1/acp-agent.ts index b2876660..d40a7fd0 100644 --- a/src/v1/acp-agent.ts +++ b/src/v1/acp-agent.ts @@ -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 { 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 }; diff --git a/src/v2/agent.ts b/src/v2/agent.ts index 606163ec..ef046490 100644 --- a/src/v2/agent.ts +++ b/src/v2/agent.ts @@ -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 { 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 { diff --git a/src/v2/config.ts b/src/v2/config.ts index a1ecdd41..9f652984 100644 --- a/src/v2/config.ts +++ b/src/v2/config.ts @@ -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;