Skip to main content

blyte_cli/
repl.rs

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