blyte-agent 0.91.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
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

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

struct NoopShell;

impl Shell for NoopShell {
    fn exec(&self, _command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
        Ok(Output {
            stdout: String::new(),
            stderr: String::new(),
            exit_code: 0,
        })
    }

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

const NUDGE_PREFIX: &str =
    "[blyte] You have spent 20 turns without changing any file or running the gate.";
const NUDGE_MARKER: &str =
    "turns without changing any file or running the gate. Stop exploring and decide now: make the change the task asks for, or, if the task needs no code change or the problem cannot be reproduced, stop calling tools and explain why in your reply.";
const LAST_CALL_TEXT: &str = "[blyte] Still no change after the last reminder. Reply now with your conclusion and why, and do not call any tools: the run stops if this reply calls a tool without changing anything.";

struct FakeClock {
    base: Instant,
    offset_ms: AtomicU64,
}

impl FakeClock {
    fn new() -> Arc<Self> {
        Arc::new(Self {
            base: Instant::now(),
            offset_ms: AtomicU64::new(0),
        })
    }

    fn now(&self) -> Instant {
        self.base + Duration::from_millis(self.offset_ms.load(Ordering::SeqCst))
    }

    fn advance(&self, d: Duration) {
        self.offset_ms
            .fetch_add(d.as_millis() as u64, Ordering::SeqCst);
    }
}

struct AlwaysBash {
    requests: Arc<Mutex<Vec<Vec<Message>>>>,
    clock_step: Option<(Arc<FakeClock>, Duration)>,
}

impl Provider for AlwaysBash {
    fn complete(&self, req: &Request) -> Result<Response, ProviderError> {
        if let Some((clock, step)) = &self.clock_step {
            clock.advance(*step);
        }
        self.requests.lock().unwrap().push(req.messages.clone());
        Ok(Response {
            text: String::new(),
            tool_calls: vec![ToolCall {
                id: "c1".into(),
                name: "bash".into(),
                arguments: json!({"command": "true"}),
                signature: None,
            }],
            usage: Usage::default(),
            finish_reason: None,
        })
    }

    fn model_id(&self) -> String {
        "stub".into()
    }
}

fn count_user_messages_with(messages: &[Message], needle: &str) -> usize {
    messages
        .iter()
        .filter(|m| matches!(m, Message::User(t) if t.contains(needle)))
        .count()
}

#[test]
fn fix_run_without_progress_nudges_at_21_last_calls_at_31_and_stops_at_32() {
    let dir = tempfile::tempdir().unwrap();
    let requests = Arc::new(Mutex::new(Vec::new()));
    let provider = AlwaysBash {
        requests: requests.clone(),
        clock_step: None,
    };
    let runner = Runner {
        provider: &provider,
        context: &Folded::default(),
        fs: &RealFs,
        shell: &NoopShell,
        root: dir.path().to_path_buf(),
        budget: Budget {
            max_turns: 60,
            max_gate_attempts: 1,
            max_duration: None,
        },
        rollback: false,
        on_event: None,
        research: false,
        claim_check: false,
        base_check: blyte_agent::run::BaseCheck::None,
    };

    let mut state = State::new("fix the bug", "true");
    let (outcome, report) = runner.run(&mut state);

    assert_eq!(outcome, Outcome::BudgetExhausted);
    assert!(report.stalled);

    let reqs = requests.lock().unwrap();
    assert_eq!(
        reqs.len(),
        31,
        "stop must happen at top of turn 32 before the model call"
    );

    let first_nudge = reqs
        .iter()
        .position(|msgs| count_user_messages_with(msgs, NUDGE_PREFIX) > 0)
        .expect("nudge must appear");
    assert_eq!(first_nudge, 20, "nudge must first appear on turn 21");
    assert_eq!(
        count_user_messages_with(&reqs[20], NUDGE_PREFIX),
        1,
        "nudge must appear exactly once in turn 21 request"
    );
    assert_eq!(
        count_user_messages_with(&reqs[20], NUDGE_MARKER),
        1,
        "full nudge wording must match"
    );

    let first_last_call = reqs
        .iter()
        .position(|msgs| count_user_messages_with(msgs, LAST_CALL_TEXT) > 0)
        .expect("last call must appear");
    assert_eq!(
        first_last_call, 30,
        "last call must first appear on turn 31"
    );
    assert_eq!(
        count_user_messages_with(&reqs[30], LAST_CALL_TEXT),
        1,
        "last call must appear exactly once in turn 31 request"
    );
    assert_eq!(
        count_user_messages_with(&reqs[30], NUDGE_PREFIX),
        1,
        "nudge must still appear only once on turn 31"
    );
}

struct StopOnLastCall {
    requests: Arc<Mutex<Vec<Vec<Message>>>>,
}

impl Provider for StopOnLastCall {
    fn complete(&self, req: &Request) -> Result<Response, ProviderError> {
        self.requests.lock().unwrap().push(req.messages.clone());
        if count_user_messages_with(&req.messages, LAST_CALL_TEXT) > 0 {
            return Ok(Response {
                text: "No code change is needed because the behaviour is already compliant.".into(),
                tool_calls: Vec::new(),
                usage: Usage::default(),
                finish_reason: None,
            });
        }
        Ok(Response {
            text: String::new(),
            tool_calls: vec![ToolCall {
                id: "c1".into(),
                name: "bash".into(),
                arguments: json!({"command": "true"}),
                signature: None,
            }],
            usage: Usage::default(),
            finish_reason: None,
        })
    }

