blyte 0.89.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::path::PathBuf;
use std::sync::Arc;

/// Configuration options for launching a session.
#[derive(Debug, Clone)]
pub struct ReplConfig {
    pub repo_root: PathBuf,
    pub model: Option<String>,
    pub gate: Option<String>,
    pub context_strategy: String,
    pub container: Option<String>,
    pub max_turns: usize,
    pub max_gates: usize,
    pub rollback: bool,
    pub converse: bool,
    pub dispatch_cmd: Option<String>,
    pub fold_budget: Option<usize>,
    pub sandbox: String,
    pub network: Option<String>,
    pub allow_read: Vec<PathBuf>,
    pub pass_env: Vec<String>,
}

impl Default for ReplConfig {
    fn default() -> Self {
        Self {
            repo_root: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            model: None,
            gate: None,
            context_strategy: "folded".to_string(),
            container: None,
            max_turns: 60,
            max_gates: 5,
            rollback: true,
            converse: false,
            dispatch_cmd: None,
            fold_budget: None,
            sandbox: "on".to_string(),
            network: None,
            allow_read: Vec::new(),
            pass_env: Vec::new(),
        }
    }
}

/// Active state and parameters of an ongoing session.
pub struct ReplSession {
    pub repo_root: PathBuf,
    pub gate: Option<String>,
    pub model: String,
    pub context_strategy: String,
    pub container: Option<String>,
    pub max_turns: usize,
    pub max_gates: usize,
    pub rollback: bool,
    pub converse: bool,
    pub dispatch_cmd: Option<String>,
    pub fold_budget: Option<usize>,
    pub sandbox: String,
    pub network: String,
    pub allow_read: Vec<PathBuf>,
    pub pass_env: Vec<String>,
    pub state: blyte_agent::state::State,
    pub session_id: String,
    private_tmpdir: Option<PathBuf>,
}

impl Drop for ReplSession {
    fn drop(&mut self) {
        if let Some(ref dir) = self.private_tmpdir {
            let _ = std::fs::remove_dir_all(dir);
        }
    }
}

/// Formats a session identifier from a Unix timestamp (in seconds) and process ID.
pub fn new_session_id(now_secs: u64, pid: u32) -> String {
    format!("{now_secs}-{pid}")
}

impl ReplSession {
    /// Creates a new `ReplSession` initialized with the given `ReplConfig`.
    pub fn try_new(config: &ReplConfig) -> Result<Self, String> {
        Self::try_new_with_approver(config, None)
    }

    /// Creates a new `ReplSession` initialized with the given `ReplConfig` and optional approver.
    pub fn try_new_with_approver(
        config: &ReplConfig,
        approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
    ) -> Result<Self, String> {
        let session_id = match std::env::var("BLYTE_SESSION") {
            Ok(v) if !v.is_empty() => v,
            _ => {
                let now_secs = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let id = new_session_id(now_secs, std::process::id());
                std::env::set_var("BLYTE_SESSION", &id);
                id
            }
        };

        let gate = config.gate.clone();
        let verification_cmd = gate.clone().unwrap_or_default();
        let goal = "Interactive REPL session".to_string();
        let mut state = blyte_agent::state::State::new(goal, verification_cmd);
        state.runtime.conversation = Some(Vec::new());

        let network = match &config.network {
            Some(v) => v.clone(),
            None if config.converse && config.sandbox == "on" && config.container.is_none() => {
                "off".to_string()
            }
            None => "on".to_string(),
        };

        let sandbox_on = config.sandbox == "on";
        let policy = crate::task_runner::configure_converse_policy_with_paths(
            config.converse,
            sandbox_on,
            &config.repo_root,
            approver,
        )?;
        if config.converse {
            if let Err(e) = crate::conversation_text::set_state_instructions(
                &mut state,
                config.dispatch_cmd.is_some(),
                &config.repo_root,
                sandbox_on,
                policy.allowed_count,
            ) {
                if let Some(ref dir) = policy.private_tmpdir {
                    let _ = std::fs::remove_dir_all(dir);
                }
                return Err(e);
            }
        }

        Ok(Self {
            repo_root: config.repo_root.clone(),
            gate,
            model: config
                .model
                .clone()
                .unwrap_or_else(|| "gemini-3.8-flash".to_string()),
            context_strategy: config.context_strategy.clone(),
            container: config.container.clone(),
            max_turns: config.max_turns,
            max_gates: config.max_gates,
            rollback: config.rollback,
            converse: config.converse,
            dispatch_cmd: config.dispatch_cmd.clone(),
            fold_budget: config.fold_budget,
            sandbox: config.sandbox.clone(),
            network,
            allow_read: config.allow_read.clone(),
            pass_env: config.pass_env.clone(),
            state,
            session_id,
            private_tmpdir: policy.private_tmpdir,
        })
    }

