Forked from ceveyne/user-docs
Forked from ceveyne/user-docs
src / tools / memorize_doc.ts
src / tools / memorize_doc.ts
/**
* memorize_doc — write or overwrite a notes document.
* Creates YAML frontmatter automatically; derives filename from title slug.
* Optionally embeds image references from the pN/aN pool.
*/
import { tool, type Tool, type ToolsProviderController } from "@lmstudio/sdk";
// @ts-ignore — zod/lib re-export chain breaks with NodeNext; runtime is fine
import { z } from "zod";
import path from "node:path";
import fs from "node:fs";
import { globalConfigSchematics } from "../config.js";
import { slugify, buildFrontmatter, buildSkillFrontmatter, sanitizeRelativeFile } from "../helpers/frontmatter.js";
// @ts-ignore — typed via core-bundle.d.mts
import { readState, formatToolMetaBlock } from "../core-bundle.mjs";
function readExistingCreated(filePath: string): string | undefined {
if (!fs.existsSync(filePath)) return undefined;
const existing = fs.readFileSync(filePath, "utf8");
const m = existing.match(/^created:\s*"?([^"\n]+)"?/m);
return m ? m[1].trim() : undefined;
}
function sanitizeImageFilename(name: string): string {
return name.replace(/[^a-zA-Z0-9._-]/g, "_");
}
export function createMemorizeDocTool(ctl: ToolsProviderController): Tool {
return tool({
name: "memorize_doc",
description: `Write a new note to the notes directory, or completely replace an existing one. Also supports SKILL.md skill bundles.
Three modes, chosen by which parameters you set:
- Note: set \`title\` (+ optional \`tags\`). Writes a flat file \`<slug>.md\` with title/tags/created/updated frontmatter. The filename is derived automatically from the title (slugified).
- Skill: set \`name\` + \`description\`. Writes \`<slug>/SKILL.md\` with name/description/created/updated frontmatter (Agent Skills–compatible) — the entry point find_doc/read_doc will surface.
- Companion file: set \`name\` + \`file\` (e.g. "tools/my-tool.md"). Writes \`<slug>/<file>\` as plain Markdown with no frontmatter — link to it from SKILL.md's body with a relative path.
Use this tool when:
- The user explicitly asks you to save or write a note
- You derive or discover information useful to persist
- Summarising the outcome of a completed task
- Creating a structured reference note (how-tos, decisions, preferences)
- Authoring or updating a reusable skill bundle for future sessions
Optionally attach images from the current chat (pN/aN notations) to a note — they are copied to images/ in the notes directory and referenced in the Markdown body. Not applicable to skill/companion-file mode.
Returns:
- Confirmation with the resulting relative path
- An error if required parameters for the selected mode are missing
${formatToolMetaBlock()}`,
parameters: {
title: z
.string()
.optional()
.describe("Document title for a plain note. Required unless `name` is set (skill mode)."),
name: z
.string()
.optional()
.describe(
"Skill identifier (kebab-case recommended). When set, targets a skill bundle folder instead of a flat note. Combine with `description` to write SKILL.md, or with `file` to write a companion file."
),
file: z
.string()
.optional()
.describe(
'Relative path inside the skill bundle for a companion file, e.g. "tools/my-tool.md". Requires `name`. Written as-is with no frontmatter.'
),
description: z
.string()
.optional()
.describe(
"One-paragraph discovery description. Required when writing SKILL.md (name set, file omitted)."
),
tags: z
.array(z.string())
.default([])
.describe("List of tags to categorise this document. Only used for plain notes."),
body: z
.string()
.describe("The main content of the document (plain Markdown, without frontmatter)."),
images: z
.array(z.string())
.default([])
.describe(
"Optional list of image notations from the current chat (e.g. ['p1', 'a2']) to embed as references at the end of the document. Only used for plain notes."
),
},
implementation: async (args) => {
const getter: any =
(ctl as any).getGlobalPluginConfig || (ctl as any).getGlobalConfig;
const gcfg = getter ? getter.call(ctl, globalConfigSchematics) : null;
const notesDirectory: string = gcfg?.get("notesDirectory") ?? "";
if (!notesDirectory) {
return "Error: Notes Directory is not configured. The initial plugin setup has not been completed yet — start a new chat and follow the setup guide, then set Notes Directory in the plugin global settings.";
}
if (args.name) {
const skillSlug = slugify(args.name);
if (!skillSlug) return "Error: name must contain at least one word character.";
const skillDir = path.join(notesDirectory, skillSlug);
if (args.file) {
const rel = sanitizeRelativeFile(args.file);
if (!rel) return `Error: invalid file "${args.file}" — must be a relative .md/.txt path without "..".`;
const filePath = path.join(skillDir, rel);
if (!fs.existsSync(skillDir)) fs.mkdirSync(skillDir, { recursive: true });
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, args.body, "utf8");
return `Saved companion file → ${skillSlug}/${rel}`;
}
if (!args.description) {
return "Error: description is required to write a SKILL.md (or pass `file` to add a companion file instead).";
}
if (!fs.existsSync(skillDir)) fs.mkdirSync(skillDir, { recursive: true });
const filePath = path.join(skillDir, "SKILL.md");
const existingCreated = readExistingCreated(filePath);
const now = new Date().toISOString();
const frontmatter = buildSkillFrontmatter(args.name, args.description, now, existingCreated);
fs.writeFileSync(filePath, `${frontmatter}${args.body}`, "utf8");
return `Saved skill "${args.name}" → ${skillSlug}/SKILL.md`;
}
if (!args.title) {
return "Error: title is required for a plain note (or use `name`/`description` to write a skill).";
}
const slug = slugify(args.title);
if (!slug) return "Error: Title must contain at least one word character.";
const filename = `${slug}.md`;
const filePath = path.join(notesDirectory, filename);
const now = new Date().toISOString();
// Preserve original created date if file exists
let existingCreated: string | undefined;
if (fs.existsSync(filePath)) {
const existing = fs.readFileSync(filePath, "utf8");
const m = existing.match(/^created:\s*"?([^"\n]+)"?/m);
existingCreated = m ? m[1].trim() : undefined;
}
// Ensure notes directory exists
if (!fs.existsSync(notesDirectory)) {
fs.mkdirSync(notesDirectory, { recursive: true });
}
// Handle image attachments
let bodyWithImages = args.body;
const imageNotations: string[] = (args.images ?? []).filter((s) => /^[aivp]\d+$/i.test(s));
if (imageNotations.length > 0) {
const chatWd = ctl.getWorkingDirectory();
if (typeof chatWd !== "string" || !chatWd.trim()) {
return "Error: Working directory not available — cannot resolve image notations.";
}
const imagesDir = path.join(notesDirectory, "images");
if (!fs.existsSync(imagesDir)) {
fs.mkdirSync(imagesDir, { recursive: true });
}
let state: any;
try {
state = await readState(chatWd);
} catch (e) {
return `Error: Could not read chat media state — ${(e as Error).message ?? String(e)}`;
}
const imageRefs: string[] = [];
let hasImages = false;
for (const notation of imageNotations) {
const m = /^([avip])(\d+)$/i.exec(notation);
if (!m) continue;
const prefix = m[1].toLowerCase() as "a" | "v" | "i" | "p";
const n = parseInt(m[2], 10);
const poolKey =
prefix === "a" ? "attachments" :
prefix === "v" ? "variants" :
prefix === "i" ? "images" :
"pictures";
const idKey = prefix;
const rec = ((state as any)[poolKey] ?? []).find((x: any) => x?.[idKey] === n);
if (!rec) {
imageRefs.push(`<!-- ${notation}: not found in state -->`);
continue;
}
// Resolve original absolute path
const origAbs: string | undefined =
prefix === "a"
? (rec.originAbs as string | undefined) ??
(rec.filename ? path.join(chatWd, rec.filename as string) : undefined)
: rec.filename
? path.join(chatWd, rec.filename as string)
: undefined;
if (!origAbs || !fs.existsSync(origAbs)) {
imageRefs.push(`<!-- ${notation}: file not found -->`);
continue;
}
const baseName = sanitizeImageFilename(path.basename(origAbs));
const dest = path.join(imagesDir, baseName);
try {
fs.copyFileSync(origAbs, dest);
imageRefs.push(``);
hasImages = true;
} catch (e) {
imageRefs.push(`<!-- ${notation}: copy failed — ${(e as Error).message} -->`);
}
}
if (imageRefs.length > 0) {
bodyWithImages = `${args.body}\n\n${imageRefs.join("\n")}`;
}
if (hasImages) {
// Append has_images tag for searchability if not already present
const hasTags: string[] = args.tags ?? [];
if (!hasTags.includes("has_images")) {
hasTags.push("has_images");
}
const frontmatter = buildFrontmatter(args.title, hasTags, now, existingCreated);
const content = `${frontmatter}${bodyWithImages}`;
fs.writeFileSync(filePath, content, "utf8");
return `Saved "${args.title}" → ${filename}`;
}
}
const frontmatter = buildFrontmatter(args.title, args.tags ?? [], now, existingCreated);
const content = `${frontmatter}${bodyWithImages}`;
fs.writeFileSync(filePath, content, "utf8");
return `Saved "${args.title}" → ${filename}`;
},
});
}
/**
* memorize_doc — write or overwrite a notes document.
* Creates YAML frontmatter automatically; derives filename from title slug.
* Optionally embeds image references from the pN/aN pool.
*/
import { tool, type Tool, type ToolsProviderController } from "@lmstudio/sdk";
// @ts-ignore — zod/lib re-export chain breaks with NodeNext; runtime is fine
import { z } from "zod";
import path from "node:path";
import fs from "node:fs";
import { globalConfigSchematics } from "../config.js";
import { slugify, buildFrontmatter, buildSkillFrontmatter, sanitizeRelativeFile } from "../helpers/frontmatter.js";
// @ts-ignore — typed via core-bundle.d.mts
import { readState, formatToolMetaBlock } from "../core-bundle.mjs";
function readExistingCreated(filePath: string): string | undefined {
if (!fs.existsSync(filePath)) return undefined;
const existing = fs.readFileSync(filePath, "utf8");
const m = existing.match(/^created:\s*"?([^"\n]+)"?/m);
return m ? m[1].trim() : undefined;
}
function sanitizeImageFilename(name: string): string {
return name.replace(/[^a-zA-Z0-9._-]/g, "_");
}
export function createMemorizeDocTool(ctl: ToolsProviderController): Tool {
return tool({
name: "memorize_doc",
description: `Write a new note to the notes directory, or completely replace an existing one. Also supports SKILL.md skill bundles.
Three modes, chosen by which parameters you set:
- Note: set \`title\` (+ optional \`tags\`). Writes a flat file \`<slug>.md\` with title/tags/created/updated frontmatter. The filename is derived automatically from the title (slugified).
- Skill: set \`name\` + \`description\`. Writes \`<slug>/SKILL.md\` with name/description/created/updated frontmatter (Agent Skills–compatible) — the entry point find_doc/read_doc will surface.
- Companion file: set \`name\` + \`file\` (e.g. "tools/my-tool.md"). Writes \`<slug>/<file>\` as plain Markdown with no frontmatter — link to it from SKILL.md's body with a relative path.
Use this tool when:
- The user explicitly asks you to save or write a note
- You derive or discover information useful to persist
- Summarising the outcome of a completed task
- Creating a structured reference note (how-tos, decisions, preferences)
- Authoring or updating a reusable skill bundle for future sessions
Optionally attach images from the current chat (pN/aN notations) to a note — they are copied to images/ in the notes directory and referenced in the Markdown body. Not applicable to skill/companion-file mode.
Returns:
- Confirmation with the resulting relative path
- An error if required parameters for the selected mode are missing
${formatToolMetaBlock()}`,
parameters: {
title: z
.string()
.optional()
.describe("Document title for a plain note. Required unless `name` is set (skill mode)."),
name: z
.string()
.optional()
.describe(
"Skill identifier (kebab-case recommended). When set, targets a skill bundle folder instead of a flat note. Combine with `description` to write SKILL.md, or with `file` to write a companion file."
),
file: z
.string()
.optional()
.describe(
'Relative path inside the skill bundle for a companion file, e.g. "tools/my-tool.md". Requires `name`. Written as-is with no frontmatter.'
),
description: z
.string()
.optional()
.describe(
"One-paragraph discovery description. Required when writing SKILL.md (name set, file omitted)."
),
tags: z
.array(z.string())
.default([])
.describe("List of tags to categorise this document. Only used for plain notes."),
body: z
.string()
.describe("The main content of the document (plain Markdown, without frontmatter)."),
images: z
.array(z.string())
.default([])
.describe(
"Optional list of image notations from the current chat (e.g. ['p1', 'a2']) to embed as references at the end of the document. Only used for plain notes."
),
},
implementation: async (args) => {
const getter: any =
(ctl as any).getGlobalPluginConfig || (ctl as any).getGlobalConfig;
const gcfg = getter ? getter.call(ctl, globalConfigSchematics) : null;
const notesDirectory: string = gcfg?.get("notesDirectory") ?? "";
if (!notesDirectory) {
return "Error: Notes Directory is not configured. The initial plugin setup has not been completed yet — start a new chat and follow the setup guide, then set Notes Directory in the plugin global settings.";
}
if (args.name) {
const skillSlug = slugify(args.name);
if (!skillSlug) return "Error: name must contain at least one word character.";
const skillDir = path.join(notesDirectory, skillSlug);
if (args.file) {
const rel = sanitizeRelativeFile(args.file);
if (!rel) return `Error: invalid file "${args.file}" — must be a relative .md/.txt path without "..".`;
const filePath = path.join(skillDir, rel);
if (!fs.existsSync(skillDir)) fs.mkdirSync(skillDir, { recursive: true });
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, args.body, "utf8");
return `Saved companion file → ${skillSlug}/${rel}`;
}
if (!args.description) {
return "Error: description is required to write a SKILL.md (or pass `file` to add a companion file instead).";
}
if (!fs.existsSync(skillDir)) fs.mkdirSync(skillDir, { recursive: true });
const filePath = path.join(skillDir, "SKILL.md");
const existingCreated = readExistingCreated(filePath);
const now = new Date().toISOString();
const frontmatter = buildSkillFrontmatter(args.name, args.description, now, existingCreated);
fs.writeFileSync(filePath, `${frontmatter}${args.body}`, "utf8");
return `Saved skill "${args.name}" → ${skillSlug}/SKILL.md`;
}
if (!args.title) {
return "Error: title is required for a plain note (or use `name`/`description` to write a skill).";
}
const slug = slugify(args.title);
if (!slug) return "Error: Title must contain at least one word character.";
const filename = `${slug}.md`;
const filePath = path.join(notesDirectory, filename);
const now = new Date().toISOString();
// Preserve original created date if file exists
let existingCreated: string | undefined;
if (fs.existsSync(filePath)) {
const existing = fs.readFileSync(filePath, "utf8");
const m = existing.match(/^created:\s*"?([^"\n]+)"?/m);
existingCreated = m ? m[1].trim() : undefined;
}
// Ensure notes directory exists
if (!fs.existsSync(notesDirectory)) {
fs.mkdirSync(notesDirectory, { recursive: true });
}
// Handle image attachments
let bodyWithImages = args.body;
const imageNotations: string[] = (args.images ?? []).filter((s) => /^[aivp]\d+$/i.test(s));
if (imageNotations.length > 0) {
const chatWd = ctl.getWorkingDirectory();
if (typeof chatWd !== "string" || !chatWd.trim()) {
return "Error: Working directory not available — cannot resolve image notations.";
}
const imagesDir = path.join(notesDirectory, "images");
if (!fs.existsSync(imagesDir)) {
fs.mkdirSync(imagesDir, { recursive: true });
}
let state: any;
try {
state = await readState(chatWd);
} catch (e) {
return `Error: Could not read chat media state — ${(e as Error).message ?? String(e)}`;
}
const imageRefs: string[] = [];
let hasImages = false;
for (const notation of imageNotations) {
const m = /^([avip])(\d+)$/i.exec(notation);
if (!m) continue;
const prefix = m[1].toLowerCase() as "a" | "v" | "i" | "p";
const n = parseInt(m[2], 10);
const poolKey =
prefix === "a" ? "attachments" :
prefix === "v" ? "variants" :
prefix === "i" ? "images" :
"pictures";
const idKey = prefix;
const rec = ((state as any)[poolKey] ?? []).find((x: any) => x?.[idKey] === n);
if (!rec) {
imageRefs.push(`<!-- ${notation}: not found in state -->`);
continue;
}
// Resolve original absolute path
const origAbs: string | undefined =
prefix === "a"
? (rec.originAbs as string | undefined) ??
(rec.filename ? path.join(chatWd, rec.filename as string) : undefined)
: rec.filename
? path.join(chatWd, rec.filename as string)
: undefined;
if (!origAbs || !fs.existsSync(origAbs)) {
imageRefs.push(`<!-- ${notation}: file not found -->`);
continue;
}
const baseName = sanitizeImageFilename(path.basename(origAbs));
const dest = path.join(imagesDir, baseName);
try {
fs.copyFileSync(origAbs, dest);
imageRefs.push(``);
hasImages = true;
} catch (e) {
imageRefs.push(`<!-- ${notation}: copy failed — ${(e as Error).message} -->`);
}
}
if (imageRefs.length > 0) {
bodyWithImages = `${args.body}\n\n${imageRefs.join("\n")}`;
}
if (hasImages) {
// Append has_images tag for searchability if not already present
const hasTags: string[] = args.tags ?? [];
if (!hasTags.includes("has_images")) {
hasTags.push("has_images");
}
const frontmatter = buildFrontmatter(args.title, hasTags, now, existingCreated);
const content = `${frontmatter}${bodyWithImages}`;
fs.writeFileSync(filePath, content, "utf8");
return `Saved "${args.title}" → ${filename}`;
}
}
const frontmatter = buildFrontmatter(args.title, args.tags ?? [], now, existingCreated);
const content = `${frontmatter}${bodyWithImages}`;
fs.writeFileSync(filePath, content, "utf8");
return `Saved "${args.title}" → ${filename}`;
},
});
}