monothink 0.1.1

A totally non-agentic coding assistant
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
/*
* This file is part of monothink.
*
* Wavething is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* Wavething is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Wavething.
* If not, see <https://www.gnu.org/licenses/>.

*/

use rig::tool::{Tool, ToolContext};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
    env,
    fs::{self, read_to_string},
    io::{Error, ErrorKind},
    path::{Path, PathBuf},
};

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
enum DirectoryEntryKind {
    File,
    Directory,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct DirectoryEntry {
    path: String,
    kind: DirectoryEntryKind,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DirectoryListing {
    entries: Vec<DirectoryEntry>,
    total_entries: usize,
    truncated: bool,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct Location {
    path: PathBuf,
    line: usize,
    //column: u32,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct Range {
    path: PathBuf,
    start: usize,
    end: usize,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct SearchMatch {
    location: Location,
    preview: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SearchResults {
    total_entries: usize,
    returned_entries: usize,
    truncated: bool,
    entries: Vec<SearchMatch>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FileContent {
    range: Range,
    content: String,
}

#[derive(Deserialize, Serialize)]
pub struct ListDirArgs {
    path: PathBuf,
    // recursive: Option<bool>,
    start: Option<usize>,
}

#[derive(Deserialize, Serialize)]
pub struct ListDir {
    base_dir: PathBuf,
    max_results: usize,
}

// @todo check access rights (i.e. calculated path must be below base_dir)
impl ListDir {
    pub fn new(base_dir: &Path, max_results: usize) -> Self {
        Self {
            base_dir: base_dir.to_path_buf(),
            max_results,
        }
    }
}
impl Tool for ListDir {
    const NAME: &'static str = "list_dir";

    type Error = std::io::Error;
    type Args = ListDirArgs;
    type Output = DirectoryListing;

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        let path = allowed_canonical_path(&args.path, &self.base_dir)?;
        // list_dir(&path, args.recursive.unwrap_or(false))
        list_dir(&path, false)
        // @todo clip long lists but preserve total entries (add actual entries as info)
    }

    fn description(&self) -> String {
        // "List the files and directory of the given directory (relative to project root) and optionally its subdirectories"
        //
        format!(
            "List the files and directories in the given directory (relative to project root), \
      returning at most {} entries. Use an empty string \"\" for the project root. \
      Results include both files and subdirectories with their types.",
            self.max_results
        )
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the directory relative to project root directory. \
                     Use an empty string for the root directory."
                },
                "start": {
                    "type": "integer",
                    "description": "Optional, zero-based index of the first result to return. \
                    Use this to paginate through results if a previous call was truncated."
                },
            },
            "required": ["path"]
        })
    }
}

#[derive(Deserialize, Serialize)]
pub struct ReadFileArgs {
    path: PathBuf,
    start: Option<usize>,
    end: Option<usize>,
}

#[derive(Deserialize, Serialize)]
pub struct ReadFile {
    base_dir: PathBuf,
}

impl ReadFile {
    pub fn new(base_dir: &Path) -> Self {
        Self {
            base_dir: base_dir.to_path_buf(),
        }
    }
}

// @todo check access rights (i.e. calculated path must be below base_dir)
impl Tool for ReadFile {
    const NAME: &'static str = "read_file";

    type Error = std::io::Error;
    type Args = ReadFileArgs;
    type Output = FileContent;

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        let path = allowed_canonical_path(&args.path, &self.base_dir)?;
        let content: Vec<String> = fs::read_to_string(path)?
            .lines()
            .map(|line| line.to_string())
            .collect();

        let mut start = match args.start {
            Some(v) => v.saturating_sub(1),
            None => 0,
        };
        let mut end = match args.end {
            Some(v) => {
                if v > 0 {
                    v // we do not substract to convert from one-based to zero-based because the line shall be included which it isn't for slicing
                } else {
                    1 // LLMs like to provide 0 or -1 for end of file, we do not support -1 but can support 0
                }
            }
            None => content.len(),
        };
        if end > content.len() {
            end = content.len();
        }
        if start > end {
            start = end;
        };

        let extract = &content[start..end].join("\n");

        // @todo clip large files
        Ok(FileContent {
            range: Range {
                path: args.path,
                start: start + 1,
                end: end + 1,
            },
            content: extract.to_owned(),
        })
    }

    fn description(&self) -> String {
        "Read the content of a file, optionally specifying a line range. \
            Lines are 1-indexed and inclusive. \
            If no range is specified, the entire file is returned."
            .to_string()
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the file relative to project root directory"
                },
                "start": {
                    "type": "integer",
                    "description": "First line number to read (1-indexed, inclusive). \
                    If not provided, reads from the beginning of the file."
                },
                "end": {
                    "type": "integer",
                    "description": "Last line number to read (1-indexed, inclusive). \
                    If not provided, reads to the end of the file. \
                      If end exceeds the file length, reads until the end."
                }
            },
            "required": ["path"]
        })
    }

    fn map_error(&self, error: Self::Error) -> rig::tool::ToolExecutionError {
        rig::tool::ToolExecutionError::from_error(error)
    }
}

#[derive(Deserialize, Serialize)]
pub struct SearchTextArgs {
    path: PathBuf,
    text: String,
    start: Option<usize>,
}

#[derive(Deserialize, Serialize)]
pub struct SearchText {
    base_dir: PathBuf,
    max_results: usize,
}

// @todo check access rights (i.e. calculated path must be below base_dir)
impl SearchText {
    pub fn new(base_dir: &Path, max_results: usize) -> Self {
        Self {
            base_dir: base_dir.to_path_buf(),
            max_results,
        }
    }
}
impl Tool for SearchText {
    const NAME: &'static str = "search_text";

