use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub use trusty_agents_common::ServiceTier;
pub use trusty_agents_common::runner::{HistoryMessage, RunContext};
use crate::tools::telemetry::ToolTelemetry;
#[derive(Debug)]
pub enum ToolResult {
Success {
text: String,
telemetry: Option<Box<ToolTelemetry>>,
},
Error { message: String, recoverable: bool },
}
impl ToolResult {
pub fn ok(s: impl Into<String>) -> Self {
ToolResult::Success {
text: s.into(),
telemetry: None,
}
}
pub fn with_telemetry(self, telemetry: ToolTelemetry) -> Self {
match self {
ToolResult::Success { text, .. } => ToolResult::Success {
text,
telemetry: Some(Box::new(telemetry)),
},
error => error,
}
}
pub fn telemetry(&self) -> Option<&ToolTelemetry> {
match self {
ToolResult::Success { telemetry, .. } => telemetry.as_deref(),
ToolResult::Error { .. } => None,
}
}
pub fn err(msg: impl Into<String>) -> Self {
ToolResult::Error {
message: msg.into(),
recoverable: true,
}
}
pub fn fatal(msg: impl Into<String>) -> Self {
ToolResult::Error {
message: msg.into(),
recoverable: false,
}
}
pub fn is_error(&self) -> bool {
matches!(self, ToolResult::Error { .. })
}
pub fn is_fatal(&self) -> bool {
matches!(
self,
ToolResult::Error {
recoverable: false,
..
}
)
}
pub fn content(&self) -> &str {
match self {
ToolResult::Success { text, .. } => text.as_str(),
ToolResult::Error { message, .. } => message.as_str(),
}
}
}
#[async_trait]
pub trait ToolExecutor: Send + Sync {
fn name(&self) -> &str;
fn schema(&self) -> Value;
async fn execute(&self, args: Value) -> ToolResult;
fn restricted_tiers(&self) -> &[ServiceTier] {
&[]
}
}
#[derive(Debug, Clone)]
pub struct AgentOutput {
pub content: String,
pub summary: Option<String>,
pub usage: crate::perf::TokenUsage,
pub finish_status: Option<crate::tools::finish_task::FinishStatus>,
}
impl AgentOutput {
pub fn from_content(content: impl Into<String>) -> Self {
Self {
content: content.into(),
summary: None,
usage: crate::perf::TokenUsage::default(),
finish_status: None,
}
}
pub fn summary_or_content(&self) -> &str {
self.summary.as_deref().unwrap_or(&self.content)
}
}
#[async_trait]
pub trait AgentRunner: Send + Sync {
async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput>;
async fn run_with_context(
&self,
agent_name: &str,
task: &str,
_ctx: &RunContext,
) -> Result<AgentOutput> {
self.run(agent_name, task).await
}
async fn run_with_history(
&self,
agent_name: &str,
task: &str,
_history: &[HistoryMessage],
ctx: &RunContext,
) -> Result<AgentOutput> {
self.run_with_context(agent_name, task, ctx).await
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
pub title: String,
pub url: String,
pub snippet: String,
}
#[async_trait]
pub trait SearchProvider: Send + Sync {
async fn search(&self, query: &str, n: usize) -> Result<Vec<SearchResult>>;
}
pub trait SkillResolver: Send + Sync {
fn resolve(&self, name: &str) -> Option<String>;
fn list(&self) -> Vec<String>;
fn metadata(&self) -> Vec<crate::skills::SkillMetadata>;
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use anyhow::Result;
use async_trait::async_trait;
use super::*;
use crate::perf::TokenUsage;
struct CtxCapture {
captured: Arc<Mutex<Vec<RunContext>>>,
}
#[async_trait]
impl AgentRunner for CtxCapture {
async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
Ok(AgentOutput::from_content("run"))
}
async fn run_with_context(
&self,
_agent_name: &str,
_task: &str,
ctx: &RunContext,
) -> Result<AgentOutput> {
self.captured
.lock()
.expect("lock poisoned")
.push(ctx.clone());
Ok(AgentOutput::from_content("run_with_context"))
}
}
#[tokio::test]
async fn test_run_with_history_forwards_ctx() {
let captured = Arc::new(Mutex::new(Vec::new()));
let runner = CtxCapture {
captured: captured.clone(),
};
let ctx = RunContext {
working_dir: Some(PathBuf::from("/tmp/test-wd")),
model: Some("anthropic/claude-opus-4-5".to_string()),
max_turns_override: Some(5),
assigned_file: None,
};
let out = runner
.run_with_history("test-agent", "do something", &[], &ctx)
.await
.expect("run_with_history should succeed");
assert_eq!(
out.content, "run_with_context",
"default run_with_history must call run_with_context, not run()"
);
let snaps = captured.lock().expect("lock poisoned");
assert_eq!(
snaps.len(),
1,
"run_with_context must be called exactly once"
);
let recorded = &snaps[0];
assert_eq!(
recorded.working_dir,
Some(PathBuf::from("/tmp/test-wd")),
"working_dir must be forwarded"
);
assert_eq!(
recorded.model,
Some("anthropic/claude-opus-4-5".to_string()),
"model must be forwarded"
);
assert_eq!(
recorded.max_turns_override,
Some(5),
"max_turns_override must be forwarded"
);
}
#[test]
fn tool_result_predicates() {
let ok = ToolResult::ok("hello");
assert!(!ok.is_error());
assert!(!ok.is_fatal());
assert_eq!(ok.content(), "hello");
let err = ToolResult::err("oops");
assert!(err.is_error());
assert!(!err.is_fatal());
assert_eq!(err.content(), "oops");
let fatal = ToolResult::fatal("crash");
assert!(fatal.is_error());
assert!(fatal.is_fatal());
assert_eq!(fatal.content(), "crash");
}
#[test]
fn tool_result_carries_optional_telemetry() {
use crate::tools::telemetry::{SearchTelemetry, ToolTelemetry};
assert!(
ToolResult::ok("plain").telemetry().is_none(),
"tools that report nothing structured must stay unaffected"
);
let telemetry = ToolTelemetry::Search(SearchTelemetry {
lane: "semantic".to_string(),
query: "q".to_string(),
hit_count: Some(3),
hits: vec![],
latency_ms: 7,
});
let result = ToolResult::ok("hits").with_telemetry(telemetry.clone());
assert_eq!(result.telemetry(), Some(&telemetry));
assert_eq!(result.content(), "hits", "the text must be untouched");
}
#[test]
fn with_telemetry_is_a_no_op_on_error() {
use crate::tools::telemetry::{SearchTelemetry, ToolTelemetry};
let result =
ToolResult::err("boom").with_telemetry(ToolTelemetry::Search(SearchTelemetry {
lane: "semantic".to_string(),
query: "q".to_string(),
hit_count: None,
hits: vec![],
latency_ms: 1,
}));
assert!(result.is_error());
assert!(result.telemetry().is_none());
assert_eq!(result.content(), "boom");
}
#[test]
fn agent_output_summary_or_content_fallback() {
let with_summary = AgentOutput {
content: "full content".into(),
summary: Some("short summary".into()),
usage: TokenUsage::default(),
finish_status: None,
};
assert_eq!(with_summary.summary_or_content(), "short summary");
let no_summary = AgentOutput::from_content("just content");
assert_eq!(no_summary.summary_or_content(), "just content");
}
}