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