summaryrefslogtreecommitdiffhomepage
path: root/src/tools.ts
blob: 68937bdde8578b24a76dc7786ed74c79829e8d9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import type { App } from "obsidian";
import { TFile } from "obsidian";

/**
 * Schema for an Ollama tool definition (function calling).
 */
export interface OllamaToolDefinition {
	type: "function";
	function: {
		name: string;
		description: string;
		parameters: {
			type: "object";
			required: string[];
			properties: Record<string, { type: string; description: string }>;
		};
	};
}

/**
 * Metadata for a tool the user can enable/disable.
 */
export interface ToolEntry {
	id: string;
	label: string;
	description: string;
	friendlyName: string;
	requiresApproval: boolean;
	approvalMessage?: (args: Record<string, unknown>) => string;
	summarize: (args: Record<string, unknown>) => string;
	summarizeResult: (result: string) => string;
	definition: OllamaToolDefinition;
	execute: (app: App, args: Record<string, unknown>) => Promise<string>;
}

/**
 * Execute the "search_files" tool.
 * Returns a newline-separated list of vault file paths matching the query.
 */
async function executeSearchFiles(app: App, args: Record<string, unknown>): Promise<string> {
	const query = typeof args.query === "string" ? args.query.toLowerCase() : "";
	if (query === "") {
		return "Error: query parameter is required.";
	}

	const files = app.vault.getFiles();
	const matches: string[] = [];

	for (const file of files) {
		if (file.path.toLowerCase().includes(query)) {
			matches.push(file.path);
		}
	}

	if (matches.length === 0) {
		return "No files found matching the query.";
	}

	// Cap results to avoid overwhelming the context
	const maxResults = 50;
	const limited = matches.slice(0, maxResults);
	const suffix = matches.length > maxResults
		? `\n... and ${matches.length - maxResults} more results.`
		: "";

	return limited.join("\n") + suffix;
}

/**
 * Execute the "read_file" tool.
 * Returns the full text content of a file by its vault path.
 */
async function executeReadFile(app: App, args: Record<string, unknown>): Promise<string> {
	const filePath = typeof args.file_path === "string" ? args.file_path : "";
	if (filePath === "") {
		return "Error: file_path parameter is required.";
	}

	const file = app.vault.getAbstractFileByPath(filePath);
	if (file === null || !(file instanceof TFile)) {
		return `Error: File not found at path "${filePath}".`;
	}

	try {
		const content = await app.vault.cachedRead(file);
		return content;
	} catch (err: unknown) {
		const msg = err instanceof Error ? err.message : "Unknown error";
		return `Error reading file: ${msg}`;
	}
}

/**
 * Execute the "delete_file" tool.
 * Deletes a file by its vault path (moves to trash).
 */
async function executeDeleteFile(app: App, args: Record<string, unknown>): Promise<string> {
	const filePath = typeof args.file_path === "string" ? args.file_path : "";
	if (filePath === "") {
		return "Error: file_path parameter is required.";
	}

	const file = app.vault.getAbstractFileByPath(filePath);
	if (file === null || !(file instanceof TFile)) {
		return `Error: File not found at path "${filePath}".`;
	}

	try {
		await app.vault.trash(file, true);
		return `File "${filePath}" has been deleted (moved to system trash).`;
	} catch (err: unknown) {
		const msg = err instanceof Error ? err.message : "Unknown error";
		return `Error deleting file: ${msg}`;
	}
}

/**
 * Execute the "get_current_note" tool.
 * Returns the vault-relative path of the currently active note.
 */
async function executeGetCurrentNote(app: App, _args: Record<string, unknown>): Promise<string> {
	const file = app.workspace.getActiveFile();
	if (file === null) {
		return "Error: No note is currently open.";
	}
	return file.path;
}

/**
 * Execute the "edit_file" tool.
 * Performs a find-and-replace on the file content using vault.process() for atomicity.
 */
async function executeEditFile(app: App, args: Record<string, unknown>): Promise<string> {
	const filePath = typeof args.file_path === "string" ? args.file_path : "";
	if (filePath === "") {
		return "Error: file_path parameter is required.";
	}

	const oldText = typeof args.old_text === "string" ? args.old_text : "";
	const newText = typeof args.new_text === "string" ? args.new_text : "";

	if (oldText === "") {
		return "Error: old_text parameter is required and cannot be empty.";
	}

	const file = app.vault.getAbstractFileByPath(filePath);
	if (file === null || !(file instanceof TFile)) {
		return `Error: File not found at path "${filePath}".`;
	}

	try {
		let replaced = false;
		await app.vault.process(file, (data) => {
			if (!data.includes(oldText)) {
				return data;
			}
			replaced = true;
			return data.replace(oldText, newText);
		});

		if (!replaced) {
			return `Error: The specified old_text was not found in "${filePath}".`;
		}

		return `Successfully edited "${filePath}".`;
	} catch (err: unknown) {
		const msg = err instanceof Error ? err.message : "Unknown error";
		return `Error editing file: ${msg}`;
	}
}

/**
 * All available tools for the plugin.
 */
