troupekit-agent 0.3.1

Persona TOML agents for the Troupekit agent framework: loader, checkpointable run state machine, typed output, evals and budgets.
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
use crate::budget::{self, Limits};
use crate::dsl::Call;
use crate::error::AgentError;
use crate::eval::{judge_request, judge_verdict, repair_message};
use crate::io::{AgentIo, ModelHandle};
use crate::persona::{open_trace, Persona, SavedTrace};
use crate::schema::{parse_json, validate};
use futures_util::future::join_all;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::time::Instant;
use troupekit_core::event::{Event, EventBody, PauseReason, Usage};
use troupekit_core::ids::RunId;
use troupekit_core::message::{ContentPart, Message, Role};
use troupekit_core::store::{Checkpoint, CheckpointStore};
use troupekit_providers::{CompletionRequest, CompletionResponse, Delta, StopReason};
use troupekit_tools::{ToolContext, ToolOutput};
use troupekit_trace::{content, trace, trace_span, Trace, TraceSpec};

/// Version of the serialized run.
/// `from_checkpoint` refuses any other, so a deploy never resumes
/// a run it cannot read.
pub const RUN_FORMAT: u32 = 1;

/// A tool call the model asked for and the run has not answered yet.
/// Kept in the run state, so a resumed run re-runs the whole batch:
/// tool calls are at least once across a crash.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PendingCall {
    pub id: String,
    pub name: String,
    pub arguments: Value,
}

/// Where a run stands. `CallModel`, `CallTools`, `Check` and `Repair` each
/// do one step of work; `Done` and `Failed` are final; `Paused` waits for
/// `resume` and then returns to the state in `resume`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum RunState {
    CallModel,
    CallTools {
        calls: Vec<PendingCall>,
    },
    Check {
        answer: String,
    },
    Repair {
        errors: Vec<String>,
    },
    Done {
        output: Value,
    },
    Failed {
        error: String,
    },
    Paused {
        reason: PauseReason,
        resume: Box<RunState>,
    },
}

impl RunState {
    fn step_name(&self) -> &'static str {
        match self {
            RunState::CallModel => "call_model",
            RunState::CallTools { .. } => "call_tools",
            RunState::Check { .. } => "check",
            RunState::Repair { .. } => "repair",
            RunState::Done { .. } | RunState::Failed { .. } | RunState::Paused { .. } => {
                unreachable!("only working states take steps")
            }
        }
    }
}

/// What one `step` did. `Continue`: step again. `Retry`: a transient
/// provider or ledger failure left the state unchanged; step again later.
/// `Paused`, `Done` and `Failed` repeat on every further step.
#[derive(Debug, Clone, PartialEq)]
pub enum StepOutcome {
    Continue,
    Retry {
        error: String,
        retry_after_ms: Option<u64>,
    },
    Paused(PauseReason),
    Done(Value),
    Failed(String),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RunSpec {
    persona: String,
    model: String,
    system: String,
    tools: Vec<String>,
    evals: Vec<Call>,
    output: Option<Value>,
    max_turns: u32,
    max_tokens: u32,
}

/// One agent run as plain serializable data: the persona snapshot, the
/// conversation, the state, counters, usage and the event sequence. The
/// host calls `step` and saves `checkpoint()` after every step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AgentRun {
    format: u32,
    run_id: RunId,
    spec: RunSpec,
    limits: Limits,
    messages: Vec<Message>,
    state: RunState,
    model_calls: u32,
    repaired: bool,
    usage: Usage,
    seq: u64,
    steps: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    trace: Option<SavedTrace>,
}

