Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(llm): send images and PDFs to the Claude Agent provider
Elian Doranbfe071d27868
diff --git a/apps/server/src/services/llm/providers/attachment_content.ts b/apps/server/src/services/llm/providers/attachment_content.tsnew file mode 100644index 0000000000..568d26d384--- /dev/null+++ b/apps/server/src/services/llm/providers/attachment_content.ts@@ -0,0 +1,73 @@+/**+ * Provider-neutral resolution of multimodal message parts.+ *+ * Both the AI-SDK providers ({@link ../base_provider}) and the Claude Agent+ * provider need the same thing from an attachment part: load the bytes out of+ * Becca and apply the conventions that don't depend on the provider — an SVG is+ * rendered as its XML source (no vision model accepts SVG, but all can read the+ * markup), and a text attachment is inlined as a labelled `<file>` block. Each+ * path then maps the neutral result into its own SDK's block shape.+ */++import type { LlmMessagePart } from "@triliumnext/commons";+import { becca, getLog } from "@triliumnext/core";+import { decodeUtf8 } from "@triliumnext/core/src/services/utils/binary.js";++export type ResolvedAttachment =+ | { kind: "text"; text: string }+ | { kind: "image"; bytes: Uint8Array; mime: string }+ | { kind: "file"; bytes: Uint8Array; mime: string; filename: string };++/**+ * Resolve a single {@link LlmMessagePart} to its provider-neutral form. Returns+ * `null` when the part can't be resolved (missing, protected without an+ * unlocked session, or a corrupt/undecodable blob) — the caller drops it and+ * the rest of the message still reaches the model.+ */+export function resolveAttachmentPart(part: LlmMessagePart): ResolvedAttachment | null {+ if (part.type === "text") {+ return { kind: "text", text: part.text };+ }+ try {+ const attachment = becca.getAttachment(part.attachmentId);+ if (!attachment) {+ getLog().error(`LLM message references missing attachment ${part.attachmentId}`);+ return null;+ }+ if (!attachment.isContentAvailable()) {+ getLog().error(`LLM message references protected attachment ${part.attachmentId} without an unlocked session`);+ return null;+ }+ // Read attachment bytes once — `getContent()` hits the blob store and+ // (for protected attachments) decrypts, so callers shouldn't repeat it.+ const content = attachment.getContent();+ if (part.type === "image") {+ const mime = part.mime || attachment.mime;+ if (mime === "image/svg+xml") {+ const filename = attachment.title || "image.svg";+ return { kind: "text", text: wrapFile(filename, decodeUtf8(content)) };+ }+ return { kind: "image", bytes: content, mime };+ }+ if (part.type === "file") {+ return {+ kind: "file",+ bytes: content,+ mime: part.mime || attachment.mime,+ filename: part.filename || attachment.title+ };+ }+ // type === "text_attachment" — decode the bytes and wrap in a labelled+ // block so the filename gives the model context about what it's reading.+ return { kind: "text", text: wrapFile(part.filename || attachment.title, decodeUtf8(content)) };+ } catch (err) {+ // A single unreadable attachment shouldn't crash the whole chat turn —+ // drop the part and log so the rest of the message still gets through.+ getLog().error(`Failed to resolve message part for attachment ${part.attachmentId}: ${err}`);+ return null;+ }+}++function wrapFile(filename: string, text: string): string {+ return `<file name="${filename}">\n${text}\n</file>`;+}diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.tsindex ffcf6ffeaa..536c412759 100644--- a/apps/server/src/services/llm/providers/base_provider.ts+++ b/apps/server/src/services/llm/providers/base_provider.ts@@ -4,12 +4,11 @@*/import { type LlmMessage, type LlmMessagePart } from "@triliumnext/commons";-import { becca, getLog } from "@triliumnext/core";-import { decodeUtf8 } from "@triliumnext/core/src/services/utils/binary.js";import { type FilePart, generateText, type ImagePart, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type TextPart, type ToolSet } from "ai";import { allToolRegistries } from "../tools/index.js";import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";+import { resolveAttachmentPart } from "./attachment_content.js";import { buildNoteHint } from "./note_hint.js";import { buildSystemPrompt as composeSystemPrompt } from "./system_prompt.js";@@ -25,73 +24,23 @@ function effectiveCost(pricing: ModelPricing): number {}/**- * Resolve a single LlmMessagePart to its AI SDK ModelMessage part form.- * For image/file parts, this reads the attachment bytes out of Becca. Text- * attachments are decoded as UTF-8 and emitted as a labelled TextPart so the- * file's content travels inline (works across all providers). Failures are- * logged and the part is dropped so the rest of the message still goes through.+ * Resolve a single LlmMessagePart to its AI SDK ModelMessage part form, mapping+ * the provider-neutral {@link resolveAttachmentPart} result into `ai`'s block+ * shapes. Returns null (and the caller drops the part) when it can't resolve.*/function resolveMessagePart(part: LlmMessagePart): TextPart | ImagePart | FilePart | null {- if (part.type === "text") {- return { type: "text", text: part.text };- }- try {- const attachment = becca.getAttachment(part.attachmentId);- if (!attachment) {- getLog().error(`LLM message references missing attachment ${part.attachmentId}`);- return null;- }- if (!attachment.isContentAvailable()) {- getLog().error(`LLM message references protected attachment ${part.attachmentId} without an unlocked session`);- return null;- }- // Read attachment bytes once — `getContent()` hits the blob store and- // (for protected attachments) decrypts, so callers shouldn't repeat it.- const content = attachment.getContent();- if (part.type === "image") {- const mime = part.mime || attachment.mime;- // SVG isn't accepted by any major provider's vision input, but every- // LLM is fluent in SVG markup — send the XML source as a text part so- // the model can actually read and reason about it.- if (mime === "image/svg+xml") {- const filename = attachment.title || "image.svg";- const text = decodeUtf8(content);- return {- type: "text",- text: `<file name="${filename}">\n${text}\n</file>`- };- }- return {- type: "image",- image: content,- mediaType: mime- };- }- if (part.type === "file") {- return {- type: "file",- data: content,- mediaType: part.mime || attachment.mime,- filename: part.filename || attachment.title- };- }- // type === "text_attachment" — decode the bytes and wrap in a labelled- // XML-style block. Anthropic recommends this shape and other providers- // handle it fine; the filename gives the model context about what it's- // reading without needing provider-specific file APIs.- const filename = part.filename || attachment.title;- const text = decodeUtf8(content);- return {- type: "text",- text: `<file name="${filename}">\n${text}\n</file>`- };- } catch (err) {- // A single unreadable attachment (corrupt blob, decryption failure,- // invalid UTF-8) shouldn't crash the whole chat turn — drop the part- // and log so the rest of the message still reaches the model.- getLog().error(`Failed to resolve message part for attachment ${part.attachmentId}: ${err}`);+ const resolved = resolveAttachmentPart(part);+ if (!resolved) {return null;}+ switch (resolved.kind) {+ case "text":+ return { type: "text", text: resolved.text };+ case "image":+ return { type: "image", image: resolved.bytes, mediaType: resolved.mime };+ case "file":+ return { type: "file", data: resolved.bytes, mediaType: resolved.mime, filename: resolved.filename };+ }}/**diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex a521ccf6a6..3b20b00830 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -27,8 +27,27 @@ vi.mock("../../port.js", () => ({ default: 8080 }));const buildNoteHintMock = vi.hoisted(() => vi.fn((noteId: string) => `NOTE_META(${noteId})`));vi.mock("./note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));+// Attachment resolution reads bytes out of Becca, which the core mock above+// omits — stub it so the multimodal tests drive block construction directly.+const resolveAttachmentPartMock = vi.hoisted(() => vi.fn());+vi.mock("./attachment_content.js", () => ({ resolveAttachmentPart: resolveAttachmentPartMock }));+const { buildSeededPrompt, ClaudeAgentProvider, hashTranscript } = await import("./claude_agent.js");+/** Drain the query prompt into the single user message it streams (multimodal path). */+async function drainPrompt(prompt: unknown): Promise<{ role: string; content: unknown[] }> {+ const iterator = (prompt as AsyncIterable<unknown>)?.[Symbol.asyncIterator];+ if (typeof prompt === "string" || typeof iterator !== "function") {+ throw new Error("expected a streamed multimodal prompt, got a plain string");+ }+ const messages: { message: { role: string; content: unknown[] } }[] = [];+ for await (const message of prompt as AsyncIterable<{ message: { role: string; content: unknown[] } }>) {+ messages.push(message);+ }+ expect(messages).toHaveLength(1);+ return messages[0].message;+}+/** Make query() replay the given SDK messages and record its invocation. */function scriptAgent(messages: unknown[]) {queryMock.mockImplementation(() => (async function* () {@@ -72,6 +91,7 @@ describe("ClaudeAgentProvider.chatChunks", () => {queryMock.mockReset();getOptionOrNullMock.mockReset();getOptionOrNullMock.mockReturnValue("true"); // mcpEnabled+ resolveAttachmentPartMock.mockReset();});it("maps stream events, tool calls, results, and usage to chunks in order", async () => {@@ -247,6 +267,57 @@ describe("ClaudeAgentProvider.chatChunks", () => {expect(secondCall.prompt).toBe("NOTE_META(note-abc)\n\nq2");});+ it("sends a supported image as a base64 block via a one-message stream", async () => {+ resolveAttachmentPartMock.mockReturnValue({ kind: "image", bytes: new Uint8Array([1, 2, 3]), mime: "image/png" });+ scriptAgent([textDelta("I see it"), successResult()]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([+ { role: "user", content: [+ { type: "text", text: "what is this?" },+ { type: "image", attachmentId: "att-1", mime: "image/png" }+ ] }+ ], {}));++ const message = await drainPrompt(queryMock.mock.calls[0][0].prompt);+ expect(message.role).toBe("user");+ expect(message.content).toEqual([+ { type: "text", text: "what is this?" },+ { type: "image", source: { type: "base64", media_type: "image/png", data: "AQID" } }+ ]);+ });++ it("sends a PDF as a document block and leads with the note hint", async () => {+ resolveAttachmentPartMock.mockReturnValue({ kind: "file", bytes: new Uint8Array([37, 80, 68, 70]), mime: "application/pdf", filename: "report.pdf" });+ scriptAgent([textDelta("summary"), successResult()]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([+ { role: "user", content: [{ type: "file", attachmentId: "att-2", mime: "application/pdf", filename: "report.pdf" }] }+ ], { contextNoteId: "note-abc" }));++ const message = await drainPrompt(queryMock.mock.calls[0][0].prompt);+ expect(message.content).toEqual([+ { type: "text", text: "NOTE_META(note-abc)" },+ { type: "document", title: "report.pdf", source: { type: "base64", media_type: "application/pdf", data: "JVBERg==" } }+ ]);+ });++ it("degrades unsupported attachments to text and keeps the plain string prompt", async () => {+ // An SVG resolves to inlined text; the string path (not the stream) is used.+ resolveAttachmentPartMock.mockReturnValue({ kind: "text", text: "<file name=\"d.svg\">\n<svg/>\n</file>" });+ scriptAgent([textDelta("ok"), successResult()]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([+ { role: "user", content: [+ { type: "text", text: "read this" },+ { type: "image", attachmentId: "att-3", mime: "image/svg+xml" }+ ] }+ ], {}));++ const prompt = queryMock.mock.calls[0][0].prompt;+ expect(typeof prompt).toBe("string");+ expect(prompt).toBe("read this\n\n<file name=\"d.svg\">\n<svg/>\n</file>");+ });+it("points the agent at Trilium's MCP server and disables built-in tools", async () => {scriptAgent([successResult()]);const provider = new ClaudeAgentProvider();diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex 04b9bb985a..78fd579cae 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -15,9 +15,11 @@* with every built-in Claude Code tool (file access, bash, …) disabled.*/-import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDKMessage } from "@anthropic-ai/claude-agent-sdk";-import type { LlmMessage, LlmMessagePart, LlmStreamChunk } from "@triliumnext/commons";+import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDKMessage, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";+import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";+import type { LlmFilePart, LlmImagePart, LlmMessage, LlmMessagePart, LlmStreamChunk, LlmTextAttachmentPart } from "@triliumnext/commons";import { getLog, options as optionService } from "@triliumnext/core";+import { encodeBase64 } from "@triliumnext/core/src/services/utils/binary.js";import { createHash } from "crypto";import fs from "fs";import path from "path";@@ -25,10 +27,15 @@ import path from "path";import dataDirs from "../../data_dir.js";import port from "../../port.js";import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";+import { resolveAttachmentPart } from "./attachment_content.js";import { buildModelList } from "./base_provider.js";import { buildNoteHint } from "./note_hint.js";import { buildSystemPrompt } from "./system_prompt.js";+/** Image media types Anthropic accepts as a base64 image block. */+type SupportedImageMime = "image/png" | "image/jpeg" | "image/gif" | "image/webp";+const SUPPORTED_IMAGE_MIMES = new Set<string>(["image/png", "image/jpeg", "image/gif", "image/webp"]);+/*** Models offered under a Claude subscription. Pricing is zero because usage is* covered by the subscription — the per-turn `usage` chunk still reports the@@ -127,23 +134,30 @@ export class ClaudeAgentProvider implements LlmProvider {const history = conversation.slice(0, -1);const historyHash = hashTranscript(history);- // Prepend the current-note metadata hint to *this* user message (not the- // stored transcript), mirroring the AI-SDK providers' applyNoteHint. It's- // volatile context — kept out of the hash so a later turn's unhinted- // transcript still matches and can resume.- const hasAttachments = Array.isArray(lastMessage.content) && lastMessage.content.some(p => p.type !== "text");- const noteHint = config.contextNoteId ? buildNoteHint(config.contextNoteId, hasAttachments) : null;- const lastText = flattenContent(lastMessage.content);- const currentMessage = noteHint ? `${noteHint}\n\n${lastText}` : lastText;-// Resume the existing agent session only when the transcript the client// sent still matches what that session last saw; any divergence (edited// history, lost mapping, server restart) reseeds a fresh session.const stored = config.chatNoteId ? sessionsByChatNote.get(config.chatNoteId) : undefined;const resume = stored && stored.transcriptHash === historyHash ? stored.sessionId : undefined;- const prompt = (resume || history.length === 0)- ? currentMessage- : buildSeededPrompt(history, currentMessage);++ // Text that precedes *this* user turn's own content: the replayed+ // transcript when reseeding a lost/diverged session, then the volatile+ // current-note metadata hint. The hint mirrors the AI-SDK providers'+ // applyNoteHint and is kept out of the session hash so a later turn's+ // unhinted transcript still matches and can 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 = [+ (!resume && history.length > 0) ? buildHistoryReplay(history) : null,+ noteHint+ ].filter((s): s is string => Boolean(s)).join("\n\n");++ // Attachments the model can consume natively (images, PDFs) are sent as+ // real content blocks via a one-message stream — the only prompt form+ // the Agent SDK accepts them in. Text-only turns (including messages+ // whose attachments all degrade to text, e.g. SVG or text files) stay on+ // the simpler string-prompt path.+ const prompt = buildPrompt(lastMessage.content, prefix, hasAttachments);const abortController = new AbortController();const onAbort = () => abortController.abort();@@ -423,23 +437,91 @@ function getAgentCwd(): string {return agentCwd;}-/** Flatten possibly-multimodal message content to plain text. */+/**+ * Build the prompt for the current user turn. When the turn carries attachments+ * the model can consume natively, this returns a one-message stream of Anthropic+ * content blocks (the SDK's only multimodal input form); otherwise it returns a+ * plain string. `prefix` (reseed transcript + note hint) always leads.+ */+function buildPrompt(content: string | LlmMessagePart[], prefix: string, hasAttachments: boolean): string | AsyncIterable<SDKUserMessage> {+ if (hasAttachments && Array.isArray(content)) {+ const blocks = buildContentBlocks(content, prefix);+ if (blocks.some(b => b.type === "image" || b.type === "document")) {+ return streamSingleUserMessage(blocks);+ }+ // Nothing the model can take natively — collapse back to text so the+ // turn stays on the well-worn string path (and out of streaming-input+ // mode). Text blocks still carry inlined SVG/text-file content.+ return blocks.map(b => (b.type === "text" ? b.text : "")).filter(Boolean).join("\n\n");+ }+ const lastText = flattenContent(content);+ return prefix ? `${prefix}\n\n${lastText}` : lastText;+}++/**+ * Map the current user turn to Anthropic content blocks: real image/document+ * blocks for natively-supported attachments, text for everything else (plain+ * text parts, inlined SVG/text files, and placeholders for anything unresolved+ * or of a type no block accepts). `prefix` leads as a text block when non-empty.+ */+function buildContentBlocks(content: LlmMessagePart[], prefix: string): ContentBlockParam[] {+ const blocks: ContentBlockParam[] = [];+ 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 || resolved.kind === "text") {+ // Unresolved (missing/protected/corrupt) or a type that degrades to+ // text (SVG source, inlined text file) — a placeholder keeps the+ // turn self-describing even when the bytes can't be sent.+ blocks.push({ type: "text", text: resolved?.kind === "text" ? resolved.text : attachmentPlaceholder(part) });+ } else if (resolved.kind === "image" && SUPPORTED_IMAGE_MIMES.has(resolved.mime)) {+ blocks.push({+ type: "image",+ source: { type: "base64", media_type: resolved.mime as SupportedImageMime, data: encodeBase64(resolved.bytes) }+ });+ } else if (resolved.kind === "file" && resolved.mime === "application/pdf") {+ blocks.push({+ type: "document",+ title: resolved.filename,+ source: { type: "base64", media_type: "application/pdf", data: encodeBase64(resolved.bytes) }+ });+ } else {+ // Resolvable bytes but a type no Anthropic block accepts (e.g. a+ // TIFF image or a .docx) — degrade to a text placeholder.+ blocks.push({ type: "text", text: attachmentPlaceholder(part) });+ }+ }+ return blocks;+}++/** One-shot streaming-input prompt: a single user message, then end of input. */+async function* streamSingleUserMessage(content: ContentBlockParam[]): AsyncIterable<SDKUserMessage> {+ yield { type: "user", message: { role: "user", content }, parent_tool_use_id: null };+}++/** Flatten possibly-multimodal message content to plain text (attachments as placeholders). */function flattenContent(content: string | LlmMessagePart[]): string {if (typeof content === "string") {return content;}return content- .map(part => {- if (part.type === "text") {- return part.text;- }- // Attachment parts are resolved server-side for API providers; the- // agent path is text-only for now.- return `[attached ${part.type === "image" ? "image" : "file"}${"filename" in part ? `: ${part.filename}` : ""}]`;- })+ .map(part => (part.type === "text" ? part.text : attachmentPlaceholder(part))).join("\n");}+/** Short "[attached …]" stand-in used wherever an attachment's bytes aren't sent. */+function attachmentPlaceholder(part: LlmImagePart | LlmFilePart | LlmTextAttachmentPart): string {+ const kind = part.type === "image" ? "image" : "file";+ const name = "filename" in part ? `: ${part.filename}` : "";+ return `[attached ${kind}${name}]`;+}+/*** Stable hash of a transcript (roles + text only). Used to detect whether the* history the client sent still matches what the mapped agent session saw.@@ -455,10 +537,15 @@ export function hashTranscript(messages: LlmMessage[]): string {* diverged (edited history, server restart).*/export function buildSeededPrompt(history: LlmMessage[], lastText: string): string {+ return `${buildHistoryReplay(history)}\n\n${lastText}`;+}++/** The `<conversation_history>` replay block, without any trailing user message. */+function buildHistoryReplay(history: LlmMessage[]): string {const transcript = history.map(m => `${m.role === "user" ? "User" : "Assistant"}: ${flattenContent(m.content)}`).join("\n\n");- return `<conversation_history>\nThis is the prior conversation between the user and you. Continue it naturally; do not mention this replay.\n\n${transcript}\n</conversation_history>\n\n${lastText}`;+ return `<conversation_history>\nThis is the prior conversation between the user and you. Continue it naturally; do not mention this replay.\n\n${transcript}\n</conversation_history>`;}/** Strip the MCP prefix so the client shows "search_notes", not "mcp__trilium__search_notes". */