Skip to content

Build your personal knowledge base with Trilium Notes

refactor(llm): share the ACP agent plumbing between providers

Elian Doranb6c2a37bbf7a
diff --git a/apps/server/src/services/llm/providers/acp_agent.ts b/apps/server/src/services/llm/providers/acp_agent.ts
new file mode 100644
index 0000000000..01561aa023
--- /dev/null
+++ b/apps/server/src/services/llm/providers/acp_agent.ts
@@ -0,0 +1,798 @@
+/**
+ * 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:
+ * - implements `chatChunks()` (chunk-native streaming) instead of `chat()`,
+ * - maps chat notes to ACP sessions and sends only the newest user message
+ * when the transcript still matches (`session/load`), falling back to
+ * seeding a fresh session from the transcript when it diverged or was lost,
+ * - exposes note tools by pointing the agent at a private loopback MCP
+ * endpoint (see acp_mcp_endpoint.ts), and answers the ACP permission
+ * callback fail-closed.
+ *
+ * A subclass supplies how to launch its CLI, its model catalog and its
+ * permission policy; the protocol handling lives here.
+ */
+
+import type { LlmMessage, LlmMessagePart, 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";
+import { buildSystemPrompt } from "@triliumnext/core/src/services/llm/system_prompt.js";
+import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "@triliumnext/core/src/services/llm/types.js";
+import { encodeBase64 } from "@triliumnext/core/src/services/utils/binary.js";
+import fs from "fs";
+import path from "path";
+
+import dataDirs from "../../data_dir.js";
+import { AcpClient } from "./acp_client.js";
+import { getAcpMcpEndpointUrl } from "./acp_mcp_endpoint.js";
+import { attachmentPlaceholder, buildHistoryReplay, hashTranscript } from "./transcript.js";
+
+/** How an ACP provider starts its agent subprocess. */
+export interface AcpLaunchSpec {
+ binary: string;
+ args: string[];
+ /** Launch through a shell (npm `.cmd` shims on Windows). */
+ shell?: boolean;
+ /** Variables set on top of the server's own environment. */
+ env?: Record<string, string>;
+}
+
+/** The ACP permission callback's answer. */
+export type AcpPermissionOutcome = { outcome: { outcome: "selected"; optionId: string } | { outcome: "cancelled" } };
+
+export interface AcpPermissionRequest {
+ sessionId?: string;
+ toolCall?: {
+ toolCallId?: string;
+ title?: string;
+ kind?: string;
+ rawInput?: unknown;
+ /** Agent-specific metadata, set by the agent itself rather than by the model. */
+ _meta?: Record<string, unknown>;
+ };
+ options?: { optionId: string; name?: string; kind?: string }[];
+}
+
+/** The `models` block of a `session/new` response — ACP's model-selection state. */
+export interface AcpSessionModelState {
+ availableModels?: AcpModel[];
+ /** The model the session starts on. */
+ currentModelId?: string;
+}
+
+export interface AcpModel {
+ modelId: string;
+ name?: string;
+ description?: string;
+ /** Vendor extensions ACP itself doesn't define. */
+ _meta?: Record<string, unknown>;
+}
+
+/** Parameters of `session/new`. */
+export interface AcpNewSessionParams {
+ cwd: string;
+ mcpServers: AcpMcpServer[];
+}
+
+type AcpMcpServer = { name: string; type: "http"; url: string; headers: never[] };
+
+/** Image media types the ACP prompt accepts as a base64 image block. */
+const SUPPORTED_IMAGE_MIMES = new Set<string>(["image/png", "image/jpeg", "image/gif", "image/webp"]);
+
+/**
+ * How long a probed catalog is reused. The line-up changes with the vendor's
+ * releases and the user's plan, neither of which moves within an editing
+ * session, and the probe costs a CLI spawn.
+ */
+const MODEL_CATALOG_TTL_MS = 60 * 60 * 1000;
+
+/** Upper bound on the catalog probe — a spawn plus one round-trip, no prompt. */
+const MODEL_PROBE_TIMEOUT_MS = 60_000;
+
+export const INIT_TIMEOUT_MS = 30_000;
+export const SESSION_TIMEOUT_MS = 120_000;
+/** Upper bound for a whole prompt turn (agentic loops included). */
+const PROMPT_TIMEOUT_MS = 15 * 60_000;
+
+/** Session mappings kept per chat note; bounded to avoid unbounded growth. */
+const MAX_TRACKED_SESSIONS = 200;
+
+/** The name the loopback MCP server is registered under in `session/new`. */
+export const NOTE_TOOLS_MCP_SERVER_NAME = "trilium";
+
+interface SessionEntry {
+ sessionId: string;
+ /** Hash of the transcript as it stood when the session last responded. */
+ transcriptHash: string;
+}
+
+/**
+ * What an ACP provider keeps between instances. The chat builds a provider per
+ * configuration and the add-provider screen builds throwaway ones, but sessions
+ * and the probed catalog belong to the agent on this host, so they are kept per
+ * provider type rather than per instance.
+ */
+interface ProviderState {
+ /**
+ * chatNoteId → ACP session. In-memory only: the CLI's sessions live on this
+ * host, so the mapping must not sync across devices. Losing it (e.g. on
+ * restart) is fine — the provider reseeds a fresh session from the
+ * transcript the client sends.
+ */
+ sessionsByChatNote: Map<string, SessionEntry>;
+ modelCatalogCache?: { models: ModelInfo[]; fetchedAt: number };
+ modelCatalogInFlight?: Promise<ModelInfo[]>;
+ agentCwd?: string;
+}
+
+const stateByProvider = new Map<string, ProviderState>();
+
+/** For tests: forget every provider's sessions, catalog and agent cwd. */
+export function resetAcpAgentStateForTests(): void {
+ stateByProvider.clear();
+}
+
+export abstract class AcpAgentProvider implements LlmProvider {
+ abstract name: string;
+
+ /** Prefix for log lines, e.g. "Copilot Agent provider". */
+ protected abstract readonly logLabel: string;
+
+ /**
+ * The catalog available without asking the CLI anything.
+ *
+ * {@link listModels} reads the real line-up off `session/new`, but that
+ * costs a subprocess and a round-trip, and the {@link LlmProvider} interface
+ * also needs a *synchronous* answer: the chat resolves its default model and
+ * display name through `getAvailableModels()` on every turn, which cannot
+ * wait on a spawn. It holds only the ids the provider itself names, rather
+ * than a mirror of a vendor line-up that changes with every release.
+ */
+ protected abstract readonly fallbackModels: ModelInfo[];
+
+ /** The model id that leaves the agent on its own default, so no `session/set_model` is sent. */
+ protected abstract readonly defaultModelId: string;
+
+ /** Directory, relative to the data dir, that the agent runs in. */
+ protected abstract readonly agentDirName: string;
+
+ /** How to spawn the agent. Resolving the binary can fail with an actionable message. */
+ protected abstract launchSpec(): Promise<AcpLaunchSpec>;
+
+ /** Turn the catalog the agent reported on `session/new` into Trilium's model list. */
+ protected abstract buildModelList(remote: AcpSessionModelState): ModelInfo[];
+
+ abstract recommendedModelIds(models: ModelInfo[]): Set<string>;
+
+ /** The cheap model for the title turn, if the agent offers one. */
+ protected titleModelId(): string | undefined {
+ return undefined;
+ }
+
+ /**
+ * Permission policy. The default denies every request; a subclass whose
+ * agent asks before running Trilium's own note tools approves those.
+ */
+ protected decidePermission(request: AcpPermissionRequest): AcpPermissionOutcome {
+ return denyPermission(request, this.logLabel);
+ }
+
+ /** Map a failure to an actionable message. */
+ protected describeFailure(error: unknown): string {
+ return describeError(error);
+ }
+
+ /**
+ * 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.
+ */
+ protected async createSession(client: AcpClient, params: AcpNewSessionParams, _interactive: boolean, timeoutMs: number) {
+ return await client.request<{ sessionId: string; models?: AcpSessionModelState }>("session/new", params, timeoutMs);
+ }
+
+ /**
+ * Free at the point of use for every model, discovered ones included: the
+ * subscription covers the whole catalog, so an id this build has never heard
+ * of still costs nothing per token. Only ids that aren't the provider's at
+ * all come back unpriced.
+ */
+ getModelPricing(model: string): ModelPricing | undefined {
+ const known = this.state().modelCatalogCache?.models ?? this.fallbackModels;
+ return known.some(m => m.id === model) ? { input: 0, output: 0 } : undefined;
+ }
+
+ getAvailableModels(): ModelInfo[] {
+ return this.fallbackModels;
+ }
+
+ /**
+ * The models this account may use, as the installed CLI reports them.
+ *
+ * There is no `/models` endpoint to call: the catalog arrives on the
+ * `session/new` response, which reflects the CLI's version and the plan the
+ * user is signed in under. Opening a session sends no prompt, so the probe
+ * spends no quota.
+ *
+ * Cached for {@link MODEL_CATALOG_TTL_MS}, with concurrent callers sharing
+ * one probe. A *failure* propagates rather than falling back to
+ * {@link fallbackModels}, so the add/edit-provider screen can say the CLI is
+ * missing or signed out instead of showing models that would fail on first
+ * use.
+ */
+ async listModels(): Promise<ModelInfo[]> {
+ const state = this.state();
+ if (state.modelCatalogCache && Date.now() - state.modelCatalogCache.fetchedAt < MODEL_CATALOG_TTL_MS) {
+ return state.modelCatalogCache.models;
+ }
+ if (!state.modelCatalogInFlight) {
+ state.modelCatalogInFlight = this.probeModelCatalog().finally(() => {
+ state.modelCatalogInFlight = undefined;
+ });
+ }
+ return state.modelCatalogInFlight;
+ }
+
+ /**
+ * Open a session purely to read the catalog off its response, then tear the
+ * CLI down. No `session/prompt` is ever sent, and note tools are left out of
+ * the session — nothing is asked of the agent, so it needs no capabilities.
+ */
+ private async probeModelCatalog(): Promise<ModelInfo[]> {
+ let client: AcpClient | undefined;
+ try {
+ client = await this.startClient(() => {});
+ const created = await this.createSession(client, { cwd: this.agentCwd(), mcpServers: [] }, true, MODEL_PROBE_TIMEOUT_MS);
+ const models = this.buildModelList(created.models ?? {});
+ this.state().modelCatalogCache = { models, fetchedAt: Date.now() };
+ return models;
+ } catch (err) {
+ // Name the reason (binary missing, not signed in, timeout) so the
+ // provider screen can show something the user can act on.
+ throw new Error(this.describeFailure(err));
+ } finally {
+ client?.dispose();
+ }
+ }
+
+ /** Not used — the route prefers {@link chatChunks} when implemented. */
+ chat(): StreamResult {
+ throw new Error(`The ${this.logLabel} streams chunks directly; use chatChunks().`);
+ }
+
+ async *chatChunks(messages: LlmMessage[], config: LlmProviderConfig, signal?: AbortSignal): AsyncIterable<LlmStreamChunk> {
+ if (signal?.aborted) {
+ // The client is gone — don't spawn an agent subprocess nobody
+ // will read from.
+ return;
+ }
+
+ const conversation = messages.filter(m => m.role !== "system");
+ const lastMessage = conversation[conversation.length - 1];
+ if (!lastMessage || lastMessage.role !== "user") {
+ yield { type: "error", error: "The last message must be a user message." };
+ return;
+ }
+
+ const sessionsByChatNote = this.state().sessionsByChatNote;
+ const history = conversation.slice(0, -1);
+ const historyHash = hashTranscript(history);
+ const stored = config.chatNoteId ? sessionsByChatNote.get(config.chatNoteId) : undefined;
+ const resume = stored && stored.transcriptHash === historyHash ? stored.sessionId : undefined;
+
+ // A config that does not mention the note tools does not get them, as `base_provider` reads
+ // it and as the AI-SDK providers therefore behave — what a request leaves unsaid has to
+ // mean the same thing whichever provider answers it.
+ const noteToolsEnabled = !!config.enableNoteTools;
+ const model = config.model || this.defaultModelId;
+
+ // Queue between the ACP notification callback and this generator: the
+ // callback is synchronous while consumption is async, so updates are
+ // buffered and drained in arrival order.
+ const chunkQueue: LlmStreamChunk[] = [];
+ let wakeup: (() => void) | undefined;
+ const emit = (chunk: LlmStreamChunk) => {
+ chunkQueue.push(chunk);
+ wakeup?.();
+ };
+
+ const collector = createUpdateCollector(emit);
+ let client: AcpClient | undefined;
+ let sessionId: string | undefined;
+ let assistantText = "";
+
+ try {
+ client = await this.startClient(collector.onNotification);
+
+ const mcpServers = noteToolsEnabled ? await buildMcpServersConfig() : [];
+
+ // Resume the existing session only when the transcript still
+ // matches what it last saw; any divergence (edited history, lost
+ // mapping, server restart) reseeds a fresh session. session/load
+ // replays the session's history as notifications — the collector
+ // suppresses everything until the load completes.
+ if (resume) {
+ collector.muted = true;
+ try {
+ await client.request("session/load", { sessionId: resume, cwd: this.agentCwd(), mcpServers }, SESSION_TIMEOUT_MS);
+ sessionId = resume;
+ } catch (err) {
+ getLog().info(`${this.logLabel}: session/load failed (${describeError(err)}); reseeding a fresh session.`);
+ } finally {
+ collector.muted = false;
+ }
+ }
+
+ if (!sessionId) {
+ const created = await this.createSession(client, { cwd: this.agentCwd(), mcpServers }, false, SESSION_TIMEOUT_MS);
+ sessionId = created.sessionId;
+ }
+ collector.sessionId = sessionId;
+
+ if (model !== this.defaultModelId) {
+ // Model selection is an optional ACP capability — degrade to the
+ // agent's default rather than failing the turn.
+ try {
+ await client.request("session/set_model", { sessionId, modelId: model }, INIT_TIMEOUT_MS);
+ } catch (err) {
+ getLog().error(`${this.logLabel}: failed to select model "${model}" (${describeError(err)}); continuing with the agent's default.`);
+ }
+ }
+
+ // Text that precedes this turn's own content: the system
+ // instructions and replayed transcript when the session is fresh,
+ // then the volatile current-note metadata hint (kept out of the
+ // transcript hash so a later turn can still resume).
+ const isFreshSession = sessionId !== resume;
+ const hasAttachments = Array.isArray(lastMessage.content) && lastMessage.content.some(p => p.type !== "text");
+ const noteHint = config.contextNoteId ? buildNoteHint(config.contextNoteId, hasAttachments) : null;
+ const prefix = [
+ isFreshSession ? wrapSystemInstructions(composeSystemPrompt(messages, { ...config, enableNoteTools: noteToolsEnabled })) : null,
+ (isFreshSession && history.length > 0) ? buildHistoryReplay(history) : null,
+ noteHint
+ ].filter((s): s is string => Boolean(s)).join("\n\n");
+
+ const onAbort = () => {
+ if (sessionId) {
+ client?.notify("session/cancel", { sessionId });
+ }
+ // Wake the drain loop below: an agent slow to honour the cancel
+ // (or ignoring it) would otherwise keep this generator — and its
+ // subprocess — suspended until PROMPT_TIMEOUT_MS elapses.
+ wakeup?.();
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+
+ try {
+ const promptPromise = client.request<{ stopReason?: string }>(
+ "session/prompt",
+ { sessionId, prompt: buildPromptBlocks(lastMessage.content, prefix) },
+ PROMPT_TIMEOUT_MS
+ );
+
+ // Drain updates as they arrive until the prompt resolves (and
+ // then whatever is still queued).
+ let result: { stopReason?: string } | undefined;
+ let promptError: unknown;
+ const done = promptPromise
+ .then(r => { result = r; })
+ .catch(err => { promptError = err; })
+ .finally(() => wakeup?.());
+
+ let finished = false;
+ void done.then(() => { finished = true; wakeup?.(); });
+ // On abort, drain what already arrived and stop — nobody is
+ // reading past this point, and `finally` disposes the client.
+ while ((!finished && !signal?.aborted) || chunkQueue.length > 0) {
+ if (chunkQueue.length === 0) {
+ await new Promise<void>(resolve => { wakeup = resolve; });
+ wakeup = undefined;
+ continue;
+ }
+ const chunk = chunkQueue.shift();
+ if (chunk) {
+ if (chunk.type === "text") {
+ assistantText += chunk.content;
+ }
+ yield chunk;
+ }
+ }
+ if (promptError) {
+ throw promptError;
+ }
+
+ const stopReason = result?.stopReason ?? "end_turn";
+ if (stopReason !== "end_turn" && stopReason !== "cancelled") {
+ yield { type: "error", error: describeStopReason(stopReason) };
+ }
+ } finally {
+ signal?.removeEventListener("abort", onAbort);
+ }
+
+ // An aborted turn stops draining before the agent settles, so the
+ // session's real history is unknown — recording a hash here would
+ // let a later turn resume a session that diverged from the
+ // transcript. Forgetting it just reseeds a fresh one.
+ if (config.chatNoteId && sessionId && !signal?.aborted) {
+ rememberSession(sessionsByChatNote, config.chatNoteId, {
+ sessionId,
+ transcriptHash: hashTranscript([
+ ...conversation,
+ { role: "assistant", content: assistantText }
+ ])
+ });
+ }
+
+ yield { type: "done" };
+ } catch (error) {
+ yield { type: "error", error: this.describeFailure(error) };
+ } finally {
+ client?.dispose();
+ }
+ }
+
+ async generateTitle(firstMessage: string): Promise<string> {
+ let client: AcpClient | undefined;
+ try {
+ let title = "";
+ client = await this.startClient((method, params) => {
+ if (method !== "session/update") {
+ return;
+ }
+ const update = (params as AcpSessionUpdate).update;
+ if (update?.sessionUpdate === "agent_message_chunk" && update.content && "text" in update.content && update.content.type === "text") {
+ title += update.content.text;
+ }
+ });
+
+ const { sessionId } = await this.createSession(client, { cwd: this.agentCwd(), mcpServers: [] }, false, SESSION_TIMEOUT_MS);
+ const titleModel = this.titleModelId();
+ if (titleModel) {
+ try {
+ await client.request("session/set_model", { sessionId, modelId: titleModel }, INIT_TIMEOUT_MS);
+ } catch {
+ // Title generation works on any model; ignore selection failures.
+ }
+ }
+ await client.request(
+ "session/prompt",
+ {
+ sessionId,
+ prompt: [{
+ type: "text",
+ text: `Generate a short title (at most 5 words) summarizing this chat message. Reply with only the title, no quotes or punctuation around it:\n\n${firstMessage.substring(0, 500)}`
+ }]
+ },
+ SESSION_TIMEOUT_MS
+ );
+ return title.trim().replace(/^["']|["']$/g, "").substring(0, 100);
+ } catch (error) {
+ getLog().error(`${this.logLabel} title generation failed: ${this.describeFailure(error)}`);
+ return "";
+ } finally {
+ client?.dispose();
+ }
+ }
+
+ /** Spawn the agent and run the ACP initialize handshake. */
+ protected async startClient(onNotification: (method: string, params: unknown) => void): Promise<AcpClient> {
+ const launch = await this.launchSpec();
+ const client = AcpClient.start(launch.binary, {
+ cwd: this.agentCwd(),
+ shell: launch.shell,
+ args: launch.args,
+ env: launch.env,
+ onNotification,
+ onAgentRequest: (method, params) => this.handleAgentRequest(method, params)
+ });
+ try {
+ await client.request(
+ "initialize",
+ {
+ protocolVersion: 1,
+ clientInfo: { name: "trilium-notes", version: "1.0" },
+ // No fs capabilities: the agent must never touch the host
+ // filesystem — notes are its only data surface.
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } }
+ },
+ INIT_TIMEOUT_MS
+ );
+ } catch (err) {
+ client.dispose();
+ throw err;
+ }
+ return client;
+ }
+
+ /**
+ * Handle agent→client requests. Only the permission callback is supported;
+ * everything else (fs, terminal) was never advertised and is refused.
+ */
+ private handleAgentRequest(method: string, params: unknown): unknown {
+ if (method === "session/request_permission") {
+ return this.decidePermission(params as AcpPermissionRequest);
+ }
+ throw new Error(`Trilium does not support "${method}".`);
+ }
+
+ /**
+ * Directory the agent subprocess runs in. The CLIs key their session storage
+ * and project-level config (custom instructions, trusted-folder state) by
+ * cwd, so a stable, dedicated directory keeps Trilium's sessions grouped and
+ * away from any real project. The `.git` marker makes it its own project
+ * root so an enclosing repository's agent config (AGENTS.md,
+ * .github/copilot-instructions.md) is never inherited — the dev-run data dir
+ * sits inside the Trilium repo.
+ */
+ protected agentCwd(): string {
+ const state = this.state();
+ if (!state.agentCwd) {
+ // Resolve to an absolute path — TRILIUM_DATA_DIR may be relative (dev
+ // runs use TRILIUM_DATA_DIR=data) and a relative spawn cwd would move
+ // with the server process's own cwd.
+ const cwd = path.resolve(dataDirs.TRILIUM_DATA_DIR, this.agentDirName);
+ fs.mkdirSync(cwd, { recursive: true });
+
+ const gitMarker = path.join(cwd, ".git");
+ if (!fs.existsSync(gitMarker)) {
+ fs.mkdirSync(path.join(gitMarker, "objects"), { recursive: true });
+ fs.mkdirSync(path.join(gitMarker, "refs"), { recursive: true });
+ fs.writeFileSync(path.join(gitMarker, "HEAD"), "ref: refs/heads/main\n");
+ }
+ state.agentCwd = cwd;
+ }
+ return state.agentCwd;
+ }
+
+ private state(): ProviderState {
+ let state = stateByProvider.get(this.name);
+ if (!state) {
+ state = { sessionsByChatNote: new Map() };
+ stateByProvider.set(this.name, state);
+ }
+ return state;
+ }
+}
+
+/**
+ * Deny a permission request, preferring a persistent "reject always" so a
+ * retrying agent stops re-asking, then a one-shot reject, then cancelling the
+ * turn. Never allows.
+ */
+export function denyPermission(request: AcpPermissionRequest, logLabel: string): AcpPermissionOutcome {
+ getLog().info(`${logLabel}: denied unapproved tool call "${request.toolCall?.title ?? "unknown"}" (kind: ${request.toolCall?.kind ?? "?"}).`);
+
+ const options = request.options ?? [];
+ const rejectOption = options.find(o => o.kind === "reject_always") ?? options.find(o => o.kind === "reject_once");
+ if (rejectOption) {
+ return { outcome: { outcome: "selected", optionId: rejectOption.optionId } };
+ }
+ return { outcome: { outcome: "cancelled" } };
+}
+
+/**
+ * Create the session/update collector: maps ACP updates to LlmStreamChunks and
+ * pushes them through `emit`. `muted` suppresses the replay flood during
+ * session/load; `sessionId` filters stray updates from other sessions.
+ */
+export function createUpdateCollector(emit: (chunk: LlmStreamChunk) => void) {
+ // toolCallId → display name, for labelling results; also the guard that
+ // only this turn's tool calls produce result chunks.
+ const toolNamesById = new Map<string, string>();
+
+ const collector = {
+ muted: false,
+ sessionId: undefined as string | undefined,
+ onNotification(method: string, params: unknown): void {
+ if (method !== "session/update" || collector.muted) {
+ return;
+ }
+ const { sessionId, update } = params as AcpSessionUpdate;
+ if (!update || (collector.sessionId && sessionId !== collector.sessionId)) {
+ return;
+ }
+
+ switch (update.sessionUpdate) {
+ case "agent_message_chunk": {
+ const text = extractText(update.content);
+ if (text) {
+ emit({ type: "text", content: text });
+ }
+ break;
+ }
+ case "agent_thought_chunk": {
+ const text = extractText(update.content);
+ if (text) {
+ emit({ type: "thinking", content: text });
+ }
+ break;
+ }
+ case "tool_call": {
+ if (!update.toolCallId || toolNamesById.has(update.toolCallId)) {
+ break; // malformed or a re-announcement of a known call
+ }
+ const toolName = update.title || "tool";
+ toolNamesById.set(update.toolCallId, toolName);
+ emit({
+ type: "tool_use",
+ toolCallId: update.toolCallId,
+ toolName,
+ toolInput: (update.rawInput ?? {}) as Record<string, unknown>
+ });
+ break;
+ }
+ case "tool_call_update": {
+ const toolCallId = update.toolCallId;
+ const toolName = toolCallId ? toolNamesById.get(toolCallId) : undefined;
+ if (!toolCallId || toolName === undefined) {
+ break; // not a call announced this turn
+ }
+ if (update.status === "completed" || update.status === "failed") {
+ emit({
+ type: "tool_result",
+ toolCallId,
+ toolName,
+ result: flattenToolContent(update.content, update.rawOutput),
+ isError: update.status === "failed"
+ });
+ toolNamesById.delete(toolCallId);
+ }
+ break;
+ }
+ default:
+ // plan / available_commands_update / config options — not
+ // surfaced in the chat.
+ break;
+ }
+ }
+ };
+ return collector;
+}
+
+/**
+ * Map the current user turn to ACP prompt blocks: real image blocks for
+ * natively-supported attachments, text for everything else. `prefix` (system
+ * instructions + reseed transcript + note hint) always leads.
+ */
+export function buildPromptBlocks(content: string | LlmMessagePart[], prefix: string): AcpContentBlock[] {
+ if (typeof content === "string") {
+ const text = prefix ? `${prefix}\n\n${content}` : content;
+ return [{ type: "text", text }];
+ }
+
+ const blocks: AcpContentBlock[] = [];
+ if (prefix) {
+ blocks.push({ type: "text", text: prefix });
+ }
+ for (const part of content) {
+ if (part.type === "text") {
+ blocks.push({ type: "text", text: part.text });
+ continue;
+ }
+ const resolved = resolveAttachmentPart(part);
+ if (resolved?.kind === "image" && SUPPORTED_IMAGE_MIMES.has(resolved.mime)) {
+ blocks.push({ type: "image", data: encodeBase64(resolved.bytes), mimeType: resolved.mime });
+ } else if (resolved?.kind === "text") {
+ // Inlined text attachments (SVG source, text files) travel as text.
+ blocks.push({ type: "text", text: resolved.text });
+ } else {
+ // Unresolved, or a type the ACP prompt can't carry (e.g. PDFs) — a
+ // placeholder keeps the turn self-describing.
+ blocks.push({ type: "text", text: attachmentPlaceholder(part) });
+ }
+ }
+ return blocks;
+}
+
+export function describeError(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+/** ACP content block (subset used by these providers). */
+type AcpContentBlock =
+ | { type: "text"; text: string }
+ | { type: "image"; data: string; mimeType: string };
+
+interface AcpSessionUpdate {
+ sessionId: string;
+ update?: {
+ sessionUpdate: string;
+ content?: AcpContentBlock | { type: string; content?: AcpContentBlock; [key: string]: unknown };
+ toolCallId?: string;
+ title?: string;
+ status?: string;
+ rawInput?: unknown;
+ rawOutput?: unknown;
+ [key: string]: unknown;
+ };
+}
+
+function rememberSession(sessionsByChatNote: Map<string, SessionEntry>, chatNoteId: string, entry: SessionEntry) {
+ // Refresh insertion order so the oldest mapping is evicted first.
+ sessionsByChatNote.delete(chatNoteId);
+ sessionsByChatNote.set(chatNoteId, entry);
+ if (sessionsByChatNote.size > MAX_TRACKED_SESSIONS) {
+ for (const oldest of sessionsByChatNote.keys()) {
+ sessionsByChatNote.delete(oldest);
+ break;
+ }
+ }
+}
+
+/** The MCP server list for `session/new`/`session/load`, pointing at the private loopback endpoint. */
+async function buildMcpServersConfig(): Promise<AcpMcpServer[]> {
+ const url = await getAcpMcpEndpointUrl();
+ return [{ name: NOTE_TOOLS_MCP_SERVER_NAME, type: "http", url, headers: [] }];
+}
+
+/**
+ * Build the same Trilium system prompt the other providers use. ACP has no
+ * system-prompt parameter, so it is delivered as a `<system_instructions>`
+ * block leading the first prompt of each session.
+ */
+function composeSystemPrompt(messages: LlmMessage[], config: LlmProviderConfig): string {
+ // buildSystemPrompt only returns undefined in its own documented-unreachable
+ // no-parts case (the markdown hints are always appended).
+ /* v8 ignore next */
+ return buildSystemPrompt(messages, config) ?? "";
+}
+
+/** Wrap the Trilium system prompt for delivery inside the first user prompt. */
+function wrapSystemInstructions(systemPrompt: string): string | null {
+ // buildSystemPrompt appends the Markdown hints unconditionally, so the only
+ // caller can never pass an empty string — this is unreachable defence.
+ /* v8 ignore next 3 -- composeSystemPrompt never yields an empty prompt */
+ if (!systemPrompt) {
+ return null;
+ }
+ return `<system_instructions>\n${systemPrompt}\n</system_instructions>`;
+}
+
+/** Pull the text out of an update's content block (nested for tool contents). */
+function extractText(content: unknown): string {
+ if (!content || typeof content !== "object") {
+ return "";
+ }
+ const block = content as { type?: string; text?: unknown };
+ return block.type === "text" && typeof block.text === "string" ? block.text : "";
+}
+
+/** Flatten a tool_call_update's content/rawOutput into the result string shown in the chat. */
+function flattenToolContent(content: unknown, rawOutput: unknown): string {
+ if (Array.isArray(content)) {
+ const texts = content
+ .map(item => {
+ if (!item || typeof item !== "object") {
+ return "";
+ }
+ // ACP wraps each block ({ type: "content", content: … }); some
+ // agents pass the MCP result's blocks straight through instead.
+ return "content" in item
+ ? extractText((item as { content?: AcpContentBlock }).content)
+ : extractText(item);
+ })
+ .filter(Boolean);
+ if (texts.length > 0) {
+ return texts.join("\n");
+ }
+ }
+ if (rawOutput !== undefined) {
+ return typeof rawOutput === "string" ? rawOutput : JSON.stringify(rawOutput);
+ }
+ return "";
+}
+
+function describeStopReason(stopReason: string): string {
+ switch (stopReason) {
+ case "refusal":
+ return "The model declined to continue this conversation.";
+ case "max_tokens":
+ case "max_turn_requests":
+ return `The agent stopped early (${stopReason.replace(/_/g, " ")}). Try a narrower request.`;
+ default:
+ return `Agent stopped: ${stopReason}`;
+ }
+}
diff --git a/apps/server/src/services/llm/providers/acp_client.spec.ts b/apps/server/src/services/llm/providers/acp_client.spec.ts
index 4e2e8428d4..882cbd4ec7 100644
--- a/apps/server/src/services/llm/providers/acp_client.spec.ts
+++ b/apps/server/src/services/llm/providers/acp_client.spec.ts
@@ -53,17 +53,27 @@ describe("AcpClient", () => {
vi.useRealTimers();
});
- it("spawns with --acp and the given args", () => {
- AcpClient.start("/usr/bin/copilot", { cwd: "/tmp", args: ["--no-color"] });
+ it("spawns with exactly the given args and the process environment", () => {
+ AcpClient.start("/usr/bin/copilot", { cwd: "/tmp", args: ["--acp", "--no-color"] });
expect(spawnMock).toHaveBeenCalledWith(
"/usr/bin/copilot",
["--acp", "--no-color"],
- expect.objectContaining({ cwd: "/tmp" })
+ expect.objectContaining({ cwd: "/tmp", env: process.env })
);
+
+ AcpClient.start("/opt/agy/agy_acp_server.par", { cwd: "/tmp" });
+ expect(spawnMock).toHaveBeenLastCalledWith("/opt/agy/agy_acp_server.par", [], expect.anything());
+ });
+
+ it("layers extra environment variables over the process environment", () => {
+ AcpClient.start("/opt/agy/agy_acp_server.par", { cwd: "/tmp", env: { GEMINI_HOME: "/data/home" } });
+ const env = spawnMock.mock.lastCall?.[2]?.env as NodeJS.ProcessEnv | undefined;
+ expect(env?.GEMINI_HOME).toBe("/data/home");
+ expect(env?.PATH).toBe(process.env.PATH);
});
it("quotes the binary path when launched through a shell", () => {
- AcpClient.start("C:\\npm\\copilot.cmd", { cwd: "/tmp", shell: true });
+ AcpClient.start("C:\\npm\\copilot.cmd", { cwd: "/tmp", shell: true, args: ["--acp"] });
expect(spawnMock).toHaveBeenCalledWith(
`"C:\\npm\\copilot.cmd"`,
["--acp"],
diff --git a/apps/server/src/services/llm/providers/acp_client.ts b/apps/server/src/services/llm/providers/acp_client.ts
index e6cf0e672e..a759993c28 100644
--- a/apps/server/src/services/llm/providers/acp_client.ts
+++ b/apps/server/src/services/llm/providers/acp_client.ts
@@ -1,7 +1,7 @@
/**
* Minimal Agent Client Protocol (ACP) client: newline-delimited JSON-RPC 2.0
- * over a subprocess's stdio, as spoken by `copilot --acp` (and other ACP
- * agents — see https://agentclientprotocol.com/).
+ * over a subprocess's stdio, as spoken by `copilot --acp`, Google's
+ * `agy_acp_server` and other ACP agents (see https://agentclientprotocol.com/).
*
* Deliberately dependency-free and transport-only: protocol semantics
* (initialize, session/new, session/prompt, permission policy) live in the
@@ -35,8 +35,13 @@ export class AcpError extends Error {
export interface AcpClientOptions {
cwd: string;
- /** Extra CLI arguments after `--acp`. */
+ /**
+ * CLI arguments, passed as-is. Each agent names its ACP mode differently
+ * (`copilot --acp`; Google's `agy_acp_server` speaks nothing else).
+ */
args?: string[];
+ /** Variables set on top of the server's own environment. */
+ env?: Record<string, string>;
/**
* Launch through a shell (required for npm `.cmd` shims on Windows). The
* binary path is quoted by the client when set.
@@ -93,12 +98,12 @@ export class AcpClient {
static start(binary: string, options: AcpClientOptions): AcpClient {
const proc = spawn(
options.shell ? `"${binary}"` : binary,
- ["--acp", ...(options.args ?? [])],
+ options.args ?? [],
{
cwd: options.cwd,
shell: options.shell ?? false,
stdio: ["pipe", "pipe", "pipe"],
- env: process.env
+ env: options.env ? { ...process.env, ...options.env } : process.env
}
);
return new AcpClient(proc, options);
diff --git a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.spec.ts b/apps/server/src/services/llm/providers/acp_mcp_endpoint.spec.ts
similarity index 89%
rename from apps/server/src/services/llm/providers/copilot_mcp_endpoint.spec.ts
rename to apps/server/src/services/llm/providers/acp_mcp_endpoint.spec.ts
index 57f56a0d16..061c6423e0 100644
--- a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.spec.ts
+++ b/apps/server/src/services/llm/providers/acp_mcp_endpoint.spec.ts
@@ -16,8 +16,8 @@ vi.mock("@triliumnext/core", () => ({
const createMcpServerMock = vi.hoisted(() => vi.fn());
vi.mock("../../mcp/mcp_server.js", () => ({ createMcpServer: createMcpServerMock }));
-const { getCopilotMcpEndpointUrl, resetCopilotMcpEndpointForTests } =
- await import("./copilot_mcp_endpoint.js");
+const { getAcpMcpEndpointUrl, resetAcpMcpEndpointForTests } =
+ await import("./acp_mcp_endpoint.js");
/** Loopback address, ephemeral port, 128-bit secret path. */
const ENDPOINT_URL = /^http:\/\/127\.0\.0\.1:\d+\/mcp-[0-9a-f]{32}$/;
@@ -85,7 +85,7 @@ function rawGetWithoutHost(url: string): Promise<string> {
});
}
-describe("copilot MCP endpoint", () => {
+describe("ACP MCP endpoint", () => {
let mcpServers: McpServer[];
beforeEach(() => {
@@ -100,24 +100,24 @@ describe("copilot MCP endpoint", () => {
});
afterEach(async () => {
- await resetCopilotMcpEndpointForTests();
+ await resetAcpMcpEndpointForTests();
vi.restoreAllMocks();
});
it("starts one loopback listener behind an unguessable path and memoizes it", async () => {
const createServerSpy = vi.spyOn(http, "createServer");
- const url = await getCopilotMcpEndpointUrl();
+ const url = await getAcpMcpEndpointUrl();
expect(url).toMatch(ENDPOINT_URL);
- await expect(getCopilotMcpEndpointUrl()).resolves.toBe(url);
+ await expect(getAcpMcpEndpointUrl()).resolves.toBe(url);
expect(createServerSpy).toHaveBeenCalledTimes(1);
expect(infoLogMock).toHaveBeenCalledTimes(1);
});
it("logs a post-startup server error instead of taking the process down", async () => {
const createServerSpy = vi.spyOn(http, "createServer");
- await getCopilotMcpEndpointUrl();
+ await getAcpMcpEndpointUrl();
// An "error" event with no listener is re-thrown by EventEmitter, which
// would crash the server — the startup listener must have been replaced.
@@ -130,33 +130,33 @@ describe("copilot MCP endpoint", () => {
const failing = new UnstartableServer() as unknown as http.Server;
vi.spyOn(http, "createServer").mockReturnValueOnce(failing);
- await expect(getCopilotMcpEndpointUrl()).rejects.toThrow(/EADDRINUSE/);
- await expect(getCopilotMcpEndpointUrl()).resolves.toMatch(ENDPOINT_URL);
+ await expect(getAcpMcpEndpointUrl()).rejects.toThrow(/EADDRINUSE/);
+ await expect(getAcpMcpEndpointUrl()).resolves.toMatch(ENDPOINT_URL);
});
it("survives a reset issued while a start is still in flight", async () => {
const failing = new UnstartableServer() as unknown as http.Server;
vi.spyOn(http, "createServer").mockReturnValueOnce(failing);
- const pending = getCopilotMcpEndpointUrl();
- const reset = resetCopilotMcpEndpointForTests();
+ const pending = getAcpMcpEndpointUrl();
+ const reset = resetAcpMcpEndpointForTests();
await expect(pending).rejects.toThrow(/EADDRINUSE/);
await expect(reset).resolves.toBeUndefined();
});
it("closes the listener on reset and hands out a fresh URL afterwards", async () => {
- const first = await getCopilotMcpEndpointUrl();
+ const first = await getAcpMcpEndpointUrl();
await expect(request(first)).resolves.toMatchObject({ status: 406 });
- await resetCopilotMcpEndpointForTests();
+ await resetAcpMcpEndpointForTests();
await expect(request(first)).rejects.toThrow(/ECONNREFUSED/);
- await expect(getCopilotMcpEndpointUrl()).resolves.not.toBe(first);
+ await expect(getAcpMcpEndpointUrl()).resolves.not.toBe(first);
});
it("404s every path but the secret one, without building an MCP server", async () => {
- const url = await getCopilotMcpEndpointUrl();
+ const url = await getAcpMcpEndpointUrl();
const base = url.slice(0, url.lastIndexOf("/"));
await expect(request(`${base}/`)).resolves.toMatchObject({ status: 404 });
@@ -166,7 +166,7 @@ describe("copilot MCP endpoint", () => {
it("answers an MCP handshake and disposes both peers on response close", async () => {
const transportClose = vi.spyOn(StreamableHTTPServerTransport.prototype, "close");
- const url = await getCopilotMcpEndpointUrl();
+ const url = await getAcpMcpEndpointUrl();
const res = await request(url, {
method: "POST",
@@ -194,7 +194,7 @@ describe("copilot MCP endpoint", () => {
});
it("rejects a rebound Host and lets the bound one through", async () => {
- const url = await getCopilotMcpEndpointUrl();
+ const url = await getAcpMcpEndpointUrl();
// The allowlist is pinned to the bound address, so a DNS-rebinding
// attempt is turned away before it reaches the transport. (Derived from
@@ -215,7 +215,7 @@ describe("copilot MCP endpoint", () => {
});
it("answers 500 when the MCP server cannot be built", async () => {
- const url = await getCopilotMcpEndpointUrl();
+ const url = await getAcpMcpEndpointUrl();
createMcpServerMock.mockImplementationOnce(() => {
throw new Error("becca unavailable");
});
@@ -227,7 +227,7 @@ describe("copilot MCP endpoint", () => {
});
it("leaves an already-sent response alone when the transport fails late", async () => {
- const url = await getCopilotMcpEndpointUrl();
+ const url = await getAcpMcpEndpointUrl();
// A failure once the transport has started writing must only be logged:
// a second writeHead() would throw ERR_HTTP_HEADERS_SENT on top of it.
const handle = vi.spyOn(StreamableHTTPServerTransport.prototype, "handleRequest");
@@ -242,7 +242,7 @@ describe("copilot MCP endpoint", () => {
});
it("treats an empty body as absent and refuses one over the 4 MB cap", async () => {
- const url = await getCopilotMcpEndpointUrl();
+ const url = await getAcpMcpEndpointUrl();
// Nothing to parse: the transport is handed no body and reports the
// JSON-RPC parse error itself.
diff --git a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts b/apps/server/src/services/llm/providers/acp_mcp_endpoint.ts
similarity index 91%
rename from apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts
rename to apps/server/src/services/llm/providers/acp_mcp_endpoint.ts
index de0360baa8..d12e131ed1 100644
--- a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts
+++ b/apps/server/src/services/llm/providers/acp_mcp_endpoint.ts
@@ -1,5 +1,6 @@
/**
- * Private loopback MCP endpoint for the Copilot Agent provider.
+ * Private loopback MCP endpoint for the ACP agent providers (GitHub Copilot, Google
+ * Antigravity).
*
* The Claude Agent provider hands its agent an *in-process* MCP server
* instance over the SDK's stdio control channel. ACP has no such channel —
@@ -30,7 +31,7 @@ let endpointUrl: Promise<string> | undefined;
* `session/new` MCP config. A failed start is not cached so a later chat
* turn retries.
*/
-export function getCopilotMcpEndpointUrl(): Promise<string> {
+export function getAcpMcpEndpointUrl(): Promise<string> {
if (!endpointUrl) {
endpointUrl = startEndpoint().catch((err: unknown) => {
endpointUrl = undefined;
@@ -41,7 +42,7 @@ export function getCopilotMcpEndpointUrl(): Promise<string> {
}
/** For tests: close the listener and forget it so the next call starts fresh. */
-export async function resetCopilotMcpEndpointForTests(): Promise<void> {
+export async function resetAcpMcpEndpointForTests(): Promise<void> {
if (endpointUrl) {
const url = await endpointUrl.catch(() => undefined);
endpointUrl = undefined;
@@ -75,7 +76,7 @@ async function startEndpoint(): Promise<string> {
// silently — log it instead (and keep a listener attached, since an
// unhandled "error" event would crash the server).
server.removeListener("error", onStartupError);
- server.on("error", err => getLog().error(`Copilot MCP endpoint server error: ${err}`));
+ server.on("error", err => getLog().error(`ACP MCP endpoint server error: ${err}`));
resolve();
});
});
@@ -88,7 +89,7 @@ async function startEndpoint(): Promise<string> {
boundHost = `127.0.0.1:${address.port}`;
const url = `http://${boundHost}${secretPath}`;
- getLog().info(`Copilot Agent provider: note-tools MCP endpoint listening on ${boundHost} (loopback only)`);
+ getLog().info(`ACP agent providers: note-tools MCP endpoint listening on ${boundHost} (loopback only)`);
return url;
}
@@ -125,7 +126,7 @@ async function handleRequest(
await mcpServer.connect(transport);
await transport.handleRequest(req, res, body);
} catch (err) {
- getLog().error(`Copilot MCP endpoint error: ${err}`);
+ getLog().error(`ACP MCP endpoint error: ${err}`);
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: "Internal MCP error" }));
}
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 b9c9d142f3..f51988adc8 100644
--- a/apps/server/src/services/llm/providers/copilot_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
@@ -30,7 +30,7 @@ vi.mock("./copilot_binary.js", () => ({
// 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"));
-vi.mock("./copilot_mcp_endpoint.js", () => ({ getCopilotMcpEndpointUrl: mcpEndpointMock }));
+vi.mock("./acp_mcp_endpoint.js", () => ({ getAcpMcpEndpointUrl: mcpEndpointMock }));
const buildNoteHintMock = vi.hoisted(() => vi.fn((noteId: string): string | null => `NOTE_META(${noteId})`));
vi.mock("@triliumnext/core/src/services/llm/note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));
@@ -119,15 +119,10 @@ class FakeAcpError extends Error {
vi.mock("./acp_client.js", () => ({ AcpClient: FakeAcpClient, AcpError: FakeAcpError }));
-const {
- buildCopilotModelList,
- buildPromptBlocks,
- CopilotAgentProvider,
- createUpdateCollector,
- decidePermission,
- resetAgentCwdForTests,
- resetModelCatalogCacheForTests
-} = await import("./copilot_agent.js");
+const { buildPromptBlocks, createUpdateCollector, denyPermission } = await import("./acp_agent.js");
+const { buildCopilotModelList, CopilotAgentProvider, resetModelCatalogCacheForTests } = await import("./copilot_agent.js");
+
+const decidePermission = (request: Parameters<typeof denyPermission>[0]) => denyPermission(request, "Copilot Agent provider");
async function collect(iterable: AsyncIterable<LlmStreamChunk>): Promise<LlmStreamChunk[]> {
const chunks: LlmStreamChunk[] = [];
@@ -144,7 +139,6 @@ function resetFakes() {
errorLogMock.mockReset();
infoLogMock.mockReset();
resolveAttachmentPartMock.mockReset();
- resetAgentCwdForTests();
resetModelCatalogCacheForTests();
mcpEndpointMock.mockClear();
resolveCopilotBinaryMock.mockClear();
@@ -686,7 +680,7 @@ describe("CopilotAgentProvider.generateTitle", () => {
});
});
-describe("decidePermission (fail-closed)", () => {
+describe("denyPermission (fail-closed)", () => {
// Note tools are pre-approved via --allow-tool and never reach the callback;
// anything that does is denied. Payload shapes mirror the real CLI 1.0.71
// permission request captured live (opaque toolCallId, kind "execute").
diff --git a/apps/server/src/services/llm/providers/copilot_agent.ts b/apps/server/src/services/llm/providers/copilot_agent.ts
index 44be682213..42b69eb19d 100644
--- a/apps/server/src/services/llm/providers/copilot_agent.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.ts
@@ -7,54 +7,23 @@
* integration on the machine), and usage is billed to the subscription.
*
* Bring-your-own-binary: nothing is bundled — the provider spawns the user's
- * own installed `copilot` CLI (see copilot_binary.ts).
- *
- * Like the Claude Agent provider, the CLI runs its own agentic loop and owns
- * conversation history in host-side sessions. This provider therefore:
- * - implements `chatChunks()` (chunk-native streaming) instead of `chat()`,
- * - maps chat notes to ACP sessions and sends only the newest user message
- * when the transcript still matches (`session/load`), falling back to
- * seeding a fresh session from the transcript when it diverged or was lost,
- * - exposes note tools by pointing the agent at a private loopback MCP
- * endpoint (see copilot_mcp_endpoint.ts), and denies every built-in
- * file/shell tool through the ACP permission callback.
+ * own installed `copilot` CLI (see copilot_binary.ts). The protocol handling is
+ * shared with the other ACP providers (see acp_agent.ts); Copilot's built-in
+ * file/shell tools are denied on its command line and again in the permission
+ * callback.
*/
-import type { LlmMessage, LlmMessagePart, 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";
-import { buildSystemPrompt } from "@triliumnext/core/src/services/llm/system_prompt.js";
-import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "@triliumnext/core/src/services/llm/types.js";
-import { encodeBase64 } from "@triliumnext/core/src/services/utils/binary.js";
-import fs from "fs";
-import path from "path";
+import type { ModelInfo } from "@triliumnext/core/src/services/llm/types.js";
-import dataDirs from "../../data_dir.js";
-import { AcpClient, AcpError } from "./acp_client.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 { getCopilotMcpEndpointUrl } from "./copilot_mcp_endpoint.js";
-import { attachmentPlaceholder, buildHistoryReplay, hashTranscript } from "./transcript.js";
-
-/** Image media types the ACP prompt accepts as a base64 image block. */
-const SUPPORTED_IMAGE_MIMES = new Set<string>(["image/png", "image/jpeg", "image/gif", "image/webp"]);
/**
- * The catalog available without asking the CLI anything.
- *
- * {@link CopilotAgentProvider.listModels} reads the real line-up off
- * `session/new`, but that costs a subprocess and a round-trip, and the
- * {@link LlmProvider} interface also needs a *synchronous* answer: the chat
- * resolves its default model and display name through `getAvailableModels()` on
- * every turn, which cannot wait on a spawn. This is that answer, and the
- * fallback when the probe can't run at all (CLI missing, logged out).
- *
- * So it holds only the two ids the provider itself names — `auto`, the default a
- * chat falls back to when it has none stored, and {@link TITLE_MODEL} — rather
- * than a mirror of the picker. Anything more would be a guess about someone
- * else's account, stale the moment GitHub changes the line-up, and the picker
- * never shows this list when the CLI can be reached. Pricing is zero throughout
- * because the subscription covers it.
+ * The catalog available without asking the CLI. It holds only the two ids the
+ * provider itself names — `auto`, the default a chat falls back to when it has
+ * none stored, and {@link TITLE_MODEL}. Pricing is zero throughout because the
+ * subscription covers it.
*/
const AVAILABLE_MODELS: ModelInfo[] = [
{ id: "auto", name: "Auto", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true },
@@ -64,16 +33,6 @@ const AVAILABLE_MODELS: ModelInfo[] = [
/** Free-tier model used for the cheap title turn. */
const TITLE_MODEL = "gpt-5-mini";
-/**
- * How long a probed catalog is reused. Matches the Claude Agent provider: the
- * line-up changes with GitHub's releases and the user's plan, neither of which
- * moves within an editing session, and the probe costs a CLI spawn.
- */
-const MODEL_CATALOG_TTL_MS = 60 * 60 * 1000;
-
-/** Upper bound on the catalog probe — a spawn plus one round-trip, no prompt. */
-const MODEL_PROBE_TIMEOUT_MS = 60_000;
-
/**
* Premium-request multipliers from the last successful probe, by model id.
*
@@ -84,13 +43,10 @@ const MODEL_PROBE_TIMEOUT_MS = 60_000;
*/
const premiumMultiplierById = new Map<string, number>();
-let modelCatalogCache: { models: ModelInfo[]; fetchedAt: number } | undefined;
-let modelCatalogInFlight: Promise<ModelInfo[]> | undefined;
-
/**
- * CLI arguments passed alongside `--acp`. These form the *primary* security
- * boundary; the permission callback (see {@link decidePermission}) is a
- * fail-closed backstop.
+ * CLI arguments. These form the *primary* security boundary; the permission
+ * callback (see `denyPermission` in acp_agent.ts) is a fail-closed backstop.
+ * - `--acp` runs the CLI as an ACP agent over stdio.
* - `--allow-tool=trilium` auto-approves every tool from our "trilium" MCP
* server, so note tools run without a permission round-trip (and without
* relying on us recognizing them — the CLI presents MCP tool calls with
@@ -103,162 +59,19 @@ let modelCatalogInFlight: Promise<ModelInfo[]> | undefined;
* - `--no-auto-update` keeps the pinned binary from mutating under us.
*/
const COPILOT_ACP_ARGS = [
+ "--acp",
"--allow-tool=trilium",
...["shell", "powershell", "write", "edit", "create", "view", "glob", "grep", "task", "web_fetch"].map(t => `--deny-tool=${t}`),
"--no-custom-instructions",
"--no-auto-update"
];
-const INIT_TIMEOUT_MS = 30_000;
-const SESSION_TIMEOUT_MS = 120_000;
-/** Upper bound for a whole prompt turn (agentic loops included). */
-const PROMPT_TIMEOUT_MS = 15 * 60_000;
-
-/** Session mappings kept per chat note; bounded to avoid unbounded growth. */
-const MAX_TRACKED_SESSIONS = 200;
-
-interface SessionEntry {
- sessionId: string;
- /** Hash of the transcript as it stood when the session last responded. */
- transcriptHash: string;
-}
-
-/**
- * chatNoteId → ACP session. In-memory only: the CLI's sessions live on this
- * host, so the mapping must not sync across devices. Losing it (e.g. on
- * restart) is fine — the provider reseeds a fresh session from the transcript
- * the client sends.
- */
-const sessionsByChatNote = new Map<string, SessionEntry>();
-
-function rememberSession(chatNoteId: string, entry: SessionEntry) {
- // Refresh insertion order so the oldest mapping is evicted first.
- sessionsByChatNote.delete(chatNoteId);
- sessionsByChatNote.set(chatNoteId, entry);
- if (sessionsByChatNote.size > MAX_TRACKED_SESSIONS) {
- for (const oldest of sessionsByChatNote.keys()) {
- sessionsByChatNote.delete(oldest);
- break;
- }
- }
-}
-
-/** ACP content block (subset used by this provider). */
-type AcpContentBlock =
- | { type: "text"; text: string }
- | { type: "image"; data: string; mimeType: string };
-
-interface AcpSessionUpdate {
- sessionId: string;
- update?: {
- sessionUpdate: string;
- content?: AcpContentBlock | { type: string; content?: AcpContentBlock; [key: string]: unknown };
- toolCallId?: string;
- title?: string;
- status?: string;
- rawInput?: unknown;
- rawOutput?: unknown;
- [key: string]: unknown;
- };
-}
-
-interface AcpPermissionRequest {
- sessionId?: string;
- toolCall?: { toolCallId?: string; title?: string; kind?: string; rawInput?: unknown };
- options?: { optionId: string; name?: string; kind?: string }[];
-}
-
-/** The `models` block of a `session/new` response — ACP's model-selection state. */
-interface AcpSessionModelState {
- availableModels?: AcpModel[];
- /** The model the session starts on. Not used: Trilium picks per chat. */
- currentModelId?: string;
-}
-
-interface AcpModel {
- modelId: string;
- name?: string;
- description?: string;
- /**
- * Vendor extensions ACP itself doesn't define. Copilot puts its quota
- * accounting here: `copilotUsage` is the premium-request multiplier as a
- * display string ("0.33x", "15x"), and `copilotEnablement` marks models the
- * account or its policy can't actually use.
- */
- _meta?: { copilotUsage?: string; copilotEnablement?: string };
-}
-
-export class CopilotAgentProvider implements LlmProvider {
+export class CopilotAgentProvider extends AcpAgentProvider {
name = "copilot-agent";
-
- /**
- * Free at the point of use for every model, discovered ones included: the
- * subscription covers the whole catalog, so an id this build has never heard
- * of still costs nothing per token. Only ids that aren't Copilot's at all
- * come back unpriced.
- */
- getModelPricing(model: string): ModelPricing | undefined {
- const known = modelCatalogCache?.models ?? AVAILABLE_MODELS;
- return known.some(m => m.id === model) ? { input: 0, output: 0 } : undefined;
- }
-
- getAvailableModels(): ModelInfo[] {
- return AVAILABLE_MODELS;
- }
-
- /**
- * The models this account may use, as the installed CLI reports them.
- *
- * There is no `/models` endpoint to call: the catalog arrives on the
- * `session/new` response, which reflects the CLI's version and the plan the
- * user is signed in under — a Pro account and a Business one are offered
- * different line-ups, and neither matches a list committed here months
- * earlier. Opening a session sends no prompt, so the probe spends no premium
- * requests.
- *
- * Cached for {@link MODEL_CATALOG_TTL_MS}, with concurrent callers sharing
- * one probe. A *failure* propagates rather than falling back to
- * {@link AVAILABLE_MODELS}, so the add/edit-provider screen can say the CLI
- * is missing or logged out instead of showing three models that would fail
- * on first use.
- */
- async listModels(): Promise<ModelInfo[]> {
- if (modelCatalogCache && Date.now() - modelCatalogCache.fetchedAt < MODEL_CATALOG_TTL_MS) {
- return modelCatalogCache.models;
- }
- if (!modelCatalogInFlight) {
- modelCatalogInFlight = this.probeModelCatalog().finally(() => {
- modelCatalogInFlight = undefined;
- });
- }
- return modelCatalogInFlight;
- }
-
- /**
- * Open a session purely to read the catalog off its response, then tear the
- * CLI down. No `session/prompt` is ever sent, and note tools are left out of
- * the session — nothing is asked of the agent, so it needs no capabilities.
- */
- private async probeModelCatalog(): Promise<ModelInfo[]> {
- let client: AcpClient | undefined;
- try {
- client = await this.startClient(() => {});
- const created = await client.request<{ models?: AcpSessionModelState }>(
- "session/new",
- { cwd: getAgentCwd(), mcpServers: [] },
- MODEL_PROBE_TIMEOUT_MS
- );
- const models = buildCopilotModelList(created.models?.availableModels ?? [], AVAILABLE_MODELS);
- modelCatalogCache = { models, fetchedAt: Date.now() };
- return models;
- } catch (err) {
- // Name the reason (binary missing, not logged in, timeout) so the
- // provider screen can show something the user can act on.
- throw new Error(describeError(err));
- } finally {
- client?.dispose();
- }
- }
+ protected readonly logLabel = "Copilot Agent provider";
+ protected readonly fallbackModels = AVAILABLE_MODELS;
+ protected readonly defaultModelId = "auto";
+ protected readonly agentDirName = "copilot-agent";
/**
* Everything except the models that bill at more than one premium request
@@ -280,268 +93,29 @@ export class CopilotAgentProvider implements LlmProvider {
return new Set(models.filter(m => (premiumMultiplierById.get(m.id) ?? 0) <= 1).map(m => m.id));
}
- /** Not used — the route prefers {@link chatChunks} when implemented. */
- chat(): StreamResult {
- throw new Error("The Copilot Agent provider streams chunks directly; use chatChunks().");
+ protected titleModelId(): string {
+ return TITLE_MODEL;
}
- async *chatChunks(messages: LlmMessage[], config: LlmProviderConfig, signal?: AbortSignal): AsyncIterable<LlmStreamChunk> {
- if (signal?.aborted) {
- // The client is gone — don't spawn an agent subprocess nobody
- // will read from.
- return;
- }
-
- const conversation = messages.filter(m => m.role !== "system");
- const lastMessage = conversation[conversation.length - 1];
- if (!lastMessage || lastMessage.role !== "user") {
- yield { type: "error", error: "The last message must be a user message." };
- return;
- }
-
- const history = conversation.slice(0, -1);
- const historyHash = hashTranscript(history);
- const stored = config.chatNoteId ? sessionsByChatNote.get(config.chatNoteId) : undefined;
- const resume = stored && stored.transcriptHash === historyHash ? stored.sessionId : undefined;
-
- // A config that does not mention the note tools does not get them, as `base_provider` reads
- // it and as the AI-SDK providers therefore behave — what a request leaves unsaid has to
- // mean the same thing whichever provider answers it.
- const noteToolsEnabled = !!config.enableNoteTools;
- const model = config.model || "auto";
-
- // Queue between the ACP notification callback and this generator: the
- // callback is synchronous while consumption is async, so updates are
- // buffered and drained in arrival order.
- const chunkQueue: LlmStreamChunk[] = [];
- let wakeup: (() => void) | undefined;
- const emit = (chunk: LlmStreamChunk) => {
- chunkQueue.push(chunk);
- wakeup?.();
- };
-
- const collector = createUpdateCollector(emit);
- let client: AcpClient | undefined;
- let sessionId: string | undefined;
- let assistantText = "";
-
- try {
- client = await this.startClient(collector.onNotification);
-
- const mcpServers = noteToolsEnabled ? await buildMcpServersConfig() : [];
-
- // Resume the existing session only when the transcript still
- // matches what it last saw; any divergence (edited history, lost
- // mapping, server restart) reseeds a fresh session. session/load
- // replays the session's history as notifications — the collector
- // suppresses everything until the load completes.
- if (resume) {
- collector.muted = true;
- try {
- await client.request("session/load", { sessionId: resume, cwd: getAgentCwd(), mcpServers }, SESSION_TIMEOUT_MS);
- sessionId = resume;
- } catch (err) {
- getLog().info(`Copilot Agent provider: session/load failed (${describeError(err)}); reseeding a fresh session.`);
- } finally {
- collector.muted = false;
- }
- }
-
- if (!sessionId) {
- const created = await client.request<{ sessionId: string }>(
- "session/new",
- { cwd: getAgentCwd(), mcpServers },
- SESSION_TIMEOUT_MS
- );
- sessionId = created.sessionId;
- }
- collector.sessionId = sessionId;
-
- if (model !== "auto") {
- // Model selection is an optional ACP capability — degrade to the
- // agent's default rather than failing the turn.
- try {
- await client.request("session/set_model", { sessionId, modelId: model }, INIT_TIMEOUT_MS);
- } catch (err) {
- getLog().error(`Copilot Agent provider: failed to select model "${model}" (${describeError(err)}); continuing with the agent's default.`);
- }
- }
-
- // Text that precedes this turn's own content: the system
- // instructions and replayed transcript when the session is fresh,
- // then the volatile current-note metadata hint (kept out of the
- // transcript hash so a later turn can still resume).
- const isFreshSession = sessionId !== resume;
- const hasAttachments = Array.isArray(lastMessage.content) && lastMessage.content.some(p => p.type !== "text");
- const noteHint = config.contextNoteId ? buildNoteHint(config.contextNoteId, hasAttachments) : null;
- const prefix = [
- isFreshSession ? wrapSystemInstructions(this.composeSystemPrompt(messages, { ...config, enableNoteTools: noteToolsEnabled })) : null,
- (isFreshSession && history.length > 0) ? buildHistoryReplay(history) : null,
- noteHint
- ].filter((s): s is string => Boolean(s)).join("\n\n");
-
- const onAbort = () => {
- if (sessionId) {
- client?.notify("session/cancel", { sessionId });
- }
- // Wake the drain loop below: an agent slow to honour the cancel
- // (or ignoring it) would otherwise keep this generator — and its
- // subprocess — suspended until PROMPT_TIMEOUT_MS elapses.
- wakeup?.();
- };
- signal?.addEventListener("abort", onAbort, { once: true });
-
- try {
- const promptPromise = client.request<{ stopReason?: string }>(
- "session/prompt",
- { sessionId, prompt: buildPromptBlocks(lastMessage.content, prefix) },
- PROMPT_TIMEOUT_MS
- );
-
- // Drain updates as they arrive until the prompt resolves (and
- // then whatever is still queued).
- let result: { stopReason?: string } | undefined;
- let promptError: unknown;
- const done = promptPromise
- .then(r => { result = r; })
- .catch(err => { promptError = err; })
- .finally(() => wakeup?.());
-
- let finished = false;
- void done.then(() => { finished = true; wakeup?.(); });
- // On abort, drain what already arrived and stop — nobody is
- // reading past this point, and `finally` disposes the client.
- while ((!finished && !signal?.aborted) || chunkQueue.length > 0) {
- if (chunkQueue.length === 0) {
- await new Promise<void>(resolve => { wakeup = resolve; });
- wakeup = undefined;
- continue;
- }
- const chunk = chunkQueue.shift();
- if (chunk) {
- if (chunk.type === "text") {
- assistantText += chunk.content;
- }
- yield chunk;
- }
- }
- if (promptError) {
- throw promptError;
- }
-
- const stopReason = result?.stopReason ?? "end_turn";
- if (stopReason !== "end_turn" && stopReason !== "cancelled") {
- yield { type: "error", error: describeStopReason(stopReason) };
- }
- } finally {
- signal?.removeEventListener("abort", onAbort);
- }
-
- // An aborted turn stops draining before the agent settles, so the
- // session's real history is unknown — recording a hash here would
- // let a later turn resume a session that diverged from the
- // transcript. Forgetting it just reseeds a fresh one.
- if (config.chatNoteId && sessionId && !signal?.aborted) {
- rememberSession(config.chatNoteId, {
- sessionId,
- transcriptHash: hashTranscript([
- ...conversation,
- { role: "assistant", content: assistantText }
- ])
- });
- }
-
- yield { type: "done" };
- } catch (error) {
- yield { type: "error", error: describeCopilotError(error) };
- } finally {
- client?.dispose();
- }
+ protected async launchSpec(): Promise<AcpLaunchSpec> {
+ const binary = await resolveCopilotBinaryPath();
+ return { binary, args: COPILOT_ACP_ARGS, shell: needsShell(binary) };
}
- async generateTitle(firstMessage: string): Promise<string> {
- let client: AcpClient | undefined;
- try {
- let title = "";
- client = await this.startClient((method, params) => {
- if (method !== "session/update") {
- return;
- }
- const update = (params as AcpSessionUpdate).update;
- if (update?.sessionUpdate === "agent_message_chunk" && update.content && "text" in update.content && update.content.type === "text") {
- title += update.content.text;
- }
- });
-
- const { sessionId } = await client.request<{ sessionId: string }>(
- "session/new",
- { cwd: getAgentCwd(), mcpServers: [] },
- SESSION_TIMEOUT_MS
- );
- try {
- await client.request("session/set_model", { sessionId, modelId: TITLE_MODEL }, INIT_TIMEOUT_MS);
- } catch {
- // Title generation works on any model; ignore selection failures.
- }
- await client.request(
- "session/prompt",
- {
- sessionId,
- prompt: [{
- type: "text",
- text: `Generate a short title (at most 5 words) summarizing this chat message. Reply with only the title, no quotes or punctuation around it:\n\n${firstMessage.substring(0, 500)}`
- }]
- },
- SESSION_TIMEOUT_MS
- );
- return title.trim().replace(/^["']|["']$/g, "").substring(0, 100);
- } catch (error) {
- getLog().error(`Copilot Agent title generation failed: ${describeCopilotError(error)}`);
- return "";
- } finally {
- client?.dispose();
- }
+ protected buildModelList(remote: AcpSessionModelState): ModelInfo[] {
+ return buildCopilotModelList(remote.availableModels ?? [], AVAILABLE_MODELS);
}
- /** Spawn `copilot --acp` and run the ACP initialize handshake. */
- private async startClient(onNotification: (method: string, params: unknown) => void): Promise<AcpClient> {
- const binary = await resolveCopilotBinaryPath();
- const client = AcpClient.start(binary, {
- cwd: getAgentCwd(),
- shell: needsShell(binary),
- args: COPILOT_ACP_ARGS,
- onNotification,
- onAgentRequest: handleAgentRequest
- });
- try {
- await client.request(
- "initialize",
- {
- protocolVersion: 1,
- clientInfo: { name: "trilium-notes", version: "1.0" },
- // No fs capabilities: the agent must never touch the host
- // filesystem — notes are its only data surface.
- clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } }
- },
- INIT_TIMEOUT_MS
- );
- } catch (err) {
- client.dispose();
- throw err;
+ /** Map failures to actionable messages (auth problems name the fix). */
+ protected describeFailure(error: unknown): string {
+ const text = describeError(error);
+ if (error instanceof AcpError && (error.code === -32000 || /auth|login|subscription/i.test(text))) {
+ return "GitHub Copilot CLI is not authenticated. Run `copilot login` on the machine running the Trilium server to sign in with your GitHub Copilot subscription.";
}
- return client;
- }
-
- /**
- * Build the same Trilium system prompt the other providers use. ACP has no
- * system-prompt parameter, so it is delivered as a `<system_instructions>`
- * block leading the first prompt of each session.
- */
- private composeSystemPrompt(messages: LlmMessage[], config: LlmProviderConfig): string {
- // buildSystemPrompt only returns undefined in its own documented-unreachable
- // no-parts case (the markdown hints are always appended).
- /* v8 ignore next */
- return buildSystemPrompt(messages, config) ?? "";
+ if (/ENOENT|spawn/i.test(text)) {
+ return `Failed to start the GitHub Copilot CLI: ${text}`;
+ }
+ return text;
}
}
@@ -557,16 +131,19 @@ export class CopilotAgentProvider implements LlmProvider {
*
* Models the CLI marks as not enabled are dropped: they appear so the terminal
* picker can grey them out with a reason, which a checkbox list has nowhere to
- * put, and selecting one would fail at the first turn.
+ * put, and selecting one would fail at the first turn. Copilot puts its quota
+ * accounting in `_meta`: `copilotUsage` is the premium-request multiplier as a
+ * display string ("0.33x", "15x"), and `copilotEnablement` marks models the
+ * account or its policy can't actually use.
*/
export function buildCopilotModelList(remote: AcpModel[], curated: ModelInfo[]): ModelInfo[] {
const curatedById = new Map(curated.map(m => [m.id, m]));
premiumMultiplierById.clear();
const models = remote
- .filter(m => m.modelId && (m._meta?.copilotEnablement ?? "enabled") === "enabled")
+ .filter(m => m.modelId && (metaString(m, "copilotEnablement") ?? "enabled") === "enabled")
.map<ModelInfo>(m => {
- const multiplier = parsePremiumMultiplier(m._meta?.copilotUsage);
+ const multiplier = parsePremiumMultiplier(metaString(m, "copilotUsage"));
if (multiplier !== undefined) {
premiumMultiplierById.set(m.modelId, multiplier);
}
@@ -595,283 +172,22 @@ export function buildCopilotModelList(remote: AcpModel[], curated: ModelInfo[]):
return models.map(m => (m === preferred ? { ...m, isDefault: true } : m));
}
-/** `"0.33x"` → `0.33`. Undefined for a missing or unparseable rate. */
-function parsePremiumMultiplier(usage: string | undefined): number | undefined {
- if (!usage) {
- return undefined;
- }
- const parsed = Number.parseFloat(usage);
- return Number.isFinite(parsed) ? parsed : undefined;
-}
-
-/** For tests: forget the probed catalog so the next call re-probes. */
+/** For tests: forget the probed catalog and the premium rates recorded from it. */
export function resetModelCatalogCacheForTests(): void {
- modelCatalogCache = undefined;
- modelCatalogInFlight = undefined;
+ resetAcpAgentStateForTests();
premiumMultiplierById.clear();
}
-/** The MCP server list for `session/new`/`session/load`, pointing at the private loopback endpoint. */
-async function buildMcpServersConfig(): Promise<{ name: string; type: "http"; url: string; headers: never[] }[]> {
- const url = await getCopilotMcpEndpointUrl();
- return [{ name: "trilium", type: "http", url, headers: [] }];
+function metaString(model: AcpModel, key: string): string | undefined {
+ const value = model._meta?.[key];
+ return typeof value === "string" ? value : undefined;
}
-/**
- * Directory the agent subprocess runs in. The CLI keys its session storage and
- * project-level config (custom instructions, trusted-folder state) by cwd, so
- * a stable, dedicated directory keeps Trilium's sessions grouped and away from
- * any real project. The `.git` marker makes it its own project root so an
- * enclosing repository's agent config (AGENTS.md, .github/copilot-instructions.md)
- * is never inherited — the dev-run data dir sits inside the Trilium repo.
- */
-let agentCwd: string | undefined;
-function getAgentCwd(): string {
- if (!agentCwd) {
- // Resolve to an absolute path — TRILIUM_DATA_DIR may be relative (dev
- // runs use TRILIUM_DATA_DIR=data) and a relative spawn cwd would move
- // with the server process's own cwd.
- agentCwd = path.resolve(dataDirs.TRILIUM_DATA_DIR, "copilot-agent");
- fs.mkdirSync(agentCwd, { recursive: true });
-
- const gitMarker = path.join(agentCwd, ".git");
- if (!fs.existsSync(gitMarker)) {
- fs.mkdirSync(path.join(gitMarker, "objects"), { recursive: true });
- fs.mkdirSync(path.join(gitMarker, "refs"), { recursive: true });
- fs.writeFileSync(path.join(gitMarker, "HEAD"), "ref: refs/heads/main\n");
- }
- }
- return agentCwd;
-}
-
-/** For tests: forget the initialized agent cwd so the next call re-runs setup. */
-export function resetAgentCwdForTests(): void {
- agentCwd = undefined;
-}
-
-/**
- * Handle agent→client requests. Only the permission callback is supported;
- * everything else (fs, terminal) was never advertised and is refused.
- */
-function handleAgentRequest(method: string, params: unknown): unknown {
- if (method === "session/request_permission") {
- return decidePermission(params as AcpPermissionRequest);
- }
- throw new Error(`Trilium does not support "${method}".`);
-}
-
-/**
- * Permission policy — fail closed. Trilium's note tools are pre-approved at the
- * CLI level (`--allow-tool=trilium`, see {@link COPILOT_ACP_ARGS}), so they run
- * without ever reaching this callback. Anything that *does* reach here is, by
- * definition, a tool we did not allow — a built-in file/shell/network tool — so
- * it is denied.
- *
- * This deliberately does NOT try to recognize note tools and allow them: the
- * CLI presents tool calls with opaque IDs and human-friendly titles that don't
- * embed the MCP server name, so any name-based allow-list would be guesswork.
- * Denying here means the worst case is a note tool failing to run (fail-safe),
- * never a shell command executing on the server host (fail-open).
- */
-export function decidePermission(request: AcpPermissionRequest): { outcome: { outcome: "selected"; optionId: string } | { outcome: "cancelled" } } {
- getLog().info(`Copilot Agent provider: denied unapproved tool call "${request.toolCall?.title ?? "unknown"}" (kind: ${request.toolCall?.kind ?? "?"}).`);
-
- const options = request.options ?? [];
- // Prefer a persistent "reject always" so a retrying agent stops re-asking;
- // fall back to a one-shot reject, then to cancelling the turn.
- const rejectOption = options.find(o => o.kind === "reject_always") ?? options.find(o => o.kind === "reject_once");
- if (rejectOption) {
- return { outcome: { outcome: "selected", optionId: rejectOption.optionId } };
- }
- return { outcome: { outcome: "cancelled" } };
-}
-
-/**
- * Create the session/update collector: maps ACP updates to LlmStreamChunks and
- * pushes them through `emit`. `muted` suppresses the replay flood during
- * session/load; `sessionId` filters stray updates from other sessions.
- */
-function createUpdateCollector(emit: (chunk: LlmStreamChunk) => void) {
- // toolCallId → display name, for labelling results; also the guard that
- // only this turn's tool calls produce result chunks.
- const toolNamesById = new Map<string, string>();
-
- const collector = {
- muted: false,
- sessionId: undefined as string | undefined,
- onNotification(method: string, params: unknown): void {
- if (method !== "session/update" || collector.muted) {
- return;
- }
- const { sessionId, update } = params as AcpSessionUpdate;
- if (!update || (collector.sessionId && sessionId !== collector.sessionId)) {
- return;
- }
-
- switch (update.sessionUpdate) {
- case "agent_message_chunk": {
- const text = extractText(update.content);
- if (text) {
- emit({ type: "text", content: text });
- }
- break;
- }
- case "agent_thought_chunk": {
- const text = extractText(update.content);
- if (text) {
- emit({ type: "thinking", content: text });
- }
- break;
- }
- case "tool_call": {
- if (!update.toolCallId || toolNamesById.has(update.toolCallId)) {
- break; // malformed or a re-announcement of a known call
- }
- const toolName = update.title || "tool";
- toolNamesById.set(update.toolCallId, toolName);
- emit({
- type: "tool_use",
- toolCallId: update.toolCallId,
- toolName,
- toolInput: (update.rawInput ?? {}) as Record<string, unknown>
- });
- break;
- }
- case "tool_call_update": {
- const toolCallId = update.toolCallId;
- const toolName = toolCallId ? toolNamesById.get(toolCallId) : undefined;
- if (!toolCallId || toolName === undefined) {
- break; // not a call announced this turn
- }
- if (update.status === "completed" || update.status === "failed") {
- emit({
- type: "tool_result",
- toolCallId,
- toolName,
- result: flattenToolContent(update.content, update.rawOutput),
- isError: update.status === "failed"
- });
- toolNamesById.delete(toolCallId);
- }
- break;
- }
- default:
- // plan / available_commands_update / config options — not
- // surfaced in the chat.
- break;
- }
- }
- };
- return collector;
-}
-
-/** Pull the text out of an update's content block (nested for tool contents). */
-function extractText(content: unknown): string {
- if (!content || typeof content !== "object") {
- return "";
- }
- const block = content as { type?: string; text?: unknown };
- return block.type === "text" && typeof block.text === "string" ? block.text : "";
-}
-
-/** Flatten a tool_call_update's content/rawOutput into the result string shown in the chat. */
-function flattenToolContent(content: unknown, rawOutput: unknown): string {
- if (Array.isArray(content)) {
- const texts = content
- .map(item => {
- if (!item || typeof item !== "object") {
- return "";
- }
- // ACP wraps each block ({ type: "content", content: … }); some
- // agents pass the MCP result's blocks straight through instead.
- return "content" in item
- ? extractText((item as { content?: AcpContentBlock }).content)
- : extractText(item);
- })
- .filter(Boolean);
- if (texts.length > 0) {
- return texts.join("\n");
- }
- }
- if (rawOutput !== undefined) {
- return typeof rawOutput === "string" ? rawOutput : JSON.stringify(rawOutput);
- }
- return "";
-}
-
-/**
- * Map the current user turn to ACP prompt blocks: real image blocks for
- * natively-supported attachments, text for everything else. `prefix` (system
- * instructions + reseed transcript + note hint) always leads.
- */
-function buildPromptBlocks(content: string | LlmMessagePart[], prefix: string): AcpContentBlock[] {
- if (typeof content === "string") {
- const text = prefix ? `${prefix}\n\n${content}` : content;
- return [{ type: "text", text }];
- }
-
- const blocks: AcpContentBlock[] = [];
- if (prefix) {
- blocks.push({ type: "text", text: prefix });
- }
- for (const part of content) {
- if (part.type === "text") {
- blocks.push({ type: "text", text: part.text });
- continue;
- }
- const resolved = resolveAttachmentPart(part);
- if (resolved?.kind === "image" && SUPPORTED_IMAGE_MIMES.has(resolved.mime)) {
- blocks.push({ type: "image", data: encodeBase64(resolved.bytes), mimeType: resolved.mime });
- } else if (resolved?.kind === "text") {
- // Inlined text attachments (SVG source, text files) travel as text.
- blocks.push({ type: "text", text: resolved.text });
- } else {
- // Unresolved, or a type the ACP prompt can't carry (e.g. PDFs) — a
- // placeholder keeps the turn self-describing.
- blocks.push({ type: "text", text: attachmentPlaceholder(part) });
- }
- }
- return blocks;
-}
-
-/** Wrap the Trilium system prompt for delivery inside the first user prompt. */
-function wrapSystemInstructions(systemPrompt: string): string | null {
- // buildSystemPrompt appends the Markdown hints unconditionally, so the only
- // caller can never pass an empty string — this is unreachable defence.
- /* v8 ignore next 3 -- composeSystemPrompt never yields an empty prompt */
- if (!systemPrompt) {
- return null;
- }
- return `<system_instructions>\n${systemPrompt}\n</system_instructions>`;
-}
-
-function describeStopReason(stopReason: string): string {
- switch (stopReason) {
- case "refusal":
- return "The model declined to continue this conversation.";
- case "max_tokens":
- case "max_turn_requests":
- return `The agent stopped early (${stopReason.replace(/_/g, " ")}). Try a narrower request.`;
- default:
- return `Agent stopped: ${stopReason}`;
- }
-}
-
-function describeError(error: unknown): string {
- return error instanceof Error ? error.message : String(error);
-}
-
-/** Map failures to actionable messages (auth problems name the fix). */
-function describeCopilotError(error: unknown): string {
- const text = describeError(error);
- if (error instanceof AcpError && (error.code === -32000 || /auth|login|subscription/i.test(text))) {
- return "GitHub Copilot CLI is not authenticated. Run `copilot login` on the machine running the Trilium server to sign in with your GitHub Copilot subscription.";
- }
- if (/ENOENT|spawn/i.test(text)) {
- return `Failed to start the GitHub Copilot CLI: ${text}`;
+/** `"0.33x"` → `0.33`. Undefined for a missing or unparseable rate. */
+function parsePremiumMultiplier(usage: string | undefined): number | undefined {
+ if (!usage) {
+ return undefined;
}
- return text;
+ const parsed = Number.parseFloat(usage);
+ return Number.isFinite(parsed) ? parsed : undefined;
}
-
-/** For tests. */
-export { buildPromptBlocks, createUpdateCollector };