Skip to content
TypeScript

fix(server): Claude append-system-prompt launch arguments reach the model (#20413)

Victor Vogel8c51e4ea7ceb
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 9af2df087ec..20bf645bdf9 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -1211,6 +1211,156 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => {
);
});
+describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
+ const startTurnWithLaunchArgs = Effect.fnUntraced(function* (launchArgs: string, cwd: string) {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const opened: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOptions> = [];
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, launchArgs },
+ environment: {},
+ attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-" }),
+ fileSystem,
+ path: yield* Path.Path,
+ crypto: yield* Crypto.Crypto,
+ idAllocator: yield* IdAllocator.IdAllocatorV2,
+ queryRunner: {
+ allocateSessionId: Effect.succeed("native-thread-claude-append-file"),
+ open: (input) =>
+ Effect.sync(() => {
+ opened.push(input.options);
+ return {
+ messages: Stream.never,
+ offer: () => Effect.void,
+ setModel: () => Effect.void,
+ applyFlagSettings: () => Effect.void,
+ setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
+ stopTask: () => Effect.void,
+ interrupt: Effect.void,
+ close: Effect.void,
+ };
+ }),
+ forkSession: () => Effect.die("unused"),
+ subagentLaunchToolUseId: () => Effect.succeed(null),
+ assertComplete: Effect.void,
+ },
+ });
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd,
+ });
+ const threadId = ThreadId.make("thread-claude-append-file");
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-claude-append-file"),
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ runtimePolicy,
+ });
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ runtimePolicy,
+ });
+ const exit = yield* runtime
+ .startTurn(
+ makeClaudeTestTurnInput({
+ threadId,
+ providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-claude-append-file"),
+ text: "What is the sentinel?",
+ attachments: [],
+ runtimePolicy,
+ }),
+ )
+ .pipe(Effect.exit);
+ return { exit, opened };
+ });
+
+ const appendSystemPrompt = (options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined) =>
+ (options?.systemPrompt as { readonly append?: string } | undefined)?.append;
+
+ it.effect("sends append launch arguments to Claude after the T3 instructions", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
+ yield* fileSystem.writeFileString(NodePath.join(cwd, "rules.md"), "File sentinel\n");
+ const plain = yield* startTurnWithLaunchArgs("", cwd);
+ const { exit, opened } = yield* startTurnWithLaunchArgs(
+ '--append-system-prompt "Inline sentinel" --append-system-prompt-file rules.md --system-prompt Replacement',
+ cwd,
+ );
+ assert.isTrue(Exit.isSuccess(exit));
+ assert.lengthOf(opened, 1);
+ assert.equal(
+ appendSystemPrompt(opened[0]),
+ `${appendSystemPrompt(plain.opened[0])}\n\nFile sentinel\n\nInline sentinel`,
+ );
+ assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt"]);
+ assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt-file"]);
+ assert.equal(opened[0]!.extraArgs?.["system-prompt"], "Replacement");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ ),
+ );
+
+ it.effect.each([
+ [
+ "--append-system-prompt-file missing.md",
+ (cwd: string) =>
+ new ClaudeAdapterV2.ClaudeAppendSystemPromptFileError({
+ path: NodePath.join(cwd, "missing.md"),
+ }).message,
+ ],
+ [
+ "--append-system-prompt-file",
+ () =>
+ new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
+ flag: "--append-system-prompt-file",
+ }).message,
+ ],
+ [
+ "--append-system-prompt-file=",
+ () =>
+ new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
+ flag: "--append-system-prompt-file",
+ }).message,
+ ],
+ [
+ "--append-system-prompt",
+ () =>
+ new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
+ flag: "--append-system-prompt",
+ }).message,
+ ],
+ ] as const)("fails the turn before opening Claude for %s", ([launchArgs, expectedMessage]) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
+ const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
+ assert.lengthOf(opened, 0);
+ assert.isTrue(Exit.isFailure(exit));
+ if (!Exit.isFailure(exit)) return;
+ assert.equal(
+ makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message,
+ expectedMessage(cwd),
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ ),
+ );
+});
+
describe("ClaudeAdapterV2 approval cancellation", () => {
it.effect("observes an approval signal that was already aborted", () =>
Effect.gen(function* () {
@@ -13815,6 +13965,136 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ it.effect("keeps the live process when its replacement cannot read the append file", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-claude-append-replacement-",
+ });
+ const appendFile = NodePath.join(cwd, "rules.md");
+ yield* fileSystem.writeFileString(appendFile, "File sentinel\n");
+ const processQueues: Array<Queue.Queue<SDKMessage>> = [];
+ let closes = 0;
+ const firstTurnTerminal = yield* Deferred.make<void>();
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
+ settings: {
+ ...DEFAULT_CLAUDE_SETTINGS,
+ launchArgs: "--append-system-prompt-file rules.md",
+ },
+ environment: {},
+ attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-claude-append-replacement-attachments-",
+ }),
+ fileSystem,
+ path: yield* Path.Path,
+ crypto: yield* Crypto.Crypto,
+ idAllocator: yield* IdAllocator.IdAllocatorV2,
+ continuationRequests: { offer: () => Effect.void },
+ queryRunner: {
+ allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
+ open: () =>
+ Effect.gen(function* () {
+ const sdkMessages = yield* Queue.unbounded<SDKMessage>();
+ processQueues.push(sdkMessages);
+ return {
+ messages: Stream.fromQueue(sdkMessages),
+ offer: () => Effect.void,
+ setModel: () => Effect.void,
+ applyFlagSettings: () => Effect.void,
+ setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
+ stopTask: () => Effect.void,
+ interrupt: Effect.void,
+ close: Effect.sync(() => {
+ closes += 1;
+ }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))),
+ };
+ }),
+ forkSession: () => Effect.die("unused forkSession"),
+ subagentLaunchToolUseId: () => Effect.succeed(null),
+ assertComplete: Effect.void,
+ },
+ });
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd,
+ });
+ const threadId = ThreadId.make("thread-claude-append-replacement");
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-claude-append-replacement"),
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ runtimePolicy,
+ });
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ runtimePolicy,
+ });
+ yield* runtime.events.pipe(
+ Stream.runForEach((event) =>
+ event.type === "turn.terminal"
+ ? Deferred.succeed(firstTurnTerminal, undefined)
+ : Effect.void,
+ ),
+ Effect.forkScoped,
+ );
+ const now = yield* DateTime.now;
+
+ yield* runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId,
+ providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-append-replacement-a"),
+ text: "What is the sentinel?",
+ attachments: [],
+ runtimePolicy,
+ }),
+ );
+ yield* Queue.offer(
+ processQueues[0]!,
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000a01",
+ result: "File sentinel",
+ }),
+ );
+ yield* Deferred.await(firstTurnTerminal);
+
+ yield* fileSystem.remove(appendFile);
+ // A thinking change cannot apply live, so this turn must replace the process.
+ const refused = yield* runtime
+ .startTurn(
+ makeClaudeTestTurnInput({
+ threadId,
+ providerThread: { ...providerThread, status: "active" },
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-append-replacement-b"),
+ text: "Switch model.",
+ attachments: [],
+ providerTurnOrdinal: 2,
+ modelSelection: CLAUDE_TEST_RESTART_MODEL_SELECTION,
+ runtimePolicy,
+ }),
+ )
+ .pipe(Effect.flip);
+ assert.equal(
+ makeProviderFailure({ cause: refused, class: "provider_error" }).message,
+ new ClaudeAdapterV2.ClaudeAppendSystemPromptFileError({ path: appendFile }).message,
+ );
+ assert.lengthOf(processQueues, 1);
+ assert.equal(closes, 0);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ ),
+ );
+
it.effect(
"keeps the process and its roster when a model change meets a running background shell",
() =>
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 704f57e91a9..9ca51fc27ee 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -517,6 +517,27 @@ export class ClaudeBackgroundWorkBlocksQueryReplacementError extends Schema.Tagg
}
}
+export class ClaudeAppendSystemPromptFileError extends Schema.TaggedError<ClaudeAppendSystemPromptFileError>()(
+ "ClaudeAppendSystemPromptFileError",
+ {
+ path: Schema.String,
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return `Claude could not read the --append-system-prompt-file launch argument at ${this.path}. Fix the path in the Claude launch arguments, then send the message again.`;
+ }
+}
+
+export class ClaudeAppendSystemPromptMissingValueError extends Schema.TaggedError<ClaudeAppendSystemPromptMissingValueError>()(
+ "ClaudeAppendSystemPromptMissingValueError",
+ { flag: Schema.Literals(["--append-system-prompt", "--append-system-prompt-file"]) },
+) {
+ override get message(): string {
+ return `The ${this.flag} launch argument has no ${this.flag === "--append-system-prompt" ? "text" : "file path"}. Add it after the flag in the Claude launch arguments, then send the message again.`;
+ }
+}
+
export interface ClaudeAgentSdkQueryRunnerShape {
readonly allocateSessionId: Effect.Effect<string, ClaudeAgentSdkQueryRunnerError>;
readonly open: (
@@ -1238,13 +1259,23 @@ export function makeClaudeQueryOptions(input: {
readonly onUserDialog?: ClaudeQueryOptions["onUserDialog"];
readonly supportedDialogKinds?: ClaudeQueryOptions["supportedDialogKinds"];
readonly allowDangerouslySkipPermissions?: boolean;
+ readonly appendSystemPromptFileText?: string;
}): ClaudeAgentSdkQueryOptions {
const compiledSelection = compileClaudeModelSelection(input.modelSelection);
const {
"permission-mode": launchArgPermissionMode,
"dangerously-skip-permissions": launchArgSkipPermissions,
+ "append-system-prompt": launchArgAppendSystemPrompt,
+ "append-system-prompt-file": _launchArgAppendSystemPromptFile,
...extraArgs
} = input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags;
+ // Claude Code overwrites its CLI append text with the SDK's initialize
+ // appendSystemPrompt, so launch-argument text has to travel in that value.
+ // The CLI puts file text before inline text and trims one trailing newline.
+ const launchAppendSystemPrompt = [
+ input.appendSystemPromptFileText?.replace(/\r?\n$/, ""),
+ launchArgAppendSystemPrompt,
+ ].filter((text): text is string => typeof text === "string" && text.length > 0);
const requestThinkingSummaries =
compiledSelection.settings.alwaysThinkingEnabled !== false &&
extraArgs["thinking-display"] !== "omitted";
@@ -1320,9 +1351,11 @@ export function makeClaudeQueryOptions(input: {
systemPrompt: {
type: "preset" as const,
preset: "claude_code" as const,
- append:
+ append: [
buildRuntimeInstructions({ harness: "Claude Code" }) +
- (input.mcpServers === undefined ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS),
+ (input.mcpServers === undefined ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS),
+ ...launchAppendSystemPrompt,
+ ].join("\n\n"),
},
...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),
};
@@ -1335,6 +1368,43 @@ export function makeClaudeQueryOptions(input: {
return input.cwd === null ? withDirectories : { ...withDirectories, cwd: input.cwd };
}
+/**
+ * Checks the append launch arguments the way the Claude CLI would and reads
+ * the file relative to the process cwd. makeClaudeQueryOptions folds these
+ * flags out of extraArgs, so a value the CLI would have rejected has to be
+ * rejected here or it silently disappears.
+ */
+const readClaudeAppendSystemPromptFile = Effect.fnUntraced(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 flags = parseCliArgs(input.settings.launchArgs).flags;
+ // parseCliArgs gives null for a flag with no following value. An explicit
+ // `--append-system-prompt ""` is a value the CLI accepts, so it stays.
+ if (flags["append-system-prompt"] === null) {
+ return yield* new ClaudeAppendSystemPromptMissingValueError({
+ flag: "--append-system-prompt",
+ });
+ }
+ const file = flags["append-system-prompt-file"];
+ if (file === undefined) return undefined;
+ // `--append-system-prompt-file=` is "" and names no file either.
+ if (file === null || file === "") {
+ return yield* new ClaudeAppendSystemPromptMissingValueError({
+ flag: "--append-system-prompt-file",
+ });
+ }
+ const filePath = input.path.resolve(input.cwd ?? ".", file);
+ return yield* input.fileSystem
+ .readFileString(filePath)
+ .pipe(
+ Effect.mapError((cause) => new ClaudeAppendSystemPromptFileError({ path: filePath, cause })),
+ );
+});
+
export const CLAUDE_T3_MCP_TOOL_WILDCARD = "mcp__t3-code__*";
// Must stay in sync with the Tool.Readonly annotations on OrchestratorToolkit;
@@ -9047,6 +9117,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
return yield* new ClaudeBackgroundWorkBlocksQueryReplacementError();
}
+ // Read before closing the live process so a bad path leaves it running.
+ const appendSystemPromptFileText = yield* readClaudeAppendSystemPromptFile({
+ 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);
@@ -9091,6 +9168,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
canUseTool,
onUserDialog,
supportedDialogKinds: ["resume_return"],
+ ...(appendSystemPromptFileText === undefined ? {} : { appendSystemPromptFileText }),
});
const querySession = yield* queryRunner
.open({
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
index 1f57b2a8a40..8cdcbaff204 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
@@ -66,9 +66,18 @@ export class ProviderTurnStartError extends Schema.TaggedError<ProviderTurnStart
const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
-/** Claude refuses to replace a process running background work before it reads the prompt. */
+/**
+ * Claude refuses these before it reads the prompt: replacing a process running background work,
+ * or launch arguments whose appended system prompt cannot be read.
+ */
+const PROMPT_REFUSAL_TAGS = [
+ "ClaudeBackgroundWorkBlocksQueryReplacementError",
+ "ClaudeAppendSystemPromptFileError",
+ "ClaudeAppendSystemPromptMissingValueError",
+] as const;
+
const refusedBeforePrompt = (error: unknown): boolean =>
- Predicate.isTagged(error, "ClaudeBackgroundWorkBlocksQueryReplacementError") ||
+ PROMPT_REFUSAL_TAGS.some((tag) => Predicate.isTagged(error, tag)) ||
(Predicate.hasProperty(error, "cause") && refusedBeforePrompt(error.cause));
export interface ProviderTurnStartServiceV2Shape {
diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
index 7f2e9cfabbf..8d9cd5532e0 100644
--- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
@@ -35,6 +35,8 @@ import * as SqlClient from "effect/sql/SqlClient";
import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import { CommandPolicyCapabilityUnsupportedError } from "../CommandPolicy.ts";
import {
+ ClaudeAppendSystemPromptFileError,
+ ClaudeAppendSystemPromptMissingValueError,
ClaudeBackgroundWorkBlocksQueryReplacementError,
ClaudeProviderCapabilitiesV2,
} from "../Adapters/ClaudeAdapterV2.ts";
@@ -103,6 +105,7 @@ function makeTestAdapter(input: {
readonly injectedHistory?: Ref.Ref<ReadonlyArray<unknown>>;
readonly failStartOnce?: Ref.Ref<boolean>;
readonly refuseStarts?: Ref.Ref<number>;
+ readonly refusalCause?: unknown;
readonly failInjectionOnce?: Ref.Ref<boolean>;
readonly nativeThreadGeneration?: Ref.Ref<number>;
readonly failResume?: boolean;
@@ -235,7 +238,8 @@ function makeTestAdapter(input: {
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
runId: turnInput.runId,
- cause: new ClaudeBackgroundWorkBlocksQueryReplacementError(),
+ cause:
+ input.refusalCause ?? new ClaudeBackgroundWorkBlocksQueryReplacementError(),
});
yield* Effect.yieldNow;
yield* Ref.update(input.capturedTurns, (turns) => [
@@ -1196,7 +1200,14 @@ describe("orchestration v2 provider switching", () => {
),
);
- it.live("keeps the native session after turns refused before reaching the provider", () =>
+ it.live.each([
+ ["background work", new ClaudeBackgroundWorkBlocksQueryReplacementError()],
+ ["an unreadable append file", new ClaudeAppendSystemPromptFileError({ path: "missing.md" })],
+ [
+ "a missing append value",
+ new ClaudeAppendSystemPromptMissingValueError({ flag: "--append-system-prompt" }),
+ ],
+ ] as const)("keeps the native session after turns refused for %s", ([, refusalCause]) =>
Effect.scoped(
Effect.gen(function* () {
const cwd = yield* checkpointWorkspace("refused-start-keeps-native");
@@ -1212,6 +1223,7 @@ describe("orchestration v2 provider switching", () => {
responseByRunOrdinal: {},
capturedTurns,
refuseStarts,
+ refusalCause,
nativeThreadGeneration: generation,
}),
]);
diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts
index 94441085a2a..68f9ef675e4 100644
--- a/packages/provider-core/src/server/failure.ts
+++ b/packages/provider-core/src/server/failure.ts
@@ -74,6 +74,8 @@ function causeMessage(cause: unknown): string | undefined {
case "ContextHandoffBudgetError":
return new ContextHandoffBudgetError().message;
case "ClaudeBackgroundWorkBlocksQueryReplacementError":
+ case "ClaudeAppendSystemPromptFileError":
+ case "ClaudeAppendSystemPromptMissingValueError":
case "CursorModelUnavailableError":
return stringField(cause, "message");
case "ContextHandoffDeliveryUncertainError":