impl AgentRun {
    /// Starts a run of `persona` on `input` under `limits` tightened by the
    /// persona budget. Checks before any model call that every tool, eval and
    /// model it names is available in `io`; returns `Setup` naming the file.
    pub async fn new(
        persona: &Persona,
        input: Vec<Message>,
        limits: Limits,
        io: &dyn AgentIo,
    ) -> Result<AgentRun, AgentError> {
        let setup = |m: String| AgentError::Setup(format!("{}: {m}", persona.source));
        if input.is_empty() {
            return Err(setup("a run needs at least one input message".into()));
        }
        if persona.instructions.trim().is_empty() {
            return Err(setup("instructions are not loaded".into()));
        }
        if let Some(t) = persona.tools.iter().find(|t| io.tools().get(t).is_none()) {
            return Err(setup(format!("tool `{t}` is not registered")));
        }
        let mut models = vec![persona.model.clone()];
        for e in &persona.evals {
            if e.name == "judge" {
                models.extend(e.args.get(2).and_then(Value::as_str).map(str::to_string));
            } else if io.evals().get(&e.name).is_none() {
                return Err(setup(format!("eval `{}` is not registered", e.name)));
            }
        }
        for m in &models {
            io.model(m).await.map_err(|e| setup(e.to_string()))?;
        }
        Ok(AgentRun {
            format: RUN_FORMAT,
            run_id: RunId::new(),
            spec: RunSpec {
                persona: persona.name.clone(),
                model: persona.model.clone(),
                system: persona.system_prompt(),
                tools: persona.tools.clone(),
                evals: persona.evals.clone(),
                output: persona.output.clone(),
                max_turns: persona.max_turns,
                max_tokens: persona.max_tokens,
            },
            limits: limits.with_budget(&persona.budget),
            messages: input,
            state: RunState::CallModel,
            model_calls: 0,
            repaired: false,
            usage: Usage::default(),
            seq: 0,
            steps: 0,
            trace: None,
        })
    }

    /// Restores a run from `cp`. Returns `Checkpoint` when the state does
    /// not parse, has unknown fields, has another `RUN_FORMAT`, or does not
    /// match the checkpoint's run id and step.
    pub fn from_checkpoint(cp: &Checkpoint) -> Result<AgentRun, AgentError> {
        let run: AgentRun = serde_json::from_value(cp.state.clone())
            .map_err(|e| AgentError::Checkpoint(e.to_string()))?;
        if run.format != RUN_FORMAT {
            return Err(AgentError::Checkpoint(format!(
                "run format {} is not {RUN_FORMAT}",
                run.format
            )));
        }
        if run.run_id != cp.run_id || run.steps != cp.step {
            return Err(AgentError::Checkpoint(
                "checkpoint header does not match its state".into(),
            ));
        }
        if let Some(saved) = &run.trace {
            saved.spec().map_err(AgentError::Checkpoint)?;
        }
        Ok(run)
    }

    /// Snapshots the run for a `CheckpointStore`: step 0 before the first
    /// step, then one more after each step, whatever its outcome.
    /// Returns the checkpoint.
    pub fn checkpoint(&self) -> Checkpoint {
        Checkpoint {
            run_id: self.run_id,
            step: self.steps,
            state: serde_json::to_value(self).expect("run state serializes"),
        }
    }

    /// Returns the run's id.
    /// Every event and checkpoint of the run carries it.
    /// It never changes.
    pub fn run_id(&self) -> RunId {
        self.run_id
    }

    /// Returns the current state.
    /// Hosts read it to show progress or the final output.
    /// It changes only in `step` and `resume`.
    pub fn state(&self) -> &RunState {
        &self.state
    }

    /// Returns the conversation so far: input, replies, tool results
    /// and repair requests, in order.
    /// The system prompt is not part of it.
    pub fn messages(&self) -> &[Message] {
        &self.messages
    }

    /// Returns tokens and cost of every model call so far.
    /// Judge calls are included; costs use the handle's price.
    /// Compare it with the run budget.
    pub fn usage(&self) -> Usage {
        self.usage
    }

    /// Returns how many agent model calls ran.
    /// This is the count `max_turns` caps; the repair call counts,
    /// judge calls do not.
    pub fn model_calls(&self) -> u32 {
        self.model_calls
    }

    /// Leaves a pause with new `limits` (for example after an owner raised
    /// a budget), back in the state that paused. The next step checks the
    /// budget again. Returns `Setup` when the run is not paused.
    pub fn resume(&mut self, limits: Limits) -> Result<(), AgentError> {
        let RunState::Paused { resume, .. } = &self.state else {
            return Err(AgentError::Setup("run is not paused".into()));
        };
        self.state = (**resume).clone();
        self.limits = limits;
        Ok(())
    }

