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:
1 parent
b1d82e163c
commit
06d5bc56bc
4 files changed
+226
-44
No files matched your search
@@ -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}
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user