monothink 0.4.7

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
/*
 * This file is part of monothink.
 *
 * monothink 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.
 *
 * monothink 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 anyhow::{Context, Result};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fs::File, io::Read, path::Path};

const API_KEY_PLACEHOLDER: &str = "<API_KEY>";

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub enum EndpointApi {
    OpenAICompletions,
    #[default]
    OpenAIResponses,
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct Auth {
    pub endpoint: BTreeMap<String, EndpointSecrets>,
    #[serde(default)]
    pub tool: ToolsAuth,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct EndpointSecrets {
    pub api_key: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct ToolsAuth {
    #[serde(rename = "websearch")]
    pub web_search: Option<ToolSecrets>,
    #[serde(default)]
    pub mcp: BTreeMap<String, ToolSecrets>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ToolSecrets {
    pub api_key: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Config {
    pub general: General,
    pub endpoint: BTreeMap<String, Endpoint>,
    #[serde(default)]
    pub model: BTreeMap<String, Model>,
    #[serde(default)]
    pub symbols: Symbols,
    #[serde(default, rename = "tool")]
    pub tools: Tools,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct General {
    pub primary_endpoint: String,
    #[serde(default = "default_max_tokens_per_iteration")]
    pub max_tokens: u64,
    #[serde(default = "default_max_iterations_per_request")]
    pub max_iterations_per_request: usize,
    #[serde(default = "default_max_dir_list_results")]
    pub max_list_dir_results: usize,
    #[serde(default = "default_max_search_text_results")]
    pub max_search_text_results: usize,
    #[serde(default = "default_max_tool_observations")]
    pub max_tool_observations: u64,
    #[serde(default = "default_min_reasoning_observations")]
    pub min_reasoning_observations: u64,
    #[serde(default = "default_view_mode")]
    pub view_mode: ViewMode,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Endpoint {
    pub base_url: String,
    pub default_model: String,
    #[serde(skip)]
    pub secrets: Option<EndpointSecrets>,
    #[serde(default)]
    pub api_type: EndpointApi,
    #[serde(default)]
    pub models: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct McpTool {
    pub url: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Model {
    #[serde(default = "default_context_window")]
    pub context_window: u64,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Tools {
    #[serde(rename = "websearch")]
    pub web_search: Option<WebSearch>,
    #[serde(default)]
    pub mcp: BTreeMap<String, McpTool>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Symbols {
    #[serde(default = "default_assistant_message_symbol")]
    pub assistant_message: String,
    #[serde(default = "default_assistant_reasoning_symbol")]
    pub assistant_reasoning: String,
    #[serde(default = "default_idle_indicator_symbol")]
    pub idle_indicator: String,
    #[serde(default = "default_active_indicator_symbols")]
    pub active_indicators: Vec<String>,
    #[serde(default = "default_tool_message_symbol")]
    pub tool_message: String,
    #[serde(default = "default_message_state_final_symbol")]
    pub message_state_final: String,
    #[serde(default = "default_message_state_intermediate_symbol")]
    pub message_state_intermediate: String,
    #[serde(default = "default_notification_debug_symbol")]
    pub message_notification_debug: String,
    #[serde(default = "default_notification_error_symbol")]
    pub message_notification_error: String,
    #[serde(default = "default_notification_info_symbol")]
    pub message_notification_info: String,
    #[serde(default = "default_notification_warning_symbol")]
    pub message_notification_warning: String,
    #[serde(default = "default_status_failed_symbol")]
    pub status_failed: String,
    #[serde(default = "default_status_success_symbol")]
    pub status_success: String,
    #[serde(default = "default_statusbar_leader_symbol")]
    pub statusbar_leader: String,
    #[serde(default = "default_statusbar_separator_symbol")]
    pub statusbar_separator: String,
    #[serde(default = "default_statusbar_reverse_separator_symbol")]
    pub statusbar_reverse_separator: String,
    #[serde(default = "default_system_message_symbol")]
    pub system_message: String,
    #[serde(default = "default_tokens_input_symbol")]
    pub input_tokens: String,
    #[serde(default = "default_tokens_output_symbol")]
    pub output_tokens: String,
    #[serde(default = "default_user_message_symbol")]
    pub user_message: String,
}

impl Default for Symbols {
    fn default() -> Self {
        Self {
            assistant_message: default_assistant_message_symbol(),
            assistant_reasoning: default_assistant_reasoning_symbol(),
            idle_indicator: default_idle_indicator_symbol(),
            active_indicators: default_active_indicator_symbols(),
            tool_message: default_tool_message_symbol(),
            message_state_final: default_message_state_final_symbol(),
            message_state_intermediate: default_message_state_intermediate_symbol(),
            message_notification_debug: default_notification_debug_symbol(),
            message_notification_error: default_notification_error_symbol(),
            message_notification_info: default_notification_info_symbol(),
            message_notification_warning: default_notification_warning_symbol(),
            system_message: default_system_message_symbol(),
            status_failed: default_status_failed_symbol(),
            status_success: default_status_success_symbol(),
            statusbar_leader: default_statusbar_leader_symbol(),
            statusbar_separator: default_statusbar_separator_symbol(),
            statusbar_reverse_separator: default_statusbar_reverse_separator_symbol(),
            input_tokens: default_tokens_input_symbol(),
            output_tokens: default_tokens_output_symbol(),
            user_message: default_user_message_symbol(),
        }
    }
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum ViewMode {
    /// show everything (incl. debug system messages intended for developers)
    Debug,
    /// show everything
    Full,

    /// show collapsed tool calls, reasoning and all user and assistant messages
    Detailed,

    /// show collapesed tool calls and all user and final assistant messages
    Compact,

    /// only show user and final assistant messages
    Minimal,
}

impl Default for ViewMode {
    fn default() -> Self {
        default_view_mode()
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebSearch {
    pub provider: WebSearchProvider,
    pub url: String,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum WebSearchProvider {
    //    Exa,
    //    Perplexity,
    SearXNG,
    Tavily,
}

impl WebSearchProvider {
    pub fn display_string(&self) -> String {
        match self {
            //WebSearchProvider::Exa => "Exa".to_string(),
            //WebSearchProvider::Perplexity => "Perplexity".to_string(),
            WebSearchProvider::SearXNG => "SearXNG".to_string(),
            WebSearchProvider::Tavily => "Tavily".to_string(),
        }
    }
}

pub fn default_assistant_message_symbol() -> String {
    "🤖".to_string()
}

pub fn default_assistant_reasoning_symbol() -> String {
    "💭".to_string()
}

// emoji: 🟢
pub fn default_idle_indicator_symbol() -> String {
    "●".to_string()
}

// ideas for alternative configs:
// minimal (black hourglass & black bowtie): active_indicators = ["⧗", "⧓"]
// snake via braille: active_indicators = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
// watch emoji: active_indicators = ["🕛", "🕐", "🕒", "🕓", "🕕", "🕖", "🕙", "🕘"]
// spinning half-circle: active_indicators = ["◐", "◓", "◑", "◒"]
// progress bar: active_indicators = ["▏  ", "▎  ", "▍  ", "▌  ", "▋  ", "▊  ", "▉  ", "█  ", "█▏ ", "█▎ ", "█▍ ", "█▌ ", "█▋ ", "█▊ ", "█▉ ", "██ ", "██▏", "██▎", "██▍", "██▌", "██▋", "██▊", "██▉", "███"]
// fade in: active_indicators = [" ", "░", "▒", "▓", "█", "▓", "▒"]
pub fn default_active_indicator_symbols() -> Vec<String> {
    vec![
        "⠋".to_string(),
        "⠙".to_string(),
        "⠹".to_string(),
        "⠸".to_string(),
        "⠼".to_string(),
        "⠴".to_string(),
        "⠦".to_string(),
        "⠧".to_string(),
        "⠇".to_string(),
        "⠏".to_string(),
    ]
}

pub fn default_context_window() -> u64 {
    128000
}

pub fn default_max_tokens_per_iteration() -> u64 {
    16000
}

fn default_max_iterations_per_request() -> usize {
    40
}

fn default_max_dir_list_results() -> usize {
    100
}

fn default_max_search_text_results() -> usize {
    100
}

fn default_max_tool_observations() -> u64 {
    5
}

fn default_min_reasoning_observations() -> u64 {
    10
}

pub fn default_message_state_final_symbol() -> String {
    "✅".to_string()
}

pub fn default_message_state_intermediate_symbol() -> String {
    "🕝".to_string()
}

pub fn default_notification_debug_symbol() -> String {
    "🪲".to_string()
}

pub fn default_notification_error_symbol() -> String {
    "🛑".to_string()
}

pub fn default_notification_info_symbol() -> String {
    "ℹ️".to_string()
}

pub fn default_notification_warning_symbol() -> String {
    "⚠️".to_string()
}

pub fn default_tool_message_symbol() -> String {
    "🔧".to_string()
}

pub fn default_status_failed_symbol() -> String {
    "❌".to_string()
}

pub fn default_status_success_symbol() -> String {
    "✅".to_string()
}

pub fn default_statusbar_leader_symbol() -> String {
    "".to_string()
}

pub fn default_statusbar_separator_symbol() -> String {
    "".to_string()
}

pub fn default_statusbar_reverse_separator_symbol() -> String {
    "".to_string()
}

pub fn default_system_message_symbol() -> String {
    "⚙️".to_string()
}

pub fn default_tokens_input_symbol() -> String {
    "⇑".to_string()
}

pub fn default_tokens_output_symbol() -> String {
    "⇓".to_string()
}

pub fn default_user_message_symbol() -> String {
    "🧑‍💻".to_string()
}

// use compact as default as it is not straining for the user while providing most information
// It is easy to switch modes at runtime if more insight is needed
fn default_view_mode() -> ViewMode {
    ViewMode::Compact
}

// @todo overall, make error nicer using with_message (e.g. which file was not found or which value was expected?)
// load config and secrets
pub fn load_config() -> Result<Config> {
    // load config from default path
    if let Some(proj_dirs) = ProjectDirs::from("org", "codemonk", "monothink") {
        let config_dir = proj_dirs.config_dir().to_path_buf();

        let mut config_file_dir = config_dir.clone();
        config_file_dir.push("config.toml");
        let config_file_path = config_file_dir.as_path();

        let mut auth_file_dir = config_dir.clone();
        auth_file_dir.push("auth.toml");
        let auth_file_path = auth_file_dir.as_path();

        let mut config = parse_config(config_file_path).with_context(|| {
            format!(
                "Error while parsing config file '{}'.",
                config_file_path.to_string_lossy()
            )
        })?;
        let auth = parse_auth(auth_file_path).with_context(|| {
            format!(
                "Error while parsing auth file '{}'.",
                auth_file_path.to_string_lossy()
            )
        })?;
        merge_config_with_auth(&mut config, &auth);

        Ok(config)
    } else {
        panic!("Could not retrieve a valid home directory from the operating system.");
    }
}

fn merge_config_with_auth(config: &mut Config, auth: &Auth) {
    for (key, val) in &auth.endpoint {
        if let Some(endpoint) = config.endpoint.get_mut(key) {
            endpoint.secrets = Some(val.to_owned());
        } else {
            // @todo if a key has no matching endpoint, print a warning
        }
        // @todo if a key is missing for a endpoint, print a warning
        // for this iterate over all endpoints in check if secrets is none after merge
    }

    if let Some(tool) = &mut config.tools.web_search {
        if let Some(api_key) = &auth
            .tool
            .web_search
            .as_ref()
            .and_then(|secrets| secrets.api_key.clone())
            && tool.url.contains(API_KEY_PLACEHOLDER)
        {
            tool.url = tool.url.replace(API_KEY_PLACEHOLDER, api_key);
        } else if tool.url.contains(API_KEY_PLACEHOLDER) {
            // @todo issue warning
            println!("Missing API key for web search. Web search not enabled.");
        }
    }

    for (key, val) in &auth.tool.mcp {
        if let Some(mcp_tool) = config.tools.mcp.get_mut(key) {
            if let Some(api_key) = &val.api_key {
                mcp_tool.url = mcp_tool.url.replace(API_KEY_PLACEHOLDER, api_key);
            } else {
                // @todo issue a warning about missing api key for placeholder (if placeholder exists)
            }
        } else {
            // @todo if a key has no matching mcp_tool, print a warning
        }
        // @todo if a key is missing for a mcp_tool, print a warning
        // for this iterate over all mcp_tools in check if secrets is none after merge
    }
}

fn parse_auth(path: &Path) -> Result<Auth> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    let auth: Auth = toml::from_str(&contents)?;
    // @todo if it fails, print an example
    Ok(auth)
}

fn parse_config(path: &Path) -> Result<Config> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    let config: Config = toml::from_str(&contents)?;
    // @todo if it fails, print an example
    Ok(config)
}