everruns-engine 0.34.2

Shared Input/Reason/Act execution and sans-IO turn planning for Everruns hosts
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
//! Pure turn-planner unit tests (EVE-840).
//!
//! These drive the engine as table tests over values — no adapter, store,
//! provider, or clock. They cover the branch outcomes the runtime host relies
//! on (unknown tool, parallel tool batch, completion, failure, cancellation,
//! max-iteration, act pause/continue) plus a serialize → deserialize → plan
//! round-trip proving determinism.

use chrono::{DateTime, Utc};
use everruns_core::events::TokenUsage;
use everruns_core::turn::TurnStopReason;
use everruns_engine::{
    ActOutcome, ActSchedulingFacts, ReasonResult, TurnLifecycleEffect, TurnPlan, TurnState,
    plan_after_act, plan_after_reason, reason_schedules_act,
};
use everruns_provider::tool_types::ToolCall;
use everruns_provider::typed_id::{HarnessId, MessageId, SessionId, TurnId, WorkspaceId};
use serde_json::json;
use uuid::Uuid;

fn fixed_now() -> DateTime<Utc> {
    DateTime::<Utc>::from_timestamp(1_700_000_000, 0).expect("valid timestamp")
}

fn turn_state() -> TurnState {
    TurnState {
        org_id: 1,
        session_id: SessionId::from_uuid(Uuid::now_v7()),
        harness_id: HarnessId::from_uuid(Uuid::now_v7()),
        agent_id: None,
        input_message_id: MessageId::from_uuid(Uuid::now_v7()),
        turn_id: Some(TurnId::from_uuid(Uuid::now_v7())),
        previous_response_id: None,
        iteration: 1,
        request_id: None,
        started_at: None,
        cumulative_usage: None,
        tool_call_count: 0,
        llm_call_count: 0,
        time_to_first_token_ms: None,
        final_message_id: None,
        final_answer_preview: None,
    }
}

fn reason_result() -> ReasonResult {
    ReasonResult {
        native_counts: None,
        success: true,
        text: String::new(),
        tool_calls: vec![],
        has_tool_calls: false,
        tool_definitions: vec![],
        max_iterations: 8,
        error: None,
        user_facing_error: None,
        error_disclosure: None,
        usage: None,
        output_message_id: None,
        time_to_first_token_ms: None,
        response_id: None,
        finish_reason: Some("stop".into()),
        locale: None,
        network_access: None,
        parallel_tool_calls: None,
        waiting_for_tool_results: false,
    }
}

fn tool_call(id: &str, name: &str) -> ToolCall {
    ToolCall {
        id: id.into(),
        name: name.into(),
        arguments: json!({}),
    }
}

/// A reason outcome that requests a tool call (even one the executor may not
/// know) schedules an act phase carrying the calls, with the host-resolved
/// blueprint + workspace and no lifecycle effects.
#[test]
fn reason_with_tool_call_schedules_act() {
    let state = turn_state();
    let workspace_id = WorkspaceId::from_uuid(Uuid::now_v7());
    let result = ReasonResult {
        text: "calling an unknown tool".into(),
        tool_calls: vec![tool_call("call_1", "mystery_tool")],
        has_tool_calls: true,
        response_id: Some("resp_1".into()),
        finish_reason: Some("tool_calls".into()),
        parallel_tool_calls: Some(true),
        ..reason_result()
    };

    assert!(reason_schedules_act(&state, &result));

    let (plan, effects) = plan_after_reason(
        &state,
        result,
        0,
        fixed_now(),
        Some(ActSchedulingFacts {
            blueprint_id: Some("blueprint.private".into()),
            workspace_id: Some(workspace_id),
        }),
    );
    assert!(effects.is_empty());
    match plan {
        TurnPlan::ScheduleAct(act) => {
            assert_eq!(act.input.tool_calls.len(), 1);
            assert_eq!(act.input.tool_calls[0].name, "mystery_tool");
            assert_eq!(act.input.blueprint_id.as_deref(), Some("blueprint.private"));
            assert_eq!(act.input.context.workspace_id, Some(workspace_id));
            assert_eq!(act.previous_response_id.as_deref(), Some("resp_1"));
            assert_eq!(act.iteration, 1);
            assert_eq!(act.input.parallel_tool_calls, Some(true));
        }
        other => panic!("expected ScheduleAct, got {other:?}"),
    }
}