    /// Traces this run with `spec` from its next step on; the spec is kept
    /// in the checkpoint, so a resumed run keeps it. Input: the spec.
    /// Output: none.
    pub fn set_trace(&mut self, spec: TraceSpec) {
        self.trace = Some(SavedTrace::from_spec(&spec));
        assert_eq!(self.trace(), Some(spec));
    }

    /// Returns the trace spec set with `set_trace`, if any.
    /// Input: none. Output: the spec.
    pub fn trace(&self) -> Option<TraceSpec> {
        self.trace
            .as_ref()
            .map(|saved| saved.spec().expect("trace spec checked when set or loaded"))
    }

    /// Runs one step: one model call, one tool batch, one output check or
    /// one repair prompt, emitting its events through `io`. Final and paused
    /// runs return their outcome again and change nothing. With a trace
    /// spec the step nests in the active scope, or writes its trace file.
    pub async fn step(&mut self, io: &dyn AgentIo) -> StepOutcome {
        let working = !matches!(
            self.state,
            RunState::Done { .. } | RunState::Failed { .. } | RunState::Paused { .. }
        );
        let Some(spec) = self.trace().filter(|_| working) else {
            return self.step_once(io).await;
        };
        if let Some(scope) = troupekit_trace::current() {
            let nested = scope.nest(spec.categories(), None);
            return nested.in_scope(self.step_once(io)).await;
        }
        match open_trace(&spec, &self.spec.persona, self.run_id) {
            Ok(tracer) => tracer.in_scope(self.step_once(io)).await,
            Err(_) => self.step_once(io).await,
        }
    }

    async fn step_once(&mut self, io: &dyn AgentIo) -> StepOutcome {
        match &self.state {
            RunState::Done { output } => return StepOutcome::Done(output.clone()),
            RunState::Failed { error } => return StepOutcome::Failed(error.clone()),
            RunState::Paused { reason, .. } => return StepOutcome::Paused(reason.clone()),
            _ => {}
        }
        if self.seq == 0 {
            self.emit(
                io,
                EventBody::RunStarted {
                    workflow: self.spec.persona.clone(),
                },
            );
        }
        self.steps += 1;
        let name = self.state.step_name();
        let mut span = trace_span!(
            Trace::Agents,
            "agent.step",
            run = self.run_id.to_string(),
            state = name,
            persona = self.spec.persona.as_str(),
        );
        self.emit(
            io,
            EventBody::StepStarted {
                step: name.into(),
                persona: None,
            },
        );
        let mut used = Usage::default();
        let outcome = span
            .instrument(async {
                match self.state.clone() {
                    RunState::CallModel => self.call_model(io, &mut used).await,
                    RunState::CallTools { calls } => self.call_tools(io, &calls).await,
                    RunState::Check { answer } => self.check(io, &answer, &mut used).await,
                    RunState::Repair { errors } => {
                        self.messages.push(repair_message(&errors));
                        self.state = RunState::CallModel;
                        StepOutcome::Continue
                    }
                    RunState::Done { .. } | RunState::Failed { .. } | RunState::Paused { .. } => {
                        unreachable!("handled above")
                    }
                }
            })
            .await;
        if let StepOutcome::Failed(error) = &outcome {
            span.fail("step failed");
            span.record("error", content(error.as_str()));
        }
        self.emit(
            io,
            EventBody::StepFinished {
                step: name.into(),
                usage: used,
            },
        );
        match &outcome {
            StepOutcome::Paused(reason) => self.emit(
                io,
                EventBody::RunPaused {
                    reason: reason.clone(),
                },
            ),
            StepOutcome::Done(_) => self.emit(io, EventBody::RunFinished { usage: self.usage }),
            StepOutcome::Failed(error) => self.emit(
                io,
                EventBody::RunFailed {
                    error: error.clone(),
                },
            ),
            StepOutcome::Continue | StepOutcome::Retry { .. } => {}
        }
        outcome
    }

