Use --system-prompt-file to pass the system prompt to Claude Code (#5024)

* Pass the system prompt through a file when using Claude Code

* Support older versions and return better errors

* Add tests

* Add changeset

* Remove outdated docs

* Use a unique file name and clean the file

* Address comments
This commit is contained in:
Tomás Barreiro authored and GitHub committed 2025-07-19 12:41:21 -07:00
1 parent b1d82e163c
commit 06d5bc56bc
4 files changed
+226 -44

No files matched your search

+163
View File
@@ -0,0 +1,163 @@
import { expect } from "chai"
import proxyquire from "proxyquire"
import path from "path"
import sinon from "sinon"
const createMockProcess = () => {
const mockProcess = {
stdin: {
write: sinon.fake(),
end: sinon.fake(),
},
stdout: {
on: sinon.fake(),
resume: sinon.fake(),
},
stderr: {
on: sinon.fake(() => {}),
},
on: sinon.fake((event, callback) => {
if (event === "close") {
setImmediate(() => callback(0))
}
if (event === "error") {
}
}),
killed: false,
kill: sinon.fake(),
exitCode: 0,
then: (onResolve: (value: any) => void) => {
setImmediate(() => onResolve({ exitCode: 0 }))
return Promise.resolve({ exitCode: 0 })
},
catch: () => Promise.resolve({ exitCode: 0 }),
finally: (callback: () => void) => {
setImmediate(callback)
return Promise.resolve({ exitCode: 0 })
},
}
return mockProcess
}
const createMockReadlineInterface = () => {
const mockInterface = {
async *[Symbol.asyncIterator]() {
// Simulate Claude CLI JSON output - yield a few chunks then end
yield '{"type":"text","text":"Hello"}'
yield '{"type":"text","text":" world"}'
// Iterator ends naturally when function returns
return
},
close: sinon.fake(),
}
return mockInterface
}
const mockExeca = sinon.fake((...args) => {
return createMockProcess()
})
let os = "darwin"
const { MAX_SYSTEM_PROMPT_LENGTH, runClaudeCode } = proxyquire("./run", {
"@/utils/path": {
getCwd: () => Promise.resolve(path.resolve("./")),
},
"node:os": {
platform: () => os,
},
execa: {
execa: mockExeca,
},
readline: {
createInterface: createMockReadlineInterface,
},
})
describe("Claude Code Integration", () => {
const scriptPath = "echo"
afterEach(() => {
sinon.restore()
})
const itCallsTheScriptWithAFile = (systemPrompt: string) => {
it("calls the script using with a file", async () => {
const cProcess = runClaudeCode({
systemPrompt,
messages: [],
modelId: "test",
path: scriptPath,
})
const chunks: string[] = []
for await (const chunk of cProcess) {
chunks.push(chunk)
}
expect(chunks).to.have.length(2)
const lastExecaCall = mockExeca.lastCall
const params = lastExecaCall.args[1]
expect(params).to.not.be.null
expect(params.includes("--system-prompt-file")).to.be.true
expect(params.includes("--system-prompt")).to.be.false
})
}
describe("when it's running on Windows", () => {
beforeEach(() => {
os = "win32"
})
describe("when the system prompt is longer than the MAX_SYSTEM_PROMPT_LENGTH", () => {
const SYSTEM_PROMPT = "a".repeat(MAX_SYSTEM_PROMPT_LENGTH * 1.2)
itCallsTheScriptWithAFile(SYSTEM_PROMPT)
})
describe("when the system prompt is shorter than the MAX_SYSTEM_PROMPT_LENGTH", () => {
const SYSTEM_PROMPT = "a".repeat(MAX_SYSTEM_PROMPT_LENGTH / 2)
itCallsTheScriptWithAFile(SYSTEM_PROMPT)
})
})
describe("when it's not running on Windows", () => {
beforeEach(() => {
os = "darwin"
})
describe("when the system prompt is longer than the MAX_SYSTEM_PROMPT_LENGTH", () => {
const SYSTEM_PROMPT = "a".repeat(MAX_SYSTEM_PROMPT_LENGTH * 1.2)
itCallsTheScriptWithAFile(SYSTEM_PROMPT)
})
describe("when the system prompt is shorter than the MAX_SYSTEM_PROMPT_LENGTH", () => {
const SYSTEM_PROMPT = "a".repeat(MAX_SYSTEM_PROMPT_LENGTH / 2)
it("calls the script without a file", async () => {
const cProcess = runClaudeCode({
systemPrompt: SYSTEM_PROMPT,
messages: [],
modelId: "test",
path: scriptPath,
})
const chunks: string[] = []
for await (const chunk of cProcess) {
chunks.push(chunk)
}
expect(chunks).to.have.length(2)
const lastExecaCall = mockExeca.lastCall
const params = lastExecaCall.args[1]
expect(params).to.not.be.null
expect(params.includes("--system-prompt-file")).to.be.false
expect(params.includes("--system-prompt")).to.be.true
})
})
})
})
+56 -24
View File
@@ -1,15 +1,20 @@
import { getCwd } from "@/utils/path"
import os from "node:os"
import path from "node:path"
import fs from "node:fs/promises"
import type Anthropic from "@anthropic-ai/sdk"
import { execa } from "execa"
import readline from "readline"
import { ClaudeCodeMessage } from "./types"
import crypto from "node:crypto"
type ClaudeCodeOptions = {
systemPrompt: string
messages: Anthropic.Messages.MessageParam[]
path?: string
modelId?: string
modelId: string
thinkingBudgetTokens?: number
shouldUseFile?: boolean
}
type ProcessState = {
@@ -19,30 +24,46 @@ type ProcessState = {
exitCode: number | null
}
// The maximum argument length is longer than this,
// but environment variables and other factors can reduce it.
// We use a conservative limit to avoid issues while supporting older Claude Code versions that don't support file input.
export const MAX_SYSTEM_PROMPT_LENGTH = 65536
export async function* runClaudeCode(options: ClaudeCodeOptions): AsyncGenerator<ClaudeCodeMessage | string> {
const process = runProcess(options, await getCwd())
const isSystemPromptTooLong = options.systemPrompt.length > MAX_SYSTEM_PROMPT_LENGTH
const uniqueId = crypto.randomUUID()
const tempFilePath = path.join(os.tmpdir(), `cline-system-prompt-${uniqueId}.txt`)
if (os.platform() === "win32" || isSystemPromptTooLong) {
// Use a temporary file to prevent ENAMETOOLONG and E2BIG errors
// https://github.com/anthropics/claude-code/issues/3411#issuecomment-3082068547
await fs.writeFile(tempFilePath, options.systemPrompt, "utf8")
options.systemPrompt = tempFilePath
options.shouldUseFile = true
}
const cProcess = runProcess(options, await getCwd())
const rl = readline.createInterface({
input: process.stdout,
input: cProcess.stdout,
})
try {
const processState: ProcessState = {
error: null,
stderrLogs: "",
exitCode: null,
partialData: null,
}
const processState: ProcessState = {
error: null,
stderrLogs: "",
exitCode: null,
partialData: null,
}
process.stderr.on("data", (data) => {
try {
cProcess.stderr.on("data", (data) => {
processState.stderrLogs += data.toString()
})
process.on("close", (code) => {
cProcess.on("close", (code) => {
processState.exitCode = code
})
process.on("error", (err) => {
cProcess.on("error", (err) => {
processState.error = err
})
@@ -68,7 +89,7 @@ export async function* runClaudeCode(options: ClaudeCodeOptions): AsyncGenerator
yield processState.partialData
}
const { exitCode } = await process
const { exitCode } = await cProcess
if (exitCode !== null && exitCode !== 0) {
const errorOutput = processState.error?.message || processState.stderrLogs?.trim()
throw new Error(
@@ -78,6 +99,12 @@ export async function* runClaudeCode(options: ClaudeCodeOptions): AsyncGenerator
} catch (err) {
console.error(`Error during Claude Code execution:`, err)
if (processState.stderrLogs.includes("unknown option '--system-prompt-file'")) {
throw new Error(`The Claude Code executable is outdated. Please update it to the latest version.`, {
cause: err,
})
}
if (err instanceof Error) {
if (err.message.includes("ENOENT")) {
throw new Error(
@@ -113,15 +140,19 @@ Anthropic is aware of this issue and is considering a fix: https://github.com/an
if (startOfCommand !== -1) {
const messageWithoutCommand = err.message.slice(0, startOfCommand).trim()
throw new Error(messageWithoutCommand, { cause: err })
throw new Error(`${messageWithoutCommand}\n${processState.stderrLogs?.trim()}`, { cause: err })
}
}
throw err
} finally {
rl.close()
if (!process.killed) {
process.kill()
if (!cProcess.killed) {
cProcess.kill()
}
if (options.shouldUseFile) {
fs.unlink(tempFilePath).catch(console.error)
}
}
}
@@ -151,12 +182,14 @@ const CLAUDE_CODE_TIMEOUT = 600000 // 10 minutes
// https://github.com/sindresorhus/execa/blob/main/docs/api.md#optionsmaxbuffer
const BUFFER_SIZE = 20_000_000 // 20 MB
function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetTokens }: ClaudeCodeOptions, cwd: string) {
function runProcess(
{ systemPrompt, messages, path, modelId, thinkingBudgetTokens, shouldUseFile }: ClaudeCodeOptions,
cwd: string,
) {
const claudePath = path?.trim() || "claude"
const args = [
"-p",
"--system-prompt",
shouldUseFile ? "--system-prompt-file" : "--system-prompt",
systemPrompt,
"--verbose",
"--output-format",
@@ -166,12 +199,11 @@ function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetToken
// Cline will handle recursive calls
"--max-turns",
"1",
"--model",
modelId,
"-p",
]
if (modelId) {
args.push("--model", modelId)
}
/**
* @see {@link https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables}
*/