Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): add a tool for partial update

Elian Doran321a7ca59508
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 7ae886d34a..6039c119f1 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2636,6 +2636,7 @@
"get_note": "Get note",
"get_note_content": "Get note content",
"update_note_content": "Update note content",
+ "edit_note_content": "Edit note content",
"append_to_note": "Append to note",
"create_note": "Create note",
"get_attributes": "Get attributes",
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
index a077fce862..9e17333233 100644
--- a/apps/server/src/services/llm/providers/base_provider.ts
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -4,8 +4,7 @@
*/
import type { LlmMessage } from "@triliumnext/commons";
-import type { LanguageModel } from "ai";
-import { generateText, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type ToolSet } from "ai";
+import { generateText, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type ToolSet } from "ai";
import yaml from "js-yaml";
import becca from "../../../becca/becca.js";
diff --git a/apps/server/src/services/llm/tools/helpers.spec.ts b/apps/server/src/services/llm/tools/helpers.spec.ts
new file mode 100644
index 0000000000..92f87e45a1
--- /dev/null
+++ b/apps/server/src/services/llm/tools/helpers.spec.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest";
+
+import { applyTextEdits } from "./helpers.js";
+
+describe("applyTextEdits", () => {
+ it("applies a single find-and-replace edit", () => {
+ const result = applyTextEdits("const x = 1;\nconst y = 2;\n", [
+ { oldText: "const x = 1;", newText: "const x = 42;" }
+ ]);
+ expect(result).toEqual({ ok: true, content: "const x = 42;\nconst y = 2;\n" });
+ });
+
+ it("applies multiple edits in order, including one that targets earlier output", () => {
+ const result = applyTextEdits("a\nb\nc\n", [
+ { oldText: "a", newText: "X" },
+ { oldText: "b", newText: "Y" },
+ // Edit 3 matches text introduced by edit 1 — edits see prior results.
+ { oldText: "X", newText: "Z" }
+ ]);
+ expect(result).toEqual({ ok: true, content: "Z\nY\nc\n" });
+ });
+
+ it("rejects an edit whose oldText is absent", () => {
+ const result = applyTextEdits("hello world", [{ oldText: "goodbye", newText: "hi" }]);
+ expect(result).toMatchObject({ ok: false, error: expect.stringContaining("not found") });
+ });
+
+ it("rejects an ambiguous oldText that matches more than once", () => {
+ const result = applyTextEdits("foo foo", [{ oldText: "foo", newText: "bar" }]);
+ expect(result).toMatchObject({ ok: false, error: expect.stringContaining("not unique") });
+ });
+
+ it("rejects empty and no-op edits", () => {
+ expect(applyTextEdits("abc", [{ oldText: "", newText: "x" }]))
+ .toMatchObject({ ok: false, error: expect.stringContaining("empty") });
+ expect(applyTextEdits("abc", [{ oldText: "abc", newText: "abc" }]))
+ .toMatchObject({ ok: false, error: expect.stringContaining("identical") });
+ });
+
+ it("is all-or-nothing: a later failing edit discards earlier ones and names the offender", () => {
+ const result = applyTextEdits("keep this", [
+ { oldText: "keep", newText: "KEEP" },
+ { oldText: "missing", newText: "x" }
+ ]);
+ // The error pinpoints the failing edit, and no content is returned to commit —
+ // so a partially-applied batch can never reach the note.
+ expect(result).toMatchObject({ ok: false, error: expect.stringContaining("edit 2 of 2") });
+ expect(result).not.toHaveProperty("content");
+ });
+});
diff --git a/apps/server/src/services/llm/tools/helpers.ts b/apps/server/src/services/llm/tools/helpers.ts
index ee348740f1..f7b1ac193d 100644
--- a/apps/server/src/services/llm/tools/helpers.ts
+++ b/apps/server/src/services/llm/tools/helpers.ts
@@ -59,6 +59,56 @@ export function setNoteContentFromLlm(note: BNote, content: string) {
}
}
+/** A single find-and-replace edit applied to note content. */
+export interface TextEdit {
+ oldText: string;
+ newText: string;
+}
+
+export type TextEditResult =
+ | { ok: true; content: string }
+ | { ok: false; error: string };
+
+/**
+ * Apply a sequence of find-and-replace edits to a string, all-or-nothing.
+ *
+ * Each edit's `oldText` must occur exactly once in the content at the moment it
+ * is applied. Edits are applied in order, so a later edit may target text that an
+ * earlier edit introduced. If any edit fails to match (or matches ambiguously),
+ * no edit is committed and an error describing the offending edit is returned.
+ */
+export function applyTextEdits(content: string, edits: TextEdit[]): TextEditResult {
+ let result = content;
+
+ for (let i = 0; i < edits.length; i++) {
+ const { oldText, newText } = edits[i];
+ const label = edits.length > 1 ? ` (edit ${i + 1} of ${edits.length})` : "";
+
+ if (oldText === "") {
+ return { ok: false, error: `oldText must not be empty${label}.` };
+ }
+ if (oldText === newText) {
+ return { ok: false, error: `oldText and newText are identical${label} — nothing to change.` };
+ }
+
+ const firstIndex = result.indexOf(oldText);
+ if (firstIndex === -1) {
+ return { ok: false, error: `oldText not found in the note content${label}.` };
+ }
+ if (result.indexOf(oldText, firstIndex + oldText.length) !== -1) {
+ return {
+ ok: false,
+ error: `oldText is not unique${label} — it matches more than once. `
+ + "Include more surrounding context so it identifies a single location."
+ };
+ }
+
+ result = result.slice(0, firstIndex) + newText + result.slice(firstIndex + oldText.length);
+ }
+
+ return { ok: true, content: result };
+}
+
/**
* Return a short plain-text content preview for a note, truncated to
* {@link CONTENT_PREVIEW_MAX_LENGTH} characters. Useful for giving an LLM a
diff --git a/apps/server/src/services/llm/tools/note_tools.ts b/apps/server/src/services/llm/tools/note_tools.ts
index 53586ef2b1..6d0430dd04 100644
--- a/apps/server/src/services/llm/tools/note_tools.ts
+++ b/apps/server/src/services/llm/tools/note_tools.ts
@@ -10,7 +10,7 @@ import noteService from "../../notes.js";
import SearchContext from "../../search/search_context.js";
import searchService from "../../search/services/search.js";
import TaskContext from "../../task_context.js";
-import { PROTECTED_SYSTEM_NOTES, TOOL_LIMITS, getContentPreview, getNoteContentForLlm, getNoteMeta, setNoteContentFromLlm } from "./helpers.js";
+import { applyTextEdits, getContentPreview, getNoteContentForLlm, getNoteMeta, PROTECTED_SYSTEM_NOTES, setNoteContentFromLlm,TOOL_LIMITS } from "./helpers.js";
import { defineTools } from "./tool_registry.js";
export const noteTools = defineTools({
@@ -98,7 +98,7 @@ export const noteTools = defineTools({
},
update_note_content: {
- description: "Replace the entire content of a note. Use this to completely rewrite a note's content. For text notes, provide Markdown content.",
+ description: "Replace the ENTIRE content of a note. Only use this for a full rewrite or for rich-text ('text') notes. For small or localized changes to a non-text note, prefer edit_note_content — resending the whole note wastes tokens. For text notes, provide Markdown content.",
inputSchema: z.object({
noteId: z.string().describe("The ID of the note to update"),
content: z.string().describe("The new content for the note (Markdown for text notes, plain text for code notes)")
@@ -168,6 +168,63 @@ export const noteTools = defineTools({
}
},
+ edit_note_content: {
+ description: [
+ "Make targeted edits to a note by replacing exact text snippets, without",
+ "resending the whole note. Prefer this over update_note_content for small",
+ "changes to large notes — it is far cheaper. Each edit's oldText must appear",
+ "exactly once in the note; include surrounding context to make it unique.",
+ "Multiple edits are applied in order. Does not support rich-text ('text')",
+ "notes — use update_note_content for those."
+ ].join(" "),
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the note to edit"),
+ edits: z
+ .array(
+ z.object({
+ oldText: z.string().describe("The exact text to find and replace. Must be unique within the note."),
+ newText: z.string().describe("The replacement text.")
+ })
+ )
+ .min(1)
+ .describe("One or more find-and-replace edits, applied in order.")
+ }),
+ mutates: true,
+ execute: ({ noteId, edits }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
+ if (!note.isContentAvailable()) {
+ return { error: "Note is protected and cannot be modified" };
+ }
+ if (!note.hasStringContent()) {
+ return { error: `Cannot edit content for note type: ${note.type}` };
+ }
+ if (note.type === "text") {
+ return { error: "edit_note_content does not support rich-text notes. Use update_note_content instead." };
+ }
+
+ const existingContent = note.getContent();
+ if (typeof existingContent !== "string") {
+ return { error: "Note has binary content" };
+ }
+
+ const result = applyTextEdits(existingContent, edits);
+ if (!result.ok) {
+ return { error: result.error };
+ }
+
+ note.saveRevision({ source: "llm" });
+ note.setContent(result.content);
+ return {
+ success: true,
+ noteId: note.noteId,
+ title: note.getTitleOrProtected()
+ };
+ }
+ },
+
create_note: {
description: [
"Create a new note in the user's knowledge base. Returns the created note's ID and title.",