    /// Returns the private temporary directory created for this session, if any.
    pub fn private_tmpdir(&self) -> Option<&std::path::Path> {
        self.private_tmpdir.as_deref()
    }

    /// Creates a new `ReplSession` initialized with the given `ReplConfig`.
    pub fn new(config: &ReplConfig) -> Self {
        Self::try_new(config).expect("failed to initialize REPL session")
    }

    pub fn task_config_for_prompt(&self, prompt: &str) -> crate::task_runner::TaskConfig {
        crate::task_runner::TaskConfig {
            prompt: prompt.to_string(),
            gate: self.gate.clone(),
            context_strategy: self.context_strategy.clone(),
            model: Some(self.model.clone()),
            container: self.container.clone(),
            max_turns: self.max_turns,
            max_gates: self.max_gates,
            rollback: self.rollback,
            root: self.repo_root.clone(),
            container_workdir: "/workspace".into(),
            max_seconds: None,
            max_cost_usd: None,
            report: None,
            fold_budget: self.fold_budget,
            sandbox: self.sandbox.clone(),
            network: self.network.clone(),
            allow_read: self.allow_read.clone(),
            pass_env: self.pass_env.clone(),
            research: false,
            claim_check: false,
            base_check: false,
            base_check_dir: None,
            converse: self.converse,
            dispatch_cmd: self.dispatch_cmd.clone(),
            in_place: None,
        }
    }
}

fn format_tokens_short(tokens: u64) -> String {
    if tokens < 1_000 {
        return tokens.to_string();
    }
    let k = (tokens + 500) / 1_000;
    let digits = k.to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3 + 1);
    for (idx, ch) in digits.chars().enumerate() {
        let remaining = digits.len() - idx;
        if idx > 0 && remaining.is_multiple_of(3) {
            out.push(',');
        }
        out.push(ch);
    }
    out.push('k');
    out
}

pub fn format_turn_metrics(
    usage: &blyte_provider::Usage,
    timing: &blyte_agent::run::TurnTiming,
) -> Option<String> {
    let total_in = usage.input + usage.cached;
    if timing.total_ms == 0
        && timing.first_output_ms.is_none()
        && total_in == 0
        && timing.retries == 0
    {
        return None;
    }
    let mut parts = Vec::new();
    if let Some(first_output_ms) = timing.first_output_ms {
        parts.push(format!(
            "first output {:.1} s",
            first_output_ms as f64 / 1_000.0
        ));
    }
    parts.push(format!("total {:.1} s", timing.total_ms as f64 / 1_000.0));
    if timing.retries > 0 {
        let label = if timing.retries == 1 {
            "retry"
        } else {
            "retries"
        };
        parts.push(format!("{} {label}", timing.retries));
    }
    if total_in > 0 {
        if usage.cached > 0 {
            parts.push(format!(
                "{} in ({} cached)",
                format_tokens_short(total_in),
                format_tokens_short(usage.cached)
            ));
        } else {
            parts.push(format!("{} in", format_tokens_short(total_in)));
        }
    }
    Some(parts.join(" · "))
}