    type Error = std::io::Error;
    type Args = SearchTextArgs;
    type Output = SearchResults;

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        let path = allowed_canonical_path(&args.path, &self.base_dir)?;
        let entries = list_dir(&path, true)?;
        let matches: Vec<SearchMatch> = entries
            .entries
            .iter()
            // filter files
            .filter_map(|e| match e.kind {
                DirectoryEntryKind::File => {
                    read_to_string(&e.path).ok().map(|v| (e.path.clone(), v))
                }
                DirectoryEntryKind::Directory => None,
            })
            // map to lines that contain the searched text
            .map(|(path, content)| {
                (
                    path,
                    content
                        .lines()
                        .enumerate()
                        .filter(|(_nr, line)| line.contains(&args.text))
                        .map(|(nr, line)| (nr, line.to_owned()))
                        .collect::<Vec<(usize, String)>>(),
                )
            })
            // filter files containing the match
            .filter(|(_path, content)| !content.is_empty())
            // map to search matches
            .flat_map(|(path, content)| {
                content
                    .iter()
                    .map(move |(nr, line)| SearchMatch {
                        location: Location {
                            path: PathBuf::from(path.clone()),
                            line: *nr,
                        },
                        preview: line.clone(),
                    })
                    .collect::<Vec<_>>()
            })
            .collect();

        // clip
        let start = args.start.unwrap_or_default();
        let requested_matches = &matches[start..];
        let final_matches = if requested_matches.len() > 100 {
            &requested_matches[..100]
        } else {
            requested_matches
        };
        Ok(SearchResults {
            total_entries: matches.len(),
            returned_entries: final_matches.len(),
            truncated: final_matches.len() != matches.len(),
            entries: final_matches.to_vec(),
        })
    }

    fn description(&self) -> String {
        format!(
            "Search for text in all files within the given directory and its subdirectories. \
      Returns matches with file paths, line numbers, and content previews. \
      The search is case-sensitive. Results are clipped at {} entries.",
            self.max_results
        )
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the directory to search in, \
                    relative to project root directory. \
                    Use an empty string for the root directory. \
                    Search is recursive."
                },
                "text": {
                    "type": "string",
                    "description": "The exact text string to search for. \
                    The search is case-sensitive."
                },
                "start": {
                    "type": "integer",
                    "description": "Optional, zero-based index of the first result to return. \
                    Use this to paginate through results if a previous call was truncated."
                },
            },
            "required": ["path", "text"]
        })
    }
}

// path is absolute
fn list_dir(path: &Path, recursive: bool) -> Result<DirectoryListing, std::io::Error> {
    let mut result = DirectoryListing {
        entries: Vec::new(),
        total_entries: 0,
        truncated: false,
    };
    let mut backlog = vec![path.to_path_buf()];

    while let Some(dir) = backlog.pop() {
        let paths = fs::read_dir(dir)?; // @todo this is brickle, because it also includes permission denied errors, we should log the error and go on

        for entry in paths.flatten() {
            if entry.path().is_dir() {
                if recursive {
                    backlog.push(entry.path());
                }
                result.entries.push(DirectoryEntry {
                    path: entry.path().to_string_lossy().to_string(),
                    kind: DirectoryEntryKind::Directory,
                });
            } else {
                result.entries.push(DirectoryEntry {
                    path: entry.path().to_string_lossy().to_string(),
                    kind: DirectoryEntryKind::File,
                });
            }
        }
    }

    result.total_entries = result.entries.len();

    Ok(result)
}

fn allowed_canonical_path(path_string: &Path, base_dir: &Path) -> Result<PathBuf, std::io::Error> {
    // let path_string = if path_string.is_empty() {
    //     "."
    // } else {
    //     path_string
    // };

    let canonical_base = base_dir.canonicalize()?;
    let path = base_dir.join(path_string).canonicalize()?;

    if path.starts_with(canonical_base) {
        Ok(path)
    } else {
        Err(Error::new(
            ErrorKind::PermissionDenied,
            "Path must be subpath of project root",
        ))
    }
}

#[tokio::test]
async fn test_list_dir() {
    // fake test to just read the current dir
    let base_dir = env::current_dir().expect("Cannot get current directory");
    let ld = ListDir::new(&base_dir, 100);
    let result = ld
        .call(
            &mut ToolContext::default(),
            ListDirArgs {
                path: PathBuf::from(""),
                // recursive: Some(true),
                start: None,
            },
        )
        .await
        .unwrap();
    println!("Result: {:?}", result.total_entries);
}

#[tokio::test]
async fn test_read_file() {
    // fake test to just see the output
    // Should output the GPLv3 license header of main.rs
    let base_dir = env::current_dir().expect("Cannot get current directory");
    let ld = ReadFile::new(&base_dir);
    let result = ld
        .call(
            &mut ToolContext::default(),
            ReadFileArgs {
                path: PathBuf::from("src/main.rs"),
                start: Some(1),
                end: Some(14),
            },
        )
        .await
        .unwrap();
    println!("Result: {:?}", result);
}

#[tokio::test]
async fn test_search_text() {
    // fake test to just see the serch results
    let base_dir = env::current_dir().expect("Cannot get current directory");
    let ld = SearchText::new(&base_dir, 100);
    let result = ld
        .call(
            &mut ToolContext::default(),
            SearchTextArgs {
                path: PathBuf::from("src"),
                text: "unwrap()".to_string(),
                start: None,
            },
        )
        .await
        .unwrap();
    println!("Result: {:?}", result);
}