    fn emit(&mut self, io: &dyn AgentIo, body: EventBody) {
        io.events().emit(Event {
            run_id: self.run_id,
            seq: self.seq,
            at_ms: io.clock().now_ms(),
            body,
        });
        self.seq += 1;
    }

    fn fail(&mut self, error: String) -> StepOutcome {
        self.state = RunState::Failed {
            error: error.clone(),
        };
        StepOutcome::Failed(error)
    }

    fn request(&self, io: &dyn AgentIo) -> CompletionRequest {
        let tools = io
            .tools()
            .specs()
            .into_iter()
            .filter(|s| self.spec.tools.contains(&s.name))
            .filter_map(|mut s| {
                if let Some(h) = s.hosted {
                    let used: u64 = self.messages.iter().map(|m| m.hosted_calls(h.name())).sum();
                    let left = u64::from(h.max_uses()).saturating_sub(used);
                    if left == 0 {
                        return None;
                    }
                    s.hosted = Some(
                        h.with_max_uses(u32::try_from(left).expect("left is at most max_uses")),
                    );
                }
                Some(s)
            })
            .collect();
        CompletionRequest {
            model: None,
            system: Some(self.spec.system.clone()),
            messages: self.messages.clone(),
            tools,
            max_tokens: self.spec.max_tokens,
            temperature: None,
            output_schema: self.spec.output.clone(),
        }
    }

    async fn call_model(&mut self, io: &dyn AgentIo, used: &mut Usage) -> StepOutcome {
        let held = self.model_calls < self.spec.max_turns;
        trace!(
            Trace::Laws,
            "law.check",
            law = "step_keeps_model_calls_within_max_turns",
            held = held,
            model_calls = self.model_calls,
            max_turns = self.spec.max_turns,
        );
        if !held {
            return self.fail(format!("max_turns {} reached", self.spec.max_turns));
        }
        let handle = match io.model(&self.spec.model).await {
            Ok(h) => h,
            Err(e) => return self.fail(e.to_string()),
        };
        let req = self.request(io);
        let reply = match self
            .call(io, &handle, &req, true, used, RunState::CallModel)
            .await
        {
            Ok(r) => r,
            Err(outcome) => return outcome,
        };
        self.model_calls += 1;
        let calls: Vec<PendingCall> = reply
            .message
            .tool_calls()
            .map(|(id, name, arguments)| PendingCall {
                id: id.into(),
                name: name.into(),
                arguments: arguments.clone(),
            })
            .collect();
        let answer = reply.message.final_text();
        let kept = reply
            .message
            .parts
            .iter()
            .any(|p| !matches!(p, ContentPart::Text { text } if text.trim().is_empty()));
        if kept {
            self.messages.push(reply.message);
        }
        self.state = if reply.stop == StopReason::PauseTurn {
            RunState::CallModel
        } else if calls.is_empty() {
            RunState::Check { answer }
        } else {
            RunState::CallTools { calls }
        };
        StepOutcome::Continue
    }

