troupekit-kit 0.4.0

Ergonomic API for the Troupekit LLM agent framework: one builder or one macro per agent, tool and graph.
Documentation
use crate::common::*;
use troupekit::Storage;

#[cfg(feature = "sqlite")]
#[tokio::test]
async fn sqlite_checkpoints_allow_resume() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("runs.db");
    let built = greeter()
        .checkpoints(Storage::sqlite(&path))
        .build()
        .await
        .unwrap();
    let first = built.run_with("I am Ada").await.unwrap();
    let again = built.resume(first.run_id()).await.unwrap();
    assert_eq!(again, "Hello! You said: I am Ada");
    let reopened = greeter()
        .checkpoints(Storage::sqlite(&path))
        .build()
        .await
        .unwrap();
    assert_eq!(
        reopened.resume(first.run_id()).await.unwrap(),
        "Hello! You said: I am Ada"
    );
    let unknown = reopened.resume(troupekit_core::ids::RunId::new()).await;
    assert!(matches!(unknown, Err(troupekit::KitError::Config { .. })));
}

#[tokio::test]
async fn memory_checkpoints_do_not_grow_across_runs() {
    let built = greeter()
        .checkpoints(Storage::memory())
        .build()
        .await
        .unwrap();
    let first = built.run_with("one").await.unwrap();
    built.run("two").await.unwrap();
    let err = built.resume(first.run_id()).await.unwrap_err();
    assert_eq!(
        err.to_string(),
        "agent `greeter`: resume needs Storage::sqlite(..) or Storage::custom(..) checkpoints"
    );
}

#[tokio::test]
async fn custom_store_keeps_runs_for_resume() {
    let store = std::sync::Arc::new(troupekit_core::inmem::InMemCheckpoints::default());
    let built = greeter()
        .checkpoints(Storage::custom(store))
        .build()
        .await
        .unwrap();
    let first = built.run_with("Ada").await.unwrap();
    for _ in 0..2 {
        assert_eq!(
            built.resume(first.run_id()).await.unwrap(),
            "Hello! You said: Ada"
        );
    }
}

#[cfg(feature = "sqlite")]
async fn exhausted_run(path: &std::path::Path, model: std::sync::Arc<troupekit_graph::testing::FnModel>) -> troupekit_core::ids::RunId {
    let err = greeter()
        .model_client(model)
        .retries(1)
        .checkpoints(Storage::sqlite(path))
        .run("hi")
        .await
        .unwrap_err();
    match err {
        troupekit::KitError::Retries { run_id, attempts, .. } => {
            assert_eq!(attempts, 1);
            run_id
        }
        other => panic!("expected Retries, got {other}"),
    }
}

#[cfg(feature = "sqlite")]
#[tokio::test]
async fn resume_keeps_the_retry_budget_of_the_run() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("runs.db");
    let model = failing_model(troupekit_core::error::ProviderErrorKind::Server);
    let run_id = exhausted_run(&path, model.clone()).await;
    assert_eq!(model.calls(), 2);
    let again = greeter()
        .model_client(model.clone())
        .retries(1)
        .checkpoints(Storage::sqlite(&path))
        .build()
        .await
        .unwrap();
    let err = again.resume(run_id).await.unwrap_err();
    assert!(matches!(err, troupekit::KitError::Retries { attempts: 1, .. }), "{err}");
    assert_eq!(model.calls(), 2, "an exhausted run makes no further model call");
}

#[cfg(feature = "sqlite")]
#[tokio::test]
async fn resume_refuses_a_run_of_another_agent() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("runs.db");
    let run_id = exhausted_run(&path, failing_model(troupekit_core::error::ProviderErrorKind::Server)).await;
    let other = troupekit::Agent::new("other")
        .instructions("Greet the user.")
        .model("fake/m")
        .model_client(echo_model())
        .retries(5)
        .checkpoints(Storage::sqlite(&path))
        .build()
        .await
        .unwrap();
    let err = other.resume(run_id).await.unwrap_err().to_string();
    assert!(err.contains("was started by agent `greeter`"), "{err}");
}

#[cfg(feature = "sqlite")]
#[tokio::test]
async fn resume_applies_the_stricter_current_limits() {
    use troupekit_core::store::UsageLedger;
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("runs.db");
    let model = troupekit_graph::testing::FnModel::new("fake/m", |_req| {
        Err(troupekit_core::error::ProviderError::new(troupekit_core::error::ProviderErrorKind::Server, "busy"))
    });
    let err = greeter()
        .model_client(std::sync::Arc::new(model))
        .retries(0)
        .checkpoints(Storage::sqlite(&path))
        .run("hi")
        .await
        .unwrap_err();
    let troupekit::KitError::Retries { run_id, .. } = err else {
        panic!("expected Retries, got {err}");
    };
    let ledger = std::sync::Arc::new(troupekit_agent::InMemoryLedger::default());
    let spent = troupekit_core::event::Usage { input_tokens: 0, output_tokens: 0, cost_usd_micros: 1_000 };
    ledger.record("user-1", spent).await.unwrap();
    let capped = troupekit_agent::Limits {
        user: Some(troupekit_agent::PeriodLimit { key: "user-1".into(), max_usd_micros: 10 }),
        ..Default::default()
    };
    let strict = greeter()
        .retries(5)
        .limits(capped)
        .ledger(ledger)
        .checkpoints(Storage::sqlite(&path))
        .build()
        .await
        .unwrap();
    let resumed = strict.resume(run_id).await;
    assert!(matches!(resumed, Err(troupekit::KitError::Paused { .. })), "{resumed:?}");
}