claudius 0.26.0

SDK for the Anthropic API
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
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
//! Slash command parsing for the chat application.
//!
//! This module handles parsing of special commands that start with `/`,
//! allowing users to control the chat session without sending messages
//! to the API.

/// A parsed chat command.
///
/// These commands control the chat session and are not sent to the API.
#[derive(Debug, Clone, PartialEq)]
pub enum ChatCommand {
    /// Clear the conversation history.
    Clear,

    /// Change the model.
    Model(String),

    /// Set or clear the system prompt.
    /// `None` clears the current system prompt.
    System(Option<String>),

    /// Set the maximum tokens per response.
    MaxTokens(u32),

    /// Set the sampling temperature.
    Temperature(f32),

    /// Clear the sampling temperature (use model default).
    ClearTemperature,

    /// Set the top-p value.
    TopP(f32),

    /// Clear the top-p value.
    ClearTopP,

    /// Set the top-k value.
    TopK(u32),

    /// Clear the top-k value.
    ClearTopK,

    /// Add a stop sequence.
    AddStopSequence(String),

    /// Clear all stop sequences.
    ClearStopSequences,

    /// List stop sequences.
    ListStopSequences,

    /// Configure extended thinking.
    /// `None` disables thinking, `Some(budget)` enables with the given token budget.
    Thinking(Option<u32>),

    /// Set a per-session token budget.
    Budget(u64),

    /// Clear the token budget.
    ClearBudget,

    /// Enable or disable prompt caching.
    Caching(bool),

    /// Set the auto-save transcript path.
    TranscriptPath(String),

    /// Clear the auto-save transcript path.
    ClearTranscriptPath,

    /// Save the transcript to a specific file immediately.
    SaveTranscript(String),

    /// Load conversation history from a file.
    LoadTranscript(String),

    /// Display help information.
    Help,

    /// Exit the chat application.
    Quit,

    /// Display session statistics (message count, current model, etc.).
    Stats,

    /// Show the current configuration.
    ShowConfig,

    /// Report a parsing error back to the caller.
    Invalid(String),
}