/// Formats a runtime event emitted during agent turn or gate execution.
pub fn format_event(event: &blyte_agent::run::Event<'_>) -> String {
    match event {
        blyte_agent::run::Event::Turn {
            n,
            text,
            usage,
            timing,
        } => match format_turn_metrics(usage, timing) {
            Some(metrics) if text.is_empty() => format!("[Turn {n}] {metrics}"),
            Some(metrics) => format!("[Turn {n}] {metrics}\n{text}"),
            None => format!("[Turn {n}] {text}"),
        },
        blyte_agent::run::Event::Tool {
            name,
            input,
            summary,
            is_error,
        } => {
            if *is_error {
                format!("\x1b[31m● {} {} -> {}\x1b[0m", name, input, summary)
            } else {
                format!("● {} {} -> {}", name, input, summary)
            }
        }
        blyte_agent::run::Event::GateStart { attempt } => {
            format!("⏳ Gate running (attempt {})", attempt)
        }
        blyte_agent::run::Event::GateSlotWait { ms } => {
            format!("⏳ Gate waited {}ms for slot", ms)
        }
        blyte_agent::run::Event::Gate {
            attempt,
            passed,
            output,
        } => {
            if *passed {
                format!("✓ Gate passed (attempt {})", attempt)
            } else {
                format!("✗ Gate failed (attempt {}): {}", attempt, output.trim())
            }
        }
        blyte_agent::run::Event::RolledBack { to } => {
            format!("↺ Rolled back working tree to {}", to)
        }
        blyte_agent::run::Event::FirstOutput { .. }
        | blyte_agent::run::Event::ToolStart { .. }
        | blyte_agent::run::Event::Retry { .. } => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use blyte_agent::run::Event;

    #[test]
    fn test_new_session_id_format() {
        assert_eq!(new_session_id(1700000000, 42), "1700000000-42");
    }

    #[test]
    fn test_repl_session_default_model_is_gemini_3_8_flash() {
        let session = ReplSession::new(&ReplConfig::default());
        assert_eq!(session.model, "gemini-3.8-flash");
    }

    #[test]
    fn test_format_event() {
        let e1 = Event::Turn {
            n: 1,
            text: "Thinking about plan",
            usage: Default::default(),
            timing: Default::default(),
        };
        let s1 = format_event(&e1);
        assert!(s1.contains('1') && s1.contains("Thinking about plan"));

        let e2 = Event::Tool {
            name: "bash",
            input: "git status".to_string(),
            summary: "clean working tree".to_string(),
            is_error: false,
        };
        let s2 = format_event(&e2);
        assert!(s2.contains('●') && s2.contains("bash") && s2.contains("git status"));

        let e3 = Event::Tool {
            name: "bash",
            input: "cargo test".to_string(),
            summary: "exit 101".to_string(),
            is_error: true,
        };
        let s3 = format_event(&e3);
        assert!(s3.contains('●') && s3.contains("cargo test"));

        let e4 = Event::Gate {
            attempt: 1,
            passed: true,
            output: "ok",
        };
        let s4 = format_event(&e4);
        assert!(s4.contains("✓ Gate passed"));

        let e5 = Event::Gate {
            attempt: 2,
            passed: false,
            output: "failed",
        };
        let s5 = format_event(&e5);
        assert!(s5.contains("✗ Gate failed"));

        let e6 = Event::RolledBack { to: "abc1234" };
        let s6 = format_event(&e6);
        assert!(s6.contains("↺ Rolled back working tree to abc1234"));
    }

    #[test]
    fn test_format_event_turn_full_text() {
        let text = "x".repeat(299) + "Z";
        let event = Event::Turn {
            n: 3,
            text: &text,
            usage: Default::default(),
            timing: Default::default(),
        };
        let formatted = format_event(&event);
        assert_eq!(formatted, format!("[Turn 3] {text}"));
        assert!(formatted.contains('Z'));
        assert!(!formatted.ends_with("..."));
    }

    #[test]
    fn test_format_event_turn_multiline() {
        let text = "Plan:\n1. a\n2. b\nShall I go ahead?";
        let event = Event::Turn {
            n: 1,
            text,
            usage: Default::default(),
            timing: Default::default(),
        };
        assert_eq!(
            format_event(&event),
            "[Turn 1] Plan:\n1. a\n2. b\nShall I go ahead?"
        );
    }

    #[test]
    fn test_format_event_turn_multibyte() {
        let text = "é".repeat(100);
        let event = Event::Turn {
            n: 1,
            text: &text,
            usage: Default::default(),
            timing: Default::default(),
        };
        let formatted = format_event(&event);
        assert_eq!(formatted.chars().count(), "[Turn 1] ".len() + 100);
    }

    #[test]
    fn test_format_event_turn_with_timing_and_cache() {
        let event = Event::Turn {
            n: 2,
            text: "",
            usage: blyte_provider::Usage {
                input: 15_000,
                cached: 230_000,
                output: 500,
                thinking: 200,
            },
            timing: blyte_agent::run::TurnTiming {
                first_event_ms: Some(2_000),
                first_output_ms: Some(18_200),
                total_ms: 24_000,
                retries: 0,
                retry_wait_ms: 0,
            },
        };
        assert_eq!(
            format_event(&event),
            "[Turn 2] first output 18.2 s · total 24.0 s · 245k in (230k cached)"
        );
    }

    #[test]
    fn a_gate_start_renders_as_gate_running() {
        let e = Event::GateStart { attempt: 2 };
        assert_eq!(format_event(&e), "⏳ Gate running (attempt 2)");
    }
}