chabeau 0.7.1

A full-screen terminal chat interface that connects to various AI APIs for real-time conversations
Documentation
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
use super::CommandResult;
use crate::core::app::App;
use std::collections::HashMap;
use std::fmt;
use std::sync::LazyLock;

/// Function pointer used by the registry to invoke a command implementation.
///
/// Command handlers receive the shared [`App`] state plus the parsed
/// [`CommandInvocation`].
pub type CommandHandler = fn(&mut App, CommandInvocation<'_>) -> CommandResult;

/// One usage line that can be surfaced in command help.
pub struct CommandUsage {
    pub syntax: &'static str,
    pub description: &'static str,
}

/// Metadata describing a single slash command.
pub struct Command {
    pub name: &'static str,
    pub usages: &'static [CommandUsage],
    pub extra_help: &'static [&'static str],
    pub handler: CommandHandler,
}

/// Parsed view of a command input string, produced by `CommandRegistry::dispatch`.
///
/// An invocation carries the original input (sans leading slash), the arguments as
/// contiguous text, and a cached token list for handlers that prefer positional
/// access.
pub struct CommandInvocation<'a> {
    pub command: &'static Command,
    pub input: &'a str,
    args: &'a str,
    tokens: Vec<&'a str>,
}

impl<'a> fmt::Debug for CommandInvocation<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CommandInvocation")
            .field("command", &self.command.name)
            .field("input", &self.input)
            .field("args", &self.args)
            .field("tokens", &self.tokens)
            .finish()
    }
}

impl<'a> CommandInvocation<'a> {
    /// Returns the raw argument substring after the command name.
    pub fn args_text(&self) -> &'a str {
        self.args
    }

    #[cfg(test)]
    /// Returns an iterator over whitespace-delimited argument tokens.
    pub fn args_iter(&'a self) -> impl Iterator<Item = &'a str> + 'a {
        self.tokens.iter().copied()
    }

    /// Returns the number of whitespace-delimited tokens in the invocation.
    pub fn args_len(&self) -> usize {
        self.tokens.len()
    }

    /// Returns the `index`th argument token if it exists.
    pub fn arg(&self, index: usize) -> Option<&'a str> {
        self.tokens.get(index).copied()
    }

    /// Maps the first argument onto a toggle intent. If no argument is provided
    /// the command toggles its state; otherwise the handler must pass a known
    /// literal such as `on`, `off`, or `toggle`.
    pub fn toggle_action(&self) -> Result<ToggleAction, ToggleError<'a>> {
        match self.arg(0) {
            None => Ok(ToggleAction::Toggle),
            Some(arg) if arg.eq_ignore_ascii_case("toggle") => Ok(ToggleAction::Toggle),
            Some(arg) if arg.eq_ignore_ascii_case("on") => Ok(ToggleAction::Enable),
            Some(arg) if arg.eq_ignore_ascii_case("off") => Ok(ToggleAction::Disable),
            Some(arg) => Err(ToggleError::InvalidValue(arg)),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ToggleAction {
    Enable,
    Disable,
    Toggle,
}

impl ToggleAction {
    pub fn apply(self, current: bool) -> bool {
        match self {
            ToggleAction::Enable => true,
            ToggleAction::Disable => false,
            ToggleAction::Toggle => !current,
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum ToggleError<'a> {
    InvalidValue(&'a str),
}

#[derive(Debug)]
/// Result of attempting to dispatch an input string through the registry.
pub enum DispatchOutcome<'a> {
    Invocation(CommandInvocation<'a>),
    NotACommand,
    UnknownCommand,
}

/// Central registry that owns the statically-defined command table and handles
/// parsing/dispatch.
pub struct CommandRegistry {
    commands: &'static [Command],
    lookup: HashMap<String, usize>,
}

impl CommandRegistry {
    /// Builds a registry for the statically-declared command table.
    pub fn new() -> Self {
        let mut lookup = HashMap::new();
        for (index, command) in COMMANDS.iter().enumerate() {
            lookup.insert(command.name.to_ascii_lowercase(), index);
        }
        Self {
            commands: COMMANDS,
            lookup,
        }
    }

    /// Returns every command known to the registry.
    pub fn all(&self) -> &'static [Command] {
        self.commands
    }

    /// Looks up a command by name using case-insensitive matching.
    pub fn find(&self, name: &str) -> Option<&'static Command> {
        let key = name.to_ascii_lowercase();
        self.lookup
            .get(&key)
            .and_then(|index| self.commands.get(*index))
    }

    /// Returns commands whose names share the provided prefix (case-insensitive).
    pub fn matching(&self, prefix: &str) -> Vec<&'static Command> {
        let lower_prefix = prefix.to_ascii_lowercase();
        self.commands
            .iter()
            .filter(|command| {
                if lower_prefix.is_empty() {
                    true
                } else {
                    command.name.to_ascii_lowercase().starts_with(&lower_prefix)
                }
            })
            .collect()
    }

    /// Parses an input line once, splitting the command name from its arguments.
    ///
    /// Handlers receive a [`CommandInvocation`] that exposes cached argument
    /// tokens, allowing them to focus on business logic instead of parsing.
    pub fn dispatch<'a>(&'static self, input: &'a str) -> DispatchOutcome<'a> {
        let trimmed = input.trim();
        if !trimmed.starts_with('/') {
            return DispatchOutcome::NotACommand;
        }

        let body = trimmed[1..].trim();
        if body.is_empty() {
            return DispatchOutcome::UnknownCommand;
        }

        let (name, args) = match body.split_once(char::is_whitespace) {
            Some((name, rest)) => (name, rest.trim()),
            None => (body, ""),
        };

        let command = match self.find(name) {
            Some(cmd) => cmd,
            None => return DispatchOutcome::UnknownCommand,
        };

        let tokens: Vec<&'a str> = if args.is_empty() {
            Vec::new()
        } else {
            args.split_whitespace().collect()
        };

        DispatchOutcome::Invocation(CommandInvocation {
            command,
            input: trimmed,
            args,
            tokens,
        })
    }
}

