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