Skip to main content

blyte_cli/
repl.rs

1use std::path::PathBuf;
2use std::sync::Arc;
3
4/// Configuration options for launching a session.
5#[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 converse: bool,
16    pub dispatch_cmd: Option<String>,
17    pub fold_budget: Option<usize>,
18    pub sandbox: String,
19    pub network: Option<String>,
20    pub allow_read: Vec<PathBuf>,
21    pub pass_env: Vec<String>,
22}
23
24impl Default for ReplConfig {
25    fn default() -> Self {
26        Self {
27            repo_root: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
28            model: None,
29            gate: None,
30            context_strategy: "folded".to_string(),
31            container: None,
32            max_turns: 60,
33            max_gates: 5,
34            rollback: true,
35            converse: false,
36            dispatch_cmd: None,
37            fold_budget: None,
38            sandbox: "on".to_string(),
39            network: None,
40            allow_read: Vec::new(),
41            pass_env: Vec::new(),
42        }
43    }
44}
45
46/// Active state and parameters of an ongoing session.
47pub struct ReplSession {
48    pub repo_root: PathBuf,
49    pub gate: Option<String>,
50    pub model: String,
51    pub context_strategy: String,
52    pub container: Option<String>,
53    pub max_turns: usize,
54    pub max_gates: usize,
55    pub rollback: bool,
56    pub converse: bool,
57    pub dispatch_cmd: Option<String>,
58    pub fold_budget: Option<usize>,
59    pub sandbox: String,
60    pub network: String,
61    pub allow_read: Vec<PathBuf>,
62    pub pass_env: Vec<String>,
63    pub state: blyte_agent::state::State,
64    pub session_id: String,
65    private_tmpdir: Option<PathBuf>,
66}
67
68impl Drop for ReplSession {
69    fn drop(&mut self) {
70        if let Some(ref dir) = self.private_tmpdir {
71            let _ = std::fs::remove_dir_all(dir);
72        }
73    }
74}
75
76/// Formats a session identifier from a Unix timestamp (in seconds) and process ID.
77pub fn new_session_id(now_secs: u64, pid: u32) -> String {
78    format!("{now_secs}-{pid}")
79}
80
81impl ReplSession {
82    /// Creates a new `ReplSession` initialized with the given `ReplConfig`.
83    pub fn try_new(config: &ReplConfig) -> Result<Self, String> {
84        Self::try_new_with_approver(config, None)
85    }
86
87    /// Creates a new `ReplSession` initialized with the given `ReplConfig` and optional approver.
88    pub fn try_new_with_approver(
89        config: &ReplConfig,
90        approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
91    ) -> Result<Self, String> {
92        let session_id = match std::env::var("BLYTE_SESSION") {
93            Ok(v) if !v.is_empty() => v,
94            _ => {
95                let now_secs = std::time::SystemTime::now()
96                    .duration_since(std::time::UNIX_EPOCH)
97                    .map(|d| d.as_secs())
98                    .unwrap_or(0);
99                let id = new_session_id(now_secs, std::process::id());
100                std::env::set_var("BLYTE_SESSION", &id);
101                id
102            }
103        };
104
105        let gate = config.gate.clone();
106        let verification_cmd = gate.clone().unwrap_or_default();
107        let goal = "Interactive REPL session".to_string();
108        let mut state = blyte_agent::state::State::new(goal, verification_cmd);
109        state.runtime.conversation = Some(Vec::new());
110
111        let network = match &config.network {
112            Some(v) => v.clone(),
113            None if config.converse && config.sandbox == "on" && config.container.is_none() => {
114                "off".to_string()
115            }
116            None => "on".to_string(),
117        };
118
119        let sandbox_on = config.sandbox == "on";
120        let policy = crate::task_runner::configure_converse_policy_with_paths(
121            config.converse,
122            sandbox_on,
123            &config.repo_root,
124            approver,
125        )?;
126        if config.converse {
127            if let Err(e) = crate::conversation_text::set_state_instructions(
128                &mut state,
129                config.dispatch_cmd.is_some(),
130                &config.repo_root,
131                sandbox_on,
132                policy.allowed_count,
133            ) {
134                if let Some(ref dir) = policy.private_tmpdir {
135                    let _ = std::fs::remove_dir_all(dir);
136                }
137                return Err(e);
138            }
139        }
140
141        Ok(Self {
142            repo_root: config.repo_root.clone(),
143            gate,
144            model: config
145                .model
146                .clone()
147                .unwrap_or_else(|| "gemini-3.8-flash".to_string()),
148            context_strategy: config.context_strategy.clone(),
149            container: config.container.clone(),
150            max_turns: config.max_turns,
151            max_gates: config.max_gates,
152            rollback: config.rollback,
153            converse: config.converse,
154            dispatch_cmd: config.dispatch_cmd.clone(),
155            fold_budget: config.fold_budget,
156            sandbox: config.sandbox.clone(),
157            network,
158            allow_read: config.allow_read.clone(),
159            pass_env: config.pass_env.clone(),
160            state,
161            session_id,
162            private_tmpdir: policy.private_tmpdir,
163        })
164    }
165
166    /// Returns the private temporary directory created for this session, if any.
167    pub fn private_tmpdir(&self) -> Option<&std::path::Path> {
168        self.private_tmpdir.as_deref()
169    }
170
171    /// Creates a new `ReplSession` initialized with the given `ReplConfig`.
172    pub fn new(config: &ReplConfig) -> Self {
173        Self::try_new(config).expect("failed to initialize REPL session")
174    }
175
176    pub fn task_config_for_prompt(&self, prompt: &str) -> crate::task_runner::TaskConfig {
177        crate::task_runner::TaskConfig {
178            prompt: prompt.to_string(),
179            gate: self.gate.clone(),
180            context_strategy: self.context_strategy.clone(),
181            model: Some(self.model.clone()),
182            container: self.container.clone(),
183            max_turns: self.max_turns,
184            max_gates: self.max_gates,
185            rollback: self.rollback,
186            root: self.repo_root.clone(),
187            container_workdir: "/workspace".into(),
188            max_seconds: None,
189            max_cost_usd: None,
190            report: None,
191            fold_budget: self.fold_budget,
192            sandbox: self.sandbox.clone(),
193            network: self.network.clone(),
194            allow_read: self.allow_read.clone(),
195            pass_env: self.pass_env.clone(),
196            research: false,
197            claim_check: false,
198            base_check: false,
199            base_check_dir: None,
200            converse: self.converse,
201            dispatch_cmd: self.dispatch_cmd.clone(),
202            in_place: None,
203        }
204    }
205}
206
207fn format_tokens_short(tokens: u64) -> String {
208    if tokens < 1_000 {
209        return tokens.to_string();
210    }
211    let k = (tokens + 500) / 1_000;
212    let digits = k.to_string();
213    let mut out = String::with_capacity(digits.len() + digits.len() / 3 + 1);
214    for (idx, ch) in digits.chars().enumerate() {
215        let remaining = digits.len() - idx;
216        if idx > 0 && remaining.is_multiple_of(3) {
217            out.push(',');
218        }
219        out.push(ch);
220    }
221    out.push('k');
222    out
223}
224
225pub fn format_turn_metrics(
226    usage: &blyte_provider::Usage,
227    timing: &blyte_agent::run::TurnTiming,
228) -> Option<String> {
229    let total_in = usage.input + usage.cached;
230    if timing.total_ms == 0
231        && timing.first_output_ms.is_none()
232        && total_in == 0
233        && timing.retries == 0
234    {
235        return None;
236    }
237    let mut parts = Vec::new();
238    if let Some(first_output_ms) = timing.first_output_ms {
239        parts.push(format!(
240            "first output {:.1} s",
241            first_output_ms as f64 / 1_000.0
242        ));
243    }
244    parts.push(format!("total {:.1} s", timing.total_ms as f64 / 1_000.0));
245    if timing.retries > 0 {
246        let label = if timing.retries == 1 {
247            "retry"
248        } else {
249            "retries"
250        };
251        parts.push(format!("{} {label}", timing.retries));
252    }
253    if total_in > 0 {
254        if usage.cached > 0 {
255            parts.push(format!(
256                "{} in ({} cached)",
257                format_tokens_short(total_in),
258                format_tokens_short(usage.cached)
259            ));
260        } else {
261            parts.push(format!("{} in", format_tokens_short(total_in)));
262        }
263    }
264    Some(parts.join(" · "))
265}
266
267/// Formats a runtime event emitted during agent turn or gate execution.
268pub fn format_event(event: &blyte_agent::run::Event<'_>) -> String {
269    match event {
270        blyte_agent::run::Event::Turn {
271            n,
272            text,
273            usage,
274            timing,
275        } => match format_turn_metrics(usage, timing) {
276            Some(metrics) if text.is_empty() => format!("[Turn {n}] {metrics}"),
277            Some(metrics) => format!("[Turn {n}] {metrics}\n{text}"),
278            None => format!("[Turn {n}] {text}"),
279        },
280        blyte_agent::run::Event::Tool {
281            name,
282            input,
283            summary,
284            is_error,
285        } => {
286            if *is_error {
287                format!("\x1b[31m● {} {} -> {}\x1b[0m", name, input, summary)
288            } else {
289                format!("● {} {} -> {}", name, input, summary)
290            }
291        }
292        blyte_agent::run::Event::GateStart { attempt } => {
293            format!("⏳ Gate running (attempt {})", attempt)
294        }
295        blyte_agent::run::Event::GateSlotWait { ms } => {
296            format!("⏳ Gate waited {}ms for slot", ms)
297        }
298        blyte_agent::run::Event::Gate {
299            attempt,
300            passed,
301            output,
302        } => {
303            if *passed {
304                format!("✓ Gate passed (attempt {})", attempt)
305            } else {
306                format!("✗ Gate failed (attempt {}): {}", attempt, output.trim())
307            }
308        }
309        blyte_agent::run::Event::RolledBack { to } => {
310            format!("↺ Rolled back working tree to {}", to)
311        }
312        blyte_agent::run::Event::FirstOutput { .. }
313        | blyte_agent::run::Event::ToolStart { .. }
314        | blyte_agent::run::Event::Retry { .. } => String::new(),
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use blyte_agent::run::Event;
322
323    #[test]
324    fn test_new_session_id_format() {
325        assert_eq!(new_session_id(1700000000, 42), "1700000000-42");
326    }
327
328    #[test]
329    fn test_repl_session_default_model_is_gemini_3_8_flash() {
330        let session = ReplSession::new(&ReplConfig::default());
331        assert_eq!(session.model, "gemini-3.8-flash");
332    }
333
334    #[test]
335    fn test_format_event() {
336        let e1 = Event::Turn {
337            n: 1,
338            text: "Thinking about plan",
339            usage: Default::default(),
340            timing: Default::default(),
341        };
342        let s1 = format_event(&e1);
343        assert!(s1.contains('1') && s1.contains("Thinking about plan"));
344
345        let e2 = Event::Tool {
346            name: "bash",
347            input: "git status".to_string(),
348            summary: "clean working tree".to_string(),
349            is_error: false,
350        };
351        let s2 = format_event(&e2);
352        assert!(s2.contains('●') && s2.contains("bash") && s2.contains("git status"));
353
354        let e3 = Event::Tool {
355            name: "bash",
356            input: "cargo test".to_string(),
357            summary: "exit 101".to_string(),
358            is_error: true,
359        };
360        let s3 = format_event(&e3);
361        assert!(s3.contains('●') && s3.contains("cargo test"));
362
363        let e4 = Event::Gate {
364            attempt: 1,
365            passed: true,
366            output: "ok",
367        };
368        let s4 = format_event(&e4);
369        assert!(s4.contains("✓ Gate passed"));
370
371        let e5 = Event::Gate {
372            attempt: 2,
373            passed: false,
374            output: "failed",
375        };
376        let s5 = format_event(&e5);
377        assert!(s5.contains("✗ Gate failed"));
378
379        let e6 = Event::RolledBack { to: "abc1234" };
380        let s6 = format_event(&e6);
381        assert!(s6.contains("↺ Rolled back working tree to abc1234"));
382    }
383
384    #[test]
385    fn test_format_event_turn_full_text() {
386        let text = "x".repeat(299) + "Z";
387        let event = Event::Turn {
388            n: 3,
389            text: &text,
390            usage: Default::default(),
391            timing: Default::default(),
392        };
393        let formatted = format_event(&event);
394        assert_eq!(formatted, format!("[Turn 3] {text}"));
395        assert!(formatted.contains('Z'));
396        assert!(!formatted.ends_with("..."));
397    }
398
399    #[test]
400    fn test_format_event_turn_multiline() {
401        let text = "Plan:\n1. a\n2. b\nShall I go ahead?";
402        let event = Event::Turn {
403            n: 1,
404            text,
405            usage: Default::default(),
406            timing: Default::default(),
407        };
408        assert_eq!(
409            format_event(&event),
410            "[Turn 1] Plan:\n1. a\n2. b\nShall I go ahead?"
411        );
412    }
413
414    #[test]
415    fn test_format_event_turn_multibyte() {
416        let text = "é".repeat(100);
417        let event = Event::Turn {
418            n: 1,
419            text: &text,
420            usage: Default::default(),
421            timing: Default::default(),
422        };
423        let formatted = format_event(&event);
424        assert_eq!(formatted.chars().count(), "[Turn 1] ".len() + 100);
425    }
426
427    #[test]
428    fn test_format_event_turn_with_timing_and_cache() {
429        let event = Event::Turn {
430            n: 2,
431            text: "",
432            usage: blyte_provider::Usage {
433                input: 15_000,
434                cached: 230_000,
435                output: 500,
436                thinking: 200,
437            },
438            timing: blyte_agent::run::TurnTiming {
439                first_event_ms: Some(2_000),
440                first_output_ms: Some(18_200),
441                total_ms: 24_000,
442                retries: 0,
443                retry_wait_ms: 0,
444            },
445        };
446        assert_eq!(
447            format_event(&event),
448            "[Turn 2] first output 18.2 s · total 24.0 s · 245k in (230k cached)"
449        );
450    }
451
452    #[test]
453    fn a_gate_start_renders_as_gate_running() {
454        let e = Event::GateStart { attempt: 2 };
455        assert_eq!(format_event(&e), "⏳ Gate running (attempt 2)");
456    }
457}