blyte-agent 0.93.0

The blyte agent loop: tools, context, persistent shell sessions, search and the command sandbox.
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! The loop, driven by a scripted provider so the behaviour is deterministic.

use std::path::Path;
use std::process::Command;
use std::sync::Mutex;
use std::time::Duration;

use blyte_agent::context::{ContextStrategy, Conversational};
use blyte_agent::fs::LocalFs;
use blyte_agent::run::{Budget, Outcome, Runner};
use blyte_agent::shell::{Output, Shell};
use blyte_agent::state::State;
use blyte_provider::{Provider, ProviderError, Request, Response, ToolCall, Usage};
use serde_json::json;

struct StubShell;

impl Shell for StubShell {
    fn exec(&self, command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
        let trimmed = command.trim();
        if command.lines().any(|l| l.trim() == "true") {
            return Ok(Output {
                stdout: String::new(),
                stderr: String::new(),
                exit_code: 0,
            });
        }
        if let Some(rest) = trimmed.strip_prefix("echo ") {
            return Ok(Output {
                stdout: format!("{rest}\n"),
                stderr: String::new(),
                exit_code: 0,
            });
        }
        Ok(Output {
            stdout: String::new(),
            stderr: String::new(),
            exit_code: 1,
        })
    }

    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
        self.exec(command, cwd, timeout)
    }

    fn describe(&self) -> String {
        String::new()
    }

    fn available_binaries(
        &self,
        _cwd: &Path,
        _candidates: &[&'static str],
    ) -> Result<Vec<String>, String> {
        Ok(vec!["git".into()])
    }
}

struct FastShell;

impl Shell for FastShell {
    fn exec(&self, command: &str, cwd: &Path, _timeout: Duration) -> Result<Output, String> {
        let out = Command::new("bash")
            .arg("-c")
            .arg(command)
            .current_dir(cwd)
            .output()
            .map_err(|e| format!("failed to run bash: {e}"))?;
        Ok(Output {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            exit_code: out.status.code().unwrap_or(-1),
        })
    }

    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
        self.exec(command, cwd, timeout)
    }

    fn describe(&self) -> String {
        String::new()
    }

    fn available_binaries(
        &self,
        _cwd: &Path,
        _candidates: &[&'static str],
    ) -> Result<Vec<String>, String> {
        Ok(vec!["git".into()])
    }
}

/// Replays a fixed list of responses and records every request it was given.
struct ScriptedProvider {
    script: Mutex<Vec<Response>>,
    seen: Mutex<Vec<Request>>,
}

impl ScriptedProvider {
    fn new(script: Vec<Response>) -> Self {
        Self {
            script: Mutex::new(script),
            seen: Mutex::new(Vec::new()),
        }
    }
}

impl Provider for ScriptedProvider {
    fn complete(&self, req: &Request) -> Result<Response, ProviderError> {
        self.seen.lock().unwrap().push(req.clone());
        let mut s = self.script.lock().unwrap();
        if s.is_empty() {
            // Stopping with no tool calls is how the model signals it is done.
            return Ok(Response::default());
        }
        Ok(s.remove(0))
    }
    fn model_id(&self) -> String {
        "scripted".into()
    }
}

fn says(text: &str) -> Response {
    Response {
        text: text.into(),
        ..Default::default()
    }
}

fn calls(name: &str, args: serde_json::Value) -> Response {
    Response {
        tool_calls: vec![ToolCall {
            id: "c0".into(),
            name: name.into(),
            arguments: args,
            signature: None,
        }],
        usage: Usage {
            input: 100,
            cached: 0,
            output: 10,
            thinking: 0,
        },
        ..Default::default()
    }
}

fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git")
        .args(args)
        .current_dir(dir)
        .status()
        .unwrap();
    assert!(status.success(), "git {args:?} failed");
}

fn repo() -> tempfile::TempDir {
    let d = tempfile::tempdir().unwrap();
    git(d.path(), &["init", "-q"]);
    std::fs::write(d.path().join("marker"), "0\n").unwrap();
    git(d.path(), &["add", "-A"]);
    git(
        d.path(),
        &[
            "-c",
            "user.email=a@b",
            "-c",
            "user.name=c",
            "commit",
            "-qm",
            "base",
        ],
    );
    d
}

