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 orchestrate: 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            orchestrate: 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 orchestrate: 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 orchestrator_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.orchestrate && 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_orchestrate_policy(
115            config.orchestrate,
116            sandbox_on,
117            &config.repo_root,
118            approver,
119            true,
120        )?;
121        let orchestrator_start_lines = if config.orchestrate {
122            Some(crate::orchestrator_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            orchestrate: config.orchestrate,
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            orchestrator_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            orchestrate: self.orchestrate,
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.orchestrator_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.orchestrate {
315        writeln!(writer, "  Mode       : orchestrator")?;
316        if let Some([process_line, repo_line, sandbox_line]) = &session.orchestrator_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.orchestrate {
366                    writeln!(
367                        writer,
368                        "Mode: orchestrator (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 (Orchestrator, 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                // Render orchestrator contract: goal specification and verification gate
536                let mut orch_val =
537                    serde_json::to_value(&session.state.orchestrator).map_err(|e| e.to_string())?;
538                if let Some(map) = orch_val.as_object_mut() {
539                    if let Some(serde_json::Value::String(instructions)) =
540                        map.get_mut("instructions")
541                    {
542                        let n = instructions.chars().count();
543                        *instructions = format!("<{n} characters>");
544                    }
545                }
546                let orch = serde_json::to_string_pretty(&orch_val).map_err(|e| e.to_string())?;
547                writeln!(writer, "Orchestrator:\n{}", orch).map_err(|e| e.to_string())?;
548
549                // Render runtime state including attempt counts, rollback metrics, and action ledger
550                let mut rt_without_conv = session.state.runtime.clone();
551                let conv = rt_without_conv.conversation.take();
552                let rt_json =
553                    serde_json::to_string_pretty(&rt_without_conv).map_err(|e| e.to_string())?;
554                let rt = if let Some(msgs) = conv {
555                    let conv_line = format!("  conversation: {} messages", msgs.len());
556                    let lines: Vec<&str> = rt_json.lines().collect();
557                    if lines.len() >= 2 {
558                        let mut out_lines = Vec::new();
559                        out_lines.push(lines[0]);
560                        out_lines.push(&conv_line);
561                        out_lines.extend_from_slice(&lines[1..]);
562                        out_lines.join("\n")
563                    } else {
564                        conv_line
565                    }
566                } else {
567                    rt_json
568                };
569                writeln!(writer, "Runtime:\n{}", rt).map_err(|e| e.to_string())?;
570
571                Ok(ReplControl::Handled)
572            }
573            "/diff" => {
574                let out = std::process::Command::new("git")
575                    .arg("diff")
576                    .current_dir(&session.repo_root)
577                    .output();
578                match out {
579                    Ok(output) => {
580                        let stdout = String::from_utf8_lossy(&output.stdout);
581                        if stdout.trim().is_empty() {
582                            writeln!(writer, "No uncommitted diff in repository.")
583                                .map_err(|e| e.to_string())?;
584                        } else {
585                            write!(writer, "{}", stdout).map_err(|e| e.to_string())?;
586                        }
587                    }
588                    Err(e) => {
589                        writeln!(writer, "Failed to run git diff: {}", e)
590                            .map_err(|e| e.to_string())?;
591                    }
592                }
593                Ok(ReplControl::Handled)
594            }
595            "/gate" => {
596                if session.orchestrate {
597                    writeln!(writer, "No gate in orchestrate mode.").map_err(|e| e.to_string())?;
598                } else if args.is_empty() {
599                    match &session.gate {
600                        Some(g) => {
601                            writeln!(writer, "Current gate: {}", g).map_err(|e| e.to_string())?
602                        }
603                        None => {
604                            writeln!(writer, "No gate configured.").map_err(|e| e.to_string())?
605                        }
606                    }
607                } else {
608                    session.gate = Some(args.to_string());
609                    session.state.orchestrator.verification_cmd = args.to_string();
610                    writeln!(writer, "Gate set to: {}", args).map_err(|e| e.to_string())?;
611                }
612                Ok(ReplControl::Handled)
613            }
614            "/clear" => {
615                session.state.runtime = blyte_agent::state::Runtime::default();
616                session.state.runtime.conversation = Some(Vec::new());
617                writeln!(
618                    writer,
619                    "Conversation cleared; the next prompt starts a new one."
620                )
621                .map_err(|e| e.to_string())?;
622                Ok(ReplControl::Handled)
623            }
624            "/exit" | "/quit" => Ok(ReplControl::Exit),
625            unknown => {
626                writeln!(
627                    writer,
628                    "Unknown command: {}. Type /help for available commands.",
629                    unknown
630                )
631                .map_err(|e| e.to_string())?;
632                Ok(ReplControl::Handled)
633            }
634        }
635    } else if trimmed.is_empty() {
636        Ok(ReplControl::Handled)
637    } else {
638        Ok(ReplControl::SubmitPrompt(line.to_string()))
639    }
640}
641
642/// Runs the interactive REPL event loop over generic input and output streams.
643pub fn run_repl_stream<R: BufRead, W: Write>(
644    mut reader: R,
645    mut writer: W,
646    mut session: ReplSession,
647) -> Result<(), String> {
648    loop {
649        write!(writer, "blyte > ").map_err(|e| e.to_string())?;
650        writer.flush().map_err(|e| e.to_string())?;
651
652        let mut line = String::new();
653        let bytes_read = reader.read_line(&mut line).map_err(|e| e.to_string())?;
654        if bytes_read == 0 {
655            // EOF reached
656            break;
657        }
658
659        let trimmed = line.trim_end();
660        match handle_repl_command(&mut session, trimmed, &mut writer)? {
661            ReplControl::Exit => break,
662            ReplControl::Handled => {}
663            ReplControl::SubmitPrompt(prompt) => {
664                writeln!(writer, "Dispatching turn for prompt: {}", prompt)
665                    .map_err(|e| e.to_string())?;
666                session.state.orchestrator.goal = prompt.clone();
667                if let Some(ref g) = session.gate {
668                    session.state.orchestrator.verification_cmd = g.clone();
669                }
670
671                // Build task configuration from current session parameters
672                let task_config = session.task_config_for_prompt(&prompt);
673
674                // Invoke solver task runner preserving state and outputting directly to REPL writer
675                match crate::task_runner::run_task_with_state_and_writer(
676                    &task_config,
677                    &mut session.state,
678                    &mut writer,
679                ) {
680                    Ok((
681                        blyte_agent::run::Outcome::Verified | blyte_agent::run::Outcome::Finished,
682                        report,
683                    )) => {
684                        if session.orchestrate {
685                            let totals = current_session_totals(&session.session_id);
686                            writeln!(
687                                writer,
688                                "{}",
689                                format_usage_line_with_session(
690                                    report.outcome_turns,
691                                    &report.usage,
692                                    &totals
693                                )
694                            )
695                            .map_err(|e| e.to_string())?;
696                        } else {
697                            writeln!(
698                                writer,
699                                "Task verified in {} turns (usage: {:?})",
700                                report.outcome_turns, report.usage
701                            )
702                            .map_err(|e| e.to_string())?;
703                        }
704                    }
705                    Ok((outcome, report)) => {
706                        if session.orchestrate {
707                            let totals = current_session_totals(&session.session_id);
708                            writeln!(
709                                writer,
710                                "Stopped ({outcome:?}): {}",
711                                format_usage_line_with_session(
712                                    report.outcome_turns,
713                                    &report.usage,
714                                    &totals
715                                )
716                            )
717                            .map_err(|e| e.to_string())?;
718                        } else {
719                            writeln!(
720                                writer,
721                                "Task finished with outcome: {:?} in {} turns",
722                                outcome, report.outcome_turns
723                            )
724                            .map_err(|e| e.to_string())?;
725                        }
726                    }
727                    Err(err) => {
728                        writeln!(writer, "Task execution error: {}", err)
729                            .map_err(|e| e.to_string())?;
730                    }
731                }
732            }
733        }
734    }
735    Ok(())
736}
737
738/// Initializes a REPL session and runs the interactive terminal loop.
739pub fn run_repl(config: ReplConfig) -> Result<(), String> {
740    let session = ReplSession::try_new(&config)?;
741    render_banner(&session);
742    let stdin = std::io::stdin();
743    let stdout = std::io::stdout();
744    run_repl_stream(stdin.lock(), stdout.lock(), session)
745}
746
747#[cfg(test)]
748mod tests {
749    use super::*;
750
751    #[test]
752    fn test_new_session_id_format() {
753        assert_eq!(new_session_id(1700000000, 42), "1700000000-42");
754    }
755
756    #[test]
757    fn test_repl_state_contains_session() {
758        let config = ReplConfig::default();
759        let mut session = ReplSession::new(&config);
760        let instructions = "x".repeat(600);
761        session.state.orchestrator.instructions = Some(instructions.clone());
762        let mut out = Vec::new();
763        let res = handle_repl_command(&mut session, "/state", &mut out).unwrap();
764        assert_eq!(res, ReplControl::Handled);
765        let text = String::from_utf8(out).unwrap();
766        assert!(text.contains("session: "));
767        assert!(text.contains(&format!("session: {}", session.session_id)));
768        assert!(text.contains("<600 characters>"));
769        assert!(!text.contains(&instructions));
770    }
771
772    #[test]
773    fn test_repl_cost_command_with_usage_log() {
774        let tmp = tempfile::tempdir().unwrap();
775        let log_path = tmp.path().join("usage.jsonl");
776
777        let config = ReplConfig {
778            repo_root: tmp.path().to_path_buf(),
779            orchestrate: true,
780            ..Default::default()
781        };
782        let mut session = ReplSession::new(&config);
783
784        let entry1 = crate::usage_log::Entry {
785            ts: 1700000000,
786            repo: "/test/repo".into(),
787            session: Some(session.session_id.clone()),
788            dispatch: None,
789            research: false,
790            model: "model-a".into(),
791            outcome: "verified".into(),
792            turns: 2,
793            input: 500,
794            cached: 100,
795            output: 200,
796            thinking: 0,
797            cost_usd: Some(0.12),
798        };
799
800        let entry2 = crate::usage_log::Entry {
801            ts: 1700000010,
802            repo: "/test/repo".into(),
803            session: Some(session.session_id.clone()),
804            dispatch: Some("disp-1".into()),
805            research: false,
806            model: "model-b".into(),
807            outcome: "verified".into(),
808            turns: 5,
809            input: 1000,
810            cached: 200,
811            output: 400,
812            thinking: 0,
813            cost_usd: Some(0.34),
814        };
815
816        crate::usage_log::append(&log_path, &entry1).unwrap();
817        crate::usage_log::append(&log_path, &entry2).unwrap();
818
819        let _env_guard = crate::usage_log::ENV_LOCK
820            .lock()
821            .unwrap_or_else(|e| e.into_inner());
822        let old_env = std::env::var_os("BLYTE_USAGE_LOG");
823        std::env::set_var("BLYTE_USAGE_LOG", &log_path);
824
825        let mut out = Vec::new();
826        let res = handle_repl_command(&mut session, "/cost", &mut out).unwrap();
827        assert_eq!(res, ReplControl::Handled);
828
829        match old_env {
830            Some(val) => std::env::set_var("BLYTE_USAGE_LOG", val),
831            None => std::env::remove_var("BLYTE_USAGE_LOG"),
832        }
833
834        let text = String::from_utf8(out).unwrap();
835        assert_eq!(
836            text.trim(),
837            "blyte $0.46 (orchestrator $0.12, implementers $0.34 in 1 runs)"
838        );
839    }
840
841    #[test]
842    fn test_format_usage_line_with_session() {
843        let usage = blyte_provider::Usage {
844            input: 12000,
845            cached: 9000,
846            output: 450,
847            thinking: 0,
848        };
849        let totals = crate::cost::Totals {
850            orchestrator_usd: 0.15,
851            implementers_usd: 0.35,
852            runs: 2,
853        };
854        let line = format_usage_line_with_session(3, &usage, &totals);
855        assert_eq!(
856            line,
857            "3 turns · 12000 in (9000 cached) · 450 out · session $0.50 (implementers $0.35, 2 runs)"
858        );
859    }
860}