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