    fn model_id(&self) -> String {
        "stub".into()
    }
}

#[test]
fn replying_without_tools_after_last_call_stops_normally_without_stalling() {
    let dir = tempfile::tempdir().unwrap();
    let requests = Arc::new(Mutex::new(Vec::new()));
    let provider = StopOnLastCall {
        requests: requests.clone(),
    };
    let runner = Runner {
        provider: &provider,
        context: &Folded::default(),
        fs: &RealFs,
        shell: &NoopShell,
        root: dir.path().to_path_buf(),
        budget: Budget {
            max_turns: 60,
            max_gate_attempts: 1,
            max_duration: None,
        },
        rollback: false,
        on_event: None,
        research: false,
        claim_check: false,
        base_check: blyte_agent::run::BaseCheck::None,
    };

    let mut state = State::new("fix the bug", "");
    let (outcome, report) = runner.run(&mut state);

    assert_eq!(outcome, Outcome::Verified);
    assert!(!report.stalled);
    assert_eq!(
        report.final_message.as_deref(),
        Some("No code change is needed because the behaviour is already compliant.")
    );
}

struct WriteOnTurn3ThenBash {
    requests: Arc<Mutex<Vec<Vec<Message>>>>,
}

impl Provider for WriteOnTurn3ThenBash {
    fn complete(&self, req: &Request) -> Result<Response, ProviderError> {
        let turn = {
            let mut reqs = self.requests.lock().unwrap();
            reqs.push(req.messages.clone());
            reqs.len()
        };
        let call = if turn == 3 {
            ToolCall {
                id: "c1".into(),
                name: "write".into(),
                arguments: json!({"path": "changed.txt", "content": "done\n"}),
                signature: None,
            }
        } else {
            ToolCall {
                id: "c1".into(),
                name: "bash".into(),
                arguments: json!({"command": "true"}),
                signature: None,
            }
        };
        Ok(Response {
            text: String::new(),
            tool_calls: vec![call],
            usage: Usage::default(),
            finish_reason: None,
        })
    }

