Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): inject current-note context hint in the Claude Agent provider

Elian Doran0a27197861b0
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
index 4a63194692..ffcf6ffeaa 100644
--- a/apps/server/src/services/llm/providers/base_provider.ts
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -7,11 +7,10 @@ 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 { dump } from "js-yaml";
-import { getNoteMeta,SYSTEM_PROMPT_LIMITS } from "../tools/helpers.js";
import { allToolRegistries } from "../tools/index.js";
import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
+import { buildNoteHint } from "./note_hint.js";
import { buildSystemPrompt as composeSystemPrompt } from "./system_prompt.js";
const DEFAULT_MAX_TOKENS = 8096;
@@ -25,31 +24,6 @@ function effectiveCost(pricing: ModelPricing): number {
return (pricing.input + 3 * pricing.output) / 4;
}
-/**
- * Build a context hint about the current note with full metadata (same as get_note / ETAPI).
- */
-function buildNoteHint(noteId: string, hasAttachments: boolean): string | null {
- const note = becca.getNote(noteId);
- if (!note) {
- return null;
- }
-
- const metadata = dump(getNoteMeta(note, SYSTEM_PROMPT_LIMITS), { lineWidth: -1 });
- const lines = [
- "The user is currently viewing the following note.",
- "Use this metadata (including contentPreview) to answer questions about the note without calling tools when possible.",
- "Use get_note_content only if the preview is insufficient."
- ];
- if (hasAttachments) {
- // When the user has attached files alongside this turn, those are
- // almost always the actual subject of the question — the note context
- // is just ambient information about where they happen to be in the app.
- lines.push("The user has attached files in this message. Treat those attachments as the primary subject of their question; refer to this note only for background context if relevant.");
- }
- lines.push("", metadata);
- return lines.join("\n");
-}
-
/**
* Resolve a single LlmMessagePart to its AI SDK ModelMessage part form.
* For image/file parts, this reads the attachment bytes out of Becca. Text
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.ts
index 2ab177127e..a521ccf6a6 100644
--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts
@@ -24,6 +24,9 @@ vi.mock("../../data_dir.js", async () => {
vi.mock("../../port.js", () => ({ default: 8080 }));
+const buildNoteHintMock = vi.hoisted(() => vi.fn((noteId: string) => `NOTE_META(${noteId})`));
+vi.mock("./note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));
+
const { buildSeededPrompt, ClaudeAgentProvider, hashTranscript } = await import("./claude_agent.js");
/** Make query() replay the given SDK messages and record its invocation. */
@@ -197,6 +200,53 @@ describe("ClaudeAgentProvider.chatChunks", () => {
expect(secondCall.prompt).toContain("follow-up");
});
+ it("prepends the current-note metadata hint to the user message when contextNoteId is set", async () => {
+ buildNoteHintMock.mockClear();
+ scriptAgent([successResult()]);
+ const provider = new ClaudeAgentProvider();
+ await collect(provider.chatChunks(
+ [{ role: "user", content: "what is this note about?" }],
+ { contextNoteId: "note-abc" }
+ ));
+
+ expect(buildNoteHintMock).toHaveBeenCalledWith("note-abc", false);
+ const prompt = queryMock.mock.calls[0][0].prompt;
+ expect(prompt).toBe("NOTE_META(note-abc)\n\nwhat is this note about?");
+ });
+
+ it("does not prepend a hint when the context note no longer exists", async () => {
+ buildNoteHintMock.mockReturnValueOnce(null);
+ scriptAgent([successResult()]);
+ const provider = new ClaudeAgentProvider();
+ await collect(provider.chatChunks(
+ [{ role: "user", content: "hello" }],
+ { contextNoteId: "gone" }
+ ));
+
+ expect(queryMock.mock.calls[0][0].prompt).toBe("hello");
+ });
+
+ it("keeps the note hint out of the session hash so a later turn still resumes", async () => {
+ const provider = new ClaudeAgentProvider();
+ const config = { contextNoteId: "note-abc", chatNoteId: "note-hint-resume" };
+
+ scriptAgent([textDelta("first reply"), successResult("sess-H")]);
+ await collect(provider.chatChunks([{ role: "user", content: "q1" }], config));
+
+ // Turn 2: transcript matches turn 1 (unhinted) → resume, and the new
+ // message still carries the freshly-built hint.
+ scriptAgent([textDelta("second reply"), successResult("sess-H")]);
+ await collect(provider.chatChunks([
+ { role: "user", content: "q1" },
+ { role: "assistant", content: "first reply" },
+ { role: "user", content: "q2" }
+ ], config));
+
+ const secondCall = queryMock.mock.calls[1][0];
+ expect(secondCall.options.resume).toBe("sess-H");
+ expect(secondCall.prompt).toBe("NOTE_META(note-abc)\n\nq2");
+ });
+
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.ts
index cf9f18ccf5..0daa76099d 100644
--- a/apps/server/src/services/llm/providers/claude_agent.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.ts
@@ -26,6 +26,7 @@ import dataDirs from "../../data_dir.js";
import port from "../../port.js";
import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
import { buildModelList } from "./base_provider.js";
+import { buildNoteHint } from "./note_hint.js";
import { buildSystemPrompt } from "./system_prompt.js";
/**
@@ -114,17 +115,25 @@ export class ClaudeAgentProvider implements LlmProvider {
}
const history = conversation.slice(0, -1);
- const lastText = flattenContent(lastMessage.content);
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)
- ? lastText
- : buildSeededPrompt(history, lastText);
+ ? currentMessage
+ : buildSeededPrompt(history, currentMessage);
const abortController = new AbortController();
const onAbort = () => abortController.abort();
@@ -314,11 +323,10 @@ export class ClaudeAgentProvider implements LlmProvider {
// The shared prompt promises note tools whenever `enableNoteTools` is
// set — but on this path they only exist if MCP is also on, so gate on
- // the effective availability. `contextNoteId` is cleared because this
- // provider does not yet inject the current-note metadata (the API
- // providers do, via applyNoteHint); leaving it set would make the
- // "you can see the current note's metadata above" notice a lie.
- const promptConfig: LlmProviderConfig = { ...config, enableNoteTools: noteToolsAvailable, contextNoteId: undefined };
+ // the effective availability. `contextNoteId` passes through: chatChunks
+ // injects the note metadata into the user turn (see buildNoteHint), so
+ // the "you can see the current note's metadata above" notice is accurate.
+ const promptConfig: LlmProviderConfig = { ...config, enableNoteTools: noteToolsAvailable };
let systemPrompt = buildSystemPrompt(messages, promptConfig) ?? "";
// Note tools were requested but unavailable — tell the model why so it
diff --git a/apps/server/src/services/llm/providers/note_hint.ts b/apps/server/src/services/llm/providers/note_hint.ts
new file mode 100644
index 0000000000..ea306f93da
--- /dev/null
+++ b/apps/server/src/services/llm/providers/note_hint.ts
@@ -0,0 +1,38 @@
+/**
+ * Builds the "current note" context hint — the metadata block describing the
+ * note the user is viewing, injected into the user turn so the model can answer
+ * questions about it without a tool call. Shared by the AI-SDK providers (via
+ * BaseProvider.applyNoteHint) and the Claude Agent provider (which prepends it
+ * to the prompt text).
+ */
+
+import { becca } from "@triliumnext/core";
+import { dump } from "js-yaml";
+
+import { getNoteMeta, SYSTEM_PROMPT_LIMITS } from "../tools/helpers.js";
+
+/**
+ * Build a context hint about the current note with full metadata (same shape as
+ * get_note / ETAPI). Returns `null` when the note no longer exists.
+ */
+export function buildNoteHint(noteId: string, hasAttachments: boolean): string | null {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return null;
+ }
+
+ const metadata = dump(getNoteMeta(note, SYSTEM_PROMPT_LIMITS), { lineWidth: -1 });
+ const lines = [
+ "The user is currently viewing the following note.",
+ "Use this metadata (including contentPreview) to answer questions about the note without calling tools when possible.",
+ "Use get_note_content only if the preview is insufficient."
+ ];
+ if (hasAttachments) {
+ // When the user has attached files alongside this turn, those are
+ // almost always the actual subject of the question — the note context
+ // is just ambient information about where they happen to be in the app.
+ lines.push("The user has attached files in this message. Treat those attachments as the primary subject of their question; refer to this note only for background context if relevant.");
+ }
+ lines.push("", metadata);
+ return lines.join("\n");
+}