Skip to main content

visdom_cli/
interactive.rs

1//! Asking for what `visdom init` was not told on the command line. Only ever
2//! used when both stdin and stderr are a terminal; without one, init behaves
3//! as if nothing could be asked and says what to pass instead.
4
5use std::io::{BufRead, IsTerminal, Write};
6use std::path::Path;
7
8use tracevault_cli::agent::Agent;
9
10use crate::billing::Billing;
11use crate::mode::TracingMode;
12
13/// Whether there is somebody to ask.
14pub fn is_interactive() -> bool {
15    std::io::stdin().is_terminal() && std::io::stderr().is_terminal()
16}
17
18/// Print `question` and read one line, trimmed. `None` at end of input.
19fn ask_line(question: &str) -> Option<String> {
20    eprint!("{question} ");
21    let _ = std::io::stderr().flush();
22    let mut line = String::new();
23    match std::io::stdin().lock().read_line(&mut line) {
24        Ok(0) | Err(_) => None,
25        Ok(_) => Some(line.trim().to_string()),
26    }
27}
28
29/// The agent an answer names: its number in the list, or its name. An empty
30/// answer takes the default, Claude Code. `None` when it names neither.
31pub fn parse_agent_choice(answer: &str) -> Option<Agent> {
32    match answer.trim().to_ascii_lowercase().as_str() {
33        "" | "1" | "claude" | "claude-code" => Some(Agent::ClaudeCode),
34        "2" | "codex" => Some(Agent::Codex),
35        _ => None,
36    }
37}
38
39/// Ask which agent to set up. End of input takes the default.
40pub fn ask_agent() -> Agent {
41    loop {
42        let Some(answer) = ask_line("Which agent? [1] Claude Code  [2] Codex  (default 1):") else {
43            return Agent::ClaudeCode;
44        };
45        match parse_agent_choice(&answer) {
46            Some(agent) => return agent,
47            None => eprintln!("Answer 1 or 2."),
48        }
49    }
50}
51
52/// What `visdom init` sets up.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum InitScope {
55    /// The repository `visdom init` is run in.
56    Repo,
57    /// Every session of the agent on this machine (`--global`).
58    Machine,
59    /// The directory `visdom init` is run in, as a folder of checkouts
60    /// recorded to one project (`--workspace`).
61    Workspace,
62}
63
64/// The scope an answer names: its number in the list, or its name. An empty
65/// answer takes `default`. `None` when it names none.
66pub fn parse_scope_choice(answer: &str, default: InitScope) -> Option<InitScope> {
67    match answer.trim().to_ascii_lowercase().as_str() {
68        "" => Some(default),
69        "1" | "repo" | "repository" => Some(InitScope::Repo),
70        "2" | "machine" | "global" => Some(InitScope::Machine),
71        "3" | "workspace" | "folder" => Some(InitScope::Workspace),
72        _ => None,
73    }
74}
75
76/// Ask what to set up. `None` at end of input: nothing chosen.
77pub fn ask_scope(default: InitScope) -> Option<InitScope> {
78    let number = match default {
79        InitScope::Repo => 1,
80        InitScope::Machine => 2,
81        InitScope::Workspace => 3,
82    };
83    eprintln!("What should visdom set up?");
84    eprintln!("  [1] this repository");
85    eprintln!("  [2] every session on this machine");
86    eprintln!("  [3] this folder of checkouts, recorded to one project (a workspace)");
87    loop {
88        let answer = ask_line(&format!("Number (default {number}):"))?;
89        match parse_scope_choice(&answer, default) {
90            Some(scope) => return Some(scope),
91            None => eprintln!("Answer 1, 2 or 3."),
92        }
93    }
94}
95
96/// Ask for a line of text; `None` when nothing was typed.
97pub fn ask_text(question: &str) -> Option<String> {
98    ask_line(question).filter(|answer| !answer.is_empty())
99}
100
101/// The mode an answer names: its number in the list, or its name. An empty
102/// answer takes the default, hooks. `None` when it names neither.
103pub fn parse_mode_choice(answer: &str) -> Option<TracingMode> {
104    match answer.trim().to_ascii_lowercase().as_str() {
105        "" | "1" | "hooks" => Some(TracingMode::Hooks),
106        "2" | "gateway" => Some(TracingMode::Gateway),
107        _ => None,
108    }
109}
110
111/// Ask how sessions should be traced. `None` at end of input: nothing chosen.
112pub fn ask_mode() -> Option<TracingMode> {
113    loop {
114        let answer = ask_line(
115            "How should your sessions be traced? [1] hooks  [2] through the AI Gateway  (default 1):",
116        )?;
117        match parse_mode_choice(&answer) {
118            Some(mode) => return Some(mode),
119            None => eprintln!("Answer 1 or 2."),
120        }
121    }
122}
123
124/// Who pays, as an answer names it: its number in the list, or its name. An
125/// empty answer takes the default, the project. `None` when it names neither.
126pub fn parse_billing_choice(answer: &str) -> Option<Billing> {
127    match answer.trim().to_ascii_lowercase().as_str() {
128        "" | "1" | "project" => Some(Billing::Project),
129        "2" | "subscription" => Some(Billing::Subscription),
130        _ => None,
131    }
132}
133
134/// Ask who pays for Claude Code's calls through the gateway. `None` at end of
135/// input: nothing chosen.
136pub fn ask_billing() -> Option<Billing> {
137    loop {
138        let answer = ask_line(
139            "Who pays for Claude Code's calls through the AI Gateway? [1] the project (gateway \
140             key)  [2] my Claude subscription  (default 1):",
141        )?;
142        match parse_billing_choice(&answer) {
143            Some(billing) => return Some(billing),
144            None => eprintln!("Answer 1 or 2."),
145        }
146    }
147}
148
149/// The entry of a list of `count` an answer names by its number, from 1.
150pub fn parse_choice(answer: &str, count: usize) -> Option<usize> {
151    let n: usize = answer.trim().parse().ok()?;
152    (1..=count).contains(&n).then(|| n - 1)
153}
154
155/// Ask for one of `options`. `None` at end of input, or with nothing to
156/// choose from.
157pub fn ask_choice(question: &str, options: &[String]) -> Option<usize> {
158    if options.is_empty() {
159        return None;
160    }
161    eprintln!("{question}");
162    for (i, option) in options.iter().enumerate() {
163        eprintln!("  [{}] {option}", i + 1);
164    }
165    loop {
166        let answer = ask_line("Number:")?;
167        match parse_choice(&answer, options.len()) {
168            Some(index) => return Some(index),
169            None => eprintln!("Answer a number from 1 to {}.", options.len()),
170        }
171    }
172}
173
174/// What a typed URL answer means.
175#[derive(Debug, PartialEq, Eq)]
176pub enum UrlAnswer {
177    Url(String),
178    /// Nothing typed.
179    Skipped,
180    Invalid,
181}
182
183/// A bare host is taken as https; anything that is then not an absolute
184/// http(s) URL is invalid.
185pub fn parse_url_answer(answer: &str) -> UrlAnswer {
186    let answer = answer.trim();
187    if answer.is_empty() {
188        return UrlAnswer::Skipped;
189    }
190    if answer.starts_with('-') {
191        return UrlAnswer::Invalid;
192    }
193    let candidate = if answer.contains("://") {
194        answer.to_string()
195    } else {
196        format!("https://{answer}")
197    };
198    if crate::components::bazaar::is_http_url(&candidate) {
199        UrlAnswer::Url(candidate.trim_end_matches('/').to_string())
200    } else {
201        UrlAnswer::Invalid
202    }
203}
204
205/// Ask for a URL until one is given or the question is skipped (Enter, or
206/// end of input).
207pub fn ask_url(question: &str) -> Option<String> {
208    loop {
209        match parse_url_answer(&ask_line(question)?) {
210            UrlAnswer::Url(url) => return Some(url),
211            UrlAnswer::Skipped => return None,
212            UrlAnswer::Invalid => eprintln!("That is not an http(s) URL."),
213        }
214    }
215}
216
217/// Record `bazaar_url` in the user config at `path`, creating the file if
218/// needed and leaving everything else in it as it is.
219pub fn save_bazaar_url(path: &Path, url: &str) -> Result<(), String> {
220    save_user_setting(path, "bazaar_url", url)
221}
222
223/// Record `tracing_mode` in the user config at `path`, the same way.
224pub fn save_tracing_mode(path: &Path, mode: TracingMode) -> Result<(), String> {
225    save_user_setting(path, "tracing_mode", mode.name())
226}
227
228/// Record `key` under `[gateway]` in the user config at `path`, creating the
229/// file if needed. A file with no `[gateway]` table gets one at its end and
230/// is otherwise kept byte for byte; one that has it is rewritten from its
231/// parsed form.
232pub fn save_gateway_setting(path: &Path, key: &str, value: &str) -> Result<(), String> {
233    let existing = match std::fs::read_to_string(path) {
234        Ok(text) => text,
235        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
236        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
237    };
238    let mut table: toml::Table =
239        toml::from_str(&existing).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
240    let value = toml::Value::String(value.to_string());
241    let updated = match table.get_mut("gateway") {
242        Some(toml::Value::Table(gateway)) => {
243            // The same setting under its other spelling (`claude-code-model`)
244            // would make the file name it twice, and then not load at all.
245            gateway.remove(&key.replace('_', "-"));
246            gateway.insert(key.to_string(), value);
247            toml::to_string(&table).map_err(|e| e.to_string())?
248        }
249        Some(_) => return Err(format!("`gateway` in {} is not a table", path.display())),
250        None => {
251            let gap = match existing.is_empty() || existing.ends_with("\n\n") {
252                true => "",
253                false if existing.ends_with('\n') => "\n",
254                false => "\n\n",
255            };
256            format!("{existing}{gap}[gateway]\n{key} = {value}\n")
257        }
258    };
259    if let Some(dir) = path.parent() {
260        std::fs::create_dir_all(dir)
261            .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
262    }
263    std::fs::write(path, updated).map_err(|e| format!("cannot write {}: {e}", path.display()))
264}
265
266/// Set the top-level string `key` in the user config at `path`, creating the
267/// file if needed and leaving everything else in it as it is.
268fn save_user_setting(path: &Path, key: &str, value: &str) -> Result<(), String> {
269    let existing = match std::fs::read_to_string(path) {
270        Ok(text) => text,
271        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
272        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
273    };
274    let mut table: toml::Table =
275        toml::from_str(&existing).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
276    let line = format!("{key} = {}\n", toml::Value::String(value.to_string()));
277    let updated = if table.contains_key(key) {
278        // Already there (empty, or it would not have been asked for): the
279        // file is rewritten from its parsed form.
280        table.insert(key.to_string(), toml::Value::String(value.to_string()));
281        toml::to_string(&table).map_err(|e| e.to_string())?
282    } else {
283        // A top-level key must come before the first table: put it first, and
284        // keep the rest of the file, comments included, byte for byte.
285        format!("{line}{existing}")
286    };
287    if let Some(dir) = path.parent() {
288        std::fs::create_dir_all(dir)
289            .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
290    }
291    std::fs::write(path, updated).map_err(|e| format!("cannot write {}: {e}", path.display()))
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297    use crate::config::load_user_config_in;
298
299    #[test]
300    fn agent_choice_by_number_name_or_default() {
301        assert_eq!(parse_agent_choice(""), Some(Agent::ClaudeCode));
302        assert_eq!(parse_agent_choice("1"), Some(Agent::ClaudeCode));
303        assert_eq!(parse_agent_choice(" Claude-Code "), Some(Agent::ClaudeCode));
304        assert_eq!(parse_agent_choice("2"), Some(Agent::Codex));
305        assert_eq!(parse_agent_choice("codex"), Some(Agent::Codex));
306        assert_eq!(parse_agent_choice("3"), None);
307        assert_eq!(parse_agent_choice("amp"), None);
308    }
309
310    #[test]
311    fn mode_choice_by_number_name_or_default() {
312        assert_eq!(parse_mode_choice(""), Some(TracingMode::Hooks));
313        assert_eq!(parse_mode_choice("1"), Some(TracingMode::Hooks));
314        assert_eq!(parse_mode_choice(" Gateway "), Some(TracingMode::Gateway));
315        assert_eq!(parse_mode_choice("2"), Some(TracingMode::Gateway));
316        assert_eq!(parse_mode_choice("3"), None);
317        assert_eq!(parse_mode_choice("proxy"), None);
318    }
319
320    #[test]
321    fn billing_choice_by_number_name_or_default() {
322        assert_eq!(parse_billing_choice(""), Some(Billing::Project));
323        assert_eq!(parse_billing_choice(" 1 "), Some(Billing::Project));
324        assert_eq!(parse_billing_choice("2"), Some(Billing::Subscription));
325        assert_eq!(
326            parse_billing_choice("Subscription"),
327            Some(Billing::Subscription)
328        );
329        assert_eq!(parse_billing_choice("3"), None);
330    }
331
332    #[test]
333    fn the_mode_is_saved_next_to_the_other_settings() {
334        let tmp = tempfile::tempdir().unwrap();
335        let path = crate::config::user_config_path_in(tmp.path());
336        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
337        let before = "agent = \"codex\"\n\n[gateway]\nproject = \"alpha\"\n";
338        std::fs::write(&path, before).unwrap();
339        save_tracing_mode(&path, TracingMode::Gateway).unwrap();
340        assert_eq!(
341            std::fs::read_to_string(&path).unwrap(),
342            format!("tracing_mode = \"gateway\"\n{before}")
343        );
344        let user = load_user_config_in(tmp.path()).unwrap();
345        assert_eq!(user.tracing_mode, Some(TracingMode::Gateway));
346        assert_eq!(user.agent, Some(Agent::Codex));
347        assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
348        // Choosing again replaces it.
349        save_tracing_mode(&path, TracingMode::Hooks).unwrap();
350        let user = load_user_config_in(tmp.path()).unwrap();
351        assert_eq!(user.tracing_mode, Some(TracingMode::Hooks));
352        assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
353    }
354
355    #[test]
356    fn scope_choice_by_number_name_or_default() {
357        use InitScope::*;
358        assert_eq!(parse_scope_choice("", Machine), Some(Machine));
359        assert_eq!(parse_scope_choice("\n", Repo), Some(Repo));
360        assert_eq!(parse_scope_choice("1", Machine), Some(Repo));
361        assert_eq!(parse_scope_choice(" 2 ", Repo), Some(Machine));
362        assert_eq!(parse_scope_choice("global", Repo), Some(Machine));
363        assert_eq!(parse_scope_choice("3", Repo), Some(Workspace));
364        assert_eq!(parse_scope_choice("Workspace", Repo), Some(Workspace));
365        assert_eq!(parse_scope_choice("4", Repo), None);
366        assert_eq!(parse_scope_choice("everything", Repo), None);
367    }
368
369    #[test]
370    fn a_choice_is_a_number_of_the_list() {
371        assert_eq!(parse_choice("1", 3), Some(0));
372        assert_eq!(parse_choice(" 3\n", 3), Some(2));
373        for answer in ["0", "4", "", "alpha", "-1"] {
374            assert_eq!(parse_choice(answer, 3), None, "{answer}");
375        }
376    }
377
378    #[test]
379    fn a_gateway_setting_is_saved_without_touching_the_rest() {
380        let tmp = tempfile::tempdir().unwrap();
381        let path = tmp.path().join("visdom").join("config.toml");
382        // A new file.
383        save_gateway_setting(&path, "project", "alpha").unwrap();
384        assert_eq!(
385            std::fs::read_to_string(&path).unwrap(),
386            "[gateway]\nproject = \"alpha\"\n"
387        );
388        // A second setting, and the first one replaced.
389        save_gateway_setting(&path, "claude_code_model", "claude-sonnet").unwrap();
390        save_gateway_setting(&path, "project", "beta").unwrap();
391        let user = load_user_config_in(tmp.path()).unwrap();
392        assert_eq!(user.gateway.project.as_deref(), Some("beta"));
393        assert_eq!(
394            user.gateway.claude_code_model.as_deref(),
395            Some("claude-sonnet")
396        );
397
398        // A file with no [gateway] keeps every byte, comments included.
399        let before =
400            "# mine\ntracing_mode = \"gateway\"\n\n[agents]\ncodex = \"cdx\" # local build";
401        std::fs::write(&path, before).unwrap();
402        save_gateway_setting(&path, "codex_model", "gpt-general").unwrap();
403        let after = std::fs::read_to_string(&path).unwrap();
404        assert_eq!(
405            after,
406            format!("{before}\n\n[gateway]\ncodex_model = \"gpt-general\"\n")
407        );
408        let user = load_user_config_in(tmp.path()).unwrap();
409        assert_eq!(user.gateway.codex_model.as_deref(), Some("gpt-general"));
410        assert_eq!(user.agents.codex.as_deref(), Some("cdx"));
411
412        // The other spelling of a key is replaced, not doubled.
413        std::fs::write(&path, "[gateway]\nclaude-code-model = \"\"\n").unwrap();
414        save_gateway_setting(&path, "claude_code_model", "claude-sonnet").unwrap();
415        let user = load_user_config_in(tmp.path()).unwrap();
416        assert_eq!(
417            user.gateway.claude_code_model.as_deref(),
418            Some("claude-sonnet")
419        );
420
421        // One that cannot be parsed is left alone.
422        std::fs::write(&path, "[gateway\n").unwrap();
423        assert!(save_gateway_setting(&path, "project", "alpha").is_err());
424        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[gateway\n");
425    }
426
427    #[test]
428    fn url_answers() {
429        assert_eq!(parse_url_answer("  "), UrlAnswer::Skipped);
430        assert_eq!(
431            parse_url_answer("https://tv.example.com/"),
432            UrlAnswer::Url("https://tv.example.com".to_string())
433        );
434        assert_eq!(
435            parse_url_answer("tv.example.com"),
436            UrlAnswer::Url("https://tv.example.com".to_string())
437        );
438        assert_eq!(
439            parse_url_answer("http://localhost:3000/mcp/remote"),
440            UrlAnswer::Url("http://localhost:3000/mcp/remote".to_string())
441        );
442        for bad in ["ftp://x.example.com", "--flag", "two words", "https://"] {
443            assert_eq!(parse_url_answer(bad), UrlAnswer::Invalid, "{bad}");
444        }
445    }
446
447    #[test]
448    fn bazaar_url_is_saved_into_a_new_file() {
449        let tmp = tempfile::tempdir().unwrap();
450        let path = crate::config::user_config_path_in(tmp.path());
451        save_bazaar_url(&path, "https://ctx.example.com/mcp/remote").unwrap();
452        let user = load_user_config_in(tmp.path()).unwrap();
453        assert_eq!(
454            user.bazaar_url.as_deref(),
455            Some("https://ctx.example.com/mcp/remote")
456        );
457    }
458
459    #[test]
460    fn bazaar_url_is_added_without_touching_the_rest() {
461        let tmp = tempfile::tempdir().unwrap();
462        let path = crate::config::user_config_path_in(tmp.path());
463        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
464        let before = "# my settings\nagent = \"codex\"\n\n[agents]\n# the nightly build\ncodex = \"/opt/codex\"\n";
465        std::fs::write(&path, before).unwrap();
466        save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
467        let after = std::fs::read_to_string(&path).unwrap();
468        assert_eq!(
469            after,
470            format!("bazaar_url = \"https://ctx.example.com/mcp\"\n{before}")
471        );
472        let user = load_user_config_in(tmp.path()).unwrap();
473        assert_eq!(user.agent, Some(Agent::Codex));
474        assert_eq!(
475            user.bazaar_url.as_deref(),
476            Some("https://ctx.example.com/mcp")
477        );
478        assert_eq!(
479            user.agents.program_for(Agent::Codex).as_deref(),
480            Some("/opt/codex")
481        );
482    }
483
484    #[test]
485    fn an_empty_bazaar_url_is_replaced() {
486        let tmp = tempfile::tempdir().unwrap();
487        let path = crate::config::user_config_path_in(tmp.path());
488        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
489        std::fs::write(&path, "bazaar_url = \"\"\nagent = \"codex\"\n").unwrap();
490        save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
491        let user = load_user_config_in(tmp.path()).unwrap();
492        assert_eq!(
493            user.bazaar_url.as_deref(),
494            Some("https://ctx.example.com/mcp")
495        );
496        assert_eq!(user.agent, Some(Agent::Codex));
497    }
498
499    #[test]
500    fn a_config_that_cannot_be_parsed_is_left_alone() {
501        let tmp = tempfile::tempdir().unwrap();
502        let path = crate::config::user_config_path_in(tmp.path());
503        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
504        std::fs::write(&path, "agent = [broken").unwrap();
505        let err = save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap_err();
506        assert!(err.contains("cannot parse"), "{err}");
507        assert_eq!(std::fs::read_to_string(&path).unwrap(), "agent = [broken");
508    }
509}