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