Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(llm): resolve the agent CLIs via the login shell
Elian Doran1709f770590f
diff --git a/apps/server/src/services/llm/providers/binary_lookup.spec.ts b/apps/server/src/services/llm/providers/binary_lookup.spec.tsnew file mode 100644index 0000000000..f8550c780e--- /dev/null+++ b/apps/server/src/services/llm/providers/binary_lookup.spec.ts@@ -0,0 +1,150 @@+import path from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// The login-shell read drives the real execFile through util.promisify's+// callback fallback, so the mock receives (shell, args, options, callback).+type ExecFileCallback = (err: Error | null, result?: { stdout: string; stderr: string }) => void;+const execFileMock = vi.hoisted(() => vi.fn<(binary: string, args: string[], options: object, cb: ExecFileCallback) => void>());+vi.mock("child_process", () => ({ execFile: execFileMock }));++const existsSyncMock = vi.hoisted(() => vi.fn((_path: string) => true));+vi.mock("fs", () => ({ existsSync: existsSyncMock }));++vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: vi.fn(), error: vi.fn() }) }));++const { extractPathFromShellEnv, findOnPath, resetLoginShellPathCache } = await import("./binary_lookup.js");++const NVM_BIN = path.join("/home/user", ".nvm", "versions", "node", "v24.19.0", "bin");+const CLAUDE = path.join(NVM_BIN, "claude");++describe("findOnPath", () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");++ beforeEach(() => {+ resetLoginShellPathCache();+ execFileMock.mockReset();+ existsSyncMock.mockReset();+ existsSyncMock.mockReturnValue(false);+ stubPlatform("linux");+ process.env.SHELL = "/bin/zsh";+ });++ afterEach(() => {+ process.env.PATH = originalPath;+ if (originalShell === undefined) {+ delete process.env.SHELL;+ } else {+ process.env.SHELL = originalShell;+ }+ if (originalPlatform) {+ Object.defineProperty(process, "platform", originalPlatform);+ }+ });++ function stubPlatform(platform: NodeJS.Platform) {+ Object.defineProperty(process, "platform", { ...originalPlatform, value: platform });+ }++ /** Answers the login-shell read with a delimited `env` dump exporting `path`. */+ function loginShellReports(shellPath: string) {+ execFileMock.mockImplementation((_shell, _args, _options, cb) => cb(null, {+ stdout: [+ "Welcome to your shell!",+ "__TRILIUM_SHELL_ENV__HOME=/home/user",+ `PATH=${shellPath}`,+ "SHELL=/bin/zsh__TRILIUM_SHELL_ENV__",+ "you have mail"+ ].join("\n"),+ stderr: ""+ }));+ }++ it("returns the inherited PATH hit without starting a shell", async () => {+ const hit = path.join("/usr/local/bin", "claude");+ process.env.PATH = ["", "/usr/bin", "/usr/local/bin"].join(path.delimiter);+ existsSyncMock.mockImplementation((candidate: string) => candidate === hit);++ await expect(findOnPath("claude")).resolves.toBe(hit);+ expect(execFileMock).not.toHaveBeenCalled();+ });++ it("falls back to the login shell's PATH and adopts it, asking the shell only once", async () => {+ // The launchd PATH a GUI-launched app inherits — no version manager.+ process.env.PATH = ["/usr/bin", "/bin"].join(path.delimiter);+ existsSyncMock.mockImplementation((candidate: string) => candidate === CLAUDE);+ loginShellReports([NVM_BIN, "/usr/bin", "/bin"].join(path.delimiter));++ await expect(findOnPath("claude")).resolves.toBe(CLAUDE);++ // The subprocess needs the same PATH (an npm shim resolves `node`+ // through it), and the inherited entries keep their precedence.+ expect(process.env.PATH?.split(path.delimiter)).toEqual(["/usr/bin", "/bin", NVM_BIN]);++ const [shell, args] = execFileMock.mock.calls[0];+ expect(shell).toBe("/bin/zsh");+ expect(args[0]).toBe("-ilc");++ // A second lookup reuses the cached answer rather than paying for+ // another shell startup.+ await expect(findOnPath("claude")).resolves.toBe(CLAUDE);+ expect(execFileMock).toHaveBeenCalledTimes(1);+ });++ it("leaves PATH untouched when the login shell cannot reach the binary either", async () => {+ process.env.PATH = "/usr/bin";+ loginShellReports(["/usr/bin", "/opt/other/bin"].join(path.delimiter));++ await expect(findOnPath("claude")).resolves.toBeUndefined();+ expect(process.env.PATH).toBe("/usr/bin");+ });++ it("gives up quietly when the shell fails, reports no PATH, or there is none to ask", async () => {+ process.env.PATH = "/usr/bin";++ execFileMock.mockImplementation((_shell, _args, _options, cb) => cb(new Error("spawn EACCES")));+ await expect(findOnPath("claude")).resolves.toBeUndefined();++ resetLoginShellPathCache();+ loginShellReports("");+ await expect(findOnPath("claude")).resolves.toBeUndefined();++ resetLoginShellPathCache();+ execFileMock.mockReset();+ delete process.env.SHELL;+ await expect(findOnPath("claude")).resolves.toBeUndefined();+ expect(execFileMock).not.toHaveBeenCalled();+ });++ it("skips the login shell on Windows and probes the executable extensions", async () => {+ stubPlatform("win32");+ const dir = path.join("npm", "prefix");+ const shim = path.join(dir, "claude.cmd");+ process.env.PATH = dir;+ existsSyncMock.mockImplementation((candidate: string) => candidate === shim);++ await expect(findOnPath("claude")).resolves.toBe(shim);++ // Only the unusable bare POSIX script is left: no .cmd/.exe/.bat, and+ // $SHELL is meaningless here, so nothing is spawned.+ existsSyncMock.mockImplementation((candidate: string) => candidate === path.join(dir, "claude"));+ await expect(findOnPath("claude")).resolves.toBeUndefined();+ expect(execFileMock).not.toHaveBeenCalled();+ });+});++describe("extractPathFromShellEnv", () => {+ it("reads PATH from between the delimiters, ignoring rc-file chatter around them", () => {+ const dump = `nvm loaded\n__TRILIUM_SHELL_ENV__A=1\nPATH=/a:/b\nZ=2__TRILIUM_SHELL_ENV__\nbye`;+ expect(extractPathFromShellEnv(dump)).toBe("/a:/b");+ });++ it("returns undefined for an unterminated dump, a missing PATH, or an empty one", () => {+ expect(extractPathFromShellEnv("__TRILIUM_SHELL_ENV__PATH=/a")).toBeUndefined();+ expect(extractPathFromShellEnv("__TRILIUM_SHELL_ENV__HOME=/h__TRILIUM_SHELL_ENV__")).toBeUndefined();+ expect(extractPathFromShellEnv("__TRILIUM_SHELL_ENV__PATH=__TRILIUM_SHELL_ENV__")).toBeUndefined();+ // A PATH printed outside the delimiters is rc-file output, not the env.+ expect(extractPathFromShellEnv("PATH=/spoofed")).toBeUndefined();+ });+});diff --git a/apps/server/src/services/llm/providers/binary_lookup.ts b/apps/server/src/services/llm/providers/binary_lookup.tsnew file mode 100644index 0000000000..e5bb64c145--- /dev/null+++ b/apps/server/src/services/llm/providers/binary_lookup.ts@@ -0,0 +1,146 @@+/**+ * Locates the bring-your-own-binary CLIs the agent providers drive (Claude+ * Code, GitHub Copilot).+ *+ * A GUI-launched app does not inherit the user's shell environment: on macOS+ * launchd hands `Trilium.app` a bare `/usr/bin:/bin:/usr/sbin:/sbin`, and on+ * Linux a `.desktop` launcher is no better. Version managers (nvm, fnm, asdf,+ * volta) put their bin directory on PATH from an rc file, so the CLI that+ * `pnpm desktop:start` finds is invisible to the packaged build.+ *+ * So the inherited PATH is searched first, and only when that misses does the+ * user's login shell get asked for its own PATH. A hit there is adopted into+ * `process.env.PATH`, because the CLI subprocess needs it too — an npm shim+ * resolves its `node` through PATH.+ */++import { getLog } from "@triliumnext/core";+import { execFile } from "child_process";+import { existsSync } from "fs";+import path from "path";+import { promisify } from "util";++const execFileAsync = promisify(execFile);++/** Brackets the `env` dump so rc-file chatter can be discarded around it. */+const DELIMITER = "__TRILIUM_SHELL_ENV__";++/** Upper bound on the login shell's startup: rc files can source a lot. */+const LOGIN_SHELL_TIMEOUT_MS = 10000;++/**+ * Finds `binary` on PATH, falling back to the login shell's PATH. Returns the+ * full path to the executable, or `undefined` if it is installed nowhere the+ * user's shell could reach it either.+ */+export async function findOnPath(binary: string): Promise<string | undefined> {+ const inherited = searchPath(process.env.PATH, binary);+ if (inherited) {+ return inherited;+ }++ const loginShellPath = await resolveLoginShellPath();+ if (!loginShellPath) {+ return undefined;+ }++ const found = searchPath(loginShellPath, binary);+ if (found) {+ process.env.PATH = mergePaths(process.env.PATH, loginShellPath);+ getLog().info(`Adopted PATH from the login shell to reach ${binary} at ${found}`);+ }+ return found;+}++/** For tests: forget the login shell's PATH so the next call re-reads it. */+export function resetLoginShellPathCache(): void {+ cachedLoginShellPath = undefined;+}++/**+ * Extracts the `PATH` value from the delimited `env` dump a login shell wrote.+ * Returns `undefined` when the shell exited before both delimiters were+ * printed, or when it reported no PATH at all.+ */+export function extractPathFromShellEnv(shellOutput: string): string | undefined {+ const start = shellOutput.indexOf(DELIMITER);+ const end = shellOutput.lastIndexOf(DELIMITER);+ if (start === -1 || end <= start) {+ return undefined;+ }++ const env = shellOutput.slice(start + DELIMITER.length, end);+ return /^PATH=(.+)$/m.exec(env)?.[1];+}++function searchPath(rawPath: string | undefined, binary: string): string | undefined {+ // 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 (rawPath ?? "").split(path.delimiter)) {+ if (!dir) {+ continue;+ }+ for (const ext of extensions) {+ const candidate = path.join(dir, binary + ext);+ if (existsSync(candidate)) {+ return candidate;+ }+ }+ }+ return undefined;+}++/**+ * The in-flight/successful login shell read. A failed read is cached too: the+ * shell is unlikely to answer differently before a restart, and every miss+ * costs a full shell startup.+ */+let cachedLoginShellPath: Promise<string | undefined> | undefined;++function resolveLoginShellPath(): Promise<string | undefined> {+ if (!cachedLoginShellPath) {+ cachedLoginShellPath = readLoginShellPath();+ }+ return cachedLoginShellPath;+}++async function readLoginShellPath(): Promise<string | undefined> {+ // Windows has no login-shell profile that PATH is built from, and $SHELL is+ // how the shell to ask is named.+ const shell = process.platform === "win32" ? undefined : process.env.SHELL?.trim();+ if (!shell) {+ return undefined;+ }++ // `printf` and `env` are external commands, so the dump reads the same under+ // bash, zsh, fish and dash. `-i` matters: nvm and fnm are commonly set up in+ // an interactive-only rc file (.zshrc, .bashrc).+ const args = ["-ilc", `printf %s ${DELIMITER}; env; printf %s ${DELIMITER}`];+ try {+ const { stdout } = await execFileAsync(shell, args, {+ timeout: LOGIN_SHELL_TIMEOUT_MS,+ encoding: "utf8",+ maxBuffer: 1024 * 1024,+ // A shell that believes it drives a terminal can redraw a prompt or+ // start an instant-prompt plugin over the output we parse.+ env: { ...process.env, TERM: "dumb" }+ });+ return extractPathFromShellEnv(stdout);+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ getLog().info(`Could not read PATH from the login shell "${shell}" (${detail})`);+ return undefined;+ }+}++/** Keeps the inherited entries ahead of the login shell's, without duplicates. */+function mergePaths(inherited: string | undefined, loginShell: string): string {+ const entries = [+ ...(inherited ?? "").split(path.delimiter),+ ...loginShell.split(path.delimiter)+ ];+ return [...new Set(entries.filter((entry) => entry))].join(path.delimiter);+}diff --git a/apps/server/src/services/llm/providers/claude_binary.spec.ts b/apps/server/src/services/llm/providers/claude_binary.spec.tsindex c7d869d370..490984dd6a 100644--- a/apps/server/src/services/llm/providers/claude_binary.spec.ts+++ b/apps/server/src/services/llm/providers/claude_binary.spec.ts@@ -13,14 +13,20 @@ vi.mock("fs", () => ({ existsSync: existsSyncMock }));vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: vi.fn(), error: vi.fn() }) }));const { resetClaudeBinaryCache, resolveClaudeBinaryPath } = await import("./claude_binary.js");+const { resetLoginShellPathCache } = await import("./binary_lookup.js");describe("resolveClaudeBinaryPath", () => {const originalOverride = process.env.TRILIUM_CLAUDE_CODE_PATH;const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");beforeEach(() => {resetClaudeBinaryCache();+ resetLoginShellPathCache();+ // No $SHELL: the login-shell fallback is a no-op, so these cases+ // stay about the inherited PATH (binary_lookup.spec.ts covers it).+ delete process.env.SHELL;execFileMock.mockReset();existsSyncMock.mockReset();existsSyncMock.mockReturnValue(true);@@ -34,6 +40,11 @@ describe("resolveClaudeBinaryPath", () => {process.env.TRILIUM_CLAUDE_CODE_PATH = originalOverride;}process.env.PATH = originalPath;+ if (originalShell === undefined) {+ delete process.env.SHELL;+ } else {+ process.env.SHELL = originalShell;+ }if (originalPlatform) {Object.defineProperty(process, "platform", originalPlatform);}diff --git a/apps/server/src/services/llm/providers/claude_binary.ts b/apps/server/src/services/llm/providers/claude_binary.tsindex c5bbfde3af..ac1cd91c36 100644--- a/apps/server/src/services/llm/providers/claude_binary.ts+++ b/apps/server/src/services/llm/providers/claude_binary.ts@@ -10,17 +10,18 @@* on NixOS, which needs no glibc/nix-ld shim — unlike the SDK's bundled ELF).** Resolution order: the TRILIUM_CLAUDE_CODE_PATH override, then `claude` on- * PATH. The resolved binary is probed with `--version` once so a broken/absent- * install surfaces as a clear, actionable error instead of an opaque spawn- * failure mid-chat.+ * PATH (see `findOnPath`, which also asks the login shell). The resolved binary+ * is probed with `--version` once so a broken/absent install surfaces as a+ * clear, actionable error instead of an opaque spawn failure mid-chat.*/import { getLog } from "@triliumnext/core";import { execFile } from "child_process";import { existsSync } from "fs";-import path from "path";import { promisify } from "util";+import { findOnPath } from "./binary_lookup.js";+const execFileAsync = promisify(execFile);/**@@ -46,7 +47,7 @@ export function resetClaudeBinaryCache(): void {}async function probeBinary(): Promise<string> {- const binary = locateBinary();+ const binary = await locateBinary();// Probe once: confirms the binary actually runs on this host (catches a// wrong-arch/broken install) and records the version for diagnostics.@@ -71,7 +72,7 @@ async function probeBinary(): Promise<string> {return binary;}-function locateBinary(): string {+async function locateBinary(): Promise<string> {const override = process.env.TRILIUM_CLAUDE_CODE_PATH?.trim();if (override) {if (!existsSync(override)) {@@ -80,30 +81,10 @@ function locateBinary(): string {return override;}- const onPath = findOnPath("claude");+ const onPath = await findOnPath("claude");if (onPath) {return onPath;}throw new Error("Claude Code CLI not found. Install it (`npm install -g @anthropic-ai/claude-code`) and run `claude /login` on the machine running the Trilium server, or set the TRILIUM_CLAUDE_CODE_PATH environment variable to its location.");}--function findOnPath(binary: string): string | undefined {- // 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;- }- for (const ext of extensions) {- const candidate = path.join(dir, binary + ext);- if (existsSync(candidate)) {- return candidate;- }- }- }- return undefined;-}diff --git a/apps/server/src/services/llm/providers/copilot_binary.spec.ts b/apps/server/src/services/llm/providers/copilot_binary.spec.tsindex 29759f02a0..2cbd9ebb9a 100644--- a/apps/server/src/services/llm/providers/copilot_binary.spec.ts+++ b/apps/server/src/services/llm/providers/copilot_binary.spec.ts@@ -13,14 +13,20 @@ vi.mock("fs", () => ({ existsSync: existsSyncMock }));vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: vi.fn(), error: vi.fn() }) }));const { needsShell, resetCopilotBinaryCache, resolveCopilotBinaryPath } = await import("./copilot_binary.js");+const { resetLoginShellPathCache } = await import("./binary_lookup.js");describe("resolveCopilotBinaryPath", () => {const originalOverride = process.env.TRILIUM_COPILOT_PATH;const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");beforeEach(() => {resetCopilotBinaryCache();+ resetLoginShellPathCache();+ // No $SHELL: the login-shell fallback is a no-op, so these cases+ // stay about the inherited PATH (binary_lookup.spec.ts covers it).+ delete process.env.SHELL;execFileMock.mockReset();existsSyncMock.mockReset();existsSyncMock.mockReturnValue(true);@@ -34,6 +40,11 @@ describe("resolveCopilotBinaryPath", () => {process.env.TRILIUM_COPILOT_PATH = originalOverride;}process.env.PATH = originalPath;+ if (originalShell === undefined) {+ delete process.env.SHELL;+ } else {+ process.env.SHELL = originalShell;+ }if (originalPlatform) {Object.defineProperty(process, "platform", originalPlatform);}diff --git a/apps/server/src/services/llm/providers/copilot_binary.ts b/apps/server/src/services/llm/providers/copilot_binary.tsindex b51e2d1e79..ee0aba736e 100644--- a/apps/server/src/services/llm/providers/copilot_binary.ts+++ b/apps/server/src/services/llm/providers/copilot_binary.ts@@ -7,18 +7,19 @@* owned entirely by the CLI (`copilot login`, or credentials shared with any* other GitHub Copilot editor integration on the machine).*- * Resolution order: the TRILIUM_COPILOT_PATH override, then `copilot` on- * PATH. The resolved binary is probed with `--version` once so a broken/absent- * install surfaces as a clear, actionable error instead of an opaque spawn- * failure mid-chat.+ * Resolution order: the TRILIUM_COPILOT_PATH override, then `copilot` on PATH+ * (see `findOnPath`, which also asks the login shell). The resolved binary is+ * probed with `--version` once so a broken/absent install surfaces as a clear,+ * actionable error instead of an opaque spawn failure mid-chat.*/import { getLog } from "@triliumnext/core";import { execFile } from "child_process";import { existsSync } from "fs";-import path from "path";import { promisify } from "util";+import { findOnPath } from "./binary_lookup.js";+const execFileAsync = promisify(execFile);/**@@ -44,7 +45,7 @@ export function resetCopilotBinaryCache(): void {}async function probeBinary(): Promise<string> {- const binary = locateBinary();+ const binary = await locateBinary();// Probe once: confirms the binary actually runs on this host (catches a// wrong-arch/broken install) and records the version for diagnostics.@@ -66,7 +67,7 @@ async function probeBinary(): Promise<string> {return binary;}-function locateBinary(): string {+async function locateBinary(): Promise<string> {const override = process.env.TRILIUM_COPILOT_PATH?.trim();if (override) {if (!existsSync(override)) {@@ -75,7 +76,7 @@ function locateBinary(): string {return override;}- const onPath = findOnPath("copilot");+ const onPath = await findOnPath("copilot");if (onPath) {return onPath;}@@ -90,23 +91,3 @@ function locateBinary(): string {export function needsShell(binary: string): boolean {return /\.(cmd|bat)$/i.test(binary);}--function findOnPath(binary: string): string | undefined {- // 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;- }- for (const ext of extensions) {- const candidate = path.join(dir, binary + ext);- if (existsSync(candidate)) {- return candidate;- }- }- }- return undefined;-}