Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): basic tool to get subtree

Elian Doranc617bea45afd
diff --git a/apps/server/src/services/llm/tools/hierarchy_tools.ts b/apps/server/src/services/llm/tools/hierarchy_tools.ts
index 8da42900b9..9bfe60afe2 100644
--- a/apps/server/src/services/llm/tools/hierarchy_tools.ts
+++ b/apps/server/src/services/llm/tools/hierarchy_tools.ts
@@ -6,6 +6,7 @@ import { tool } from "ai";
import { z } from "zod";
import becca from "../../../becca/becca.js";
+import type BNote from "../../../becca/entities/bnote.js";
/**
* Get the child notes of a given note.
@@ -30,6 +31,72 @@ export const getChildNotes = tool({
}
});
+//#region Subtree tool implementation
+const MAX_DEPTH = 5;
+const MAX_CHILDREN_PER_LEVEL = 10;
+
+interface SubtreeNode {
+ noteId: string;
+ title: string;
+ type: string;
+ children?: SubtreeNode[] | string;
+}
+
+function buildSubtree(note: BNote, depth: number, maxDepth: number): SubtreeNode {
+ const node: SubtreeNode = {
+ noteId: note.noteId,
+ title: note.getTitleOrProtected(),
+ type: note.type
+ };
+
+ if (depth >= maxDepth) {
+ const childCount = note.getChildNotes().length;
+ if (childCount > 0) {
+ node.children = `${childCount} children not shown (depth limit reached)`;
+ }
+ return node;
+ }
+
+ const children = note.getChildNotes();
+ if (children.length === 0) {
+ return node;
+ }
+
+ const shown = children.slice(0, MAX_CHILDREN_PER_LEVEL);
+ node.children = shown.map((child) => buildSubtree(child, depth + 1, maxDepth));
+
+ if (children.length > MAX_CHILDREN_PER_LEVEL) {
+ node.children.push({
+ noteId: "",
+ title: `... and ${children.length - MAX_CHILDREN_PER_LEVEL} more`,
+ type: "truncated"
+ });
+ }
+
+ return node;
+}
+
+/**
+ * Get a subtree of notes up to a specified depth.
+ */
+export const getSubtree = tool({
+ description: "Get a nested subtree of notes starting from a given note, traversing multiple levels deep. Useful for understanding the structure of a section of the note tree. Each level shows up to 10 children.",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the root note for the subtree (use 'root' for the entire tree)"),
+ depth: z.number().min(1).max(MAX_DEPTH).optional().describe(`How many levels deep to traverse (1-${MAX_DEPTH}). Defaults to 2.`)
+ }),
+ execute: async ({ noteId, depth = 2 }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
+
+ return buildSubtree(note, 0, depth);
+ }
+});
+//#endregion
+
export const hierarchyTools = {
- get_child_notes: getChildNotes
+ get_child_notes: getChildNotes,
+ get_subtree: getSubtree
};