Skip to main content

blyte_cli/
repl.rs

1use std::io::{BufRead, Write};
2use std::path::PathBuf;
3
4/// Configuration options for launching the interactive REPL harness.
5#[derive(Debug, Clone)]
6pub struct ReplConfig {
7    pub repo_root: PathBuf,
8    pub model: Option<String>,
9    pub gate: Option<String>,
10    pub context_strategy: String,
11    pub container: Option<String>,
12    pub max_turns: usize,
13    pub max_gates: usize,
14    pub rollback: bool,
15    pub orchestrate: bool,
16    pub dispatch_cmd: Option<String>,
17    pub fold_budget: Option<usize>,
18}
19
20impl Default for ReplConfig {
21    fn default() -> Self {
22        Self {
23            repo_root: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
24            model: None,
25            gate: None,
26            context_strategy: "folded".to_string(),
27            container: None,
28            max_turns: 60,
29            max_gates: 5,
30            rollback: true,
31            orchestrate: false,
32            dispatch_cmd: None,
33            fold_budget: None,
34        }
35    }
36}
37
38/// Active state and parameters of an ongoing REPL session.
39pub struct ReplSession {
40    pub repo_root: PathBuf,
41    pub gate: Option<String>,
42    pub model: String,
43    pub cached_models: Vec<blyte_provider::ModelInfo>,
44    pub context_strategy: String,
45    pub container: Option<String>,
46    pub max_turns: usize,
47    pub max_gates: usize,
48    pub rollback: bool,
49    pub orchestrate: bool,
50    pub dispatch_cmd: Option<String>,
51    pub fold_budget: Option<usize>,
52    pub state: blyte_agent::state::State,
53    pub session_id: String,
54}
55
56/// Formats a session identifier from a Unix timestamp (in seconds) and process ID.
57pub fn new_session_id(now_secs: u64, pid: u32) -> String {
58    format!("{now_secs}-{pid}")
59}
60
61impl ReplSession {
62    /// Creates a new `ReplSession` initialized with the given `ReplConfig`.
63    pub fn new(config: &ReplConfig) -> Self {
64        let session_id = match std::env::var("BLYTE_SESSION") {
65            Ok(v) if !v.is_empty() => v,
66            _ => {
67                let now_secs = std::time::SystemTime::now()
68                    .duration_since(std::time::UNIX_EPOCH)
69                    .map(|d| d.as_secs())
70                    .unwrap_or(0);
71                let id = new_session_id(now_secs, std::process::id());
72                std::env::set_var("BLYTE_SESSION", &id);
73                id
74            }
75        };
76
77        let gate = config.gate.clone();
78        let verification_cmd = gate.clone().unwrap_or_default();
79        let goal = "Interactive REPL session".to_string();
80        let mut state = blyte_agent::state::State::new(goal, verification_cmd);
81        state.runtime.conversation = Some(Vec::new());
82
83        if config.orchestrate {
84            let rules_path = blyte_agent::orchestrator::user_rules_path();
85            let loaded_rules = rules_path
86                .as_deref()
87                .and_then(|p| blyte_agent::orchestrator::load_user_rules(p).map(|text| (p, text)));
88            let rules_ref = loaded_rules.as_ref().map(|(p, t)| (*p, t.as_str()));
89            state.orchestrator.instructions =
90                Some(blyte_agent::orchestrator::prompt_sections_with_dispatch(
91                    crate::skill::SKILL_MD,
92                    rules_ref,
93                    config.dispatch_cmd.is_some(),
94                ));
95        }
96
97        Self {
98            repo_root: config.repo_root.clone(),
99            gate,
100            model: config
101                .model
102                .clone()
103                .unwrap_or_else(|| "gemini-3.8-flash".to_string()),
104            cached_models: Vec::new(),
105            context_strategy: config.context_strategy.clone(),
106            container: config.container.clone(),
107            max_turns: config.max_turns,
108            max_gates: config.max_gates,
109            rollback: config.rollback,
110            orchestrate: config.orchestrate,
111            dispatch_cmd: config.dispatch_cmd.clone(),
112            fold_budget: config.fold_budget,
113            state,
114            session_id,
115        }
116    }
117}
118
119/// Control flow signal emitted after handling REPL input.
120#[derive(Debug, PartialEq, Eq)]
121pub enum ReplControl {
122    Handled,
123    Exit,
124    SubmitPrompt(String),
125}
126
127/// Formats turns and token usage into a single line summary.
128pub fn format_usage_line(turns: u32, usage: &blyte_provider::Usage) -> String {
129    format!(
130        "{} turns · {} in ({} cached) · {} out",
131        turns, usage.input, usage.cached, usage.output
132    )
133}
134
135/// Formats turns, token usage, and session cost into a single line summary.
136pub fn format_usage_line_with_session(
137    turns: u32,
138    usage: &blyte_provider::Usage,
139    totals: &crate::cost::Totals,
140) -> String {
141    let total = totals.orchestrator_usd + totals.implementers_usd;
142    format!(
143        "{} · session ${:.2} (implementers ${:.2}, {} runs)",
144        format_usage_line(turns, usage),
145        total,
146        totals.implementers_usd,
147        totals.runs
148    )
149}
150
151/// Reads the usage log and computes totals for the given session.
152fn current_session_totals(session_id: &str) -> crate::cost::Totals {
153    let entries = crate::usage_log::default_path()
154        .as_deref()
155        .map(crate::usage_log::read)
156        .unwrap_or_default();
157    crate::cost::totals(&entries, Some(session_id), None, None)
158}
159
160/// Formats a runtime event emitted during agent turn or gate execution.
161pub fn format_event(event: &blyte_agent::run::Event<'_>) -> String {
162    match event {
163        blyte_agent::run::Event::Turn { n, text, .. } => {
164            format!("[Turn {}] {}", n, text)
165        }
166        blyte_agent::run::Event::Tool {
167            name,
168            input,
169            summary,
170            is_error,
171        } => {
172            if *is_error {
173                format!("\x1b[31m● {} {} -> {}\x1b[0m", name, input, summary)
174            } else {
175                format!("● {} {} -> {}", name, input, summary)
176            }
177        }
178        blyte_agent::run::Event::GateStart { attempt } => {
179            format!("⏳ Gate running (attempt {})", attempt)
180        }
181        blyte_agent::run::Event::GateSlotWait { ms } => {
182            format!("⏳ Gate waited {}ms for slot", ms)
183        }
184        blyte_agent::run::Event::Gate {
185            attempt,
186            passed,
187            output,
188        } => {
189            if *passed {
190                format!("✓ Gate passed (attempt {})", attempt)
191            } else {
192                format!("✗ Gate failed (attempt {}): {}", attempt, output.trim())
193            }
194        }
195        blyte_agent::run::Event::RolledBack { to } => {
196            format!("↺ Rolled back working tree to {}", to)
197        }
198    }
199}
200
201/// Renders the Blyte ASCII banner and environment summary to a writer.
202pub fn render_banner_to<W: Write>(writer: &mut W, session: &ReplSession) -> std::io::Result<()> {
203    let version = env!("CARGO_PKG_VERSION");
204    let repo = session.repo_root.display().to_string();
205    let model = &session.model;
206    let gate = session
207        .gate
208        .as_deref()
209        .unwrap_or("None (fail-closed disabled)");
210
211    let mut toolchains = Vec::new();
212    if session.repo_root.join("Cargo.toml").exists() {
213        toolchains.push("Rust (Cargo)");
214    }
215    if session.repo_root.join("pyproject.toml").exists()
216        || session.repo_root.join("requirements.txt").exists()
217    {
218        toolchains.push("Python");
219    }
220    if session.repo_root.join("package.json").exists() {
221        toolchains.push("Node.js");
222    }
223    if session.repo_root.join("go.mod").exists() {
224        toolchains.push("Go");
225    }
226    let toolchains_str = if toolchains.is_empty() {
227        "Standard POSIX".to_string()
228    } else {
229        toolchains.join(", ")
230    };
231
232    writeln!(
233        writer,
234        "╔═══════════════════════════════════════════════════════════╗"
235    )?;
236    writeln!(
237        writer,
238        "║   ____                                _        _          ║"
239    )?;
240    writeln!(
241        writer,
242        "║  / ___| _   _ _ __   ___ _ __ ___   __| |  ___| |_ ___    ║"
243    )?;
244    writeln!(
245        writer,
246        "║  \\___ \\| | | | '_ \\ / _ \\ '__/ __| / _` | / __| __/ _ \\   ║"
247    )?;
248    writeln!(
249        writer,
250        "║   ___) | |_| | |_) |  __/ |  \\__ \\| (_| || (__| ||  __/   ║"
251    )?;
252    writeln!(
253        writer,
254        "║  |____/ \\__,_| .__/ \\___|_|  |___/ \\__,_(_)___|\\__\\___|   ║"
255    )?;
256    writeln!(
257        writer,
258        "║              |_|                                          ║"
259    )?;
260    writeln!(writer, "║  Blyte Interactive Harness v{:<25}║", version)?;
261    writeln!(
262        writer,
263        "╚═══════════════════════════════════════════════════════════╝"
264    )?;
265    writeln!(writer, "  Repository : {}", repo)?;
266    writeln!(writer, "  Model      : {}", model)?;
267    if session.orchestrate {
268        writeln!(writer, "  Mode       : orchestrator")?;
269    } else {
270        writeln!(writer, "  Gate       : {}", gate)?;
271    }
272    writeln!(writer, "  Toolchains : {}", toolchains_str)?;
273    writeln!(
274        writer,
275        "  Type /help for slash commands or enter a prompt to begin."
276    )?;
277    writeln!(writer)?;
278    Ok(())
279}
280
281/// Renders the Blyte banner to standard output.
282pub fn render_banner(session: &ReplSession) {
283    let mut stdout = std::io::stdout();
284    let _ = render_banner_to(&mut stdout, session);
285}
286
287/// Processes a single line of REPL input, dispatching slash commands or submitting prompts.
288pub fn handle_repl_command<W: Write>(
289    session: &mut ReplSession,
290    line: &str,
291    writer: &mut W,
292) -> Result<ReplControl, String> {
293    let trimmed = line.trim();
294
295    // Check if input is a slash command
296    if trimmed.starts_with('/') {
297        let (cmd, args) = match trimmed.split_once(char::is_whitespace) {
298            Some((c, a)) => (c, a.trim()),
299            None => (trimmed, ""),
300        };
301
302        match cmd {
303            "/help" => {
304                if session.orchestrate {
305                    writeln!(
306                        writer,
307                        "Mode: orchestrator (plan, dispatch implementers, review and merge)"
308                    )
309                    .map_err(|e| e.to_string())?;
310                }
311                writeln!(writer, "Available Slash Commands:").map_err(|e| e.to_string())?;
312                writeln!(writer, "  /help         - Show this command reference")
313                    .map_err(|e| e.to_string())?;
314                writeln!(
315                    writer,
316                    "  /model [name|idx] - Discover and switch active AI model"
317                )
318                .map_err(|e| e.to_string())?;
319                writeln!(writer, "  /cost         - Show session cost totals")
320                    .map_err(|e| e.to_string())?;
321                writeln!(
322                    writer,
323                    "  /state        - Inspect SKILL.state (Orchestrator, Runtime)"
324                )
325                .map_err(|e| e.to_string())?;
326                writeln!(
327                    writer,
328                    "  /diff         - Show current git diff in working tree"
329                )
330                .map_err(|e| e.to_string())?;
331                writeln!(
332                    writer,
333                    "  /gate [cmd]   - Inspect or update the verification gate command"
334                )
335                .map_err(|e| e.to_string())?;
336                writeln!(
337                    writer,
338                    "  /clear        - Clear session history and reset working state"
339                )
340                .map_err(|e| e.to_string())?;
341                writeln!(writer, "  /exit, /quit  - Exit the interactive REPL")
342                    .map_err(|e| e.to_string())?;
343                Ok(ReplControl::Handled)
344            }
345            "/model" => {
346                let args = args.trim();
347                if args.is_empty() {
348                    // Discover and display all models supported by configured providers
349                    writeln!(writer, "Discovering available cloud models...")
350                        .map_err(|e| e.to_string())?;
351                    session.cached_models.clear();
352                    let discovered = blyte_provider::discover_all_models();
353                    for (provider_name, res) in discovered {
354                        match res {
355                            Ok(models) => {
356                                let via_info = match provider_name.as_str() {
357                                    "Google Gemini" => " (via GEMINI_API_KEY)",
358                                    "Anthropic Claude" => " (via ANTHROPIC_API_KEY)",
359                                    "Ollama Cloud" => "",
360                                    _ => "",
361                                };
362                                let header = if provider_name == "Ollama Cloud" {
363                                    let host = std::env::var("OLLAMA_HOST")
364                                        .unwrap_or_else(|_| "https://ollama.com/api".to_string());
365                                    format!("[Ollama Cloud] (via OLLAMA_API_KEY at {})", host)
366                                } else {
367                                    format!("[{}]{}", provider_name, via_info)
368                                };
369                                writeln!(writer, "\n{}", header).map_err(|e| e.to_string())?;
370
371                                for m in models {
372                                    session.cached_models.push(m.clone());
373                                    let idx = session.cached_models.len();
374                                    let is_active = session.model == m.id
375                                        || session.model.ends_with(&format!("/{}", m.id));
376                                    let active_tag = if is_active { " (active)" } else { "" };
377                                    let id_with_active = format!("{}{}", m.id, active_tag);
378
379                                    if let Some(ref desc) = m.description {
380                                        if id_with_active.len() < 25 {
381                                            writeln!(
382                                                writer,
383                                                "  [{}] {:<25} - {}",
384                                                idx, id_with_active, desc
385                                            )
386                                            .map_err(|e| e.to_string())?;
387                                        } else {
388                                            writeln!(
389                                                writer,
390                                                "  [{}] {} - {}",
391                                                idx, id_with_active, desc
392                                            )
393                                            .map_err(|e| e.to_string())?;
394                                        }
395                                    } else {
396                                        writeln!(writer, "  [{}] {}", idx, id_with_active)
397                                            .map_err(|e| e.to_string())?;
398                                    }
399                                }
400                            }
401                            Err(blyte_provider::ProviderError::MissingKey(key)) => {
402                                writeln!(
403                                    writer,
404                                    "\n[{}] Not configured (set {} to discover models)",
405                                    provider_name, key
406                                )
407                                .map_err(|e| e.to_string())?;
408                            }
409                            Err(err) => {
410                                writeln!(writer, "\n[{}] Discovery error: {}", provider_name, err)
411                                    .map_err(|e| e.to_string())?;
412                            }
413                        }
414                    }
415                    writeln!(writer, "\nActive model: {}", session.model)
416                        .map_err(|e| e.to_string())?;
417                    writeln!(
418                        writer,
419                        "To switch: /model <number> or /model <name> (e.g. /model 1 or /model claude-3-7-sonnet-latest)"
420                    )
421                    .map_err(|e| e.to_string())?;
422                } else if let Ok(idx) = args.parse::<usize>() {
423                    // Populate model cache on-demand if user immediately specifies numeric index
424                    if session.cached_models.is_empty() {
425                        let discovered = blyte_provider::discover_all_models();
426                        for (_, res) in discovered {
427                            if let Ok(models) = res {
428                                session.cached_models.extend(models);
429                            }
430                        }
431                    }
432                    if idx >= 1 && idx <= session.cached_models.len() {
433                        let chosen = &session.cached_models[idx - 1];
434                        session.model = chosen.id.clone();
435                        writeln!(
436                            writer,
437                            "Switched active model to: {} ({})",
438                            chosen.id, chosen.provider
439                        )
440                        .map_err(|e| e.to_string())?;
441                    } else {
442                        writeln!(
443                            writer,
444                            "Invalid model index: {}. Use /model to view available models.",
445                            idx
446                        )
447                        .map_err(|e| e.to_string())?;
448                    }
449                } else if let Ok(idx) = args.parse::<i64>() {
450                    writeln!(
451                        writer,
452                        "Invalid model index: {}. Use /model to view available models.",
453                        idx
454                    )
455                    .map_err(|e| e.to_string())?;
456                } else {
457                    // Switch model by explicit identifier or provider-namespaced tag
458                    let kind = blyte_provider::registry::detect_provider_kind(Some(args));
459                    session.model = args.to_string();
460                    writeln!(writer, "Switched active model to: {} ({:?})", args, kind)
461                        .map_err(|e| e.to_string())?;
462                }
463                Ok(ReplControl::Handled)
464            }
465            "/cost" => {
466                let totals = current_session_totals(&session.session_id);
467                writeln!(writer, "{}", crate::cost::format_totals(&totals))
468                    .map_err(|e| e.to_string())?;
469                Ok(ReplControl::Handled)
470            }
471            "/state" => {
472                writeln!(writer, "=== Blyte SKILL.state ===").map_err(|e| e.to_string())?;
473                writeln!(writer, "session: {}", session.session_id).map_err(|e| e.to_string())?;
474                // Render orchestrator contract: goal specification and verification gate
475                let mut orch_val =
476                    serde_json::to_value(&session.state.orchestrator).map_err(|e| e.to_string())?;
477                if let Some(map) = orch_val.as_object_mut() {
478                    if let Some(serde_json::Value::String(instructions)) =
479                        map.get_mut("instructions")
480                    {
481                        let n = instructions.chars().count();
482                        *instructions = format!("<{n} characters>");
483                    }
484                }
485                let orch = serde_json::to_string_pretty(&orch_val).map_err(|e| e.to_string())?;
486                writeln!(writer, "Orchestrator:\n{}", orch).map_err(|e| e.to_string())?;
487
488                // Render runtime state including attempt counts, rollback metrics, and action ledger
489                let mut rt_without_conv = session.state.runtime.clone();
490                let conv = rt_without_conv.conversation.take();
491                let rt_json =
492                    serde_json::to_string_pretty(&rt_without_conv).map_err(|e| e.to_string())?;
493                let rt = if let Some(msgs) = conv {
494                    let conv_line = format!("  conversation: {} messages", msgs.len());
495                    let lines: Vec<&str> = rt_json.lines().collect();
496                    if lines.len() >= 2 {
497                        let mut out_lines = Vec::new();
498                        out_lines.push(lines[0]);
499                        out_lines.push(&conv_line);
500                        out_lines.extend_from_slice(&lines[1..]);
501                        out_lines.join("\n")
502                    } else {
503                        conv_line
504                    }
505                } else {
506                    rt_json
507                };
508                writeln!(writer, "Runtime:\n{}", rt).map_err(|e| e.to_string())?;
509
510                Ok(ReplControl::Handled)
511            }
512            "/diff" => {
513                let out = std::process::Command::new("git")
514                    .arg("diff")
515                    .current_dir(&session.repo_root)
516                    .output();
517                match out {
518                    Ok(output) => {
519                        let stdout = String::from_utf8_lossy(&output.stdout);
520                        if stdout.trim().is_empty() {
521                            writeln!(writer, "No uncommitted diff in repository.")
522                                .map_err(|e| e.to_string())?;
523                        } else {
524                            write!(writer, "{}", stdout).map_err(|e| e.to_string())?;
525                        }
526                    }
527                    Err(e) => {
528                        writeln!(writer, "Failed to run git diff: {}", e)
529                            .map_err(|e| e.to_string())?;
530                    }
531                }
532                Ok(ReplControl::Handled)
533            }
534            "/gate" => {
535                if session.orchestrate {
536                    writeln!(writer, "No gate in orchestrate mode.").map_err(|e| e.to_string())?;
537                } else if args.is_empty() {
538                    match &session.gate {
539                        Some(g) => {
540                            writeln!(writer, "Current gate: {}", g).map_err(|e| e.to_string())?
541                        }
542                        None => {
543                            writeln!(writer, "No gate configured.").map_err(|e| e.to_string())?
544                        }
545                    }
546                } else {
547                    session.gate = Some(args.to_string());
548                    session.state.orchestrator.verification_cmd = args.to_string();
549                    writeln!(writer, "Gate set to: {}", args).map_err(|e| e.to_string())?;
550                }
551                Ok(ReplControl::Handled)
552            }
553            "/clear" => {
554                session.state.runtime = blyte_agent::state::Runtime::default();
555                session.state.runtime.conversation = Some(Vec::new());
556                writeln!(
557                    writer,
558                    "Conversation cleared; the next prompt starts a new one."
559                )
560                .map_err(|e| e.to_string())?;
561                Ok(ReplControl::Handled)
562            }
563            "/exit" | "/quit" => Ok(ReplControl::Exit),
564            unknown => {
565                writeln!(
566                    writer,
567                    "Unknown command: {}. Type /help for available commands.",
568                    unknown
569                )
570                .map_err(|e| e.to_string())?;
571                Ok(ReplControl::Handled)
572            }
573        }
574    } else if trimmed.is_empty() {
575        Ok(ReplControl::Handled)
576    } else {
577        Ok(ReplControl::SubmitPrompt(line.to_string()))
578    }
579}
580
581/// Runs the interactive REPL event loop over generic input and output streams.
582pub fn run_repl_stream<R: BufRead, W: Write>(
583    mut reader: R,
584    mut writer: W,
585    mut session: ReplSession,
586) -> Result<(), String> {
587    loop {
588        write!(writer, "blyte > ").map_err(|e| e.to_string())?;
589        writer.flush().map_err(|e| e.to_string())?;
590
591        let mut line = String::new();
592        let bytes_read = reader.read_line(&mut line).map_err(|e| e.to_string())?;
593        if bytes_read == 0 {
594            // EOF reached
595            break;
596        }
597
598        let trimmed = line.trim_end();
599        match handle_repl_command(&mut session, trimmed, &mut writer)? {
600            ReplControl::Exit => break,
601            ReplControl::Handled => {}
602            ReplControl::SubmitPrompt(prompt) => {
603                writeln!(writer, "Dispatching turn for prompt: {}", prompt)
604                    .map_err(|e| e.to_string())?;
605                session.state.orchestrator.goal = prompt.clone();
606                if let Some(ref g) = session.gate {
607                    session.state.orchestrator.verification_cmd = g.clone();
608                }
609
610                // Build task configuration from current session parameters
611                let task_config = crate::task_runner::TaskConfig {
612                    prompt: prompt.clone(),
613                    gate: session.gate.clone(),
614                    context_strategy: session.context_strategy.clone(),
615                    model: Some(session.model.clone()),
616                    container: session.container.clone(),
617                    max_turns: session.max_turns,
618                    max_gates: session.max_gates,
619                    rollback: session.rollback,
620                    root: session.repo_root.clone(),
621                    container_workdir: "/workspace".into(),
622                    max_seconds: None,
623                    max_cost_usd: None,
624                    report: None,
625                    fold_budget: session.fold_budget,
626                    sandbox: if session.orchestrate {
627                        "off".into()
628                    } else {
629                        "on".into()
630                    },
631                    network: "on".into(),
632                    allow_read: Vec::new(),
633                    pass_env: Vec::new(),
634                    research: false,
635                    claim_check: false,
636                    base_check: false,
637                    orchestrate: session.orchestrate,
638                    dispatch_cmd: session.dispatch_cmd.clone(),
639                };
640
641                // Invoke solver task runner preserving state and outputting directly to REPL writer
642                match crate::task_runner::run_task_with_state_and_writer(
643                    &task_config,
644                    &mut session.state,
645                    &mut writer,
646                ) {
647                    Ok((
648                        blyte_agent::run::Outcome::Verified | blyte_agent::run::Outcome::Finished,
649                        report,
650                    )) => {
651                        if session.orchestrate {
652                            let totals = current_session_totals(&session.session_id);
653                            writeln!(
654                                writer,
655                                "{}",
656                                format_usage_line_with_session(
657                                    report.outcome_turns,
658                                    &report.usage,
659                                    &totals
660                                )
661                            )
662                            .map_err(|e| e.to_string())?;
663                        } else {
664                            writeln!(
665                                writer,
666                                "Task verified in {} turns (usage: {:?})",
667                                report.outcome_turns, report.usage
668                            )
669                            .map_err(|e| e.to_string())?;
670                        }
671                    }
672                    Ok((outcome, report)) => {
673                        if session.orchestrate {
674                            let totals = current_session_totals(&session.session_id);
675                            writeln!(
676                                writer,
677                                "Stopped ({outcome:?}): {}",
678                                format_usage_line_with_session(
679                                    report.outcome_turns,
680                                    &report.usage,
681                                    &totals
682                                )
683                            )
684                            .map_err(|e| e.to_string())?;
685                        } else {
686                            writeln!(
687                                writer,
688                                "Task finished with outcome: {:?} in {} turns",
689                                outcome, report.outcome_turns
690                            )
691                            .map_err(|e| e.to_string())?;
692                        }
693                    }
694                    Err(err) => {
695                        writeln!(writer, "Task execution error: {}", err)
696                            .map_err(|e| e.to_string())?;
697                    }
698                }
699            }
700        }
701    }
702    Ok(())
703}
704
705/// Initializes a REPL session and runs the interactive terminal loop.
706pub fn run_repl(config: ReplConfig) -> Result<(), String> {
707    let session = ReplSession::new(&config);
708    render_banner(&session);
709    let stdin = std::io::stdin();
710    let stdout = std::io::stdout();
711    run_repl_stream(stdin.lock(), stdout.lock(), session)
712}
713
714#[cfg(test)]
715mod tests {
716    use super::*;
717
718    #[test]
719    fn test_new_session_id_format() {
720        assert_eq!(new_session_id(1700000000, 42), "1700000000-42");
721    }
722
723    #[test]
724    fn test_repl_state_contains_session() {
725        let config = ReplConfig::default();
726        let mut session = ReplSession::new(&config);
727        let instructions = "x".repeat(600);
728        session.state.orchestrator.instructions = Some(instructions.clone());
729        let mut out = Vec::new();
730        let res = handle_repl_command(&mut session, "/state", &mut out).unwrap();
731        assert_eq!(res, ReplControl::Handled);
732        let text = String::from_utf8(out).unwrap();
733        assert!(text.contains("session: "));
734        assert!(text.contains(&format!("session: {}", session.session_id)));
735        assert!(text.contains("<600 characters>"));
736        assert!(!text.contains(&instructions));
737    }
738
739    #[test]
740    fn test_repl_cost_command_with_usage_log() {
741        let tmp = tempfile::tempdir().unwrap();
742        let log_path = tmp.path().join("usage.jsonl");
743
744        let config = ReplConfig {
745            orchestrate: true,
746            ..Default::default()
747        };
748        let mut session = ReplSession::new(&config);
749
750        let entry1 = crate::usage_log::Entry {
751            ts: 1700000000,
752            repo: "/test/repo".into(),
753            session: Some(session.session_id.clone()),
754            dispatch: None,
755            research: false,
756            model: "model-a".into(),
757            outcome: "verified".into(),
758            turns: 2,
759            input: 500,
760            cached: 100,
761            output: 200,
762            thinking: 0,
763            cost_usd: Some(0.12),
764        };
765
766        let entry2 = crate::usage_log::Entry {
767            ts: 1700000010,
768            repo: "/test/repo".into(),
769            session: Some(session.session_id.clone()),
770            dispatch: Some("disp-1".into()),
771            research: false,
772            model: "model-b".into(),
773            outcome: "verified".into(),
774            turns: 5,
775            input: 1000,
776            cached: 200,
777            output: 400,
778            thinking: 0,
779            cost_usd: Some(0.34),
780        };
781
782        crate::usage_log::append(&log_path, &entry1).unwrap();
783        crate::usage_log::append(&log_path, &entry2).unwrap();
784
785        let old_env = std::env::var_os("BLYTE_USAGE_LOG");
786        std::env::set_var("BLYTE_USAGE_LOG", &log_path);
787
788        let mut out = Vec::new();
789        let res = handle_repl_command(&mut session, "/cost", &mut out).unwrap();
790        assert_eq!(res, ReplControl::Handled);
791
792        match old_env {
793            Some(val) => std::env::set_var("BLYTE_USAGE_LOG", val),
794            None => std::env::remove_var("BLYTE_USAGE_LOG"),
795        }
796
797        let text = String::from_utf8(out).unwrap();
798        assert_eq!(
799            text.trim(),
800            "blyte $0.46 (orchestrator $0.12, implementers $0.34 in 1 runs)"
801        );
802    }
803
804    #[test]
805    fn test_format_usage_line_with_session() {
806        let usage = blyte_provider::Usage {
807            input: 12000,
808            cached: 9000,
809            output: 450,
810            thinking: 0,
811        };
812        let totals = crate::cost::Totals {
813            orchestrator_usd: 0.15,
814            implementers_usd: 0.35,
815            runs: 2,
816        };
817        let line = format_usage_line_with_session(3, &usage, &totals);
818        assert_eq!(
819            line,
820            "3 turns · 12000 in (9000 cached) · 450 out · session $0.50 (implementers $0.35, 2 runs)"
821        );
822    }
823}