Skip to content

Build your personal knowledge base with Trilium Notes

fix(llm): resolve and spawn Claude Code .cmd shim on Windows

Elian Doranc1ed4fd78466
diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.ts
index e8fd5d893c..695050ab16 100644
--- a/apps/server/src/services/llm/providers/claude_agent.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.ts
@@ -20,11 +20,12 @@
* with every built-in Claude Code tool (file access, bash, …) disabled.
*/
-import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDKMessage, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
+import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDKMessage, type SDKUserMessage, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";
import type { LlmFilePart, LlmImagePart, LlmMessage, LlmMessagePart, LlmStreamChunk, LlmTextAttachmentPart } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
import { encodeBase64 } from "@triliumnext/core/src/services/utils/binary.js";
+import { spawn as nodeSpawn } from "child_process";
import { createHash } from "crypto";
import fs from "fs";
import path from "path";
@@ -444,10 +445,11 @@ export class ClaudeAgentProvider implements LlmProvider {
const builtinTools = config.enableWebSearch ? ["WebSearch", "WebFetch"] : [];
const allowedTools = [...builtinTools];
+ const binaryPath = await resolveClaudeBinaryPath();
const options: AgentOptions = {
// Bring-your-own-binary: the SDK's bundled native binary is stripped
// at install time; drive the user's own installed Claude Code CLI.
- pathToClaudeCodeExecutable: await resolveClaudeBinaryPath(),
+ pathToClaudeCodeExecutable: binaryPath,
cwd: getAgentCwd(),
tools: builtinTools,
settingSources: [],
@@ -462,6 +464,18 @@ export class ClaudeAgentProvider implements LlmProvider {
: { type: "disabled" }
};
+ // On Windows the resolved binary is typically a .cmd batch file (npm
+ // shim). Node's spawn() cannot execute .cmd files directly — it must
+ // delegate to cmd.exe via `shell: true`. The SDK spawns without a
+ // shell, so we override the spawn to add it.
+ if (process.platform === "win32" && binaryPath.endsWith(".cmd")) {
+ options.spawnClaudeCodeProcess = ({ command, args, cwd, env, signal }) => {
+ return nodeSpawn(command, args, {
+ cwd, env, signal, shell: true, stdio: "pipe"
+ }) as unknown as SpawnedProcess;
+ };
+ }
+
if (areNoteToolsAvailable(config)) {
// In-process MCP: hand the agent Trilium's own MCP server instance
// (the same one createMcpServer builds for the /mcp HTTP endpoint,
diff --git a/apps/server/src/services/llm/providers/claude_binary.spec.ts b/apps/server/src/services/llm/providers/claude_binary.spec.ts
index cfa50df868..c7d869d370 100644
--- a/apps/server/src/services/llm/providers/claude_binary.spec.ts
+++ b/apps/server/src/services/llm/providers/claude_binary.spec.ts
@@ -115,6 +115,18 @@ describe("resolveClaudeBinaryPath", () => {
await expect(resolveClaudeBinaryPath()).resolves.toBe(hit);
});
+ it("skips the bare extensionless `claude` on Windows (it is a POSIX bash script)", async () => {
+ stubPlatform("win32");
+ const dir = path.join("npm", "prefix");
+ // Only the bare `claude` exists — no .cmd/.exe/.bat.
+ const bashScript = path.join(dir, "claude");
+ process.env.PATH = dir;
+ existsSyncMock.mockImplementation((candidate: string) => candidate === bashScript);
+
+ await expect(resolveClaudeBinaryPath()).rejects.toThrow(/Claude Code CLI not found/);
+ expect(execFileMock).not.toHaveBeenCalled();
+ });
+
it("rejects with install instructions when `claude` is nowhere on PATH (or PATH is unset)", async () => {
stubPlatform("linux");
delete process.env.PATH;
diff --git a/apps/server/src/services/llm/providers/claude_binary.ts b/apps/server/src/services/llm/providers/claude_binary.ts
index a5e32d443d..c5bbfde3af 100644
--- a/apps/server/src/services/llm/providers/claude_binary.ts
+++ b/apps/server/src/services/llm/providers/claude_binary.ts
@@ -54,7 +54,14 @@ async function probeBinary(): Promise<string> {
// would freeze the whole server for up to the 15 s timeout.
let version: string;
try {
- version = (await execFileAsync(binary, ["--version"], { timeout: 15000, encoding: "utf8" })).stdout.trim();
+ version = (await execFileAsync(binary, ["--version"], {
+ timeout: 15000,
+ encoding: "utf8",
+ // On Windows the resolved binary is typically a .cmd batch file
+ // (npm shim); Node's execFile cannot run .cmd files directly —
+ // it must delegate to cmd.exe via `shell: true`.
+ shell: process.platform === "win32"
+ })).stdout.trim();
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
throw new Error(`Found Claude Code at "${binary}" but it failed to run (${detail}). Ensure it is installed correctly and that you've run \`claude /login\` on the machine running the Trilium server.`);
@@ -82,8 +89,11 @@ function locateBinary(): string {
}
function findOnPath(binary: string): string | undefined {
- // Windows resolves executables via PATHEXT; on POSIX the bare name suffices.
- const extensions = process.platform === "win32" ? ["", ".cmd", ".exe", ".bat"] : [""];
+ // On Windows, npm-installed packages create a bare extensionless file (a
+ // POSIX bash script for Git Bash/WSL) alongside the real .cmd/.exe shims.
+ // The bash script can't be executed by Node's execFile/spawn, so we must
+ // try the Windows-native extensions first and skip the bare name entirely.
+ const extensions = process.platform === "win32" ? [".cmd", ".exe", ".bat"] : [""];
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
if (!dir) {
continue;