yolop 0.14.0

Yolop — a terminal coding agent built on everruns-runtime
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
//! Scripted agent loop scenario tests.
//!
//! These tests drive a real `InProcessRuntime` (via `runtime::build_with_options`)
//! against the bundled llmsim driver in **scripted** mode, where each
//! assistant turn is pre-specified as `SimTurn::{Assistant, ToolCalls, Mixed,
//! Error}`. That gives us deterministic multi-turn agent behavior without
//! reaching a real LLM provider, so we can pin down:
//!
//!   * the agent loop completes when the script returns plain text
//!   * a scripted bash tool call actually runs through `BashTool` and has
//!     the documented filesystem side effect
//!   * the agent loops back to the LLM after a tool result and consumes the
//!     next scripted turn
//!   * a scripted `SimError` propagates as a turn failure
//!   * `OnExhausted::Error` makes a second `run_turn` fail once the script
//!     is consumed; the default `RepeatLast` keeps replaying the last turn
//!
//! Streaming-pipeline coverage lives in `streaming_tests`; this module is
//! specifically about the agent control flow.

use std::sync::Arc;
use std::time::{Duration, Instant};

use everruns_core::llmsim_driver::{LlmSimConfig, OnExhausted, SimError, SimToolCall, SimTurn};
use everruns_core::session_task::SessionTaskState;
use serde_json::json;

use crate::config::SettingsStore;
use crate::runtime::{BuildOptions, BuiltRuntime, ProviderChoice, build_with_options};
use crate::tui::host_ui::UiCommand;

/// Wall-clock cap on a single scripted `run_turn`. Scripted llmsim has no
/// latency by default; the budget is generous so a slow CI box won't flake.
const TURN_TIMEOUT: Duration = Duration::from_secs(15);

/// Build a runtime backed by a scripted llmsim config. The workspace and
/// session-dir tempdirs are turned into kept `PathBuf`s via
/// `TempDir::keep()` so the directories outlive `build_scripted_runtime`
/// (the runtime canonicalizes paths and holds on to them past return)
/// without leaking the `TempDir` handle. These are tmpfs paths under the
/// OS-managed temp tree, so the OS still cleans the directories.
///
/// Returns both the built runtime and the workspace root so tests that
/// assert on filesystem side effects (scripted bash tool calls) can read
/// files back.
async fn build_scripted_runtime(config: LlmSimConfig) -> (BuiltRuntime, std::path::PathBuf) {
    build_scripted_runtime_with_workspace(config, |_| {}).await
}

async fn build_scripted_runtime_with_workspace(
    config: LlmSimConfig,
    setup_workspace: impl FnOnce(&std::path::Path),
) -> (BuiltRuntime, std::path::PathBuf) {
    build_scripted_runtime_with_workspace_and_options(
        config,
        setup_workspace,
        BuildOptions::default(),
    )
    .await
}

async fn build_scripted_runtime_with_workspace_and_options(
    config: LlmSimConfig,
    setup_workspace: impl FnOnce(&std::path::Path),
    mut options: BuildOptions,
) -> (BuiltRuntime, std::path::PathBuf) {
    let workspace_root = tempfile::tempdir().expect("workspace tempdir").keep();
    let sessions_root = tempfile::tempdir().expect("sessions tempdir").keep();
    setup_workspace(&workspace_root);

    options.llmsim_override = Some(config.with_model("llmsim-yolop"));
    let settings_path = sessions_root.join("settings.toml");
    let settings = Arc::new(SettingsStore::open(settings_path));
    let runtime = build_with_options(
        workspace_root.clone(),
        ProviderChoice::Sim,
        None,
        sessions_root,
        settings,
        options,
    )
    .await
    .expect("build scripted llmsim runtime");

    (runtime, workspace_root)
}

