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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
|
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 "grep_search" tool.
* Searches file contents for a text query, returning matching lines with context.
*/
async function executeGrepSearch(app: App, args: Record<string, unknown>): Promise<string> {
const query = typeof args.query === "string" ? args.query : "";
if (query === "") {
return "Error: query parameter is required.";
}
const filePattern = typeof args.file_pattern === "string" ? args.file_pattern.toLowerCase() : "";
const queryLower = query.toLowerCase();
const files = app.vault.getMarkdownFiles();
const results: string[] = [];
const maxResults = 50;
let totalMatches = 0;
for (const file of files) {
if (totalMatches >= maxResults) break;
// Optional file pattern filter
if (filePattern !== "" && !file.path.toLowerCase().includes(filePattern)) {
continue;
}
try {
const content = await app.vault.cachedRead(file);
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line !== undefined && line.toLowerCase().includes(queryLower)) {
results.push(`${file.path}:${i + 1}: ${line.trim()}`);
totalMatches++;
if (totalMatches >= maxResults) break;
}
}
} catch {
// Skip files that can't be read
}
}
if (results.length === 0) {
return "No matches found.";
}
const suffix = totalMatches >= maxResults
? `\n... results capped at ${maxResults}. Narrow your query for more specific results.`
: "";
return results.join("\n") + suffix;
}
/**
* Execute the "create_file" tool.
* Creates a new file at the given vault path with the provided content.
*/
async function executeCreateFile(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 content = typeof args.content === "string" ? args.content : "";
// Check if file already exists
const existing = app.vault.getAbstractFileByPath(filePath);
if (existing !== null) {
return `Error: A file already exists at "${filePath}". Use edit_file to modify it.`;
}
try {
// Ensure parent folder exists
const lastSlash = filePath.lastIndexOf("/");
if (lastSlash > 0) {
const folderPath = filePath.substring(0, lastSlash);
const folder = app.vault.getFolderByPath(folderPath);
if (folder === null) {
await app.vault.createFolder(folderPath);
}
}
await app.vault.create(filePath, content);
return `File created at "${filePath}".`;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Unknown error";
return `Error creating file: ${msg}`;
}
}
/**
* Execute the "move_file" tool.
* Moves or renames a file, auto-updating all links.
*/
async function executeMoveFile(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 newPath = typeof args.new_path === "string" ? args.new_path : "";
if (newPath === "") {
return "Error: new_path parameter is required.";
}
const file = app.vault.getAbstractFileByPath(filePath);
if (file === null || !(file instanceof TFile)) {
return `Error: File not found at path "${filePath}".`;
}
// Check if destination already exists
const destExists = app.vault.getAbstractFileByPath(newPath);
if (destExists !== null) {
return `Error: A file or folder already exists at "${newPath}".`;
}
try {
// Ensure target folder exists
const lastSlash = newPath.lastIndexOf("/");
if (lastSlash > 0) {
const folderPath = newPath.substring(0, lastSlash);
const folder = app.vault.getFolderByPath(folderPath);
if (folder === null) {
await app.vault.createFolder(folderPath);
}
}
await app.fileManager.renameFile(file, newPath);
return `File moved from "${filePath}" to "${newPath}". All links have been updated.`;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Unknown error";
return `Error moving 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 : "";
const file = app.vault.getAbstractFileByPath(filePath);
if (file === null || !(file instanceof TFile)) {
return `Error: File not found at path "${filePath}".`;
}
try {
if (oldText === "") {
// Empty old_text: only allowed when the file is empty (write initial content)
let replaced = false;
await app.vault.process(file, (data) => {
if (data.length !== 0) {
return data;
}
replaced = true;
return newText;
});
if (!replaced) {
return `Error: old_text is empty but "${filePath}" is not empty. You must read the file first with read_file and provide the exact text you want to replace as old_text.`;
}
return `Successfully wrote content to empty file "${filePath}".`;
}
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}". Make sure you read the file first with read_file and copy the exact text.`;
}
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. " +
"IMPORTANT: You MUST call read_file on the target file BEFORE calling edit_file so you can see its exact current content. " +
"Copy the exact text you want to change from the read_file output and use it as old_text. " +
"old_text must match a passage in the file exactly (including whitespace and newlines). " +
"Only the first occurrence of old_text is replaced with new_text. " +
"SPECIAL CASE: If the file is empty (read_file returned no content), set old_text to an empty string to write initial content. " +
"If old_text is empty but the file is NOT empty, the edit will be rejected. " +
"The file_path must be an exact path from 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, copied verbatim from read_file output. Include enough surrounding lines to uniquely identify the location. Preserve all whitespace and newlines exactly. Only set to an empty string when the file itself is empty.",
},
new_text: {
type: "string",
description: "The text to replace old_text with. Use an empty string to delete the matched text.",
},
},
},
},
},
execute: executeEditFile,
},
{
id: "grep_search",
label: "Search File Contents",
description: "Search for text across all markdown files in the vault.",
friendlyName: "Search Contents",
requiresApproval: false,
summarize: (args) => {
const query = typeof args.query === "string" ? args.query : "";
const filePattern = typeof args.file_pattern === "string" ? args.file_pattern : "";
const suffix = filePattern !== "" ? ` in "${filePattern}"` : "";
return `"${query}"${suffix}`;
},
summarizeResult: (result) => {
if (result === "No matches found.") {
return "No results found";
}
const lines = result.split("\n").filter((l) => l.length > 0 && !l.startsWith("..."));
const cappedMatch = result.match(/results capped at (\d+)/);
const count = cappedMatch !== null ? `${cappedMatch[1]}+` : `${lines.length}`;
return `${count} match${lines.length === 1 ? "" : "es"} found`;
},
definition: {
type: "function",
function: {
name: "grep_search",
description: "Search for a text string across all markdown file contents in the vault. Returns matching lines with file paths and line numbers (e.g. 'folder/note.md:12: matching line'). Case-insensitive. Optionally filter by file path pattern.",
parameters: {
type: "object",
required: ["query"],
properties: {
query: {
type: "string",
description: "The text to search for in file contents. Case-insensitive.",
},
file_pattern: {
type: "string",
description: "Optional filter: only search files whose path contains this string (e.g. 'journal/' or 'project').",
},
},
},
},
},
execute: executeGrepSearch,
},
{
id: "create_file",
label: "Create File",
description: "Create a new file in the vault (requires approval).",
friendlyName: "Create File",
requiresApproval: true,
approvalMessage: (args) => {
const filePath = typeof args.file_path === "string" ? args.file_path : "unknown";
return `Create "${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 created";
},
definition: {
type: "function",
function: {
name: "create_file",
description: "Create a new file in the Obsidian vault. Parent folders are created automatically if they don't exist. Fails if a file already exists at the path — use edit_file to modify existing files. This action requires user approval.",
parameters: {
type: "object",
required: ["file_path"],
properties: {
file_path: {
type: "string",
description: "The vault-relative path for the new file (e.g. 'folder/new-note.md').",
},
content: {
type: "string",
description: "The text content to write to the new file. Defaults to empty string if not provided.",
},
},
},
},
},
execute: executeCreateFile,
},
{
id: "move_file",
label: "Move/Rename File",
description: "Move or rename a file and auto-update all links (requires approval).",
friendlyName: "Move File",
requiresApproval: true,
approvalMessage: (args) => {
const filePath = typeof args.file_path === "string" ? args.file_path : "unknown";
const newPath = typeof args.new_path === "string" ? args.new_path : "unknown";
return `Move "${filePath}" to "${newPath}"?`;
},
summarize: (args) => {
const filePath = typeof args.file_path === "string" ? args.file_path : "";
const newPath = typeof args.new_path === "string" ? args.new_path : "";
return `"/${filePath}" → "/${newPath}"`;
},
summarizeResult: (result) => {
if (result.startsWith("Error")) {
return result;
}
if (result.includes("declined")) {
return "Declined by user";
}
return "File moved";
},
definition: {
type: "function",
function: {
name: "move_file",
description: "Move or rename a file in the Obsidian vault. All internal links throughout the vault are automatically updated to reflect the new path. Target folders are created automatically if they don't exist. The file_path must be an exact path as returned by search_files. This action requires user approval.",
parameters: {
type: "object",
required: ["file_path", "new_path"],
properties: {
file_path: {
type: "string",
description: "The current vault-relative path of the file (e.g. 'folder/note.md').",
},
new_path: {
type: "string",
description: "The new vault-relative path for the file (e.g. 'new-folder/renamed-note.md').",
},
},
},
},
},
execute: executeMoveFile,
},
];
/**
* 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);
}
|