    async fn call(
        &mut self,
        io: &dyn AgentIo,
        handle: &ModelHandle,
        req: &CompletionRequest,
        stream: bool,
        used: &mut Usage,
        resume: RunState,
    ) -> Result<CompletionResponse, StepOutcome> {
        let estimate = budget::estimate(req, &handle.price);
        match budget::check(
            &self.limits,
            &handle.price,
            self.usage.cost_usd_micros,
            estimate,
            io.ledger(),
        )
        .await
        {
            Err(e) => {
                return Err(StepOutcome::Retry {
                    error: format!("usage ledger: {e}"),
                    retry_after_ms: None,
                })
            }
            Ok(Some(layer)) => {
                let reason = PauseReason::Budget {
                    limit: layer.into(),
                };
                self.state = RunState::Paused {
                    reason: reason.clone(),
                    resume: Box::new(resume),
                };
                return Err(StepOutcome::Paused(reason));
            }
            Ok(None) => {}
        }
        let mut span = trace_span!(
            Trace::Models,
            "model.call",
            model = handle.model.id(),
            stream = stream,
            messages = content(serde_json::to_string(&req.messages).expect("messages serialize")),
        );
        let started = span.is_enabled().then(Instant::now);
        let mut first_delta: Option<Instant> = None;
        let result = if stream {
            let (sink, clock, run_id, seq) = (io.events(), io.clock(), self.run_id, &mut self.seq);
            let first = &mut first_delta;
            let timed = started.is_some();
            let mut on_delta = |d: &Delta| {
                if timed {
                    first.get_or_insert_with(Instant::now);
                }
                if let Delta::TextDelta { text } = d {
                    sink.emit(Event {
                        run_id,
                        seq: *seq,
                        at_ms: clock.now_ms(),
                        body: EventBody::TextDelta { text: text.clone() },
                    });
                    *seq += 1;
                }
            };
            span.instrument(handle.model.stream(req, &mut on_delta)).await
        } else {
            span.instrument(handle.model.complete(req)).await
        };
        if let (Some(started), Some(at)) = (started, first_delta) {
            span.record("ttft_us", at.saturating_duration_since(started).as_micros() as u64);
        }
        if let Err(e) = &result {
            span.fail("model call failed");
            span.record("retryable", e.is_retryable());
            span.record("error", content(e.to_string()));
        }
        let mut reply = match result {
            Ok(r) => r,
            Err(e) if e.is_retryable() => {
                return Err(StepOutcome::Retry {
                    error: e.to_string(),
                    retry_after_ms: e.retry_after_ms,
                })
            }
            Err(e) => return Err(self.fail(e.to_string())),
        };
        reply.usage.cost_usd_micros = handle.price.cost_usd_micros(&reply.usage);
        if span.is_enabled() {
            span.record("input_tokens", reply.usage.input_tokens);
            span.record("output_tokens", reply.usage.output_tokens);
            span.record("cost_usd_micros", reply.usage.cost_usd_micros);
            span.record("stop", format!("{:?}", reply.stop));
            span.record("reply", content(reply.message.text_content()));
        }
        drop(span);
        self.usage += reply.usage;
        *used += reply.usage;
        if let Err(e) = budget::record(&self.limits, io.ledger(), reply.usage).await {
            return Err(self.fail(format!("usage ledger: {e}")));
        }
        Ok(reply)
    }

    async fn call_tools(&mut self, io: &dyn AgentIo, calls: &[PendingCall]) -> StepOutcome {
        assert!(!calls.is_empty(), "a tool step has at least one call");
        for c in calls {
            self.emit(
                io,
                EventBody::ToolCallStarted {
                    call_id: c.id.clone(),
                    name: c.name.clone(),
                },
            );
        }
        let (run_id, step) = (self.run_id, self.steps);
        let allowed = &self.spec.tools;
        let outputs = join_all(calls.iter().enumerate().map(|(i, c)| {
            let ctx = ToolContext::for_call(run_id, step, i);
            async move {
                let mut span = trace_span!(
                    Trace::Tools,
                    "tool.call",
                    name = c.name.as_str(),
                    call_id = c.id.as_str(),
                    args = content(c.arguments.to_string()),
                );
                let out = if allowed.contains(&c.name) {
                    let call = io.tools().call(&c.name, c.arguments.clone(), &ctx);
                    ToolOutput::from_result(span.instrument(call).await)
                } else {
                    ToolOutput::error(format!("tool `{}` is not allowed for this agent", c.name))
                };
                if span.is_enabled() {
                    span.record("is_error", out.is_error);
                    span.record("output", content(out.content.as_str()));
                }
                out
            }
        }))
        .await;
        assert_eq!(outputs.len(), calls.len());
        let mut parts = Vec::with_capacity(calls.len());
        for (c, out) in calls.iter().zip(outputs) {
            self.emit(
                io,
                EventBody::ToolCallFinished {
                    call_id: c.id.clone(),
                    is_error: out.is_error,
                },
            );
            parts.push(ContentPart::ToolResult {
                call_id: c.id.clone(),
                content: out.content,
                is_error: out.is_error,
            });
        }
        self.messages
            .push(Message::new(Role::Tool, parts).expect("tool results form a valid tool message"));
        self.state = RunState::CallModel;
        StepOutcome::Continue
    }

