use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::sync::Arc;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::agent::Resolution;
use crate::approval::CallEffects;
use crate::approval::SharedDeclines;
use crate::authority::Authority;
use crate::message::Image;
use crate::outcome::FinishOutcome;
use crate::provider::{ToolSpec, Usage};
use crate::state::{RunId, RunState};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceTrust {
Trusted,
#[default]
Untrusted,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolAnnotations {
pub read_only: bool,
pub destructive: bool,
pub idempotent: bool,
#[serde(default)]
pub egress: bool,
}
impl ToolAnnotations {
pub const READ_ONLY: Self = Self {
read_only: true,
destructive: false,
idempotent: true,
egress: false,
};
pub const WRITE: Self = Self {
read_only: false,
destructive: false,
idempotent: false,
egress: false,
};
pub const DESTRUCTIVE: Self = Self {
read_only: false,
destructive: true,
idempotent: false,
egress: true,
};
}
impl Default for ToolAnnotations {
fn default() -> Self {
Self::DESTRUCTIVE
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccessManifest {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub reads: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub writes: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hosts: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub commands: Vec<String>,
}
impl AccessManifest {
pub fn is_empty(&self) -> bool {
self.reads.is_empty()
&& self.writes.is_empty()
&& self.hosts.is_empty()
&& self.commands.is_empty()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolInfo {
pub annotations: ToolAnnotations,
pub access: AccessManifest,
pub effects: CallEffects,
pub outbound: Outbound,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Outbound {
#[default]
Nothing,
Exact(Vec<String>),
Composed,
}
#[derive(Clone, Default)]
pub struct Extensions {
values: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}
impl Extensions {
pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
self.values.insert(TypeId::of::<T>(), Arc::new(value));
}
pub fn get<T: 'static>(&self) -> Option<&T> {
self.values
.get(&TypeId::of::<T>())
.and_then(|value| value.downcast_ref::<T>())
}
}
impl fmt::Debug for Extensions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Extensions")
.field("len", &self.values.len())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ToolContext {
pub run_id: RunId,
pub session_id: String,
pub call_id: String,
pub turn: u32,
pub cancel: CancellationToken,
pub extensions: Extensions,
pub declines: Option<SharedDeclines>,
pub authority: Option<Authority>,
pub nested: Option<crate::NestedCalls>,
}
impl ToolContext {
pub fn new(session_id: impl Into<String>, call_id: impl Into<String>) -> Self {
Self {
run_id: RunId::new(),
session_id: session_id.into(),
call_id: call_id.into(),
turn: 0,
cancel: CancellationToken::new(),
extensions: Extensions::default(),
declines: None,
authority: None,
nested: None,
}
}
pub fn with_run(mut self, run_id: RunId, turn: u32) -> Self {
self.run_id = run_id;
self.turn = turn;
self
}
pub fn with_cancel(mut self, cancel: CancellationToken) -> Self {
self.cancel = cancel;
self
}
pub fn with_extensions(mut self, extensions: Extensions) -> Self {
self.extensions = extensions;
self
}
pub fn with_declines(mut self, declines: SharedDeclines) -> Self {
self.declines = Some(declines);
self
}
pub fn with_authority(mut self, authority: Option<Authority>) -> Self {
self.authority = authority;
self
}
pub fn with_nested(mut self, nested: Option<crate::NestedCalls>) -> Self {
self.nested = nested;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Finish {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reply: Option<String>,
pub outcome: FinishOutcome,
}
impl Finish {
pub fn new(outcome: FinishOutcome, reply: Option<String>) -> Self {
Self { reply, outcome }
}
pub fn succeeded(reply: impl Into<String>) -> Self {
Self::new(FinishOutcome::Succeeded, Some(reply.into()))
}
pub fn partial(reply: impl Into<String>) -> Self {
Self::new(FinishOutcome::Partial, Some(reply.into()))
}
pub fn blocked(reply: impl Into<String>) -> Self {
Self::new(FinishOutcome::Blocked, Some(reply.into()))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolOutput {
pub content: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub images: Vec<Image>,
pub is_error: bool,
#[serde(default, skip_serializing_if = "Value::is_null")]
pub details: Value,
#[serde(default)]
pub usage: Usage,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trust: Option<SourceTrust>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub finish: Option<Finish>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub suspended: Option<Box<RunState>>,
}
impl ToolOutput {
pub fn text(content: impl Into<String>) -> Self {
Self {
content: content.into(),
images: Vec::new(),
is_error: false,
details: Value::Null,
usage: Usage::default(),
trust: None,
finish: None,
suspended: None,
}
}
pub fn error(content: impl Into<String>) -> Self {
Self {
content: content.into(),
images: Vec::new(),
is_error: true,
details: Value::Null,
usage: Usage::default(),
trust: None,
finish: None,
suspended: None,
}
}
pub fn suspended(child: RunState) -> Self {
Self {
suspended: Some(Box::new(child)),
..Self::text("")
}
}
pub fn with_usage(mut self, usage: Usage) -> Self {
self.usage = usage;
self
}
pub fn with_images(mut self, images: impl IntoIterator<Item = Image>) -> Self {
self.images.extend(images);
self
}
pub fn with_details(mut self, details: Value) -> Self {
self.details = details;
self
}
pub fn with_trust(mut self, trust: SourceTrust) -> Self {
self.trust = Some(trust);
self
}
pub fn finish(mut self, finish: Finish) -> Self {
self.finish = Some(finish);
self
}
}
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[error("{0}")]
pub struct ToolError(pub String);
impl ToolError {
pub fn new(message: impl Into<String>) -> Self {
Self(message.into())
}
}
impl From<String> for ToolError {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for ToolError {
fn from(value: &str) -> Self {
Self(value.to_string())
}
}
impl From<std::io::Error> for ToolError {
fn from(value: std::io::Error) -> Self {
Self(value.to_string())
}
}
impl From<serde_json::Error> for ToolError {
fn from(value: serde_json::Error) -> Self {
Self(format!("invalid arguments: {value}"))
}
}
pub type ToolResult = Result<ToolOutput, ToolError>;
#[async_trait]
pub trait Tool: Send + Sync {
fn spec(&self) -> ToolSpec;
fn annotations(&self) -> ToolAnnotations {
ToolAnnotations::default()
}
fn annotations_for(&self, _arguments: &Value) -> ToolAnnotations {
self.annotations()
}
fn source_trust(&self, _arguments: &Value) -> SourceTrust {
SourceTrust::Untrusted
}
fn outbound(&self, _arguments: &Value) -> Outbound {
Outbound::Nothing
}
fn validate(&self, arguments: &Value) -> Result<(), String> {
check_arguments(&self.spec().parameters, arguments)
}
fn timeout(&self) -> Option<std::time::Duration> {
None
}
fn access(&self, _arguments: &Value) -> AccessManifest {
AccessManifest::default()
}
fn effects(&self, arguments: &Value) -> CallEffects {
let annotations = self.annotations_for(arguments);
if annotations.read_only && !annotations.egress {
CallEffects::none()
} else {
CallEffects::from_access(&self.access(arguments), annotations)
}
}
fn concurrent_peers(&self) -> usize {
0
}
fn suspends(&self) -> bool {
false
}
async fn resume_child(
&self,
_child: RunState,
_resolution: Resolution,
_ctx: &ToolContext,
) -> ToolResult {
Err(ToolError(format!(
"`{}` cannot continue a paused run",
self.spec().name
)))
}
async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult;
}
pub fn strip_reserved_arguments(map: &mut serde_json::Map<String, Value>) {
map.retain(|key, _| !key.starts_with('_'));
}
pub fn check_arguments(schema: &Value, arguments: &Value) -> Result<(), String> {
check_value(schema, arguments, "arguments", true)
}
pub fn check_argument_types(schema: &Value, arguments: &Value) -> Result<(), String> {
check_value(schema, arguments, "arguments", false)
}
fn check_value(schema: &Value, value: &Value, at: &str, required_keys: bool) -> Result<(), String> {
if let Some(types) = schema.get("type") {
let allowed: Vec<&str> = match types {
Value::String(one) => vec![one.as_str()],
Value::Array(many) => many.iter().filter_map(Value::as_str).collect(),
_ => Vec::new(),
};
if !allowed.is_empty() && !allowed.iter().any(|t| is_type(value, t)) {
return Err(if at == "arguments" && allowed == ["object"] {
"arguments must be a JSON object".to_string()
} else {
format!(
"`{at}` must be {}, not {}",
allowed.join(" or "),
kind(value)
)
});
}
}
if let Some(options) = schema.get("enum").and_then(Value::as_array)
&& !options.contains(value)
{
let listed: Vec<String> = options.iter().map(Value::to_string).collect();
return Err(format!("`{at}` must be one of {}", listed.join(", ")));
}
if let Value::Object(object) = value {
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let missing: Vec<&str> = required
.iter()
.filter(|_| required_keys)
.copied()
.filter(|key| object.get(*key).is_none_or(Value::is_null))
.filter(|key| {
!object.contains_key(*key)
|| !schema
.get("properties")
.and_then(|p| p.get(*key))
.is_some_and(allows_null)
})
.collect();
if !missing.is_empty() {
let prefix = if at == "arguments" {
String::new()
} else {
format!("`{at}`: ")
};
return Err(format!(
"{prefix}missing required argument(s): {}",
missing.join(", ")
));
}
if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
for (key, property) in properties {
let Some(item) = object.get(key) else {
continue;
};
if item.is_null() && !required.contains(&key.as_str()) {
continue;
}
let path = if at == "arguments" {
key.clone()
} else {
format!("{at}.{key}")
};
check_value(property, item, &path, required_keys)?;
}
}
}
if let (Value::Array(items), Some(item_schema)) = (value, schema.get("items"))
&& item_schema.is_object()
{
for (index, item) in items.iter().enumerate() {
check_value(item_schema, item, &format!("{at}[{index}]"), required_keys)?;
}
}
Ok(())
}
fn allows_null(schema: &Value) -> bool {
match schema.get("type") {
Some(Value::String(t)) => t == "null",
Some(Value::Array(ts)) => ts.iter().any(|t| t == "null"),
_ => true,
}
}
fn is_type(value: &Value, wanted: &str) -> bool {
match wanted {
"string" => value.is_string(),
"number" => value.is_number(),
"integer" => {
value.is_i64()
|| value.is_u64()
|| value
.as_f64()
.is_some_and(|n| n.fract() == 0.0 && n.is_finite())
}
"boolean" => value.is_boolean(),
"array" => value.is_array(),
"object" => value.is_object(),
"null" => value.is_null(),
_ => true,
}
}
fn kind(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "a boolean",
Value::Number(_) => "a number",
Value::String(_) => "a string",
Value::Array(_) => "an array",
Value::Object(_) => "an object",
}
}
pub struct FnTool<F, Fut> {
spec: ToolSpec,
annotations: ToolAnnotations,
trust: SourceTrust,
func: F,
_fut: PhantomData<fn() -> Fut>,
}
impl<F, Fut> FnTool<F, Fut>
where
F: Fn(Value) -> Fut + Send + Sync,
Fut: Future<Output = ToolResult> + Send,
{
pub fn new(spec: ToolSpec, annotations: ToolAnnotations, func: F) -> Self {
Self {
spec,
annotations,
trust: SourceTrust::default(),
func,
_fut: PhantomData,
}
}
pub fn with_trust(mut self, trust: SourceTrust) -> Self {
self.trust = trust;
self
}
}
#[async_trait]
impl<F, Fut> Tool for FnTool<F, Fut>
where
F: Fn(Value) -> Fut + Send + Sync,
Fut: Future<Output = ToolResult> + Send,
{
fn spec(&self) -> ToolSpec {
self.spec.clone()
}
fn annotations(&self) -> ToolAnnotations {
self.annotations
}
fn source_trust(&self, _arguments: &Value) -> SourceTrust {
self.trust
}
async fn call(&self, arguments: Value, _ctx: &ToolContext) -> ToolResult {
(self.func)(arguments).await
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SameToolStreak {
#[default]
Standard,
Versatile,
Stepwise,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn required_keys_are_checked() {
let schema = json!({"type": "object", "required": ["path", "text"]});
assert!(check_arguments(&schema, &json!({"path": "a", "text": "b"})).is_ok());
let err = check_arguments(&schema, &json!({"path": "a"})).unwrap_err();
assert!(err.contains("text"), "{err}");
assert!(check_arguments(&schema, &json!("not an object")).is_err());
}
#[test]
fn default_effects_of_a_read_only_egress_call_are_unknown() {
let tool = |annotations| {
FnTool::new(
ToolSpec {
name: "probe".into(),
description: "synthetic".into(),
parameters: json!({"type": "object"}),
},
annotations,
|_args: Value| async move { Ok(ToolOutput::text("ok")) },
)
};
let local_read = tool(ToolAnnotations::READ_ONLY);
assert_eq!(local_read.effects(&json!({})), CallEffects::none());
let remote_read = tool(ToolAnnotations {
egress: true,
..ToolAnnotations::READ_ONLY
});
assert_eq!(remote_read.effects(&json!({})), CallEffects::unknown());
}
#[test]
fn unannotated_tools_are_conservative() {
let ann = ToolAnnotations::default();
assert!(!ann.read_only);
assert!(ann.destructive);
}
}