Skip to content

Build your personal knowledge base with Trilium Notes

refactor(llm): share the sign-in, effort, hook and probe code of the agent providers

Elian Doran5884ea6d6d13
diff --git a/apps/server/src/services/llm/providers/acp_agent.ts b/apps/server/src/services/llm/providers/acp_agent.ts
index 1cffeb54c2..878ab707ab 100644
--- a/apps/server/src/services/llm/providers/acp_agent.ts
+++ b/apps/server/src/services/llm/providers/acp_agent.ts
@@ -1,9 +1,10 @@
/**
* Shared base for the providers that drive a subscription agent over the Agent
- * Client Protocol (ACP) — GitHub Copilot (`copilot --acp`) and Google
- * Antigravity (`agy_acp_server`). The agent CLI runs as a subprocess, owns the
- * account's authentication, runs its own agentic loop and keeps conversation
- * history in host-side sessions. So every ACP provider:
+ * Client Protocol (ACP) — GitHub Copilot (`copilot --acp`), Google Antigravity
+ * (`agy_acp_server`) and OpenAI Codex (through `codex-acp`). The agent runs as a
+ * subprocess or in a worker thread, owns the account's authentication, runs its
+ * own agentic loop and keeps conversation history in host-side sessions. So
+ * every ACP provider:
* - implements `chatChunks()` (chunk-native streaming) instead of `chat()`,
* - keeps its agent process running between turns (see acp_client_pool.ts),
* - maps chat notes to ACP sessions and sends only the newest user message
@@ -18,7 +19,7 @@
* permission policy; the protocol handling lives here.
*/
-import type { LlmMessage, LlmMessagePart, LlmStreamChunk } from "@triliumnext/commons";
+import { LLM_REASONING_EFFORTS, type LlmMessage, type LlmMessagePart, type LlmReasoningEffort, type LlmStreamChunk } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
import { resolveAttachmentPart } from "@triliumnext/core/src/services/llm/attachment_content.js";
import { buildNoteHint } from "@triliumnext/core/src/services/llm/note_hint.js";
@@ -29,7 +30,7 @@ import fs from "fs";
import path from "path";
import dataDirs from "../../data_dir.js";
-import { AcpClient } from "./acp_client.js";
+import { AcpClient, AcpError } from "./acp_client.js";
import { AcpClientPool, type AcpLease, type AcpPoolConnection } from "./acp_client_pool.js";
import { getAcpMcpEndpointUrl } from "./acp_mcp_endpoint.js";
import { attachmentPlaceholder, buildHistoryReplay, hashTranscript } from "./transcript.js";
@@ -108,6 +109,28 @@ const MODEL_PROBE_TIMEOUT_MS = 60_000;
export const INIT_TIMEOUT_MS = 30_000;
export const SESSION_TIMEOUT_MS = 120_000;
+
+/** How long the add-provider screen waits for the user to finish signing in in the browser. */
+export const SIGN_IN_TIMEOUT_MS = 5 * 60_000;
+
+/**
+ * How long after a sign-in `session/new` is retried while the agent's account
+ * does not show it yet, and how often: Codex reports a sign-in complete before
+ * its account does.
+ */
+const SIGN_IN_SETTLE_MS = 10_000;
+const SIGN_IN_RETRY_MS = 500;
+
+/** How an agent signs in from the add-provider screen (see {@link AcpAgentProvider.signIn}). */
+export interface AcpSignIn {
+ /** The ACP `authenticate` method. */
+ methodId: string;
+ /** The provider's name in messages ("OpenAI Codex"). */
+ product: string;
+ /** The account the user signs in with ("ChatGPT"). */
+ account: string;
+}
+
/** Upper bound for a whole prompt turn (agentic loops included). */
const PROMPT_TIMEOUT_MS = 15 * 60_000;
@@ -306,11 +329,46 @@ export abstract class AcpAgentProvider implements LlmProvider {
}
/**
- * Open a session. `interactive` is true only on the add-provider screen,
- * where a subclass can run a sign-in the user is there to complete.
+ * How the agent signs in from the add-provider screen: the `authenticate`
+ * method that opens its sign-in page in a browser on the device running
+ * Trilium, and the names its messages use. Absent for an agent whose CLI
+ * is signed in on its own (`copilot login`).
+ */
+ protected readonly signIn?: AcpSignIn;
+
+ /**
+ * Open a session. `interactive` is true only on the add-provider screen: an
+ * agent with a {@link signIn} that has no saved sign-in then signs in, and
+ * the session is opened once the user has finished in the browser. The
+ * agent keeps the sign-in, so later sessions need none.
+ */
+ protected async createSession(client: AcpClient, params: AcpNewSessionParams, interactive: boolean, timeoutMs: number) {
+ try {
+ return await openSession(client, params, timeoutMs);
+ } catch (err) {
+ if (!this.signIn || !interactive || !isSignInRequired(err)) {
+ throw err;
+ }
+ await client.request("authenticate", { methodId: this.signIn.methodId }, SIGN_IN_TIMEOUT_MS);
+ return await openSessionAfterSignIn(client, params, timeoutMs);
+ }
+ }
+
+ /**
+ * What to tell the user about a sign-in that is missing or was not
+ * completed, for {@link describeFailure}; undefined for any other failure.
*/
- protected async createSession(client: AcpClient, params: AcpNewSessionParams, _interactive: boolean, timeoutMs: number) {
- return await client.request<{ sessionId: string; models?: AcpSessionModelState }>("session/new", params, timeoutMs);
+ protected describeSignInFailure(error: unknown): string | undefined {
+ if (!this.signIn) {
+ return undefined;
+ }
+ if (isSignInRequired(error)) {
+ return `${this.signIn.product} is not signed in. Open this provider in the AI settings and go to the model selection, which opens the ${this.signIn.account} sign-in page in a browser on the device running Trilium.`;
+ }
+ if (/"authenticate" timed out/.test(describeError(error))) {
+ return `The ${this.signIn.account} sign-in was not completed in time. Try again, and finish signing in in the browser window that opens on the device running Trilium.`;
+ }
+ return undefined;
}
/**
@@ -968,6 +1026,31 @@ export function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+/** Whether an agent refused a request because no one is signed in. */
+export function isSignInRequired(error: unknown): boolean {
+ return error instanceof AcpError && error.code === -32000 && /authentication required/i.test(error.message);
+}
+
+/** Effort levels weakest first, for an agent that names a level inside its model ids. */
+export function sortEfforts(efforts: LlmReasoningEffort[]): LlmReasoningEffort[] {
+ return [ ...efforts ].sort((a, b) => LLM_REASONING_EFFORTS.indexOf(a) - LLM_REASONING_EFFORTS.indexOf(b));
+}
+
+/**
+ * The level of `levels` (sorted weakest first) nearest to `wanted`, the
+ * higher on a tie, for a model that lacks the level a chat chose.
+ */
+export function nearestEffort(levels: LlmReasoningEffort[], wanted: LlmReasoningEffort): LlmReasoningEffort {
+ const target = LLM_REASONING_EFFORTS.indexOf(wanted);
+ let chosen = levels[0];
+ for (const level of levels) {
+ if (Math.abs(LLM_REASONING_EFFORTS.indexOf(level) - target) <= Math.abs(LLM_REASONING_EFFORTS.indexOf(chosen) - target)) {
+ chosen = level;
+ }
+ }
+ return chosen;
+}
+
/** ACP content block (subset used by these providers). */
type AcpContentBlock =
| { type: "text"; text: string }
@@ -1140,3 +1223,22 @@ function describeStopReason(stopReason: string): string {
return `Agent stopped: ${stopReason}`;
}
}
+
+function openSession(client: AcpClient, params: AcpNewSessionParams, timeoutMs: number) {
+ return client.request<{ sessionId: string; models?: AcpSessionModelState }>("session/new", params, timeoutMs);
+}
+
+/** `session/new` once a sign-in has completed, retried while the agent's account does not show it yet. */
+async function openSessionAfterSignIn(client: AcpClient, params: AcpNewSessionParams, timeoutMs: number) {
+ const giveUpAt = Date.now() + SIGN_IN_SETTLE_MS;
+ for (;;) {
+ try {
+ return await openSession(client, params, timeoutMs);
+ } catch (err) {
+ if (!isSignInRequired(err) || Date.now() >= giveUpAt) {
+ throw err;
+ }
+ await new Promise(resolve => setTimeout(resolve, SIGN_IN_RETRY_MS));
+ }
+ }
+}
diff --git a/apps/server/src/services/llm/providers/acp_hook.spec.ts b/apps/server/src/services/llm/providers/acp_hook.spec.ts
new file mode 100644
index 0000000000..9996e17f28
--- /dev/null
+++ b/apps/server/src/services/llm/providers/acp_hook.spec.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const findOnPathMock = vi.hoisted(() => vi.fn<(binary: string) => Promise<string | undefined>>());
+vi.mock("./binary_lookup.js", async (importOriginal) => ({ ...await importOriginal<typeof import("./binary_lookup.js")>(), findOnPath: findOnPathMock }));
+
+const { buildHookCommand, resetCurlCache, resolveCurlPath, stringsIn } = await import("./acp_hook.js");
+
+describe("buildHookCommand", () => {
+ it("posts the tool call to Trilium and fails on anything but a decision", () => {
+ expect(buildHookCommand("C:\\Windows\\System32\\curl.exe", "http://127.0.0.1:5000/hook-abc"))
+ .toBe("\"C:\\Windows\\System32\\curl.exe\" --silent --show-error --fail --noproxy 127.0.0.1 --max-time 8 --data-binary @- http://127.0.0.1:5000/hook-abc");
+ expect(() => buildHookCommand("/opt/\"odd\"/curl", "http://127.0.0.1:5000/hook-abc")).toThrow(/quote/);
+ });
+});
+
+describe("resolveCurlPath", () => {
+ beforeEach(() => {
+ resetCurlCache();
+ findOnPathMock.mockReset();
+ });
+
+ it("finds curl once, and explains what to install when it is missing", async () => {
+ findOnPathMock.mockResolvedValueOnce(undefined);
+ await expect(resolveCurlPath()).rejects.toThrow(/Google Antigravity and OpenAI Codex providers need curl.*Install curl/s);
+
+ findOnPathMock.mockResolvedValue("/usr/bin/curl");
+ await expect(resolveCurlPath()).resolves.toBe("/usr/bin/curl");
+ await expect(resolveCurlPath()).resolves.toBe("/usr/bin/curl");
+ expect(findOnPathMock).toHaveBeenCalledTimes(2);
+ expect(findOnPathMock).toHaveBeenCalledWith("curl");
+ });
+});
+
+describe("stringsIn", () => {
+ it("collects every string, however deeply nested, and nothing else", () => {
+ expect(stringsIn({ open: [ { ref_id: "a" } ], n: 3, flag: true, nested: { list: [ "b", [ "c" ] ] } })).toEqual([ "a", "b", "c" ]);
+ expect(stringsIn("d")).toEqual([ "d" ]);
+ expect(stringsIn(null)).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/llm/providers/acp_hook.ts b/apps/server/src/services/llm/providers/acp_hook.ts
new file mode 100644
index 0000000000..5d6f7b1f0c
--- /dev/null
+++ b/apps/server/src/services/llm/providers/acp_hook.ts
@@ -0,0 +1,61 @@
+/**
+ * What the ACP providers whose agents run `PreToolUse` hooks share (Google
+ * Antigravity, OpenAI Codex): the `curl` command that posts a tool call to
+ * Trilium's loopback hook endpoint (`getAcpHookEndpointUrl`), where `curl` is,
+ * and the strings inside a call's arguments. Each provider writes its own hook
+ * file and decides its own calls (see `antigravity_hook.ts`, `codex_hook.ts`).
+ */
+
+import { cachedProbe, findOnPath } from "./binary_lookup.js";
+
+/** How long `curl` waits for Trilium's decision, in seconds; each agent's hook timeout is longer. */
+const CURL_MAX_TIME_S = 8;
+
+/**
+ * The hook command: `curl` posts the call (the hook's stdin) to Trilium and
+ * prints the decision. `--fail` turns an error response into a failed hook.
+ * `--noproxy` keeps an `HTTP_PROXY` from routing the loopback request away
+ * from Trilium. Agents run it with `sh -c`, or `cmd /c` on Windows; the URL
+ * holds no character either shell reads.
+ */
+export function buildHookCommand(curl: string, hookUrl: string): string {
+ if (curl.includes("\"")) {
+ throw new Error(`Cannot quote the path of curl for the agent hook: ${curl}`);
+ }
+ return `"${curl}" --silent --show-error --fail --noproxy 127.0.0.1 --max-time ${CURL_MAX_TIME_S} --data-binary @- ${hookUrl}`;
+}
+
+/** The found `curl`, shared by concurrent first calls (see {@link cachedProbe}). */
+const curl = cachedProbe(findCurl);
+
+/** The absolute path of `curl`, which the hook runs. The path makes it independent of the server's PATH. */
+export function resolveCurlPath(): Promise<string> {
+ return curl.resolve();
+}
+
+/** For tests: forget the found `curl`. */
+export function resetCurlCache(): void {
+ curl.reset();
+}
+
+/** Every string inside a hook call's arguments, however deeply nested. */
+export function stringsIn(value: unknown): string[] {
+ if (typeof value === "string") {
+ return [ value ];
+ }
+ if (Array.isArray(value)) {
+ return value.flatMap(stringsIn);
+ }
+ if (value && typeof value === "object") {
+ return Object.values(value).flatMap(stringsIn);
+ }
+ return [];
+}
+
+async function findCurl(): Promise<string> {
+ const found = await findOnPath("curl");
+ if (!found) {
+ throw new Error("The Google Antigravity and OpenAI Codex providers need curl, which Trilium uses to control what the agent can access, and curl was not found. Install curl (it ships with Windows 10 and later and with macOS) and make sure it is on PATH.");
+ }
+ return found;
+}
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
index c6b6c0c831..4a66e5fae3 100644
--- a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
@@ -24,8 +24,8 @@ vi.mock("./acp_mcp_endpoint.js", () => ({
getAcpMcpEndpointUrl: async () => "http://127.0.0.1:12345/mcp-secret",
getAcpHookEndpointUrl: getAcpHookEndpointUrlMock
}));
-vi.mock("./antigravity_hook.js", async (importOriginal) => ({
- ...await importOriginal<typeof import("./antigravity_hook.js")>(),
+vi.mock("./acp_hook.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./acp_hook.js")>(),
resolveCurlPath: async () => "/usr/bin/curl"
}));
vi.mock("@triliumnext/core/src/services/llm/note_hint.js", () => ({ buildNoteHint: () => null }));
@@ -341,7 +341,7 @@ describe("AntigravityAgentProvider", () => {
it("signs in during the model probe, but reports a missing sign-in in the chat instead", async () => {
FakeAcpClient.signedIn = false;
const chunks = await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));
- expect(chunks).toEqual([{ type: "error", error: expect.stringContaining("not signed in") }]);
+ expect(chunks).toEqual([{ type: "error", error: "Google Antigravity is not signed in. Open this provider in the AI settings and go to the model selection, which opens the Google sign-in page in a browser on the device running Trilium." }]);
expect(FakeAcpClient.current?.methods()).not.toContain("authenticate");
const models = await new AntigravityAgentProvider().listModels();
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.ts b/apps/server/src/services/llm/providers/antigravity_agent.ts
index 9441bbdd87..9991f87d8b 100644
--- a/apps/server/src/services/llm/providers/antigravity_agent.ts
+++ b/apps/server/src/services/llm/providers/antigravity_agent.ts
@@ -18,18 +18,19 @@
* Trilium's note tools.
*/
-import { LLM_REASONING_EFFORTS, type LlmReasoningEffort } from "@triliumnext/commons";
+import type { LlmReasoningEffort } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
import type { LlmProviderConfig, ModelInfo } from "@triliumnext/core/src/services/llm/types.js";
import { existsSync } from "fs";
import path from "path";
import dataDirs from "../../data_dir.js";
-import { AcpAgentProvider, type AcpLaunchSpec, type AcpNewSessionParams, type AcpPermissionOutcome, type AcpPermissionRequest, type AcpSessionModelState, type AcpToolCallUpdate, type BuiltInToolDisplay, denyPermission, describeError, NOTE_TOOLS_MCP_SERVER_NAME } from "./acp_agent.js";
-import { type AcpClient, AcpError } from "./acp_client.js";
+import { AcpAgentProvider, type AcpLaunchSpec, type AcpNewSessionParams, type AcpPermissionOutcome, type AcpPermissionRequest, type AcpSessionModelState, type AcpToolCallUpdate, type BuiltInToolDisplay, denyPermission, describeError, nearestEffort, NOTE_TOOLS_MCP_SERVER_NAME, sortEfforts } from "./acp_agent.js";
+import type { AcpClient } from "./acp_client.js";
import { getAcpHookEndpointUrl } from "./acp_mcp_endpoint.js";
import { resolveAntigravityBinaryPath } from "./antigravity_binary.js";
-import { type AntigravityDirs, type AntigravityHookDecision, buildHookCommand, decideAntigravityToolCall, resolveCurlPath, writeAntigravityHooks } from "./antigravity_hook.js";
+import { buildHookCommand, resolveCurlPath } from "./acp_hook.js";
+import { type AntigravityDirs, type AntigravityHookDecision, decideAntigravityToolCall, writeAntigravityHooks } from "./antigravity_hook.js";
import { isPublicHttpUrl } from "./public_url.js";
/** The model id that leaves the session on the model the server picks. */
@@ -52,9 +53,6 @@ const AVAILABLE_MODELS: ModelInfo[] = [
*/
const SIGN_IN_METHOD = "oauth-personal";
-/** How long the add-provider screen waits for the user to finish signing in in the browser. */
-export const SIGN_IN_TIMEOUT_MS = 5 * 60_000;
-
/** CA bundle locations on common Linux distributions, in the order Go's crypto/x509 tries them. */
const LINUX_CA_BUNDLES = [
"/etc/ssl/certs/ca-certificates.crt",
@@ -79,6 +77,7 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
protected readonly fallbackModels = AVAILABLE_MODELS;
protected readonly defaultModelId = DEFAULT_MODEL_ID;
protected readonly agentDirName = path.join("antigravity-agent", "workspace");
+ protected readonly signIn = { methodId: SIGN_IN_METHOD, product: "Google Antigravity", account: "Google" };
/**
* The newest version of each family, every effort level included, plus
@@ -183,24 +182,9 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
return undefined;
}
- /**
- * Open a session, signing in first when the server has no saved sign-in and
- * the user is on the add-provider screen to complete it. The server opens
- * the Google sign-in page in a browser on the device running Trilium and
- * answers `authenticate` once the user has finished there; it keeps the
- * sign-in under `GEMINI_HOME`, so later sessions need none.
- */
+ /** Remember the catalog of every session opened, which picks the variant a turn runs on. */
protected async createSession(client: AcpClient, params: AcpNewSessionParams, interactive: boolean, timeoutMs: number) {
- let created: Awaited<ReturnType<AcpAgentProvider["createSession"]>>;
- try {
- created = await super.createSession(client, params, interactive, timeoutMs);
- } catch (err) {
- if (!interactive || !isSignInRequired(err)) {
- throw err;
- }
- await client.request("authenticate", { methodId: SIGN_IN_METHOD }, SIGN_IN_TIMEOUT_MS);
- created = await super.createSession(client, params, interactive, timeoutMs);
- }
+ const created = await super.createSession(client, params, interactive, timeoutMs);
if (created.models) {
recordCatalog(created.models);
}
@@ -209,11 +193,9 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
protected describeFailure(error: unknown): string {
const text = describeError(error);
- if (isSignInRequired(error)) {
- return "Google Antigravity is not signed in. Open this provider in the AI settings and go to the model selection, which opens the Google sign-in page in a browser on the device running Trilium.";
- }
- if (/"authenticate" timed out/.test(text)) {
- return "The Google sign-in was not completed in time. Try again, and finish signing in in the browser window that opens on the device running Trilium.";
+ const signInFailure = this.describeSignInFailure(error);
+ if (signInFailure) {
+ return signInFailure;
}
if (/ENOENT|spawn/i.test(text)) {
return `Failed to start Google's Antigravity ACP server: ${text}`;
@@ -288,15 +270,8 @@ export function resolveAntigravityModel(model: string, effort: LlmReasoningEffor
return model;
}
const levels = sortEfforts([ ...byEffort.keys() ]);
- const wanted = LLM_REASONING_EFFORTS.indexOf(effort ?? defaultEffort(levels));
- let chosen = levels[0];
- for (const level of levels) {
- if (Math.abs(LLM_REASONING_EFFORTS.indexOf(level) - wanted) <= Math.abs(LLM_REASONING_EFFORTS.indexOf(chosen) - wanted)) {
- chosen = level;
- }
- }
- /* v8 ignore next -- `chosen` is one of `byEffort`'s own keys. */
- return byEffort.get(chosen) ?? model;
+ /* v8 ignore next -- the level chosen is one of `byEffort`'s own keys. */
+ return byEffort.get(nearestEffort(levels, effort ?? defaultEffort(levels))) ?? model;
}
/**
@@ -400,10 +375,6 @@ function recordCatalog(remote: AcpSessionModelState) {
catalog = { variants, titleModel };
}
-function sortEfforts(efforts: LlmReasoningEffort[]): LlmReasoningEffort[] {
- return [ ...efforts ].sort((a, b) => LLM_REASONING_EFFORTS.indexOf(a) - LLM_REASONING_EFFORTS.indexOf(b));
-}
-
/** High where the model has it, as the server itself defaults to a High variant; the strongest otherwise. */
function defaultEffort(sortedEfforts: LlmReasoningEffort[]): LlmReasoningEffort {
return sortedEfforts.includes("high") ? "high" : sortedEfforts[sortedEfforts.length - 1];
@@ -462,6 +433,3 @@ function isWebSearch(toolCall: { kind?: string; title?: string } | undefined): b
return toolCall?.kind === "search" && /^Run(?:ning)? search_web\??$/.test(toolCall.title ?? "");
}
-function isSignInRequired(error: unknown): boolean {
- return error instanceof AcpError && error.code === -32000 && /authentication required/i.test(error.message);
-}
diff --git a/apps/server/src/services/llm/providers/antigravity_binary.spec.ts b/apps/server/src/services/llm/providers/antigravity_binary.spec.ts
index 69d6bc146c..71a5b4f9ab 100644
--- a/apps/server/src/services/llm/providers/antigravity_binary.spec.ts
+++ b/apps/server/src/services/llm/providers/antigravity_binary.spec.ts
@@ -10,7 +10,7 @@ const existsSyncMock = vi.hoisted(() => vi.fn((_path: string) => true));
vi.mock("fs", () => ({ existsSync: existsSyncMock }));
const findOnPathMock = vi.hoisted(() => vi.fn<(binary: string) => Promise<string | undefined>>());
-vi.mock("./binary_lookup.js", () => ({ findOnPath: findOnPathMock }));
+vi.mock("./binary_lookup.js", async (importOriginal) => ({ ...await importOriginal<typeof import("./binary_lookup.js")>(), findOnPath: findOnPathMock }));
const logInfoMock = vi.hoisted(() => vi.fn());
vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: logInfoMock, error: vi.fn() }) }));
diff --git a/apps/server/src/services/llm/providers/antigravity_binary.ts b/apps/server/src/services/llm/providers/antigravity_binary.ts
index 55dc561f6f..e6c2fc9747 100644
--- a/apps/server/src/services/llm/providers/antigravity_binary.ts
+++ b/apps/server/src/services/llm/providers/antigravity_binary.ts
@@ -20,7 +20,7 @@ import { execFile } from "child_process";
import { existsSync } from "fs";
import { promisify } from "util";
-import { findOnPath } from "./binary_lookup.js";
+import { cachedProbe, findOnPath } from "./binary_lookup.js";
const execFileAsync = promisify(execFile);
@@ -38,26 +38,16 @@ const PROBE_TIMEOUT_MS = 60_000;
/** Where the setup steps live; the error messages point there. */
const SETUP_HINT = "See \"Google Antigravity\" in the AI section of the User Guide for how to download it.";
-/**
- * The in-flight/successful resolution. Caching the promise lets concurrent
- * first calls share one probe; a failed probe clears it so a later install is
- * picked up without a restart.
- */
-let cachedResolution: Promise<string> | undefined;
+/** The probed binary, shared by concurrent first calls (see {@link cachedProbe}). */
+const probed = cachedProbe(probeBinary);
export function resolveAntigravityBinaryPath(): Promise<string> {
- if (!cachedResolution) {
- cachedResolution = probeBinary().catch((err: unknown) => {
- cachedResolution = undefined;
- throw err;
- });
- }
- return cachedResolution;
+ return probed.resolve();
}
/** For tests: forget the probed binary so the next call re-resolves. */
export function resetAntigravityBinaryCache(): void {
- cachedResolution = undefined;
+ probed.reset();
}
/**
diff --git a/apps/server/src/services/llm/providers/antigravity_hook.spec.ts b/apps/server/src/services/llm/providers/antigravity_hook.spec.ts
index 4487dd40e4..e8a8ca03d7 100644
--- a/apps/server/src/services/llm/providers/antigravity_hook.spec.ts
+++ b/apps/server/src/services/llm/providers/antigravity_hook.spec.ts
@@ -1,12 +1,9 @@
import fs from "fs";
import os from "os";
import path from "path";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it } from "vitest";
-const findOnPathMock = vi.hoisted(() => vi.fn<(binary: string) => Promise<string | undefined>>());
-vi.mock("./binary_lookup.js", () => ({ findOnPath: findOnPathMock }));
-
-const { buildHookCommand, decideAntigravityToolCall, resetCurlCache, resolveCurlPath, writeAntigravityHooks } = await import("./antigravity_hook.js");
+const { decideAntigravityToolCall, writeAntigravityHooks } = await import("./antigravity_hook.js");
const ROOT = path.join(os.tmpdir(), "trilium-antigravity-hook-spec");
const HOME = path.join(ROOT, "home");
@@ -83,29 +80,3 @@ describe("writeAntigravityHooks", () => {
});
});
});
-
-describe("buildHookCommand", () => {
- it("posts the tool call to Trilium and fails on anything but a decision", () => {
- expect(buildHookCommand("C:\\Windows\\System32\\curl.exe", "http://127.0.0.1:5000/hook-abc"))
- .toBe("\"C:\\Windows\\System32\\curl.exe\" --silent --show-error --fail --noproxy 127.0.0.1 --max-time 8 --data-binary @- http://127.0.0.1:5000/hook-abc");
- expect(() => buildHookCommand("/opt/\"odd\"/curl", "http://127.0.0.1:5000/hook-abc")).toThrow(/quote/);
- });
-});
-
-describe("resolveCurlPath", () => {
- beforeEach(() => {
- resetCurlCache();
- findOnPathMock.mockReset();
- });
-
- it("finds curl once, and explains what to install when it is missing", async () => {
- findOnPathMock.mockResolvedValueOnce(undefined);
- await expect(resolveCurlPath()).rejects.toThrow(/Google Antigravity and OpenAI Codex providers need curl.*Install curl/s);
-
- findOnPathMock.mockResolvedValue("/usr/bin/curl");
- await expect(resolveCurlPath()).resolves.toBe("/usr/bin/curl");
- await expect(resolveCurlPath()).resolves.toBe("/usr/bin/curl");
- expect(findOnPathMock).toHaveBeenCalledTimes(2);
- expect(findOnPathMock).toHaveBeenCalledWith("curl");
- });
-});
diff --git a/apps/server/src/services/llm/providers/antigravity_hook.ts b/apps/server/src/services/llm/providers/antigravity_hook.ts
index a843d7d9df..154a57c584 100644
--- a/apps/server/src/services/llm/providers/antigravity_hook.ts
+++ b/apps/server/src/services/llm/providers/antigravity_hook.ts
@@ -17,7 +17,7 @@
import { existsSync, mkdirSync, realpathSync, writeFileSync } from "fs";
import path from "path";
-import { findOnPath } from "./binary_lookup.js";
+import { stringsIn } from "./acp_hook.js";
export interface AntigravityHookDecision {
decision: "allow" | "ask" | "deny";
@@ -37,7 +37,6 @@ const DENY_REASON = "Trilium does not allow access to this location. Use Trilium
/** How long the server waits for the hook, in seconds; `curl` gives up first. */
const HOOK_TIMEOUT_S = 10;
-const CURL_MAX_TIME_S = 8;
/**
* The answer to one `PreToolUse` call. `deny` when any path in the call's
@@ -82,62 +81,6 @@ export function writeAntigravityHooks(home: string, command: string): void {
writeFileSync(path.join(configDir, "hooks.json"), JSON.stringify(hooks, null, 2));
}
-/**
- * The hook command: `curl` posts the call (the hook's stdin) to Trilium and
- * prints the decision. `--fail` turns an error response into a failed hook,
- * which the server treats as a denial. `--noproxy` keeps an `HTTP_PROXY`
- * from routing the loopback request away from Trilium. The server runs it
- * with `sh -c`, or `cmd /c` on Windows; the URL holds no character either
- * shell reads.
- */
-export function buildHookCommand(curl: string, hookUrl: string): string {
- if (curl.includes("\"")) {
- throw new Error(`Cannot quote the path of curl for the agent hook: ${curl}`);
- }
- return `"${curl}" --silent --show-error --fail --noproxy 127.0.0.1 --max-time ${CURL_MAX_TIME_S} --data-binary @- ${hookUrl}`;
-}
-
-/** The in-flight or successful lookup; a failed one is forgotten so a later install is found. */
-let cachedCurl: Promise<string> | undefined;
-
-/** The absolute path of `curl`, which the hook runs. The path makes it independent of the server's PATH. */
-export function resolveCurlPath(): Promise<string> {
- if (!cachedCurl) {
- cachedCurl = findCurl().catch((err: unknown) => {
- cachedCurl = undefined;
- throw err;
- });
- }
- return cachedCurl;
-}
-
-/** For tests: forget the found `curl`. */
-export function resetCurlCache(): void {
- cachedCurl = undefined;
-}
-
-async function findCurl(): Promise<string> {
- const curl = await findOnPath("curl");
- if (!curl) {
- throw new Error("The Google Antigravity and OpenAI Codex providers need curl, which Trilium uses to control what the agent can access, and curl was not found. Install curl (it ships with Windows 10 and later and with macOS) and make sure it is on PATH.");
- }
- return curl;
-}
-
-/** Every string inside a hook call's arguments, however deeply nested. */
-export function stringsIn(value: unknown): string[] {
- if (typeof value === "string") {
- return [ value ];
- }
- if (Array.isArray(value)) {
- return value.flatMap(stringsIn);
- }
- if (value && typeof value === "object") {
- return Object.values(value).flatMap(stringsIn);
- }
- return [];
-}
-
function looksLikePath(value: string): boolean {
return path.isAbsolute(value) || value.startsWith(".") || /[\\/]/.test(value);
}
diff --git a/apps/server/src/services/llm/providers/binary_lookup.spec.ts b/apps/server/src/services/llm/providers/binary_lookup.spec.ts
index f8550c780e..688fe5bc95 100644
--- a/apps/server/src/services/llm/providers/binary_lookup.spec.ts
+++ b/apps/server/src/services/llm/providers/binary_lookup.spec.ts
@@ -12,7 +12,7 @@ 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 { extractPathFromShellEnv, findOnPath, needsShell, 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");
@@ -148,3 +148,13 @@ describe("extractPathFromShellEnv", () => {
expect(extractPathFromShellEnv("PATH=/spoofed")).toBeUndefined();
});
});
+
+describe("needsShell", () => {
+ it("is true only for .cmd/.bat shims", () => {
+ expect(needsShell("C:\\npm\\copilot.cmd")).toBe(true);
+ expect(needsShell("C:\\npm\\copilot.bat")).toBe(true);
+ expect(needsShell("C:\\npm\\copilot.CMD")).toBe(true);
+ expect(needsShell("/usr/bin/copilot")).toBe(false);
+ expect(needsShell("C:\\npm\\copilot.exe")).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/llm/providers/binary_lookup.ts b/apps/server/src/services/llm/providers/binary_lookup.ts
index e5bb64c145..1495ca5956 100644
--- a/apps/server/src/services/llm/providers/binary_lookup.ts
+++ b/apps/server/src/services/llm/providers/binary_lookup.ts
@@ -1,6 +1,6 @@
/**
- * Locates the bring-your-own-binary CLIs the agent providers drive (Claude
- * Code, GitHub Copilot).
+ * Locates and probes the bring-your-own-binary CLIs the agent providers drive
+ * (Claude Code, GitHub Copilot, Google Antigravity, OpenAI Codex).
*
* 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
@@ -52,6 +52,64 @@ export async function findOnPath(binary: string): Promise<string | undefined> {
return found;
}
+/**
+ * Memoize a binary probe: concurrent first calls share one run, and a failed
+ * one is forgotten so a later install is picked up without a restart.
+ */
+export function cachedProbe(probe: () => Promise<string>): { resolve: () => Promise<string>; reset: () => void } {
+ let cached: Promise<string> | undefined;
+ return {
+ resolve() {
+ if (!cached) {
+ cached = probe().catch((err: unknown) => {
+ cached = undefined;
+ throw err;
+ });
+ }
+ return cached;
+ },
+ reset() {
+ cached = undefined;
+ }
+ };
+}
+
+/**
+ * Runs `binary --version` with stdin closed and resolves with everything it
+ * printed, stdout before stderr. On failure, `failure` names the timeout or
+ * carries execFile's own message for a spawn or exit failure.
+ */
+export function runVersionProbe(binary: string, timeoutMs: number): Promise<{ output: string; failure?: string }> {
+ return new Promise((resolve) => {
+ // `shell` is required for the .cmd/.bat shims npm creates on Windows —
+ // Node refuses to spawn those directly (CVE-2024-27980). With a shell
+ // the command line is not auto-quoted, so quote the path ourselves.
+ const shell = needsShell(binary);
+ const options = { timeout: timeoutMs, encoding: "utf8" as const, shell };
+ const child = execFile(shell ? `"${binary}"` : binary, ["--version"], options, (err, stdout, stderr) => {
+ const output = [stdout, stderr].map((text) => text.trim()).filter(Boolean).join("\n");
+ if (!err) {
+ resolve({ output });
+ } else if (err.killed) {
+ resolve({ output, failure: `did not exit within ${timeoutMs / 1000} seconds` });
+ } else {
+ // execFile's message already quotes stderr after the command.
+ const failure = (err instanceof Error ? err.message : String(err)).trim();
+ resolve({ output: stdout.trim(), failure });
+ }
+ });
+ child.stdin?.end();
+ });
+}
+
+/**
+ * Whether the binary is an npm `.cmd`/`.bat` shim that can only be launched
+ * through a shell. Used by the version probe and the ACP spawn.
+ */
+export function needsShell(binary: string): boolean {
+ return /\.(cmd|bat)$/i.test(binary);
+}
+
/** For tests: forget the login shell's PATH so the next call re-reads it. */
export function resetLoginShellPathCache(): void {
cachedLoginShellPath = undefined;
diff --git a/apps/server/src/services/llm/providers/claude_binary.ts b/apps/server/src/services/llm/providers/claude_binary.ts
index ac1cd91c36..8255606cf2 100644
--- a/apps/server/src/services/llm/providers/claude_binary.ts
+++ b/apps/server/src/services/llm/providers/claude_binary.ts
@@ -20,30 +20,20 @@ import { execFile } from "child_process";
import { existsSync } from "fs";
import { promisify } from "util";
-import { findOnPath } from "./binary_lookup.js";
+import { cachedProbe, findOnPath } from "./binary_lookup.js";
const execFileAsync = promisify(execFile);
-/**
- * The in-flight/successful resolution. Caching the promise lets concurrent
- * first calls share one probe; a failed probe clears it so a later install is
- * picked up without a restart.
- */
-let cachedResolution: Promise<string> | undefined;
+/** The probed binary, shared by concurrent first calls (see {@link cachedProbe}). */
+const probed = cachedProbe(probeBinary);
export function resolveClaudeBinaryPath(): Promise<string> {
- if (!cachedResolution) {
- cachedResolution = probeBinary().catch((err: unknown) => {
- cachedResolution = undefined;
- throw err;
- });
- }
- return cachedResolution;
+ return probed.resolve();
}
/** For tests: forget the probed binary so the next call re-resolves. */
export function resetClaudeBinaryCache(): void {
- cachedResolution = undefined;
+ probed.reset();
}
async function probeBinary(): Promise<string> {
diff --git a/apps/server/src/services/llm/providers/codex_agent.spec.ts b/apps/server/src/services/llm/providers/codex_agent.spec.ts
index 2896fa04ec..52a4869357 100644
--- a/apps/server/src/services/llm/providers/codex_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/codex_agent.spec.ts
@@ -26,8 +26,8 @@ vi.mock("./acp_mcp_endpoint.js", () => ({
getAcpMcpEndpointUrl: async () => "http://127.0.0.1:12345/mcp-secret",
getAcpHookEndpointUrl: getAcpHookEndpointUrlMock
}));
-vi.mock("./antigravity_hook.js", async (importOriginal) => ({
- ...await importOriginal<typeof import("./antigravity_hook.js")>(),
+vi.mock("./acp_hook.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./acp_hook.js")>(),
resolveCurlPath: async () => "/usr/bin/curl"
}));
vi.mock("@triliumnext/core/src/services/llm/note_hint.js", () => ({ buildNoteHint: () => null }));
@@ -182,7 +182,7 @@ describe("CodexAgentProvider", () => {
it("signs in with ChatGPT during the model probe, but reports a missing sign-in in the chat instead", async () => {
FakeAcpClient.signedIn = false;
const chunks = await collect(new CodexAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));
- expect(chunks).toEqual([{ type: "error", error: expect.stringContaining("not signed in") }]);
+ expect(chunks).toEqual([{ type: "error", error: "OpenAI Codex is not signed in. Open this provider in the AI settings and go to the model selection, which opens the ChatGPT sign-in page in a browser on the device running Trilium." }]);
expect(FakeAcpClient.current?.methods()).not.toContain("authenticate");
await new CodexAgentProvider().listModels();
diff --git a/apps/server/src/services/llm/providers/codex_agent.ts b/apps/server/src/services/llm/providers/codex_agent.ts
index 16ea507428..72d87f3faa 100644
--- a/apps/server/src/services/llm/providers/codex_agent.ts
+++ b/apps/server/src/services/llm/providers/codex_agent.ts
@@ -20,10 +20,10 @@ import type { LlmProviderConfig, ModelInfo } from "@triliumnext/core/src/service
import path from "path";
import dataDirs from "../../data_dir.js";
-import { AcpAgentProvider, type AcpLaunchSpec, type AcpModel, type AcpNewSessionParams, type AcpPermissionOutcome, type AcpPermissionRequest, type AcpSessionModelState, type AcpToolCallUpdate, type BuiltInToolDisplay, denyPermission, describeError, NOTE_TOOLS_MCP_SERVER_NAME } from "./acp_agent.js";
-import { type AcpClient, AcpError } from "./acp_client.js";
+import { AcpAgentProvider, type AcpLaunchSpec, type AcpModel, type AcpNewSessionParams, type AcpPermissionOutcome, type AcpPermissionRequest, type AcpSessionModelState, type AcpToolCallUpdate, type BuiltInToolDisplay, denyPermission, describeError, nearestEffort, NOTE_TOOLS_MCP_SERVER_NAME, sortEfforts } from "./acp_agent.js";
+import type { AcpClient } from "./acp_client.js";
import { getAcpHookEndpointUrl } from "./acp_mcp_endpoint.js";
-import { buildHookCommand, resolveCurlPath } from "./antigravity_hook.js";
+import { buildHookCommand, resolveCurlPath } from "./acp_hook.js";
import { resolveCodexAcpScript, resolveCodexBinaryPath } from "./codex_binary.js";
import { buildCodexHookCommand, type CodexHookAnswer, codexSearchSources, decideCodexToolCall, describeWebrunInput, webrunFailure, writeCodexHooks } from "./codex_hook.js";
@@ -42,13 +42,6 @@ const AVAILABLE_MODELS: ModelInfo[] = [
/** The adapter's sign-in method for a ChatGPT account; its other one takes an API key, which the OpenAI provider serves. */
const SIGN_IN_METHOD = "chat-gpt";
-/** How long the add-provider screen waits for the user to finish signing in in the browser. */
-export const SIGN_IN_TIMEOUT_MS = 5 * 60_000;
-
-/** How long after a sign-in `session/new` is retried while Codex's account does not show it yet, and how often. */
-const SIGN_IN_SETTLE_MS = 10_000;
-const SIGN_IN_RETRY_MS = 500;
-
/**
* The settings the adapter merges into every session, as `CODEX_CONFIG`.
* Codex runs a hook only once the user has trusted it, which no one can do in
@@ -98,6 +91,7 @@ export class CodexAgentProvider extends AcpAgentProvider {
protected readonly fallbackModels = AVAILABLE_MODELS;
protected readonly defaultModelId = DEFAULT_MODEL_ID;
protected readonly agentDirName = path.join("codex-agent", "workspace");
+ protected readonly signIn = { methodId: SIGN_IN_METHOD, product: "OpenAI Codex", account: "ChatGPT" };
/**
* The newest models this Codex offers, and its default. Codex describes a
@@ -191,49 +185,15 @@ export class CodexAgentProvider extends AcpAgentProvider {
return { toolName, toolInput };
}
- /**
- * Open a session, signing in first when Codex has no saved sign-in and the
- * user is on the add-provider screen to complete it. The adapter opens the
- * ChatGPT sign-in page in a browser on the device running Trilium and
- * answers `authenticate` once the user has finished there; it keeps the
- * sign-in under `CODEX_HOME`, so later sessions need none.
- *
- * Codex reports the sign-in complete before its account shows it, so the
- * first `session/new` after it can still find no account; it is retried
- * for a few seconds.
- */
+ /** Remember the catalog of every session opened, which picks the variant a turn runs on. */
protected async createSession(client: AcpClient, params: AcpNewSessionParams, interactive: boolean, timeoutMs: number) {
- let created: Awaited<ReturnType<AcpAgentProvider["createSession"]>>;
- try {
- created = await super.createSession(client, params, interactive, timeoutMs);
- } catch (err) {
- if (!interactive || !isSignInRequired(err)) {
- throw err;
- }
- await client.request("authenticate", { methodId: SIGN_IN_METHOD }, SIGN_IN_TIMEOUT_MS);
- created = await this.createSessionAfterSignIn(client, params, timeoutMs);
- }
+ const created = await super.createSession(client, params, interactive, timeoutMs);
if (created.models) {
recordCatalog(created.models);
}
return created;
}
- /** `session/new` once a sign-in has completed, retried while Codex's account does not show it yet. */
- private async createSessionAfterSignIn(client: AcpClient, params: AcpNewSessionParams, timeoutMs: number) {
- const giveUpAt = Date.now() + SIGN_IN_SETTLE_MS;
- for (;;) {
- try {
- return await super.createSession(client, params, true, timeoutMs);
- } catch (err) {
- if (!isSignInRequired(err) || Date.now() >= giveUpAt) {
- throw err;
- }
- await new Promise(resolve => setTimeout(resolve, SIGN_IN_RETRY_MS));
- }
- }
- }
-
/** The turn, with the citation markers Codex writes into its reply taken out (see {@link CitationStripper}). */
async *chatChunks(messages: LlmMessage[], config: LlmProviderConfig, signal?: AbortSignal): AsyncIterable<LlmStreamChunk> {
const citations = new CitationStripper();
@@ -305,11 +265,9 @@ export class CodexAgentProvider extends AcpAgentProvider {
protected describeFailure(error: unknown): string {
const text = describeError(error);
- if (isSignInRequired(error)) {
- return "OpenAI Codex is not signed in. Open this provider in the AI settings and go to the model selection, which opens the ChatGPT sign-in page in a browser on the device running Trilium.";
- }
- if (/"authenticate" timed out/.test(text)) {
- return "The ChatGPT sign-in was not completed in time. Try again, and finish signing in in the browser window that opens on the device running Trilium.";
+ const signInFailure = this.describeSignInFailure(error);
+ if (signInFailure) {
+ return signInFailure;
}
if (/ENOENT|spawn/i.test(text)) {
return `Failed to start Codex: ${text}`;
@@ -380,14 +338,7 @@ export function resolveCodexModel(model: string, effort: LlmReasoningEffort | un
if (!levels?.length) {
return model;
}
- const wanted = LLM_REASONING_EFFORTS.indexOf(effort ?? defaultEffort(levels));
- let chosen = levels[0];
- for (const level of levels) {
- if (Math.abs(LLM_REASONING_EFFORTS.indexOf(level) - wanted) <= Math.abs(LLM_REASONING_EFFORTS.indexOf(chosen) - wanted)) {
- chosen = level;
- }
- }
- return `${model}[${chosen}]`;
+ return `${model}[${nearestEffort(levels, effort ?? defaultEffort(levels))}]`;
}
/** The catalog's models, variants of one model gathered into one entry. */
@@ -412,10 +363,7 @@ function groupCodexCatalog(remote: AcpSessionModelState) {
entry.efforts.push(effort);
}
}
- for (const entry of entries.values()) {
- entry.efforts.sort((a, b) => LLM_REASONING_EFFORTS.indexOf(a) - LLM_REASONING_EFFORTS.indexOf(b));
- }
- return [ ...entries.values() ];
+ return [ ...entries.values() ].map(entry => ({ ...entry, efforts: sortEfforts(entry.efforts) }));
}
/** Remember the variants and the title model of a catalog Codex reported. */
@@ -459,9 +407,6 @@ function agentHome(): string {
return path.resolve(dataDirs.TRILIUM_DATA_DIR, "codex-agent", "home");
}
-function isSignInRequired(error: unknown): boolean {
- return error instanceof AcpError && error.code === -32000 && /authentication required/i.test(error.message);
-}
/** A citation marker opens with U+E200, separates its parts with U+E202 and closes with U+E201, private-use characters. */
const MARKER_START = "\uE200";
diff --git a/apps/server/src/services/llm/providers/codex_binary.spec.ts b/apps/server/src/services/llm/providers/codex_binary.spec.ts
new file mode 100644
index 0000000000..e6395ba697
--- /dev/null
+++ b/apps/server/src/services/llm/providers/codex_binary.spec.ts
@@ -0,0 +1,99 @@
+import path from "path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+type ExecFileCallback = (err: Error | null, stdout: string, stderr: string) => void;
+const fakeChild = vi.hoisted(() => ({ stdin: { end: vi.fn() } }));
+const execFileMock = vi.hoisted(() => vi.fn<(binary: string, args: string[], options: object, cb: ExecFileCallback) => typeof fakeChild>());
+vi.mock("child_process", () => ({ execFile: execFileMock }));
+
+const existsSyncMock = vi.hoisted(() => vi.fn((_path: string) => true));
+vi.mock("fs", () => ({ existsSync: existsSyncMock }));
+
+const infoLogMock = vi.hoisted(() => vi.fn());
+vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: infoLogMock, error: vi.fn() }) }));
+vi.mock("../../resource_dir.js", () => ({ RESOURCE_DIR: "/opt/trilium/assets" }));
+
+const { resetCodexBinaryCache, resolveCodexAcpScript, resolveCodexBinaryPath } = await import("./codex_binary.js");
+const { resetLoginShellPathCache } = await import("./binary_lookup.js");
+
+describe("resolveCodexBinaryPath", () => {
+ const originalOverride = process.env.TRILIUM_CODEX_PATH;
+ const originalPath = process.env.PATH;
+ const originalShell = process.env.SHELL;
+
+ beforeEach(() => {
+ resetCodexBinaryCache();
+ resetLoginShellPathCache();
+ // No $SHELL: the login-shell fallback is a no-op (binary_lookup.spec.ts covers it).
+ delete process.env.SHELL;
+ execFileMock.mockReset();
+ infoLogMock.mockReset();
+ existsSyncMock.mockReset();
+ existsSyncMock.mockReturnValue(true);
+ process.env.TRILIUM_CODEX_PATH = "/opt/codex/codex";
+ });
+
+ afterEach(() => {
+ for (const [ name, value ] of [ [ "TRILIUM_CODEX_PATH", originalOverride ], [ "PATH", originalPath ], [ "SHELL", originalShell ] ] as const) {
+ if (value === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = value;
+ }
+ }
+ });
+
+ /** Answer the `--version` probe with `stdout`, or fail it with `err`. */
+ function probe(stdout: string, err: Error | null = null) {
+ execFileMock.mockImplementation((_binary, _args, _options, cb) => {
+ cb(err, stdout, "");
+ return fakeChild;
+ });
+ }
+
+ it("probes the binary once, with stdin closed, and logs the version it reports", async () => {
+ probe("codex-cli 0.156.1\n");
+
+ await expect(Promise.all([ resolveCodexBinaryPath(), resolveCodexBinaryPath() ])).resolves.toEqual([ "/opt/codex/codex", "/opt/codex/codex" ]);
+ expect(execFileMock).toHaveBeenCalledOnce();
+ expect(execFileMock.mock.calls[0].slice(0, 2)).toEqual([ "/opt/codex/codex", [ "--version" ] ]);
+ expect(fakeChild.stdin.end).toHaveBeenCalled();
+ expect(infoLogMock).toHaveBeenCalledWith(expect.stringContaining("(0.156.1)"));
+ });
+
+ it("names what went wrong with an install, and probes again once it is fixed", async () => {
+ probe("", new Error("spawn EACCES"));
+ await expect(resolveCodexBinaryPath()).rejects.toThrow(/failed to run \(spawn EACCES\).*npm install -g @openai\/codex/s);
+
+ probe("usage: codex [OPTIONS]\n");
+ await expect(resolveCodexBinaryPath()).rejects.toThrow(/did not report a version \(it printed: usage: codex \[OPTIONS\]\)/);
+
+ probe("codex-cli 0.146.0\n");
+ await expect(resolveCodexBinaryPath()).resolves.toBe("/opt/codex/codex");
+ });
+
+ it("finds codex on PATH, and says how to install it when it is nowhere", async () => {
+ delete process.env.TRILIUM_CODEX_PATH;
+ process.env.PATH = [ "/usr/local/bin", "/usr/bin" ].join(path.delimiter);
+ existsSyncMock.mockImplementation(candidate => candidate === path.join("/usr/bin", "codex"));
+ probe("codex-cli 0.156.1\n");
+ await expect(resolveCodexBinaryPath()).resolves.toBe(path.join("/usr/bin", "codex"));
+
+ resetCodexBinaryCache();
+ existsSyncMock.mockReturnValue(false);
+ await expect(resolveCodexBinaryPath()).rejects.toThrow(/Codex CLI \(codex\) was not found/);
+
+ process.env.TRILIUM_CODEX_PATH = "/nowhere/codex";
+ await expect(resolveCodexBinaryPath()).rejects.toThrow(`TRILIUM_CODEX_PATH is set to "/nowhere/codex", but no file exists there.`);
+ });
+});
+
+describe("resolveCodexAcpScript", () => {
+ it("runs the copy the build placed under RESOURCE_DIR, else the installed package", () => {
+ existsSyncMock.mockReturnValue(true);
+ expect(resolveCodexAcpScript()).toBe(path.join("/opt/trilium/assets", "codex-acp.mjs"));
+
+ existsSyncMock.mockReturnValue(false);
+ expect(resolveCodexAcpScript()).toMatch(/@agentclientprotocol[\\/]codex-acp[\\/]dist[\\/]index\.js$/);
+ });
+});
diff --git a/apps/server/src/services/llm/providers/codex_binary.ts b/apps/server/src/services/llm/providers/codex_binary.ts
index 9b1c235b9e..bfefa2c74d 100644
--- a/apps/server/src/services/llm/providers/codex_binary.ts
+++ b/apps/server/src/services/llm/providers/codex_binary.ts
@@ -15,41 +15,26 @@
*/
import { getLog } from "@triliumnext/core";
-import { execFile } from "child_process";
import { existsSync } from "fs";
import path from "path";
-import { promisify } from "util";
import { RESOURCE_DIR } from "../../resource_dir.js";
-import { findOnPath } from "./binary_lookup.js";
-import { needsShell } from "./copilot_binary.js";
-
-const execFileAsync = promisify(execFile);
+import { cachedProbe, findOnPath, runVersionProbe } from "./binary_lookup.js";
const PROBE_TIMEOUT_MS = 15000;
const INSTALL_HINT = "Install it (for example with `npm install -g @openai/codex`) on the machine running the Trilium server, or set the TRILIUM_CODEX_PATH environment variable to its location.";
-/**
- * The in-flight/successful resolution. Caching the promise lets concurrent
- * first calls share one probe; a failed probe clears it so a later install is
- * picked up without a restart.
- */
-let cachedResolution: Promise<string> | undefined;
+/** The probed binary, shared by concurrent first calls (see {@link cachedProbe}). */
+const probed = cachedProbe(probeBinary);
export function resolveCodexBinaryPath(): Promise<string> {
- if (!cachedResolution) {
- cachedResolution = probeBinary().catch((err: unknown) => {
- cachedResolution = undefined;
- throw err;
- });
- }
- return cachedResolution;
+ return probed.resolve();
}
/** For tests: forget the probed binary so the next call re-resolves. */
export function resetCodexBinaryCache(): void {
- cachedResolution = undefined;
+ probed.reset();
}
/**
@@ -66,16 +51,9 @@ async function probeBinary(): Promise<string> {
// Async on purpose — this runs on the first chat request, and a sync probe
// would freeze the whole server for up to the timeout.
- let output: string;
- try {
- // `shell` is required for the .cmd shim npm creates on Windows, and
- // then the path is not quoted for us.
- const shell = needsShell(binary);
- const { stdout } = await execFileAsync(shell ? `"${binary}"` : binary, ["--version"], { timeout: PROBE_TIMEOUT_MS, encoding: "utf8", shell });
- output = stdout.trim();
- } catch (err) {
- const detail = err instanceof Error ? err.message : String(err);
- throw new Error(`Found the Codex CLI at "${binary}" but it failed to run (${detail}). ${INSTALL_HINT}`);
+ const { output, failure } = await runVersionProbe(binary, PROBE_TIMEOUT_MS);
+ if (failure) {
+ throw new Error(`Found the Codex CLI at "${binary}" but it failed to run (${failure}). ${INSTALL_HINT}`);
}
const version = /\d+\.\d+\.\d+\S*/.exec(output)?.[0];
diff --git a/apps/server/src/services/llm/providers/codex_hook.spec.ts b/apps/server/src/services/llm/providers/codex_hook.spec.ts
index e3a6bda372..5281ee7087 100644
--- a/apps/server/src/services/llm/providers/codex_hook.spec.ts
+++ b/apps/server/src/services/llm/providers/codex_hook.spec.ts
@@ -4,7 +4,7 @@ import os from "os";
import path from "path";
import { describe, expect, it } from "vitest";
-import { resolveCurlPath } from "./antigravity_hook.js";
+import { resolveCurlPath } from "./acp_hook.js";
import { buildCodexHookCommand, codexSearchSources, decideCodexToolCall, describeWebrunInput, webrunFailure, writeCodexHooks } from "./codex_hook.js";
/** `PreToolUse` events as Codex 0.146.0 and 0.156.1 send them, less the session bookkeeping. */
diff --git a/apps/server/src/services/llm/providers/codex_hook.ts b/apps/server/src/services/llm/providers/codex_hook.ts
index 41f4fd9691..7ebc5c03b6 100644
--- a/apps/server/src/services/llm/providers/codex_hook.ts
+++ b/apps/server/src/services/llm/providers/codex_hook.ts
@@ -24,7 +24,7 @@ import { mkdirSync, writeFileSync } from "fs";
import path from "path";
import { type BuiltInToolDisplay, NOTE_TOOLS_MCP_SERVER_NAME } from "./acp_agent.js";
-import { buildHookCommand, stringsIn } from "./antigravity_hook.js";
+import { buildHookCommand, stringsIn } from "./acp_hook.js";
import { type HostLookup, isPublicHttpUrl } from "./public_url.js";
/** What the hook prints: no decision leaves the call to Codex, a `deny` stops it. */
diff --git a/apps/server/src/services/llm/providers/copilot_agent.spec.ts b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
index 2eec9cef52..f5d987a003 100644
--- a/apps/server/src/services/llm/providers/copilot_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
@@ -23,10 +23,7 @@ const AGENT_CWD = path.resolve(os.tmpdir(), "trilium-copilot-agent-spec", "copil
// BYO binary resolution shells out to the user's `copilot`; stub it.
const resolveCopilotBinaryMock = vi.hoisted(() => vi.fn(async () => "/usr/bin/copilot"));
-vi.mock("./copilot_binary.js", () => ({
- resolveCopilotBinaryPath: resolveCopilotBinaryMock,
- needsShell: () => false
-}));
+vi.mock("./copilot_binary.js", () => ({ resolveCopilotBinaryPath: resolveCopilotBinaryMock }));
// The loopback MCP endpoint opens a real socket; stub it to a fixed URL.
const mcpEndpointMock = vi.hoisted(() => vi.fn(async () => "http://127.0.0.1:12345/mcp-secret"));
diff --git a/apps/server/src/services/llm/providers/copilot_agent.ts b/apps/server/src/services/llm/providers/copilot_agent.ts
index 42b69eb19d..97fec4283c 100644
--- a/apps/server/src/services/llm/providers/copilot_agent.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.ts
@@ -17,7 +17,8 @@ import type { ModelInfo } from "@triliumnext/core/src/services/llm/types.js";
import { AcpAgentProvider, type AcpLaunchSpec, type AcpModel, type AcpSessionModelState, describeError, resetAcpAgentStateForTests } from "./acp_agent.js";
import { AcpError } from "./acp_client.js";
-import { needsShell, resolveCopilotBinaryPath } from "./copilot_binary.js";
+import { needsShell } from "./binary_lookup.js";
+import { resolveCopilotBinaryPath } from "./copilot_binary.js";
/**
* The catalog available without asking the CLI. It holds only the two ids the
diff --git a/apps/server/src/services/llm/providers/copilot_binary.spec.ts b/apps/server/src/services/llm/providers/copilot_binary.spec.ts
index 0a77606c90..dda2f5a49d 100644
--- a/apps/server/src/services/llm/providers/copilot_binary.spec.ts
+++ b/apps/server/src/services/llm/providers/copilot_binary.spec.ts
@@ -13,7 +13,7 @@ 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 { resetCopilotBinaryCache, resolveCopilotBinaryPath } = await import("./copilot_binary.js");
const { resetLoginShellPathCache } = await import("./binary_lookup.js");
describe("resolveCopilotBinaryPath", () => {
@@ -213,14 +213,4 @@ describe("resolveCopilotBinaryPath", () => {
expect(execFileMock).not.toHaveBeenCalled();
});
});
-
- describe("needsShell", () => {
- it("is true only for .cmd/.bat shims", () => {
- expect(needsShell("C:\\npm\\copilot.cmd")).toBe(true);
- expect(needsShell("C:\\npm\\copilot.bat")).toBe(true);
- expect(needsShell("C:\\npm\\copilot.CMD")).toBe(true);
- expect(needsShell("/usr/bin/copilot")).toBe(false);
- expect(needsShell("C:\\npm\\copilot.exe")).toBe(false);
- });
- });
});
diff --git a/apps/server/src/services/llm/providers/copilot_binary.ts b/apps/server/src/services/llm/providers/copilot_binary.ts
index 232169509f..778aff9b4e 100644
--- a/apps/server/src/services/llm/providers/copilot_binary.ts
+++ b/apps/server/src/services/llm/providers/copilot_binary.ts
@@ -21,33 +21,22 @@
*/
import { getLog } from "@triliumnext/core";
-import { execFile } from "child_process";
import { existsSync } from "fs";
-import { findOnPath } from "./binary_lookup.js";
+import { cachedProbe, findOnPath, runVersionProbe } from "./binary_lookup.js";
const PROBE_TIMEOUT_MS = 15000;
-/**
- * The in-flight/successful resolution. Caching the promise lets concurrent
- * first calls share one probe; a failed probe clears it so a later install is
- * picked up without a restart.
- */
-let cachedResolution: Promise<string> | undefined;
+/** The probed binary, shared by concurrent first calls (see {@link cachedProbe}). */
+const probed = cachedProbe(probeBinary);
export function resolveCopilotBinaryPath(): Promise<string> {
- if (!cachedResolution) {
- cachedResolution = probeBinary().catch((err: unknown) => {
- cachedResolution = undefined;
- throw err;
- });
- }
- return cachedResolution;
+ return probed.resolve();
}
/** For tests: forget the probed binary so the next call re-resolves. */
export function resetCopilotBinaryCache(): void {
- cachedResolution = undefined;
+ probed.reset();
}
async function probeBinary(): Promise<string> {
@@ -57,7 +46,7 @@ async function probeBinary(): Promise<string> {
// wrong-arch/broken install) and records the version for diagnostics.
// Async on purpose — this runs on the first chat request, and a sync probe
// would freeze the whole server for up to the timeout.
- const { output, failure } = await runVersionProbe(binary);
+ const { output, failure } = await runVersionProbe(binary, PROBE_TIMEOUT_MS);
const version = failure ? undefined : output.split("\n").find((line) => /\d+\.\d+\.\d+/.test(line))?.trim();
if (!version) {
const reason = failure ?? "did not report a version";
@@ -74,34 +63,6 @@ async function probeBinary(): Promise<string> {
return binary;
}
-/**
- * Runs `binary --version` with stdin closed and resolves with everything it
- * printed, stdout before stderr. On failure, `failure` names the timeout or
- * carries execFile's own message for a spawn or exit failure.
- */
-function runVersionProbe(binary: string): Promise<{ output: string; failure?: string }> {
- return new Promise((resolve) => {
- // `shell` is required for the .cmd/.bat shims npm creates on Windows —
- // Node refuses to spawn those directly (CVE-2024-27980). With a shell
- // the command line is not auto-quoted, so quote the path ourselves.
- const shell = needsShell(binary);
- const options = { timeout: PROBE_TIMEOUT_MS, encoding: "utf8" as const, shell };
- const child = execFile(shell ? `"${binary}"` : binary, ["--version"], options, (err, stdout, stderr) => {
- const output = [stdout, stderr].map((text) => text.trim()).filter(Boolean).join("\n");
- if (!err) {
- resolve({ output });
- } else if (err.killed) {
- resolve({ output, failure: `did not exit within ${PROBE_TIMEOUT_MS / 1000} seconds` });
- } else {
- // execFile's message already quotes stderr after the command.
- const failure = (err instanceof Error ? err.message : String(err)).trim();
- resolve({ output: stdout.trim(), failure });
- }
- });
- child.stdin?.end();
- });
-}
-
async function locateBinary(): Promise<string> {
const override = process.env.TRILIUM_COPILOT_PATH?.trim();
if (override) {
@@ -118,11 +79,3 @@ async function locateBinary(): Promise<string> {
throw new Error("GitHub Copilot CLI not found. Install it (`npm install -g @github/copilot`) and run `copilot login` on the machine running the Trilium server, or set the TRILIUM_COPILOT_PATH environment variable to its location.");
}
-
-/**
- * Whether the binary is an npm `.cmd`/`.bat` shim that can only be launched
- * through a shell. Used by both the probe and the ACP spawn.
- */
-export function needsShell(binary: string): boolean {
- return /\.(cmd|bat)$/i.test(binary);
-}