Skip to main content

troupekit_kit/
built.rs

1use crate::error::KitError;
2use crate::laws::Laws;
3use serde_json::Value;
4use crate::trace::{path_of, root_span, Traced};
5use std::fmt;
6use std::future::Future;
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9use std::time::Duration;
10use troupekit_agent::{
11    AgentError, AgentIo, AgentRun, EventSink, Limits, Persona, RunState, SimpleIo, StepOutcome,
12};
13use troupekit_core::event::{Event, Usage};
14use troupekit_core::ids::RunId;
15use troupekit_core::inmem::InMemCheckpoints;
16use troupekit_core::message::{Message, Role};
17use troupekit_core::store::CheckpointStore;
18use troupekit_trace::Trace;
19
20mod start;
21mod stream;
22
23pub use start::{Progress, MAX_STEPS_PER_WINDOW};
24pub(crate) use stream::{detached, Cancel, Queue, StreamIo};
25pub use stream::{RunStream, StreamSettings};
26
27const BASE_RETRY_MS: u64 = 500;
28const MAX_RETRY_MS: u64 = 30_000;
29
30pub(crate) struct Discard;
31
32impl EventSink for Discard {
33    fn emit(&self, _event: Event) {}
34}
35
36/// What an agent runs on: one user text, or a prepared conversation.
37/// Built from `&str`, `String`, one `Message` or a `Vec<Message>`.
38/// An empty conversation fails when the run starts.
39#[derive(Debug, Clone, PartialEq)]
40pub struct Input(Vec<Message>);
41
42impl From<&str> for Input {
43    fn from(text: &str) -> Self {
44        Input(vec![Message::text(Role::User, text)])
45    }
46}
47
48impl From<String> for Input {
49    fn from(text: String) -> Self {
50        Input(vec![Message::text(Role::User, text)])
51    }
52}
53
54impl From<Message> for Input {
55    fn from(message: Message) -> Self {
56        Input(vec![message])
57    }
58}
59
60impl From<Vec<Message>> for Input {
61    fn from(messages: Vec<Message>) -> Self {
62        Input(messages)
63    }
64}
65
66/// The result of one finished run: the answer and how it was reached.
67/// `text` is the answer as text; `output` is the raw final value.
68/// Read it through the getters.
69#[derive(Debug, Clone, PartialEq)]
70#[non_exhaustive]
71pub struct RunOutcome {
72    text: String,
73    output: Value,
74    usage: Usage,
75    model_calls: u32,
76    run_id: RunId,
77    messages: Vec<Message>,
78    trace_path: Option<PathBuf>,
79}
80
81impl RunOutcome {
82    /// Returns the answer as text: a string output as is, any other
83    /// output as JSON text.
84    /// The same text `run` returns.
85    pub fn text(&self) -> &str {
86        &self.text
87    }
88
89    /// Returns the final output value of the run.
90    /// A string for plain agents, a JSON value for typed output.
91    /// Never null for a finished run.
92    pub fn output(&self) -> &Value {
93        &self.output
94    }
95
96    /// Returns the tokens and cost the run used, summed over calls.
97    /// Cost is in millionths of a US dollar.
98    /// Includes eval and repair calls.
99    pub fn usage(&self) -> Usage {
100        self.usage
101    }
102
103    /// Returns how many model calls the run made.
104    /// Retried calls count once per attempt that reached the model.
105    /// At least one for a finished run.
106    pub fn model_calls(&self) -> u32 {
107        self.model_calls
108    }
109
110    /// Returns the id of the run, for `resume` and logs.
111    /// Unique per run.
112    /// Stable across checkpoints.
113    pub fn run_id(&self) -> RunId {
114        self.run_id
115    }
116
117    /// Returns the whole conversation, input first.
118    /// Includes tool calls and tool results.
119    /// The last message is the answer.
120    pub fn messages(&self) -> &[Message] {
121        &self.messages
122    }
123
124    /// Returns the trace file this run was written to.
125    /// `None` when tracing is off or goes to a custom sink.
126    /// Every run of one built agent shares the file.
127    pub fn trace_path(&self) -> Option<&Path> {
128        self.trace_path.as_deref()
129    }
130}
131
132/// An agent that passed every `build` check, ready to run many times.
133/// Cheap to clone and safe to share across tasks; each run gets its own
134/// state, and in-memory checkpoints are dropped after the run.
135#[derive(Clone)]
136pub struct BuiltAgent {
137    inner: Arc<Inner>,
138}
139
140struct Inner {
141    persona: Persona,
142    io: SimpleIo,
143    limits: Limits,
144    store: Option<Arc<dyn CheckpointStore>>,
145    retries: u32,
146    laws: Laws,
147    trace: Option<Traced>,
148    #[cfg(feature = "knowledge")]
149    preamble: Option<troupekit_context::tools::KnowledgeKit>,
150}
151
152impl BuiltAgent {
153    pub(crate) fn new(
154        persona: Persona,
155        io: SimpleIo,
156        limits: Limits,
157        store: Option<Arc<dyn CheckpointStore>>,
158        retries: u32,
159        laws: Laws,
160    ) -> Self {
161        BuiltAgent {
162            inner: Arc::new(Inner {
163                persona,
164                io,
165                limits,
166                store,
167                retries,
168                laws,
169                trace: None,
170                #[cfg(feature = "knowledge")]
171                preamble: None,
172            }),
173        }
174    }
175
176    pub(crate) fn with_trace(mut self, trace: Option<Traced>) -> Self {
177        let inner = Arc::get_mut(&mut self.inner).expect("a fresh BuiltAgent is not shared");
178        inner.trace = trace;
179        self
180    }
181
182    /// Returns the trace file this agent writes, one root span per run.
183    /// `None` when tracing is off or goes to a custom sink.
184    /// The file is created at `build`.
185    pub fn trace_path(&self) -> Option<&Path> {
186        path_of(&self.inner.trace)
187    }
188
189    async fn traced<T>(
190        &self,
191        run_id: Option<RunId>,
192        work: impl Future<Output = Result<T, KitError>>,
193        id_of: impl Fn(&T) -> RunId,
194    ) -> Result<T, KitError> {
195        let owner = self.inner.persona.name.as_str();
196        let traced = self.inner.trace.as_ref();
197        root_span(traced, Trace::Agents, "agent.run", owner, run_id, work, id_of).await
198    }
199
200    #[cfg(feature = "knowledge")]
201    pub(crate) fn with_preamble(
202        mut self,
203        preamble: Option<troupekit_context::tools::KnowledgeKit>,
204    ) -> Self {
205        let inner = Arc::get_mut(&mut self.inner).expect("a fresh BuiltAgent is not shared");
206        inner.preamble = preamble;
207        self
208    }
209
210    #[cfg(feature = "knowledge")]
211    async fn messages(&self, input: Input) -> Result<Vec<Message>, KitError> {
212        match &self.inner.preamble {
213            Some(kit) => crate::memory::prepend(kit, input.0).await,
214            None => Ok(input.0),
215        }
216    }
217
218    #[cfg(not(feature = "knowledge"))]
219    async fn messages(&self, input: Input) -> Result<Vec<Message>, KitError> {
220        Ok(input.0)
221    }
222
223    /// Runs the agent once on `input` and returns the answer as text.
224    /// Retries transient provider failures; fails with `Failed`,
225    /// `Paused` or `Retries` when the run ends without an answer.
226    pub async fn run(&self, input: impl Into<Input>) -> Result<String, KitError> {
227        Ok(self.run_with(input).await?.text)
228    }
229
230    /// Runs the agent once on `input` and returns the full outcome.
231    /// Same failures as `run`.
232    /// The run id in the outcome works with `resume`.
233    pub async fn run_with(&self, input: impl Into<Input>) -> Result<RunOutcome, KitError> {
234        let input = input.into();
235        self.traced(None, self.run_untraced(input), RunOutcome::run_id)
236            .await
237    }
238
239    async fn run_untraced(&self, input: Input) -> Result<RunOutcome, KitError> {
240        let inner = &self.inner;
241        let messages = self.messages(input).await?;
242        let run =
243            AgentRun::new(&inner.persona, messages, inner.limits.clone(), &inner.io).await?;
244        let store: Arc<dyn CheckpointStore> = match &inner.store {
245            Some(store) => store.clone(),
246            None => Arc::new(InMemCheckpoints::default()),
247        };
248        let agent = self.clone();
249        detached(run.run_id(), move |stop| async move {
250            let mut run = run;
251            agent.finish(&agent.inner.io, &mut run, store.as_ref(), &stop).await
252        })
253        .await
254    }
255
256    /// Continues run `run_id` from its latest checkpoint, after a crash
257    /// or restart, and returns the answer. A finished run returns its
258    /// answer again. Needs `Storage::sqlite(..)` or `Storage::custom(..)`.
259    /// Refuses another agent's run; limits become the stricter of the
260    /// run's and this agent's, and the retry budget counts across resumes.
261    pub async fn resume(&self, run_id: RunId) -> Result<String, KitError> {
262        self.traced(Some(run_id), self.resume_untraced(run_id), |_| run_id)
263            .await
264    }
265
266    async fn resume_untraced(&self, run_id: RunId) -> Result<String, KitError> {
267        let name = self.inner.persona.name.as_str();
268        let Some(store) = &self.inner.store else {
269            return Err(KitError::config(
270                name,
271                "resume needs Storage::sqlite(..) or Storage::custom(..) checkpoints",
272            ));
273        };
274        let Some(checkpoint) = store.latest(run_id).await? else {
275            return Err(KitError::config(
276                name,
277                format!("no checkpoint for run {run_id}"),
278            ));
279        };
280        let mut run = AgentRun::from_checkpoint(&checkpoint)?;
281        if run.persona() != name {
282            return Err(KitError::config(
283                name,
284                format!(
285                    "run {run_id} was started by agent `{}`; resume it with that agent",
286                    run.persona()
287                ),
288            ));
289        }
290        let current = self.inner.limits.clone().with_budget(&self.inner.persona.budget);
291        run.tighten(&current);
292        let agent = self.clone();
293        let store = store.clone();
294        let outcome = detached(run_id, move |stop| async move {
295            let mut run = run;
296            agent.finish(&agent.inner.io, &mut run, store.as_ref(), &stop).await
297        })
298        .await?;
299        Ok(outcome.text)
300    }
301
302    /// Returns the validated persona this agent runs.
303    /// Built from the builder settings by `Persona::parse`.
304    /// Read only.
305    pub fn persona(&self) -> &Persona {
306        &self.inner.persona
307    }
308
309    /// Returns the laws checked at `build`.
310    /// 0.2 stores them; runs do not prove them yet.
311    /// Read only.
312    pub fn laws(&self) -> &Laws {
313        &self.inner.laws
314    }
315
316    /// Refuses a restored run whose saved retry count is past this agent's
317    /// cap, before any step: an earlier call already ended it with
318    /// `Retries`. A count equal to the cap may still take its last retry.
319    fn refuse_exhausted(&self, run: &AgentRun) -> Result<(), KitError> {
320        let retries = run.retries();
321        if retries <= self.inner.retries {
322            return Ok(());
323        }
324        assert!(retries > 0);
325        Err(KitError::Retries {
326            run_id: run.run_id(),
327            attempts: retries - 1,
328            last_error: "retries were used up by an earlier call".into(),
329        })
330    }
331
332    async fn finish(
333        &self,
334        io: &dyn AgentIo,
335        run: &mut AgentRun,
336        store: &dyn CheckpointStore,
337        cancel: &Cancel,
338    ) -> Result<RunOutcome, KitError> {
339        match run.state().clone() {
340            RunState::Done { output } => return Ok(self.outcome(run, output)),
341            RunState::Failed { error } => {
342                return Err(KitError::failed(run.run_id(), error, run.host_failed()))
343            }
344            RunState::Paused { reason, .. } => {
345                return Err(KitError::Paused {
346                    run_id: run.run_id(),
347                    reason,
348                })
349            }
350            _ => {}
351        }
352        self.refuse_exhausted(run)?;
353        let saved_wait = retry_left(run, io.clock().now_ms());
354        if !saved_wait.is_zero() {
355            tokio::time::sleep(saved_wait).await;
356        }
357        run.set_retry_at_ms(None);
358        loop {
359            let step = drive_until(run, io, store, cancel)
360                .await
361                .map_err(|e| KitError::in_run(run.run_id(), e.into()))?;
362            let Some(step) = step else {
363                return Err(KitError::Cancelled {
364                    run_id: run.run_id(),
365                });
366            };
367            match step {
368                StepOutcome::Done(output) => return Ok(self.outcome(run, output)),
369                StepOutcome::Retry {
370                    error,
371                    retry_after_ms,
372                } => {
373                    assert!(run.retries() > 0);
374                    let attempts = run.retries() - 1;
375                    if attempts >= self.inner.retries {
376                        return Err(KitError::Retries {
377                            run_id: run.run_id(),
378                            attempts,
379                            last_error: error,
380                        });
381                    }
382                    if cancel.sleep(retry_delay(attempts, retry_after_ms)).await {
383                        return Err(KitError::Cancelled {
384                            run_id: run.run_id(),
385                        });
386                    }
387                }
388                StepOutcome::Paused(reason) => {
389                    return Err(KitError::Paused {
390                        run_id: run.run_id(),
391                        reason,
392                    })
393                }
394                StepOutcome::Failed(reason) => {
395                    return Err(KitError::failed(run.run_id(), reason, run.host_failed()))
396                }
397                StepOutcome::Continue => {
398                    unreachable!("drive_until returns only a final, paused or retry outcome")
399                }
400            }
401            assert!(run.retries() <= self.inner.retries);
402        }
403    }
404
405    fn outcome(&self, run: &AgentRun, output: Value) -> RunOutcome {
406        let mut outcome = outcome(run, output);
407        outcome.trace_path = self.trace_path().map(Path::to_path_buf);
408        outcome
409    }
410}
411
412impl fmt::Debug for BuiltAgent {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414        let inner = &self.inner;
415        f.debug_struct("BuiltAgent")
416            .field("name", &inner.persona.name)
417            .field("model", &inner.persona.model)
418            .field("tools", &inner.persona.tools)
419            .field("retries", &inner.retries)
420            .field("durable", &inner.store.is_some())
421            .field("laws", &inner.laws)
422            .finish_non_exhaustive()
423    }
424}
425
426fn outcome(run: &AgentRun, output: Value) -> RunOutcome {
427    let text = match &output {
428        Value::String(text) => text.clone(),
429        other => other.to_string(),
430    };
431    RunOutcome {
432        text,
433        output,
434        usage: run.usage(),
435        model_calls: run.model_calls(),
436        run_id: run.run_id(),
437        messages: run.messages().to_vec(),
438        trace_path: None,
439    }
440}
441
442/// Steps `run`, saving after every step, until a step ends in something
443/// other than `Continue`, as `drive` does, but checks `cancel` around each
444/// step, so a step in flight always finishes, is billed and saved, then
445/// stops. Output: the outcome, `None` once a stop was asked for, or the
446/// store error.
447async fn drive_until(
448    run: &mut AgentRun,
449    io: &dyn AgentIo,
450    store: &dyn CheckpointStore,
451    cancel: &Cancel,
452) -> Result<Option<StepOutcome>, AgentError> {
453    if store.latest(run.run_id()).await?.is_none() {
454        store.save(run.checkpoint()).await?;
455    }
456    loop {
457        if cancel.is_set() {
458            return Ok(None);
459        }
460        let outcome = run.step(io).await;
461        store.save(run.checkpoint()).await?;
462        if cancel.is_set() {
463            return Ok(None);
464        }
465        if outcome != StepOutcome::Continue {
466            return Ok(Some(outcome));
467        }
468    }
469}
470
471fn retry_delay(attempt: u32, retry_after_ms: Option<u64>) -> Duration {
472    let backoff = BASE_RETRY_MS.saturating_mul(1u64 << attempt.min(16));
473    Duration::from_millis(retry_after_ms.unwrap_or(backoff).min(MAX_RETRY_MS))
474}
475
476/// Records on `run` the wait after `step`, at `now_ms` on the io clock:
477/// the backoff of a `Retry`, cleared for any other outcome, so the next
478/// checkpoint carries it. Output: the wait of a `Retry`, else `None`.
479fn note_retry(run: &mut AgentRun, step: &StepOutcome, now_ms: i64) -> Option<Duration> {
480    let StepOutcome::Retry { retry_after_ms, .. } = step else {
481        run.set_retry_at_ms(None);
482        return None;
483    };
484    assert!(run.retries() > 0, "a retry step is counted");
485    let wait = retry_delay(run.retries() - 1, *retry_after_ms);
486    let wait_ms = i64::try_from(wait.as_millis()).expect("a retry wait is capped");
487    run.set_retry_at_ms(Some(now_ms.saturating_add(wait_ms)));
488    Some(wait)
489}
490
491/// Returns how much of the retry wait saved on `run` is left at `now_ms`,
492/// capped at the longest retry wait so a skewed clock cannot stall a run.
493/// Output: zero when no wait is saved or it has passed.
494fn retry_left(run: &AgentRun, now_ms: i64) -> Duration {
495    let left = run
496        .retry_at_ms()
497        .map_or(0, |at_ms| at_ms.saturating_sub(now_ms))
498        .clamp(0, i64::try_from(MAX_RETRY_MS).expect("the cap fits"));
499    let left = Duration::from_millis(u64::try_from(left).expect("left is clamped to 0 or more"));
500    assert!(left <= Duration::from_millis(MAX_RETRY_MS));
501    left
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    #[test]
509    fn retry_delay_backs_off_and_caps() {
510        assert_eq!(retry_delay(0, None), Duration::from_millis(500));
511        assert_eq!(retry_delay(2, None), Duration::from_millis(2000));
512        assert_eq!(retry_delay(20, None), Duration::from_millis(30_000));
513        assert_eq!(retry_delay(0, Some(7)), Duration::from_millis(7));
514        assert_eq!(retry_delay(0, Some(90_000)), Duration::from_millis(30_000));
515    }
516}