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