/// Parses user input for slash commands.
///
/// Returns `Some(ChatCommand)` if the input is a valid command,
/// or `None` if it should be treated as a regular message.
///
/// # Examples
///
/// ```
/// # use claudius::chat::parse_command;
/// assert!(parse_command("/quit").is_some());
/// assert!(parse_command("/model claude-sonnet-4-0").is_some());
/// assert!(parse_command("Hello, Claude!").is_none());
/// ```
pub fn parse_command(input: &str) -> Option<ChatCommand> {
    let input = input.trim();

    if !input.starts_with('/') {
        return None;
    }

    let mut parts = input[1..].splitn(2, ' ');
    let command = parts.next()?.to_lowercase();
    let argument = parts.next().map(|s| s.trim()).filter(|s| !s.is_empty());

    let result = match command.as_str() {
        "clear" => ChatCommand::Clear,
        "model" => match argument {
            Some(model) => ChatCommand::Model(model.to_string()),
            None => ChatCommand::Invalid("/model requires a model name".to_string()),
        },
        "system" => ChatCommand::System(argument.map(|s| s.to_string())),
        "help" | "?" => ChatCommand::Help,
        "quit" | "exit" | "q" => ChatCommand::Quit,
        "stats" | "status" => ChatCommand::Stats,
        "config" => ChatCommand::ShowConfig,
        "max_tokens" => parse_u32_command(argument, ChatCommand::MaxTokens, "/max_tokens"),
        "temperature" => match argument {
            Some(arg) if arg.eq_ignore_ascii_case("clear") => ChatCommand::ClearTemperature,
            Some(arg) => match parse_f32_in_range(arg, 0.0, 1.0) {
                Ok(value) => ChatCommand::Temperature(value),
                Err(err) => ChatCommand::Invalid(format!("/temperature {err}")),
            },
            None => ChatCommand::Invalid("/temperature requires a value".to_string()),
        },
        "top_p" => match argument {
            Some(arg) if arg.eq_ignore_ascii_case("clear") => ChatCommand::ClearTopP,
            Some(arg) => match parse_f32_in_range(arg, 0.0, 1.0) {
                Ok(value) => ChatCommand::TopP(value),
                Err(err) => ChatCommand::Invalid(format!("/top_p {err}")),
            },
            None => ChatCommand::Invalid("/top_p requires a value".to_string()),
        },
        "top_k" => match argument {
            Some(arg) if arg.eq_ignore_ascii_case("clear") => ChatCommand::ClearTopK,
            Some(arg) => match arg.parse::<u32>() {
                Ok(value) => ChatCommand::TopK(value),
                Err(_) => ChatCommand::Invalid("/top_k expects a positive integer".to_string()),
            },
            None => ChatCommand::Invalid("/top_k requires a value".to_string()),
        },
        "stop" => parse_stop_command(argument),
        "thinking" => parse_thinking_command(argument),
        "budget" => match argument {
            Some(arg) if arg.eq_ignore_ascii_case("clear") => ChatCommand::ClearBudget,
            Some(arg) => match arg.parse::<u64>() {
                Ok(value) => ChatCommand::Budget(value),
                Err(_) => {
                    ChatCommand::Invalid("/budget expects an integer token count".to_string())
                }
            },
            None => ChatCommand::Invalid("/budget requires a value".to_string()),
        },
        "cache" => parse_cache_command(argument),
        "transcript" => match argument {
            Some(arg) if arg.eq_ignore_ascii_case("clear") => ChatCommand::ClearTranscriptPath,
            Some(arg) => ChatCommand::TranscriptPath(arg.to_string()),
            None => ChatCommand::Invalid("/transcript requires a file path".to_string()),
        },
        "save" => match argument {
            Some(arg) => ChatCommand::SaveTranscript(arg.to_string()),
            None => ChatCommand::Invalid("/save requires a file path".to_string()),
        },
        "load" => match argument {
            Some(arg) => ChatCommand::LoadTranscript(arg.to_string()),
            None => ChatCommand::Invalid("/load requires a file path".to_string()),
        },
        _ => ChatCommand::Invalid(format!("Unknown command: /{}", command)),
    };

    Some(result)
}

fn parse_stop_command(argument: Option<&str>) -> ChatCommand {
    let Some(arg) = argument else {
        return ChatCommand::Invalid(
            "/stop requires 'add <sequence>', 'clear', or 'list'".to_string(),
        );
    };

    let mut parts = arg.splitn(2, ' ');
    let action = parts.next().unwrap();
    match action.to_lowercase().as_str() {
        "add" => {
            let Some(sequence) = parts.next().map(|s| s.trim()).filter(|s| !s.is_empty()) else {
                return ChatCommand::Invalid("/stop add requires a sequence".to_string());
            };
            ChatCommand::AddStopSequence(sequence.to_string())
        }
        "clear" => ChatCommand::ClearStopSequences,
        "list" => ChatCommand::ListStopSequences,
        _ => {
            ChatCommand::Invalid("Unrecognized /stop action (use add, clear, or list)".to_string())
        }
    }
}

fn parse_u32_command<F>(argument: Option<&str>, constructor: F, name: &str) -> ChatCommand
where
    F: Fn(u32) -> ChatCommand,
{
    match argument {
        Some(arg) => match arg.parse::<u32>() {
            Ok(value) => constructor(value),
            Err(_) => ChatCommand::Invalid(format!("{} expects a positive integer", name)),
        },
        None => ChatCommand::Invalid(format!("{} requires a value", name)),
    }
}

fn parse_f32_in_range(value: &str, min: f32, max: f32) -> Result<f32, String> {
    let parsed: f32 = value
        .parse()
        .map_err(|_| format!("expects a value between {min} and {max}"))?;
    if parsed.is_finite() && parsed >= min && parsed <= max {
        Ok(parsed)
    } else {
        Err(format!("expects a value between {min} and {max}"))
    }
}

