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): give the scripting skills every API signature
Elian Doran3363b6c23cb3
diff --git a/apps/edit-docs/src/docs_pipeline.ts b/apps/edit-docs/src/docs_pipeline.tsindex ab5c4e5c46..42b7965265 100644--- a/apps/edit-docs/src/docs_pipeline.ts+++ b/apps/edit-docs/src/docs_pipeline.ts@@ -19,7 +19,7 @@ import { deferred } from "../../../packages/commons/src/index.js";import { buildHelpBundle } from "./help_bundle_generator.js";import { buildHelpMeta, serializeHelpMeta, stripAppVersion } from "./help_meta_generator.js";import { openApiToMarkdown, type OpenApiSpec } from "./openapi_markdown.js";-import { runTypeDoc, type TypeDocMarkdownOptions, typeDocToMarkdown } from "./typedoc_markdown.js";+import { runTypeDoc, typeDocToDeclarations, type TypeDocMarkdownOptions, typeDocToMarkdown } from "./typedoc_markdown.js";export interface NoteMapping {rootNoteId: string;@@ -54,6 +54,11 @@ export interface TypeDocPage extends TypeDocMarkdownOptions {entryPoint: string;/** The tsconfig that compiles it. Relative to the configuration file. */tsconfig: string;+ /**+ * Where to also write the declarations as compact TypeScript, for the LLM skill sheets that+ * `load_skill` serves. Relative to the configuration file.+ */+ skillReference?: string;}export interface Config {@@ -88,7 +93,8 @@ export async function loadConfig(configPath?: string): Promise<Config> {typeDocPages: mapping.typeDocPages?.map((page) => ({...page,entryPoint: path.resolve(configDir, page.entryPoint),- tsconfig: path.resolve(configDir, page.tsconfig)+ tsconfig: path.resolve(configDir, page.tsconfig),+ skillReference: page.skillReference ? path.resolve(configDir, page.skillReference) : undefined}))}))};@@ -179,7 +185,10 @@ export async function exportMappings(mappings: NoteMapping[], baseUrl: string) {}}-/** Regenerates the Markdown of the mapping's `openApiPages` and `typeDocPages` from their sources. */+/**+ * Regenerates the Markdown of the mapping's `openApiPages` and `typeDocPages` from their sources,+ * and the skill references of the `typeDocPages` that name one.+ */async function writeGeneratedPages(mapping: NoteMapping) {const pages = [...(mapping.openApiPages ?? []).map((page) => ({@@ -188,7 +197,13 @@ async function writeGeneratedPages(mapping: NoteMapping) {})),...(mapping.typeDocPages ?? []).map((page) => ({noteId: page.noteId,- render: async () => typeDocToMarkdown(await runTypeDoc(page.entryPoint, page.tsconfig), page)+ render: async () => {+ const project = await runTypeDoc(page.entryPoint, page.tsconfig);+ if (page.skillReference) {+ await writeArtifact(page.skillReference, renderSkillReference(project, page));+ }+ return typeDocToMarkdown(project, page);+ }}))];if (!pages.length) {@@ -207,6 +222,16 @@ async function writeGeneratedPages(mapping: NoteMapping) {}}+/** The skill reference of a TypeDoc page: its declarations under a heading `readSkill()` appends. */+function renderSkillReference(project: Awaited<ReturnType<typeof runTypeDoc>>, page: TypeDocPage) {+ return [+ `<!-- Generated from ${path.basename(page.entryPoint)} by \`pnpm edit-docs:sync-docs\`. Do not edit. -->`,+ "## API reference",+ "Every member of `api` and of the objects it returns, as TypeScript declarations, each under the first sentence of its description.",+ `\`\`\`ts\n${typeDocToDeclarations(project, page)}\n\`\`\``+ ].join("\n\n") + "\n";+}+/*** Converts generated Markdown to the form `MarkdownExportProvider` writes, so an import that no* export follows leaves the page unchanged on disk.diff --git a/apps/edit-docs/src/typedoc_markdown.spec.ts b/apps/edit-docs/src/typedoc_markdown.spec.tsindex ed7281b9d4..d40e621fad 100644--- a/apps/edit-docs/src/typedoc_markdown.spec.ts+++ b/apps/edit-docs/src/typedoc_markdown.spec.ts@@ -3,7 +3,7 @@ import { tmpdir } from "os";import { join } from "path";import { afterAll, beforeAll, describe, expect, it } from "vitest";-import { runTypeDoc, typeDocToMarkdown } from "./typedoc_markdown.js";+import { runTypeDoc, typeDocToDeclarations, typeDocToMarkdown } from "./typedoc_markdown.js";const FIXTURE = `/**@@ -73,6 +73,9 @@ export interface DemoWindowApi {/** @deprecated Use {@link resize}. */maximize(): void;+ /** Reloads the window, e.g. after an update. Unsaved changes are lost. */+ reload(): void;+/** Reads a stored value. */read<T extends string | number = string, K = string>(key: K): T | null;@@ -93,6 +96,24 @@ export interface DemoApi {}`;+/** A second root, whose interface extends one of `FIXTURE`'s. */+const DOCKING = `+/** A window that can also be docked. */+export interface DockableWindowApi extends DemoWindowApi {+ /** Docks the window. */+ dock(): void;+}++export interface DockApi {+ window: DemoWindowApi;+ docked: DockableWindowApi;+}++export interface DockOnlyApi {+ docked: DockableWindowApi;+}+`;+const IMPORTED = `/** Who a window serves. */export type Audience = "user" | "guest";@@ -284,3 +305,73 @@ describe("typeDocToMarkdown", () => {.toThrow("DemoApi and DemoWindowApi would both be named Api");});});++describe("typeDocToDeclarations", () => {+ let dir: string;+ let project: Awaited<ReturnType<typeof runTypeDoc>>;+ let declarations: string;++ beforeAll(async () => {+ dir = await mkdtemp(join(tmpdir(), "typedoc-declarations-"));+ await writeFile(join(dir, "api.ts"), FIXTURE + DOCKING);+ await writeFile(join(dir, "audience.ts"), IMPORTED);+ await writeFile(join(dir, "tsconfig.json"), JSON.stringify({+ compilerOptions: { strict: true, target: "ES2022", module: "ESNext", moduleResolution: "bundler" },+ files: [ "api.ts", "audience.ts" ]+ }));+ project = await runTypeDoc(join(dir, "api.ts"), join(dir, "tsconfig.json"));+ declarations = typeDocToDeclarations(project, { root: "DemoApi", stripPrefixes: [ "Demo" ] });+ }, 60_000);++ afterAll(async () => {+ await rm(dir, { recursive: true, force: true });+ });++ it("writes the root and what it reaches as TypeScript, each member under its first sentence", () => {+ expect(declarations.startsWith([+ "/** The root of the API. */",+ "interface Api {",+ " /** Window controls, as `WindowApi` lists them. */",+ " window: WindowApi;",+ " /** The version, as in `1.2.3`. */",+ " readonly version: string;",+ "}"+ ].join("\n"))).toBe(true);+ expect(declarations).toContain([+ " /** Resizes the window. */",+ " resize(options: ResizeOptions): Promise<boolean>;"+ ].join("\n"));+ expect(declarations).toContain(" read<T extends string | number = string, K = string>(key: K): T | null;");+ expect(declarations).toContain(" /** Reloads the window, e.g. after an update. */\n reload(): void;");+ expect(declarations).toContain(" animate?: boolean;");+ expect(declarations).toContain("/** A size in pixels. */\ntype Size = number | \"auto\";");+ expect(declarations).not.toContain("Unreached");+ });++ it("writes out a union of literals that one member uses, and links nothing", () => {+ expect(declarations).toContain(" screen: \"primary\" | \"secondary\";");+ expect(declarations).toContain(" audience: Audience;");+ expect(declarations).not.toContain("](#");+ });++ it("leaves out deprecated members", () => {+ expect(declarations).not.toContain("maximize");+ });++ it("declares an inherited member only on the interface it comes from, when that one is written too", () => {+ const docking = typeDocToDeclarations(project, { root: "DockApi" });+ expect(docking).toContain([+ "/** A window that can also be docked. */",+ "interface DockableWindowApi extends DemoWindowApi {",+ " /** Docks the window. */",+ " dock(): void;",+ "}"+ ].join("\n"));+ expect(docking.match(/ resize\(/g)).toHaveLength(1);++ // The selection does not follow `extends`, so without its parent the interface keeps them.+ const dockOnly = typeDocToDeclarations(project, { root: "DockOnlyApi" });+ expect(dockOnly).not.toContain("interface DemoWindowApi");+ expect(dockOnly.match(/ resize\(/g)).toHaveLength(1);+ });+});diff --git a/apps/edit-docs/src/typedoc_markdown.ts b/apps/edit-docs/src/typedoc_markdown.tsindex 0c9a104fa4..4c4f4f3aed 100644--- a/apps/edit-docs/src/typedoc_markdown.ts+++ b/apps/edit-docs/src/typedoc_markdown.ts@@ -64,21 +64,13 @@ export async function runTypeDoc(entryPoint: string, tsconfig: string): Promise<* they use follow under "Types". A union of literals that one place uses is written out there* instead of getting an entry. A reference to a declaration the page shows links to its heading.*/-export function typeDocToMarkdown(project: Project, { root, stripPrefixes = [] }: TypeDocMarkdownOptions = {}): string {- const { declarations, inlined } = selectDeclarations(project, root);- inlinedAliases = inlined;- displayNames = stripNames(declarations.map((declaration) => declaration.name), stripPrefixes);- shownNames = new Set(declarations.map((declaration) => declaration.name));- try {+export function typeDocToMarkdown(project: Project, options: TypeDocMarkdownOptions = {}): string {+ return renderSelection(project, options, true, ({ apis, types }) => {const blocks: string[] = [];if (project.comment) {blocks.push(renderComment(project.comment));}- const isApi = (declaration: Declaration) => declaration.name === root- || !!declaration.children?.some((member) => member.kind === KIND.method);- const apis = declarations.filter(isApi);- const types = declarations.filter((declaration) => !isApi(declaration));for (const declaration of apis) {blocks.push(...renderDeclaration(declaration, "##"));}@@ -91,11 +83,20 @@ export function typeDocToMarkdown(project: Project, { root, stripPrefixes = [] }}return blocks.filter(Boolean).join("\n\n");- } finally {- inlinedAliases = new Map();- displayNames = new Map();- shownNames = new Set();- }+ });+}++/**+ * Renders the declarations `typeDocToMarkdown()` shows as compact TypeScript: every member on one+ * line, under the first sentence of its description, for an LLM to read where the page would cost+ * too many tokens. Deprecated declarations and members are left out.+ */+export function typeDocToDeclarations(project: Project, options: TypeDocMarkdownOptions = {}): string {+ return renderSelection(project, options, false, ({ apis, types }) => {+ const declarations = [ ...apis, ...types ].filter((declaration) => !isDeprecated(declaration.comment));+ const names = new Set(declarations.map((declaration) => declaration.name));+ return declarations.map((declaration) => declarationToString(declaration, names)).join("\n\n");+ });}export interface TypeDocMarkdownOptions {@@ -132,6 +133,35 @@ let markingLinks = false;const LINK_START = "\u0002";const LINK_END = "\u0003";+/**+ * Selects what a page shows and sets the naming state `typeToString()` reads while `render` runs.+ * `root` and the interfaces with methods are the APIs; the rest are the types they use. Only a+ * `linked` rendering marks the names it can link to a heading.+ */+function renderSelection(+ project: Project,+ { root, stripPrefixes = [] }: TypeDocMarkdownOptions,+ linked: boolean,+ render: (selection: { apis: Declaration[]; types: Declaration[] }) => string+) {+ const { declarations, inlined } = selectDeclarations(project, root);+ inlinedAliases = inlined;+ displayNames = stripNames(declarations.map((declaration) => declaration.name), stripPrefixes);+ shownNames = linked ? new Set(declarations.map((declaration) => declaration.name)) : new Set();+ try {+ const isApi = (declaration: Declaration) => declaration.name === root+ || !!declaration.children?.some((member) => member.kind === KIND.method);+ return render({+ apis: declarations.filter(isApi),+ types: declarations.filter((declaration) => !isApi(declaration))+ });+ } finally {+ inlinedAliases = new Map();+ displayNames = new Map();+ shownNames = new Set();+ }+}+/*** Maps each name that starts with one of `prefixes`, before an uppercase letter, to the name* without it, trying the longest prefix first. Throws when two names would end up the same.@@ -304,6 +334,72 @@ function renderDeclaration(declaration: Declaration, heading: string) {return blocks;}+/**+ * A declaration as TypeScript, under the first sentence of its description. A member inherited+ * from one of `written`, the declarations written alongside, is left to that declaration.+ */+function declarationToString(declaration: Declaration, written: Set<string>) {+ const name = `${displayName(declaration.name)}${typeParametersToString(declaration.typeParameters)}`;+ const comment = summaryComment(declaration.comment, "");+ if (declaration.kind === KIND.typeAlias) {+ return `${comment}type ${name} = ${typeToString(declaration.type)};`;+ }++ const extended = declaration.extendedTypes?.length+ ? ` extends ${declaration.extendedTypes.map(typeToString).join(", ")}`+ : "";+ const members = (declaration.children ?? [])+ .filter((member) => !written.has(member.inheritedFrom?.name.split(".")[0] ?? ""))+ .flatMap(memberToLines);+ return members.length+ ? `${comment}interface ${name}${extended} {\n${members.join("\n")}\n}`+ : `${comment}interface ${name}${extended} {}`;+}++/** A member's lines in an interface: the first sentence of its description, then one line per signature. */+function memberToLines(member: Declaration): string[] {+ const indent = " ";+ const optional = member.flags.isOptional ? "?" : "";+ let comment: Comment | undefined;+ let lines: string[];+ if (member.kind === KIND.method) {+ const signatures = member.signatures ?? [];+ comment = (signatures.find((candidate) => candidate.comment) ?? signatures[0])?.comment;+ lines = signatures.map((signature) =>+ `${indent}${member.name}${optional}${parametersToString(signature)}: ${typeToString(signature.type)};`);+ } else if (member.kind === KIND.property || member.kind === KIND.accessor) {+ const isAccessor = member.kind === KIND.accessor;+ comment = member.comment ?? member.getSignature?.comment;+ const readonly = member.flags.isReadonly || (isAccessor && !member.setSignature) ? "readonly " : "";+ const type = isAccessor ? member.getSignature?.type : member.type;+ lines = [ `${indent}${readonly}${member.name}${optional}: ${typeToString(type)};` ];+ } else {+ return [];+ }++ if (isDeprecated(comment)) {+ return [];+ }+ const summary = summaryComment(comment, indent);+ return summary ? [ summary.trimEnd(), ...lines ] : lines;+}++/** The first sentence of a comment's summary as a `/** … *\/` line, or nothing without one. */+function summaryComment(comment: Comment | undefined, indent: string) {+ const summary = comment ? oneLine(partsToMarkdown(comment.summary)) : "";+ if (!summary) {+ return "";+ }++ // A sentence ends at a stop followed by a capital, which keeps "e.g. `x`" in one piece.+ const sentence = /^.*?[.!?](?=\s+[A-Z]|$)/.exec(summary)?.[0] ?? summary;+ return `${indent}/** ${sentence.replaceAll("*/", "*\\/")} */\n`;+}++function isDeprecated(comment: Comment | undefined) {+ return !!comment?.blockTags?.some((tag) => tag.tag === "@deprecated");+}+function propertyDetails(property: Declaration) {const type = typeMarkdown(property.type ?? property.getSignature?.type);return details(type, [ property.comment, ...inlinedComments(property) ]);diff --git a/apps/standalone/src/lightweight/llm_skills.ts b/apps/standalone/src/lightweight/llm_skills.tsindex f9af0db073..0c1c6c619e 100644--- a/apps/standalone/src/lightweight/llm_skills.ts+++ b/apps/standalone/src/lightweight/llm_skills.ts@@ -1,6 +1,8 @@import backendScripting from "@triliumnext/core/src/assets/llm/skills/backend_scripting.md?raw";+import backendScriptingApi from "@triliumnext/core/src/assets/llm/skills/backend_scripting_api.md?raw";import dashboards from "@triliumnext/core/src/assets/llm/skills/dashboards.md?raw";import frontendScripting from "@triliumnext/core/src/assets/llm/skills/frontend_scripting.md?raw";+import frontendScriptingApi from "@triliumnext/core/src/assets/llm/skills/frontend_scripting_api.md?raw";import searchSyntax from "@triliumnext/core/src/assets/llm/skills/search_syntax.md?raw";import { registerSkillReader } from "@triliumnext/core/src/services/llm/skills.js";@@ -11,14 +13,16 @@ import { registerSkillReader } from "@triliumnext/core/src/services/llm/skills.j* moment to fetch them either — a tool's `execute` is synchronous by contract,* so the sheets have to already be in memory when the model asks. `?raw` settles* that at build time, the same way this build already takes core's schema.sql,- * and costs ~44 KB of markdown in an app that ships a SQLite engine.+ * and costs ~130 KB of markdown in an app that ships a SQLite engine.** Keyed by file name, which is what core's catalog asks a reader for.*/const SKILL_SHEETS: Record<string, string> = {"search_syntax.md": searchSyntax,"backend_scripting.md": backendScripting,+ "backend_scripting_api.md": backendScriptingApi,"frontend_scripting.md": frontendScripting,+ "frontend_scripting_api.md": frontendScriptingApi,"dashboards.md": dashboards};diff --git a/docs/Developer Guide/Developer Guide/Documentation.md b/docs/Developer Guide/Developer Guide/Documentation.mdindex 05a117436d..945b21568a 100644--- a/docs/Developer Guide/Developer Guide/Documentation.md+++ b/docs/Developer Guide/Developer Guide/Documentation.md@@ -73,7 +73,7 @@ The `deploy-docs` workflow triggers the documentation build and uploads it to ClThe REST API references (ETAPI and the internal API), the Electron API reference and the frontend and backend script API references are User Guide pages whose Markdown is generated from their sources, so they appear both in the in-app help and on the website. `edit-docs-config.yaml` lists them for each documentation tree:* `openApiPages` renders an OpenAPI document (`apps/server/src/assets/etapi.openapi.yaml`, `apps/server/internal.openapi.yaml`), through `apps/edit-docs/src/openapi_markdown.ts`.-* `typeDocPages` renders the exports of a TypeScript module, as TypeDoc reads them, through `apps/edit-docs/src/typedoc_markdown.ts`. The Electron API page documents `packages/commons/src/lib/electron_api_interface.ts`, starting from `ElectronApi`; its introduction is the module's `@packageDocumentation` comment. The Frontend API and Backend API pages document `packages/commons/src/lib/script_api.ts`, the curated types that script notes' autocomplete also uses, starting from `FrontendApi` and `BackendApi`. A page with a `root` shows only what the root reaches, so one module can hold the types of several pages. `stripPrefixes` leaves a naming prefix out of the names the page shows, so `ScriptBNote` reads `BNote` and `ElectronWindowApi` reads `WindowApi`; references, signatures and code spans that name a type follow, and two types that would end up with one name stop the sync.+* `typeDocPages` renders the exports of a TypeScript module, as TypeDoc reads them, through `apps/edit-docs/src/typedoc_markdown.ts`. The Electron API page documents `packages/commons/src/lib/electron_api_interface.ts`, starting from `ElectronApi`; its introduction is the module's `@packageDocumentation` comment. The Frontend API and Backend API pages document `packages/commons/src/lib/script_api.ts`, the curated types that script notes' autocomplete also uses, starting from `FrontendApi` and `BackendApi`. A page with a `root` shows only what the root reaches, so one module can hold the types of several pages. `stripPrefixes` leaves a naming prefix out of the names the page shows, so `ScriptBNote` reads `BNote` and `ElectronWindowApi` reads `WindowApi`; references, signatures and code spans that name a type follow, and two types that would end up with one name stop the sync. A page with a `skillReference` also writes what it shows as compact TypeScript (every member on one line, under the first sentence of its description, deprecated members left out) to that file. The Frontend API and Backend API pages write `frontend_scripting_api.md` and `backend_scripting_api.md` under `packages/trilium-core/src/assets/llm/skills/`, which `load_skill` appends to the hand-written scripting sheets so the AI has every member's exact signature. A spec in `skills.spec.ts` fails when a reference lists other members than `script_api.ts` declares.Both `pnpm edit-docs:sync-docs` and `pnpm edit-docs:edit-docs` regenerate these pages before importing the documentation, so any edit made to them directly is overwritten. To change one, edit its source (the OpenAPI document, or the comments of the TypeScript module), then run `pnpm edit-docs:sync-docs` and commit the regenerated page along with the help files.diff --git a/edit-docs-config.yaml b/edit-docs-config.yamlindex 7c0e5c4439..a78cf1d832 100644--- a/edit-docs-config.yaml+++ b/edit-docs-config.yaml@@ -25,11 +25,13 @@ noteMappings:tsconfig: "packages/commons/tsconfig.lib.json"root: "BackendApi"stripPrefixes: [ "Script" ]+ skillReference: "packages/trilium-core/src/assets/llm/skills/backend_scripting_api.md"- noteId: "Q2z6av6JZVWm" # Scripting › Script API › Frontend APIentryPoint: "packages/commons/src/lib/script_api.ts"tsconfig: "packages/commons/tsconfig.lib.json"root: "FrontendApi"stripPrefixes: [ "Script" ]+ skillReference: "packages/trilium-core/src/assets/llm/skills/frontend_scripting_api.md"- rootNoteId: "jdjRLhLV3TtI"path: "docs/Developer Guide"diff --git a/packages/trilium-core/src/assets/llm/skills/backend_scripting.md b/packages/trilium-core/src/assets/llm/skills/backend_scripting.mdindex fe29e61e7b..73c37b3978 100644--- a/packages/trilium-core/src/assets/llm/skills/backend_scripting.md+++ b/packages/trilium-core/src/assets/llm/skills/backend_scripting.md@@ -31,6 +31,8 @@ Note that most `api.*` methods (e.g. `api.getNote`, `api.searchForNotes`, `api.c## Script API (`api` global)+The API reference at the end of this sheet lists every member of `api` and of the objects it returns (`BNote`, `BBranch`, `BAttachment`, `api.sql`), with exact signatures. The sections below cover what a signature cannot say.+### Script context- `api.startNote` - note where the script execution started (the entry point of the script bundle; in C terms, the file with `main()`). All module notes loaded via `require()` share the same `startNote`. May be null when the execution came from the frontend via `runOnBackend()` (the frontend's `startNote` is preserved). `api.log()` messages are grouped under this note.- `api.currentNote` - note containing the source code currently executing (in C terms, `__FILE__`). Equal to `startNote` except inside child module notes loaded via `require()`. NOT the note open in the UI.@@ -48,43 +50,8 @@ Concrete examples:Note: `#customResourceProvider` notes never execute a script — the note's content is served directly as the HTTP response, so there is no `api` context at all. Only `#customRequestHandler` runs code.-### Note retrieval-- `api.getNote(noteId)` - get note by ID-- `api.searchForNotes(query, searchParams)` - search notes (returns array)-- `api.searchForNote(query)` - search notes (returns first match)-- `api.getNotesWithLabel(name, value?)` - find notes by label-- `api.getNoteWithLabel(name, value?)` - find first note by label-- `api.getBranch(branchId)` - get branch by ID-- `api.getAttribute(attributeId)` - get attribute by ID--### Note creation-- `api.createTextNote(parentNoteId, title, content)` - create text note-- `api.createDataNote(parentNoteId, title, content)` - create JSON note-- `api.createNewNote({ parentNoteId, title, content, type })` - create note with full options--### Branch management-- `api.ensureNoteIsPresentInParent(noteId, parentNoteId, prefix?)` - create or reuse branch-- `api.ensureNoteIsAbsentFromParent(noteId, parentNoteId)` - remove branch if exists-- `api.toggleNoteInParent(present, noteId, parentNoteId, prefix?)` - toggle branch--### Calendar/date notes-- `api.getTodayNote()` - get/create today's day note-- `api.getDayNote(date)` - get/create day note (YYYY-MM-DD)-- `api.getWeekNote(date)` - get/create week note-- `api.getMonthNote(date)` - get/create month note (YYYY-MM)-- `api.getYearNote(year)` - get/create year note (YYYY)--### Utilities-- `api.log(message)` - log to Trilium logs and UI-- `api.randomString(length)` - generate random string-- `api.escapeHtml(string)` / `api.unescapeHtml(string)`-- `api.getInstanceName()` - get instance name-- `api.getAppInfo()` - get application info--### Libraries-- `api.dayjs` - date manipulation-- `api.xml2js` - XML parser-- `api.htmlParser` - HTML parser (node-html-parser), use `api.htmlParser.parse(html)` to parse+### Note content+Text notes store **HTML**, not Markdown: pass HTML to `api.createTextNote()` and `note.setContent()`, or convert with `api.markdownToHtml()`. `note.setContent()` saves immediately; there is no need to call `note.save()` afterwards.### HTTP RequestsUse the native `fetch()` API for HTTP requests. Since `fetch()` is async and top-level `await` is not allowed (see "Async code" above), wrap it in an async IIFE:@@ -98,56 +65,6 @@ Use the native `fetch()` API for HTTP requests. Since `fetch()` is async and topNote: `api.axios` was removed in March 2026 following an npm supply chain attack. Use `fetch()` instead.-### Advanced-- `api.transactional(func)` - wrap code in a database transaction-- `api.sql` - direct SQL access-- `api.sortNotes(parentNoteId, sortConfig)` - sort child notes-- `api.runOnFrontend(script, params)` - execute code on all connected frontends-- `api.backupNow(backupName)` - create a backup-- `api.exportSubtreeToZipFile(noteId, format, zipFilePath)` - export subtree (format: "markdown" or "html")-- `api.duplicateSubtree(origNoteId, newParentNoteId)` - clone note and children--## BNote object--Available on notes returned from API methods (`api.getNote()`, `api.originEntity`, etc.).--### Content-- `note.getContent()` / `note.setContent(content)`-- `note.getJsonContent()` / `note.setJsonContent(obj)`-- `note.getJsonContentSafely()` - returns null on parse error--### Properties-- `note.noteId`, `note.title`, `note.type`, `note.mime`-- `note.dateCreated`, `note.dateModified`-- `note.isProtected`, `note.isArchived`--### Hierarchy-- `note.getParentNotes()` / `note.getChildNotes()`-- `note.getParentBranches()` / `note.getChildBranches()`-- `note.hasChildren()`, `note.getAncestors()`-- `note.getSubtreeNoteIds()` - all descendant IDs-- `note.hasAncestor(ancestorNoteId)`--### Attributes (including inherited)-- `note.getLabels(name?)` / `note.getLabelValue(name)`-- `note.getRelations(name?)` / `note.getRelation(name)`-- `note.hasLabel(name, value?)` / `note.hasRelation(name, value?)`--### Attribute modification-- `note.setLabel(name, value?)` / `note.removeLabel(name, value?)`-- `note.setRelation(name, targetNoteId)` / `note.removeRelation(name, value?)`-- `note.addLabel(name, value?, isInheritable?)` / `note.addRelation(name, targetNoteId, isInheritable?)`-- `note.toggleLabel(enabled, name, value?)`--### Operations-- `note.save()` - persist changes-- `note.deleteNote()` - soft delete-- `note.cloneTo(parentNoteId)` - clone to another parent--### Type checks-- `note.isJson()`, `note.isJavaScript()`, `note.isHtml()`, `note.isImage()`-- `note.hasStringContent()` - true if not binary-## Events and triggers### Global events (via `#run` label on the script note)@@ -223,7 +140,7 @@ let summary = "## Open Tasks\n";for (const task of tasks) {summary += `- ${task.title}\n`;}-api.createTextNote(today.noteId, "Daily Summary", summary);+api.createTextNote(today.noteId, "Daily Summary", api.markdownToHtml(summary));```## Module systemdiff --git a/packages/trilium-core/src/assets/llm/skills/backend_scripting_api.md b/packages/trilium-core/src/assets/llm/skills/backend_scripting_api.mdnew file mode 100644index 0000000000..a3225dda9f--- /dev/null+++ b/packages/trilium-core/src/assets/llm/skills/backend_scripting_api.md@@ -0,0 +1,743 @@+<!-- Generated from script_api.ts by `pnpm edit-docs:sync-docs`. Do not edit. -->++## API reference++Every member of `api` and of the objects it returns, as TypeScript declarations, each under the first sentence of its description.++```ts+/** The `api` global available inside **backend** script notes (`application/javascript;env=backend`). */+interface BackendApi {+ /** Note where the script execution started — the entry point of the current script bundle (in C terms, the file containing `main()`). */+ startNote?: BNote | null;+ /** Note containing the source code that is currently executing (in C terms, `__FILE__`). */+ currentNote: BNote;+ /** Entity whose event triggered this execution; `undefined` when the run was not event-driven (e.g. started manually via "Execute script" or `note.executeScript()`). */+ originEntity?: Attribute | BBranch | BNote | null;+ /** The HTTP request, present only when the script runs as a custom request handler: a note with the `#customRequestHandler` label, invoked through a `/custom/...` URL. */+ req: Request;+ /** The HTTP response to write the reply to, such as `api.res.status(200).json({ ok: true })`. */+ res: Response;+ /** The capture groups from the `#customRequestHandler` regex that matched this request's URL, in order. */+ pathParams: string[];+ /** day.js library for date manipulation. */+ dayjs: Dayjs;+ /** The xml2js library, which converts between XML and JavaScript objects. */+ xml2js: Xml2js;+ /** The node-html-parser library, which parses HTML into elements that can be queried. */+ htmlParser: HtmlParser;+ /** Instance name identifies particular Trilium instance. */+ getInstanceName(): string | null;+ /** Returns a note by its ID, or null. */+ getNote(noteId: string): BNote | null;+ /** Returns a branch by its ID, or null. */+ getBranch(branchId: string): BBranch | null;+ /** Returns an attribute by its ID, or null. */+ getAttribute(attributeId: string): Attribute | null;+ /** Returns an attachment by its ID, or null. */+ getAttachment(attachmentId: string): BAttachment | null;+ /** Returns a revision by its ID, or null. */+ getRevision(revisionId: string): BRevision | null;+ /** Returns an ETAPI token by its ID, or null. */+ getEtapiToken(etapiTokenId: string): BEtapiToken | null;+ /** Returns all ETAPI tokens. */+ getEtapiTokens(): BEtapiToken[];+ /** Returns an option by name, or null. */+ getOption(optionName: string): BOption | null;+ /** Returns all options. */+ getOptions(): BOption[];+ /** This is a powerful search method - you can search by attributes and their values, e.g.: "#dateModified =* MONTH AND #log". */+ searchForNotes(query: string, searchParams?: SearchParams): BNote[];+ /** This is a powerful search method - you can search by attributes and their values, e.g.: "#dateModified =* MONTH AND #log". */+ searchForNote(query: string, searchParams?: SearchParams): BNote | null;+ /** Retrieves notes with given label name & value */+ getNotesWithLabel(name: string, value?: string): BNote[];+ /** Retrieves first note with given label name & value */+ getNoteWithLabel(name: string, value?: string): BNote | null;+ /** If there's no branch between note and parent note, create one. */+ ensureNoteIsPresentInParent(noteId: string, parentNoteId: string, prefix?: string): { branch: BBranch | null };+ /** If there's a branch between note and parent note, remove it. */+ ensureNoteIsAbsentFromParent(noteId: string, parentNoteId: string): void;+ /** Based on the value, either create or remove branch between note and parent note. */+ toggleNoteInParent(present: boolean, noteId: string, parentNoteId: string, prefix?: string): void;+ /** Create text note. */+ createTextNote(parentNoteId: string, title: string, content: string): NoteAndBranch;+ /** Create data note - data in this context means object serializable to JSON. */+ createDataNote(parentNoteId: string, title: string, content: object): NoteAndBranch;+ createNewNote(params: { parentNoteId: string; title: string; content: string | Uint8Array<ArrayBufferLike>; type: string; mime?: string; [key: string]: unknown }): NoteAndBranch;+ /** Per-note log message buffers shown in the UI log pane. */+ logMessages: Record<string, string[]>;+ /** Per-note spaced-update handlers for the log pane. */+ logSpacedUpdates: Record<string, unknown>;+ /** Log given message to trilium logs and log pane in UI. */+ log(...args: unknown[]): void;+ /** Returns root note of the calendar. */+ getRootCalendarNote(): BNote | null;+ /** Returns day note for given date. */+ getDayNote(date: string, rootNote?: BNote): BNote | null;+ /** Returns today's day note. */+ getTodayNote(rootNote?: BNote): BNote | null;+ /** Returns note for the first date of the week of the given date. */+ getWeekFirstDayNote(date: string, rootNote?: BNote): BNote | null;+ /** Returns week note for given date. */+ getWeekNote(date: string, rootNote?: BNote): BNote | null;+ /** Returns month note for given date. */+ getMonthNote(date: string, rootNote?: BNote): BNote | null;+ /** Returns quarter note for given date. */+ getQuarterNote(date: string, rootNote?: BNote): BNote | null;+ /** Returns year note for given year. */+ getYearNote(year: string, rootNote?: BNote): BNote | null;+ /** Sort child notes of a given note. `sortBy` takes the `#sorted` grammar — comma-separated levels of `title`, `dateCreated`, `dateModified` or a label name, each optionally followed by `asc` or `desc` (`priority desc, dueDate`); `reverse` is the direction of the levels without their own, of the folders grouping and of ties. */+ sortNotes(parentNoteId: string, sortConfig: { sortBy?: string; reverse?: boolean; foldersFirst?: boolean }): void;+ /** This functions wraps code which is supposed to be running in transaction. */+ transactional<T>(func: () => T): T;+ /** Return randomly generated string of given length. */+ randomString(length: number): string;+ escapeHtml(str: string): string;+ unescapeHtml(str: string): string;+ /** Converts the given HTML string to Markdown. */+ htmlToMarkdown(html: string): string;+ /** Converts the given Markdown string to HTML. */+ markdownToHtml(markdown: string): string;+ /** Direct access to Trilium's SQLite database. */+ sql: Sql;+ /** Application info (version, build date, etc.). */+ getAppInfo(): AppInfo;+ /** Creates a new launcher to the launchbar. */+ createOrUpdateLauncher(opts: { id: string; type: "note" | "script" | "customWidget"; title: string; isVisible: boolean; icon: string; keyboardShortcut: string; targetNoteId?: string; scriptNoteId?: string; widgetNoteId?: string }): { note: BNote };+ exportSubtreeToZipFile(noteId: string, format: "markdown" | "html", zipFilePath: string): Promise<void>;+ /** Executes given anonymous function on the frontend(s). */+ runOnFrontend(script: string | (() => void), params?: unknown[]): void;+ /** Sync process can make data intermittently inconsistent. */+ runOutsideOfSync(callback: () => void): Promise<void>;+ backupNow(backupName: string): Promise<string>;+ /** Enables the complete duplication of the specified original note and all its children into the specified parent note. */+ duplicateSubtree(origNoteId: string, newParentNoteId: string): NoteAndBranch;+}++/** A note as seen by backend scripts (subset of trilium-core's `BNote`). */+interface BNote {+ /** The ID of the note. */+ noteId: string;+ /** The title of the note. */+ title: string;+ /** The note type, such as `text`, `code`, `file`, `image`, `search` or `book`. */+ type: string;+ /** The MIME type of the note's content, such as `text/html` for a text note or `application/javascript;env=backend` for a backend script. */+ mime: string;+ /** Whether the note is protected. */+ isProtected: boolean;+ /** Whether the note is archived: it has an `archived` label of its own or inherits one. */+ isArchived: boolean;+ /** Whether the note has been deleted, or its deletion is in progress. */+ isDeleted: boolean;+ /** Share root ID this note is published under, if any. */+ shareId: string;+ /** The ID of the blob that stores the note's content. */+ blobId: string;+ /** The date and time the note was created, in local time with its UTC offset, for example `2026-10-22 14:03:05.123+0200`. */+ dateCreated: string;+ /** The date and time the note was last modified, in local time with its UTC offset, for example `2026-10-22 14:03:05.123+0200`. */+ dateModified: string;+ /** The date and time the note was created, in UTC, for example `2026-10-22 12:03:05.123Z`. */+ utcDateCreated: string;+ /** The date and time the note was last modified, in UTC, for example `2026-10-22 12:03:05.123Z`. */+ utcDateModified: string;+ /** Returns the content of the note: a string for text-based notes (see `hasStringContent()`), a `Uint8Array` for binary ones such as images and files. */+ getContent(): string | Uint8Array<ArrayBufferLike>;+ /** Replaces the content of the note and saves it immediately; there is no need to call `save()` afterwards. */+ setContent(content: string | Uint8Array<ArrayBufferLike>, opts?: { forceFrontendReload?: boolean }): void;+ /** Returns the note's content parsed as JSON. */+ getJsonContent<T = unknown>(): T | null;+ /** Returns the note's content parsed as JSON, like `getJsonContent()`, but returns `null` instead of throwing an error when the content is not valid JSON. */+ getJsonContentSafely(): unknown;+ /** Serializes `content` to JSON, indented with tabs, and saves it as the note's content through `setContent()`, with the same errors. */+ setJsonContent(content: unknown): void;+ /** Returns whether `getContent()` returns a string rather than a `Uint8Array`. */+ hasStringContent(): boolean;+ /** Returns a file name for the note, as used when it is downloaded or exported: the title with characters invalid in file names removed (`untitled` when the title is empty), plus an extension. */+ getFileName(): string;+ /** Returns a single line of text that Trilium searches when matching notes: the note ID, type, MIME type, branch prefixes, title and attributes (as `#name=value` and `~name=value`, inherited ones included), lowercased and with diacritics removed. */+ getFlatText(): string;+ /** Plain serialisable representation of the note (the real return type is `NotePojo`). */+ getPojo(): Record<string, unknown>;+ /** Returns the note's title, or the literal string `[protected]` when the note is protected and no protected session is active. */+ getTitleOrProtected(): string;+ /** Returns the CSS classes of the note's icon, for example `tn-icon bx bx-note`. */+ getIcon(): string;+ /** The parent notes of this note: one per place the note appears in the tree, so a cloned note has several. */+ parents: BNote[];+ /** The child notes of this note, in their order in the tree. */+ children: BNote[];+ /** The branches that place this note under each of its parents, in the same order as `parents`. */+ parentBranches: BBranch[];+ /** The number of parent notes, which is greater than 1 for a cloned note. */+ parentCount: number;+ /** The number of child notes, including hidden and system notes. */+ childrenCount: number;+ /** Returns the parent notes of this note, one per place the note appears in the tree. */+ getParentNotes(): BNote[];+ /** Returns the child notes of this note, in their order in the tree. */+ getChildNotes(): BNote[];+ /** Returns the child notes that are shown in a shared note's navigation tree, in tree order. */+ getVisibleChildNotes(): BNote[];+ /** Returns the branches that place this note under each of its parents. */+ getParentBranches(): BBranch[];+ /** Returns the branches that connect this note to each of its children, in their order in the tree. */+ getChildBranches(): BBranch[];+ /** Returns the child branches whose notes are shown in a shared note's navigation tree, in tree order. */+ getVisibleChildBranches(): BBranch[];+ /** Returns the parent branches the user created, leaving out the automatic placements under the shared notes (`_share`) and the bookmarks (`_lbBookmarks`). */+ getStrongParentBranches(): BBranch[];+ /** Returns the same branches as `getChildBranches()`. */+ getFilteredChildBranches(): BBranch[];+ /** Returns whether the note has at least one child note, including hidden and system notes. */+ hasChildren(): boolean;+ /** Returns whether `getVisibleChildNotes()` returns at least one note. */+ hasVisibleChildren(): boolean;+ /** Returns every ancestor of the note across all of its paths in the tree, each note once, up to and including the root note. */+ getAncestors(): BNote[];+ /** Returns the IDs of the notes `getAncestors()` returns, in the same order. */+ getAncestorNoteIds(): string[];+ /** Returns the number of levels between this note and the given ancestor along the shortest path: `1` for a parent, `2` for a grandparent, and `0` for the note itself. */+ getDistanceToAncestor(ancestorNoteId: string): number;+ /** Returns whether the given note is an ancestor of this note on any of its paths. */+ hasAncestor(ancestorNoteId: string): boolean;+ /** Returns whether the given note lies on at least one of this note's paths from the root. */+ isDescendantOfNote(ancestorNoteId: string): boolean;+ /** Returns whether this note is the root of the note tree, whose ID is `root`. */+ isRoot(): boolean;+ /** Returns the note and all its descendants, each note once, together with every parent-child relationship among them, including those of cloned notes. */+ getSubtree(opts?: SubtreeOpts): { notes: BNote[]; relationships: SubtreeRelationship[] };+ /** Returns the IDs of this note and all its descendants, each once. */+ getSubtreeNoteIds(opts?: SubtreeOpts): string[];+ /** Returns the notes that this note's inheritable attributes reach: the note itself, its descendants, and every note that uses one of them as a `template` or `inherit` relation target, along with that note's descendants. */+ getSubtreeNotesIncludingTemplated(): BNote[];+ /** Returns the notes that this note's non-inheritable attributes apply to: the note itself and every note that uses it as a `template` or `inherit` relation target. */+ getInheritingNotes(): BNote[];+ /** Returns every path from the root note to this note, one per placement in the tree. */+ getAllNotePaths(): string[][];+ /** Returns the best path from the root note to this note as an array of note IDs, ranked as in `getSortedNotePathRecords()`. */+ getBestNotePath(hoistedNoteId?: string): string[];+ /** Returns the best path from the root note to this note as a string of note IDs joined by `/`, for example `root/a1h315/js725h`. */+ getBestNotePathString(hoistedNoteId?: string): string;+ /** Returns a record for every path from the root note to this note, best path first. */+ getSortedNotePathRecords(hoistedNoteId?: string): NotePathRecord[];+ /** Returns whether every path to this note passes through an archived note. */+ areAllNotePathsArchived(): boolean;+ /** The labels and relations defined directly on this note, without inherited ones. */+ ownedAttributes: Attribute[];+ /** The relations in other notes (or this one) that point to this note. */+ targetRelations: Attribute[];+ /** The number of labels and relations on this note, inherited ones and automatic link relations included. */+ attributeCount: number;+ /** The number of labels and relations defined directly on this note, automatic link relations included. */+ ownedAttributeCount: number;+ /** The number of labels on this note, inherited ones included. */+ labelCount: number;+ /** The number of labels defined directly on this note. */+ ownedLabelCount: number;+ /** The number of relations on this note, inherited ones included. */+ relationCount: number;+ /** The number of relations on this note, inherited ones included, together with the link relations Trilium creates automatically for links in note content. */+ relationCountIncludingLinks: number;+ /** The number of relations defined directly on this note, excluding the link relations Trilium creates automatically for links in note content. */+ ownedRelationCount: number;+ /** The number of relations defined directly on this note, together with the link relations Trilium creates automatically for links in note content. */+ ownedRelationCountIncludingLinks: number;+ /** The number of relations in other notes that point to this note, excluding the link relations Trilium creates automatically for links in note content. */+ targetRelationCount: number;+ /** The number of relations in other notes that point to this note, together with the link relations Trilium creates automatically for links in note content. */+ targetRelationCountIncludingLinks: number;+ /** Returns the labels and relations of this note, inherited ones included, optionally filtered by type and name. */+ getAttributes(type?: string, name?: string): Attribute[];+ /** Returns the labels and relations defined directly on this note, optionally filtered by type and name. */+ getOwnedAttributes(type?: string, name?: string): Attribute[];+ /** Returns the first attribute of the given type and name, inherited ones included, or `null` if there is none. */+ getAttribute(type: string, name: string): Attribute | null;+ /** Returns the first attribute of the given type and name defined directly on this note, or `null` if there is none. */+ getOwnedAttribute(type: string, name: string, value?: string | null): Attribute | null;+ /** Returns the value of the first attribute of the given type and name, inherited ones included, or `null` if there is none. */+ getAttributeValue(type: string, name: string): string | null;+ /** Returns the value of the first attribute of the given type and name defined directly on this note, or `null` if there is none. */+ getOwnedAttributeValue(type: string, name: string): string | null;+ /** Returns the attribute of this note with the given ID, inherited ones included, or `undefined` if there is none. */+ getAttributeById(attributeId: string): Attribute | undefined;+ /** Returns the first attribute of the given type whose name, and optionally value, matches regardless of letter case, or `undefined` if none does. */+ getAttributeCaseInsensitive(type: string, name: string, value?: string | null): Attribute | undefined;+ /** Returns `true` if the note has a label or relation of the given type and name, inherited ones included. */+ hasAttribute(type: string, name: string): boolean;+ /** Returns whether the note has a label or relation of the given type and name defined directly on it. */+ hasOwnedAttribute(type: string, name: string, value?: string): boolean;+ /** Returns the attribute definitions on this note, inherited ones included. */+ getLabelDefinitions(): Attribute[];+ /** Returns the relation definitions on this note, inherited ones included: the `#relation:*` labels that declare promoted relations, such as `#relation:author="promoted,single"`. */+ getRelationDefinitions(): Attribute[];+ /** Returns the relations in other notes (or this one) that point to this note, the automatic link relations included. */+ getTargetRelations(): Attribute[];+ /** Returns the first label with the given name, inherited ones included, or `null` if there is none. */+ getLabel(name: string): Attribute | null;+ /** Returns the first label with the given name defined directly on this note, or `null` if there is none. */+ getOwnedLabel(name: string): Attribute | null;+ /** Returns the labels of this note, inherited ones included. */+ getLabels(name?: string): Attribute[];+ /** Returns the labels with the given name defined directly on this note. */+ getOwnedLabels(name: string): Attribute[];+ /** Returns the value of the first label with the given name, inherited ones included, or `null` if there is none. */+ getLabelValue(name: string): string | null;+ /** Returns the value of the first label with the given name defined directly on this note, or `null` if there is none. */+ getOwnedLabelValue(name: string): string | null;+ /** Returns the values of all labels with the given name, inherited ones included, for labels that can occur more than once. */+ getLabelValues(name: string): string[];+ /** Returns the values of all labels with the given name defined directly on this note. */+ getOwnedLabelValues(name: string): string[];+ /** Returns whether the note has a label with the given name, inherited ones included. */+ hasLabel(name: string): boolean;+ /** Returns whether the note has a label with the given name defined directly on it. */+ hasOwnedLabel(name: string, value?: string): boolean;+ /** Returns whether the note has a label with the given name, inherited ones included, whose value is not `"false"`. */+ isLabelTruthy(name: string): boolean;+ /** Returns `true` if the note has an inheritable `#archived` label, owned or inherited, so that the note's descendants are archived too. */+ hasInheritableArchivedLabel(): boolean;+ /** Returns the first relation with the given name, inherited ones included, or `null` if there is none. */+ getRelation(name: string): Attribute | null;+ /** Returns the first relation with the given name defined directly on this note, or `null` if there is none. */+ getOwnedRelation(name: string): Attribute | null;+ /** Returns the relations of this note, inherited ones included. */+ getRelations(name?: string): Attribute[];+ /** Returns the relations defined directly on this note. */+ getOwnedRelations(name?: string | null): Attribute[];+ /** Returns the ID of the note that the first relation with the given name points to, inherited relations included, or `null` if there is none. */+ getRelationValue(name: string): string | null;+ /** Returns the ID of the note that the first relation with the given name defined directly on this note points to, or `null` if there is none. */+ getOwnedRelationValue(name: string): string | null;+ /** Returns the note that the first relation with the given name points to, or `null` if the note has no such relation. */+ getRelationTarget(name: string): BNote | null;+ /** Returns whether the note has a relation with the given name, inherited ones included. */+ hasRelation(name: string, value?: string): boolean;+ /** Returns whether the note has a relation with the given name defined directly on it. */+ hasOwnedRelation(name: string, value?: string): boolean;+ /** Adds a label to this note, saves it and returns it. */+ addLabel(name: string, value?: string, isInheritable?: boolean): Attribute;+ /** Adds a relation from this note to another note, saves it and returns it. */+ addRelation(name: string, targetNoteId: string, isInheritable?: boolean): Attribute;+ /** Adds a label or relation to this note, saves it and returns it. `addLabel()` and `addRelation()` do the same for one type. */+ addAttribute(type: string, name: string, value?: string, isInheritable?: boolean): Attribute;+ /** Sets the value of the first label with the given name defined directly on this note, or adds a non-inheritable label if the note has none of its own. */+ setLabel(name: string, value?: string): void;+ /** Points the first relation with the given name defined directly on this note to another note, or adds a non-inheritable relation if the note has none of its own. */+ setRelation(name: string, value?: string): void;+ /** Sets the value of the first attribute of the given type and name defined directly on this note, or adds a non-inheritable one if the note has none of its own. `setLabel()` and `setRelation()` do the same for one type. */+ setAttribute(type: string, name: string, value?: string): void;+ /** Sets the value of the attribute with the given ID, which must be defined directly on this note, and saves it. */+ setAttributeValueById(attributeId: string, value?: string): void;+ /** Sets the label like `setLabel()` when `enabled` is `true`, and removes it like `removeLabel()` when it is `false`. */+ toggleLabel(enabled: boolean, name: string, value?: string): void;+ /** Sets the relation like `setRelation()` when `enabled` is `true`, and removes it like `removeRelation()` when it is `false`. */+ toggleRelation(enabled: boolean, name: string, value?: string): void;+ /** Sets the attribute like `setAttribute()` when `enabled` is `true`, and removes it like `removeAttribute()` when it is `false`. */+ toggleAttribute(type: string, enabled: boolean, name: string, value?: string): void;+ /** Removes every label with the given name defined directly on this note. */+ removeLabel(name: string, value?: string): void;+ /** Removes every relation with the given name defined directly on this note. */+ removeRelation(name: string, value?: string): void;+ /** Removes every attribute of the given type and name defined directly on this note. */+ removeAttribute(type: string, name: string, value?: string): void;+ /** Returns `true` if another note uses this note as its template or inheritance source, through a `~template` or `~inherit` relation. */+ isInherited(): boolean;+ /** The number of revisions of this note. */+ revisionCount: number | null;+ /** Returns the saved revisions of this note, oldest first. */+ getRevisions(): BRevision[];+ /** Saves a revision that snapshots the note's current title, content and attachments, and returns it. */+ saveRevision(opts?: { description?: string; source?: string }): BRevision;+ /** Returns the attachments of this note, ordered by position. */+ getAttachments(): BAttachment[];+ /** Returns the attachment of this note with the given ID. */+ getAttachmentById(attachmentId: string): BAttachment;+ /** Returns the first attachment of this note whose title matches exactly, or `undefined` if none does. */+ getAttachmentByTitle(title: string): BAttachment | undefined;+ /** Returns the attachments of this note with the given role, such as `"image"` or `"file"`, ordered by position. */+ getAttachmentsByRole(role: string): BAttachment[];+ /** Saves an attachment of this note and returns it. */+ saveAttachment(attachment: SaveAttachmentInput, matchBy?: "title" | "attachmentId"): BAttachment;+ /** Converts this image note into an image attachment of its parent text note, points the parent's content at the attachment, deletes this note and returns the attachment. */+ convertToParentAttachment(opts?: { autoConversion?: boolean }): BAttachment | null;+ /** Returns `true` if this note can be converted into an attachment of its parent: it is an image note with no children and a single parent, the parent is a text note, both are readable in the current session, and at most one `~imageLink` relation points to the image, from the parent. */+ isEligibleForConversionToAttachment(opts?: { autoConversion?: boolean }): boolean;+ /** The size of the note's content in bytes. */+ contentSize: number | null;+ /** The size in bytes of the note's content together with its attachments, counting content that several of them share once. */+ contentAndAttachmentsSize: number | null;+ /** The size in bytes of the note's content together with its attachments and its revisions and their attachments, counting shared content once. */+ contentAndAttachmentsAndRevisionsSize: number | null;+ /** Places this note under another parent note as well, keeping its existing placements, and expands the new parent in the note tree. */+ cloneTo(parentNoteId: string): CloneResponse;+ /** Deletes the note from every place in the tree, together with its descendants that have no other placement, and runs its `runOnNoteDeletion` relations first. */+ deleteNote(deleteId?: string | null): void;+ /** Reorders this note's `parents` and `parentBranches` in memory so that archived and hidden parents come last, which makes Trilium prefer the other paths when it picks a note path. */+ sortParents(): void;+ /** Reorders this note's `children` array in memory by each child's `notePosition`. */+ sortChildren(): void;+ /** Returns the notes that match a search query. */+ searchNotesInSubtree(searchString: string): BNote[];+ /** Returns the first note that matches a search query, or `undefined` if none does. */+ searchNoteInSubtree(searchString: string): BNote | null;+ /** Runs the saved search of a search note and returns the notes it finds. */+ getSearchResultNotes(): BNote[];+ /** Returns `true` if this note is a search note or has at least one child, archived children included. */+ isFolder(): boolean;+ /** Returns `true` if the note's title and content can be read: the note is not protected, or a protected session is open. */+ isContentAvailable(): boolean;+ /** Returns whether this is a code, file or render note with the MIME type `text/html`. */+ isHtml(): boolean;+ /** Returns whether this is an image note, or a file note with an `image/*` MIME type. */+ isImage(): boolean;+ /** Returns whether this is a code, file or launcher note with a JavaScript MIME type. */+ isJavaScript(): boolean;+ /** Returns `true` if this is a code note with the MIME type `text/jsx`. */+ isJsx(): boolean;+ /** Returns whether the note's MIME type is `application/json`, whatever its type. */+ isJson(): boolean;+ /** Returns whether this is a code note with a Markdown MIME type. */+ isMarkdown(): boolean;+ /** Returns `true` if this note is one of the settings pages in the hidden subtree, whose IDs start with `_options`. */+ isOptions(): boolean;+ /** Returns `true` if this note is a launcher or one of the containers that configure the desktop or mobile launch bar. */+ isLaunchBarConfig(): boolean;+ /** Returns whether every path to this note passes through the hidden subtree (`_hidden`), so that the note has no placement in the visible tree. */+ isHiddenCompletely(): boolean;+ /** Returns `true` if this note is the hidden root note (`_hidden`) or lies under it in any of its placements. */+ isInHiddenSubtree(): boolean;+ /** Returns where the note runs as a script: `"backend"` for JavaScript with `env=backend` in its MIME type, `"frontend"` for frontend JavaScript, JSX, HTML and render notes, and `null` for notes that are not scripts. */+ getScriptEnv(): "frontend" | "backend" | null;+ /** Runs this note as a backend script and returns the script's return value, which is a promise for an async script. */+ executeScript(): unknown;+}++/** A branch (note→parent placement) as seen by backend scripts (subset of `BBranch`). */+interface BBranch {+ /** The ID of the branch. */+ branchId: string;+ /** The ID of the child note this branch places in the tree. */+ noteId: string;+ /** The ID of the parent note. */+ parentNoteId: string;+ /** The text shown before the note's title in the note tree for this placement only, or `null` if there is none. */+ prefix: string | null;+ /** The position of the note among its siblings under this parent; notes with lower values come first. */+ notePosition: number;+ /** Whether the note is expanded in the note tree at this placement, showing its children. */+ isExpanded: boolean;+ /** Returns the child note this branch places in the tree. */+ getNote(): BNote;+ /** Returns the parent note. */+ getParentNote(): BNote | null;+}++/** Minimal Express `Request` surface available to **custom request handlers** (a subset of Express's `Request` — re-declared here to keep this module self-contained). */+interface Request {+ /** Route/path parameters. */+ params: Record<string, string>;+ /** Parsed query-string parameters. */+ query: Record<string, unknown>;+ /** Parsed request body (requires a matching body parser). */+ body: unknown;+ /** Request headers (lower-cased names). */+ headers: Record<string, string | string[] | undefined>;+ /** HTTP method, e.g. "GET", "POST". */+ method: string;+ /** Request URL (path + query string). */+ url: string;+ /** Returns the value of the given (case-insensitive) header. */+ get(headerName: string): string | undefined;+}++/** Minimal Express `Response` surface available to **custom request handlers** (a subset of Express's `Response`). */+interface Response {+ /** Sets the HTTP status code (chainable). */+ status(code: number): Response;+ /** Sends the response body (string, Buffer, object, …) and ends the response. */+ send(body?: unknown): Response;+ /** Sends a JSON response and ends the response. */+ json(body: unknown): Response;+ /** Sets a response header (chainable). */+ setHeader(name: string, value: string | string[]): Response;+ /** Sets a response header (Express alias of `setHeader`, chainable). */+ set(field: string, value?: string): Response;+ /** Redirects to the given URL. */+ redirect(url: string): void;+ /** Ends the response without further data. */+ end(): void;+}++/** An attachment as seen by backend scripts (subset of trilium-core's `BAttachment`). */+interface BAttachment {+ /** The ID of the attachment. */+ attachmentId?: string;+ /** The ID of the note the attachment belongs to. */+ ownerId: string;+ /** The purpose of the attachment: `image` for an image shown in a text note, `file` for an attached file. */+ role: string;+ /** The MIME type of the attachment's content, such as `image/png`. */+ mime: string;+ /** The title of the attachment, usually its file name. */+ title: string;+ /** The place of the attachment among its owner's attachments, listed by ascending position. */+ position?: number;+ /** Whether the attachment is protected (encrypted). */+ isProtected?: boolean;+ /** The ID of the blob that stores the content. */+ blobId?: string;+ /** The date and time, in UTC, that the attachment was last saved. */+ utcDateModified?: string;+ /** The length of the attachment's content, when it was loaded together with the attachment. */+ contentLength?: number;+ /** Returns the note the attachment belongs to, or `undefined` for a revision's attachment. */+ getNote(): BNote | undefined;+ /** Returns the content: a string for text-based content, a `Uint8Array` for binary content such as images. */+ getContent(): string | Uint8Array<ArrayBufferLike>;+ /** Replaces the content and saves it immediately. */+ setContent(content: string | Uint8Array<ArrayBufferLike>, opts?: { forceSave?: boolean; forceFrontendReload?: boolean }): void;+ /** Returns whether the content is text rather than binary, judged by the MIME type. */+ hasStringContent(): boolean;+ /** Returns whether the title and content can be read: the attachment is not protected, or a protected session is active. */+ isContentAvailable(): boolean;+ /** Returns the title, or `[protected]` when the title cannot be read. */+ getTitleOrProtected(): string;+ /** Returns the file name the attachment downloads under: its title with a fitting extension. */+ getFileName(): string;+ /** Turns the attachment into a child note of its owner and deletes the attachment. */+ convertToNote(): NoteAndBranch;+ /** Saves changes made to the attachment's properties, such as `title`. */+ save(): this;+ /** Deletes the attachment. */+ markAsDeleted(deleteId?: string | null): void;+}++/** A note revision as seen by backend scripts (subset of trilium-core's `BRevision`). */+interface BRevision {+ /** The ID of the revision. */+ revisionId?: string;+ /** The ID of the note this revision belongs to. */+ noteId: string;+ /** The note's type at the time of the revision, such as `"text"` or `"code"`. */+ type: string;+ /** The note's MIME type at the time of the revision. */+ mime: string;+ /** The note's title at the time of the revision. */+ title: string;+ /** When the note was last edited before the revision was saved, in local time with its UTC offset, formatted as `YYYY-MM-DD HH:mm:ss.SSS+ZZZZ` (for example, `2026-10-22 14:05:09.123+0200`). */+ dateLastEdited?: string;+ /** When the note was last edited before the revision was saved, in UTC, formatted as `YYYY-MM-DD HH:mm:ss.SSSZ` (for example, `2026-10-22 12:05:09.123Z`). */+ utcDateLastEdited?: string;+ /** The size of the revision's content in bytes, when it was loaded together with the revision. */+ contentLength?: number;+ /** Returns the content of the revision: a string for text-based note types, a `Uint8Array` for binary ones such as images and files. */+ getContent(): string | Uint8Array<ArrayBufferLike>;+ /** Returns the revision's content parsed as JSON. */+ getJsonContent(): unknown;+}++/** Direct access to Trilium's SQLite database (subset of trilium-core's `SqlService`). */+interface Sql {+ /** Returns the first row of the result, as an object of column names to values, or `undefined` when the query returns no rows. */+ getRow<T>(query: string, params?: unknown[]): T;+ /** Returns the first row of the result, or `null` when the query returns no rows. */+ getRowOrNull<T>(query: string, params?: unknown[]): T | null;+ /** Returns the first column of the first row, such as the count of `SELECT COUNT(*) FROM notes`, or `undefined` when the query returns no rows. */+ getValue<T>(query: string, params?: unknown[]): T;+ /** Returns every row of the result, each as an object of column names to values. */+ getRows<T>(query: string, params?: unknown[]): T[];+ /** Returns the first column of every row of the result. */+ getColumn<T>(query: string, params?: unknown[]): T[];+ /** Returns an object that maps the first column of each row to its second column. */+ getMap<K extends string | number | symbol, V>(query: string, params?: unknown[]): Record<K, V>;+ /** Returns the rows of the result one at a time, which keeps a large result out of memory. */+ iterateRows<T>(query: string, params?: unknown[]): IterableIterator<T>;+ /** Runs a statement that changes data, such as `UPDATE` or `INSERT`. */+ execute(query: string, params?: unknown[]): { changes: number; lastInsertRowid: number };+ /** Runs several statements separated by semicolons, without parameters. */+ executeScript(query: string): void;+ /** Calls `func` in a transaction: when it throws, every change it made is undone. */+ transactional<T>(func: () => T): T;+}++/** A date as day.js wraps it (subset). */+interface DayjsInstance {+ /** Formats the date, such as `"YYYY-MM-DD"` for `2026-10-22`. */+ format(template?: string): string;+ /** Returns a new date, `value` units later. */+ add(value: number, unit: string): DayjsInstance;+ /** Returns a new date, `value` units earlier. */+ subtract(value: number, unit: string): DayjsInstance;+ /** Returns the date as a JavaScript `Date`. */+ toDate(): Date;+}++/** A label or relation attached to a note. */+interface Attribute {+ /** The ID of the attribute. */+ attributeId: string;+ /** The type of the attribute: `label` or `relation`. */+ type: "label" | "relation";+ /** The name of the attribute, without the `#` or `~` prefix. */+ name: string;+ /** The value of the attribute. */+ value: string;+ /** Whether the note's descendants inherit the attribute. */+ isInheritable: boolean;+ /** Not set by Trilium: neither frontend nor backend attributes carry this property, so it reads `undefined`. */+ isOwned: boolean;+}++/** Minimal day.js surface (the real API exposes the full day.js factory). */+type Dayjs = (date?: string | number | Date) => DayjsInstance;++/** The [xml2js](https://github.com/Leonidas-from-XIV/node-xml2js) library, version 0.6, which converts between XML and JavaScript objects, such as with `xml2js.parseStringPromise(xml)`. */+interface Xml2js {}++/** The [node-html-parser](https://github.com/taoqf/node-html-parser) library, version 9, which parses HTML into elements that can be queried, such as with `htmlParser.parse(html).querySelectorAll("a")`. */+interface HtmlParser {}++/** An ETAPI token, which grants an external program access to the ETAPI (subset of trilium-core's `BEtapiToken`). */+interface BEtapiToken {+ /** The ID of the token. */+ etapiTokenId?: string;+ /** The name given to the token when it was created. */+ name: string;+ /** The date and time, in UTC, that the token was created. */+ utcDateCreated: string;+ /** The date and time, in UTC, that the token was last changed, such as renamed. */+ utcDateModified?: string;+ /** Whether the token has been deleted, which revokes it. */+ isDeleted: boolean;+}++/** An option, one of Trilium's settings (subset of trilium-core's `BOption`). */+interface BOption {+ /** The name of the option, such as `theme` or `locale`. */+ name: string;+ /** The value of the option. */+ value: string;+ /** Whether the option syncs to other devices; device-specific options do not. */+ isSynced?: boolean;+ /** The date and time, in UTC, that the option last changed. */+ utcDateModified?: string;+}++/** Options of `api.searchForNotes()` and `api.searchForNote()`. */+interface SearchParams {+ /** Whether to search only titles and attributes, leaving out note content, which is faster. */+ fastSearch?: boolean;+ /** Whether to include archived notes. */+ includeArchivedNotes?: boolean;+ /** Whether to include the hidden subtree's notes, such as settings and launchers. */+ includeHiddenNotes?: boolean;+ /** Whether to search the whole tree even while a note is hoisted. */+ ignoreHoistedNote?: boolean;+ /** The ID of a note to search under: only its descendants are found. */+ ancestorNoteId?: string;+ /** How deep under `ancestorNoteId` the found notes can lie: `eq`, `gt` or `lt` followed by a depth, such as `eq1` for its children only or `lt4` for less than four levels down. */+ ancestorDepth?: string;+ /** What to order the results by: a note property such as `title`, `dateCreated` or `dateModified`, or `relevancy`, the default. */+ orderBy?: string;+ /** `asc` or `desc`; the direction of `orderBy`. */+ orderDirection?: string;+ /** The largest number of results to return. */+ limit?: number | null;+ /** Whether to write how the query was parsed to the backend log. */+ debug?: boolean;+ /** Whether attribute conditions match loosely: `#status=done` also matches values that contain `done`, and `#stat` matches attributes whose name starts with `stat`. */+ fuzzyAttributeSearch?: boolean;+}++/** Result of the backend note-creation helpers. */+interface NoteAndBranch {+ /** The new note. */+ note: BNote;+ /** The branch that places the new note under its parent. */+ branch: BBranch;+}++/** Information about the running Trilium, as `api.getAppInfo()` returns it. */+interface AppInfo {+ /** The version of Trilium, such as `0.106.0`. */+ appVersion: string;+ /** The version of the database schema. */+ dbVersion: number;+ /** The version of Node.js; absent in the standalone and mobile apps, which have no Node.js. */+ nodeVersion?: string;+ /** The version of the sync protocol, which both sides of a sync must share. */+ syncVersion: number;+ /** When this build of Trilium was made. */+ buildDate: string;+ /** The Git commit this build of Trilium was made from. */+ buildRevision: string;+ /** The directory that holds the database and the other data; absent in the standalone and mobile apps. */+ dataDirectory?: string;+ /** The version of the protocol the web clipper speaks with Trilium. */+ clipperProtocolVersion: string;+ /** The date and time, in UTC, that Trilium started, in ISO 8601 form. */+ utcDateTime: string;+}++/** Options accepted by the subtree traversal helpers on `BNote`. */+interface SubtreeOpts {+ /** Whether to include archived notes and their descendants. */+ includeArchived?: boolean;+ /** Whether to descend into the hidden subtree, `_hidden`, which holds Trilium's system notes. */+ includeHidden?: boolean;+ /** Whether to run each search note and include its results as its children. */+ resolveSearch?: boolean;+}++/** A single parent→child link in a subtree (`BNote.getSubtree`). */+interface SubtreeRelationship {+ /** The ID of the parent note. */+ parentNoteId: string;+ /** The ID of the child note. */+ childNoteId: string;+}++/** One resolved tree path to a note (subset of the client's `NotePathRecord`). */+interface NotePathRecord {+ /** Whether a note on the path, the note itself included, is archived, which means it has the `#archived` label, owned or inherited. */+ isArchived: boolean;+ /** Whether the path passes through the hoisted note passed to `getSortedNotePathRecords()`. */+ isInHoistedSubTree: boolean;+ /** Whether the note itself is a search note. */+ isSearch?: boolean;+ /** The note IDs along the path, from `root` to the note itself. */+ notePath: string[];+ /** Whether the path passes through the hidden subtree, `_hidden`, which holds Trilium's system notes. */+ isHidden: boolean;+}++/** Input accepted by `BNote.saveAttachment`. */+interface SaveAttachmentInput {+ /** The ID of the attachment to update. */+ attachmentId?: string;+ /** The purpose of the attachment, such as `image` or `file`. */+ role: string;+ /** The MIME type of the content, such as `image/png`. */+ mime: string;+ /** The title of the attachment, usually its file name. */+ title: string;+ /** The content of the attachment: a string, or bytes for binary content. */+ content?: string | Uint8Array<ArrayBufferLike>;+ /** The place of the attachment among the note's attachments, which `getAttachments()` lists by ascending `position`. */+ position?: number;+}++/** Result of a clone operation (`BNote.cloneTo`); mirrors `CloneResponse`. */+interface CloneResponse {+ /** Whether the note was cloned. */+ success: boolean;+ /** Why the clone failed, such as the note already being in that parent. */+ message?: string;+ /** The ID of the new branch that places the note under the new parent. */+ branchId?: string;+ /** The path of the clone, as note IDs from `root` joined by `/`, ending in the note's ID. */+ notePath?: string;+}+```diff --git a/packages/trilium-core/src/assets/llm/skills/frontend_scripting.md b/packages/trilium-core/src/assets/llm/skills/frontend_scripting.mdindex 6aec7a71d9..738f76ce01 100644--- a/packages/trilium-core/src/assets/llm/skills/frontend_scripting.md+++ b/packages/trilium-core/src/assets/llm/skills/frontend_scripting.md@@ -194,6 +194,8 @@ import { showMessage } from "trilium:api";In JSX, use `import { method } from "trilium:api"`. In JavaScript (Trilium frontend), use the `api` global.+The API reference at the end of this sheet lists every member of `api` and of the objects it returns (`FNote`, `FBranch`, the widget base classes), with exact signatures. The sections below cover what a signature cannot say.+### Script context- `startNote` - note where the script execution started (the entry point of the script bundle). All module notes loaded by the same execution share one `startNote`; `log()` messages are grouped under it.- `currentNote` - note containing the source code currently executing. Equal to `startNote` except inside child module notes. NOT the note open in the UI — that is `getActiveContextNote()`.@@ -208,21 +210,6 @@ Concrete examples:| Render note "Stats" with `~renderNote` → JSX note "StatsComponent" | "StatsComponent" | "StatsComponent" (or module note) | "Stats" (the render note) || `api.runOnFrontend()` called from a backend script | the backend execution's `currentNote` | same | the backend's `originEntity` if it was a note, else `null` |-### Navigation & tabs-- `activateNote(notePath)` - navigate to a note-- `activateNewNote(notePath)` - navigate and wait for sync-- `openTabWithNote(notePath, activate?)` - open in new tab-- `openSplitWithNote(notePath, activate?)` - open in new split-- `getActiveContextNote()` - get currently active note-- `getActiveContextNotePath()` - get path of active note-- `setHoistedNoteId(noteId)` - hoist/unhoist note--### Note access & search-- `getNote(noteId)` - get note by ID-- `getNotes(noteIds)` - bulk fetch notes-- `searchForNotes(searchString)` - search with full query syntax-- `searchForNote(searchString)` - search returning first result-### Note creation- `createNote(parentNotePath, opts?)` - create a note under `parentNotePath` (a noteId or path) **entirely on the frontend — no backend scripting required.** `opts` accepts `{ title, content, type, mime, templateNoteId, isProtected, activate, focus, target, attributes }` and returns `{ note, branch }` from the cache. The new note is activated with its title focused by default; pass `{ activate: false }` to create it silently. **Prefer this over `runOnBackend(() => api.createTextNote(...))`** — the backend variant needs backend scripting, which is off by default.@@ -230,21 +217,6 @@ Concrete examples:const { note } = await createNote(parentNoteId, { title: "New task", type: "text" });```-### Calendar/date notes-- `getTodayNote()` - get/create today's note-- `getDayNote(date)` / `getWeekNote(date)` / `getMonthNote(month)` / `getYearNote(year)`--### Editor access-- `getActiveContextTextEditor()` - get CKEditor instance-- `getActiveContextCodeEditor()` - get CodeMirror instance-- `addTextToActiveContextEditor(text)` - insert text into active editor--### Dialogs & notifications-- `showMessage(msg)` - info toast-- `showError(msg)` - error toast-- `showConfirmDialog(msg)` - confirm dialog (returns boolean)-- `showPromptDialog(msg)` - prompt dialog (returns user input)-### Backend integrationBackend script execution is **disabled by default** (a security setting, since backend scripts have full server access). When it is off, `runOnBackend` and `runAsyncOnBackendWithManualTransactionHandling` reject with *"Backend script execution is disabled"*. **Prefer doing the work on the frontend** whenever possible (most `api.*` note/search/date operations are available on the frontend too). When the backend is genuinely required, guard the call with the check below and tell the user to enable it in **Options → Security**.@@ -278,37 +250,6 @@ const data = await runAsyncOnBackendWithManualTransactionHandling(async (url) =>}, [url]);```-### UI interaction-- `triggerCommand(name, data)` - trigger a command-- `bindGlobalShortcut(shortcut, handler, namespace?)` - add keyboard shortcut--### Utilities-- `formatDateISO(date)` - format as YYYY-MM-DD-- `randomString(length)` - generate random string-- `dayjs` - day.js library-- `log(message)` - log to script log pane--## FNote object--Available via `getNote()`, `getActiveContextNote()`, `useNoteContext()`, etc.--### Properties-- `note.noteId`, `note.title`, `note.type`, `note.mime`-- `note.isProtected`, `note.isArchived`--### Content-- `note.getContent()` - get note content-- `note.getJsonContent()` - parse content as JSON--### Hierarchy-- `note.getParentNotes()` / `note.getChildNotes()`-- `note.hasChildren()`, `note.getSubtreeNoteIds()`--### Attributes-- `note.getAttributes(type?, name?)` - all attributes (including inherited)-- `note.getOwnedAttributes(type?, name?)` - only owned attributes-- `note.hasAttribute(type, name)` - check for attribute-## Electron API (desktop only)Desktop-only functionality is exposed on `window.electronApi` by the preload script. It is **not** part of the `api` global. The global is `undefined` in the browser/server build and in the standalone (WASM) build, so always guard usage.diff --git a/packages/trilium-core/src/assets/llm/skills/frontend_scripting_api.md b/packages/trilium-core/src/assets/llm/skills/frontend_scripting_api.mdnew file mode 100644index 0000000000..294370adde--- /dev/null+++ b/packages/trilium-core/src/assets/llm/skills/frontend_scripting_api.md@@ -0,0 +1,626 @@+<!-- Generated from script_api.ts by `pnpm edit-docs:sync-docs`. Do not edit. -->++## API reference++Every member of `api` and of the objects it returns, as TypeScript declarations, each under the first sentence of its description.++```ts+/** The `api` global available inside **frontend** script notes (`application/javascript;env=frontend`). */+interface FrontendApi {+ /** The element a render note's script renders into: the script of a note that a `~renderNote` relation points to. */+ $container: JQuery | null;+ /** Note where the script execution started — the entry point of the current script bundle (in C terms, the file containing `main()`). */+ startNote: FNote;+ /** Note containing the source code that is currently executing (in C terms, `__FILE__`). */+ currentNote: FNote;+ /** Entity whose event triggered this execution, or `null`. */+ originEntity: FNote | null;+ /** day.js library for date manipulation. */+ dayjs: Dayjs;+ /** Base class for right-panel widgets — `class X extends api.RightPanelWidget { … }`. */+ RightPanelWidget: WidgetClass<RightPanelWidget>;+ /** Base class for note-context-aware widgets — `class X extends api.NoteContextAwareWidget { … }`. */+ NoteContextAwareWidget: WidgetClass<NoteContextAwareWidget>;+ /** Base class for basic widgets — `class X extends api.BasicWidget { … }`. */+ BasicWidget: WidgetClass<BasicWidget>;+ /** Activates note in the tree and in the note detail. */+ activateNote(notePath: string): Promise<void>;+ /** Activates newly created note. */+ activateNewNote(notePath: string): Promise<void>;+ /** Open a note in a new tab. */+ openTabWithNote(notePath: string, activate: boolean): Promise<void>;+ /** Open a note in a new split. */+ openSplitWithNote(notePath: string, activate: boolean): Promise<void>;+ /** Executes given anonymous function on the backend. */+ runOnBackend(func: Func, params?: unknown[]): Promise<unknown>;+ /** Executes given anonymous function on the backend. */+ runAsyncOnBackendWithManualTransactionHandling(func: Func, params?: unknown[]): Promise<unknown>;+ /** Whether backend script execution is enabled on the server (the `[Security] backendScriptingEnabled` config toggle). */+ isBackendScriptingEnabled(): boolean;+ /** Whether the SQL console is enabled on the server (the `[Security] sqlConsoleEnabled` config toggle). */+ isSqlConsoleEnabled(): boolean;+ /** This is a powerful search method - you can search by attributes and their values, e.g.: "#dateModified =* MONTH AND #log". */+ searchForNotes(searchString: string): Promise<FNote[]>;+ /** This is a powerful search method - you can search by attributes and their values, e.g.: "#dateModified =* MONTH AND #log". */+ searchForNote(searchString: string): Promise<FNote | null>;+ /** Returns note by given noteId. */+ getNote(noteId: string): Promise<FNote | null>;+ /** Returns list of notes. */+ getNotes(noteIds: string[], silentNotFoundError?: boolean): Promise<FNote[]>;+ /** Update frontend tree (note) cache from the backend. */+ reloadNotes(noteIds: string[]): Promise<void>;+ /** Creates a new note as a child of the given parent, entirely on the frontend — no backend scripting required (unlike `api.runOnBackend(() => api.createTextNote(...))`). */+ createNote(parentNotePath: string, opts?: CreateNoteOpts): Promise<{ note: FNote | null; branch: FBranch | undefined }>;+ /** Instance name identifies particular Trilium instance. */+ getInstanceName(): string | null;+ /** Adds given text to the editor cursor */+ addTextToActiveContextEditor(text: string): void;+ getActiveContextNote(): FNote;+ /** Obtains the currently active/focused split in the current tab. */+ getActiveContext(): NoteContext;+ /** Obtains the main context of the current tab. */+ getActiveMainContext(): NoteContext;+ getNoteContexts(): NoteContext[];+ getMainNoteContexts(): NoteContext[];+ /** Returns the editor of the text note in the active tab or split. */+ getActiveContextTextEditor(): Promise<TextEditor | null>;+ /** Returns the editor of the code note in the active tab or split. */+ getActiveContextCodeEditor(): Promise<CodeEditor | null>;+ /** Get access to the widget handling note detail. */+ getActiveNoteDetailWidget(): Promise<unknown>;+ getActiveContextNotePath(): string | null;+ /** Returns component which owns the given DOM element (the nearest parent component in DOM tree) */+ getComponentByEl(el: HTMLElement): unknown;+ /** Show an info toast message to the user. */+ showMessage(message: string, delay?: number): void;+ /** Show an error toast message to the user. */+ showError(message: string, delay?: number): void;+ /** Show an info dialog to the user. */+ showInfoDialog(message: string): Promise<void>;+ /** Show confirm dialog to the user. */+ showConfirmDialog(message: string): Promise<boolean>;+ /** Show prompt dialog to the user. */+ showPromptDialog(props: { title?: string; message?: string; defaultValue?: string }): Promise<string | null>;+ /** Show a dialog for picking one item out of many, grouped and searchable. `items` are either the items themselves or groups of them, never the two mixed. */+ pickSingleItem(props: { title?: string; items: PickerItem[] | PickerItemGroup[]; placeholder?: string }): Promise<PickerItem | null>;+ /** Create a note link (jQuery object) for given note. */+ createLink(notePath: string, params?: LinkOptions): Promise<JQuery>;+ /** Trigger command. */+ triggerCommand(name: string, data?: Record<string, unknown>): Promise<unknown>;+ /** Trigger event. */+ triggerEvent(name: string, data?: Record<string, unknown>): Promise<unknown>;+ /** Shows a preview of the linked note while the mouse pointer rests on the element, as Trilium does for links in note content. */+ setupElementTooltip(el: JQuery): void;+ protectNote(noteId: string, protect: boolean): Promise<void>;+ protectSubTree(noteId: string, protect: boolean): Promise<void>;+ /** Returns date-note for today. */+ getTodayNote(): Promise<FNote>;+ /** Returns day note for a given date. */+ getDayNote(date: string): Promise<FNote>;+ /** Returns day note for the first date of the week of the given date. */+ getWeekFirstDayNote(date: string): Promise<FNote>;+ /** Returns week note for given date. */+ getWeekNote(date: string): Promise<FNote>;+ /** Returns month-note. */+ getMonthNote(month: string): Promise<FNote>;+ /** Returns quarter note for given date. */+ getQuarterNote(date: string): Promise<FNote>;+ /** Returns year-note. */+ getYearNote(year: string): Promise<FNote>;+ /** Hoist note in the current tab. */+ setHoistedNoteId(noteId: string): void;+ bindGlobalShortcut(keyboardShortcut: string, handler: () => void, namespace?: string): void;+ /** Trilium runs in a backend and frontend process, when something is changed on the backend from a script, frontend will get asynchronously synchronized. */+ waitUntilSynced(): Promise<unknown>;+ /** This will refresh all currently opened notes which have included note specified in the parameter */+ refreshIncludedNote(includedNoteId: string): void;+ /** Return randomly generated string of given length. */+ randomString(length: number): string;+ formatSize(size: number): string;+ /** Converts the given HTML string to Markdown. */+ htmlToMarkdown(html: string): Promise<string>;+ /** Converts the given Markdown string to HTML. */+ markdownToHtml(markdown: string): Promise<string>;+ formatDateISO(date: Date): string;+ /** Parses a date string into a Date. */+ parseDate(str: string): Date;+ /** Per-note log message buffers shown in the UI log pane. */+ logMessages: Record<string, string[]>;+ /** Per-note spaced-update handlers for the log pane. */+ logSpacedUpdates: Record<string, unknown>;+ /** Log given message to the log pane in UI. */+ log(...args: unknown[]): void;+ /** The Preact API surface (components, hooks) for render scripts. */+ preact: Preact;+}++/** A note as seen by frontend scripts (subset of the client's `FNote`). */+interface FNote {+ /** The ID of the note. */+ noteId: string;+ /** The title of the note. */+ title: string;+ /** The note type, such as `text`, `code`, `file`, `image`, `search`, `book`, `render` or `launcher`. */+ type: string;+ /** The MIME type of the note's content, such as `application/json`. */+ mime: string;+ /** Whether the note is protected (encrypted). */+ isProtected: boolean;+ /** Whether the note is archived (has the `archived` label). */+ isArchived: boolean;+ /** Whether the note's title and icon cannot be edited, which is the case for the system notes behind the options, the in-app help and the launch bar configuration. */+ isMetadataReadOnly: boolean;+ /** IDs of this note's owned attributes. */+ attributes: string[];+ /** IDs of relations pointing *at* this note. */+ targetRelations: string[];+ /** Parent note IDs. */+ parents: string[];+ /** Child note IDs. */+ children: string[];+ /** Returns the parent notes that the client has already loaded. */+ getParentNotes(): FNote[];+ /** Loads any missing child notes from the server, then returns all child notes in tree order. */+ getChildNotes(): Promise<FNote[]>;+ /** Returns the IDs of the parent notes. */+ getParentNoteIds(): string[];+ /** Returns the IDs of the child notes in tree order, archived ones included. */+ getChildNoteIds(): string[];+ /** Returns the IDs of the child notes in tree order, leaving out archived notes unless `includeArchived` is `true`. */+ getChildNoteIdsWithArchiveFiltering(includeArchived?: boolean): Promise<string[]>;+ /** Returns all descendants of the note, loading missing ones from the server one level at a time. */+ getSubtreeNotes(): Promise<FNote[]>;+ /** Returns the IDs of all the note's descendants, depth-first, without the note itself. */+ getSubtreeNoteIds(includeArchived?: boolean): Promise<string[]>;+ /** Returns `true` if the note has at least one child, archived ones included. */+ hasChildren(): boolean;+ /** Returns `true` if the note with the given ID is this note or one of its ancestors. */+ hasAncestor(ancestorNoteId: string, followTemplates?: boolean): boolean;+ /** Returns `true` if this is the root note of the tree. */+ isRoot(): boolean;+ /** Returns the IDs of the branches that place this note under each of its parents. */+ getParentBranchIds(): string[];+ /** Returns the branches that place this note under each of its parents. */+ getParentBranches(): FBranch[];+ /** Returns the branches to this note's children, in tree order. */+ getChildBranches(): FBranch[];+ /** Returns the same branches as `getChildBranches()`. */+ getFilteredChildBranches(): FBranch[];+ /** Returns every path from the root to the note, each as a list of note IDs that starts with `root`. */+ getAllNotePaths(): string[][];+ /** Returns the note's best path as a list of note IDs that starts with `root`. */+ getBestNotePath(hoistedNoteId?: string, activeNotePath?: string | null): string[];+ /** Returns the note's best path, as `getBestNotePath()` chooses it, as note IDs joined by `/`, such as `root/a1h315/js725h`. */+ getBestNotePathString(hoistedNoteId?: string): string;+ /** Returns every path from the root to this note, best first. */+ getSortedNotePathRecords(hoistedNoteId?: string, activeNotePath?: string | null): NotePathRecord[];+ /** Returns the note's attributes, including inherited ones, optionally only those of the given type and name. */+ getAttributes(type?: string, name?: string): Attribute[];+ /** Returns the note's own attributes, without inherited ones, optionally only those of the given type and name. */+ getOwnedAttributes(type?: string, name?: string): Attribute[];+ /** Returns the first attribute of the given type and name, including inherited ones, or `undefined` if the note has none. */+ getAttribute(type: string, name: string): Attribute | null;+ /** Returns the first of the note's own attributes with the given type and name, or `undefined` if the note has none. */+ getOwnedAttribute(type: string, name: string): Attribute | null;+ /** Returns the value of the first attribute of the given type and name, including inherited ones, or `null` if the note has none. */+ getAttributeValue(type: string, name: string): string | null;+ /** Returns the value of the first of the note's own attributes with the given type and name, or `null` if the note has none. */+ getOwnedAttributeValue(type: string, name: string): string | null;+ /** Returns whether the note has an attribute of the given type and name, including inherited ones. */+ hasAttribute(type: string, name: string): boolean;+ /** Returns whether the note itself has an attribute of the given type and name, without inherited ones. */+ hasOwnedAttribute(type: string, name: string): boolean;+ /** Returns the attribute definitions that apply to the note, at most one per defined name. */+ getAttributeDefinitions(): Attribute[];+ /** Returns the attribute definitions that are marked as promoted, at most one per name, grouped by the note that owns them and ordered by position. */+ getPromotedDefinitionAttributes(): Attribute[];+ /** Returns the note's labels, including inherited ones, optionally only those with `name`. */+ getLabels(name?: string): Attribute[];+ /** Returns the note's own labels, without inherited ones, optionally only those with `name`. */+ getOwnedLabels(name?: string): Attribute[];+ /** Returns the first label with the given name, including inherited ones, or `undefined` if the note has none. */+ getLabel(name: string): Attribute | null;+ /** Returns the first of the note's own labels with the given name, or `undefined` if the note has none. */+ getOwnedLabel(name: string): Attribute | null;+ /** Returns the value of the first label with the given name, including inherited ones, or `null` if the note has none. */+ getLabelValue(name: string): string | null;+ /** Returns the value of the first of the note's own labels with the given name, or `null` if the note has none. */+ getOwnedLabelValue(name: string): string | null;+ /** Returns whether the note has a label with the given name, including inherited ones. */+ hasLabel(name: string): boolean;+ /** Returns whether the note itself has a label with the given name, without inherited ones. */+ hasOwnedLabel(name: string): boolean;+ /** Returns whether the note has a label with the given name, including inherited ones, or the same label with the `disabled:` prefix, which a safe import gives it. */+ hasLabelOrDisabled(name: string): boolean;+ /** Returns whether the note has a label with the given name, including inherited ones, whose value is anything but `false`. */+ isLabelTruthy(name: string): boolean;+ /** Returns the note's relations, including inherited ones, optionally only those with `name`. */+ getRelations(name?: string): Attribute[];+ /** Returns the note's own relations, without inherited ones, optionally only those with `name`. */+ getOwnedRelations(name: string): Attribute[];+ /** Returns the first relation with the given name, including inherited ones, or `undefined` if the note has none. */+ getRelation(name: string): Attribute | null;+ /** Returns the first of the note's own relations with the given name, or `undefined` if the note has none. */+ getOwnedRelation(name: string): Attribute | null;+ /** Returns the target note ID of the first relation with the given name, including inherited ones, or `null` if the note has none. */+ getRelationValue(name: string): string | null;+ /** Returns the target note ID of the first of the note's own relations with the given name, or `null` if the note has none. */+ getOwnedRelationValue(name: string): string | null;+ /** Returns whether the note has a relation with the given name, including inherited ones. */+ hasRelation(name: string): boolean;+ /** Returns whether the note itself has a relation with the given name, without inherited ones. */+ hasOwnedRelation(name: string): boolean;+ /** Returns the value of a label or relation, inherited ones included, or `null` if the note has none. */+ getLabelOrRelation(nameWithPrefix: string): string | null;+ /** Returns the target note of the first relation with the given name, including inherited ones. */+ getRelationTarget(name: string): Promise<FNote | null>;+ /** Returns the target notes of the note's relations with the given name, including inherited ones, in the order of the relations. */+ getRelationTargets(name: string): Promise<(FNote | null)[]>;+ /** Returns the relations, owned by any note, that point at this note. */+ getTargetRelations(): Attribute[];+ /** Returns the notes that own a relation pointing at this note. */+ getTargetRelationSourceNotes(): Promise<FNote[]>;+ /** Fetches the note's content from the server. */+ getContent(): Promise<string | Uint8Array<ArrayBufferLike>>;+ /** Fetches the note's content and parses it as JSON. */+ getJsonContent(): Promise<unknown>;+ /** Fetches the note's content together with its blob ID, length and modification date. */+ getBlob(): Promise<Blob | null>;+ /** Returns the note's creation and modification dates, which it requests from the server. */+ getMetadata(): Promise<NoteMetadata>;+ /** The note's attachments, or `null` until `getAttachments()` loads them. */+ attachments: Attachment[] | null;+ /** Returns the note's attachments. */+ getAttachments(): Promise<Attachment[]>;+ /** Returns the note's attachments with the given role, such as `image` or `file`. */+ getAttachmentsByRole(role: string): Promise<Attachment[]>;+ /** Returns the note's attachment with the given ID, or `undefined` if this note has no such attachment. */+ getAttachmentById(attachmentId: string): Promise<Attachment | undefined>;+ /** Returns the target notes of this note's `~template` and `~inherit` relations, inherited relations included. */+ getNotesToInheritAttributesFrom(): FNote[];+ /** Returns the CSS classes of the note's icon, such as `tn-icon bx bx-note`. */+ getIcon(): string;+ /** Returns `true` if the note shows as a folder in the tree: a search note, or a note with children (archived ones included). */+ isFolder(): boolean;+ /** Returns `true` if the note is placed, directly or through ancestors the client has loaded, under the shared notes root (`_share`). */+ isShared(): boolean;+ /** Returns `true` if the note's content can be read: the note is not protected, or a protected session is active. */+ isContentAvailable(): boolean;+ /** Returns `true` if the note's MIME type is `application/json`. */+ isJson(): boolean;+ /** Returns whether the note is a code, file or launcher note with a JavaScript MIME type. */+ isJavaScript(): boolean;+ /** Returns `true` if the note is a code note with the MIME type `text/jsx`. */+ isJsx(): boolean;+ /** Returns whether the note is a code, file or render note with the `text/html` MIME type. */+ isHtml(): boolean;+ /** Returns `true` if the note is a code note with a Markdown MIME type (`text/markdown`, `text/x-markdown` or `text/x-gfm`). */+ isMarkdown(): boolean;+ /** Returns `true` if the note is one of Trilium's settings pages. */+ isOptions(): boolean;+ /** Returns `true` if the note's MIME type starts with `application/javascript`, which covers both frontend and backend scripts. */+ isTriliumScript(): boolean;+ /** Returns `true` if the note is a SQL console note, which has the MIME type `text/x-sqlite;schema=trilium`. */+ isTriliumSqlite(): boolean;+ /** Returns `true` if the note is a launcher or one of the notes that hold the launch bar's launchers. */+ isLaunchBarConfig(): boolean;+ /** Returns whether every path to the note runs through the hidden subtree, so that no clone of it appears in the visible tree. */+ isHiddenCompletely(): boolean;+ /** Returns `true` if the note is the hidden subtree's root (`_hidden`) or has it as an ancestor through any of its loaded parents, even when the note is also cloned into the visible tree. */+ isInHiddenSubtree(): boolean;+ /** Returns `true` if the image note can be converted into an attachment of its parent: it is an image note without children, it has exactly one parent, that parent is a text note, the content of both is available, and no note other than the parent links to the image. */+ isEligibleForConversionToAttachment(): boolean;+ /** Returns the CSS class that applies the note's `color` label, such as `color-ff0000`, or an empty string if the label is missing or not a valid color. */+ getColorClass(): string;+ /** Returns the values of all the note's `cssClass` labels, inherited ones included, separated by spaces. */+ getCssClass(): string;+ /** Returns the value of the note's `workspaceIconClass` label, or an empty string if it has none. */+ getWorkspaceIconClass(): string;+ /** Returns the value of the note's `workspaceTabBackgroundColor` label, or an empty string if it has none. */+ getWorkspaceTabBackgroundColor(): string;+ /** Returns where the note runs as a script: `frontend` for HTML, JSX, render notes and JavaScript with `env=frontend` in its MIME type, `backend` for JavaScript with `env=backend`, and `null` for any other note. */+ getScriptEnv(): "frontend" | "backend" | null;+ /** Runs the note as a frontend or backend script, depending on `getScriptEnv()`. */+ executeScript(): Promise<unknown>;+ /** Blob ID of the current content; changes when content changes. */+ blobId: string;+ /** Map of parent note ID → branch ID. */+ parentToBranch: Record<string, string>;+ /** Map of child note ID → branch ID. */+ childToBranch: Record<string, string>;+ /** For a search note, `true` once its results have been loaded as its children; otherwise not set. */+ searchResultsLoaded?: boolean;+ /** For a search note whose results are loaded, the search words to highlight in those results; otherwise not set. */+ highlightedTokens?: string[];+ /** Plain data representation of the note (the live object minus its cache handle). */+ dto: Record<string, unknown>;+ /** Adds a parent to this note in the client's cache only. */+ addParent(parentNoteId: string, branchId: string, sort?: boolean): void;+ /** Adds a child to this note in the client's cache only. */+ addChild(childNoteId: string, branchId: string, sort?: boolean): void;+ /** Reorders the parent list in the client's cache so that ordinary parents come before search notes, archived notes and notes outside the visible tree. */+ sortParents(): void;+ /** Reorders the child list in the client's cache by each branch's position. */+ sortChildren(): void;+ /** Overwrites the note's ID, title, type, MIME type, protection flag and blob ID in the client's cache with the values in `row`. */+ update(row: Record<string, unknown>): void;+ /** Returns a short description of the note for logging, such as `Note(noteId=abc123, title=My note)`. */+ toString(): string;+}++/** Instance shape of `RightPanelWidget` (subset) — a widget shown in the right sidebar. */+interface RightPanelWidget extends NoteContextAwareWidget {+ /** The title shown in the panel's header, `Untitled widget` unless overridden. */+ readonly widgetTitle: string;+ /** Builds the panel's body. */+ doRenderBody(): void | Promise<void>;+}++/** Instance shape of `NoteContextAwareWidget` (subset) — reacts to the active note. */+interface NoteContextAwareWidget extends BasicWidget {+ /** The note currently shown in this widget's context. */+ note: FNote | null;+ /** The ID of `note`, such as for `loadResults.isNoteContentReloaded(this.noteId)`. */+ readonly noteId: string | undefined;+ /** The path of `note` in the tree, such as `root/abc123/def456`. */+ readonly notePath: string | null | undefined;+ /** The ID of the note context (split) this widget is attached to. */+ readonly ntxId: string | null | undefined;+ /** The note context (split) this widget is attached to. */+ noteContext?: NoteContext;+ /** Returns whether `noteId` is the note shown in this widget's context. */+ isNote(noteId: string): boolean;+ /** Updates the widget for the note in its context. */+ refreshWithNote(note: FNote | null | undefined): void | Promise<void>;+ /** Forces a refresh against the current note. */+ refresh(): void | Promise<void>;+}++/** Instance shape of `BasicWidget` (subset) — the base for custom frontend widgets. */+interface BasicWidget {+ /** The widget's root element, which `doRender()` assigns, such as `this.$widget = $(TPL)`. */+ $widget: JQuery;+ /** Returns whether the widget is shown: always for a `BasicWidget`, and only while a note is active for a `NoteContextAwareWidget`. */+ isEnabled(): boolean | null | undefined;+ /** Builds the widget's DOM. */+ doRender(): void;+ /** Renders the widget and returns its root element. */+ render(): JQuery;+ /** Tears down the widget; override to release resources. */+ cleanup(): void;+ /** Shows or hides the widget from inside the widget itself, such as from `refreshWithNote()` when the note does not apply. */+ toggleInt(show: boolean | null | undefined): void;+ /** Fluent builder: set the element id. */+ id(id: string): this;+ /** Fluent builder: add a CSS class. */+ class(className: string): this;+ /** Sets an inline CSS property on the widget's root element, such as `css("padding-inline-start", "12px")`, and returns the widget for chaining. */+ css(name: string, value: string): this;+ /** Fluent builder: append child components. */+ child(...components: unknown[]): this;+}++/** A branch (parent↔child link) as seen by frontend scripts (subset of `FBranch`). */+interface FBranch {+ /** The unique ID of the branch. */+ branchId: string;+ /** The ID of the child note that this branch places in the tree. */+ noteId: string;+ /** The ID of the parent note. */+ parentNoteId: string;+ /** The place of the note among its siblings; the note tree lists siblings by ascending `notePosition`. */+ notePosition: number;+ /** The prefix shown before the note's title in the note tree, for this placement of the note only. */+ prefix?: string;+ /** Whether the note tree shows this branch expanded, with the note's children visible. */+ isExpanded?: boolean;+ /** Returns the child note, loading it from the server if the frontend cache does not hold it yet. */+ getNote(): Promise<FNote | null>;+ /** Returns the child note from the frontend cache, without contacting the server. */+ getNoteFromCache(): FNote | undefined;+ /** Returns the parent note, loading it from the server if the frontend cache does not hold it yet. */+ getParentNote(): Promise<FNote | null>;+ /** Returns whether the branch places its note directly under the root note. */+ isTopLevel(): boolean;+}++/** A split/tab context as seen by frontend scripts (subset of `NoteContext`). */+interface NoteContext {+ /** The ID of the note context, which identifies one tab or split. */+ ntxId: string | null;+ /** The note this context shows, or `null` if the context is empty. */+ note: FNote | null;+ /** The path of the note this context shows, as note IDs from `root` joined by `/`, such as `root/abc123/def456`. */+ notePath: string | null;+ /** Returns the CodeMirror editor of the code note this context shows. */+ getCodeEditor(): Promise<CodeEditor | null>;+ /** Returns the CKEditor instance of the editable text note this context shows. */+ getTextEditor(): Promise<TextEditor | null>;+}++/** A date as day.js wraps it (subset). */+interface DayjsInstance {+ /** Formats the date, such as `"YYYY-MM-DD"` for `2026-10-22`. */+ format(template?: string): string;+ /** Returns a new date, `value` units later. */+ add(value: number, unit: string): DayjsInstance;+ /** Returns a new date, `value` units earlier. */+ subtract(value: number, unit: string): DayjsInstance;+ /** Returns the date as a JavaScript `Date`. */+ toDate(): Date;+}++/** A jQuery object: one or more page elements with jQuery's methods, as `$(…)` returns. */+interface JQuery {}++/** Minimal day.js surface (the real API exposes the full day.js factory). */+type Dayjs = (date?: string | number | Date) => DayjsInstance;++/** Constructor type allowing `class X extends api.Widget { … }`. */+type WidgetClass<T> = new (...args: unknown[]) => T;++type Func = ((...args: unknown[]) => unknown) | string;++/** Options accepted by `FrontendApi.createNote`. */+interface CreateNoteOpts {+ /** Title of the new note. */+ title?: string | null;+ /** Content of the new note (HTML for text notes, source for code notes, etc.). */+ content?: string | null;+ /** Note type, e.g. "text" (default), "code", "book". */+ type?: string;+ /** MIME type, e.g. "application/javascript;env=frontend" for a frontend code note. */+ mime?: string;+ /** Note ID of a template to apply to the new note. */+ templateNoteId?: string;+ /** Create the note as protected (only takes effect when a protected session is available). */+ isProtected?: boolean;+ /** Activate (open) the new note after creation. */+ activate?: boolean;+ /** Which part of the activated note to focus. */+ focus?: "title" | "content";+ /** Where to place the note relative to the parent/target: "into" (default) or "after". */+ target?: string;+ /** Branch ID used together with `target: "after"`. */+ targetBranchId?: string;+ /** Attributes to set atomically on creation. */+ attributes?: CreateAttribute[];+}++/** The editor of a text note, a CKEditor 5 editor. */+interface TextEditor {}++/** The editor of a code note, a CodeMirror 6 `EditorView`. */+interface CodeEditor {}++/** One thing a picker offers, as `pickSingleItem` takes and answers with. */+interface PickerItem {+ /** The ID of the item. */+ key: string;+ /** The text shown for the item. */+ caption: string;+ /** An icon class, `bx` prefix included. */+ icon?: string;+ /** HTML shown in a tooltip while the item is hovered. */+ tooltip?: string;+}++/** A run of picker items under a heading of their own. */+interface PickerItemGroup {+ /** The ID of the group. */+ key: string;+ /** The heading shown above the group's items. */+ groupHeader: string;+ /** The items in the group, in the order the picker shows them. */+ items: PickerItem[];+}++/** Options of `api.createLink()`. */+interface LinkOptions {+ /** The text of the link. */+ title?: string;+ /** Whether a preview of the note shows while the mouse pointer rests on the link. */+ showTooltip?: boolean;+ /** Whether the path of the note's parents shows below the link. */+ showNotePath?: boolean;+ /** Whether the note's icon shows before the link. */+ showNoteIcon?: boolean;+ /** Whether the link is styled as a reference link, as in text notes. */+ referenceLink?: boolean;+ /** Whether an image, canvas or Mermaid note shows as its picture instead of a link. */+ autoConvertToImage?: boolean;+ /** Text shown right after the link's title. */+ titleSuffix?: string;+}++/** The Preact API that render notes import from `trilium:preact`: Preact's own functions and hooks, and Trilium's components and `defineWidget()`. */+interface Preact {}++/** One resolved tree path to a note (subset of the client's `NotePathRecord`). */+interface NotePathRecord {+ /** Whether a note on the path, the note itself included, is archived, which means it has the `#archived` label, owned or inherited. */+ isArchived: boolean;+ /** Whether the path passes through the hoisted note passed to `getSortedNotePathRecords()`. */+ isInHoistedSubTree: boolean;+ /** Whether the note itself is a search note. */+ isSearch?: boolean;+ /** The note IDs along the path, from `root` to the note itself. */+ notePath: string[];+ /** Whether the path passes through the hidden subtree, `_hidden`, which holds Trilium's system notes. */+ isHidden: boolean;+}++/** A label or relation attached to a note. */+interface Attribute {+ /** The ID of the attribute. */+ attributeId: string;+ /** The type of the attribute: `label` or `relation`. */+ type: "label" | "relation";+ /** The name of the attribute, without the `#` or `~` prefix. */+ name: string;+ /** The value of the attribute. */+ value: string;+ /** Whether the note's descendants inherit the attribute. */+ isInheritable: boolean;+ /** Not set by Trilium: neither frontend nor backend attributes carry this property, so it reads `undefined`. */+ isOwned: boolean;+}++/** A note's binary/text content blob (subset of the client's `FBlob`). */+interface Blob {+ /** The ID of the blob, derived from its content. */+ blobId: string;+ /** The content as text. */+ content: string;+ /** The length of the content as stored: characters for text, bytes for binary content. */+ contentLength: number;+ /** The local date and time this content was first stored, with the UTC offset, such as `2026-10-22 14:03:05.123+0200`. */+ dateModified: string;+ /** The date and time, in UTC, that this content was first stored, such as `2026-10-22 12:03:05.123Z`. */+ utcDateModified: string;+}++/** Creation/modification timestamps returned by `FNote.getMetadata`. */+interface NoteMetadata {+ /** The local date and time the note was created, with the UTC offset, such as `2026-10-22 14:03:05.123+0200`. */+ dateCreated: string;+ /** The date and time, in UTC, that the note was created, such as `2026-10-22 12:03:05.123Z`. */+ utcDateCreated: string;+ /** The local date and time the note was last modified, with the UTC offset, such as `2026-10-22 14:03:05.123+0200`. */+ dateModified: string;+ /** The date and time, in UTC, that the note was last modified, such as `2026-10-22 12:03:05.123Z`. */+ utcDateModified: string;+}++/** An attachment as seen by frontend scripts (subset of the client's `FAttachment`). */+interface Attachment {+ /** The ID of the attachment. */+ attachmentId: string;+ /** The ID of the note the attachment belongs to. */+ ownerId: string;+ /** The purpose of the attachment, such as `image` for an image shown in a text note or `file` for an attached file. */+ role: string;+ /** The MIME type of the attachment's content, such as `image/png`. */+ mime: string;+ /** The title of the attachment, usually its file name. */+ title: string;+ /** The date and time, in UTC, that the attachment was last saved, such as `2026-10-22 12:03:05.123Z`. */+ utcDateModified: string;+ /** The length of the attachment's content. */+ contentLength: number;+}++/** An attribute to create together with a note (see `CreateNoteOpts.attributes`). */+interface CreateAttribute {+ /** The type of the attribute: `label` or `relation`. */+ type: "label" | "relation";+ /** The name of the attribute, without the `#` or `~` prefix. */+ name: string;+ /** The value of the attribute. */+ value?: string;+ /** Whether the note's descendants inherit the attribute. */+ isInheritable?: boolean;+ /** The place of the attribute among the note's attributes, which are listed by ascending `position`. */+ position?: number;+}+```diff --git a/packages/trilium-core/src/services/llm/skills.spec.ts b/packages/trilium-core/src/services/llm/skills.spec.tsindex 7ddcadffdb..e73d89b760 100644--- a/packages/trilium-core/src/services/llm/skills.spec.ts+++ b/packages/trilium-core/src/services/llm/skills.spec.ts@@ -1,4 +1,4 @@-import { existsSync } from "fs";+import { existsSync, readFileSync } from "fs";import { dirname, join } from "path";import { fileURLToPath } from "url";import { afterEach, describe, expect, it } from "vitest";@@ -13,6 +13,7 @@ import { getSkillsSummary, readSkill, registerSkillReader, SKILLS } from "./skil* can use.*/const HERE = dirname(fileURLToPath(import.meta.url));+const SKILLS_DIR = join(HERE, "../../assets/llm/skills");/** Restore the "no host has registered anything" state the module starts in. */function clearReader() {@@ -25,9 +26,32 @@ describe("llm skill sheets", () => {it("ships a markdown sheet for every catalogued skill", () => {// The catalog is the contract between core and both readers: an entry with// no file behind it is a tool call that fails at the far end of a chat.- for (const skill of SKILLS) {- const path = join(HERE, "../../assets/llm/skills", skill.file);- expect(existsSync(path), `missing sheet: ${skill.file}`).toBe(true);+ for (const file of SKILLS.flatMap((skill) => [ skill.file, skill.reference ?? [] ]).flat()) {+ expect(existsSync(join(SKILLS_DIR, file)), `missing sheet: ${file}`).toBe(true);+ }+ });++ it("appends the API reference to a sheet that has one", () => {+ registerSkillReader((file) => ({ "backend_scripting.md": "SHEET\n", "backend_scripting_api.md": "REFERENCE" })[file] ?? null);+ expect(readSkill("backend_scripting")).toBe("SHEET\n\nREFERENCE");++ // A host without the reference still serves the sheet.+ registerSkillReader((file) => file === "backend_scripting.md" ? "SHEET" : null);+ expect(readSkill("backend_scripting")).toBe("SHEET");+ });++ it("keeps each API reference in step with script_api.ts", () => {+ // Each reference is generated by `pnpm edit-docs:sync-docs`; a member added to or removed+ // from script_api.ts without a sync since fails here.+ const source = interfaceMembers(readFileSync(join(HERE, "../../../../commons/src/lib/script_api.ts"), "utf-8"), true);+ for (const reference of SKILLS.flatMap((skill) => skill.reference ?? [])) {+ const generated = interfaceMembers(readFileSync(join(SKILLS_DIR, reference), "utf-8"), false);+ expect(generated.size, reference).toBeGreaterThan(0);+ for (const [ name, members ] of generated) {+ const declared = source.get(`Script${name}`) ?? source.get(name);+ expect(declared, `${reference}: ${name} is not in script_api.ts`).toBeDefined();+ expect([ ...members ].sort(), `${reference}: ${name}`).toEqual([ ...(declared ?? []) ].sort());+ }}});@@ -65,3 +89,42 @@ describe("llm skill sheets", () => {}});});++/**+ * The member names of each interface in TypeScript source, one member per line at a 4-space indent.+ * With `skipDeprecated`, a member whose doc comment carries `@deprecated` is left out, as the+ * generated references leave it out.+ */+function interfaceMembers(source: string, skipDeprecated: boolean) {+ const interfaces = new Map<string, Set<string>>();+ let members: Set<string> | undefined;+ let comment = "";+ for (const line of source.split("\n")) {+ const start = /^(?:export )?interface (\w+)/.exec(line);+ if (start) {+ members = new Set();+ interfaces.set(start[1], members);+ continue;+ }+ if (line.startsWith("}")) {+ members = undefined;+ continue;+ }++ if (/^ {4}\/\*\*/.test(line)) {+ comment = "";+ }+ if (/^ {4}(\/\*\*| \*)/.test(line)) {+ comment += line;+ continue;+ }+ const member = /^ {4}(?:readonly )?([\w$]+)[?(<:]/.exec(line);+ if (members && member) {+ if (!skipDeprecated || !comment.includes("@deprecated")) {+ members.add(member[1]);+ }+ comment = "";+ }+ }+ return interfaces;+}diff --git a/packages/trilium-core/src/services/llm/skills.ts b/packages/trilium-core/src/services/llm/skills.tsindex ae39065b7b..a18a2493dc 100644--- a/packages/trilium-core/src/services/llm/skills.ts+++ b/packages/trilium-core/src/services/llm/skills.ts@@ -20,6 +20,11 @@ interface SkillDefinition {summary: string;/** Markdown file under `src/assets/llm/skills`, which is what a reader is asked for. */file: string;+ /**+ * Markdown file under `src/assets/llm/skills` that `readSkill()` appends to the sheet: the API+ * reference `pnpm edit-docs:sync-docs` generates from `script_api.ts`.+ */+ reference?: string;}export const SKILLS: SkillDefinition[] = [@@ -33,13 +38,15 @@ export const SKILLS: SkillDefinition[] = [name: "backend_scripting",description: "Backend (Node.js) scripting API — creating notes, handling events, accessing entities, database operations, and automation.",summary: "the backend Node.js scripting API",- file: "backend_scripting.md"+ file: "backend_scripting.md",+ reference: "backend_scripting_api.md"},{name: "frontend_scripting",description: "Frontend (browser) scripting API — UI widgets, navigation, dialogs, editor access, Preact/JSX components, and keyboard shortcuts.",summary: "the frontend browser scripting API",- file: "frontend_scripting.md"+ file: "frontend_scripting.md",+ reference: "frontend_scripting_api.md"},{name: "dashboards",@@ -65,15 +72,18 @@ export function registerSkillReader(reader: (file: string) => string | null) {}/**- * The sheet's markdown, or null when the skill is unknown to the catalog or the- * host cannot produce it.+ * The sheet's markdown, followed by its API reference when it has one, or null+ * when the skill is unknown to the catalog or the host cannot produce the sheet.*/export function readSkill(name: string): string | null {const skill = SKILLS.find((s) => s.name === name);if (!skill || !skillReader) {return null;}- return skillReader(skill.file);++ const sheet = skillReader(skill.file);+ const reference = skill.reference ? skillReader(skill.reference) : null;+ return sheet && reference ? `${sheet.trimEnd()}\n\n${reference}` : sheet;}/**