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