/// A parallel batch of tool calls threads through into one act phase intact.
#[test]
fn reason_with_parallel_tool_batch_schedules_single_act() {
    let state = turn_state();
    let result = ReasonResult {
        text: "parallel work".into(),
        tool_calls: vec![
            tool_call("call_a", "search"),
            tool_call("call_b", "read"),
            tool_call("call_c", "write"),
        ],
        has_tool_calls: true,
        finish_reason: Some("tool_calls".into()),
        ..reason_result()
    };

    let (plan, effects) = plan_after_reason(&state, result, 0, fixed_now(), None);
    assert!(effects.is_empty());
    match plan {
        TurnPlan::ScheduleAct(act) => {
            assert_eq!(act.input.tool_calls.len(), 3);
            // Facts absent -> no blueprint/workspace attached.
            assert_eq!(act.input.blueprint_id, None);
            assert_eq!(act.input.context.workspace_id, None);
        }
        other => panic!("expected ScheduleAct, got {other:?}"),
    }
}

/// A successful reason with no tool calls and no pending steering completes the
/// turn and returns the completion lifecycle effects in order.
#[test]
fn reason_success_completes_turn_with_effects() {
    let mut state = turn_state();
    state.started_at = Some(fixed_now() - chrono::Duration::milliseconds(1_234));
    let final_message_id = MessageId::from_uuid(Uuid::now_v7());
    let result = ReasonResult {
        text: "the final answer".into(),
        usage: Some(TokenUsage::new(20, 8)),
        output_message_id: Some(final_message_id),
        time_to_first_token_ms: Some(50),
        finish_reason: Some("stop".into()),
        ..reason_result()
    };

    let (plan, effects) = plan_after_reason(&state, result, 0, fixed_now(), None);
    assert!(matches!(
        plan,
        TurnPlan::Complete {
            stop_reason: TurnStopReason::EndTurn,
            error: None,
        }
    ));
    assert_eq!(effects.len(), 3);
    match &effects[0] {
        TurnLifecycleEffect::TurnCompleted {
            input_message_id,
            data,
        } => {
            assert_eq!(*input_message_id, state.input_message_id);
            assert_eq!(data.final_message_id, Some(final_message_id));
            assert_eq!(
                data.final_answer_preview.as_deref(),
                Some("the final answer")
            );
            assert_eq!(data.llm_call_count, Some(1));
            assert_eq!(data.duration_ms, Some(1_234));
            let usage = data.usage.as_ref().expect("usage aggregated");
            assert_eq!(usage.input_tokens, 20);
            assert_eq!(usage.output_tokens, 8);
        }
        other => panic!("expected TurnCompleted first, got {other:?}"),
    }
    assert!(matches!(
        effects[1],
        TurnLifecycleEffect::SessionIdled { .. }
    ));
    assert!(matches!(
        effects[2],
        TurnLifecycleEffect::FireTurnEndHooks { success: true, .. }
    ));
}

/// A failed reason completes with an error stop reason and returns the
/// turn-failed + turn-end-hook effects (no completion/idle pair).
#[test]
fn reason_failure_completes_with_failure_effect() {
    let state = turn_state();
    let result = ReasonResult {
        native_counts: None,
        success: false,
        text: "budget exhausted".into(),
        has_tool_calls: false,
        error: Some("Budget exhausted".into()),
        finish_reason: None,
        ..reason_result()
    };

    let (plan, effects) = plan_after_reason(&state, result, 0, fixed_now(), None);
    match plan {
        TurnPlan::Complete { stop_reason, error } => {
            assert_eq!(stop_reason, TurnStopReason::Error);
            assert_eq!(error.as_deref(), Some("Budget exhausted"));
        }
        other => panic!("expected Complete, got {other:?}"),
    }
    assert_eq!(effects.len(), 2);
    match &effects[0] {
        TurnLifecycleEffect::TurnFailedWithDisclosure { text, .. } => {
            assert_eq!(text, "budget exhausted");
        }
        other => panic!("expected TurnFailedWithDisclosure, got {other:?}"),
    }
    assert!(matches!(
        effects[1],
        TurnLifecycleEffect::FireTurnEndHooks { success: false, .. }
    ));
}