/// Default thinking budget when enabled without a specific value.
const DEFAULT_THINKING_BUDGET: u32 = 1024;

fn parse_thinking_command(argument: Option<&str>) -> ChatCommand {
    let Some(arg) = argument else {
        return ChatCommand::Invalid(
            "/thinking expects 'on', 'off', or a token budget (e.g., 2048)".to_string(),
        );
    };

    let lower = arg.to_lowercase();
    match lower.as_str() {
        "off" | "false" | "no" => ChatCommand::Thinking(None),
        "on" | "true" | "yes" => ChatCommand::Thinking(Some(DEFAULT_THINKING_BUDGET)),
        _ => match arg.parse::<u32>() {
            Ok(budget) => ChatCommand::Thinking(Some(budget)),
            Err(_) => ChatCommand::Invalid(
                "/thinking expects 'on', 'off', or a token budget (e.g., 2048)".to_string(),
            ),
        },
    }
}

fn parse_cache_command(argument: Option<&str>) -> ChatCommand {
    let Some(arg) = argument else {
        return ChatCommand::Invalid("/cache expects 'on' or 'off'".to_string());
    };

    let lower = arg.to_lowercase();
    match lower.as_str() {
        "on" | "true" | "yes" | "enable" | "enabled" => ChatCommand::Caching(true),
        "off" | "false" | "no" | "disable" | "disabled" => ChatCommand::Caching(false),
        _ => ChatCommand::Invalid("/cache expects 'on' or 'off'".to_string()),
    }
}

