Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into worktree-copilot-agent-provider

Elian Doran86641584c629
diff --cc apps/client/src/translations/en/translation.json
index adf8061f01,bcb4d67ded..2f09d019a0
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@@ -3134,31 -3850,50 +3850,52 @@@
"configured_providers": "Configured Providers",
"no_providers_configured": "No providers configured yet.",
"provider_name": "Name",
- "provider_type": "Provider",
- "connection_details": "Connection",
- "advanced_options": "Advanced options",
"beta": "Beta",
- "provider_desc_anthropic": "Claude models via the Anthropic API. Requires an API key.",
- "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.",
+ "provider_desc_claude_agent": "Requires Claude Code on the machine running Trilium.",
- "provider_unavailable_standalone": "Unavailable in the browser version: this provider works by running Claude Code as a separate program, and there is no machine here to run it on.",
++ "provider_desc_copilot_agent": "Requires the GitHub Copilot CLI on the machine running Trilium.",
++ "provider_unavailable_standalone": "Unavailable in the browser version: this provider works by running a separate program on the machine, and there is no machine here to run it on.",
"actions": "Actions",
"delete_provider": "Delete",
"delete_provider_confirmation": "Are you sure you want to delete the provider \"{{name}}\"?",
"api_key": "API Key",
"api_key_placeholder": "Enter your API key",
"base_url": "Base URL",
- "base_url_description": "Optional. Override the default API endpoint — useful for self-hosted models (Ollama, LM Studio, vLLM) or proxies.",
+ "base_url_description": "Optional. Reaches the same API through a proxy or gateway. To run a model yourself, add an Ollama or LM Studio provider instead.",
"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",
+ "add_provider_title_named": "Add {{- name}}",
+ "provider_group_cloud": "Cloud providers",
+ "provider_group_cloud_description": "Pay per use with an API key, billed separately from any subscription you already have. Your notes are sent to the provider's servers.",
+ "provider_group_subscription": "Subscription",
+ "provider_group_subscription_description": "Reuses a subscription you already pay for, at no extra cost. Your notes are sent to the provider's servers.",
+ "provider_group_local": "Local / self-hosted",
+ "provider_group_local_description": "No API key, no usage cost. Your notes only reach the machine running the model.",
+ "provider_group_custom": "Custom endpoint",
+ "provider_group_custom_description": "Any OpenAI-compatible API, local or hosted (OpenRouter, Groq, Mistral). Cost and privacy depend on where you point it.",
+ "provider_openai_compatible": "OpenAI-compatible",
+ "provider_desc_openai_compatible": "Point Trilium at any endpoint that speaks the OpenAI API.",
+ "api_key_optional_description": "Optional. Only needed if your endpoint is behind an authenticating proxy or gateway.",
+ "setup_hint_ollama": "Ollama must be running on this address — start it with <Code>ollama serve</Code> if it isn't.",
+ "setup_hint_lmstudio": "Start the server in LM Studio under the Developer tab, then check the port shown there matches this address.",
+ "setup_hint_openai_compatible": "The base URL of the OpenAI-compatible API, usually ending in <Code>/v1</Code>.",
+ "troubleshoot_server_running": "Is the server running on the machine you expect?",
+ "troubleshoot_port": "Does the port in the URL match the one the server reports?",
+ "troubleshoot_remote": "If the server is on another machine, is it configured to accept connections from the network rather than localhost only?",
"mcp_title": "MCP (Model Context Protocol)",
"mcp_enabled": "MCP server",
- "mcp_enabled_description": "Expose a Model Context Protocol (MCP) endpoint so that AI coding assistants (e.g. Claude Code, GitHub Copilot) can read and modify your notes. The endpoint is only accessible from localhost.",
+ "mcp_enabled_description": "Expose a Model Context Protocol (MCP) endpoint so that AI coding assistants (e.g. Claude Code, GitHub Copilot) can read and modify your notes. Every request must be authenticated with an ETAPI token.",
+ "mcp_unavailable_standalone": "Unavailable in the browser version: assistants would connect to Trilium over the network, but this build has no address to give them, since it runs entirely inside this page.",
"mcp_endpoint_title": "Endpoint URL",
- "mcp_endpoint_description": "Add this URL to your AI assistant's MCP configuration",
+ "mcp_endpoint_description": "Add one of these URLs to your AI assistant's MCP configuration, using the HTTP (streamable) transport rather than SSE.",
+ "mcp_endpoint_this_device": "This device",
+ "mcp_endpoint_network": "From other devices on your network",
+ "mcp_endpoint_loopback_only": "Trilium is only listening on localhost, so the endpoint cannot be reached from other devices.",
+ "mcp_config_title": "How to connect an assistant",
+ "mcp_config_description": "Create a token under Options → ETAPI, then add the following to your assistant's MCP configuration, replacing the placeholder with your token:",
+ "mcp_config_token_placeholder": "your-etapi-token",
+ "mcp_config_cli_description": "Claude Code can be configured from the command line instead:",
+ "mcp_config_warning": "A token grants full read and write access to all of your notes, so treat it like a password. If you connect from another device, prefer HTTPS — a token sent over plain HTTP can be intercepted.",
"tools": {
"search_notes": "Search notes",
"get_note": "Get note",
diff --cc apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts
index 0000000000,839fa26093..a38bf1cc57
mode 000000,100644..100644
--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts
@@@ -1,0 -1,99 +1,108 @@@
+ import { describe, expect, it, vi } from "vitest";
+
+ vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+ import { prefilledBaseUrl, PROVIDER_TYPES } from "./AddProviderModal";
+
+ /** Card ids are persisted in the llmProviders option, so they double as an API. */
+ const SELF_HOSTED = ["ollama", "lmstudio", "openai-compatible"];
+
+ describe("AddProviderModal provider cards", () => {
+ it("prefills an endpoint for self-hosted providers only", () => {
+ // The port is the one detail a self-hosted user must get right, and it
+ // differs per runtime — whereas prefilling a vendor endpoint would store
+ // a redundant override on every provider the user adds.
+ expect(prefilledBaseUrl("ollama")).toBe("http://localhost:11434");
+ expect(prefilledBaseUrl("lmstudio")).toBe("http://localhost:1234/v1");
+ expect(prefilledBaseUrl("openai")).toBe("");
+ expect(prefilledBaseUrl("anthropic")).toBe("");
+ expect(prefilledBaseUrl("claude-agent")).toBe("");
+ // The generic card has no single sensible endpoint to guess.
+ expect(prefilledBaseUrl("openai-compatible")).toBe("");
+ expect(prefilledBaseUrl("unknown")).toBe("");
+ });
+
+ it("declares an endpoint and a setup hint for every self-hosted card", () => {
+ for (const id of SELF_HOSTED) {
+ const card = PROVIDER_TYPES.find(p => p.id === id);
+ expect(card, `missing card: ${id}`).toBeDefined();
+ expect(card?.baseUrl).toBe("required");
+ expect(card?.setupHintKey).toBeTruthy();
+ expect(card?.defaultBaseUrl).toBeTruthy();
+ }
+ });
+
+ it("sorts every card into a section by how it is billed and where it runs", () => {
+ // Groups follow the user guide's taxonomy — metered API keys, a fixed-fee
+ // subscription reused from elsewhere, self-hosted — plus a custom-endpoint
+ // section, which exists because that card also reaches *hosted* services
+ // (OpenRouter, Groq) and so can claim neither free use nor locality.
+ expect(PROVIDER_TYPES.filter(p => p.group === "cloud").map(p => p.id))
+ .toEqual(["anthropic", "openai", "google", "deepseek"]);
+ expect(PROVIDER_TYPES.filter(p => p.group === "subscription").map(p => p.id))
- .toEqual(["claude-agent"]);
++ .toEqual(["claude-agent", "copilot-agent"]);
+ expect(PROVIDER_TYPES.filter(p => p.group === "local").map(p => p.id))
+ .toEqual(["ollama", "lmstudio"]);
+ expect(PROVIDER_TYPES.filter(p => p.group === "custom").map(p => p.id))
+ .toEqual(["openai-compatible"]);
+ // Every card lands in exactly one section.
+ expect(PROVIDER_TYPES.filter(p => p.group === undefined)).toEqual([]);
+ });
+
+ it("keeps the endpoint-driven cards together regardless of section", () => {
+ // `group` and `baseUrl` are independent fields: splitting the custom
+ // endpoint out of "local" must not stop it asking for a URL.
+ expect(PROVIDER_TYPES.filter(p => p.baseUrl === "required").map(p => p.id)).toEqual(SELF_HOSTED);
+ });
+
+ it("bills every subscription provider through an existing account rather than a key", () => {
+ for (const card of PROVIDER_TYPES.filter(p => p.group === "subscription")) {
+ expect(card.apiKey, `${card.id} should not ask for an API key`).toBe("none");
+ }
+ });
+
+ it("keeps vendor cards on a required key and an advanced endpoint override", () => {
+ for (const id of ["anthropic", "openai", "google", "deepseek"]) {
+ const card = PROVIDER_TYPES.find(p => p.id === id);
+ // Both default, so neither is set explicitly.
+ expect(card?.apiKey ?? "required").toBe("required");
+ expect(card?.baseUrl ?? "advanced").toBe("advanced");
+ }
+ });
+
+ it("asks for no key from local runtimes and an optional one from arbitrary endpoints", () => {
+ const byId = new Map(PROVIDER_TYPES.map(p => [p.id, p]));
+ expect(byId.get("ollama")?.apiKey).toBe("none");
+ expect(byId.get("lmstudio")?.apiKey).toBe("none");
+ // A generic endpoint may sit behind an authenticating proxy (vLLM, LiteLLM).
+ expect(byId.get("openai-compatible")?.apiKey).toBe("optional");
+ // Subscription auth belongs to Claude Code itself.
+ expect(byId.get("claude-agent")?.apiKey).toBe("none");
+ expect(byId.get("claude-agent")?.baseUrl).toBe("none");
+ });
+
- it("marks Claude Code as the only card a browser-only build cannot run", () => {
- // It works by running the Claude Code CLI as a separate process, which the
- // standalone build — whose entire server is a worker in the page — has
- // nowhere to do; the picker disables that card there rather than dropping
- // it. Every other provider is reached over HTTP and so runs anywhere.
- expect(PROVIDER_TYPES.filter(p => p.needsHostProcess).map(p => p.id)).toEqual(["claude-agent"]);
++ it("marks the CLI-driven cards as the ones a browser-only build cannot run", () => {
++ // They work by running a CLI as a separate process, which the standalone
++ // build — whose entire server is a worker in the page — has nowhere to do;
++ // the picker disables those cards there rather than dropping them. Every
++ // other provider is reached over HTTP and so runs anywhere.
++ expect(PROVIDER_TYPES.filter(p => p.needsHostProcess).map(p => p.id)).toEqual(["claude-agent", "copilot-agent"]);
++ });
++
++ it("explains the account behind every card that asks for neither key nor endpoint", () => {
++ // With both fields gone the connection step would otherwise be empty, so
++ // the blurb is what the user reads there — and it must be the right one:
++ // each names its own CLI and login command.
++ for (const card of PROVIDER_TYPES.filter(p => p.apiKey === "none" && p.baseUrl === "none")) {
++ expect(card.connectionDescription, `${card.id} has nothing to show on the connection step`).toBeTruthy();
++ }
+ });
+
+ it("gives every card a logo", () => {
+ // SelectableCard is only passed `iconUrl`, so a card without one renders
+ // with an empty icon slot rather than falling back to anything.
+ for (const card of PROVIDER_TYPES) {
+ expect(card.iconUrl, `no icon for ${card.id}`).toBeTruthy();
+ }
+ });
+ });
diff --cc apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
index e4f0233e20,8d0b7f7f91..5923961903
--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
@@@ -27,29 -30,112 +30,121 @@@ export interface LlmProviderConfig
export interface ProviderType {
id: string;
name: string;
+ /** Shown as the endpoint field's placeholder, and prefilled into it when {@link prefillBaseUrl} is set. */
defaultBaseUrl: string;
+ /**
+ * Write {@link defaultBaseUrl} into the field when the card is picked. Set for
+ * self-hosted providers, where the port is the one detail the user must get
+ * right and differs per runtime; vendor providers keep it as a hint only, so
+ * that an unedited field stores no endpoint override.
+ */
+ prefillBaseUrl?: boolean;
/** URL of the provider's logo (an imported `*.svg?url`), rendered monochrome via a CSS mask. */
iconUrl: string;
- /** Short blurb shown under the provider name on its selectable card. */
- description: string;
+ /**
+ * Short blurb under the provider name, only where the name doesn't already say
+ * what the card is or what it needs — a prerequisite (Claude Code), or a card
+ * that names no vendor at all (OpenAI-compatible). Every vendor card goes
+ * without: "GPT models via the OpenAI API" under "OpenAI", inside a group
+ * headed "Cloud providers", is a line of height for nothing.
+ */
+ description?: string;
++ /**
++ * What the connection step shows when the provider has neither a key nor an
++ * endpoint to ask for: the full account-and-prerequisite story, in place of
++ * the fields that would otherwise fill the step.
++ */
++ connectionDescription?: string;
+ /** One-line setup reminder shown under the endpoint field (i18n key, rendered via `<Trans>`). */
+ setupHintKey?: string;
/** Marks the provider as beta, shown as a badge next to its name. */
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 provider drives a program on the machine, so the standalone build —
+ * where the whole server is a worker inside the page — has nothing to run it
+ * on; core refuses to instantiate it there at all. Such a card is shown
+ * disabled with the reason in place of its blurb, rather than dropped: the
+ * provider is documented and the user may well be looking for it, and a list
+ * that silently omits it leaves them hunting.
+ */
+ needsHostProcess?: boolean;
+ /**
+ * How the provider authenticates: a key it requires (vendor APIs), one it may
+ * take (self-hosted endpoints that sit behind a proxy or gateway), or none at
+ * all (subscription auth). Defaults to `"required"`.
+ */
+ apiKey?: "required" | "optional" | "none";
+ /**
+ * Where the endpoint URL belongs: the primary connection detail (self-hosted),
+ * an advanced override (vendor APIs), or not applicable. Defaults to `"advanced"`.
+ */
+ baseUrl?: "required" | "advanced" | "none";
+ /**
+ * Which section of the provider list this card belongs to — how it is billed,
+ * mirroring the three the user guide describes: metered API keys, a fixed-fee
+ * subscription reused from elsewhere, and self-hosted.
+ */
+ group: ProviderGroupId;
}
- // The two Claude-powered providers lead the list so they sit together on the top row,
- // making the subscription-vs-API-key choice easy to spot.
+ /**
+ * List sections, in the order they are shown. Keys are spelled out rather than
+ * built from the id so they stay greppable for the translation tooling.
+ *
+ * `columns` is stated per group rather than derived, because the right answer
+ * depends on how many cards the group holds: two columns halve the height of a
+ * group that fills its rows, but leave a lone tile stranded beside empty space in
+ * one that doesn't — conspicuous now that each group has its own card. Adding a
+ * provider means revisiting the number for its group.
+ */
+ const PROVIDER_GROUPS = [
+ { id: "cloud", columns: 2, headingKey: "llm.provider_group_cloud", descriptionKey: "llm.provider_group_cloud_description" },
- { id: "subscription", columns: 1, headingKey: "llm.provider_group_subscription", descriptionKey: "llm.provider_group_subscription_description" },
++ { id: "subscription", columns: 2, headingKey: "llm.provider_group_subscription", descriptionKey: "llm.provider_group_subscription_description" },
+ { id: "local", columns: 2, headingKey: "llm.provider_group_local", descriptionKey: "llm.provider_group_local_description" },
+ // Kept apart from the local runtimes: the same card reaches a hosted
+ // OpenAI-compatible service (OpenRouter, Groq, …), so neither "no usage cost"
+ // nor "stays on your machine" can be claimed for it.
+ { id: "custom", columns: 1, headingKey: "llm.provider_group_custom", descriptionKey: "llm.provider_group_custom_description" }
+ ] as const;
+
+ type ProviderGroupId = (typeof PROVIDER_GROUPS)[number]["id"];
+
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, 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") },
- // 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") }
+ { id: "anthropic", name: "Anthropic", group: "cloud", defaultBaseUrl: "https://api.anthropic.com/v1", iconUrl: PROVIDER_ICONS.anthropic },
+ { id: "openai", name: "OpenAI", group: "cloud", defaultBaseUrl: "https://api.openai.com/v1", iconUrl: PROVIDER_ICONS.openai },
+ { id: "google", name: "Google Gemini", group: "cloud", defaultBaseUrl: "https://generativelanguage.googleapis.com/v1beta", iconUrl: PROVIDER_ICONS.google },
+ // Reachable through the custom endpoint card too — it speaks the OpenAI API —
+ // but carded here so its models resolve against the committed price table,
+ // which a nameless endpoint never can.
+ { id: "deepseek", name: "DeepSeek", group: "cloud", defaultBaseUrl: "https://api.deepseek.com/v1", iconUrl: PROVIDER_ICONS.deepseek, beta: true },
+ // Uses the Claude Agent SDK on the server; auth belongs to Claude Code (`claude /login`),
+ // and usage is covered by the subscription rather than charged per token.
- { id: "claude-agent", name: "Claude Code", group: "subscription", defaultBaseUrl: "", iconUrl: PROVIDER_ICONS["claude-agent"], description: t("llm.provider_desc_claude_agent"), beta: true, apiKey: "none", baseUrl: "none", needsHostProcess: true },
++ { id: "claude-agent", name: "Claude Code", group: "subscription", defaultBaseUrl: "", iconUrl: PROVIDER_ICONS["claude-agent"], description: t("llm.provider_desc_claude_agent"), connectionDescription: t("llm.claude_agent_description"), beta: true, apiKey: "none", baseUrl: "none", needsHostProcess: true },
++ // The same arrangement over the GitHub Copilot CLI, driven in its ACP mode;
++ // auth belongs to the CLI (`copilot login`).
++ { id: "copilot-agent", name: "GitHub Copilot", group: "subscription", defaultBaseUrl: "", iconUrl: PROVIDER_ICONS["copilot-agent"], description: t("llm.provider_desc_copilot_agent"), connectionDescription: t("llm.copilot_agent_description"), beta: true, apiKey: "none", baseUrl: "none", needsHostProcess: true },
+ // The three self-hosted cards share one server-side provider; they differ only in
+ // the endpoint they prefill and the setup hint they show.
+ // No blurbs: the group heading already says local/self-hosted, and how to start
+ // each server belongs on the connection step, where the setup hints live.
+ {
+ id: "ollama", name: "Ollama", group: "local", defaultBaseUrl: "http://localhost:11434", prefillBaseUrl: true,
+ iconUrl: PROVIDER_ICONS.ollama,
+ setupHintKey: "llm.setup_hint_ollama", apiKey: "none", baseUrl: "required",
+ beta: true
+ },
+ {
+ id: "lmstudio", name: "LM Studio", group: "local", defaultBaseUrl: "http://localhost:1234/v1", prefillBaseUrl: true,
+ iconUrl: PROVIDER_ICONS.lmstudio,
+ setupHintKey: "llm.setup_hint_lmstudio", apiKey: "none", baseUrl: "required",
+ beta: true
+ },
+ {
+ id: "openai-compatible", name: t("llm.provider_openai_compatible"), group: "custom", defaultBaseUrl: "http://localhost:8080/v1",
+ iconUrl: PROVIDER_ICONS["openai-compatible"], description: t("llm.provider_desc_openai_compatible"),
+ setupHintKey: "llm.setup_hint_openai_compatible", apiKey: "optional", baseUrl: "required",
+ beta: true
+ }
];
function isValidBaseUrl(value: string): boolean {
@@@ -103,24 -275,116 +284,116 @@@ export default function AddProviderModa
onHidden();
}
- function resetForm() {
- setSelectedProvider(PROVIDER_TYPES[0].id);
- setApiKey("");
- setBaseUrl("");
- }
+ // Past the picker the cards are gone, so the title carries which provider is
+ // being set up.
+ const namedTitle = isEdit
+ ? t("llm.edit_provider_title", { name: existingProvider?.name ?? providerType?.name ?? selectedProvider })
+ : t("llm.add_provider_title_named", { name: providerType?.name ?? selectedProvider });
- function handleCancel() {
- resetForm();
- onHidden();
- }
+ const steps: WizardStep<ProviderStep>[] = [
+ {
+ id: "provider",
+ title: t("llm.add_provider_title"),
+ // Choosing a card advances on its own, so the step needs no primary action —
+ // but Enter must still not advance with whichever provider happens to be
+ // first in the list, hence the guard.
+ autoAdvance: true,
+ canContinue: providerChosen,
+ content: (
+ // One card per group rather than one "Provider" card holding them all:
+ // the groups are the step's structure, so each gets the heading and the
+ // enclosure, and the choices below it are only the ones it describes.
+ PROVIDER_GROUPS.map(group => (
+ <ProviderGroup
+ key={group.id}
+ heading={t(group.headingKey)}
+ description={t(group.descriptionKey)}
+ columns={group.columns}
+ providers={PROVIDER_TYPES.filter(p => p.group === group.id)}
+ selectedProvider={providerChosen ? selectedProvider : undefined}
+ onSelect={selectProviderType}
+ />
+ ))
+ )
+ },
+ {
+ id: "connection",
+ title: namedTitle,
+ canContinue: connectionValid,
+ content: (
+ <>
+ {providerType && <ProviderIllustration providerType={providerType} />}
+
+ {/* A single unlabelled card of settings rows: the step holds a handful of
+ fields for one provider — already named in the modal title — so the
+ hairline between rows is all the structure it needs. */}
+ <Card>
+ <CardSection>
+ {/* Self-hosted providers lead with the endpoint — the port is the
+ detail that has to be right — and treat the key as optional. */}
+ {baseUrlMode === "required" && baseUrlField}
+ {usesApiKey && (
+ <OptionsRow
+ name="api-key"
+ label={t("llm.api_key")}
+ description={apiKeyMode === "optional" ? t("llm.api_key_optional_description") : undefined}
+ stacked
+ >
+ <FormTextBox
+ type="password"
+ currentValue={apiKey}
+ onChange={setApiKey}
+ placeholder={t("llm.api_key_placeholder")}
+ autoFocus={baseUrlMode !== "required"}
+ />
+ </OptionsRow>
+ )}
+ {baseUrlMode === "advanced" && baseUrlField}
+ {!usesApiKey && baseUrlMode === "none" && (
- <p>{t("llm.claude_agent_description")}</p>
++ <p>{providerType?.connectionDescription}</p>
+ )}
+ </CardSection>
+ </Card>
+ </>
+ )
+ },
+ {
+ id: "models",
+ title: namedTitle,
+ // Never blocked: an empty selection is valid (it hides all of the provider's
+ // models, same as a pre-selection migration), and allowing it avoids a
+ // dead-end when the live model fetch fails.
+ content: (
+ <Card heading={t("llm.select_models")}>
+ <CardSection>
+ <ModelSelection
+ query={modelQuery}
+ selected={selectedModels}
+ onChange={setSelectedModels}
+ autoSelectDefaults={seedDefaultModels}
+ // Only for the local runtimes: the checklist is about starting a
+ // server on your own machine, which says nothing useful about a
+ // hosted endpoint failing to list.
+ troubleshooting={providerType?.group === "local" ? <SelfHostedTroubleshooting /> : undefined}
+ />
+ </CardSection>
+ </Card>
+ )
+ }
+ ];
return createPortal(
- <Modal
+ <WizardModal
show={show}
onHidden={handleCancel}
- onSubmit={handleSubmit}
- formRef={formRef}
- title={t("llm.add_provider_title")}
+ steps={steps}
+ step={step}
+ onStepChange={setStep}
+ // Editing starts at the connection details — the provider type of a saved
+ // config is fixed — so the picker behind it is not somewhere Back can go.
+ entryStep={firstStep}
+ finishLabel={isEdit ? t("llm.save") : t("llm.add_provider")}
+ onFinish={handleFinish}
className="add-provider-modal"
size="md"
maxWidth={600}
diff --cc apps/client/src/widgets/type_widgets/options/llm/provider_icons.ts
index 0000000000,a37183f0a9..fac5d15a3f
mode 000000,100644..100644
--- a/apps/client/src/widgets/type_widgets/options/llm/provider_icons.ts
+++ b/apps/client/src/widgets/type_widgets/options/llm/provider_icons.ts
@@@ -1,0 -1,40 +1,42 @@@
+ /**
+ * Per-provider marks, shared by the provider setup wizard and the chat model picker.
+ *
+ * Keyed by provider *type* (`LlmProviderConfig.provider`), not by the user's configuration
+ * id — two Ollama configurations show the same mark, which is why the model picker keeps its
+ * per-configuration group headers rather than relying on the icon alone to tell them apart.
+ *
+ * Rendered through `MaskedIcon`, so these are tinted monochrome with `currentColor` rather
+ * than shown in brand colours: the shape is what distinguishes them, and monochrome sits
+ * with the rest of Trilium's chrome.
+ */
+
+ import anthropicIcon from "./icons/anthropic.svg?url";
+ import claudeAgentIcon from "./icons/claude-ai.svg?url";
+ import deepseekIcon from "./icons/deepseek.svg?url";
+ import geminiIcon from "./icons/gemini.svg?url";
++import githubCopilotIcon from "./icons/github-copilot.svg?url";
+ import lmStudioIcon from "./icons/lmstudio.svg?url";
+ import ollamaIcon from "./icons/ollama.svg?url";
+ import openaiIcon from "./icons/openai.svg?url";
+ import openAiCompatibleIcon from "./icons/robot.svg?url";
+
+ export const PROVIDER_ICONS: Record<string, string> = {
+ anthropic: anthropicIcon,
+ "claude-agent": claudeAgentIcon,
++ "copilot-agent": githubCopilotIcon,
+ deepseek: deepseekIcon,
+ google: geminiIcon,
+ lmstudio: lmStudioIcon,
+ ollama: ollamaIcon,
+ openai: openaiIcon,
+ "openai-compatible": openAiCompatibleIcon
+ };
+
+ /**
+ * The mark for a provider type, falling back to the generic one so a provider added later —
+ * or a configuration restored from a newer version — still gets a glyph rather than a gap
+ * that would misalign the row.
+ */
+ export function providerIconUrl(provider: string | undefined): string {
+ return (provider && PROVIDER_ICONS[provider]) || openAiCompatibleIcon;
+ }
diff --cc apps/desktop/package.json
index 0ff7078da5,980ff58369..c7a5478fb5
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@@ -49,10 -49,9 +49,9 @@@
"@triliumnext/server": "workspace:*",
"@types/electron-squirrel-startup": "1.0.2",
"@types/pngjs": "6.0.5",
- "electron": "42.7.0",
+ "electron": "43.3.0",
"gifenc": "1.0.3",
- "node-mocks-http": "1.18.0",
- "pngjs": "7.0.0",
- "prebuild-install": "7.1.3"
+ "node-mocks-http": "1.18.1",
+ "pngjs": "7.0.0"
}
-}
+}
diff --cc apps/server/src/services/llm/index.spec.ts
index 7b36382428,ecb14c4efc..8f5aa7ce20
--- a/apps/server/src/services/llm/index.spec.ts
+++ b/apps/server/src/services/llm/index.spec.ts
@@@ -1,170 -1,44 +1,46 @@@
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+ import { describe, expect, it, vi } from "vitest";
- const { getOptionOrNullMock, errorMock } = vi.hoisted(() => ({
- getOptionOrNullMock: vi.fn(),
- errorMock: vi.fn()
+ const registrations = vi.hoisted(() => ({
+ hostProviders: [] as { type: string; factory: () => unknown }[],
+ docNoteReader: undefined as ((note: unknown) => string | null) | undefined,
+ skillReader: undefined as ((file: string) => string | null) | undefined,
+ toolRegistries: [] as unknown[]
}));
- vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- options: { ...actual.options, getOptionOrNull: getOptionOrNullMock },
- getLog: () => ({ error: errorMock, info: vi.fn(), warn: vi.fn() })
- };
- });
-
- /** Each provider stub records its constructor args and exposes a tagged model list. */
- function makeProviderMock(tag: string) {
- return class {
- static lastArgs: unknown[] = [];
- constructor(...args: unknown[]) {
- (this.constructor as any).lastArgs = args;
- }
- getAvailableModels() {
- return [{ id: `${tag}-model`, name: `${tag} Model` }];
- }
- };
- }
-
- vi.mock("./providers/anthropic.js", () => ({ AnthropicProvider: makeProviderMock("anthropic") }));
- vi.mock("./providers/openai.js", () => ({ OpenAiProvider: makeProviderMock("openai") }));
- vi.mock("./providers/google.js", () => ({ GoogleProvider: makeProviderMock("google") }));
- vi.mock("./providers/claude_agent.js", () => ({ ClaudeAgentProvider: makeProviderMock("claude-agent") }));
- vi.mock("./providers/copilot_agent.js", () => ({ CopilotAgentProvider: makeProviderMock("copilot-agent") }));
-
- import {
- clearProviderCache,
- getAllModels,
- getProvider,
- getProviderByType,
- hasConfiguredProviders
- } from "./index.js";
-
- function setProviders(configs: unknown) {
- getOptionOrNullMock.mockReturnValue(typeof configs === "string" ? configs : JSON.stringify(configs));
- }
-
- const TWO = [
- { id: "a1", name: "My Claude", provider: "anthropic", apiKey: "k1", baseURL: "https://proxy" },
- { id: "o1", name: "My GPT", provider: "openai", apiKey: "k2" }
- ];
-
- describe("llm/index provider registry", () => {
- beforeEach(() => {
- clearProviderCache();
- vi.clearAllMocks();
- });
- afterEach(() => {
- clearProviderCache();
- });
-
- describe("getProvider", () => {
- it("returns the first provider when no id is given and caches it", () => {
- setProviders(TWO);
- const p1 = getProvider();
- const p2 = getProvider();
- expect(p1).toBe(p2); // cached
- expect((p1.constructor as any).lastArgs).toEqual(["k1", "https://proxy"]);
- });
-
- it("returns the provider matching a given id", () => {
- setProviders(TWO);
- const p = getProvider("o1");
- expect((p.constructor as any).lastArgs).toEqual(["k2", undefined]);
- });
-
- it("instantiates each known provider type via its factory", () => {
- setProviders([
- { id: "a", name: "A", provider: "anthropic", apiKey: "ka" },
- { id: "o", name: "O", provider: "openai", apiKey: "ko" },
- { id: "g", name: "G", provider: "google", apiKey: "kg" },
- { id: "c", name: "C", provider: "claude-agent", apiKey: "" },
- { id: "gh", name: "GH", provider: "copilot-agent", apiKey: "" }
- ]);
- expect((getProvider("a").constructor as any).lastArgs).toEqual(["ka", undefined]);
- expect((getProvider("o").constructor as any).lastArgs).toEqual(["ko", undefined]);
- expect((getProvider("g").constructor as any).lastArgs).toEqual(["kg", undefined]);
- // The subscription providers take no constructor args — auth belongs
- // to Claude Code and the Copilot CLI respectively.
- expect((getProvider("c").constructor as any).lastArgs).toEqual([]);
- expect((getProvider("gh").constructor as any).lastArgs).toEqual([]);
- });
-
- it("throws when no providers are configured (null and empty array)", () => {
- getOptionOrNullMock.mockReturnValue(null);
- expect(() => getProvider()).toThrow(/No LLM providers configured/);
- setProviders([]);
- expect(() => getProvider()).toThrow(/No LLM providers configured/);
- });
-
- it("throws when the requested id is not found", () => {
- setProviders(TWO);
- expect(() => getProvider("nope")).toThrow(/not found: nope/);
- });
-
- it("throws for an unknown provider type", () => {
- setProviders([{ id: "x", name: "X", provider: "mystery", apiKey: "k" }]);
- expect(() => getProvider("x")).toThrow(/Unknown LLM provider type: mystery/);
- });
- });
-
- describe("getConfiguredProviders error handling (via hasConfiguredProviders)", () => {
- it("treats malformed JSON as no providers and logs the error", () => {
- getOptionOrNullMock.mockReturnValue("{not json");
- expect(hasConfiguredProviders()).toBe(false);
- expect(errorMock).toHaveBeenCalled();
- });
-
- it("treats a null option as no providers", () => {
- getOptionOrNullMock.mockReturnValue(null);
- expect(hasConfiguredProviders()).toBe(false);
- });
-
- it("reports true when providers exist", () => {
- setProviders(TWO);
- expect(hasConfiguredProviders()).toBe(true);
- });
- });
-
- describe("getProviderByType", () => {
- it("returns the first provider of the given type", () => {
- setProviders(TWO);
- const p = getProviderByType("openai");
- expect((p.constructor as any).lastArgs).toEqual(["k2", undefined]);
- });
-
- it("throws when no provider of that type is configured", () => {
- setProviders(TWO);
- expect(() => getProviderByType("google")).toThrow(/No google provider configured/);
- });
- });
-
- describe("getAllModels", () => {
- it("aggregates models across provider types, tagged with the provider", () => {
- setProviders(TWO);
- const models = getAllModels();
- expect(models).toEqual([
- { id: "anthropic-model", name: "anthropic Model", provider: "anthropic" },
- { id: "openai-model", name: "openai Model", provider: "openai" }
- ]);
- });
-
- it("includes each provider type only once even with duplicate configs", () => {
- setProviders([
- { id: "a1", name: "A1", provider: "anthropic", apiKey: "k1" },
- { id: "a2", name: "A2", provider: "anthropic", apiKey: "k2" }
- ]);
- const models = getAllModels();
- expect(models).toHaveLength(1);
- expect(models[0].provider).toBe("anthropic");
- });
+ vi.mock("@triliumnext/core/src/services/llm/index.js", () => ({
+ registerHostProvider: (type: string, factory: () => unknown) => { registrations.hostProviders.push({ type, factory }); }
+ }));
+ vi.mock("@triliumnext/core/src/services/llm/skills.js", () => ({
+ registerSkillReader: (reader: (file: string) => string | null) => { registrations.skillReader = reader; }
+ }));
+ vi.mock("@triliumnext/core/src/services/llm/tools/helpers.js", () => ({
+ registerDocNoteHtmlReader: (reader: (note: unknown) => string | null) => { registrations.docNoteReader = reader; }
+ }));
+ vi.mock("@triliumnext/core/src/services/llm/tools/index.js", () => ({
+ registerToolRegistry: (registry: unknown) => { registrations.toolRegistries.push(registry); }
+ }));
- it("skips and logs a provider whose model lookup throws", () => {
- setProviders([{ id: "x", name: "X", provider: "mystery", apiKey: "k" }]);
- // Unknown type → getProvider throws inside getAllModels and is caught.
- expect(getAllModels()).toEqual([]);
- expect(errorMock).toHaveBeenCalled();
- });
+ import { registerServerLlmExtensions } from "./index.js";
+ import { ClaudeAgentProvider } from "./providers/claude_agent.js";
++import { CopilotAgentProvider } from "./providers/copilot_agent.js";
+ import { helpTools } from "./tools/help_tools.js";
+
+ describe("registerServerLlmExtensions", () => {
+ it("hands core every piece of the stack that needs Node", () => {
+ registerServerLlmExtensions();
+
- // The subscription provider, which shells out to the Claude Code CLI, under
- // the type core knows it by. Registered as a factory, so nothing is
- // constructed until a chat asks for it.
- expect(registrations.hostProviders.map(p => p.type)).toEqual(["claude-agent"]);
++ // The subscription providers, which shell out to the Claude Code and Copilot
++ // CLIs, under the types core knows them by. Registered as factories, so
++ // nothing is constructed until a chat asks for it.
++ expect(registrations.hostProviders.map(p => p.type)).toEqual(["claude-agent", "copilot-agent"]);
+ expect(registrations.hostProviders[0].factory()).toBeInstanceOf(ClaudeAgentProvider);
++ expect(registrations.hostProviders[1].factory()).toBeInstanceOf(CopilotAgentProvider);
+ // The User Guide reader, which core's note-content helper calls for doc notes.
+ expect(registrations.docNoteReader).toBeTypeOf("function");
+ // The skill sheets: core owns the catalog and the tool, the server only
+ // knows how to get a sheet off disk.
+ expect(registrations.skillReader?.("search_syntax.md")).toContain("#");
+ // The one registry still backed by files this build alone carries.
+ expect(registrations.toolRegistries).toEqual([helpTools]);
});
});
diff --cc apps/server/src/services/llm/index.ts
index 2f5328900d,cd037d2259..451c0e52e8
--- a/apps/server/src/services/llm/index.ts
+++ b/apps/server/src/services/llm/index.ts
@@@ -1,148 -1,37 +1,38 @@@
- 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";
-
- /**
- * Configuration for a single LLM provider instance.
- * This matches the structure stored in the llmProviders option.
- */
- export interface LlmProviderSetup {
- id: string;
- name: string;
- provider: string;
- apiKey: string;
- /** Optional override for the SDK's default API endpoint (e.g. for self-hosted Ollama, vLLM, or proxies). */
- baseURL?: string;
- }
-
- /** Factory functions for creating provider instances */
- const providerFactories: Record<string, (apiKey: string, baseURL?: string) => LlmProvider> = {
- anthropic: (apiKey, baseURL) => new AnthropicProvider(apiKey, baseURL),
- openai: (apiKey, baseURL) => new OpenAiProvider(apiKey, baseURL),
- google: (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(),
- // 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 */
- let cachedProviders: Record<string, LlmProvider> = {};
-
/**
- * Get configured providers from the options.
+ * The server's Node-only contributions to the LLM stack.
+ *
+ * The stack itself lives in `@triliumnext/core`, so the browser-hosted
+ * (standalone) build can run it too. What could not follow it there is anything
- * that needs Node: the provider that spawns the Claude Code CLI, and the User
- * Guide tools, which read pages off disk. Core exposes a seam for each; this is
- * where the server fills them in — including the skill sheets, whose catalog is
- * core's while the reading is per-runtime.
++ * that needs Node: the providers that spawn the Claude Code and GitHub Copilot
++ * CLIs, and the User Guide tools, which read pages off disk. Core exposes a seam
++ * for each; this is where the server fills them in — including the skill sheets,
++ * whose catalog is core's while the reading is per-runtime.
+ *
- * Each seam is keyed rather than bespoke, so the next host-provided provider
- * (GitHub Copilot and the like) is one more line here and one more entry in
- * core's HOST_PROVIDED_TYPES.
++ * Each seam is keyed rather than bespoke, so the next host-provided provider is
++ * one more line here and one more entry in core's HOST_PROVIDED_TYPES.
*/
- function getConfiguredProviders(): LlmProviderSetup[] {
- try {
- const providersJson = optionService.getOptionOrNull("llmProviders");
- if (!providersJson) {
- return [];
- }
- return JSON.parse(providersJson) as LlmProviderSetup[];
- } catch (e) {
- getLog().error(`Failed to parse llmProviders option: ${e}`);
- return [];
- }
- }
-
- /**
- * Get a provider instance by its configuration ID.
- * If no ID is provided, returns the first configured provider.
- */
- export function getProvider(providerId?: string): LlmProvider {
- const configs = getConfiguredProviders();
-
- if (configs.length === 0) {
- throw new Error("No LLM providers configured. Please add a provider in Options → AI / LLM.");
- }
- // Find the requested provider or use the first one
- const config = providerId
- ? configs.find(c => c.id === providerId)
- : configs[0];
-
- if (!config) {
- throw new Error(`LLM provider not found: ${providerId}`);
- }
-
- // Check cache
- if (cachedProviders[config.id]) {
- return cachedProviders[config.id];
- }
-
- // Create new provider instance
- const factory = providerFactories[config.provider];
- if (!factory) {
- throw new Error(`Unknown LLM provider type: ${config.provider}. Available: ${Object.keys(providerFactories).join(", ")}`);
- }
-
- const provider = factory(config.apiKey, config.baseURL);
- cachedProviders[config.id] = provider;
- return provider;
- }
+ import { registerHostProvider } from "@triliumnext/core/src/services/llm/index.js";
+ import { registerSkillReader } from "@triliumnext/core/src/services/llm/skills.js";
+ import { registerDocNoteHtmlReader } from "@triliumnext/core/src/services/llm/tools/helpers.js";
+ import { registerToolRegistry } from "@triliumnext/core/src/services/llm/tools/index.js";
- /**
- * Get the first configured provider of a specific type (e.g., "anthropic").
- */
- export function getProviderByType(providerType: string): LlmProvider {
- const configs = getConfiguredProviders();
- const config = configs.find(c => c.provider === providerType);
-
- if (!config) {
- throw new Error(`No ${providerType} provider configured. Please add one in Options → AI / LLM.`);
- }
-
- return getProvider(config.id);
- }
-
- /**
- * Check if any providers are configured.
- */
- export function hasConfiguredProviders(): boolean {
- return getConfiguredProviders().length > 0;
- }
-
- /**
- * Get all models from all configured providers, tagged with their provider type.
- */
- export function getAllModels(): ModelInfo[] {
- const configs = getConfiguredProviders();
- const seenProviderTypes = new Set<string>();
- const allModels: ModelInfo[] = [];
-
- for (const config of configs) {
- // Only include models once per provider type (not per config instance)
- if (seenProviderTypes.has(config.provider)) {
- continue;
- }
- seenProviderTypes.add(config.provider);
-
- try {
- const provider = getProvider(config.id);
- const models = provider.getAvailableModels();
- for (const model of models) {
- allModels.push({ ...model, provider: config.provider });
- }
- } catch (e) {
- getLog().error(`Failed to get models from provider ${config.provider}: ${e}`);
- }
- }
-
- return allModels;
- }
+ import { loadSkillSheet } from "../../core_assets.js";
+ import { ClaudeAgentProvider } from "./providers/claude_agent.js";
++import { CopilotAgentProvider } from "./providers/copilot_agent.js";
+ import { getDocNoteHtml } from "./tools/doc_notes.js";
+ import { helpTools } from "./tools/help_tools.js";
/**
- * Clear the provider cache. Call this when provider configurations change.
+ * Contribute those pieces to core. Called once from startup, beside the other
+ * registrations there, rather than run as an import side effect: core's own LLM
+ * routes reach the stack directly, so what a chat can use must not depend on
+ * whether some module that happens to import this one was loaded first.
*/
- export function clearProviderCache(): void {
- cachedProviders = {};
+ export function registerServerLlmExtensions() {
+ registerHostProvider("claude-agent", () => new ClaudeAgentProvider());
++ registerHostProvider("copilot-agent", () => new CopilotAgentProvider());
+ registerDocNoteHtmlReader(getDocNoteHtml);
+ registerSkillReader(loadSkillSheet);
+ registerToolRegistry(helpTools);
}
-
- export type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing } from "./types.js";
diff --cc apps/server/src/services/llm/providers/claude_agent.ts
index e785d153d0,6c25323417..010d58d484
--- a/apps/server/src/services/llm/providers/claude_agent.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.ts
@@@ -22,26 -22,23 +22,27 @@@
import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDKMessage, type SDKUserMessage, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";
-import type { LlmFilePart, LlmImagePart, LlmMessage, LlmMessagePart, LlmStreamChunk, LlmTextAttachmentPart } from "@triliumnext/commons";
+import 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 { anthropicRecommendedIds } from "@triliumnext/core/src/services/llm/providers/anthropic.js";
+ import { buildModelList, mergeModelLists, type RemoteModel } from "@triliumnext/core/src/services/llm/providers/base_provider.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 { spawn as nodeSpawn } from "child_process";
-import { createHash } from "crypto";
import fs from "fs";
import path from "path";
import dataDirs from "../../data_dir.js";
import { createMcpServer } from "../../mcp/mcp_server.js";
- import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
- import { resolveAttachmentPart } from "./attachment_content.js";
- 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";
diff --cc apps/server/src/services/llm/providers/copilot_agent.spec.ts
index b828d3e672,0000000000..5e9030b0d0
mode 100644,000000..100644
--- a/apps/server/src/services/llm/providers/copilot_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
@@@ -1,697 -1,0 +1,697 @@@
+import type { LlmStreamChunk } from "@triliumnext/commons";
+import fs from "fs";
+import os from "os";
+import path from "path";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const errorLogMock = vi.hoisted(() => vi.fn());
+const infoLogMock = vi.hoisted(() => vi.fn());
+vi.mock("@triliumnext/core", () => ({
+ getLog: () => ({ info: infoLogMock, 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") } };
+});
+
+/** The directory the provider derives from the mocked data dir above. */
+const AGENT_CWD = path.resolve(os.tmpdir(), "trilium-copilot-agent-spec", "copilot-agent");
+
+// 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 }));
++vi.mock("@triliumnext/core/src/services/llm/note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));
+
+const resolveAttachmentPartMock = vi.hoisted(() => vi.fn());
- vi.mock("./attachment_content.js", () => ({ resolveAttachmentPart: resolveAttachmentPartMock }));
++vi.mock("@triliumnext/core/src/services/llm/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 initializeError: Error | undefined;
+ static sessionNewError: Error | undefined;
+ static sessionLoadError: Error | undefined;
+ static setModelError: Error | undefined;
+ /** Id handed out by the next `session/new` (the real CLI never reuses one). */
+ static newSessionId = "sess-1";
+
+ 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") {
+ if (FakeAcpClient.initializeError) throw FakeAcpClient.initializeError;
+ return {} as T;
+ }
+ if (method === "session/new") {
+ if (FakeAcpClient.sessionNewError) throw FakeAcpClient.sessionNewError;
+ return { sessionId: FakeAcpClient.newSessionId } as T;
+ }
+ if (method === "session/load") {
+ if (FakeAcpClient.sessionLoadError) throw FakeAcpClient.sessionLoadError;
+ // A real load replays the session's history as notifications.
+ this.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "REPLAY" } });
+ return {} as T;
+ }
+ if (method === "session/set_model") {
+ if (FakeAcpClient.setModelError) throw FakeAcpClient.setModelError;
+ 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, createUpdateCollector, 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 });
+const assistantMessage = (text: string) => ({ role: "assistant" as const, content: text });
+
+function resetFakes() {
+ errorLogMock.mockReset();
+ infoLogMock.mockReset();
+ resolveAttachmentPartMock.mockReset();
+ resetAgentCwdForTests();
+ mcpEndpointMock.mockClear();
+ FakeAcpClient.current = undefined;
+ FakeAcpClient.initializeError = undefined;
+ FakeAcpClient.sessionNewError = undefined;
+ FakeAcpClient.sessionLoadError = undefined;
+ FakeAcpClient.setModelError = undefined;
+ FakeAcpClient.newSessionId = "sess-1";
+ FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });
+}
+
+describe("CopilotAgentProvider metadata", () => {
+ it("exposes the subscription model list and refuses the AI-SDK chat entry point", () => {
+ const provider = new CopilotAgentProvider();
+
+ expect(provider.getAvailableModels().filter(m => m.isDefault).map(m => m.id)).toEqual(["auto"]);
+ expect(provider.getModelPricing("gpt-5.4")).toEqual({ input: 0, output: 0 });
+ expect(provider.getModelPricing("gpt-4-turbo")).toBeUndefined();
+ expect(() => provider.chat()).toThrow(/chatChunks/);
+ });
+});
+
+describe("CopilotAgentProvider.chatChunks", () => {
+ beforeEach(resetFakes);
+
+ 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("ends the turn on abort even when the agent never answers the cancel", async () => {
+ const controller = new AbortController();
+ FakeAcpClient.promptScript = client => {
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "partial" } });
+ setTimeout(() => controller.abort(), 0);
+ // Never settles: only the abort can end this turn.
+ return new Promise<{ stopReason?: string }>(() => {});
+ };
+
+ const provider = new CopilotAgentProvider();
+ const chunks = await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-abort" }, controller.signal));
+
+ expect(chunks).toEqual([{ type: "text", content: "partial" }, { type: "done" }]);
+ expect(FakeAcpClient.current?.notifications).toContainEqual({ method: "session/cancel", params: { sessionId: "sess-1" } });
+ expect(FakeAcpClient.current?.disposed).toBe(true);
+
+ // The aborted session's real history is unknown, so the next turn must
+ // reseed rather than resume it — even though the transcript lines up.
+ FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });
+ await collect(provider.chatChunks(
+ [userMessage("hi"), { role: "assistant", content: "partial" }, userMessage("more")],
+ { chatNoteId: "chat-abort" }
+ ));
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(false);
+ });
+
+ it("flattens both wrapped and direct tool-result content blocks", async () => {
+ FakeAcpClient.promptScript = async client => {
+ client.update({ sessionUpdate: "tool_call", toolCallId: "t1", title: "search_notes" });
+ client.update({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "t1",
+ status: "completed",
+ content: [
+ { type: "content", content: { type: "text", text: "wrapped" } },
+ { type: "text", text: "direct" }
+ ]
+ });
+ return { stopReason: "end_turn" };
+ };
+
+ const provider = new CopilotAgentProvider();
+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));
+
+ expect(chunks).toContainEqual(expect.objectContaining({ type: "tool_result", result: "wrapped\ndirect" }));
+ });
+
+ 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)");
+ });
+
+ it("flags attachments to the note hint and leads the prompt blocks with the prefix", async () => {
+ resolveAttachmentPartMock.mockReturnValue(undefined);
+
+ const provider = new CopilotAgentProvider();
+ await collect(provider.chatChunks([{
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "file", attachmentId: "p", mime: "application/pdf", filename: "doc.pdf" }
+ ]
+ }], { contextNoteId: "note123" }));
+
+ expect(buildNoteHintMock).toHaveBeenCalledWith("note123", true);
+ 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)");
+ expect(blocks.at(-1)).toEqual({ type: "text", text: "[attached file: doc.pdf]" });
+ });
+
+ it("resumes a mapped session, suppressing the load replay, and reseeds once the transcript diverges", async () => {
+ const provider = new CopilotAgentProvider();
+ FakeAcpClient.promptScript = async client => {
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "answer" } });
+ return { stopReason: "end_turn" };
+ };
+ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-resume" }));
+
+ // Same transcript → session/load instead of a fresh session/new, and no
+ // system instructions or history replay in the prompt.
+ FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });
+ const resumed = await collect(provider.chatChunks(
+ [userMessage("hi"), assistantMessage("answer"), userMessage("more")],
+ { chatNoteId: "chat-resume" }
+ ));
+
+ const load = FakeAcpClient.current?.requests.find(r => r.method === "session/load");
+ expect(load?.params).toMatchObject({ sessionId: "sess-1", cwd: AGENT_CWD });
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/new")).toBe(false);
+ expect(resumed).toEqual([{ type: "done" }]);
+ 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).toBe("more");
+
+ // An edited history no longer hashes to the mapped session, so the next
+ // turn must reseed rather than resume.
+ await collect(provider.chatChunks(
+ [userMessage("rewritten"), assistantMessage("answer"), userMessage("more")],
+ { chatNoteId: "chat-resume" }
+ ));
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(false);
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/new")).toBe(true);
+ });
+
+ it("reseeds a fresh session when session/load fails", async () => {
+ const provider = new CopilotAgentProvider();
+ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-load-fail" }));
+
+ FakeAcpClient.sessionLoadError = new Error("unknown session");
+ FakeAcpClient.newSessionId = "sess-2";
+ const chunks = await collect(provider.chatChunks(
+ [userMessage("hi"), assistantMessage(""), userMessage("more")],
+ { chatNoteId: "chat-load-fail" }
+ ));
+
+ expect(FakeAcpClient.current?.requests.map(r => r.method))
+ .toEqual(["initialize", "session/load", "session/new", "session/prompt"]);
+ expect(infoLogMock).toHaveBeenCalledWith(expect.stringContaining("session/load failed (unknown session)"));
+ expect(chunks).toEqual([{ type: "done" }]);
+ // A reseeded session is told everything again: instructions + replay.
+ 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("<system_instructions>");
+ expect(blocks[0].text).toContain("<conversation_history>");
+ });
+
+ it("continues with the agent's default model when session/set_model fails", async () => {
+ FakeAcpClient.setModelError = new Error("model unavailable");
+
+ const provider = new CopilotAgentProvider();
+ const chunks = await collect(provider.chatChunks([userMessage("hi")], { model: "gpt-5.4" }));
+
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining(`failed to select model "gpt-5.4"`));
+ expect(chunks).toEqual([{ type: "done" }]);
+ });
+
+ it("disposes the client and reports the failure when the initialize handshake fails", async () => {
+ FakeAcpClient.initializeError = new Error("handshake rejected");
+
+ const provider = new CopilotAgentProvider();
+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));
+
+ expect(chunks).toEqual([{ type: "error", error: "handshake rejected" }]);
+ expect(FakeAcpClient.current?.disposed).toBe(true);
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/new")).toBe(false);
+ });
+
+ it("maps prompt failures to actionable messages", async () => {
+ const provider = new CopilotAgentProvider();
+
+ FakeAcpClient.promptScript = async () => { throw new Error("the agent crashed"); };
+ expect(await collect(provider.chatChunks([userMessage("hi")], {})))
+ .toEqual([{ type: "error", error: "the agent crashed" }]);
+
+ // Non-Error rejections are stringified rather than dropped.
+ FakeAcpClient.promptScript = () => Promise.reject("plain rejection");
+ expect(await collect(provider.chatChunks([userMessage("hi")], {})))
+ .toEqual([{ type: "error", error: "plain rejection" }]);
+
+ // A spawn failure names the CLI that could not start.
+ FakeAcpClient.sessionNewError = new Error("spawn copilot ENOENT");
+ expect(await collect(provider.chatChunks([userMessage("hi")], {})))
+ .toEqual([{ type: "error", error: "Failed to start the GitHub Copilot CLI: spawn copilot ENOENT" }]);
+
+ // Auth problems are recognized by wording too, not only by error code.
+ FakeAcpClient.sessionNewError = new FakeAcpError(-32603, "authentication required");
+ expect(await collect(provider.chatChunks([userMessage("hi")], {})))
+ .toEqual([{ type: "error", error: expect.stringContaining("copilot login") }]);
+ });
+
+ it("describes early and unknown stop reasons", async () => {
+ const provider = new CopilotAgentProvider();
+ const errorFor = async (stopReason: string) => {
+ FakeAcpClient.promptScript = async () => ({ stopReason });
+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));
+ return chunks.find(c => c.type === "error");
+ };
+
+ expect(await errorFor("max_tokens")).toEqual({ type: "error", error: expect.stringContaining("max tokens") });
+ expect(await errorFor("max_turn_requests")).toEqual({ type: "error", error: expect.stringContaining("max turn requests") });
+ expect(await errorFor("something_new")).toEqual({ type: "error", error: "Agent stopped: something_new" });
+ });
+
+ it("answers the permission callback and refuses every other agent request", async () => {
+ const provider = new CopilotAgentProvider();
+ await collect(provider.chatChunks([userMessage("hi")], {}));
+
+ const onAgentRequest = FakeAcpClient.current?.onAgentRequest;
+ expect(onAgentRequest?.("session/request_permission", {
+ toolCall: { toolCallId: "toolu_x", title: "Echo hello", kind: "execute" },
+ options: [{ optionId: "reject_once", kind: "reject_once" }]
+ })).toEqual({ outcome: { outcome: "selected", optionId: "reject_once" } });
+ expect(() => onAgentRequest?.("fs/read_text_file", {})).toThrow(`Trilium does not support "fs/read_text_file".`);
+ });
+
+ it("creates the agent cwd with a .git marker so enclosing repo config is not inherited", async () => {
+ fs.rmSync(AGENT_CWD, { recursive: true, force: true });
+
+ const provider = new CopilotAgentProvider();
+ await collect(provider.chatChunks([userMessage("hi")], {}));
+
+ expect(fs.readFileSync(path.join(AGENT_CWD, ".git", "HEAD"), "utf8")).toBe("ref: refs/heads/main\n");
+ expect(fs.existsSync(path.join(AGENT_CWD, ".git", "objects"))).toBe(true);
+ expect(fs.existsSync(path.join(AGENT_CWD, ".git", "refs"))).toBe(true);
+ });
+
+ it("evicts the oldest mapping once more chat notes are tracked than the limit", async () => {
+ const provider = new CopilotAgentProvider();
+ // One more than MAX_TRACKED_SESSIONS (200), so "lru-0" falls out.
+ for (let i = 0; i <= 200; i++) {
+ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: `lru-${i}` }));
+ }
+
+ const followUp = [userMessage("hi"), assistantMessage(""), userMessage("more")];
+ await collect(provider.chatChunks(followUp, { chatNoteId: "lru-0" }));
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(false);
+
+ await collect(provider.chatChunks(followUp, { chatNoteId: "lru-200" }));
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(true);
+ });
+});
+
+describe("CopilotAgentProvider.generateTitle", () => {
+ beforeEach(resetFakes);
+
+ it("accumulates the streamed title on the cheap model, trimming quotes and capping length", async () => {
+ const longTitle = "Weekly planning notes".padEnd(120, "!");
+ FakeAcpClient.promptScript = async client => {
+ client.onNotification("session/idle", {});
+ client.update({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "thinking" } });
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "image", data: "x", mimeType: "image/png" } });
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: ` "${longTitle.slice(0, 30)}` } });
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: `${longTitle.slice(30)}" ` } });
+ return { stopReason: "end_turn" };
+ };
+
+ const title = await new CopilotAgentProvider().generateTitle("plan my week");
+
+ expect(title).toBe(longTitle.substring(0, 100));
+ expect(FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params)
+ .toMatchObject({ modelId: "gpt-5-mini" });
+ expect(FakeAcpClient.current?.requests.find(r => r.method === "session/new")?.params)
+ .toMatchObject({ mcpServers: [] });
+ expect(FakeAcpClient.current?.disposed).toBe(true);
+ });
+
+ it("still produces a title when the cheap model cannot be selected", async () => {
+ FakeAcpClient.setModelError = new Error("model unavailable");
+ FakeAcpClient.promptScript = async client => {
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Fallback title" } });
+ return { stopReason: "end_turn" };
+ };
+
+ expect(await new CopilotAgentProvider().generateTitle("hi")).toBe("Fallback title");
+ });
+
+ it("returns an empty title and logs when the agent fails", async () => {
+ FakeAcpClient.sessionNewError = new Error("spawn copilot ENOENT");
+
+ expect(await new CopilotAgentProvider().generateTitle("hi")).toBe("");
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("Failed to start the GitHub Copilot CLI"));
+ expect(FakeAcpClient.current?.disposed).toBe(true);
+ });
+});
+
+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" } });
+ // ...and when the request carries no tool call or options at all.
+ expect(decidePermission({})).toEqual({ outcome: { outcome: "cancelled" } });
+ });
+});
+
+describe("createUpdateCollector", () => {
+ type UpdateCollector = ReturnType<typeof createUpdateCollector>;
+
+ const notify = (collector: UpdateCollector, update: Record<string, unknown>, sessionId = "sess-1") =>
+ collector.onNotification("session/update", { sessionId, update });
+
+ /** A collector already bound to "sess-1", collecting into the returned array. */
+ function boundCollector(): { collector: UpdateCollector; chunks: LlmStreamChunk[] } {
+ const chunks: LlmStreamChunk[] = [];
+ const collector = createUpdateCollector(chunk => chunks.push(chunk));
+ collector.sessionId = "sess-1";
+ return { collector, chunks };
+ }
+
+ it("ignores other methods, muted replay, empty updates, and stray sessions", () => {
+ const chunks: LlmStreamChunk[] = [];
+ const collector = createUpdateCollector(chunk => chunks.push(chunk));
+ const message = { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "nope" } };
+
+ collector.onNotification("session/idle", {});
+ collector.muted = true;
+ notify(collector, message);
+ collector.muted = false;
+ collector.onNotification("session/update", { sessionId: "sess-1" });
+ collector.sessionId = "sess-1";
+ notify(collector, message, "sess-other");
+
+ expect(chunks).toEqual([]);
+ });
+
+ it("drops message and thought chunks that carry no text, and unknown update kinds", () => {
+ const { collector, chunks } = boundCollector();
+
+ notify(collector, { sessionUpdate: "agent_message_chunk" });
+ notify(collector, { sessionUpdate: "agent_message_chunk", content: { type: "image", data: "x", mimeType: "image/png" } });
+ notify(collector, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "" } });
+ notify(collector, { sessionUpdate: "plan", entries: [] });
+
+ expect(chunks).toEqual([]);
+ });
+
+ it("ignores malformed, duplicate, and unannounced tool calls", () => {
+ const { collector, chunks } = boundCollector();
+
+ notify(collector, { sessionUpdate: "tool_call", title: "missing id" });
+ notify(collector, { sessionUpdate: "tool_call_update", status: "completed" });
+ notify(collector, { sessionUpdate: "tool_call_update", toolCallId: "never-announced", status: "completed" });
+ expect(chunks).toEqual([]);
+
+ // A re-announcement keeps the first registration (untitled → "tool").
+ notify(collector, { sessionUpdate: "tool_call", toolCallId: "t1" });
+ notify(collector, { sessionUpdate: "tool_call", toolCallId: "t1", title: "re-announced" });
+ // Progress without a terminal status is not a result yet.
+ notify(collector, { sessionUpdate: "tool_call_update", toolCallId: "t1", status: "in_progress" });
+
+ expect(chunks).toEqual([{ type: "tool_use", toolCallId: "t1", toolName: "tool", toolInput: {} }]);
+ });
+
+ it("reports a failed tool call and falls back to rawOutput for the result text", () => {
+ const { collector, chunks } = boundCollector();
+
+ notify(collector, { sessionUpdate: "tool_call", toolCallId: "t1", title: "create_note" });
+ notify(collector, { sessionUpdate: "tool_call_update", toolCallId: "t1", status: "failed", rawOutput: { error: "denied" } });
+ notify(collector, { sessionUpdate: "tool_call", toolCallId: "t2", title: "read_note" });
+ // No usable text in the blocks and no rawOutput → an empty result.
+ notify(collector, { sessionUpdate: "tool_call_update", toolCallId: "t2", status: "completed", content: [null, { type: "image" }] });
+
+ expect(chunks).toEqual([
+ { type: "tool_use", toolCallId: "t1", toolName: "create_note", toolInput: {} },
+ { type: "tool_result", toolCallId: "t1", toolName: "create_note", result: `{"error":"denied"}`, isError: true },
+ { type: "tool_use", toolCallId: "t2", toolName: "read_note", toolInput: {} },
+ { type: "tool_result", toolCallId: "t2", toolName: "read_note", result: "", isError: false }
+ ]);
+ });
+});
+
+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, led by the prefix", () => {
+ resolveAttachmentPartMock.mockReturnValue({ kind: "image", mime: "image/png", bytes: new Uint8Array([1, 2, 3]) });
+ const blocks = buildPromptBlocks([{ type: "image", attachmentId: "a", mime: "image/png" }], "PREFIX");
+ expect(blocks).toEqual([
+ { type: "text", text: "PREFIX" },
+ { 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 --cc apps/server/src/services/llm/providers/copilot_agent.ts
index e5c135af28,0000000000..c01e32000f
mode 100644,000000..100644
--- a/apps/server/src/services/llm/providers/copilot_agent.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.ts
@@@ -1,678 -1,0 +1,693 @@@
+/**
+ * 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 { 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 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).
++ * covered by the subscription, which is what the picker shows.
++ *
++ * The CLI additionally reports a premium-request multiplier per model (0.33x,
++ * 1x, …); it isn't carried here, because it is only comparable against other
++ * Copilot models and the picker has no way to say so — the same reason the
++ * shared model metadata dropped its relative multiplier in favour of absolute
++ * per-token prices.
+ */
+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 }
++ { id: "claude-sonnet-5", name: "Claude Sonnet 5", pricing: { input: 0, output: 0 }, isSubscription: true },
++ { id: "claude-haiku-4.5", name: "Claude Haiku 4.5", pricing: { input: 0, output: 0 }, isSubscription: true },
++ { id: "gpt-5.4", name: "GPT-5.4", pricing: { input: 0, output: 0 }, isSubscription: true },
++ { id: "gpt-5.3-codex", name: "GPT-5.3-Codex", pricing: { input: 0, output: 0 }, isSubscription: true },
++ { id: "gpt-5.4-mini", name: "GPT-5.4 mini", pricing: { input: 0, output: 0 }, isSubscription: true },
++ { id: "gpt-5-mini", name: "GPT-5 mini", pricing: { input: 0, output: 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;
+ }
+
++ /**
++ * Every model on offer. Unlike the API providers there is nothing to filter:
++ * the list is the CLI's own picker, curated here rather than discovered, so
++ * it carries no legacy or preview entries to leave out — and all of them cost
++ * the same (nothing beyond the subscription).
++ */
++ recommendedModelIds(models: ModelInfo[]): Set<string> {
++ return new Set(models.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().");
+ }
+
+ 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 });
+ }
+ // 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();
+ }
+ }
+
+ 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") {
+ 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}`;
+ }
+ return text;
+}
+
+/** For tests. */
+export { buildPromptBlocks, createUpdateCollector };
diff --cc packages/trilium-core/src/services/llm/index.ts
index 0000000000,749bee1e43..535ce8318c
mode 000000,100644..100644
--- a/packages/trilium-core/src/services/llm/index.ts
+++ b/packages/trilium-core/src/services/llm/index.ts
@@@ -1,0 -1,254 +1,258 @@@
+ import { getLog } from "../../services/log.js";
+ import optionService from "../../services/options.js";
+
+ import { AnthropicProvider } from "./providers/anthropic.js";
+ import { DeepSeekProvider } from "./providers/deepseek.js";
+ import { GoogleProvider } from "./providers/google.js";
+ import { LocalProvider } from "./providers/local.js";
+ import { OpenAiProvider } from "./providers/openai.js";
+ import type { LlmProvider, ModelInfo } from "./types.js";
+
+ /**
+ * Configuration for a single LLM provider instance.
+ * This matches the structure stored in the llmProviders option.
+ */
+ export interface LlmProviderSetup {
+ id: string;
+ name: string;
+ provider: string;
+ apiKey: string;
+ /** Optional override for the SDK's default API endpoint (e.g. for self-hosted Ollama, vLLM, or proxies). */
+ baseURL?: string;
+ /**
+ * Models the user selected for this provider, with full metadata denormalized
+ * so the chat picker renders them without a live fetch. Absent in configs
+ * saved before model selection existed.
+ */
+ selectedModels?: ModelInfo[];
+ }
+
+ /** Provider type identifiers that can be instantiated, for error messages. */
-const PROVIDER_TYPES = ["anthropic", "openai", "google", "deepseek", "claude-agent", "ollama", "lmstudio", "openai-compatible"];
++const PROVIDER_TYPES = ["anthropic", "openai", "google", "deepseek", "claude-agent", "copilot-agent", "ollama", "lmstudio", "openai-compatible"];
+
+ /**
+ * Provider types core cannot build for itself, each mapped to the name the user
+ * knows it by.
+ *
+ * What they have in common is a dependency on the runtime around them rather
- * than on an API key: Claude Code is a CLI this process spawns, and the
- * subscription services lined up behind it authenticate through the host's own
- * account plumbing. Core runs in the browser too, where none of that exists, so
- * the host that *can* do it registers a factory at startup with
- * {@link registerHostProvider}. Where nothing registers one, selecting the
- * provider fails with a message naming it rather than a bare "unknown type".
++ * than on an API key: both are CLIs this process spawns, authenticating through
++ * the host's own account plumbing rather than a key the user pastes in. Core
++ * runs in the browser too, where none of that exists, so the host that *can* do
++ * it registers a factory at startup with {@link registerHostProvider}. Where
++ * nothing registers one, selecting the provider fails with a message naming it
++ * rather than a bare "unknown type".
+ *
+ * Adding one means an entry here, a literal branch in
+ * {@link createProviderInstance} (see the note there on why it must be literal),
+ * and a registration in whichever hosts can serve it.
+ */
+ export const HOST_PROVIDED_TYPES = {
+ /** Claude Pro/Max through the Claude Agent SDK, authenticated by `claude /login`. */
- "claude-agent": "Claude Code"
++ "claude-agent": "Claude Code",
++ /** GitHub Copilot through the Copilot CLI's ACP mode, authenticated by `copilot login`. */
++ "copilot-agent": "GitHub Copilot"
+ } as const;
+
+ /** A provider type from {@link HOST_PROVIDED_TYPES}. */
+ export type HostProvidedType = keyof typeof HOST_PROVIDED_TYPES;
+
+ const hostProviderFactories = new Map<string, () => LlmProvider>();
+
+ /**
+ * Register the host's implementation of a provider core cannot construct.
+ * Called once at startup, before any chat can ask for it.
+ */
+ export function registerHostProvider(type: HostProvidedType, factory: () => LlmProvider) {
+ hostProviderFactories.set(type, factory);
+ }
+
+ /**
+ * Forget every registered factory, putting the registry back to how a build that
+ * supplies none starts. For a runtime that re-initialises core (tests, an
+ * Electron reload), which registers again on the way back up.
+ */
+ export function clearHostProviders() {
+ hostProviderFactories.clear();
+ }
+
+ /**
+ * Build a host-provided provider, or explain that this build has no one to build
+ * it. The type is always a literal from the call site — see
+ * {@link createProviderInstance} — never the string the user's config carried.
+ */
+ function createHostProvider(type: HostProvidedType): LlmProvider {
+ const factory = hostProviderFactories.get(type);
+ if (!factory) {
+ throw new Error(`The ${HOST_PROVIDED_TYPES[type]} provider is not available in this build.`);
+ }
+ return factory();
+ }
+
+ /**
+ * Instantiate a provider from its type identifier.
+ *
+ * Deliberately a switch over literal cases rather than a lookup table: the
+ * provider type is user-controlled, and looking a factory up by it — with a
+ * plain object *or* a Map — makes the invoked function a value derived from
+ * untrusted input, which is exactly what CodeQL's
+ * `js/unvalidated-dynamic-method-call` flags. Here every branch calls a
+ * statically known constructor, so no dynamic dispatch is possible at all.
+ * The host-provided factories are looked up too, but only ever under a literal
+ * spelled out in their branch below — the untrusted string picks the branch and
+ * goes no further.
+ */
+ function createProviderInstance(provider: string, apiKey: string, baseURL?: string): LlmProvider {
+ switch (provider) {
+ case "anthropic":
+ return new AnthropicProvider(apiKey, baseURL);
+ case "openai":
+ return new OpenAiProvider(apiKey, baseURL);
+ case "google":
+ return new GoogleProvider(apiKey, baseURL);
+ // OpenAI-compatible on the wire, but carded separately from the generic
+ // custom endpoint so its models resolve against the committed price table.
+ case "deepseek":
+ return new DeepSeekProvider(apiKey, baseURL);
+ // Subscription providers, whose credentials belong to the host rather than
+ // to a key the user pastes in — so the host builds them. One branch each,
+ // naming its own type: see HOST_PROVIDED_TYPES.
+ case "claude-agent":
+ return createHostProvider("claude-agent");
++ case "copilot-agent":
++ return createHostProvider("copilot-agent");
+ // Self-hosted endpoints. The three cards differ only in the URL and setup
+ // hint the UI prefills; they all speak the OpenAI-compatible API, with
+ // Ollama and LM Studio additionally offering a richer native listing.
+ case "ollama":
+ case "lmstudio":
+ case "openai-compatible":
+ return new LocalProvider(provider, apiKey, baseURL);
+ default:
+ throw new Error(`Unknown LLM provider type: ${provider}. Available: ${PROVIDER_TYPES.join(", ")}`);
+ }
+ }
+
+ /** Cache of instantiated providers by their config ID */
+ let cachedProviders: Record<string, LlmProvider> = {};
+
+ /**
+ * The raw llmProviders JSON the cache was built from. When the option changes
+ * (provider added/edited/removed in the settings), the cache self-invalidates
+ * so stale instances — and their dynamic model-list caches — are dropped.
+ */
+ let cachedProvidersSource: string | null = null;
+
+ /**
+ * Get configured providers from the options.
+ */
+ function getConfiguredProviders(): LlmProviderSetup[] {
+ try {
+ const providersJson = optionService.getOptionOrNull("llmProviders");
+ if (providersJson !== cachedProvidersSource) {
+ cachedProviders = {};
+ cachedProvidersSource = providersJson;
+ }
+ if (!providersJson) {
+ return [];
+ }
+ return JSON.parse(providersJson) as LlmProviderSetup[];
+ } catch (e) {
+ getLog().error(`Failed to parse llmProviders option: ${e}`);
+ return [];
+ }
+ }
+
+ /**
+ * Get a provider instance by its configuration ID.
+ * If no ID is provided, returns the first configured provider.
+ */
+ export function getProvider(providerId?: string): LlmProvider {
+ const configs = getConfiguredProviders();
+
+ if (configs.length === 0) {
+ throw new Error("No LLM providers configured. Please add a provider in Options → AI / LLM.");
+ }
+
+ // Find the requested provider or use the first one
+ const config = providerId
+ ? configs.find(c => c.id === providerId)
+ : configs[0];
+
+ if (!config) {
+ throw new Error(`LLM provider not found: ${providerId}`);
+ }
+
+ // Check cache
+ if (cachedProviders[config.id]) {
+ return cachedProviders[config.id];
+ }
+
+ // Create new provider instance
+ const provider = createProviderInstance(config.provider, config.apiKey, config.baseURL);
+ cachedProviders[config.id] = provider;
+ return provider;
+ }
+
+ /**
+ * Get the first configured provider of a specific type (e.g., "anthropic").
+ */
+ export function getProviderByType(providerType: string): LlmProvider {
+ const configs = getConfiguredProviders();
+ const config = configs.find(c => c.provider === providerType);
+
+ if (!config) {
+ throw new Error(`No ${providerType} provider configured. Please add one in Options → AI / LLM.`);
+ }
+
+ return getProvider(config.id);
+ }
+
+ /**
+ * Check if any providers are configured.
+ */
+ export function hasConfiguredProviders(): boolean {
+ return getConfiguredProviders().length > 0;
+ }
+
+ /**
+ * List the models available for a provider described by raw credentials —
+ * used by the model-selection screen during the add/edit flow, where the
+ * provider config isn't necessarily persisted yet. Instantiates the provider
+ * ad-hoc (bypassing the config cache) and queries it live — a listing failure
+ * (bad credentials, unreachable endpoint) propagates so the caller can surface
+ * it — falling back to the curated list only when the provider doesn't support
+ * dynamic listing.
+ */
+ export async function listProviderModels(provider: string, apiKey: string, baseURL?: string): Promise<ModelInfo[]> {
+ const instance = createProviderInstance(provider, apiKey, baseURL);
+ const models = await (instance.listModels?.() ?? instance.getAvailableModels());
+ // Tag the default-selected set here so the recommendation rule lives on the
+ // server — in the provider that owns its model id shape — rather than in the
+ // client picker.
+ const recommended = instance.recommendedModelIds(models);
+ return models.map(model => ({ ...model, recommended: recommended.has(model.id) }));
+ }
+
+ /**
+ * Find the model a chat is targeting within its provider config's stored
+ * selection — the denormalized source of display name and pricing for the
+ * response's usage/cost, working even for dynamically discovered models the
+ * curated list doesn't know. Returns undefined when the model isn't stored.
+ */
+ export function getSelectedModel(providerId: string | undefined, modelId: string): ModelInfo | undefined {
+ if (!providerId) {
+ return undefined;
+ }
+ const config = getConfiguredProviders().find(c => c.id === providerId);
+ return config?.selectedModels?.find(m => m.id === modelId);
+ }
+
+ /**
+ * Clear the provider cache. Call this when provider configurations change.
+ */
+ export function clearProviderCache(): void {
+ cachedProviders = {};
+ cachedProvidersSource = null;
+ }
+
+ export type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing } from "./types.js";