/// A blocked act (host-side cancellation / dependency block) ends the turn with
/// no effects.
#[test]
fn act_blocked_completes_end_turn() {
    let state = turn_state();
    let (plan, effects) = plan_after_act(
        &state,
        ActOutcome {
            blocked: true,
            waiting_for_tool_results: false,
            waiting_for_url_elicitation: false,
            waiting_for_ask_user: false,
            waiting_for_tool_approval: false,
        },
        false,
        false,
        false,
        Vec::new(),
    );
    assert!(effects.is_empty());
    assert!(matches!(
        plan,
        TurnPlan::Complete {
            stop_reason: TurnStopReason::EndTurn,
            error: None,
        }
    ));
}

/// When the iteration budget is already spent, a reason that still wants tools
/// surfaces `MaxTurnRequests` instead of scheduling another act.
#[test]
fn reason_at_max_iterations_surfaces_max_turn_requests() {
    let state = turn_state(); // iteration = 1
    let result = ReasonResult {
        text: "still calling tools".into(),
        tool_calls: vec![tool_call("call_x", "multiply")],
        has_tool_calls: true,
        max_iterations: 1, // reached
        finish_reason: Some("tool_calls".into()),
        ..reason_result()
    };

    assert!(!reason_schedules_act(&state, &result));
    let (plan, effects) = plan_after_reason(&state, result, 0, fixed_now(), None);
    assert!(matches!(
        plan,
        TurnPlan::Complete {
            stop_reason: TurnStopReason::MaxTurnRequests,
            error: None,
        }
    ));
    // Terminal: completion + idle + turn-end-hook effects.
    assert_eq!(effects.len(), 3);
}

/// A remote tool loop that paused on a tool call (EVE-1124) parks the turn,
/// even at the iteration cap and with a steering message queued: the provider
/// still holds the call open, so only the pause's answer may advance it.
#[test]
fn reason_waiting_for_tool_results_parks_the_turn() {
    let state = turn_state();
    let result = ReasonResult {
        waiting_for_tool_results: true,
        max_iterations: 1,
        ..reason_result()
    };
    assert!(!reason_schedules_act(&state, &result));
    let (plan, effects) = plan_after_reason(&state, result, 1, fixed_now(), None);
    match plan {
        TurnPlan::WaitForToolResults { resume } => {
            assert_eq!(resume.iteration, state.iteration + 1);
        }
        other => panic!("expected WaitForToolResults, got {other:?}"),
    }
    assert!(matches!(
        effects.as_slice(),
        [TurnLifecycleEffect::WaitingForToolResults]
    ));

    // A failed reason never parks.
    let failed = ReasonResult {
        success: false,
        waiting_for_tool_results: true,
        error: Some("boom".into()),
        ..reason_result()
    };
    let (plan, _) = plan_after_reason(&state, failed, 0, fixed_now(), None);
    assert!(matches!(plan, TurnPlan::Complete { .. }));
}

/// An act awaiting tool results pauses only when the setup_connection hint is
/// enabled, emitting the waiting effect and bumping the iteration.
#[test]
fn act_waiting_pauses_when_hint_enabled() {
    let state = turn_state();
    let (plan, effects) = plan_after_act(
        &state,
        ActOutcome {
            blocked: false,
            waiting_for_tool_results: true,
            waiting_for_url_elicitation: false,
            waiting_for_ask_user: false,
            waiting_for_tool_approval: false,
        },
        true,
        false,
        false,
        Vec::new(),
    );
    match plan {
        TurnPlan::WaitForToolResults { resume } => {
            assert_eq!(resume.iteration, 2);
            assert_eq!(resume.turn_id, state.turn_id);
        }
        other => panic!("expected WaitForToolResults, got {other:?}"),
    }
    assert_eq!(effects.len(), 1);
    assert!(matches!(
        effects[0],
        TurnLifecycleEffect::WaitingForToolResults
    ));
}