fn runner<'a>(
    p: &'a ScriptedProvider,
    shell: &'a dyn Shell,
    root: &std::path::Path,
    ctx: &'a dyn ContextStrategy,
    rollback: bool,
) -> Runner<'a> {
    Runner {
        provider: p,
        shell,
        fs: &LocalFs,
        context: ctx,
        root: root.to_path_buf(),
        budget: Budget {
            max_turns: 12,
            max_gate_attempts: 3,
            max_duration: None,
        },
        rollback,
        on_event: None,
        research: false,
        claim_check: false,
        base_check: blyte_agent::run::BaseCheck::None,
    }
}

#[test]
fn the_gate_is_not_in_the_tool_surface() {
    // Invariant II. A gate the model can invoke is one it can decline to invoke, invoke
    // selectively, or report the result of. It must not be reachable at all.
    let names: Vec<String> = blyte_agent::tools::specs()
        .into_iter()
        .map(|t| t.name)
        .collect();
    for forbidden in [
        "verify",
        "gate",
        "check",
        "run_tests",
        "complete",
        "done",
        "finish",
    ] {
        assert!(
            !names.iter().any(|n| n == forbidden),
            "`{forbidden}` must not be callable by the model: {names:?}"
        );
    }
}

#[test]
fn stopping_triggers_the_gate_and_passing_it_ends_the_run() {
    let d = tempfile::tempdir().unwrap();
    let p = ScriptedProvider::new(vec![says("I think that is done.")]);
    let mut st = State::new("make it work", "true");
    let (outcome, rep) = runner(&p, &StubShell, d.path(), &Conversational, true).run(&mut st);
    assert_eq!(outcome, Outcome::Verified);
    assert_eq!(rep.gate_attempts, 1);
}

#[test]
fn the_model_cannot_finish_by_claiming_to_have_finished() {
    // It says it is done, confidently, repeatedly. The command disagrees, and the command wins.
    let d = tempfile::tempdir().unwrap();
    let p = ScriptedProvider::new(vec![
        says("Done! All tests pass."),
        says("Definitely finished now."),
        says("Complete."),
    ]);
    let mut st = State::new("fix it", "false");
    let (outcome, rep) = runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
    assert_eq!(outcome, Outcome::GateFailed);
    assert_eq!(
        rep.gate_attempts, 3,
        "every claim was tested, none accepted"
    );
}

#[test]
fn a_gate_that_cannot_run_is_a_failure_not_a_pass() {
    // Treating an execution error as success is how an ungated run gets mistaken for a
    // verified one -- the defect that made a whole family of earlier results unreadable.
    let d = tempfile::tempdir().unwrap();
    let p = ScriptedProvider::new(vec![says("done")]);
    let mut st = State::new("g", "this-command-does-not-exist-anywhere");
    let (outcome, _) = runner(&p, &FastShell, d.path(), &Conversational, false).run(&mut st);
    assert_eq!(outcome, Outcome::GateFailed);
}

#[test]
fn a_failed_gate_resets_the_tree_to_the_checkpoint() {
    // Invariant III: a failing attempt's edits must not survive into the next one.
    let d = repo();
    let p = ScriptedProvider::new(vec![
        calls(
            "write",
            json!({"path": "marker", "content": "vandalised\n"}),
        ),
        says("done"),
    ]);
    let mut st = State::new("g", "false");
    let (_, _) = runner(&p, &FastShell, d.path(), &Conversational, true).run(&mut st);
    assert_eq!(
        std::fs::read_to_string(d.path().join("marker")).unwrap(),
        "0\n",
        "the working tree must be back at the checkpoint"
    );
    assert!(st.runtime.rollbacks >= 1);
}

#[test]
fn rollback_can_be_switched_off_because_it_is_not_free() {
    // One run reset a worker's COMMITTED feature five times (FINDINGS 13.2), so the policy is
    // a switch rather than a law.
    let d = tempfile::tempdir().unwrap();
    std::fs::write(d.path().join("marker"), "0\n").unwrap();
    let p = ScriptedProvider::new(vec![
        calls("write", json!({"path": "marker", "content": "kept\n"})),
        says("done"),
    ]);
    let mut st = State::new("g", "false");
    let (_, _) = runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
    assert_eq!(
        std::fs::read_to_string(d.path().join("marker")).unwrap(),
        "kept\n"
    );
    assert_eq!(st.runtime.rollbacks, 0);
}