    fn model_id(&self) -> String {
        "stub".into()
    }
}

#[test]
fn successful_write_disables_no_progress_nudge_and_stop() {
    let dir = tempfile::tempdir().unwrap();
    let requests = Arc::new(Mutex::new(Vec::new()));
    let provider = WriteOnTurn3ThenBash {
        requests: requests.clone(),
    };
    let runner = Runner {
        provider: &provider,
        context: &Folded::default(),
        fs: &RealFs,
        shell: &NoopShell,
        root: dir.path().to_path_buf(),
        budget: Budget {
            max_turns: 60,
            max_gate_attempts: 1,
            max_duration: None,
        },
        rollback: false,
        on_event: None,
        research: false,
        claim_check: false,
        base_check: blyte_agent::run::BaseCheck::None,
    };

    let mut state = State::new("fix the bug", "true");
    let (outcome, report) = runner.run(&mut state);

    assert_eq!(outcome, Outcome::BudgetExhausted);
    assert!(!report.stalled);
    assert_eq!(report.outcome_turns, 60);

    let reqs = requests.lock().unwrap();
    assert_eq!(reqs.len(), 60);
    for msgs in reqs.iter() {
        assert_eq!(count_user_messages_with(msgs, NUDGE_MARKER), 0);
        assert_eq!(count_user_messages_with(msgs, LAST_CALL_TEXT), 0);
    }
}

#[test]
fn research_run_never_receives_no_progress_nudge_or_stops() {
    let dir = tempfile::tempdir().unwrap();
    let requests = Arc::new(Mutex::new(Vec::new()));
    let provider = AlwaysBash {
        requests: requests.clone(),
        clock_step: None,
    };
    let runner = Runner {
        provider: &provider,
        context: &Folded::default(),
        fs: &RealFs,
        shell: &NoopShell,
        root: dir.path().to_path_buf(),
        budget: Budget {
            max_turns: 40,
            max_gate_attempts: 1,
            max_duration: None,
        },
        rollback: false,
        on_event: None,
        research: true,
        claim_check: false,
        base_check: blyte_agent::run::BaseCheck::None,
    };

    let mut state = State::new("investigate the repo", "");
    let (outcome, report) = runner.run(&mut state);

    assert_eq!(outcome, Outcome::BudgetExhausted);
    assert!(!report.stalled);

    let reqs = requests.lock().unwrap();
    assert_eq!(reqs.len(), 40);
    for msgs in reqs.iter() {
        assert_eq!(count_user_messages_with(msgs, NUDGE_MARKER), 0);
        assert_eq!(count_user_messages_with(msgs, LAST_CALL_TEXT), 0);
    }
}

#[test]
fn time_fraction_triggers_nudge_early_and_last_call_before_end() {
    let dir = tempfile::tempdir().unwrap();
    let clock = FakeClock::new();
    let requests = Arc::new(Mutex::new(Vec::new()));
    let provider = AlwaysBash {
        requests: requests.clone(),
        clock_step: Some((Arc::clone(&clock), Duration::from_secs(20))),
    };
    let runner = Runner {
        provider: &provider,
        context: &Folded::default(),
        fs: &RealFs,
        shell: &NoopShell,
        root: dir.path().to_path_buf(),
        budget: Budget {
            max_turns: 200,
            max_gate_attempts: 1,
            max_duration: Some(Duration::from_secs(600)),
        },
        rollback: false,
        on_event: None,
        research: false,
        claim_check: false,
        base_check: blyte_agent::run::BaseCheck::None,
    };

    let mut state = State::new("fix the bug", "true");
    let (outcome, report) = runner.run_with_clock(&mut state, &|| clock.now());

    assert_eq!(outcome, Outcome::BudgetExhausted);
    assert!(report.stalled);

    let reqs = requests.lock().unwrap();
    let first_nudge_turn = reqs
        .iter()
        .position(|msgs| count_user_messages_with(msgs, NUDGE_MARKER) > 0)
        .map(|idx| idx + 1)
        .expect("nudge must appear");
    assert!(
        (9..=20).contains(&first_nudge_turn),
        "expected time-triggered nudge on turn in 9..=20, got turn {first_nudge_turn}"
    );
    assert_eq!(
        count_user_messages_with(&reqs[first_nudge_turn - 1], NUDGE_MARKER),
        1,
        "nudge must appear exactly once"
    );

    let first_last_call_turn = reqs
        .iter()
        .position(|msgs| count_user_messages_with(msgs, LAST_CALL_TEXT) > 0)
        .map(|idx| idx + 1)
        .expect("last call must appear before the run ends");
    assert!(
        first_last_call_turn > first_nudge_turn,
        "last call (turn {first_last_call_turn}) must appear after nudge (turn {first_nudge_turn})"
    );
    assert!(
        first_last_call_turn < first_nudge_turn + 10,
        "expected time-triggered last call before turn {}, got turn {first_last_call_turn}",
        first_nudge_turn + 10
    );
    assert_eq!(
        count_user_messages_with(reqs.last().unwrap(), NUDGE_MARKER),
        1,
        "nudge must still appear only once at the end of the run"
    );
    assert_eq!(
        count_user_messages_with(reqs.last().unwrap(), LAST_CALL_TEXT),
        1,
        "last call must appear exactly once"
    );
}