/// Returns help text describing available commands.
pub fn help_text() -> &'static str {
    r#"Available commands:
  /clear                 Clear conversation history
  /model <name>          Change the model (e.g., /model claude-sonnet-4-0)
  /system [prompt]       Set system prompt (no argument clears it)
  /max_tokens <n>        Set maximum response tokens
  /temperature <v>       Set temperature 0.0-1.0 (use 'clear' to reset)
  /top_p <v>             Set top-p 0.0-1.0 (use 'clear' to reset)
  /top_k <n>             Set top-k (use 'clear' to reset)
  /stop add <seq>        Add a stop sequence
  /stop clear            Clear all stop sequences
  /stop list             List current stop sequences
  /thinking on|off|<n>   Enable/disable extended thinking (or set budget)
  /cache on|off          Enable/disable prompt caching
  /budget <tokens>       Set total session budget (or 'clear')
  /transcript <file>     Enable auto-saving transcripts (or 'clear')
  /save <file>           Save the current transcript immediately
  /load <file>           Load a transcript from disk
  /stats                 Show session statistics
  /config                Show current configuration
  /help                  Show this help message
  /quit                  Exit the chat"#
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_quit_commands() {
        assert_eq!(parse_command("/quit"), Some(ChatCommand::Quit));
        assert_eq!(parse_command("/exit"), Some(ChatCommand::Quit));
        assert_eq!(parse_command("/q"), Some(ChatCommand::Quit));
        assert_eq!(parse_command("  /quit  "), Some(ChatCommand::Quit));
    }

    #[test]
    fn parse_clear() {
        assert_eq!(parse_command("/clear"), Some(ChatCommand::Clear));
        assert_eq!(parse_command("/CLEAR"), Some(ChatCommand::Clear));
    }

    #[test]
    fn parse_model() {
        assert_eq!(
            parse_command("/model claude-sonnet-4-0"),
            Some(ChatCommand::Model("claude-sonnet-4-0".to_string()))
        );
        assert_eq!(
            parse_command("/model   claude-haiku-4-5  "),
            Some(ChatCommand::Model("claude-haiku-4-5".to_string()))
        );
        assert_eq!(
            parse_command("/model"),
            Some(ChatCommand::Invalid(
                "/model requires a model name".to_string()
            ))
        );
    }

    #[test]
    fn parse_system() {
        assert_eq!(
            parse_command("/system You are a helpful assistant"),
            Some(ChatCommand::System(Some(
                "You are a helpful assistant".to_string()
            )))
        );
        assert_eq!(parse_command("/system"), Some(ChatCommand::System(None)));
    }

    #[test]
    fn parse_temperature() {
        assert_eq!(
            parse_command("/temperature 0.5"),
            Some(ChatCommand::Temperature(0.5))
        );
        assert_eq!(
            parse_command("/temperature clear"),
            Some(ChatCommand::ClearTemperature)
        );
        assert!(matches!(
            parse_command("/temperature"),
            Some(ChatCommand::Invalid(msg)) if msg.contains("requires")
        ));
    }

    #[test]
    fn parse_stop_commands() {
        assert_eq!(
            parse_command("/stop add END"),
            Some(ChatCommand::AddStopSequence("END".to_string()))
        );
        assert_eq!(
            parse_command("/stop clear"),
            Some(ChatCommand::ClearStopSequences)
        );
        assert_eq!(
            parse_command("/stop list"),
            Some(ChatCommand::ListStopSequences)
        );
    }

    #[test]
    fn parse_thinking_toggle() {
        assert_eq!(
            parse_command("/thinking on"),
            Some(ChatCommand::Thinking(Some(DEFAULT_THINKING_BUDGET)))
        );
        assert_eq!(
            parse_command("/thinking off"),
            Some(ChatCommand::Thinking(None))
        );
        assert_eq!(
            parse_command("/thinking 2048"),
            Some(ChatCommand::Thinking(Some(2048)))
        );
        assert!(matches!(
            parse_command("/thinking maybe"),
            Some(ChatCommand::Invalid(msg)) if msg.contains("expects")
        ));
    }

    #[test]
    fn parse_budget() {
        assert_eq!(
            parse_command("/budget 1000"),
            Some(ChatCommand::Budget(1000))
        );
        assert_eq!(
            parse_command("/budget clear"),
            Some(ChatCommand::ClearBudget)
        );
    }

    #[test]
    fn parse_transcript_commands() {
        assert_eq!(
            parse_command("/transcript chat.json"),
            Some(ChatCommand::TranscriptPath("chat.json".to_string()))
        );
        assert_eq!(
            parse_command("/transcript clear"),
            Some(ChatCommand::ClearTranscriptPath)
        );
        assert_eq!(
            parse_command("/save session.json"),
            Some(ChatCommand::SaveTranscript("session.json".to_string()))
        );
        assert_eq!(
            parse_command("/load session.json"),
            Some(ChatCommand::LoadTranscript("session.json".to_string()))
        );
    }

    #[test]
    fn parse_stats_and_config() {
        assert_eq!(parse_command("/stats"), Some(ChatCommand::Stats));
        assert_eq!(parse_command("/config"), Some(ChatCommand::ShowConfig));
    }

    #[test]
    fn parse_cache() {
        assert_eq!(parse_command("/cache on"), Some(ChatCommand::Caching(true)));
        assert_eq!(
            parse_command("/cache off"),
            Some(ChatCommand::Caching(false))
        );
        assert_eq!(
            parse_command("/cache enable"),
            Some(ChatCommand::Caching(true))
        );
        assert_eq!(
            parse_command("/cache disable"),
            Some(ChatCommand::Caching(false))
        );
        assert!(matches!(
            parse_command("/cache"),
            Some(ChatCommand::Invalid(msg)) if msg.contains("expects")
        ));
        assert!(matches!(
            parse_command("/cache maybe"),
            Some(ChatCommand::Invalid(msg)) if msg.contains("expects")
        ));
    }

    #[test]
    fn non_commands() {
        assert_eq!(parse_command("Hello, Claude!"), None);
        assert_eq!(parse_command(""), None);
        assert_eq!(parse_command("  "), None);
    }

    #[test]
    fn help_text_not_empty() {
        let help = help_text();
        assert!(!help.is_empty());
        assert!(help.contains("/quit"));
        assert!(help.contains("/clear"));
        assert!(help.contains("/model"));
        assert!(help.contains("/temperature"));
    }
}