export const TOOL_REGISTRY: ToolEntry[] = [
	{
		id: "search_files",
		label: "Search File Names",
		description: "Search for files in the vault by name or path.",
		friendlyName: "Search Files",
		requiresApproval: false,
		summarize: (args) => {
			const query = typeof args.query === "string" ? args.query : "";
			return `"${query}"`;
		},
		summarizeResult: (result) => {
			if (result === "No files found matching the query.") {
				return "No results found";
			}
			const lines = result.split("\n").filter((l) => l.length > 0);
			const moreMatch = result.match(/\.\.\.\s*and\s+(\d+)\s+more/);
			const extraCount = moreMatch !== null ? parseInt(moreMatch[1], 10) : 0;
			const count = lines.length - (moreMatch !== null ? 1 : 0) + extraCount;
			return `${count} result${count === 1 ? "" : "s"} found`;
		},
		definition: {
			type: "function",
			function: {
				name: "search_files",
				description: "Search for files in the Obsidian vault by name or path. Returns a list of exact file paths. Use these exact paths for any subsequent file operations.",
				parameters: {
					type: "object",
					required: ["query"],
					properties: {
						query: {
							type: "string",
							description: "The search query to match against file names and paths.",
						},
					},
				},
			},
		},
		execute: executeSearchFiles,
	},
	{
		id: "read_file",
		label: "Read File Contents",
		description: "Read the full text content of a file in the vault.",
		friendlyName: "Read File",
		requiresApproval: false,
		summarize: (args) => {
			const filePath = typeof args.file_path === "string" ? args.file_path : "";
			return `"/${filePath}"`;
		},
		summarizeResult: (result) => {
			if (result.startsWith("Error")) {
				return result;
			}
			const lines = result.split("\n").length;
			return `${lines} line${lines === 1 ? "" : "s"} read`;
		},
		definition: {
			type: "function",
			function: {
				name: "read_file",
				description: "Read the full text content of a file in the Obsidian vault. The file_path must be an exact path as returned by search_files.",
				parameters: {
					type: "object",
					required: ["file_path"],
					properties: {
						file_path: {
							type: "string",
							description: "The vault-relative path to the file (e.g. 'folder/note.md').",
						},
					},
				},
			},
		},
		execute: executeReadFile,
	},
	{
		id: "delete_file",
		label: "Delete File",
		description: "Delete a file from the vault (requires approval).",
		friendlyName: "Delete File",
		requiresApproval: true,
		approvalMessage: (args) => {
			const filePath = typeof args.file_path === "string" ? args.file_path : "unknown";
			return `Delete "${filePath}"?`;
		},
		summarize: (args) => {
			const filePath = typeof args.file_path === "string" ? args.file_path : "";
			return `"/${filePath}"`;
		},
		summarizeResult: (result) => {
			if (result.startsWith("Error")) {
				return result;
			}
			if (result.includes("declined")) {
				return "Declined by user";
			}
			return "File deleted";
		},
		definition: {
			type: "function",
			function: {
				name: "delete_file",
				description: "Delete a file from the Obsidian vault. The file is moved to the system trash. The file_path must be an exact path as returned by search_files. This action requires user approval.",
				parameters: {
					type: "object",
					required: ["file_path"],
					properties: {
						file_path: {
							type: "string",
							description: "The vault-relative path to the file to delete (e.g. 'folder/note.md').",
						},
					},
				},
			},
		},
		execute: executeDeleteFile,
	},
	{
		id: "get_current_note",
		label: "Get Current Note",
		description: "Get the file path of the currently open note.",
		friendlyName: "Get Current Note",
		requiresApproval: false,
		summarize: () => "Checking active note",
		summarizeResult: (result) => {
			if (result.startsWith("Error")) {
				return result;
			}
			return `"/${result}"`;
		},
		definition: {
			type: "function",
			function: {
				name: "get_current_note",
				description: "Get the vault-relative file path of the note currently open in the editor. Use this to find out which note the user is looking at. Returns an exact path that can be used with read_file or edit_file.",
				parameters: {
					type: "object",
					required: [],
					properties: {},
				},
			},
		},
		execute: executeGetCurrentNote,
	},
	{
		id: "edit_file",
		label: "Edit File",
		description: "Find and replace text in a vault file (requires approval).",
		friendlyName: "Edit File",
		requiresApproval: true,
		approvalMessage: (args) => {
			const filePath = typeof args.file_path === "string" ? args.file_path : "unknown";
			return `Edit "${filePath}"?`;
		},
		summarize: (args) => {
			const filePath = typeof args.file_path === "string" ? args.file_path : "";
			return `"/${filePath}"`;
		},
		summarizeResult: (result) => {
			if (result.startsWith("Error")) {
				return result;
			}
			if (result.includes("declined")) {
				return "Declined by user";
			}
			return "File edited";
		},
		definition: {
			type: "function",
			function: {
				name: "edit_file",
				description: "Edit a file in the Obsidian vault by finding and replacing text. Provide the exact text to find (old_text) and the replacement (new_text). The old_text must match exactly as it appears in the file, including whitespace and newlines. Only the first occurrence is replaced. The file_path must be an exact path as returned by search_files or get_current_note. This action requires user approval.",
				parameters: {
					type: "object",
					required: ["file_path", "old_text", "new_text"],
					properties: {
						file_path: {
							type: "string",
							description: "The vault-relative path to the file (e.g. 'folder/note.md').",
						},
						old_text: {
							type: "string",
							description: "The exact text to find in the file. Must match exactly including whitespace.",
						},
						new_text: {
							type: "string",
							description: "The text to replace old_text with. Use an empty string to delete the matched text.",
						},
					},
				},
			},
		},
		execute: executeEditFile,
	},
];

/**
 * Get the default enabled state for all tools (all disabled).
 */
export function getDefaultToolStates(): Record<string, boolean> {
	const states: Record<string, boolean> = {};
	for (const tool of TOOL_REGISTRY) {
		states[tool.id] = false;
	}
	return states;
}

/**
 * Look up a tool entry by function name.
 */
export function findToolByName(name: string): ToolEntry | undefined {
	return TOOL_REGISTRY.find((t) => t.definition.function.name === name);
}