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