diff --git a/src/claude-cli.ts b/src/claude-cli.ts index d4fb2897..1bf83c7c 100644 --- a/src/claude-cli.ts +++ b/src/claude-cli.ts @@ -31,26 +31,44 @@ export async function claudeCliPath(): Promise { return installedClaudeCliPath(); } +/** How an option reaches the Claude CLI: in a flag, or over stdin in the SDK's initialize request. */ +type Delivery = NonNullable; + /** - * How a session's MCP servers reach the CLI of {@link claudeCliPath}, unless - * the client's options name a `mcpServersDelivery`. + * The SDK options that say how a session's MCP servers and its `settings` + * reach the CLI of {@link claudeCliPath}. A client's own options replace them. * * - `'initialize'` for the CLI that the adapter ships: over stdin, in the - * SDK's initialize request. A server's `env` and `headers`, such as the - * bearer token of an MCP-over-ACP endpoint (see `McpOverAcp`), stay off the - * CLI's command line, which other users of the machine can read. Only a - * launch that the client's options give `--sdk-url` still gets them there. + * SDK's initialize request. * - `'argv'` for a CLI that `CLAUDE_CODE_EXECUTABLE` names: in the - * `--mcp-config` flag, so on its command line, as before SDK 0.3.326. Its - * version is not known, and the SDK ends the session at startup when the CLI - * cannot read the servers from the initialize request (e.g. 2.1.323). + * `--mcp-config` and `--settings` flags, as before SDK 0.3.326. Its version + * is not known, and a CLI that cannot take them over stdin fails the session + * at startup (2.1.323: "too old to read MCP servers from the initialize + * request", "unknown option '--initialize-fields=settings'"). + * - `settings` stay `'argv'` when the client's `extraArgs` hold `settings`: + * Claude Code refuses to start with both ("--initialize-fields=settings + * cannot be used with --settings"), and in the flag the `settings` option + * replaces that argument. They also stay `'argv'` with `sdk-url` in the + * `extraArgs`: such a session cannot read the request at launch, and the SDK + * sends its MCP servers in the flag for the same reason. * - * The adapter always sets the option. It names the CLI to start + * The SDK reads `settingsDelivery` (0.3.328) but does not declare it in + * `sdk.d.ts`, so nothing fails to compile if a later SDK drops it. The v2 + * integration tests check the delivery against the real CLI. + * + * `mcpServersDelivery` is always set. The adapter names the CLI to start * (`pathToClaudeCodeExecutable`), and for such an app the SDK prints a * `DeprecationWarning` when a session has MCP servers and the option is unset. */ -export function mcpServersDelivery(): NonNullable { - return process.env.CLAUDE_CODE_EXECUTABLE ? "argv" : "initialize"; +export function cliDelivery(clientExtraArgs: Options["extraArgs"]): { + mcpServersDelivery: Delivery; + settingsDelivery: Delivery; +} { + const delivery = process.env.CLAUDE_CODE_EXECUTABLE ? "argv" : "initialize"; + const settingsInFlag = Object.keys(clientExtraArgs ?? {}).some( + (name) => name === "settings" || name === "sdk-url" || name.startsWith("sdk-url="), + ); + return { mcpServersDelivery: delivery, settingsDelivery: settingsInFlag ? "argv" : delivery }; } function bundledClaudeCliPath(directory: string): string { diff --git a/src/tests/claude-cli.test.ts b/src/tests/claude-cli.test.ts index 9f8cfccf..e6b37ef4 100644 --- a/src/tests/claude-cli.test.ts +++ b/src/tests/claude-cli.test.ts @@ -56,24 +56,49 @@ describe("claudeCliPath", () => { }); }); -describe("mcpServersDelivery", () => { +describe("cliDelivery", () => { afterEach(() => vi.unstubAllEnvs()); - it.each([ + it.each<{ + name: string; + cli: string; + extraArgs?: Record; + mcpServers: string; + settings: string; + }>([ { - name: "is initialize for the CLI that it ships", + name: "is stdin for the CLI that it ships", cli: "", - delivery: "initialize", + mcpServers: "initialize", + settings: "initialize", }, { - name: "is argv for a CLAUDE_CODE_EXECUTABLE CLI", + name: "is a flag for a CLAUDE_CODE_EXECUTABLE", cli: "/opt/claude", - delivery: "argv", + mcpServers: "argv", + settings: "argv", }, - ])("$name", async ({ cli, delivery }) => { + { + name: "keeps settings a flag beside a client's", + cli: "", + extraArgs: { settings: "{}" }, + mcpServers: "initialize", + settings: "argv", + }, + { + name: "keeps settings a flag with sdk-url", + cli: "", + extraArgs: { "sdk-url": "wss://example.com/session" }, + mcpServers: "initialize", + settings: "argv", + }, + ])("$name", async ({ cli, extraArgs, mcpServers, settings }) => { vi.stubEnv("CLAUDE_CODE_EXECUTABLE", cli); - const { mcpServersDelivery } = await load(); + const { cliDelivery } = await load(); - expect(mcpServersDelivery()).toBe(delivery); + expect(cliDelivery(extraArgs)).toEqual({ + mcpServersDelivery: mcpServers, + settingsDelivery: settings, + }); }); }); diff --git a/src/tests/v1/create-session-options.test.ts b/src/tests/v1/create-session-options.test.ts index 40fa4487..cb05eece 100644 --- a/src/tests/v1/create-session-options.test.ts +++ b/src/tests/v1/create-session-options.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { describe, it, expect, beforeEach, afterEach, onTestFinished, vi } from "vitest"; import { CreateElicitationRequest, RequestError, @@ -630,17 +630,33 @@ describe("createSession options merging", () => { }); it.each([ - { name: "sends MCP servers as the CLI takes them", delivery: undefined }, - { name: "lets a caller choose the MCP delivery", delivery: "initialize" as const }, - ])("$name", async ({ delivery }) => { + { name: "sends MCP servers as the CLI takes them", option: "mcpServersDelivery" }, + { + name: "lets a caller choose the MCP delivery", + option: "mcpServersDelivery", + own: "initialize", + }, + { name: "sends settings as the CLI takes them", option: "settingsDelivery" }, + { + name: "lets a caller choose settings delivery", + option: "settingsDelivery", + own: "initialize", + }, + ])("$name", async ({ option, own }) => { + // A CLI that CLAUDE_CODE_EXECUTABLE names gets both in flags. + // `vitest.config.ts` sets the variable for unit runs only. + vi.stubEnv("CLAUDE_CODE_EXECUTABLE", "/usr/bin/false"); + onTestFinished(() => { + vi.unstubAllEnvs(); + }); + await agent.newSession({ cwd: process.cwd(), mcpServers: [], - ...(delivery && { _meta: { claudeCode: { options: { mcpServersDelivery: delivery } } } }), + ...(own && { _meta: { claudeCode: { options: { [option]: own } } } }), }); - // Unit runs name a CLI with CLAUDE_CODE_EXECUTABLE (see `vitest.config.ts`). - expect(capturedOptions!.mcpServersDelivery).toBe(delivery ?? "argv"); + expect((capturedOptions as Record)[option]).toBe(own ?? "argv"); }); it("defaults tools to claude_code preset when not provided", async () => { diff --git a/src/tests/v2/v2-integration.test.ts b/src/tests/v2/v2-integration.test.ts index 968dfb0c..3575685a 100644 --- a/src/tests/v2/v2-integration.test.ts +++ b/src/tests/v2/v2-integration.test.ts @@ -1,4 +1,5 @@ import { spawn, spawnSync, type ChildProcess } from "node:child_process"; +import { randomUUID } from "node:crypto"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; @@ -70,6 +71,19 @@ describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)("v2 core with Claude Code", afterAll(() => child?.kill()); + /** + * Whether the adapter sends MCP servers and settings to Claude Code over + * stdin (see `cliDelivery`), and `ps` can show that: not for a + * CLAUDE_CODE_EXECUTABLE CLI, and not on Windows. + */ + const takesOptionsOverStdin = process.platform !== "win32" && !process.env.CLAUDE_CODE_EXECUTABLE; + + /** The command lines of the processes that the adapter started. */ + const adapterCommandLines = () => + spawnSync("ps", ["-axww", "-o", "ppid=,command="], { encoding: "utf8" }) + .stdout.split("\n") + .filter((line) => line.trim().startsWith(`${child.pid} `)); + /** The states of the root session's `state_update`s, in order. */ const states = (sessionId: string) => updates.flatMap(({ sessionId: id, update }) => @@ -218,19 +232,34 @@ describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)("v2 core with Claude Code", // Claude Code asks for the server's MCP revision first, not with `initialize`. await until(() => served.includes("tools/list"), 30_000); expect(served[0]).toBe("server/discover"); - // The server's bearer token went to Claude Code over stdin: it is on no - // command line of the adapter's processes (`ps`, so not on Windows). A - // CLAUDE_CODE_EXECUTABLE CLI gets it on its command line. - if (process.platform !== "win32" && !process.env.CLAUDE_CODE_EXECUTABLE) { - const commandLines = spawnSync("ps", ["-axww", "-o", "ppid=,command="], { encoding: "utf8" }) - .stdout.split("\n") - .filter((line) => line.trim().startsWith(`${child.pid} `)); + // The server's bearer token went to Claude Code over stdin. + if (takesOptionsOverStdin) { + const commandLines = adapterCommandLines(); // Claude Code's session process is one of them. expect(commandLines.some((line) => line.includes("stream-json"))).toBe(true); expect(commandLines.filter((line) => line.includes("Bearer "))).toEqual([]); } }, 60_000); + // No prompt: it costs no API usage. + it.skipIf(!takesOptionsOverStdin)( + "sends a session's settings to Claude Code over stdin", + async () => { + const marker = `v2-integration-${randomUUID()}`; + await agent.request(v2.methods.agent.session.new, { + cwd, + _meta: { + claudeCode: { options: { settings: { env: { V2_INTEGRATION_MARKER: marker } } } }, + }, + }); + const commandLines = adapterCommandLines(); + // Claude Code's session process, told to read the settings from the initialize request. + expect(commandLines.some((line) => line.includes("--initialize-fields=settings"))).toBe(true); + expect(commandLines.filter((line) => line.includes(marker))).toEqual([]); + }, + 60_000, + ); + it("reports requires_action while a permission request waits", async () => { const sessionId = await newSession("default"); await prompt( diff --git a/src/tests/v2/v2.test.ts b/src/tests/v2/v2.test.ts index d91c3ec7..0e489442 100644 --- a/src/tests/v2/v2.test.ts +++ b/src/tests/v2/v2.test.ts @@ -1024,9 +1024,23 @@ describe("ACP v2 core", () => { }); it.each([ - { name: "sends MCP servers as the CLI takes them", delivery: undefined }, - { name: "lets the client choose the MCP delivery", delivery: "initialize" }, - ])("$name", async ({ delivery }) => { + { name: "sends MCP servers as the CLI takes them", option: "mcpServersDelivery" }, + { + name: "lets the client choose the MCP delivery", + option: "mcpServersDelivery", + own: "initialize", + }, + { name: "sends settings as the CLI takes them", option: "settingsDelivery" }, + { + name: "lets the client choose settings delivery", + option: "settingsDelivery", + own: "initialize", + }, + ])("$name", async ({ option, own }) => { + // A CLI that CLAUDE_CODE_EXECUTABLE names gets both in flags. + // `vitest.config.ts` sets the variable for unit runs only. + vi.stubEnv("CLAUDE_CODE_EXECUTABLE", "/usr/bin/false"); + const client = v2Client(); await client.connect(async (agent) => { await agent.request(v2.methods.agent.initialize, { @@ -1036,12 +1050,11 @@ describe("ACP v2 core", () => { }); await agent.request(v2.methods.agent.session.new, { cwd, - ...(delivery && { _meta: { claudeCode: { options: { mcpServersDelivery: delivery } } } }), + ...(own && { _meta: { claudeCode: { options: { [option]: own } } } }), }); }); - // Unit runs name a CLI with CLAUDE_CODE_EXECUTABLE (see `vitest.config.ts`). - expect(sdk.processes[0].options.mcpServersDelivery).toBe(delivery ?? "argv"); + expect((sdk.processes[0].options as Record)[option]).toBe(own ?? "argv"); }); it("answers a prompt when Claude Code starts it, and reports the work until the turn's result", async () => { diff --git a/src/v1/acp-agent.ts b/src/v1/acp-agent.ts index eca4a900..b975bf96 100644 --- a/src/v1/acp-agent.ts +++ b/src/v1/acp-agent.ts @@ -192,7 +192,7 @@ import { import { AuthStatusReporter, cliLogout } from "../auth-status-reporter.js"; import { terminalAuthMethods as authMethodsForTerminal } from "../auth-methods.js"; import { McpOverAcp, sdkMcpServers, type UnservedMcpServer } from "../mcp-servers.js"; -import { claudeCliPath, mcpServersDelivery } from "../claude-cli.js"; +import { claudeCliPath, cliDelivery } from "../claude-cli.js"; import { ContentBlockParam } from "@anthropic-ai/sdk/resources"; import { randomUUID } from "node:crypto"; import type { Stats } from "node:fs"; @@ -10226,8 +10226,9 @@ export class ClaudeAcpAgent { // Before `userProvidedOptions`, so a client that passes // `promptSuggestions: false` keeps it off. ...promptSuggestionOptions(suggestionForms), - // Before `userProvidedOptions`, so a client's own `mcpServersDelivery` wins. - mcpServersDelivery: mcpServersDelivery(), + // Before `userProvidedOptions`, so a client's own `mcpServersDelivery` + // and `settingsDelivery` win. + ...cliDelivery(userProvidedOptions?.extraArgs), ...userProvidedOptions, // Claude Code uses the same checkpoint store for /rewind. Enable it only // for clients that negotiated per-turn file-change reports; this avoids diff --git a/src/v2/agent.ts b/src/v2/agent.ts index 48221749..5632ad74 100644 --- a/src/v2/agent.ts +++ b/src/v2/agent.ts @@ -35,7 +35,7 @@ import { messageIdForGrouping } from "../sdk-to-acp.js"; import type { Logger } from "../logger.js"; import { customAgents } from "../session-config-options.js"; import { restrictedChild } from "../acp-subagents.js"; -import { claudeCliPath, mcpServersDelivery } from "../claude-cli.js"; +import { claudeCliPath, cliDelivery } from "../claude-cli.js"; import { clientSystemPrompt, sessionSystemPrompt } from "../client-system-prompt.js"; import type { ElicitationSupport } from "../elicitation.js"; import { forkSession } from "../fork-session.js"; @@ -1102,8 +1102,9 @@ class V2Agent implements AgentHandle, SessionConnection { // other client's session spends a request on it. // Before the client's options: `promptSuggestions: false` turns it off. ...promptSuggestionOptions(this.promptSuggestions), - // Before the client's options: its own `mcpServersDelivery` wins. - mcpServersDelivery: mcpServersDelivery(), + // Before the client's options: its own `mcpServersDelivery` and + // `settingsDelivery` win. + ...cliDelivery(client?.extraArgs), ...client, // The checkpoints that AIR's file-change reports read (see // `file-changes.ts`), only for a client that declared them, as on v1.