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