Skip to main content

troupekit_kit/built/
start.rs

1use super::{detached, note_retry, outcome, retry_left, BuiltAgent, Cancel, Input};
2use crate::error::KitError;
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5use troupekit_agent::{AgentIo, AgentRun, RunState, StepOutcome};
6use troupekit_core::ids::RunId;
7use troupekit_core::store::CheckpointStore;
8
9/// Most steps one `resume_for` call takes before it returns `Pending`,
10/// whatever the budget. Bounds a window even when steps are instant.
11/// Fixed at 10 000.
12pub const MAX_STEPS_PER_WINDOW: u32 = 10_000;
13
14/// Where a run stands after one `resume_for` window.
15/// `Done` holds the answer as text; `Pending` means the budget or the
16/// step bound ran out first, and the run resumes from its last save.
17#[derive(Debug, Clone, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum Progress {
20    Done(String),
21    Pending { run_id: RunId },
22}
23
24impl BuiltAgent {
25    /// Starts a run on `input`: checks it, saves the first checkpoint and
26    /// returns the run id, with no model call. Continue it with `resume`
27    /// or `resume_for`. Needs `Storage::sqlite(..)` or `Storage::custom(..)`.
28    pub async fn start(&self, input: impl Into<Input>) -> Result<RunId, KitError> {
29        let store = self.durable("start")?;
30        let messages = self.messages(input.into()).await?;
31        let inner = &self.inner;
32        let run = AgentRun::new(&inner.persona, messages, inner.limits.clone(), &inner.io).await?;
33        store.save(run.checkpoint()).await?;
34        Ok(run.run_id())
35    }
36
37    /// Continues run `run_id` for about `budget`, saving after every step.
38    /// A step in flight finishes, so leave one model call of slack in a
39    /// background window. Fails with `Failed`, `Paused` or `Retries` as
40    /// `resume` does; a retry wait that would pass the budget is `Pending`
41    /// and is saved, so the next window waits out what is left of it.
42    pub async fn resume_for(&self, run_id: RunId, budget: Duration) -> Result<Progress, KitError> {
43        let store = self.durable("resume_for")?;
44        let Some(checkpoint) = store.latest(run_id).await? else {
45            return Err(KitError::config(
46                &self.inner.persona.name,
47                format!("no checkpoint for run {run_id}"),
48            ));
49        };
50        let deadline = Instant::now().checked_add(budget);
51        let mut run = AgentRun::from_checkpoint(&checkpoint)?;
52        let name = self.inner.persona.name.as_str();
53        if run.persona() != name {
54            return Err(KitError::config(
55                name,
56                format!(
57                    "run {run_id} was started by agent `{}`; resume it with that agent",
58                    run.persona()
59                ),
60            ));
61        }
62        let current = self.inner.limits.clone().with_budget(&self.inner.persona.budget);
63        run.tighten(&current);
64        match run.state().clone() {
65            RunState::Done { output } => return Ok(Progress::Done(outcome(&run, output).text)),
66            RunState::Failed { error } => {
67                return Err(KitError::failed(run_id, error, run.host_failed()))
68            }
69            RunState::Paused { reason, .. } => return Err(KitError::Paused { run_id, reason }),
70            _ => {}
71        }
72        self.refuse_exhausted(&run)?;
73        let agent = self.clone();
74        detached(run_id, move |stop| async move {
75            agent.window(run, store, deadline, &stop).await
76        })
77        .await
78    }
79
80    /// Steps `run` until it ends, `deadline` passes, `MAX_STEPS_PER_WINDOW`
81    /// steps ran or `cancel` is set after a step, saving after each step.
82    /// Input: the restored run, its store, the deadline and the stop flag.
83    /// Output: the window's progress, or the run's error.
84    async fn window(
85        &self,
86        mut run: AgentRun,
87        store: Arc<dyn CheckpointStore>,
88        deadline: Option<Instant>,
89        cancel: &Cancel,
90    ) -> Result<Progress, KitError> {
91        let run_id = run.run_id();
92        let spent = |extra: Duration| match deadline {
93            Some(deadline) => Instant::now() + extra >= deadline,
94            None => false,
95        };
96        let io: &dyn AgentIo = &self.inner.io;
97        let saved_wait = retry_left(&run, io.clock().now_ms());
98        if !saved_wait.is_zero() {
99            if spent(saved_wait) {
100                return Ok(Progress::Pending { run_id });
101            }
102            if cancel.sleep(saved_wait).await {
103                return Err(KitError::Cancelled { run_id });
104            }
105        }
106        let mut steps = 0u32;
107        while steps < MAX_STEPS_PER_WINDOW && !spent(Duration::ZERO) {
108            if cancel.is_set() {
109                return Err(KitError::Cancelled { run_id });
110            }
111            let step = run.step(io).await;
112            let wait = note_retry(&mut run, &step, io.clock().now_ms());
113            store
114                .save(run.checkpoint())
115                .await
116                .map_err(|e| KitError::in_run(run_id, e.into()))?;
117            steps += 1;
118            if cancel.is_set() {
119                return Err(KitError::Cancelled { run_id });
120            }
121            match step {
122                StepOutcome::Continue => {}
123                StepOutcome::Done(output) => return Ok(Progress::Done(outcome(&run, output).text)),
124                StepOutcome::Retry { error, .. } => {
125                    assert!(run.retries() > 0);
126                    let attempts = run.retries() - 1;
127                    if attempts >= self.inner.retries {
128                        return Err(KitError::Retries {
129                            run_id,
130                            attempts,
131                            last_error: error,
132                        });
133                    }
134                    let wait = wait.expect("a retry step has a wait");
135                    if spent(wait) {
136                        return Ok(Progress::Pending { run_id });
137                    }
138                    if cancel.sleep(wait).await {
139                        return Err(KitError::Cancelled { run_id });
140                    }
141                }
142                StepOutcome::Paused(reason) => return Err(KitError::Paused { run_id, reason }),
143                StepOutcome::Failed(reason) => {
144                    return Err(KitError::failed(run_id, reason, run.host_failed()))
145                }
146            }
147            assert!(run.retries() <= self.inner.retries);
148        }
149        assert!(steps <= MAX_STEPS_PER_WINDOW);
150        Ok(Progress::Pending { run_id })
151    }
152
153    fn durable(&self, what: &str) -> Result<Arc<dyn CheckpointStore>, KitError> {
154        match &self.inner.store {
155            Some(store) => Ok(store.clone()),
156            None => Err(KitError::config(
157                &self.inner.persona.name,
158                format!("{what} needs Storage::sqlite(..) or Storage::custom(..) checkpoints"),
159            )),
160        }
161    }
162}