Skip to main content

blyte_cli/
repl.rs

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