use crate::error::KitError;
use crate::laws::Laws;
use serde_json::Value;
use crate::trace::{path_of, root_span, Traced};
use std::fmt;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use troupekit_agent::{
AgentError, AgentIo, AgentRun, EventSink, Limits, Persona, RunState, SimpleIo, StepOutcome,
};
use troupekit_core::event::{Event, Usage};
use troupekit_core::ids::RunId;
use troupekit_core::inmem::InMemCheckpoints;
use troupekit_core::message::{Message, Role};
use troupekit_core::store::CheckpointStore;
use troupekit_trace::Trace;
mod start;
mod stream;
pub use start::{Progress, MAX_STEPS_PER_WINDOW};
pub(crate) use stream::{detached, Cancel, Queue, StreamIo};
pub use stream::{RunStream, StreamSettings};
const BASE_RETRY_MS: u64 = 500;
const MAX_RETRY_MS: u64 = 30_000;
pub(crate) struct Discard;
impl EventSink for Discard {
fn emit(&self, _event: Event) {}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Input(Vec<Message>);
impl From<&str> for Input {
fn from(text: &str) -> Self {
Input(vec![Message::text(Role::User, text)])
}
}
impl From<String> for Input {
fn from(text: String) -> Self {
Input(vec![Message::text(Role::User, text)])
}
}
impl From<Message> for Input {
fn from(message: Message) -> Self {
Input(vec![message])
}
}
impl From<Vec<Message>> for Input {
fn from(messages: Vec<Message>) -> Self {
Input(messages)
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RunOutcome {
text: String,
output: Value,
usage: Usage,
model_calls: u32,
run_id: RunId,
messages: Vec<Message>,
trace_path: Option<PathBuf>,
}
impl RunOutcome {
pub fn text(&self) -> &str {
&self.text
}
pub fn output(&self) -> &Value {
&self.output
}
pub fn usage(&self) -> Usage {
self.usage
}
pub fn model_calls(&self) -> u32 {
self.model_calls
}
pub fn run_id(&self) -> RunId {
self.run_id
}
pub fn messages(&self) -> &[Message] {
&self.messages
}
pub fn trace_path(&self) -> Option<&Path> {
self.trace_path.as_deref()
}
}
#[derive(Clone)]
pub struct BuiltAgent {
inner: Arc<Inner>,
}
struct Inner {
persona: Persona,
io: SimpleIo,
limits: Limits,
store: Option<Arc<dyn CheckpointStore>>,
retries: u32,
laws: Laws,
trace: Option<Traced>,
#[cfg(feature = "knowledge")]
preamble: Option<troupekit_context::tools::KnowledgeKit>,
}
impl BuiltAgent {
pub(crate) fn new(
persona: Persona,
io: SimpleIo,
limits: Limits,
store: Option<Arc<dyn CheckpointStore>>,
retries: u32,
laws: Laws,
) -> Self {
BuiltAgent {
inner: Arc::new(Inner {
persona,
io,
limits,
store,
retries,
laws,
trace: None,
#[cfg(feature = "knowledge")]
preamble: None,
}),
}
}
pub(crate) fn with_trace(mut self, trace: Option<Traced>) -> Self {
let inner = Arc::get_mut(&mut self.inner).expect("a fresh BuiltAgent is not shared");
inner.trace = trace;
self
}
pub fn trace_path(&self) -> Option<&Path> {
path_of(&self.inner.trace)
}
async fn traced<T>(
&self,
run_id: Option<RunId>,
work: impl Future<Output = Result<T, KitError>>,
id_of: impl Fn(&T) -> RunId,
) -> Result<T, KitError> {
let owner = self.inner.persona.name.as_str();
let traced = self.inner.trace.as_ref();
root_span(traced, Trace::Agents, "agent.run", owner, run_id, work, id_of).await
}
#[cfg(feature = "knowledge")]
pub(crate) fn with_preamble(
mut self,
preamble: Option<troupekit_context::tools::KnowledgeKit>,
) -> Self {
let inner = Arc::get_mut(&mut self.inner).expect("a fresh BuiltAgent is not shared");
inner.preamble = preamble;
self
}
#[cfg(feature = "knowledge")]
async fn messages(&self, input: Input) -> Result<Vec<Message>, KitError> {
match &self.inner.preamble {
Some(kit) => crate::memory::prepend(kit, input.0).await,
None => Ok(input.0),
}
}
#[cfg(not(feature = "knowledge"))]
async fn messages(&self, input: Input) -> Result<Vec<Message>, KitError> {
Ok(input.0)
}
pub async fn run(&self, input: impl Into<Input>) -> Result<String, KitError> {
Ok(self.run_with(input).await?.text)
}
pub async fn run_with(&self, input: impl Into<Input>) -> Result<RunOutcome, KitError> {
let input = input.into();
self.traced(None, self.run_untraced(input), RunOutcome::run_id)
.await
}
async fn run_untraced(&self, input: Input) -> Result<RunOutcome, KitError> {
let inner = &self.inner;
let messages = self.messages(input).await?;
let run =
AgentRun::new(&inner.persona, messages, inner.limits.clone(), &inner.io).await?;
let store: Arc<dyn CheckpointStore> = match &inner.store {
Some(store) => store.clone(),
None => Arc::new(InMemCheckpoints::default()),
};
let agent = self.clone();
detached(run.run_id(), move |stop| async move {
let mut run = run;
agent.finish(&agent.inner.io, &mut run, store.as_ref(), &stop).await
})
.await
}
pub async fn resume(&self, run_id: RunId) -> Result<String, KitError> {
self.traced(Some(run_id), self.resume_untraced(run_id), |_| run_id)
.await
}
async fn resume_untraced(&self, run_id: RunId) -> Result<String, KitError> {
let name = self.inner.persona.name.as_str();
let Some(store) = &self.inner.store else {
return Err(KitError::config(
name,
"resume needs Storage::sqlite(..) or Storage::custom(..) checkpoints",
));
};
let Some(checkpoint) = store.latest(run_id).await? else {
return Err(KitError::config(
name,
format!("no checkpoint for run {run_id}"),
));
};
let mut run = AgentRun::from_checkpoint(&checkpoint)?;
if run.persona() != name {
return Err(KitError::config(
name,
format!(
"run {run_id} was started by agent `{}`; resume it with that agent",
run.persona()
),
));
}
let current = self.inner.limits.clone().with_budget(&self.inner.persona.budget);
run.tighten(¤t);
let agent = self.clone();
let store = store.clone();
let outcome = detached(run_id, move |stop| async move {
let mut run = run;
agent.finish(&agent.inner.io, &mut run, store.as_ref(), &stop).await
})
.await?;
Ok(outcome.text)
}
pub fn persona(&self) -> &Persona {
&self.inner.persona
}
pub fn laws(&self) -> &Laws {
&self.inner.laws
}
fn refuse_exhausted(&self, run: &AgentRun) -> Result<(), KitError> {
let retries = run.retries();
if retries <= self.inner.retries {
return Ok(());
}
assert!(retries > 0);
Err(KitError::Retries {
run_id: run.run_id(),
attempts: retries - 1,
last_error: "retries were used up by an earlier call".into(),
})
}
async fn finish(
&self,
io: &dyn AgentIo,
run: &mut AgentRun,
store: &dyn CheckpointStore,
cancel: &Cancel,
) -> Result<RunOutcome, KitError> {
match run.state().clone() {
RunState::Done { output } => return Ok(self.outcome(run, output)),
RunState::Failed { error } => {
return Err(KitError::failed(run.run_id(), error, run.host_failed()))
}
RunState::Paused { reason, .. } => {
return Err(KitError::Paused {
run_id: run.run_id(),
reason,
})
}
_ => {}
}
self.refuse_exhausted(run)?;
let saved_wait = retry_left(run, io.clock().now_ms());
if !saved_wait.is_zero() {
tokio::time::sleep(saved_wait).await;
}
run.set_retry_at_ms(None);
loop {
let step = drive_until(run, io, store, cancel)
.await
.map_err(|e| KitError::in_run(run.run_id(), e.into()))?;
let Some(step) = step else {
return Err(KitError::Cancelled {
run_id: run.run_id(),
});
};
match step {
StepOutcome::Done(output) => return Ok(self.outcome(run, output)),
StepOutcome::Retry {
error,
retry_after_ms,
} => {
assert!(run.retries() > 0);
let attempts = run.retries() - 1;
if attempts >= self.inner.retries {
return Err(KitError::Retries {
run_id: run.run_id(),
attempts,
last_error: error,
});
}
if cancel.sleep(retry_delay(attempts, retry_after_ms)).await {
return Err(KitError::Cancelled {
run_id: run.run_id(),
});
}
}
StepOutcome::Paused(reason) => {
return Err(KitError::Paused {
run_id: run.run_id(),
reason,
})
}
StepOutcome::Failed(reason) => {
return Err(KitError::failed(run.run_id(), reason, run.host_failed()))
}
StepOutcome::Continue => {
unreachable!("drive_until returns only a final, paused or retry outcome")
}
}
assert!(run.retries() <= self.inner.retries);
}
}
fn outcome(&self, run: &AgentRun, output: Value) -> RunOutcome {
let mut outcome = outcome(run, output);
outcome.trace_path = self.trace_path().map(Path::to_path_buf);
outcome
}
}
impl fmt::Debug for BuiltAgent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let inner = &self.inner;
f.debug_struct("BuiltAgent")
.field("name", &inner.persona.name)
.field("model", &inner.persona.model)
.field("tools", &inner.persona.tools)
.field("retries", &inner.retries)
.field("durable", &inner.store.is_some())
.field("laws", &inner.laws)
.finish_non_exhaustive()
}
}
fn outcome(run: &AgentRun, output: Value) -> RunOutcome {
let text = match &output {
Value::String(text) => text.clone(),
other => other.to_string(),
};
RunOutcome {
text,
output,
usage: run.usage(),
model_calls: run.model_calls(),
run_id: run.run_id(),
messages: run.messages().to_vec(),
trace_path: None,
}
}
async fn drive_until(
run: &mut AgentRun,
io: &dyn AgentIo,
store: &dyn CheckpointStore,
cancel: &Cancel,
) -> Result<Option<StepOutcome>, AgentError> {
if store.latest(run.run_id()).await?.is_none() {
store.save(run.checkpoint()).await?;
}
loop {
if cancel.is_set() {
return Ok(None);
}
let outcome = run.step(io).await;
store.save(run.checkpoint()).await?;
if cancel.is_set() {
return Ok(None);
}
if outcome != StepOutcome::Continue {
return Ok(Some(outcome));
}
}
}
fn retry_delay(attempt: u32, retry_after_ms: Option<u64>) -> Duration {
let backoff = BASE_RETRY_MS.saturating_mul(1u64 << attempt.min(16));
Duration::from_millis(retry_after_ms.unwrap_or(backoff).min(MAX_RETRY_MS))
}
fn note_retry(run: &mut AgentRun, step: &StepOutcome, now_ms: i64) -> Option<Duration> {
let StepOutcome::Retry { retry_after_ms, .. } = step else {
run.set_retry_at_ms(None);
return None;
};
assert!(run.retries() > 0, "a retry step is counted");
let wait = retry_delay(run.retries() - 1, *retry_after_ms);
let wait_ms = i64::try_from(wait.as_millis()).expect("a retry wait is capped");
run.set_retry_at_ms(Some(now_ms.saturating_add(wait_ms)));
Some(wait)
}
fn retry_left(run: &AgentRun, now_ms: i64) -> Duration {
let left = run
.retry_at_ms()
.map_or(0, |at_ms| at_ms.saturating_sub(now_ms))
.clamp(0, i64::try_from(MAX_RETRY_MS).expect("the cap fits"));
let left = Duration::from_millis(u64::try_from(left).expect("left is clamped to 0 or more"));
assert!(left <= Duration::from_millis(MAX_RETRY_MS));
left
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn retry_delay_backs_off_and_caps() {
assert_eq!(retry_delay(0, None), Duration::from_millis(500));
assert_eq!(retry_delay(2, None), Duration::from_millis(2000));
assert_eq!(retry_delay(20, None), Duration::from_millis(30_000));
assert_eq!(retry_delay(0, Some(7)), Duration::from_millis(7));
assert_eq!(retry_delay(0, Some(90_000)), Duration::from_millis(30_000));
}
}