static REGISTRY: LazyLock<CommandRegistry> = LazyLock::new(CommandRegistry::new);

/// Provides read-only access to the registered command metadata.
pub fn all_commands() -> &'static [Command] {
    REGISTRY.all()
}

#[cfg(test)]
pub fn find_command(name: &str) -> Option<&'static Command> {
    REGISTRY.find(name)
}

/// Returns commands whose names share the provided prefix.
pub fn matching_commands(prefix: &str) -> Vec<&'static Command> {
    REGISTRY.matching(prefix)
}

/// Exposes the lazily-initialised registry singleton for direct queries.
pub fn registry() -> &'static CommandRegistry {
    &REGISTRY
}

const COMMANDS: &[Command] = &[
    Command {
        name: "help",
        usages: &[CommandUsage {
            syntax: "/help",
            description: "Show available commands and usage information.",
        }],
        extra_help: &[],
        handler: super::handlers::core::handle_help,
    },
    Command {
        name: "clear",
        usages: &[CommandUsage {
            syntax: "/clear",
            description: "Clear the conversation transcript.",
        }],
        extra_help: &[],
        handler: super::handlers::core::handle_clear,
    },
    Command {
        name: "mcp",
        usages: &[
            CommandUsage {
                syntax: "/mcp",
                description: "List configured MCP servers.",
            },
            CommandUsage {
                syntax: "/mcp <server-id>",
                description: "List MCP tools, resources, templates, and prompts.",
            },
            CommandUsage {
                syntax: "/mcp <server-id> on",
                description: "Enable an MCP server and persist to config.toml.",
            },
            CommandUsage {
                syntax: "/mcp <server-id> off",
                description: "Disable an MCP server and persist to config.toml.",
            },
            CommandUsage {
                syntax: "/mcp <server-id> forget",
                description: "Clear cached MCP data for a server.",
            },
        ],
        extra_help: &[],
        handler: super::handlers::mcp::handle_mcp,
    },
    Command {
        name: "yolo",
        usages: &[
            CommandUsage {
                syntax: "/yolo <server-id>",
                description: "Show MCP YOLO mode for a server.",
            },
            CommandUsage {
                syntax: "/yolo <server-id> on",
                description: "Enable MCP YOLO mode for a server.",
            },
            CommandUsage {
                syntax: "/yolo <server-id> off",
                description: "Disable MCP YOLO mode for a server.",
            },
        ],
        extra_help: &[],
        handler: super::handlers::mcp::handle_yolo,
    },
    Command {
        name: "log",
        usages: &[CommandUsage {
            syntax: "/log [filename]",
            description:
                "Enable logging to a file, or toggle pause/resume when no filename is provided.",
        }],
        extra_help: &[],
        handler: super::handlers::io::handle_log,
    },
    Command {
        name: "dump",
        usages: &[CommandUsage {
            syntax: "/dump [filename]",
            description:
                "Dump the full conversation to a file (default: `chabeau-log-YYYY-MM-DD.txt`).",
        }],
        extra_help: &[],
        handler: super::handlers::io::handle_dump,
    },
    Command {
        name: "theme",
        usages: &[
            CommandUsage {
                syntax: "/theme",
                description:
                    "Pick a theme (built-in or custom) with filtering and sorting options.",
            },
            CommandUsage {
                syntax: "/theme <id>",
                description: "Apply a theme by id and persist the selection to config.",
            },
        ],
        extra_help: &[],
        handler: super::handlers::config::handle_theme,
    },
    Command {
        name: "model",
        usages: &[
            CommandUsage {
                syntax: "/model",
                description:
                    "Pick a model from the current provider with filtering, sorting, and metadata.",
            },
            CommandUsage {
                syntax: "/model <id>",
                description: "Switch to the specified model for this session only.",
            },
        ],
        extra_help: &[],
        handler: super::handlers::config::handle_model,
    },
    Command {
        name: "provider",
        usages: &[
            CommandUsage {
                syntax: "/provider",
                description: "Pick a provider with filtering and sorting.",
            },
            CommandUsage {
                syntax: "/provider <id>",
                description: "Switch to the specified provider for this session only.",
            },
        ],
        extra_help: &[],
        handler: super::handlers::config::handle_provider,
    },
    Command {
        name: "markdown",
        usages: &[CommandUsage {
            syntax: "/markdown [on|off|toggle]",
            description: "Toggle Markdown rendering and persist the preference to config.",
        }],
        extra_help: &[],
        handler: super::handlers::config::handle_markdown,
    },
    Command {
        name: "syntax",
        usages: &[CommandUsage {
            syntax: "/syntax [on|off|toggle]",
            description: "Toggle code syntax highlighting and persist the preference to config.",
        }],
        extra_help: &[],
        handler: super::handlers::config::handle_syntax,
    },
    Command {
        name: "character",
        usages: &[
            CommandUsage {
                syntax: "/character",
                description:
                    "Pick a character card from available cards with filtering and sorting.",
            },
            CommandUsage {
                syntax: "/character <name>",
                description: "Load the specified character card for this session.",
            },
        ],
        extra_help: &[],
        handler: super::handlers::config::handle_character,
    },
    Command {
        name: "persona",
        usages: &[
            CommandUsage {
                syntax: "/persona",
                description: "Pick a persona from available personas with filtering and sorting.",
            },
            CommandUsage {
                syntax: "/persona <id>",
                description: "Activate the specified persona for this session.",
            },
        ],
        extra_help: &[],
        handler: super::handlers::config::handle_persona,
    },
    Command {
        name: "preset",
        usages: &[
            CommandUsage {
                syntax: "/preset",
                description: "Pick a preset from available presets with filtering and sorting.",
            },
            CommandUsage {
                syntax: "/preset <id>",
                description: "Activate the specified preset for this session.",
            },
        ],
        extra_help: &[],
        handler: super::handlers::config::handle_preset,
    },
    Command {
        name: "refine",
        usages: &[CommandUsage {
            syntax: "/refine <prompt>",
            description: "Refine the previous response with new instructions.",
        }],
        extra_help: &[],
        handler: super::refine::handle_refine,
    },
];