    async fn check(&mut self, io: &dyn AgentIo, answer: &str, used: &mut Usage) -> StepOutcome {
        let (output, mut errors) = match &self.spec.output {
            None => (Value::String(answer.to_string()), Vec::new()),
            Some(schema) => match parse_json(answer) {
                Err(e) => (Value::Null, vec![e]),
                Ok(v) => {
                    let errs = validate(schema, &v);
                    (v, errs)
                }
            },
        };
        if errors.is_empty() {
            for call in self.spec.evals.clone() {
                if call.name == "judge" {
                    match self.judge(io, &call, &output, answer, used).await {
                        Ok(None) => {}
                        Ok(Some(reason)) => errors.push(format!("judge: {reason}")),
                        Err(outcome) => return outcome,
                    }
                    continue;
                }
                let Some(f) = io.evals().get(&call.name) else {
                    return self.fail(format!("eval `{}` is not registered", call.name));
                };
                let mut span = trace_span!(Trace::Evals, "eval.run", name = call.name.as_str());
                let passed = f(&output, &call.args);
                span.record("passed", passed.is_ok());
                if let Err(e) = passed {
                    errors.push(format!("{}: {e}", call.name));
                }
            }
        }
        if errors.is_empty() {
            self.state = RunState::Done {
                output: output.clone(),
            };
            return StepOutcome::Done(output);
        }
        if !self.repaired && self.model_calls < self.spec.max_turns {
            self.repaired = true;
            self.state = RunState::Repair { errors };
            return StepOutcome::Continue;
        }
        self.fail(errors.join("; "))
    }

    async fn judge(
        &mut self,
        io: &dyn AgentIo,
        call: &Call,
        output: &Value,
        answer: &str,
        used: &mut Usage,
    ) -> Result<Option<String>, StepOutcome> {
        let criteria = call
            .args
            .first()
            .and_then(Value::as_str)
            .expect("judge criteria checked at persona load");
        let min_score = call
            .args
            .get(1)
            .and_then(Value::as_f64)
            .expect("judge min_score checked at persona load");
        let selector = call
            .args
            .get(2)
            .and_then(Value::as_str)
            .unwrap_or(self.spec.model.as_str())
            .to_string();
        let mut span = trace_span!(
            Trace::Evals,
            "eval.judge",
            name = "judge",
            selector = selector.as_str(),
        );
        let handle = match io.model(&selector).await {
            Ok(h) => h,
            Err(e) => {
                span.fail(e.to_string());
                return Err(self.fail(format!("judge: {e}")));
            }
        };
        let req = judge_request(criteria, output);
        let resume = RunState::Check {
            answer: answer.to_string(),
        };
        let reply = match span.instrument(self.call(io, &handle, &req, false, used, resume)).await {
            Ok(reply) => reply,
            Err(outcome) => {
                span.fail("judge call did not complete");
                return Err(outcome);
            }
        };
        let text = reply.message.text_content();
        let verdict = judge_verdict(&text, min_score);
        if span.is_enabled() {
            span.record("passed", verdict.is_ok());
            if let Some(score) = parse_json(&text).ok().and_then(|v| v["score"].as_f64()) {
                span.record("score", score);
            }
        }
        Ok(verdict.err())
    }
}

/// Drives `run` until it is done, failed, paused or asks for a retry,
/// saving a checkpoint to `store` before the first step (when the store has
/// none) and after every step. Returns the last outcome.
pub async fn drive(
    run: &mut AgentRun,
    io: &dyn AgentIo,
    store: &dyn CheckpointStore,
) -> Result<StepOutcome, AgentError> {
    if store.latest(run.run_id).await?.is_none() {
        store.save(run.checkpoint()).await?;
    }
    loop {
        let outcome = run.step(io).await;
        store.save(run.checkpoint()).await?;
        if outcome != StepOutcome::Continue {
            return Ok(outcome);
        }
    }
}