/// Without the hint, an act awaiting tool results continues to reason instead.
#[test]
fn act_waiting_continues_when_hint_absent() {
    let state = turn_state();
    let (plan, effects) = plan_after_act(
        &state,
        ActOutcome {
            blocked: false,
            waiting_for_tool_results: true,
            waiting_for_url_elicitation: false,
            waiting_for_ask_user: false,
            waiting_for_tool_approval: false,
        },
        false,
        false,
        false,
        Vec::new(),
    );
    assert!(effects.is_empty());
    match plan {
        TurnPlan::ScheduleReason(next) => assert_eq!(next.iteration, 2),
        other => panic!("expected ScheduleReason, got {other:?}"),
    }
}

/// Serializing a `TurnState`, deserializing it, and planning from both must
/// yield the same next plan for the same input — the durable-replay property in
/// miniature.
#[test]
fn serialize_deserialize_plan_round_trip_is_equal() {
    let mut state = turn_state();
    state.started_at = Some(fixed_now() - chrono::Duration::milliseconds(500));
    state.cumulative_usage = Some(TokenUsage::new(3, 1));
    state.tool_call_count = 2;
    state.llm_call_count = 1;

    let serialized = serde_json::to_string(&state).expect("serialize");
    let restored: TurnState = serde_json::from_str(&serialized).expect("deserialize");

    let now = fixed_now();
    let (plan_a, effects_a) = plan_after_reason(&state, reason_result(), 0, now, None);
    let (plan_b, effects_b) = plan_after_reason(&restored, reason_result(), 0, now, None);

    // Both terminal completions with identical stop reason + summarized fields.
    let (sr_a, err_a) = match plan_a {
        TurnPlan::Complete { stop_reason, error } => (stop_reason, error),
        other => panic!("expected Complete, got {other:?}"),
    };
    let (sr_b, err_b) = match plan_b {
        TurnPlan::Complete { stop_reason, error } => (stop_reason, error),
        other => panic!("expected Complete, got {other:?}"),
    };
    assert_eq!(sr_a, sr_b);
    assert_eq!(err_a, err_b);

    let completed = |effects: &[TurnLifecycleEffect]| -> everruns_core::events::TurnCompletedData {
        match &effects[0] {
            TurnLifecycleEffect::TurnCompleted { data, .. } => data.clone(),
            other => panic!("expected TurnCompleted, got {other:?}"),
        }
    };
    let data_a = completed(&effects_a);
    let data_b = completed(&effects_b);
    assert_eq!(data_a.duration_ms, data_b.duration_ms);
    assert_eq!(data_a.tool_call_count, data_b.tool_call_count);
    assert_eq!(data_a.llm_call_count, data_b.llm_call_count);
    assert_eq!(
        serde_json::to_value(&data_a.usage).unwrap(),
        serde_json::to_value(&data_b.usage).unwrap()
    );
}

/// A URL elicitation consent card is only worth pausing for when the client
/// said it can render one. The `setup_connection` hint does not stand in for
/// that: a client that renders connection cards need not render this one.
#[test]
fn act_waiting_on_a_url_elicitation_pauses_only_on_its_own_hint() {
    let state = turn_state();
    let outcome = ActOutcome {
        blocked: false,
        waiting_for_tool_results: true,
        waiting_for_url_elicitation: true,
        waiting_for_ask_user: false,
        waiting_for_tool_approval: false,
    };

    let (plan, effects) = plan_after_act(&state, outcome, false, true, false, Vec::new());
    assert!(matches!(plan, TurnPlan::WaitForToolResults { .. }));
    assert_eq!(effects.len(), 1);

    // No hint for it: the elicitation reaches the user as an ordinary tool
    // result instead of stalling the turn on a card nobody draws.
    let (plan, effects) = plan_after_act(&state, outcome, false, false, false, Vec::new());
    assert!(matches!(plan, TurnPlan::ScheduleReason(_)));
    assert!(effects.is_empty());
}