/// Drive one user turn against the scripted runtime under a wall-clock
/// timeout so a hung agent loop fails the test instead of hanging CI.
async fn run_single_turn(runtime: &BuiltRuntime, user_text: &str) -> everruns_runtime::TurnResult {
    let session_id = runtime.handles.session_id;
    let input = runtime.model.input_message(user_text.to_string());
    tokio::time::timeout(
        TURN_TIMEOUT,
        runtime.handles.runtime.run_turn(session_id, input),
    )
    .await
    .expect("run_turn timed out")
    .expect("run_turn errored")
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scripted_get_config_capabilities_smoke() {
    let (runtime, _ws) = build_scripted_runtime(LlmSimConfig::scripted(vec![
        SimTurn::ToolCalls(vec![SimToolCall {
            name: "get_config".to_string(),
            arguments: json!({ "key": "capabilities" }),
            id: None,
        }]),
        SimTurn::Assistant("listed capabilities".to_string()),
    ]))
    .await;

    let result = run_single_turn(&runtime, "what capabilities can I configure?").await;

    assert!(
        result.success,
        "get_config capabilities smoke must succeed: {result:?}"
    );
    assert_eq!(
        result.tool_calls_count, 1,
        "scripted get_config must run exactly once"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scripted_assistant_text_returns_success_with_no_tools() {
    let (runtime, _ws) = build_scripted_runtime(LlmSimConfig::scripted(vec![SimTurn::Assistant(
        "hello from scripted llmsim".to_string(),
    )]))
    .await;

    let result = run_single_turn(&runtime, "ping").await;

    assert!(
        result.success,
        "scripted assistant turn must succeed: {result:?}"
    );
    assert_eq!(
        result.tool_calls_count, 0,
        "Assistant-only turn must not run tools"
    );
    assert!(
        result.iterations >= 1,
        "agent loop must record at least one iteration: {result:?}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scripted_prompt_command_tool_queues_quit_ui_command() {
    let (mut runtime, _ws) = build_scripted_runtime_with_workspace_and_options(
        LlmSimConfig::scripted(vec![
            SimTurn::ToolCalls(vec![SimToolCall {
                name: "run_yolop_command".to_string(),
                arguments: json!({ "command": "exit" }),
                id: None,
            }]),
            SimTurn::Assistant("exiting".to_string()),
        ]),
        |_| {},
        BuildOptions {
            client_commands: true,
            ..BuildOptions::default()
        },
    )
    .await;

    let result = run_single_turn(&runtime, "exit").await;

    assert!(
        result.success,
        "prompt command turn must succeed: {result:?}"
    );
    assert_eq!(
        result.tool_calls_count, 1,
        "natural-language command should run through the tool entry point"
    );
    let command = runtime.ui_rx.try_recv().expect("queued UI command");
    assert_eq!(command.command, UiCommand::Quit);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scripted_tool_call_executes_bash_then_assistant_completes() {
    // First scripted turn issues a bash tool call that touches a marker
    // file in the workspace. Second turn closes the loop with plain text
    // so the agent stops iterating.
    let marker = "scripted_bash_ran.marker";
    let cmd = format!("touch {marker}");
    let (runtime, workspace) = build_scripted_runtime(LlmSimConfig::scripted(vec![
        SimTurn::ToolCalls(vec![SimToolCall {
            name: "bash".to_string(),
            arguments: json!({ "command": cmd }),
            id: None,
        }]),
        SimTurn::Assistant("did the bash".to_string()),
    ]))
    .await;

    let result = run_single_turn(&runtime, "do the thing").await;

    assert!(
        result.success,
        "tool-call + assistant turn must succeed: {result:?}"
    );
    assert_eq!(
        result.tool_calls_count, 1,
        "exactly one bash invocation expected"
    );
    assert!(
        workspace.join(marker).exists(),
        "BashTool must have run the scripted command and created {marker:?} in {workspace:?}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn repeated_read_reuse_runs_through_real_file_tools_and_invalidates_on_write() {
    use everruns_core::events::EventData;

    let original = "ORIGINAL-EVIDENCE\n".repeat(400);
    let changed = "CHANGED-EVIDENCE\n".repeat(400);
    let (runtime, _workspace) = build_scripted_runtime_with_workspace(
        LlmSimConfig::scripted(vec![
            SimTurn::ToolCalls(vec![SimToolCall {
                name: "read_file".to_string(),
                arguments: json!({ "path": "evidence.txt" }),
                id: None,
            }]),
            SimTurn::ToolCalls(vec![SimToolCall {
                name: "read_file".to_string(),
                arguments: json!({ "path": "evidence.txt" }),
                id: None,
            }]),
            SimTurn::ToolCalls(vec![SimToolCall {
                name: "write_file".to_string(),
                arguments: json!({ "path": "evidence.txt", "content": changed }),
                id: None,
            }]),
            SimTurn::ToolCalls(vec![SimToolCall {
                name: "read_file".to_string(),
                arguments: json!({ "path": "evidence.txt" }),
                id: None,
            }]),
            SimTurn::Assistant("used fresh evidence".to_string()),
        ]),
        |workspace| {
            std::fs::write(workspace.join("evidence.txt"), &original).expect("seed evidence");
        },
    )
    .await;

    let result = run_single_turn(&runtime, "inspect, repeat, update, and inspect").await;
    assert!(result.success, "scripted discovery turn: {result:?}");
    assert_eq!(result.tool_calls_count, 4);

    let events = runtime
        .handles
        .runtime
        .events()
        .await
        .expect("runtime events");
    let reads = events
        .iter()
        .filter_map(|event| match &event.data {
            EventData::ToolCompleted(data) if data.tool_name == "read_file" => {
                Some(serde_json::to_string(&data.result).expect("serialize read result"))
            }
            _ => None,
        })
        .collect::<Vec<_>>();
    assert_eq!(reads.len(), 3);
    assert!(reads[0].contains("ORIGINAL-EVIDENCE"));
    assert!(reads[1].contains("unchanged_since_last_read"));
    assert!(!reads[1].contains("ORIGINAL-EVIDENCE"));
    assert!(
        reads[2].contains("CHANGED-EVIDENCE"),
        "a real write must invalidate compact reuse: {}",
        reads[2]
    );
    assert!(!reads[2].contains("unchanged_since_last_read"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scripted_spawn_background_runs_bash_detached() {
    let marker = "spawn_background_bash.marker";
    let cmd = format!("printf background-ok > {marker}");
    let (runtime, workspace) = build_scripted_runtime(LlmSimConfig::scripted(vec![
        SimTurn::ToolCalls(vec![SimToolCall {
            name: "spawn_background".to_string(),
            arguments: json!({
                "tool": "bash",
                "args": { "command": cmd },
                "title": "write marker",
                "signal_on_completion": false
            }),
            id: None,
        }]),
        SimTurn::Assistant("background started".to_string()),
    ]))
    .await;

    assert!(
        runtime
            .startup
            .tool_names
            .contains(&"spawn_background".to_string()),
        "spawn_background should be visible when bash supports background: {:?}",
        runtime.startup.tool_names
    );

    let result = run_single_turn(&runtime, "start the background marker write").await;

    assert!(
        result.success,
        "spawn_background turn must succeed: {result:?}"
    );
    assert_eq!(
        result.tool_calls_count, 1,
        "the scripted turn should call spawn_background once"
    );
    tokio::time::timeout(Duration::from_secs(10), async {
        loop {
            if workspace.join(marker).exists() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("background bash did not create marker in time");
    let marker_text = tokio::fs::read_to_string(workspace.join(marker))
        .await
        .expect("read marker");
    assert_eq!(marker_text, "background-ok");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn predictable_long_command_returns_immediately_and_terminal_result_is_durable() {
    let (runtime, _workspace) = build_scripted_runtime(LlmSimConfig::scripted(vec![
        SimTurn::ToolCalls(vec![SimToolCall {
            name: "spawn_background".to_string(),
            arguments: json!({
                "tool": "bash",
                "args": { "command": "sleep 1; printf durable-result" },
                "title": "synthetic long validation",
                "signal_on_completion": false
            }),
            id: None,
        }]),
        SimTurn::Assistant("background validation started".to_string()),
    ]))
    .await;

    let started = Instant::now();
    let turn = run_single_turn(&runtime, "run the predictable long validation").await;
    let foreground_elapsed = started.elapsed();
    assert!(
        turn.success,
        "background launch turn must succeed: {turn:?}"
    );
    assert!(
        foreground_elapsed < Duration::from_millis(750),
        "the one-second command must not consume foreground time: {foreground_elapsed:?}"
    );

    let session_id = runtime.handles.session_id;
    let task = runtime
        .task_registry
        .list(session_id, None)
        .await
        .expect("list real session tasks")
        .into_iter()
        .find(|task| task.kind == "background_tool")
        .expect("spawn_background must create a session task");
    let terminal = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            let current = runtime
                .task_registry
                .get(session_id, &task.id)
                .await
                .expect("retrieve task while it runs")
                .expect("task must remain retrievable");
            if current.state.is_terminal() {
                break current;
            }
            tokio::time::sleep(Duration::from_millis(25)).await;
        }
    })
    .await
    .expect("background command should finish");

    assert_eq!(terminal.state, SessionTaskState::Succeeded);
    assert!(
        terminal.result_path.is_some(),
        "terminal result path is delivered"
    );
    let retrieved = runtime
        .task_registry
        .get(session_id, &task.id)
        .await
        .expect("retrieve completed task")
        .expect("completed tasks must not disappear before wait_task/get_task");
    assert_eq!(retrieved.id, task.id);
    assert_eq!(retrieved.result_path, terminal.result_path);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn workspace_hook_blocks_matching_bash_call() {
    let marker = "git_hook_should_block.marker";
    let cmd = format!("git status > {marker}");
    let (runtime, workspace) = build_scripted_runtime_with_workspace(
        LlmSimConfig::scripted(vec![
            SimTurn::ToolCalls(vec![SimToolCall {
                name: "bash".to_string(),
                arguments: json!({ "command": cmd }),
                id: None,
            }]),
            SimTurn::Assistant("git was blocked".to_string()),
        ]),
        |workspace| {
            let hooks_dir = workspace.join(".agents");
            std::fs::create_dir_all(&hooks_dir).expect("create hooks dir");
            std::fs::write(
                hooks_dir.join("hooks.json"),
                r#"{
                  "hooks": [
                    {
                      "id": "block-git",
                      "event": "pre_tool_use",
                      "matcher": {
                        "tool_name": "bash",
                        "args_jsonpath": "$.command",
                        "match_regex": "(^|[;&|()[:space:]])git([[:space:]]|$)"
                      },
                      "executor": {
                        "type": "bash",
                        "command": "printf '%s\\n' '{\"decision\":\"block\",\"reason\":\"git blocked by test hook\",\"user_message\":\"git is blocked\"}'"
                      },
                      "timeout_ms": 1000,
                      "on_error": "block",
                      "description": "Block git"
                    }
                  ]
                }"#,
            )
            .expect("write hooks config");
        },
    )
    .await;

    let result = run_single_turn(&runtime, "try git").await;

    assert!(result.success, "agent should continue after blocked tool");
    assert!(
        !workspace.join(marker).exists(),
        "pre_tool_use hook must block bash before it creates {marker:?}"
    );
    assert_eq!(
        runtime.startup.hook_count, 1,
        "workspace hook should be loaded into startup info"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scripted_error_turn_marks_run_failed() {
    let (runtime, _ws) = build_scripted_runtime(LlmSimConfig::scripted(vec![SimTurn::Error(
        SimError::Other("scripted llmsim refused the request".to_string()),
    )]))
    .await;

    let result = run_single_turn(&runtime, "anything").await;

    assert!(
        !result.success,
        "scripted error turn must surface as failure"
    );
    let error = result
        .error
        .as_deref()
        .expect("failed run_turn must carry an error message");
    assert!(
        error.contains("scripted llmsim refused"),
        "the scripted error message must reach the caller, got: {error}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scripted_default_repeat_last_lets_second_call_succeed_after_exhaustion() {
    // Default OnExhausted::RepeatLast: once the script is consumed the
    // last turn keeps serving. Two run_turns against a 1-turn script
    // must both succeed — proving the agent loop does not error out
    // when the script has been exhausted under the default mode.
    let (runtime, _ws) = build_scripted_runtime(LlmSimConfig::scripted(vec![SimTurn::Assistant(
        "only turn".to_string(),
    )]))
    .await;

    let first = run_single_turn(&runtime, "first").await;
    let second = run_single_turn(&runtime, "second").await;

    assert!(first.success, "first run_turn must succeed");
    assert!(
        second.success,
        "RepeatLast must let a second run_turn succeed past exhaustion: {second:?}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scripted_on_exhausted_error_fails_second_call() {
    // OnExhausted::Error makes the agent loop fail once the script has
    // been consumed. Proves the exhaustion mode is wired through end-to-end.
    let (runtime, _ws) = build_scripted_runtime(
        LlmSimConfig::scripted(vec![SimTurn::Assistant("once".to_string())])
            .with_on_exhausted(OnExhausted::Error),
    )
    .await;

    let first = run_single_turn(&runtime, "first").await;
    assert!(
        first.success,
        "first run_turn before exhaustion must succeed"
    );

    let second = run_single_turn(&runtime, "second").await;
    assert!(
        !second.success,
        "OnExhausted::Error must surface as a failed turn after the script is consumed"
    );
}