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#[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#[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 pub fn text(&self) -> &str {
86 &self.text
87 }
88
89 pub fn output(&self) -> &Value {
93 &self.output
94 }
95
96 pub fn usage(&self) -> Usage {
100 self.usage
101 }
102
103 pub fn model_calls(&self) -> u32 {
107 self.model_calls
108 }
109
110 pub fn run_id(&self) -> RunId {
114 self.run_id
115 }
116
117 pub fn messages(&self) -> &[Message] {
121 &self.messages
122 }
123
124 pub fn trace_path(&self) -> Option<&Path> {
128 self.trace_path.as_deref()
129 }
130}
131
132#[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 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 pub async fn run(&self, input: impl Into<Input>) -> Result<String, KitError> {
227 Ok(self.run_with(input).await?.text)
228 }
229
230 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 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(¤t);
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 pub fn persona(&self) -> &Persona {
306 &self.inner.persona
307 }
308
309 pub fn laws(&self) -> &Laws {
313 &self.inner.laws
314 }
315
316 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
442async 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
476fn 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
491fn 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}