#[test]
fn the_worker_is_told_when_its_edits_were_reverted() {
    // Silently resetting leaves the model editing against a file it no longer has, and its
    // next `edit` fails on a string that is gone.
    let d = repo();
    let p = ScriptedProvider::new(vec![
        calls("write", json!({"path": "marker", "content": "x\n"})),
        says("done"),
        says("done"),
    ]);
    let mut st = State::new("g", "false");
    runner(&p, &FastShell, d.path(), &Conversational, true).run(&mut st);
    let last = p.seen.lock().unwrap().last().cloned().unwrap();
    let text = format!("{:?}", last.messages);
    assert!(
        text.contains("reverted"),
        "the reset must be stated to the worker: {text:.400}"
    );
}

#[test]
fn the_system_prompt_states_the_gate_without_offering_it() {
    let d = tempfile::tempdir().unwrap();
    let p = ScriptedProvider::new(vec![says("done")]);
    let mut st = State::new("fix the parser", "npm test");
    runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
    let sys = p.seen.lock().unwrap()[0].system.clone();
    assert!(
        sys.contains("npm test"),
        "the worker must know the standard it is held to"
    );
    assert!(sys.contains("you do not decide the verdict"));
    assert!(
        sys.contains("Available:"),
        "the environment probe must reach the prompt"
    );
}

#[test]
fn conversational_context_does_grow_which_is_the_thing_being_compared() {
    let d = tempfile::tempdir().unwrap();
    let script: Vec<_> = (0..6)
        .map(|i| calls("bash", json!({"command": format!("echo {i}")})))
        .collect();
    let p = ScriptedProvider::new(script);
    let mut st = State::new("g", "true");
    runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
    let seen = p.seen.lock().unwrap();
    let first = seen.first().unwrap().messages.len();
    let last = seen.last().unwrap().messages.len();
    assert!(
        last > first,
        "the baseline is meant to accumulate: {first} -> {last}"
    );
}

#[test]
fn a_provider_error_is_reported_as_an_error_not_as_failed_work() {
    struct Broken;
    impl Provider for Broken {
        fn complete(&self, _: &Request) -> Result<Response, ProviderError> {
            Err(ProviderError::Auth("bad key".into()))
        }
        fn model_id(&self) -> String {
            "broken".into()
        }
    }
    let d = tempfile::tempdir().unwrap();
    let mut st = State::new("g", "true");
    let r = Runner {
        provider: &Broken,
        shell: &StubShell,
        fs: &LocalFs,
        context: &Conversational,
        root: d.path().to_path_buf(),
        budget: Budget::default(),
        rollback: false,
        on_event: None,
        research: false,
        claim_check: false,
        base_check: blyte_agent::run::BaseCheck::None,
    };
    let (outcome, _) = r.run(&mut st);
    assert!(
        matches!(outcome, Outcome::Error(_)),
        "infrastructure failure must not read as a
                     failed task: {outcome:?}"
    );
}

#[test]
fn the_turn_budget_bounds_a_model_that_never_stops() {
    let d = tempfile::tempdir().unwrap();
    let script: Vec<_> = (0..500)
        .map(|_| calls("bash", json!({"command": "true"})))
        .collect();
    let p = ScriptedProvider::new(script);
    let mut st = State::new("g", "true");
    let (outcome, rep) = runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
    assert_eq!(outcome, Outcome::BudgetExhausted);
    assert_eq!(rep.outcome_turns, 12);
}

struct FailingResetShell {
    exec_error: Option<&'static str>,
}

