From 06d5bc56bc7c31ec15878c953e63fc28ff9cfa22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Barreiro?= <52393857+BarreiroT@users.noreply.github.com> Date: Sat, 19 Jul 2025 21:41:21 +0200 Subject: [PATCH] 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 --- .changeset/popular-flies-explode.md | 5 + docs/provider-config/claude-code.mdx | 22 +-- src/integrations/claude-code/run.test.ts | 163 +++++++++++++++++++++++ src/integrations/claude-code/run.ts | 80 +++++++---- 4 files changed, 226 insertions(+), 44 deletions(-) create mode 100644 .changeset/popular-flies-explode.md create mode 100644 src/integrations/claude-code/run.test.ts diff --git a/.changeset/popular-flies-explode.md b/.changeset/popular-flies-explode.md new file mode 100644 index 00000000..5aa9feb4 --- /dev/null +++ b/.changeset/popular-flies-explode.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Introduce Claude Code support on Windows and fix E2BIG issues diff --git a/docs/provider-config/claude-code.mdx b/docs/provider-config/claude-code.mdx index 8f47abae..a05066bc 100644 --- a/docs/provider-config/claude-code.mdx +++ b/docs/provider-config/claude-code.mdx @@ -35,26 +35,8 @@ First, you'll need to install and authenticate Claude Code on your system:
-On Windows, Cline supports integrating with Claude Code through WSL. -Windows doesn't support long commands, and Claude Code only accepts the system prompt through a flag, which means we can't properly prompt Claude through Claude Code. Anthropic is [working on a workaround to streamline this](https://github.com/anthropics/claude-code/issues/3411). - -1. **Make sure you have WSL set-up**. You can follow [this](https://code.visualstudio.com/docs/remote/wsl#_installation) guide to do it. - -2. **Open VSCode from WSL** and verify it's properly set-up. You should see an indicator in the bottom left that says "WSL". You can find an image of the indicator [here](https://code.visualstudio.com/docs/remote/wsl#_from-the-wsl-terminal). - -3. Install Cline within WSL and make sure it shows the following: - - - Indicator that an extension is installed on WSL - - -4. Clone or [move](https://stackoverflow.com/a/42586455) your project over to WSL - -5. Follow the [instructions on how to set up Claude Code normally](#setup), but from the WSL terminal. - + Anthropic introduced full support for Claude Code on Windows. Follow the [instructions on how to set up Claude Code + normally](#setup) and make sure you have the latest Claude Code and Cline versions. ### Finding your Claude Code path diff --git a/src/integrations/claude-code/run.test.ts b/src/integrations/claude-code/run.test.ts new file mode 100644 index 00000000..09004428 --- /dev/null +++ b/src/integrations/claude-code/run.test.ts @@ -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 + }) + }) + }) +}) diff --git a/src/integrations/claude-code/run.ts b/src/integrations/claude-code/run.ts index 140ac966..7468b632 100644 --- a/src/integrations/claude-code/run.ts +++ b/src/integrations/claude-code/run.ts @@ -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 { - 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} */