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
/**
* Shared helpers for LLM tools — content conversion, metadata building, and previews.
*/
import type BAttachment from "../../../becca/entities/battachment.js";
import type BAttribute from "../../../becca/entities/battribute.js";
import becca from "../../../becca/becca.js";
import type BNote from "../../../becca/entities/bnote.js";
import blobService from "../../../services/blob.js";
import markdownExport from "../../../services/export/markdown.js";
import markdownImport from "../../../services/import/markdown.js";
import { unwrapStringOrBuffer } from "../../../services/utils/binary.js";
const CONTENT_PREVIEW_MAX_LENGTH = 500;
const ATTACHMENT_PREVIEW_MAX_LENGTH = 200;
/** Skip expensive content loading/conversion for notes larger than this. */
const CONTENT_PREVIEW_SIZE_THRESHOLD = 10_000;
/**
* Note types the LLM can create or change a note to; each one stores string content. An `image` must
* be an SVG ({@link getSvgImageError}).
*/
export const LLM_NOTE_TYPES = [
"text", "code", "render", "book", "mermaid", "canvas", "webView", "relationMap", "search", "mindMap", "image"
] as const;
export const SVG_MIME = "image/svg+xml";
/** An optional XML prolog, doctype and comments, then an `<svg>` root element through to `</svg>`. */
const SVG_SOURCE_RE = /^\s*(?:<\?xml[\s\S]*?\?>\s*)?(?:(?:<!--(?:(?!-->)[\s\S])*-->|<!DOCTYPE[^>]*>)\s*)*<svg[\s>/][\s\S]*<\/svg>\s*$/i;
/** Note IDs that must not be deleted, moved, or cloned by the LLM. */
export const PROTECTED_SYSTEM_NOTES = new Set(["root", "_hidden", "_share", "_lbRoot", "_globalNoteMap"]);
/** Label that hides a note from the LLM tools, and its subtree too when the label is inheritable. */
export const EXCLUDE_FROM_LLM_LABEL = "excludeFromLlm";
/** Whether the LLM must not see a note: it owns or inherits a truthy {@link EXCLUDE_FROM_LLM_LABEL}. */
export function isExcludedFromLlm(note: BNote) {
return note.isLabelTruthy(EXCLUDE_FROM_LLM_LABEL);
}
/** Returns the note, or `null` when it is missing or excluded, so the LLM cannot tell the two apart. */
export function getLlmNote(noteId: string): BNote | null {
const note = becca.getNote(noteId);
return note && !isExcludedFromLlm(note) ? note : null;
}
/** Returns the note's children that the LLM can see. */
export function getLlmChildNotes(note: BNote) {
return note.getChildNotes().filter((child) => !isExcludedFromLlm(child));
}
/** Returns the note's parents that the LLM can see. */
export function getLlmParentNotes(note: BNote) {
return note.getParentNotes().filter((parent) => !isExcludedFromLlm(parent));
}
/** Whether the LLM can see an attribute: its owner and, for a relation, its target are not excluded. */
export function isAttributeVisibleToLlm(attribute: BAttribute) {
const owner = becca.getNote(attribute.noteId);
if (!owner || isExcludedFromLlm(owner)) {
return false;
}
const target = attribute.type === "relation" ? becca.getNote(attribute.value) : null;
return !target || !isExcludedFromLlm(target);
}
/** Returns the attachment, or `null` when it is missing or its owning note (or the revision's note) is excluded. */
export function getLlmAttachment(attachmentId: string): BAttachment | null {
const attachment = becca.getAttachment(attachmentId);
if (!attachment) {
return null;
}
const owner = becca.getNote(attachment.ownerId) ?? becca.getRevision(attachment.ownerId)?.getNote();
return owner && !isExcludedFromLlm(owner) ? attachment : null;
}
/**
* Return `true` if the value is truthy, otherwise `undefined`.
* Since `undefined` values are omitted from JSON serialization,
* this effectively includes the field only when true.
* Usage: `{ isInheritable: flag(attr.isInheritable) }`
*/
export function flag(value: boolean | undefined): true | undefined {
return value ? true : undefined;
}
/**
* Convert note content to a format suitable for LLM consumption.
* Text notes are converted from HTML to Markdown to reduce token usage.
*/
export function getNoteContentForLlm(note: BNote) {
if (note.type === "doc") {
// Doc notes hold no content of their own: the client renders an explanatory page picked
// by their `docName` label, out of its own translation catalog.
return "[doc content not available]";
}
const content = note.getContent();
if (typeof content !== "string") {
// For binary content (images, files), use extracted text if available.
const blob = note.blobId ? becca.getBlob({ blobId: note.blobId }) : null;
const extractedText = blobService.decryptTextRepresentation(blob?.textRepresentation, !!note.isProtected);
if (extractedText) {
return `[extracted text from ${note.type}]\n${extractedText}`;
}
return "[binary content]";
}
if (note.type === "text") {
return markdownExport.toMarkdown(content);
}
return content;
}
/**
* Convert LLM-provided content to a format suitable for storage.
* For text notes, converts Markdown to HTML.
*/
export function setNoteContentFromLlm(note: BNote, content: string) {
if (note.type === "text") {
note.setContent(markdownImport.renderToHtml(content, note.title));
} else {
note.setContent(content);
}
}
/**
* Why the LLM cannot write `content` into an image note of `mime`, or `undefined` if it can. The LLM
* writes only SVG images, and a truncated reply must not leave a broken image behind.
*/
export function getSvgImageError(mime: string, content: string): string | undefined {
if (mime !== SVG_MIME) {
return `Only SVG images are supported; use mime '${SVG_MIME}'`;
}
if (!SVG_SOURCE_RE.test(content)) {
return "Image content must be complete SVG source: an <svg> root element and its closing </svg>";
}
return undefined;
}
/** 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
* glimpse of the content without sending the full body.
*
* For large notes (>{@link CONTENT_PREVIEW_SIZE_THRESHOLD} bytes), returns a
* size hint instead of loading and converting the full content.
*/
export function getContentPreview(note: BNote): string | null {
if (!note.isContentAvailable()) {
return null;
}
// Check content size before loading to avoid expensive conversion for large notes
const blob = note.blobId ? becca.getBlob({ blobId: note.blobId }) : null;
if (blob && blob.contentLength > CONTENT_PREVIEW_SIZE_THRESHOLD) {
const sizeKb = Math.round(blob.contentLength / 1024);
return `[${sizeKb}KB - use get_note_content for full text]`;
}
const full = getNoteContentForLlm(note);
if (!full || full === "[binary content]" || full === "[doc content not available]") {
return null;
}
if (full.length <= CONTENT_PREVIEW_MAX_LENGTH) {
return full;
}
return `${full.slice(0, CONTENT_PREVIEW_MAX_LENGTH)}…`;
}
/**
* Return a short content preview for an attachment, or null if no readable
* content is available. For text attachments the raw content is used; for
* binary attachments (PDF, images) the OCR/extracted text is used when present.
*/
export function getAttachmentContentPreview(att: BAttachment): string | null {
let text: string | null = null;
if (att.hasStringContent()) {
const content = att.getContent();
text = unwrapStringOrBuffer(content);
} else {
const blob = att.blobId ? becca.getBlob({ blobId: att.blobId }) : null;
text = blobService.decryptTextRepresentation(blob?.textRepresentation, !!att.isProtected) || null;
}
if (!text) {
return null;
}
if (text.length <= ATTACHMENT_PREVIEW_MAX_LENGTH) {
return text;
}
return `${text.slice(0, ATTACHMENT_PREVIEW_MAX_LENGTH)}…`;
}
/** Limits for collections returned in system prompt context. */
export const SYSTEM_PROMPT_LIMITS = {
childNotes: 20,
attributes: 20,
attachments: 20
} as const;
/** Limits for collections returned by the get_note tool. */
export const TOOL_LIMITS = {
childNotes: 50,
attributes: 50,
attachments: 50
} as const;
interface NoteMetaLimits {
childNotes: number;
attributes: number;
attachments: number;
}
/**
* Truncate an array and return it with total count metadata.
* If the array exceeds `limit`, only the first `limit` items are returned.
*/
function truncated<T>(items: T[], limit: number) {
return {
totalCount: items.length,
results: items.slice(0, limit)
};
}
/**
* Build the full metadata object for a note. Used by both the `get_note` tool
* and the system prompt.
*
* @param limits — controls how many child notes, attributes, and attachments
* are included. Use {@link SYSTEM_PROMPT_LIMITS} for the system prompt and
* {@link TOOL_LIMITS} for the `get_note` tool.
*/
export function getNoteMeta(note: BNote, limits: NoteMetaLimits) {
const allChildNotes = getLlmChildNotes(note).map((ch) => ({
noteId: ch.noteId,
title: ch.getTitleOrProtected()
}));
const allAttributes = note.getAttributes().filter(isAttributeVisibleToLlm).map((attr) => ({
attributeId: attr.attributeId,
type: attr.type,
name: attr.name,
value: attr.value,
isInheritable: flag(attr.isInheritable)
}));
const allAttachments = note.getAttachments().map((att) => ({
attachmentId: att.attachmentId,
role: att.role,
mime: att.mime,
title: att.title,
contentLength: att.contentLength,
contentPreview: getAttachmentContentPreview(att)
}));
return {
noteId: note.noteId,
isProtected: flag(note.isProtected),
title: note.getTitleOrProtected(),
type: note.type,
mime: note.mime,
dateCreated: note.dateCreated,
dateModified: note.dateModified,
parentNoteIds: getLlmParentNotes(note).map((p) => p.noteId),
childNotes: truncated(allChildNotes, limits.childNotes),
attributes: truncated(allAttributes, limits.attributes),
contentPreview: getContentPreview(note),
attachments: truncated(allAttachments, limits.attachments)
};
}