/// EVE-1057: a question nobody can render must not hold the turn.
///
/// Burning a 300-second timeout waiting for a human who structurally is not
/// there — a cron run, a trigger, an SDK caller — is the obvious failure mode
/// of a timed question, so the pause needs a client that declared it can draw
/// one.
#[test]
fn an_ask_user_pause_without_the_hint_continues_the_turn() {
    let state = turn_state();
    let outcome = ActOutcome {
        blocked: false,
        waiting_for_tool_results: true,
        waiting_for_url_elicitation: false,
        waiting_for_ask_user: true,
        waiting_for_tool_approval: false,
    };
    let calls = vec![(
        "toolu_ask_1".to_string(),
        serde_json::json!({"questions": [{
            "id": "target", "header": "Target", "question": "Where?",
            "options": [
                {"label": "Staging", "description": "Safe.", "default": true},
                {"label": "Production", "description": "Live."}
            ]
        }]}),
    )];

    // setup_connection is on, which is enough for any other client-side tool.
    // It must not be enough for a question: a client can finish a connection
    // setup and still have no way to render one.
    let (plan, effects) = plan_after_act(&state, outcome, true, true, false, calls);
    match plan {
        TurnPlan::ScheduleReason(_) => {}
        other => panic!("expected the turn to continue, got {other:?}"),
    }
    match effects.as_slice() {
        [TurnLifecycleEffect::ResolveAskUserUnattended { calls, .. }] => {
            assert_eq!(calls.len(), 1);
            assert_eq!(calls[0].0, "toolu_ask_1");
        }
        other => panic!("expected an unattended resolution, got {other:?}"),
    }
}

#[test]
fn an_ask_user_pause_with_the_hint_parks_as_usual() {
    let state = turn_state();
    let outcome = ActOutcome {
        blocked: false,
        waiting_for_tool_results: true,
        waiting_for_url_elicitation: false,
        waiting_for_ask_user: true,
        waiting_for_tool_approval: false,
    };
    let calls = vec![(
        "toolu_ask_1".to_string(),
        serde_json::json!({"questions": []}),
    )];

    // The hint is the only thing on, so it is the hint doing the work.
    let (plan, effects) = plan_after_act(&state, outcome, false, false, true, calls);
    match plan {
        TurnPlan::WaitForToolResults { .. } => {}
        other => panic!("expected the turn to park, got {other:?}"),
    }
    assert!(
        matches!(
            effects.as_slice(),
            [TurnLifecycleEffect::WaitingForToolResults]
        ),
        "a parked question is answered by the client, not by defaults: {effects:?}"
    );
}

/// The gate is per-pause-kind. A URL elicitation keeps its own behaviour when
/// only the `ask_user` hint is declared.
#[test]
fn the_ask_user_hint_does_not_speak_for_a_url_elicitation() {
    let state = turn_state();
    let outcome = ActOutcome {
        blocked: false,
        waiting_for_tool_results: true,
        waiting_for_url_elicitation: true,
        waiting_for_ask_user: false,
        waiting_for_tool_approval: false,
    };
    let (plan, effects) = plan_after_act(&state, outcome, false, false, true, Vec::new());
    match plan {
        TurnPlan::ScheduleReason(_) => {}
        other => panic!("expected the turn to continue, got {other:?}"),
    }
    assert!(
        effects.is_empty(),
        "no defaults for a URL card: {effects:?}"
    );
}

/// EVE-1140: a hard tool-approval request parks the turn whatever the client
/// declared. The gated call already failed closed; continuing would only throw
/// away the chance for a person to approve it through the API.
#[test]
fn a_tool_approval_pause_holds_without_any_hint() {
    let state = turn_state();
    let outcome = ActOutcome {
        blocked: false,
        waiting_for_tool_results: true,
        waiting_for_url_elicitation: false,
        waiting_for_ask_user: false,
        waiting_for_tool_approval: true,
    };
    let (plan, effects) = plan_after_act(&state, outcome, false, false, false, Vec::new());
    assert!(matches!(plan, TurnPlan::WaitForToolResults { .. }));
    assert!(matches!(
        effects.as_slice(),
        [TurnLifecycleEffect::WaitingForToolResults]
    ));

    // An `ask_user` call in the same batch rides the same pause rather than
    // being answered unattended underneath a pending approval.
    let outcome = ActOutcome {
        waiting_for_ask_user: true,
        ..outcome
    };
    let calls = vec![(
        "toolu_ask_1".to_string(),
        serde_json::json!({"questions": []}),
    )];
    let (plan, _) = plan_after_act(&state, outcome, false, false, false, calls);
    assert!(matches!(plan, TurnPlan::WaitForToolResults { .. }));
}