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
207/// Formats a runtime event emitted during agent turn or gate execution.
208pub fn format_event(event: &blyte_agent::run::Event<'_>) -> String {
209    match event {
210        blyte_agent::run::Event::Turn { n, text, .. } => {
211            format!("[Turn {}] {}", n, text)
212        }
213        blyte_agent::run::Event::Tool {
214            name,
215            input,
216            summary,
217            is_error,
218        } => {
219            if *is_error {
220                format!("\x1b[31m● {} {} -> {}\x1b[0m", name, input, summary)
221            } else {
222                format!("● {} {} -> {}", name, input, summary)
223            }
224        }
225        blyte_agent::run::Event::GateStart { attempt } => {
226            format!("⏳ Gate running (attempt {})", attempt)
227        }
228        blyte_agent::run::Event::GateSlotWait { ms } => {
229            format!("⏳ Gate waited {}ms for slot", ms)
230        }
231        blyte_agent::run::Event::Gate {
232            attempt,
233            passed,
234            output,
235        } => {
236            if *passed {
237                format!("✓ Gate passed (attempt {})", attempt)
238            } else {
239                format!("✗ Gate failed (attempt {}): {}", attempt, output.trim())
240            }
241        }
242        blyte_agent::run::Event::RolledBack { to } => {
243            format!("↺ Rolled back working tree to {}", to)
244        }
245        blyte_agent::run::Event::FirstOutput { .. }
246        | blyte_agent::run::Event::ToolStart { .. }
247        | blyte_agent::run::Event::Retry { .. } => String::new(),
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use blyte_agent::run::Event;
255
256    #[test]
257    fn test_new_session_id_format() {
258        assert_eq!(new_session_id(1700000000, 42), "1700000000-42");
259    }
260
261    #[test]
262    fn test_repl_session_default_model_is_gemini_3_8_flash() {
263        let session = ReplSession::new(&ReplConfig::default());
264        assert_eq!(session.model, "gemini-3.8-flash");
265    }
266
267    #[test]
268    fn test_format_event() {
269        let e1 = Event::Turn {
270            n: 1,
271            text: "Thinking about plan",
272            usage: Default::default(),
273        };
274        let s1 = format_event(&e1);
275        assert!(s1.contains('1') && s1.contains("Thinking about plan"));
276
277        let e2 = Event::Tool {
278            name: "bash",
279            input: "git status".to_string(),
280            summary: "clean working tree".to_string(),
281            is_error: false,
282        };
283        let s2 = format_event(&e2);
284        assert!(s2.contains('●') && s2.contains("bash") && s2.contains("git status"));
285
286        let e3 = Event::Tool {
287            name: "bash",
288            input: "cargo test".to_string(),
289            summary: "exit 101".to_string(),
290            is_error: true,
291        };
292        let s3 = format_event(&e3);
293        assert!(s3.contains('●') && s3.contains("cargo test"));
294
295        let e4 = Event::Gate {
296            attempt: 1,
297            passed: true,
298            output: "ok",
299        };
300        let s4 = format_event(&e4);
301        assert!(s4.contains("✓ Gate passed"));
302
303        let e5 = Event::Gate {
304            attempt: 2,
305            passed: false,
306            output: "failed",
307        };
308        let s5 = format_event(&e5);
309        assert!(s5.contains("✗ Gate failed"));
310
311        let e6 = Event::RolledBack { to: "abc1234" };
312        let s6 = format_event(&e6);
313        assert!(s6.contains("↺ Rolled back working tree to abc1234"));
314    }
315
316    #[test]
317    fn test_format_event_turn_full_text() {
318        let text = "x".repeat(299) + "Z";
319        let event = Event::Turn {
320            n: 3,
321            text: &text,
322            usage: Default::default(),
323        };
324        let formatted = format_event(&event);
325        assert_eq!(formatted, format!("[Turn 3] {text}"));
326        assert!(formatted.contains('Z'));
327        assert!(!formatted.ends_with("..."));
328    }
329
330    #[test]
331    fn test_format_event_turn_multiline() {
332        let text = "Plan:\n1. a\n2. b\nShall I go ahead?";
333        let event = Event::Turn {
334            n: 1,
335            text,
336            usage: Default::default(),
337        };
338        assert_eq!(
339            format_event(&event),
340            "[Turn 1] Plan:\n1. a\n2. b\nShall I go ahead?"
341        );
342    }
343
344    #[test]
345    fn test_format_event_turn_multibyte() {
346        let text = "é".repeat(100);
347        let event = Event::Turn {
348            n: 1,
349            text: &text,
350            usage: Default::default(),
351        };
352        let formatted = format_event(&event);
353        assert_eq!(formatted.chars().count(), "[Turn 1] ".len() + 100);
354    }
355
356    #[test]
357    fn a_gate_start_renders_as_gate_running() {
358        let e = Event::GateStart { attempt: 2 };
359        assert_eq!(format_event(&e), "⏳ Gate running (attempt 2)");
360    }
361}