use std::collections::{BTreeSet, HashMap};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use dashmap::DashMap;
use serde_json::json;
use crate::config::{GuardrailRef, LlmProviderRef, ToolRef};
use crate::tenant::TenantContext;
const CATALOG_TTL: Duration = Duration::from_secs(5 * 60);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlaybookLlmTier {
Fast,
Balanced,
Reasoning,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum PlaybookLlmCapability {
ToolCalling,
StructuredOutput,
Vision,
LongContext,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlaybookLlmRequirement {
pub tier: PlaybookLlmTier,
pub requires: Vec<PlaybookLlmCapability>,
}
impl Default for PlaybookLlmRequirement {
fn default() -> Self {
Self {
tier: PlaybookLlmTier::Balanced,
requires: Vec::new(),
}
}
}
#[derive(Clone, Debug)]
pub struct PlaybookOperation {
pub playbook_id: String,
pub description: String,
pub parameters: serde_json::Value,
pub instructions: String,
pub llm: PlaybookLlmRequirement,
pub allow_list: Vec<ToolRef>,
pub guardrails: Vec<GuardrailRef>,
}
#[derive(Clone, Debug)]
pub struct PlaybookToolEntry {
pub description: String,
pub parameters: serde_json::Value,
pub instructions: String,
pub llm: PlaybookLlmRequirement,
pub tools: Vec<ToolRef>,
pub guardrails: Vec<GuardrailRef>,
}
pub trait PlaybookSource: Send + Sync {
fn list_playbooks(&self) -> Vec<PlaybookOperation>;
}
#[derive(Clone, Debug)]
pub struct PlaybookTurnRequest {
pub tenant: TenantContext,
pub playbook_id: String,
pub instructions: String,
pub llm: PlaybookLlmRequirement,
pub tools: Vec<ToolRef>,
pub guardrails: Vec<GuardrailRef>,
pub caller_llm: LlmProviderRef,
pub input: serde_json::Value,
}
#[derive(Clone, Debug)]
pub struct PlaybookTurnResult {
pub reply: String,
}
pub type PlaybookTurnFn = Arc<
dyn Fn(
PlaybookTurnRequest,
)
-> Pin<Box<dyn Future<Output = Result<PlaybookTurnResult, String>> + Send + 'static>>
+ Send
+ Sync,
>;
pub struct PlaybookToolCatalog {
tools: HashMap<String, PlaybookToolEntry>,
turn: PlaybookTurnFn,
caller_llm: LlmProviderRef,
tenant: TenantContext,
fetched_at: Instant,
}
impl PlaybookToolCatalog {
pub fn from_source(
source: &dyn PlaybookSource,
turn: PlaybookTurnFn,
caller_tools: &[ToolRef],
caller_llm: LlmProviderRef,
tenant: TenantContext,
) -> Self {
let held: BTreeSet<(&str, &str)> = caller_tools
.iter()
.map(|t| (t.extension_id.as_str(), t.tool_name.as_str()))
.collect();
let mut tools = HashMap::new();
for op in source.list_playbooks() {
let narrowed: Vec<ToolRef> = op
.allow_list
.iter()
.filter(|t| held.contains(&(t.extension_id.as_str(), t.tool_name.as_str())))
.cloned()
.collect();
if narrowed.len() != op.allow_list.len() {
tracing::warn!(
playbook = %op.playbook_id,
declared = op.allow_list.len(),
callable = narrowed.len(),
"playbook binds tools the calling worker does not hold; they are not granted"
);
}
tools.insert(
op.playbook_id,
PlaybookToolEntry {
description: op.description,
parameters: op.parameters,
instructions: op.instructions,
llm: op.llm,
tools: narrowed,
guardrails: op.guardrails,
},
);
}
Self {
tools,
turn,
caller_llm,
tenant,
fetched_at: Instant::now(),
}
}
pub fn tools(&self) -> impl Iterator<Item = (&String, &PlaybookToolEntry)> {
self.tools.iter()
}
pub fn len(&self) -> usize {
self.tools.len()
}
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
pub fn tool_entry(&self, playbook_id: &str) -> Option<&PlaybookToolEntry> {
self.tools.get(playbook_id)
}
pub async fn dispatch(&self, playbook_id: &str, args_json: &str) -> serde_json::Value {
let Some(entry) = self.tool_entry(playbook_id) else {
return json!({ "error": format!("unknown playbook tool '{playbook_id}'") });
};
let input: serde_json::Value = match serde_json::from_str(args_json) {
Ok(v) => v,
Err(e) => {
return json!({
"error": format!("invalid JSON args for playbook '{playbook_id}': {e}")
});
}
};
let request = PlaybookTurnRequest {
tenant: self.tenant.clone(),
playbook_id: playbook_id.to_string(),
instructions: entry.instructions.clone(),
llm: entry.llm.clone(),
tools: entry.tools.clone(),
guardrails: entry.guardrails.clone(),
caller_llm: self.caller_llm.clone(),
input,
};
match (self.turn)(request).await {
Ok(result) => json!({ "reply": result.reply }),
Err(e) => json!({ "error": e }),
}
}
}
pub struct PlaybookToolSource {
source: Arc<dyn PlaybookSource>,
turn: PlaybookTurnFn,
cache: DashMap<String, Arc<PlaybookToolCatalog>>,
}
impl PlaybookToolSource {
pub fn new(source: Arc<dyn PlaybookSource>, turn: PlaybookTurnFn) -> Self {
Self {
source,
turn,
cache: DashMap::new(),
}
}
fn cache_key(
tenant: &TenantContext,
caller_tools: &[ToolRef],
caller_llm: &LlmProviderRef,
) -> String {
let held: BTreeSet<String> = caller_tools
.iter()
.map(|t| format!("{}/{}", t.extension_id, t.tool_name))
.collect();
format!(
"{}:{}:{}/{}:{}",
tenant.tenant_id,
tenant.env_id,
caller_llm.provider,
caller_llm.model,
held.into_iter().collect::<Vec<_>>().join(",")
)
}
pub async fn catalog(
&self,
tenant: &TenantContext,
caller_tools: &[ToolRef],
caller_llm: &LlmProviderRef,
) -> Arc<PlaybookToolCatalog> {
let key = Self::cache_key(tenant, caller_tools, caller_llm);
if let Some(entry) = self.cache.get(&key) {
let snap = entry.value();
if snap.fetched_at.elapsed() < CATALOG_TTL {
return snap.clone();
}
}
let built = Arc::new(PlaybookToolCatalog::from_source(
self.source.as_ref(),
self.turn.clone(),
caller_tools,
caller_llm.clone(),
tenant.clone(),
));
self.cache.insert(key, built.clone());
built
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
fn caller_llm() -> LlmProviderRef {
LlmProviderRef {
provider: "openai".into(),
model: "gpt-4o-mini".into(),
credential_ref: None,
}
}
fn tool(ext: &str, name: &str) -> ToolRef {
ToolRef {
extension_id: ext.to_string(),
tool_name: name.to_string(),
description: None,
input_schema: None,
usage_note: None,
}
}
struct FakeSource;
impl PlaybookSource for FakeSource {
fn list_playbooks(&self) -> Vec<PlaybookOperation> {
vec![PlaybookOperation {
playbook_id: "refund".into(),
description: "Issue a refund".into(),
parameters: json!({ "type": "object" }),
instructions: "Follow the refund policy.".into(),
llm: PlaybookLlmRequirement {
tier: PlaybookLlmTier::Reasoning,
requires: vec![PlaybookLlmCapability::ToolCalling],
},
allow_list: vec![
tool("greentic.billing", "refund"),
tool("greentic.crm", "note"),
],
guardrails: vec![],
}]
}
}
fn recording_turn() -> (
PlaybookTurnFn,
Arc<std::sync::Mutex<Vec<PlaybookTurnRequest>>>,
) {
let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = seen.clone();
let turn: PlaybookTurnFn = Arc::new(move |req: PlaybookTurnRequest| {
let sink = sink.clone();
Box::pin(async move {
sink.lock().expect("lock").push(req);
Ok(PlaybookTurnResult {
reply: "done".into(),
})
})
});
(turn, seen)
}
fn failing_turn(message: &'static str) -> PlaybookTurnFn {
Arc::new(move |_req| Box::pin(async move { Err(message.to_string()) }))
}
#[tokio::test]
async fn catalog_lists_and_runs_a_playbook() {
let (turn, _) = recording_turn();
let cat = PlaybookToolCatalog::from_source(
&FakeSource,
turn,
&[
tool("greentic.billing", "refund"),
tool("greentic.crm", "note"),
],
caller_llm(),
TenantContext::new("acme", "prod"),
);
assert_eq!(cat.len(), 1);
let entry = cat.tool_entry("refund").expect("entry");
assert_eq!(entry.description, "Issue a refund");
assert_eq!(entry.llm.tier, PlaybookLlmTier::Reasoning);
let out = cat.dispatch("refund", "{\"order\":7}").await;
assert_eq!(out["reply"], "done");
}
#[tokio::test]
async fn the_turn_receives_the_playbooks_instructions_and_arguments() {
let (turn, seen) = recording_turn();
let cat = PlaybookToolCatalog::from_source(
&FakeSource,
turn,
&[
tool("greentic.billing", "refund"),
tool("greentic.crm", "note"),
],
caller_llm(),
TenantContext::new("acme", "prod"),
);
cat.dispatch("refund", "{\"order\":7}").await;
let calls = seen.lock().expect("lock");
let req = calls.first().expect("one turn");
assert_eq!(req.instructions, "Follow the refund policy.");
assert_eq!(req.input["order"], 7);
}
#[tokio::test]
async fn a_tool_the_caller_does_not_hold_is_not_granted() {
let (turn, seen) = recording_turn();
let cat = PlaybookToolCatalog::from_source(
&FakeSource,
turn,
&[tool("greentic.billing", "refund")],
caller_llm(),
TenantContext::new("acme", "prod"),
);
let entry = cat.tool_entry("refund").expect("entry");
assert_eq!(
entry.tools,
vec![tool("greentic.billing", "refund")],
"the unheld tool must be dropped, never granted"
);
cat.dispatch("refund", "{}").await;
let calls = seen.lock().expect("lock");
assert_eq!(
calls.first().expect("one turn").tools.len(),
1,
"the turn must run with the narrowed set"
);
}
#[tokio::test]
async fn a_callers_other_tools_do_not_reach_the_playbook() {
let (turn, _) = recording_turn();
let cat = PlaybookToolCatalog::from_source(
&FakeSource,
turn,
&[
tool("greentic.billing", "refund"),
tool("greentic.crm", "note"),
tool("greentic.payroll", "pay"),
],
caller_llm(),
TenantContext::new("acme", "prod"),
);
let entry = cat.tool_entry("refund").expect("entry");
assert_eq!(entry.tools.len(), 2, "union would have given three");
assert!(
!entry
.tools
.iter()
.any(|t| t.extension_id == "greentic.payroll"),
"a tool the document does not bind must not reach the turn"
);
}
#[tokio::test]
async fn dispatch_unknown_playbook_returns_an_error_value_not_err() {
let (turn, _) = recording_turn();
let cat = PlaybookToolCatalog::from_source(
&FakeSource,
turn,
&[],
caller_llm(),
TenantContext::new("acme", "prod"),
);
let out = cat.dispatch("no_such_playbook", "{}").await;
assert!(out.get("error").is_some(), "must yield an error value");
assert!(
out["error"]
.as_str()
.unwrap_or("")
.contains("no_such_playbook"),
"the error must name the playbook, got: {out}"
);
}
#[tokio::test]
async fn unreadable_arguments_are_an_error_value_and_no_turn_runs() {
let (turn, seen) = recording_turn();
let cat = PlaybookToolCatalog::from_source(
&FakeSource,
turn,
&[],
caller_llm(),
TenantContext::new("acme", "prod"),
);
let out = cat.dispatch("refund", "not json").await;
assert!(out.get("error").is_some());
assert!(
seen.lock().expect("lock").is_empty(),
"a turn must not run on arguments that could not be read"
);
}
#[tokio::test]
async fn a_failed_turn_is_an_error_value_not_err() {
let cat = PlaybookToolCatalog::from_source(
&FakeSource,
failing_turn("no provider satisfies tier reasoning"),
&[],
caller_llm(),
TenantContext::new("acme", "prod"),
);
let out = cat.dispatch("refund", "{}").await;
assert_eq!(out["error"], "no provider satisfies tier reasoning");
}
#[tokio::test]
async fn an_empty_source_yields_an_empty_catalog() {
struct Empty;
impl PlaybookSource for Empty {
fn list_playbooks(&self) -> Vec<PlaybookOperation> {
Vec::new()
}
}
let (turn, _) = recording_turn();
let cat = PlaybookToolCatalog::from_source(
&Empty,
turn,
&[],
caller_llm(),
TenantContext::new("acme", "prod"),
);
assert!(cat.is_empty());
}
#[tokio::test]
async fn source_caches_within_ttl_for_the_same_caller() {
let (turn, _) = recording_turn();
let source = PlaybookToolSource::new(Arc::new(FakeSource), turn);
let tenant = TenantContext::new("acme", "prod");
let held = [tool("greentic.billing", "refund")];
let first = source.catalog(&tenant, &held, &caller_llm()).await;
let second = source.catalog(&tenant, &held, &caller_llm()).await;
assert!(
Arc::ptr_eq(&first, &second),
"second call must hit the cache"
);
}
#[tokio::test]
async fn two_callers_with_different_tools_get_different_catalogs() {
let (turn, _) = recording_turn();
let source = PlaybookToolSource::new(Arc::new(FakeSource), turn);
let tenant = TenantContext::new("acme", "prod");
let narrow = source
.catalog(
&tenant,
&[tool("greentic.billing", "refund")],
&caller_llm(),
)
.await;
let wide = source
.catalog(
&tenant,
&[
tool("greentic.billing", "refund"),
tool("greentic.crm", "note"),
],
&caller_llm(),
)
.await;
assert!(
!Arc::ptr_eq(&narrow, &wide),
"one worker must not inherit another's narrowing"
);
assert_eq!(narrow.tool_entry("refund").expect("entry").tools.len(), 1);
assert_eq!(wide.tool_entry("refund").expect("entry").tools.len(), 2);
}
#[tokio::test]
async fn the_cache_key_ignores_the_order_of_the_callers_tools() {
let (turn, _) = recording_turn();
let source = PlaybookToolSource::new(Arc::new(FakeSource), turn);
let tenant = TenantContext::new("acme", "prod");
let one = source
.catalog(
&tenant,
&[
tool("greentic.billing", "refund"),
tool("greentic.crm", "note"),
],
&caller_llm(),
)
.await;
let other = source
.catalog(
&tenant,
&[
tool("greentic.crm", "note"),
tool("greentic.billing", "refund"),
],
&caller_llm(),
)
.await;
assert!(
Arc::ptr_eq(&one, &other),
"two spellings of one set must share an entry"
);
}
#[tokio::test]
async fn a_different_env_does_not_share_a_catalog() {
let (turn, _) = recording_turn();
let source = PlaybookToolSource::new(Arc::new(FakeSource), turn);
let prod = source
.catalog(&TenantContext::new("acme", "prod"), &[], &caller_llm())
.await;
let staging = source
.catalog(&TenantContext::new("acme", "staging"), &[], &caller_llm())
.await;
assert!(!Arc::ptr_eq(&prod, &staging));
}
}