src / toolsProvider.ts
import { text, tool, type Tool, type ToolsProviderController } from "@lmstudio/sdk";
import { writeFile } from "fs/promises";
import { join } from "path";
import { z } from "zod";
const chatMessageSchema = z.object({
role: z.enum(["user", "assistant", "system"]),
content: z.string(),
timestamp: z.number().optional(),
});
export async function toolsProvider(ctl: ToolsProviderController) {
const tools: Tool[] = [];
const exportTxtTool = tool({
name: "export_chat_to_txt",
description: text`
Exports the current chat conversation to a plain text (.txt) file.
You must receive the full list of messages from the user to export.
Each message should include the role (user/assistant/system) and content.
The file will be saved in the current working directory with a timestamped name.
Returns the path where the file was saved.
`,
parameters: {
messages: z.array(chatMessageSchema).describe("Array of chat messages to export"),
filename: z.string().optional().describe("Optional custom filename (without extension)"),
},
implementation: async ({ messages, filename }) => {
const workingDirectory = ctl.getWorkingDirectory();
const now = new Date();
const timestamp = now.toISOString().replace(/[:.]/g, "-");
const outputFilename = (filename ?? `chat-export-${timestamp}`) + ".txt";
const outputPath = join(workingDirectory, outputFilename);
const separator = "=".repeat(70);
let content = "";
content += separator + "\n";
content += "EXPORTACION DE CHAT - LM STUDIO\n";
content += `Fecha: ${now.toLocaleString("es-ES")}\n`;
content += `Mensajes: ${messages.length}\n`;
content += separator + "\n\n";
for (let i = 0; i < messages.length; i++) {
const msg = messages[i];
const role =
msg.role === "user" ? "USUARIO" :
msg.role === "assistant" ? "ASISTENTE" : "SISTEMA";
const time = msg.timestamp
? new Date(msg.timestamp).toLocaleTimeString("es-ES")
: "--:--";
content += `[${i + 1}] ${role} (${time})\n`;
content += "-".repeat(40) + "\n";
content += msg.content.replace(/\r/g, "").trim() + "\n\n";
}
await writeFile(outputPath, content, "utf-8");
return { success: true, path: outputPath };
},
});
tools.push(exportTxtTool);
return tools;
}