Skip to content
TypeScript

fix(server): Claude --settings launch args merge with T3's settings instead of being dropped (#22864)

Theo Browne8d94203c1728
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 470e04a384d..87c40b572b0 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -606,6 +606,19 @@ describe("ClaudeAdapterV2 native protocol logging", () => {
assert.equal(logged.hasMcpServers, true);
assert.notInclude(JSON.stringify(logged), "secret-claude-token");
});
+
+ it("logs --settings key names without their values", () => {
+ const options = ClaudeAdapterV2.makeClaudeQueryOptions({
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ nativeThreadId: "native-thread-claude-settings-log",
+ resume: false,
+ cwd: "/workspace",
+ sdkSettings: { env: { ANTHROPIC_API_KEY: "secret-settings-key" } },
+ });
+ const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options);
+ assert.deepEqual(logged.settingKeys, ["env", "showThinkingSummaries"]);
+ assert.notInclude(JSON.stringify(logged), "secret-settings-key");
+ });
});
describe("ClaudeAdapterV2 context usage", () => {
@@ -949,6 +962,34 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
),
);
+ // regression: #15073 the SDK replaced the --settings launch argument with T3's settings
+ it.effect.each([
+ `--settings '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}'`,
+ "--settings user-settings.json",
+ ])("merges %s beneath T3's settings", (launchArgs) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-settings-" });
+ yield* fileSystem.writeFileString(
+ NodePath.join(cwd, "user-settings.json"),
+ '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}',
+ );
+ const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
+ assert.isTrue(Exit.isSuccess(exit));
+ assert.deepInclude(opened[0]!.settings, {
+ skillOverrides: { lint: "off" },
+ showThinkingSummaries: true,
+ });
+ assert.isUndefined(opened[0]!.extraArgs?.["settings"]);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ ),
+ );
+
// regression: #20413 malformed append-system-prompt launch args fail before a query opens
it.effect.each([
[
@@ -979,6 +1020,19 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
flag: "--append-system-prompt",
}).message,
],
+ [
+ "--settings missing.json",
+ (cwd: string) =>
+ new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({
+ path: NodePath.join(cwd, "missing.json"),
+ }).message,
+ ],
+ ["--settings '{not json}'", () => new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({}).message],
+ // Without a closing brace this must not become a file path that echoes the secret.
+ [
+ `--settings '{"env":{"ANTHROPIC_API_KEY":"secret-settings-key"},'`,
+ () => new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({}).message,
+ ],
] as const)("fails the turn before opening Claude for %s", ([launchArgs, expectedMessage]) =>
Effect.scoped(
Effect.gen(function* () {
@@ -3284,29 +3338,31 @@ describe("ClaudeAdapterV2 background wake turns", () => {
vi.importActual<typeof ClaudeSdk>("@anthropic-ai/claude-agent-sdk"),
);
vi.mocked(ClaudeSdk.resolveSettings).mockImplementation(sdk.resolveSettings);
- const open = Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWakeHarnessWithOptions({
- settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
- });
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("attempt-cached-managed-policy"),
- text: "Run git status.",
- attachments: [],
- runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd,
+ const openWith = (launchArgs: string) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarnessWithOptions({
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home, launchArgs },
+ });
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-cached-managed-policy"),
+ text: "Run git status.",
+ attachments: [],
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd,
+ }),
}),
- }),
- );
- return harness.getOpenedOptions()!;
- }),
- );
+ );
+ return harness.getOpenedOptions()!;
+ }),
+ );
+ const open = openWith("");
yield* fileSystem.writeFileString(
remoteFile,
JSON.stringify({
@@ -3320,6 +3376,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
assert.isUndefined(restricted.allowDangerouslySkipPermissions);
yield* fileSystem.remove(remoteFile);
assert.equal((yield* open).permissionMode, "bypassPermissions");
+ const launchRestricted = yield* openWith(
+ `--settings '{"permissions":{"disableBypassPermissionsMode":"disable"}}'`,
+ );
+ assert.equal(launchRestricted.permissionMode, "auto");
+ assert.isUndefined(launchRestricted.allowDangerouslySkipPermissions);
yield* fileSystem.writeFileString(remoteFile, "{ invalid json");
assert.equal((yield* open).permissionMode, "auto");
yield* fileSystem.remove(remoteFile);
@@ -3740,12 +3801,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
settingsJson: string,
cwd = CLAUDE_TEST_RUNTIME_POLICY.cwd,
environment?: NodeJS.ProcessEnv,
+ launchArgs = "",
) =>
Effect.scoped(
Effect.gen(function* () {
yield* fileSystem.writeFileString(path.join(home, "settings.json"), settingsJson);
const harness = yield* makeWakeHarnessWithOptions({
- settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home, launchArgs },
...(environment === undefined ? {} : { environment }),
});
yield* harness.runtime.startTurn(
@@ -3769,6 +3831,16 @@ describe("ClaudeAdapterV2 background wake turns", () => {
assert.equal(yield* openedToolSearch('{"env":{"ENABLE_TOOL_SEARCH":"auto"}}'), "true");
assert.isUndefined(yield* openedToolSearch('{"env":{"ENABLE_TOOL_SEARCH":"false"}}'));
assert.isUndefined(yield* openedToolSearch("{}"));
+ // --settings beats local, project, and user settings.
+ assert.equal(
+ yield* openedToolSearch(
+ '{"env":{"ENABLE_TOOL_SEARCH":"auto"}}',
+ CLAUDE_TEST_RUNTIME_POLICY.cwd,
+ undefined,
+ `--settings '{"env":{"ENABLE_TOOL_SEARCH":"false"}}'`,
+ ),
+ "false",
+ );
// Claude Code keeps the local file at the repository root, the main checkout's root in a
// worktree, and that file beats the user's settings.
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 5644051d957..ed43fd36c47 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -573,6 +573,18 @@ export class ClaudeAppendSystemPromptMissingValueError extends Schema.TaggedErro
}
}
+export class ClaudeSettingsLaunchArgError extends Schema.TaggedError<ClaudeSettingsLaunchArgError>()(
+ "ClaudeSettingsLaunchArgError",
+ {
+ path: Schema.optional(Schema.String),
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return `Claude could not read the --settings launch argument${this.path === undefined ? "" : ` at ${this.path}`} as a JSON object. Fix it in the Claude launch arguments, then send the message again.`;
+ }
+}
+
export interface ClaudeAgentSdkQueryRunnerShape {
readonly allocateSessionId: Effect.Effect<string, ClaudeAgentSdkQueryRunnerError>;
readonly open: (
@@ -648,7 +660,7 @@ export interface ClaudeAgentSdkLoggedQueryOptions {
readonly cwd?: ClaudeAgentSdkQueryOptions["cwd"];
readonly allowedTools?: ClaudeAgentSdkQueryOptions["allowedTools"];
readonly disallowedTools?: ClaudeAgentSdkQueryOptions["disallowedTools"];
- readonly settings?: ClaudeAgentSdkQueryOptions["settings"];
+ readonly settingKeys?: ReadonlyArray<string>;
readonly effort?: ClaudeAgentSdkQueryOptions["effort"];
readonly includePartialMessages?: true;
readonly pathToClaudeCodeExecutable?: ClaudeAgentSdkQueryOptions["pathToClaudeCodeExecutable"];
@@ -787,7 +799,10 @@ export function loggedClaudeQueryOptions(
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
- ...(options.settings === undefined ? {} : { settings: options.settings }),
+ // Settings can carry the user's --settings values, such as an env block with credentials.
+ ...(typeof options.settings === "object" && options.settings !== null
+ ? { settingKeys: Object.keys(options.settings) }
+ : {}),
...(options.effort === undefined ? {} : { effort: options.effort }),
...(options.includePartialMessages === true ? { includePartialMessages: true } : {}),
...(options.pathToClaudeCodeExecutable === undefined
@@ -1431,6 +1446,8 @@ export function makeClaudeQueryOptions(input: {
"dangerously-skip-permissions": launchArgSkipPermissions,
"append-system-prompt": launchArgAppendSystemPrompt,
"append-system-prompt-file": _launchArgAppendSystemPromptFile,
+ // The SDK replaces this flag with options.settings, so it arrives read as sdkSettings.
+ settings: _launchArgSettings,
...extraArgs
} = input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags;
// Claude Code overwrites its CLI append text with the SDK's initialize
@@ -1579,6 +1596,42 @@ const readClaudeAppendSystemPromptFile = Effect.fnUntraced(function* (input: {
);
});
+const decodeClaudeLaunchArgSettings = Schema.decodeUnknownEffect(
+ fromLenientJson(Schema.Record(Schema.String, Schema.Unknown)),
+);
+
+/**
+ * Reads the --settings launch argument: a value starting with a brace is inline
+ * JSON, anything else is a file path relative to the cwd. makeClaudeQueryOptions
+ * merges the result beneath T3's own settings.
+ */
+const readClaudeLaunchArgSettings = Effect.fn("ClaudeAdapterV2.readLaunchArgSettings")(
+ function* (input: {
+ readonly settings: ClaudeSettings | undefined;
+ readonly cwd: string | null;
+ readonly fileSystem: FileSystem.FileSystem;
+ readonly path: Path.Path;
+ }) {
+ if (input.settings === undefined) return undefined;
+ const value = parseCliArgs(input.settings.launchArgs).flags.settings;
+ if (value === undefined) return undefined;
+ const trimmed = value?.trim() ?? "";
+ if (trimmed.length === 0) return yield* new ClaudeSettingsLaunchArgError({});
+ // The CLI also wants a closing brace, but then malformed JSON, secrets included, would
+ // become the file path in the error message.
+ if (trimmed.startsWith("{")) {
+ return (yield* decodeClaudeLaunchArgSettings(trimmed).pipe(
+ Effect.mapError((cause) => new ClaudeSettingsLaunchArgError({ cause })),
+ )) as ClaudeSdkSettings;
+ }
+ const filePath = input.path.resolve(input.cwd ?? ".", trimmed);
+ return (yield* input.fileSystem.readFileString(filePath).pipe(
+ Effect.flatMap(decodeClaudeLaunchArgSettings),
+ Effect.mapError((cause) => new ClaudeSettingsLaunchArgError({ path: filePath, cause })),
+ )) as ClaudeSdkSettings;
+ },
+);
+
export const CLAUDE_T3_MCP_TOOL_WILDCARD = "mcp__t3-code__*";
// Keep in sync with OrchestratorToolkit Tool.Readonly annotations; ClaudeAdapterV2.test.ts checks this.
@@ -2507,6 +2560,7 @@ const ClaudeBypassSettings = Schema.StructWithRest(
const decodeClaudeBypassSettings = Schema.decodeUnknownEffect(
fromLenientJson(ClaudeBypassSettings),
);
+const decodeClaudeLaunchArgBypassSettings = Schema.decodeUnknownEffect(ClaudeBypassSettings);
const ClaudePromptCacheTtl = Schema.Literals(["5m", "1h"]);
const decodeClaudePromptCacheTtl = Schema.decodeUnknownOption(ClaudePromptCacheTtl);
@@ -4279,12 +4333,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
serverManagedSettings: remote,
}),
);
- const cascade = claudeBypassAvailability(resolved.effective);
- const user = claudeBypassAvailability(home);
- const cached = claudeBypassAvailability(remote);
+ const launchArgSettings = yield* readClaudeLaunchArgSettings({
+ settings: adapterOptions.settings,
+ cwd,
+ fileSystem,
+ path,
+ });
+ const launch = yield* decodeClaudeLaunchArgBypassSettings(launchArgSettings ?? {});
+ const sources = [resolved.effective, home, remote, launch].map(claudeBypassAvailability);
return {
- bypassDisabled: cascade.bypassDisabled || user.bypassDisabled || cached.bypassDisabled,
- autoDisabled: cascade.autoDisabled || user.autoDisabled || cached.autoDisabled,
+ bypassDisabled: sources.some((source) => source.bypassDisabled),
+ autoDisabled: sources.some((source) => source.autoDisabled),
};
},
);
@@ -4357,10 +4416,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
if (path.dirname(directory) === directory) return cwd;
}
});
- // Settings env beats the process env, local over project over user, and a local file an older
- // Claude Code left in cwd applies under the root one. resolveSettings reads local from cwd only.
+ // Settings env beats the process env, --settings over local over project over user, and a local
+ // file an older Claude Code left in cwd applies under the root one. resolveSettings reads local
+ // from cwd only.
const resolveToolSearchOverride = Effect.fn("ClaudeAdapterV2.resolveToolSearchOverride")(
- function* (cwd: string | null) {
+ function* (cwd: string | null, launchArgSettings: ClaudeSdkSettings | undefined) {
+ const launchValue = launchArgSettings?.env?.ENABLE_TOOL_SEARCH;
+ if (typeof launchValue === "string") return claudeToolSearchOverride(launchValue);
const localDirectory = cwd === null ? null : yield* localSettingsDirectory(cwd);
const settingsFiles = [
...(cwd === null || localDirectory === null
@@ -9711,6 +9773,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
fileSystem,
path,
});
+ const launchArgSettings = yield* readClaudeLaunchArgSettings({
+ settings: adapterOptions.settings,
+ cwd: turnInput.runtimePolicy.cwd,
+ fileSystem,
+ path,
+ });
const closedExistingNativeThreadId = existing !== null ? existing.nativeThreadId : null;
if (existing !== null) {
yield* existing.query.close.pipe(Effect.ignore);
@@ -9728,7 +9796,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
turnInput.nativeThreadHasTurns ?? turnInput.providerTurnOrdinal > 1;
const shouldResume =
resumeSessionAt !== undefined || openedWithResume || hasPersistedProviderTurn;
- const toolSearchOverride = yield* resolveToolSearchOverride(turnInput.runtimePolicy.cwd);
+ const toolSearchOverride = yield* resolveToolSearchOverride(
+ turnInput.runtimePolicy.cwd,
+ launchArgSettings,
+ );
const queryOptions = makeClaudeQueryOptions({
modelSelection: turnInput.modelSelection,
nativeThreadId,
@@ -9737,6 +9808,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
cwd: turnInput.runtimePolicy.cwd,
attachmentsDir,
settings: adapterOptions.settings,
+ ...(launchArgSettings === undefined ? {} : { sdkSettings: launchArgSettings }),
environment: claudeQueryEnvironment(
adapterOptions.environment,
turnInput.appThread,
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
index 2e0eee3828e..94ba406b106 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
@@ -95,13 +95,14 @@ const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
/**
* Claude refuses these before it reads the prompt: replacing a process running background work,
- * launch arguments whose appended system prompt cannot be read, or MCP registration that never
- * answers while the query opens.
+ * launch arguments whose appended system prompt or settings cannot be read, or MCP registration
+ * that never answers while the query opens.
*/
const PROMPT_REFUSAL_TAGS = [
"ClaudeBackgroundWorkBlocksQueryReplacementError",
"ClaudeAppendSystemPromptFileError",
"ClaudeAppendSystemPromptMissingValueError",
+ "ClaudeSettingsLaunchArgError",
"ClaudeMcpRegistrationTimeoutError",
] as const;
diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts
index 4e24fcc945c..b0ac1ed8b93 100644
--- a/packages/provider-core/src/server/failure.ts
+++ b/packages/provider-core/src/server/failure.ts
@@ -105,6 +105,7 @@ function curatedCauseMessages(cause: unknown): {
case "ClaudeBackgroundWorkBlocksQueryReplacementError":
case "ClaudeAppendSystemPromptFileError":
case "ClaudeAppendSystemPromptMissingValueError":
+ case "ClaudeSettingsLaunchArgError":
case "ClaudeMcpRegistrationTimeoutError":
case "CursorModelUnavailableError":
return { known: stringField(cause, "message"), category: categoryMessage() };