impl Shell for FailingResetShell {
    fn exec(&self, command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
        let trimmed = command.trim();
        if trimmed == "git rev-parse HEAD" {
            return Ok(Output {
                stdout: "deadbeef1234\n".into(),
                stderr: String::new(),
                exit_code: 0,
            });
        }
        if trimmed.starts_with("git reset --hard ") {
            if let Some(err) = self.exec_error {
                return Err(err.into());
            }
            return Ok(Output {
                stdout: String::new(),
                stderr: "fatal: unable to create '.git/index.lock': File exists\n".into(),
                exit_code: 128,
            });
        }
        Ok(Output {
            stdout: String::new(),
            stderr: String::new(),
            exit_code: 1,
        })
    }

    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
        self.exec(command, cwd, timeout)
    }

    fn describe(&self) -> String {
        String::new()
    }

    fn available_binaries(
        &self,
        _cwd: &Path,
        _candidates: &[&'static str],
    ) -> Result<Vec<String>, String> {
        Ok(vec!["git".into()])
    }
}

#[test]
fn a_failed_rollback_nonzero_exit_ends_the_run_with_an_error() {
    let d = tempfile::tempdir().unwrap();
    let p = ScriptedProvider::new(vec![says("done"), says("should not run")]);
    let shell = FailingResetShell { exec_error: None };
    let mut st = State::new("g", "false");
    let (outcome, _) = runner(&p, &shell, d.path(), &Conversational, true).run(&mut st);
    match outcome {
        Outcome::Error(msg) => {
            assert!(msg.contains("could not roll back to deadbeef1234"), "{msg}");
            assert!(msg.contains("index.lock"), "{msg}");
        }
        other => panic!("expected Outcome::Error, got {other:?}"),
    }
    assert_eq!(st.runtime.rollbacks, 0);
    assert_eq!(p.seen.lock().unwrap().len(), 1);
}

#[test]
fn a_failed_rollback_exec_error_ends_the_run_with_an_error() {
    let d = tempfile::tempdir().unwrap();
    let p = ScriptedProvider::new(vec![says("done"), says("should not run")]);
    let shell = FailingResetShell {
        exec_error: Some("shell session closed"),
    };
    let mut st = State::new("g", "false");
    let (outcome, _) = runner(&p, &shell, d.path(), &Conversational, true).run(&mut st);
    match outcome {
        Outcome::Error(msg) => {
            assert!(msg.contains("could not roll back to deadbeef1234"), "{msg}");
            assert!(msg.contains("shell session closed"), "{msg}");
        }
        other => panic!("expected Outcome::Error, got {other:?}"),
    }
    assert_eq!(st.runtime.rollbacks, 0);
    assert_eq!(p.seen.lock().unwrap().len(), 1);
}

struct FailingProbeShell {
    outcome: Result<Output, String>,
}

impl Shell for FailingProbeShell {
    fn exec(&self, _command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
        self.outcome.clone()
    }

    fn describe(&self) -> String {
        "broken shell".into()
    }
}

#[test]
fn a_failed_environment_probe_spawn_error_ends_the_run_with_an_error() {
    let d = tempfile::tempdir().unwrap();
    let p = ScriptedProvider::new(vec![says("should not run")]);
    let shell = FailingProbeShell {
        outcome: Err("cannot run command `docker`: No such file or directory".into()),
    };
    let mut st = State::new("g", "true");
    let (outcome, _) = runner(&p, &shell, d.path(), &Conversational, false).run(&mut st);
    match outcome {
        Outcome::Error(msg) => {
            assert!(msg.contains("command -v"), "{msg}");
            assert!(msg.contains("No such file or directory"), "{msg}");
        }
        other => panic!("expected Outcome::Error, got {other:?}"),
    }
    assert!(p.seen.lock().unwrap().is_empty());
}

#[test]
fn a_failed_environment_probe_nonzero_exit_ends_the_run_with_an_error() {
    let d = tempfile::tempdir().unwrap();
    let p = ScriptedProvider::new(vec![says("should not run")]);
    let shell = FailingProbeShell {
        outcome: Ok(Output {
            stdout: String::new(),
            stderr: "container is not running\n".into(),
            exit_code: 125,
        }),
    };
    let mut st = State::new("g", "true");
    let (outcome, _) = runner(&p, &shell, d.path(), &Conversational, false).run(&mut st);
    match outcome {
        Outcome::Error(msg) => {
            assert!(msg.contains("command -v"), "{msg}");
            assert!(msg.contains("125"), "{msg}");
            assert!(msg.contains("container is not running"), "{msg}");
        }
        other => panic!("expected Outcome::Error, got {other:?}"),
    }
    assert!(p.seen.lock().unwrap().is_empty());
}