Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(llm): add GitHub Copilot provider via Copilot CLI ACP mode
Elian Doran375d6a348ab8
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex afd7bbe796..cad15ed3ac 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3130,6 +3130,7 @@"provider_desc_claude_agent": "Uses your Claude Pro/Max subscription, no API key. Requires Claude Code on the machine running Trilium.","provider_desc_openai": "GPT models via the OpenAI API. Requires an API key.","provider_desc_google": "Gemini models via the Google API. Requires an API key.",+ "provider_desc_copilot_agent": "Uses your GitHub Copilot subscription, no API key. Requires the Copilot CLI on the machine running Trilium.","actions": "Actions","delete_provider": "Delete","delete_provider_confirmation": "Are you sure you want to delete the provider \"{{name}}\"?",@@ -3139,6 +3140,7 @@"base_url_description": "Optional. Override the default API endpoint — useful for self-hosted models (Ollama, LM Studio, vLLM) or proxies.","base_url_invalid": "Base URL must be a valid http:// or https:// URL","claude_agent_description": "Uses your Claude Pro/Max subscription through Claude Code, so no API key is needed. Claude Code must be installed on the machine running Trilium (the server when self-hosting, or this computer on desktop); sign in once by running \"claude /login\" there.",+ "copilot_agent_description": "Uses your GitHub Copilot subscription through the GitHub Copilot CLI, so no API key is needed. The Copilot CLI must be installed on the machine running Trilium (the server when self-hosting, or this computer on desktop); sign in once by running \"copilot login\" there — an existing Copilot login from another editor is reused automatically.","cancel": "Cancel","mcp_title": "MCP (Model Context Protocol)","mcp_enabled": "MCP server",diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsxindex b9191b301f..e4f0233e20 100644--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx@@ -13,6 +13,7 @@ import SelectableCard, { SelectableCardGrid } from "../../../react/SelectableCarimport anthropicIcon from "./icons/anthropic.svg?url";import claudeAgentIcon from "./icons/claude-ai.svg?url";import geminiIcon from "./icons/gemini.svg?url";+import githubCopilotIcon from "./icons/github-copilot.svg?url";import openaiIcon from "./icons/openai.svg?url";export interface LlmProviderConfig {@@ -35,6 +36,8 @@ export interface ProviderType {beta?: boolean;/** When false, the provider needs no API key or base URL (e.g. subscription-based auth). */usesApiKey?: boolean;+ /** Connection-details blurb shown instead of the API-key field when `usesApiKey` is false. */+ connectionDescription?: string;}// The two Claude-powered providers lead the list so they sit together on the top row,@@ -42,9 +45,11 @@ export interface ProviderType {export const PROVIDER_TYPES: ProviderType[] = [{ id: "anthropic", name: "Anthropic", defaultBaseUrl: "https://api.anthropic.com/v1", iconUrl: anthropicIcon, description: t("llm.provider_desc_anthropic") },// Uses the Claude Agent SDK on the server; auth belongs to Claude Code (`claude /login`).- { id: "claude-agent", name: "Claude Code", defaultBaseUrl: "", iconUrl: claudeAgentIcon, description: t("llm.provider_desc_claude_agent"), beta: true, usesApiKey: false },+ { id: "claude-agent", name: "Claude Code", defaultBaseUrl: "", iconUrl: claudeAgentIcon, description: t("llm.provider_desc_claude_agent"), beta: true, usesApiKey: false, connectionDescription: t("llm.claude_agent_description") },{ id: "openai", name: "OpenAI", defaultBaseUrl: "https://api.openai.com/v1", iconUrl: openaiIcon, description: t("llm.provider_desc_openai") },- { id: "google", name: "Google Gemini", defaultBaseUrl: "https://generativelanguage.googleapis.com/v1beta", iconUrl: geminiIcon, description: t("llm.provider_desc_google") }+ { id: "google", name: "Google Gemini", defaultBaseUrl: "https://generativelanguage.googleapis.com/v1beta", iconUrl: geminiIcon, description: t("llm.provider_desc_google") },+ // Uses the GitHub Copilot CLI in ACP mode on the server; auth belongs to the CLI (`copilot login`).+ { id: "copilot-agent", name: "GitHub Copilot", defaultBaseUrl: "", iconUrl: githubCopilotIcon, description: t("llm.provider_desc_copilot_agent"), beta: true, usesApiKey: false, connectionDescription: t("llm.copilot_agent_description") }];function isValidBaseUrl(value: string): boolean {@@ -163,7 +168,7 @@ export default function AddProviderModal({ show, onHidden, onSave }: AddProvider/></FormGroup>) : (- <p>{t("llm.claude_agent_description")}</p>+ <p>{providerType?.connectionDescription}</p>)}</CardSection></Card>diff --git a/apps/client/src/widgets/type_widgets/options/llm/icons/github-copilot.svg b/apps/client/src/widgets/type_widgets/options/llm/icons/github-copilot.svgnew file mode 100644index 0000000000..f064947d1d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/llm/icons/github-copilot.svg@@ -0,0 +1 @@+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub Copilot</title><path d="M23.922 16.997C23.061 18.492 18.063 22.02 12 22.02 5.937 22.02.939 18.492.078 16.997A.641.641 0 0 1 0 16.741v-2.869a.883.883 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.098 10.098 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952C7.255 2.937 9.248 1.98 11.978 1.98c2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.841.841 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256Zm-11.75-5.992h-.344a4.359 4.359 0 0 1-.355.508c-.77.947-1.918 1.492-3.508 1.492-1.725 0-2.989-.359-3.782-1.259a2.137 2.137 0 0 1-.085-.104L4 11.746v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.359 4.359 0 0 1-.355-.508Zm2.328 3.25c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm-5 0c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm3.313-6.185c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z"/></svg>\ No newline at end of filediff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 63900becbd..232eb50240 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -11,7 +11,7 @@"url": "https://triliumnotes.org"},"scripts": {- "dev": "cross-env TRILIUM_PORT=37742 TRILIUM_DATA_DIR=data TRILIUM_ELECTRON_DATA_DIR=data-electron-37742 tsx ../../scripts/electron-start.mts src/main.ts",+ "dev": "cross-env TRILIUM_PORT=37743 TRILIUM_DATA_DIR=data TRILIUM_ELECTRON_DATA_DIR=data-electron-37742 tsx ../../scripts/electron-start.mts src/main.ts","start-no-dir": "cross-env TRILIUM_PORT=37743 tsx ../../scripts/electron-start.mts src/main.ts","build": "tsx scripts/build.ts","start-prod": "pnpm build && cross-env TRILIUM_DATA_DIR=data TRILIUM_ELECTRON_DATA_DIR=data-electron-37841 TRILIUM_PORT=37841 ELECTRON_IS_DEV=0 electron dist",@@ -55,4 +55,4 @@"pngjs": "7.0.0","prebuild-install": "7.1.3"}-}\ No newline at end of file+}diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.tsindex 5a0bf0d314..2f5328900d 100644--- a/apps/server/src/services/llm/index.ts+++ b/apps/server/src/services/llm/index.ts@@ -2,6 +2,7 @@ import { getLog, options as optionService } from "@triliumnext/core";import { AnthropicProvider } from "./providers/anthropic.js";import { ClaudeAgentProvider } from "./providers/claude_agent.js";+import { CopilotAgentProvider } from "./providers/copilot_agent.js";import { GoogleProvider } from "./providers/google.js";import { OpenAiProvider } from "./providers/openai.js";import type { LlmProvider, ModelInfo } from "./types.js";@@ -26,7 +27,10 @@ const providerFactories: Record<string, (apiKey: string, baseURL?: string) => Llgoogle: (apiKey, baseURL) => new GoogleProvider(apiKey, baseURL),// Claude Pro/Max subscription via the Claude Agent SDK — no API key;// authentication is handled by Claude Code itself (`claude /login`).- "claude-agent": () => new ClaudeAgentProvider()+ "claude-agent": () => new ClaudeAgentProvider(),+ // GitHub Copilot subscription via the Copilot CLI's ACP mode — no API key;+ // authentication is handled by the CLI itself (`copilot login`).+ "copilot-agent": () => new CopilotAgentProvider()};/** Cache of instantiated providers by their config ID */diff --git a/apps/server/src/services/llm/providers/acp_client.spec.ts b/apps/server/src/services/llm/providers/acp_client.spec.tsnew file mode 100644index 0000000000..b4a83c8e3b--- /dev/null+++ b/apps/server/src/services/llm/providers/acp_client.spec.ts@@ -0,0 +1,155 @@+import { EventEmitter } from "events";+import { PassThrough } from "stream";+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: vi.fn(), error: vi.fn() }) }));++// A fake ChildProcess: stdin captures what the client writes, stdout/stderr are+// streams the test pushes into, and it is an EventEmitter for exit/error.+class FakeProc extends EventEmitter {+ stdin = new PassThrough();+ stdout = new PassThrough();+ stderr = new PassThrough();+ killed = false;+ written: string[] = [];++ constructor() {+ super();+ this.stdin.on("data", (chunk: Buffer) => this.written.push(chunk.toString()));+ }++ kill() {+ this.killed = true;+ this.emit("exit", 0, null);+ }++ /** Simulate the agent writing a line to stdout. */+ send(obj: unknown) {+ this.stdout.write(`${JSON.stringify(obj)}\n`);+ }+}++const spawnMock = vi.hoisted(() => vi.fn());+vi.mock("child_process", () => ({ spawn: spawnMock }));++const { AcpClient, AcpError } = await import("./acp_client.js");++function lastWritten(proc: FakeProc): Record<string, unknown> {+ return JSON.parse(proc.written[proc.written.length - 1]);+}++describe("AcpClient", () => {+ let proc: FakeProc;++ beforeEach(() => {+ proc = new FakeProc();+ spawnMock.mockReset();+ spawnMock.mockReturnValue(proc);+ });++ it("spawns with --acp and the given args", () => {+ AcpClient.start("/usr/bin/copilot", { cwd: "/tmp", args: ["--no-color"] });+ expect(spawnMock).toHaveBeenCalledWith(+ "/usr/bin/copilot",+ ["--acp", "--no-color"],+ expect.objectContaining({ cwd: "/tmp" })+ );+ });++ it("quotes the binary path when launched through a shell", () => {+ AcpClient.start("C:\\npm\\copilot.cmd", { cwd: "/tmp", shell: true });+ expect(spawnMock).toHaveBeenCalledWith(+ `"C:\\npm\\copilot.cmd"`,+ ["--acp"],+ expect.objectContaining({ shell: true })+ );+ });++ it("correlates a response to its request by id", async () => {+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });+ const promise = client.request<{ ok: boolean }>("initialize", { v: 1 });++ const sent = lastWritten(proc);+ expect(sent).toMatchObject({ jsonrpc: "2.0", method: "initialize", params: { v: 1 } });++ proc.send({ jsonrpc: "2.0", id: sent.id, result: { ok: true } });+ await expect(promise).resolves.toEqual({ ok: true });+ });++ it("rejects with an AcpError when the response carries an error", async () => {+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });+ const promise = client.request("session/new", {});++ proc.send({ jsonrpc: "2.0", id: lastWritten(proc).id, error: { code: -32000, message: "no auth" } });+ await expect(promise).rejects.toBeInstanceOf(AcpError);+ await expect(promise).rejects.toMatchObject({ code: -32000, message: "no auth" });+ });++ it("routes notifications (no id) to onNotification", async () => {+ const onNotification = vi.fn();+ AcpClient.start("/bin/copilot", { cwd: "/tmp", onNotification });++ proc.send({ jsonrpc: "2.0", method: "session/update", params: { hello: 1 } });+ await vi.waitFor(() => expect(onNotification).toHaveBeenCalledWith("session/update", { hello: 1 }));+ });++ it("answers an agent request via onAgentRequest and writes the result", async () => {+ const onAgentRequest = vi.fn(async () => ({ outcome: "ok" }));+ AcpClient.start("/bin/copilot", { cwd: "/tmp", onAgentRequest });++ proc.send({ jsonrpc: "2.0", id: 7, method: "session/request_permission", params: {} });+ await vi.waitFor(() => expect(onAgentRequest).toHaveBeenCalled());+ await vi.waitFor(() => {+ const reply = lastWritten(proc);+ expect(reply).toMatchObject({ id: 7, result: { outcome: "ok" } });+ });+ });++ it("replies method-not-found to an agent request when no handler is set", async () => {+ AcpClient.start("/bin/copilot", { cwd: "/tmp" });++ proc.send({ jsonrpc: "2.0", id: 8, method: "fs/read_text_file", params: {} });+ await vi.waitFor(() => {+ const reply = lastWritten(proc);+ expect(reply).toMatchObject({ id: 8, error: { code: -32601 } });+ });+ });++ it("turns a thrown agent-request handler into a JSON-RPC error response", async () => {+ const onAgentRequest = vi.fn(() => { throw new Error("nope"); });+ AcpClient.start("/bin/copilot", { cwd: "/tmp", onAgentRequest });++ proc.send({ jsonrpc: "2.0", id: 9, method: "terminal/create", params: {} });+ await vi.waitFor(() => {+ const reply = lastWritten(proc);+ expect(reply).toMatchObject({ id: 9, error: { code: -32603, message: "nope" } });+ });+ });++ it("rejects in-flight requests when the subprocess exits unexpectedly", async () => {+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });+ const promise = client.request("session/prompt", {});++ proc.emit("exit", 1, null);+ await expect(promise).rejects.toThrow(/exited unexpectedly/);+ });++ it("does not treat a post-dispose exit as an unexpected failure", async () => {+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });+ client.dispose();+ expect(proc.killed).toBe(true);++ // A request after disposal fails with the disposal error, not a crash.+ await expect(client.request("initialize", {})).rejects.toThrow(/disposed/);+ });++ it("ignores non-JSON lines on stdout", async () => {+ const onNotification = vi.fn();+ AcpClient.start("/bin/copilot", { cwd: "/tmp", onNotification });++ proc.stdout.write("Welcome to Copilot!\n");+ proc.send({ jsonrpc: "2.0", method: "ping", params: {} });+ await vi.waitFor(() => expect(onNotification).toHaveBeenCalledWith("ping", {}));+ expect(onNotification).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/llm/providers/acp_client.ts b/apps/server/src/services/llm/providers/acp_client.tsnew file mode 100644index 0000000000..655d6ac31a--- /dev/null+++ b/apps/server/src/services/llm/providers/acp_client.ts@@ -0,0 +1,196 @@+/**+ * 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/).+ *+ * Deliberately dependency-free and transport-only: protocol semantics+ * (initialize, session/new, session/prompt, permission policy) live in the+ * provider. The client handles framing, request/response correlation,+ * agent→client requests, and subprocess lifecycle.+ */++import { getLog } from "@triliumnext/core";+import { type ChildProcessWithoutNullStreams, spawn } from "child_process";+import { createInterface } from "readline";++interface JsonRpcMessage {+ jsonrpc: "2.0";+ id?: number | string;+ method?: string;+ params?: unknown;+ result?: unknown;+ error?: { code: number; message: string; data?: unknown };+}++export class AcpError extends Error {+ constructor(+ public readonly code: number,+ message: string,+ public readonly data?: unknown+ ) {+ super(message);+ this.name = "AcpError";+ }+}++export interface AcpClientOptions {+ cwd: string;+ /** Extra CLI arguments after `--acp`. */+ args?: string[];+ /**+ * Launch through a shell (required for npm `.cmd` shims on Windows). The+ * binary path is quoted by the client when set.+ */+ shell?: boolean;+ /** Called for every notification (no `id`) the agent sends. */+ onNotification?: (method: string, params: unknown) => void;+ /**+ * Called for every agent→client *request* (has an `id`; e.g.+ * `session/request_permission`). The returned value is sent as the+ * response result; a thrown error becomes a JSON-RPC error response.+ * When no handler is set, requests are answered with "method not found".+ */+ onAgentRequest?: (method: string, params: unknown) => Promise<unknown> | unknown;+}++export class AcpClient {+ private nextId = 1;+ private readonly pending = new Map<number, { resolve: (msg: JsonRpcMessage) => void; reject: (err: Error) => void }>();+ private exitError: Error | undefined;+ private disposed = false;++ private constructor(+ private readonly proc: ChildProcessWithoutNullStreams,+ private readonly options: AcpClientOptions+ ) {+ const rl = createInterface({ input: proc.stdout });+ rl.on("line", line => this.handleLine(line));++ proc.stderr.on("data", (data: Buffer) => {+ const text = data.toString().trim();+ if (text) {+ getLog().info(`ACP agent stderr: ${text}`);+ }+ });++ proc.on("error", err => this.failAll(new Error(`Failed to start the ACP agent: ${err.message}`)));+ proc.on("exit", (code, sig) => {+ // A deliberate dispose() kills the subprocess — that exit is expected+ // and must not surface as an error for in-flight (cancelled) requests.+ if (!this.disposed) {+ this.failAll(new Error(`The ACP agent exited unexpectedly (${sig ?? `code ${code}`}).`));+ }+ });+ }++ static start(binary: string, options: AcpClientOptions): AcpClient {+ const proc = spawn(+ options.shell ? `"${binary}"` : binary,+ ["--acp", ...(options.args ?? [])],+ {+ cwd: options.cwd,+ shell: options.shell ?? false,+ stdio: ["pipe", "pipe", "pipe"],+ env: process.env+ }+ );+ return new AcpClient(proc, options);+ }++ /** Send a request and await its response result (rejects with {@link AcpError} on error responses). */+ async request<T = unknown>(method: string, params: unknown, timeoutMs = 120_000): Promise<T> {+ if (this.exitError) {+ throw this.exitError;+ }+ const id = this.nextId++;+ const response = await new Promise<JsonRpcMessage>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error(`ACP request "${method}" timed out after ${Math.round(timeoutMs / 1000)} s.`));+ }, timeoutMs);+ this.pending.set(id, {+ resolve: msg => {+ clearTimeout(timer);+ resolve(msg);+ },+ reject: err => {+ clearTimeout(timer);+ reject(err);+ }+ });+ this.send({ jsonrpc: "2.0", id, method, params });+ });+ if (response.error) {+ throw new AcpError(response.error.code, response.error.message, response.error.data);+ }+ return response.result as T;+ }++ /** Send a notification (fire-and-forget, e.g. `session/cancel`). */+ notify(method: string, params: unknown): void {+ this.send({ jsonrpc: "2.0", method, params });+ }++ /** Kill the subprocess and reject anything still in flight. */+ dispose(): void {+ if (this.disposed) {+ return;+ }+ this.disposed = true;+ this.failAll(new Error("The ACP client was disposed."));+ this.proc.kill();+ }++ private send(message: JsonRpcMessage): void {+ this.proc.stdin.write(`${JSON.stringify(message)}\n`);+ }++ private handleLine(line: string): void {+ if (!line.trim()) {+ return;+ }+ let message: JsonRpcMessage;+ try {+ message = JSON.parse(line) as JsonRpcMessage;+ } catch {+ // Not part of the protocol stream (e.g. a stray banner) — ignore.+ return;+ }++ if (message.id !== undefined && message.method === undefined) {+ // Response to one of our requests.+ const entry = this.pending.get(message.id as number);+ if (entry) {+ this.pending.delete(message.id as number);+ entry.resolve(message);+ }+ } else if (message.method !== undefined && message.id !== undefined) {+ void this.answerAgentRequest(message.id, message.method, message.params);+ } else if (message.method !== undefined) {+ this.options.onNotification?.(message.method, message.params);+ }+ }++ private async answerAgentRequest(id: number | string, method: string, params: unknown): Promise<void> {+ const handler = this.options.onAgentRequest;+ if (!handler) {+ this.send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Client does not support "${method}".` } });+ return;+ }+ try {+ const result = await handler(method, params);+ this.send({ jsonrpc: "2.0", id, result });+ } catch (err) {+ const text = err instanceof Error ? err.message : String(err);+ this.send({ jsonrpc: "2.0", id, error: { code: -32603, message: text } });+ }+ }++ private failAll(error: Error): void {+ this.exitError = error;+ for (const entry of this.pending.values()) {+ entry.reject(error);+ }+ this.pending.clear();+ }+}diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex 696abddfab..82a22be5f8 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -21,10 +21,9 @@import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDKMessage, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";-import type { LlmFilePart, LlmImagePart, LlmMessage, LlmMessagePart, LlmStreamChunk, LlmTextAttachmentPart } from "@triliumnext/commons";+import type { LlmMessage, LlmMessagePart, LlmStreamChunk } from "@triliumnext/commons";import { getLog } from "@triliumnext/core";import { encodeBase64 } from "@triliumnext/core/src/services/utils/binary.js";-import { createHash } from "crypto";import fs from "fs";import path from "path";@@ -36,6 +35,11 @@ import { buildModelList } from "./base_provider.js";import { resolveClaudeBinaryPath } from "./claude_binary.js";import { buildNoteHint } from "./note_hint.js";import { buildSystemPrompt } from "./system_prompt.js";+import { attachmentPlaceholder, buildHistoryReplay, flattenContent, hashTranscript } from "./transcript.js";++// Re-exported for existing importers (specs, siblings); the implementations+// now live in the shared transcript module.+export { buildSeededPrompt, hashTranscript } from "./transcript.js";/** Image media types Anthropic accepts as a base64 image block. */type SupportedImageMime = "image/png" | "image/jpeg" | "image/gif" | "image/webp";@@ -596,49 +600,6 @@ async function* streamSingleUserMessage(content: ContentBlockParam[]): AsyncIteryield { type: "user", message: { role: "user", content }, parent_tool_use_id: null };}-/** Flatten possibly-multimodal message content to plain text (attachments as placeholders). */-function flattenContent(content: string | LlmMessagePart[]): string {- if (typeof content === "string") {- return content;- }- return content- .map(part => (part.type === "text" ? part.text : attachmentPlaceholder(part)))- .join("\n");-}--/** Short "[attached …]" stand-in used wherever an attachment's bytes aren't sent. */-function attachmentPlaceholder(part: LlmImagePart | LlmFilePart | LlmTextAttachmentPart): string {- const kind = part.type === "image" ? "image" : "file";- const name = "filename" in part ? `: ${part.filename}` : "";- return `[attached ${kind}${name}]`;-}--/**- * Stable hash of a transcript (roles + text only). Used to detect whether the- * history the client sent still matches what the mapped agent session saw.- */-export function hashTranscript(messages: LlmMessage[]): string {- const normalized = messages.map(m => [m.role, flattenContent(m.content).trim()]);- return createHash("sha256").update(JSON.stringify(normalized)).digest("hex");-}--/**- * First prompt of a reseeded session: replays the retained transcript as- * context so the agent can continue a conversation whose session was lost or- * diverged (edited history, server restart).- */-export function buildSeededPrompt(history: LlmMessage[], lastText: string): string {- return `${buildHistoryReplay(history)}\n\n${lastText}`;-}--/** The `<conversation_history>` replay block, without any trailing user message. */-function buildHistoryReplay(history: LlmMessage[]): string {- const transcript = history- .map(m => `${m.role === "user" ? "User" : "Assistant"}: ${flattenContent(m.content)}`)- .join("\n\n");- return `<conversation_history>\nThis is the prior conversation between the user and you. Continue it naturally; do not mention this replay.\n\n${transcript}\n</conversation_history>`;-}-/** Strip the MCP prefix so the client shows "search_notes", not "mcp__trilium__search_notes". */function friendlyToolName(name: string): string {return name.replace(/^mcp__trilium__/, "");diff --git a/apps/server/src/services/llm/providers/copilot_agent.spec.ts b/apps/server/src/services/llm/providers/copilot_agent.spec.tsnew file mode 100644index 0000000000..3db8e43363--- /dev/null+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts@@ -0,0 +1,313 @@+import type { LlmStreamChunk } from "@triliumnext/commons";+import { beforeEach, describe, expect, it, vi } from "vitest";++const errorLogMock = vi.hoisted(() => vi.fn());+vi.mock("@triliumnext/core", () => ({+ getLog: () => ({ info: vi.fn(), error: errorLogMock }),+ // buildSystemPrompt reads the workspace task states; none in this unit test.+ task_states: { getTaskStates: () => [] }+}));++vi.mock("../../data_dir.js", async () => {+ const os = await import("os");+ const path = await import("path");+ return { default: { TRILIUM_DATA_DIR: path.join(os.tmpdir(), "trilium-copilot-agent-spec") } };+});++// 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+}));++// 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 }));++const buildNoteHintMock = vi.hoisted(() => vi.fn((noteId: string): string | null => `NOTE_META(${noteId})`));+vi.mock("./note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));++const resolveAttachmentPartMock = vi.hoisted(() => vi.fn());+vi.mock("./attachment_content.js", () => ({ resolveAttachmentPart: resolveAttachmentPartMock }));++// A scriptable fake ACP client. `AcpClient.start` returns the active instance;+// each test scripts what `session/prompt` streams via onNotification and what+// it finally resolves to.+class FakeAcpClient {+ onNotification: (method: string, params: unknown) => void;+ onAgentRequest?: (method: string, params: unknown) => unknown;+ requests: { method: string; params: unknown }[] = [];+ notifications: { method: string; params: unknown }[] = [];+ disposed = false;++ static current: FakeAcpClient | undefined;+ static promptScript: (client: FakeAcpClient) => Promise<{ stopReason?: string }> = async () => ({ stopReason: "end_turn" });+ static sessionNewError: Error | undefined;++ constructor(opts: { onNotification: (m: string, p: unknown) => void; onAgentRequest?: (m: string, p: unknown) => unknown }) {+ this.onNotification = opts.onNotification;+ this.onAgentRequest = opts.onAgentRequest;+ }++ static start(_binary: string, opts: { args?: string[]; onNotification: (m: string, p: unknown) => void; onAgentRequest?: (m: string, p: unknown) => unknown }) {+ FakeAcpClient.current = new FakeAcpClient(opts);+ return FakeAcpClient.current;+ }++ async request<T>(method: string, params: unknown): Promise<T> {+ this.requests.push({ method, params });+ if (method === "initialize") return {} as T;+ if (method === "session/new") {+ if (FakeAcpClient.sessionNewError) throw FakeAcpClient.sessionNewError;+ return { sessionId: "sess-1" } as T;+ }+ if (method === "session/set_model") return {} as T;+ if (method === "session/prompt") return (await FakeAcpClient.promptScript(this)) as T;+ return {} as T;+ }++ notify(method: string, params: unknown): void {+ this.notifications.push({ method, params });+ }++ dispose(): void {+ this.disposed = true;+ }++ /** Fire a session/update notification as the agent would. */+ update(update: Record<string, unknown>, sessionId = "sess-1"): void {+ this.onNotification("session/update", { sessionId, update });+ }+}++class FakeAcpError extends Error {+ constructor(public readonly code: number, message: string) {+ super(message);+ }+}++vi.mock("./acp_client.js", () => ({ AcpClient: FakeAcpClient, AcpError: FakeAcpError }));++const { buildPromptBlocks, CopilotAgentProvider, decidePermission, resetAgentCwdForTests } = await import("./copilot_agent.js");++async function collect(iterable: AsyncIterable<LlmStreamChunk>): Promise<LlmStreamChunk[]> {+ const chunks: LlmStreamChunk[] = [];+ for await (const chunk of iterable) {+ chunks.push(chunk);+ }+ return chunks;+}++const userMessage = (text: string) => ({ role: "user" as const, content: text });++describe("CopilotAgentProvider.chatChunks", () => {+ beforeEach(() => {+ errorLogMock.mockReset();+ resolveAttachmentPartMock.mockReset();+ resetAgentCwdForTests();+ mcpEndpointMock.mockClear();+ FakeAcpClient.current = undefined;+ FakeAcpClient.sessionNewError = undefined;+ FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });+ });++ it("maps message, thought, and tool updates to chunks and ends with done", async () => {+ FakeAcpClient.promptScript = async client => {+ client.update({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "hmm" } });+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Hello " } });+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "world" } });+ client.update({ sessionUpdate: "tool_call", toolCallId: "t1", title: "search_notes", rawInput: { query: "x" } });+ client.update({ sessionUpdate: "tool_call_update", toolCallId: "t1", status: "completed", rawOutput: "3 results" });+ return { stopReason: "end_turn" };+ };++ const provider = new CopilotAgentProvider();+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));++ expect(chunks).toEqual([+ { type: "thinking", content: "hmm" },+ { type: "text", content: "Hello " },+ { type: "text", content: "world" },+ { type: "tool_use", toolCallId: "t1", toolName: "search_notes", toolInput: { query: "x" } },+ { type: "tool_result", toolCallId: "t1", toolName: "search_notes", result: "3 results", isError: false },+ { type: "done" }+ ]);+ expect(FakeAcpClient.current?.disposed).toBe(true);+ });++ it("wires the loopback MCP server into session/new when note tools are enabled", async () => {+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], { enableNoteTools: true }));++ const sessionNew = FakeAcpClient.current?.requests.find(r => r.method === "session/new");+ expect(sessionNew?.params).toMatchObject({+ mcpServers: [{ name: "trilium", type: "http", url: "http://127.0.0.1:12345/mcp-secret" }]+ });+ });++ it("omits MCP servers when note tools are disabled", async () => {+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], { enableNoteTools: false }));++ const sessionNew = FakeAcpClient.current?.requests.find(r => r.method === "session/new");+ expect(sessionNew?.params).toMatchObject({ mcpServers: [] });+ expect(mcpEndpointMock).not.toHaveBeenCalled();+ });++ it("spawns the CLI with the note-tool allow-list and built-in tool denials", async () => {+ const startSpy = vi.spyOn(FakeAcpClient, "start");+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], {}));++ const args = startSpy.mock.calls[0][1].args ?? [];+ expect(args).toContain("--allow-tool=trilium");+ expect(args).toContain("--deny-tool=shell");+ expect(args).toContain("--deny-tool=write");+ startSpy.mockRestore();+ });++ it("selects a non-default model via session/set_model", async () => {+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], { model: "gpt-5.4" }));++ const setModel = FakeAcpClient.current?.requests.find(r => r.method === "session/set_model");+ expect(setModel?.params).toMatchObject({ sessionId: "sess-1", modelId: "gpt-5.4" });+ });++ it("does not call session/set_model for the default 'auto' model", async () => {+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], {}));++ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/set_model")).toBe(false);+ });++ it("surfaces a non-terminal stop reason as an error chunk before done", async () => {+ FakeAcpClient.promptScript = async () => ({ stopReason: "refusal" });++ const provider = new CopilotAgentProvider();+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));++ expect(chunks).toContainEqual({ type: "error", error: expect.stringContaining("declined") });+ expect(chunks.at(-1)).toEqual({ type: "done" });+ });++ it("maps an authentication AcpError to an actionable message", async () => {+ FakeAcpClient.sessionNewError = new FakeAcpError(-32000, "not logged in");++ const provider = new CopilotAgentProvider();+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));++ expect(chunks).toEqual([{ type: "error", error: expect.stringContaining("copilot login") }]);+ expect(FakeAcpClient.current?.disposed).toBe(true);+ });++ it("rejects a transcript whose last message is not from the user", async () => {+ const provider = new CopilotAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "assistant", content: "hi" }], {}));++ expect(chunks).toEqual([{ type: "error", error: expect.stringContaining("last message must be a user message") }]);+ });++ it("does nothing when the abort signal is already aborted", async () => {+ const provider = new CopilotAgentProvider();+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}, AbortSignal.abort()));++ expect(chunks).toEqual([]);+ expect(FakeAcpClient.current).toBeUndefined();+ });++ it("cancels the session on mid-stream abort", async () => {+ const controller = new AbortController();+ FakeAcpClient.promptScript = async client => {+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "partial" } });+ controller.abort();+ return { stopReason: "cancelled" };+ };++ const provider = new CopilotAgentProvider();+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}, controller.signal));++ expect(chunks).toContainEqual({ type: "text", content: "partial" });+ // A "cancelled" stop reason must not surface as an error.+ expect(chunks.some(c => c.type === "error")).toBe(false);+ expect(FakeAcpClient.current?.notifications).toContainEqual({ method: "session/cancel", params: { sessionId: "sess-1" } });+ });++ it("prepends the note-metadata hint to a fresh session's prompt", async () => {+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], { contextNoteId: "note123" }));++ const prompt = FakeAcpClient.current?.requests.find(r => r.method === "session/prompt");+ const blocks = (prompt?.params as { prompt: { type: string; text: string }[] }).prompt;+ expect(blocks[0].text).toContain("NOTE_META(note123)");+ });+});++describe("decidePermission (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").+ it("rejects a built-in shell tool, preferring a persistent reject_always", () => {+ const decision = decidePermission({+ toolCall: { toolCallId: "toolu_011pPt1cC28vErGNDqhwut15", title: "Echo hello", kind: "execute" },+ options: [+ { optionId: "allow_once", kind: "allow_once" },+ { optionId: "allow_always", kind: "allow_always" },+ { optionId: "reject_always", kind: "reject_always" },+ { optionId: "reject_once", kind: "reject_once" }+ ]+ });+ expect(decision).toEqual({ outcome: { outcome: "selected", optionId: "reject_always" } });+ });++ it("falls back to reject_once when no reject_always is offered (real CLI 1.0.71 shape)", () => {+ const decision = decidePermission({+ toolCall: { toolCallId: "toolu_x", title: "Echo hello", kind: "execute" },+ options: [+ { optionId: "allow_once", kind: "allow_once" },+ { optionId: "allow_always", kind: "allow_always" },+ { optionId: "reject_once", kind: "reject_once" }+ ]+ });+ expect(decision).toEqual({ outcome: { outcome: "selected", optionId: "reject_once" } });+ });++ it("cancels the turn when only allow options are offered (never allows)", () => {+ const decision = decidePermission({ toolCall: { toolCallId: "toolu_y" }, options: [{ optionId: "a", kind: "allow_once" }] });+ expect(decision).toEqual({ outcome: { outcome: "cancelled" } });+ });+});++describe("buildPromptBlocks", () => {+ beforeEach(() => resolveAttachmentPartMock.mockReset());++ it("joins the prefix with plain string content in a single text block", () => {+ expect(buildPromptBlocks("hello", "PREFIX")).toEqual([{ type: "text", text: "PREFIX\n\nhello" }]);+ });++ it("returns the content verbatim when there is no prefix", () => {+ expect(buildPromptBlocks("hello", "")).toEqual([{ type: "text", text: "hello" }]);+ });++ it("emits an image block for a supported image attachment", () => {+ resolveAttachmentPartMock.mockReturnValue({ kind: "image", mime: "image/png", bytes: new Uint8Array([1, 2, 3]) });+ const blocks = buildPromptBlocks([{ type: "image", attachmentId: "a", mime: "image/png" }], "");+ expect(blocks).toEqual([{ type: "image", data: expect.any(String), mimeType: "image/png" }]);+ });++ it("inlines text attachments and placeholders unsupported ones", () => {+ resolveAttachmentPartMock.mockImplementation((part?: { type: string }) =>+ part?.type === "text_attachment" ? { kind: "text", text: "inlined source" } : undefined);+ const blocks = buildPromptBlocks([+ { type: "text", text: "look:" },+ { type: "text_attachment", attachmentId: "t", filename: "a.md" },+ { type: "file", attachmentId: "p", mime: "application/pdf", filename: "doc.pdf" }+ ], "");+ expect(blocks).toEqual([+ { type: "text", text: "look:" },+ { type: "text", text: "inlined source" },+ { type: "text", text: "[attached file: doc.pdf]" }+ ]);+ });+});diff --git a/apps/server/src/services/llm/providers/copilot_agent.ts b/apps/server/src/services/llm/providers/copilot_agent.tsnew file mode 100644index 0000000000..fa39022e25--- /dev/null+++ b/apps/server/src/services/llm/providers/copilot_agent.ts@@ -0,0 +1,661 @@+/**+ * Copilot Agent provider — drives the GitHub Copilot CLI in ACP mode+ * (`copilot --acp`, the Agent Client Protocol) as a subprocess. This lets+ * users with a GitHub Copilot subscription (Pro/Pro+/Business/Enterprise) use+ * the in-app chat without an API key: authentication is owned entirely by the+ * CLI (`copilot login`, or credentials shared with any other Copilot editor+ * 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.+ */++import type { LlmMessage, LlmMessagePart, LlmStreamChunk } from "@triliumnext/commons";+import { getLog } from "@triliumnext/core";+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 type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";+import { AcpClient, AcpError } from "./acp_client.js";+import { resolveAttachmentPart } from "./attachment_content.js";+import { needsShell, resolveCopilotBinaryPath } from "./copilot_binary.js";+import { getCopilotMcpEndpointUrl } from "./copilot_mcp_endpoint.js";+import { buildNoteHint } from "./note_hint.js";+import { buildSystemPrompt } from "./system_prompt.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"]);++/**+ * Models offered under a Copilot subscription, mirroring the CLI's own model+ * picker (as reported by `session/new`). Pricing is zero because usage is+ * covered by the subscription; `costMultiplier` carries the CLI-reported+ * premium-request multiplier instead (e.g. 0.33x, 1x).+ */+const AVAILABLE_MODELS: ModelInfo[] = [+ { id: "auto", name: "Auto", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true },+ { id: "claude-sonnet-5", name: "Claude Sonnet 5", pricing: { input: 0, output: 0 }, costMultiplier: 1, isSubscription: true },+ { id: "claude-haiku-4.5", name: "Claude Haiku 4.5", pricing: { input: 0, output: 0 }, costMultiplier: 0.3, isSubscription: true },+ { id: "gpt-5.4", name: "GPT-5.4", pricing: { input: 0, output: 0 }, costMultiplier: 1, isSubscription: true },+ { id: "gpt-5.3-codex", name: "GPT-5.3-Codex", pricing: { input: 0, output: 0 }, costMultiplier: 1, isSubscription: true },+ { id: "gpt-5.4-mini", name: "GPT-5.4 mini", pricing: { input: 0, output: 0 }, costMultiplier: 0.3, isSubscription: true },+ { id: "gpt-5-mini", name: "GPT-5 mini", pricing: { input: 0, output: 0 }, costMultiplier: 0, isSubscription: true }+];++/** Free-tier model used for the cheap title turn. */+const TITLE_MODEL = "gpt-5-mini";++/**+ * CLI arguments passed alongside `--acp`. These form the *primary* security+ * boundary; the permission callback (see {@link decidePermission}) is a+ * fail-closed backstop.+ * - `--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+ * opaque IDs and human-friendly titles that don't embed the server name).+ * - `--deny-tool` on each built-in file/shell/network tool guarantees they+ * can never run even if a future CLI build changed the permission-prompt+ * defaults. The agent's only capability surface is Trilium's note tools.+ * - `--no-custom-instructions` keeps any AGENTS.md/copilot-instructions.md in+ * an enclosing directory out of the notes chat.+ * - `--no-auto-update` keeps the pinned binary from mutating under us.+ */+const COPILOT_ACP_ARGS = [+ "--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 }[];+}++export class CopilotAgentProvider implements LlmProvider {+ name = "copilot-agent";++ getModelPricing(model: string): ModelPricing | undefined {+ return AVAILABLE_MODELS.some(m => m.id === model) ? { input: 0, output: 0 } : undefined;+ }++ getAvailableModels(): ModelInfo[] {+ return AVAILABLE_MODELS;+ }++ /** Not used — the route prefers {@link chatChunks} when implemented. */+ chat(): StreamResult {+ throw new Error("The Copilot Agent provider 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 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;++ const noteToolsEnabled = config.enableNoteTools !== false;+ 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 });+ }+ };+ 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?.(); });+ while (!finished || 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);+ }++ if (config.chatNoteId && sessionId) {+ 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();+ }+ }++ 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();+ }+ }++ /** 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;+ }+ 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) ?? "";+ }+}++/** 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: [] }];+}++/**+ * 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" && "content" in item) {+ return extractText((item as { content?: AcpContentBlock }).content);+ }+ return "";+ })+ .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 {+ 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}`;+ }+ return text;+}++/** For tests. */+export { buildPromptBlocks, createUpdateCollector };diff --git a/apps/server/src/services/llm/providers/copilot_binary.spec.ts b/apps/server/src/services/llm/providers/copilot_binary.spec.tsnew file mode 100644index 0000000000..d1c875c037--- /dev/null+++ b/apps/server/src/services/llm/providers/copilot_binary.spec.ts@@ -0,0 +1,140 @@+import path from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// The probe drives the real execFile through util.promisify's callback+// fallback, so the mock receives (binary, args, options, callback).+type ExecFileCallback = (err: Error | null, result?: { stdout: string; stderr: string }) => void;+const execFileMock = vi.hoisted(() => vi.fn<(binary: string, args: string[], options: object, cb: ExecFileCallback) => void>());+vi.mock("child_process", () => ({ execFile: execFileMock }));++const existsSyncMock = vi.hoisted(() => vi.fn((_path: string) => true));+vi.mock("fs", () => ({ existsSync: existsSyncMock }));++vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: vi.fn(), error: vi.fn() }) }));++const { needsShell, resetCopilotBinaryCache, resolveCopilotBinaryPath } = await import("./copilot_binary.js");++describe("resolveCopilotBinaryPath", () => {+ const originalOverride = process.env.TRILIUM_COPILOT_PATH;+ const originalPath = process.env.PATH;+ const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");++ beforeEach(() => {+ resetCopilotBinaryCache();+ execFileMock.mockReset();+ existsSyncMock.mockReset();+ existsSyncMock.mockReturnValue(true);+ process.env.TRILIUM_COPILOT_PATH = "/opt/copilot/copilot";+ });++ afterEach(() => {+ if (originalOverride === undefined) {+ delete process.env.TRILIUM_COPILOT_PATH;+ } else {+ process.env.TRILIUM_COPILOT_PATH = originalOverride;+ }+ process.env.PATH = originalPath;+ if (originalPlatform) {+ Object.defineProperty(process, "platform", originalPlatform);+ }+ });++ function stubPlatform(platform: NodeJS.Platform) {+ Object.defineProperty(process, "platform", { ...originalPlatform, value: platform });+ }++ function probeSucceeds() {+ execFileMock.mockImplementation((_binary, _args, _options, cb) => cb(null, { stdout: "1.0.71\n", stderr: "" }));+ }++ it("probes the overridden binary once and shares the result across calls (even concurrent ones)", async () => {+ probeSucceeds();++ const [first, second] = await Promise.all([resolveCopilotBinaryPath(), resolveCopilotBinaryPath()]);+ const third = await resolveCopilotBinaryPath();++ expect(first).toBe("/opt/copilot/copilot");+ expect(second).toBe("/opt/copilot/copilot");+ expect(third).toBe("/opt/copilot/copilot");+ expect(execFileMock).toHaveBeenCalledTimes(1);+ expect(execFileMock.mock.calls[0][0]).toBe("/opt/copilot/copilot");+ expect(execFileMock.mock.calls[0][1]).toEqual(["--version"]);+ });++ it("rejects with an actionable message on a broken binary and re-probes on the next call", async () => {+ execFileMock.mockImplementationOnce((_binary, _args, _options, cb) => cb(new Error("spawn ENOENT")));++ await expect(resolveCopilotBinaryPath()).rejects.toThrow(/failed to run.*copilot login/s);++ // The failure must not be cached — a later (fixed) install is picked up.+ probeSucceeds();+ await expect(resolveCopilotBinaryPath()).resolves.toBe("/opt/copilot/copilot");+ expect(execFileMock).toHaveBeenCalledTimes(2);+ });++ it("stringifies non-Error probe failures into the actionable message", async () => {+ execFileMock.mockImplementationOnce((_binary, _args, _options, cb) => cb("killed by signal" as unknown as Error));++ await expect(resolveCopilotBinaryPath()).rejects.toThrow(/failed to run \(killed by signal\)/);+ });++ it("rejects when TRILIUM_COPILOT_PATH points at a missing file, without probing", async () => {+ existsSyncMock.mockReturnValue(false);++ await expect(resolveCopilotBinaryPath()).rejects.toThrow(/TRILIUM_COPILOT_PATH/);+ expect(execFileMock).not.toHaveBeenCalled();+ });++ describe("PATH fallback (no override)", () => {+ beforeEach(() => {+ delete process.env.TRILIUM_COPILOT_PATH;+ });++ it("finds the bare `copilot` binary on POSIX, skipping empty PATH segments", async () => {+ stubPlatform("linux");+ const hit = path.join("/home/user/bin", "copilot");+ // Leading empty segment exercises the `if (!dir) continue` guard.+ process.env.PATH = ["", "/usr/local/bin", "/home/user/bin"].join(path.delimiter);+ existsSyncMock.mockImplementation((candidate: string) => candidate === hit);+ probeSucceeds();++ await expect(resolveCopilotBinaryPath()).resolves.toBe(hit);+ expect(execFileMock.mock.calls[0][0]).toBe(hit);+ });++ it("probes PATHEXT-style extensions on Windows and quotes the shimmed path for the shell", async () => {+ stubPlatform("win32");+ // No drive letter: a `C:` prefix would be split apart by the POSIX+ // `:` PATH delimiter when this spec runs on a non-Windows host.+ const dir = path.join("npm", "prefix");+ const hit = path.join(dir, "copilot.cmd");+ process.env.PATH = dir;+ existsSyncMock.mockImplementation((candidate: string) => candidate === hit);+ probeSucceeds();++ await expect(resolveCopilotBinaryPath()).resolves.toBe(hit);+ // .cmd shim must be launched through a shell, with the path quoted.+ expect(execFileMock.mock.calls[0][0]).toBe(`"${hit}"`);+ expect(execFileMock.mock.calls[0][2]).toMatchObject({ shell: true });+ });++ it("rejects with install instructions when `copilot` is nowhere on PATH (or PATH is unset)", async () => {+ stubPlatform("linux");+ delete process.env.PATH;+ existsSyncMock.mockReturnValue(false);++ await expect(resolveCopilotBinaryPath()).rejects.toThrow(/GitHub Copilot CLI not found/);+ 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.tsnew file mode 100644index 0000000000..f08254ad85--- /dev/null+++ b/apps/server/src/services/llm/providers/copilot_binary.ts@@ -0,0 +1,109 @@+/**+ * Resolves the GitHub Copilot CLI binary the Copilot Agent provider drives.+ *+ * Like the Claude Agent provider, this runs in "bring-your-own-binary" mode:+ * nothing is bundled with Trilium — the provider spawns the user's own+ * installed `copilot` CLI in ACP mode (`copilot --acp`). Authentication is+ * owned entirely by the CLI (`copilot login`, or credentials shared with any+ * other GitHub Copilot editor integration on the machine).+ *+ * Resolution order: the TRILIUM_COPILOT_PATH override, then `copilot` on+ * PATH. The resolved binary is probed with `--version` once so a broken/absent+ * install surfaces as a clear, actionable error instead of an opaque spawn+ * failure mid-chat.+ */++import { getLog } from "@triliumnext/core";+import { execFile } from "child_process";+import { existsSync } from "fs";+import path from "path";+import { promisify } from "util";++const execFileAsync = promisify(execFile);++/**+ * 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;++export function resolveCopilotBinaryPath(): Promise<string> {+ if (!cachedResolution) {+ cachedResolution = probeBinary().catch((err: unknown) => {+ cachedResolution = undefined;+ throw err;+ });+ }+ return cachedResolution;+}++/** For tests: forget the probed binary so the next call re-resolves. */+export function resetCopilotBinaryCache(): void {+ cachedResolution = undefined;+}++async function probeBinary(): Promise<string> {+ const binary = locateBinary();++ // Probe once: confirms the binary actually runs on this host (catches a+ // 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 15 s timeout.+ let version: string;+ try {+ // `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);+ version = (await execFileAsync(shell ? `"${binary}"` : binary, ["--version"], { timeout: 15000, encoding: "utf8", shell })).stdout.trim();+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ throw new Error(`Found GitHub Copilot CLI at "${binary}" but it failed to run (${detail}). Ensure it is installed correctly and that you've run \`copilot login\` on the machine running the Trilium server.`);+ }++ getLog().info(`Copilot Agent provider: using GitHub Copilot CLI at ${binary} (${version})`);+ return binary;+}++function locateBinary(): string {+ const override = process.env.TRILIUM_COPILOT_PATH?.trim();+ if (override) {+ if (!existsSync(override)) {+ throw new Error(`TRILIUM_COPILOT_PATH is set to "${override}", but no file exists there.`);+ }+ return override;+ }++ const onPath = findOnPath("copilot");+ if (onPath) {+ return onPath;+ }++ 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);+}++function findOnPath(binary: string): string | undefined {+ // Windows resolves executables via PATHEXT; on POSIX the bare name suffices.+ const extensions = process.platform === "win32" ? ["", ".cmd", ".exe", ".bat"] : [""];+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {+ if (!dir) {+ continue;+ }+ for (const ext of extensions) {+ const candidate = path.join(dir, binary + ext);+ if (existsSync(candidate)) {+ return candidate;+ }+ }+ }+ return undefined;+}diff --git a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts b/apps/server/src/services/llm/providers/copilot_mcp_endpoint.tsnew file mode 100644index 0000000000..15eb3202c7--- /dev/null+++ b/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts@@ -0,0 +1,123 @@+/**+ * Private loopback MCP endpoint for the Copilot Agent provider.+ *+ * 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 —+ * `session/new` only accepts MCP servers by URL (http/sse) — so this module+ * exposes Trilium's MCP server on an ephemeral, loopback-only HTTP listener+ * instead.+ *+ * Deliberately separate from the public `/mcp` route: that route exists to+ * expose notes to *external* clients and is gated on the user-facing+ * `mcpEnabled` option. The in-chat agent's note access is governed by the+ * chat's own "Note access" toggle, so it must not depend on that option.+ * Access control: the listener binds to 127.0.0.1 on a random port, and the+ * endpoint lives under an unguessable 128-bit secret path known only to the+ * agent subprocess we spawn.+ */++import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";+import { getLog } from "@triliumnext/core";+import { randomBytes } from "crypto";+import http from "http";++import { createMcpServer } from "../../mcp/mcp_server.js";++let endpointUrl: Promise<string> | undefined;++/**+ * Start (once) and return the endpoint URL to hand to the agent's+ * `session/new` MCP config. A failed start is not cached so a later chat+ * turn retries.+ */+export function getCopilotMcpEndpointUrl(): Promise<string> {+ if (!endpointUrl) {+ endpointUrl = startEndpoint().catch((err: unknown) => {+ endpointUrl = undefined;+ throw err;+ });+ }+ return endpointUrl;+}++/** For tests: close the listener and forget it so the next call starts fresh. */+export async function resetCopilotMcpEndpointForTests(): Promise<void> {+ if (endpointUrl) {+ const url = await endpointUrl.catch(() => undefined);+ endpointUrl = undefined;+ if (url) {+ await new Promise<void>(resolve => {+ listener?.close(() => resolve());+ listener = undefined;+ });+ }+ }+}++let listener: http.Server | undefined;++async function startEndpoint(): Promise<string> {+ const secretPath = `/mcp-${randomBytes(16).toString("hex")}`;++ const server = http.createServer((req, res) => {+ void handleRequest(req, res, secretPath);+ });+ listener = server;++ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => resolve());+ });++ const address = server.address();+ /* v8 ignore next 3 -- listen() on a TCP port always yields an AddressInfo */+ if (address === null || typeof address === "string") {+ throw new Error("Failed to determine the MCP endpoint's bound address.");+ }++ const url = `http://127.0.0.1:${address.port}${secretPath}`;+ getLog().info(`Copilot Agent provider: note-tools MCP endpoint listening on 127.0.0.1:${address.port} (loopback only)`);+ return url;+}++async function handleRequest(req: http.IncomingMessage, res: http.ServerResponse, secretPath: string): Promise<void> {+ try {+ if (req.url !== secretPath) {+ res.writeHead(404).end();+ return;+ }++ // Stateless per-request server+transport, mirroring the public /mcp route.+ const mcpServer = createMcpServer();+ const transport = new StreamableHTTPServerTransport({+ sessionIdGenerator: undefined,+ enableDnsRebindingProtection: true,+ // The agent connects via the URL we hand it, so the Host header is+ // always the bound loopback address.+ allowedHosts: [req.headers.host ?? ""].filter(h => /^127\.0\.0\.1:\d+$/.test(h))+ });++ res.on("close", () => {+ void transport.close();+ void mcpServer.close();+ });++ const body = req.method === "POST" ? await readJsonBody(req) : undefined;+ await mcpServer.connect(transport);+ await transport.handleRequest(req, res, body);+ } catch (err) {+ getLog().error(`Copilot MCP endpoint error: ${err}`);+ if (!res.headersSent) {+ res.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: "Internal MCP error" }));+ }+ }+}++async function readJsonBody(req: http.IncomingMessage): Promise<unknown> {+ const chunks: Buffer[] = [];+ for await (const chunk of req) {+ chunks.push(chunk as Buffer);+ }+ const text = Buffer.concat(chunks).toString("utf8");+ return text ? JSON.parse(text) : undefined;+}diff --git a/apps/server/src/services/llm/providers/transcript.ts b/apps/server/src/services/llm/providers/transcript.tsnew file mode 100644index 0000000000..d60a76b6b7--- /dev/null+++ b/apps/server/src/services/llm/providers/transcript.ts@@ -0,0 +1,53 @@+/**+ * Transcript helpers shared by the session-based agent providers (Claude+ * Agent, Copilot Agent). These providers own their conversation history in+ * host-side sessions, so they need a stable way to detect whether the+ * transcript the client sent still matches a mapped session (hash) and to+ * reseed a fresh session when it doesn't (replay).+ */++import type { LlmFilePart, LlmImagePart, LlmMessage, LlmMessagePart, LlmTextAttachmentPart } from "@triliumnext/commons";+import { createHash } from "crypto";++/**+ * Stable hash of a transcript (roles + text only). Used to detect whether the+ * history the client sent still matches what the mapped agent session saw.+ */+export function hashTranscript(messages: LlmMessage[]): string {+ const normalized = messages.map(m => [m.role, flattenContent(m.content).trim()]);+ return createHash("sha256").update(JSON.stringify(normalized)).digest("hex");+}++/**+ * First prompt of a reseeded session: replays the retained transcript as+ * context so the agent can continue a conversation whose session was lost or+ * diverged (edited history, server restart).+ */+export function buildSeededPrompt(history: LlmMessage[], lastText: string): string {+ return `${buildHistoryReplay(history)}\n\n${lastText}`;+}++/** The `<conversation_history>` replay block, without any trailing user message. */+export function buildHistoryReplay(history: LlmMessage[]): string {+ const transcript = history+ .map(m => `${m.role === "user" ? "User" : "Assistant"}: ${flattenContent(m.content)}`)+ .join("\n\n");+ return `<conversation_history>\nThis is the prior conversation between the user and you. Continue it naturally; do not mention this replay.\n\n${transcript}\n</conversation_history>`;+}++/** Flatten possibly-multimodal message content to plain text (attachments as placeholders). */+export function flattenContent(content: string | LlmMessagePart[]): string {+ if (typeof content === "string") {+ return content;+ }+ return content+ .map(part => (part.type === "text" ? part.text : attachmentPlaceholder(part)))+ .join("\n");+}++/** Short "[attached …]" stand-in used wherever an attachment's bytes aren't sent. */+export function attachmentPlaceholder(part: LlmImagePart | LlmFilePart | LlmTextAttachmentPart): string {+ const kind = part.type === "image" ? "image" : "file";+ const name = "filename" in part ? `: ${part.filename}` : "";+ return `[attached ${kind}${name}]`;+}