use std::{
error::Error as StdError,
fmt,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de, de::DeserializeOwned};
use thiserror::Error;
use crate::{
ArtifactRef, AttemptId, BoundedJson, BudgetRemaining, ByteCount, CancellationSignal,
CapabilityIdentity, CapabilityReference, Digest, DurationMillis, EventId, ExecutionCount,
Failure, FailureCategory, FailureCode, FailureId, FailureMessage, FailureOrigin, InvocationId,
JsonLimits, PrincipalIdentity, RetryAdvice, RunId, SchemaReference, TenantId, ThreadId,
Timestamp, ToolDescriptor, ToolExecutionLimits, ToolIdempotency, ToolRisk,
};
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ToolIdempotencyKey(InvocationId);
impl ToolIdempotencyKey {
#[must_use]
pub const fn from_invocation_id(invocation_id: InvocationId) -> Self {
Self(invocation_id)
}
#[must_use]
pub const fn invocation_id(self) -> InvocationId {
self.0
}
}
impl fmt::Display for ToolIdempotencyKey {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, formatter)
}
}
impl fmt::Debug for ToolIdempotencyKey {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("ToolIdempotencyKey([REDACTED])")
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct ToolRecoveryHandle {
namespace: FailureOrigin,
binding: Digest,
opaque_id: Box<str>,
}
impl ToolRecoveryHandle {
pub const MAX_OPAQUE_ID_BYTES: usize = 1024;
pub fn new(
namespace: FailureOrigin,
binding: Digest,
opaque_id: impl Into<String>,
) -> Result<Self, ToolRecoveryHandleError> {
let opaque_id = opaque_id.into();
validate_recovery_opaque_id(&opaque_id)?;
Ok(Self {
namespace,
binding,
opaque_id: opaque_id.into_boxed_str(),
})
}
#[must_use]
pub const fn namespace(&self) -> &FailureOrigin {
&self.namespace
}
#[must_use]
pub const fn binding(&self) -> Digest {
self.binding
}
#[must_use]
pub fn opaque_id(&self) -> &str {
&self.opaque_id
}
}
fn validate_recovery_opaque_id(value: &str) -> Result<(), ToolRecoveryHandleError> {
if value.is_empty() {
return Err(ToolRecoveryHandleError::EmptyOpaqueId);
}
if value.len() > ToolRecoveryHandle::MAX_OPAQUE_ID_BYTES {
return Err(ToolRecoveryHandleError::OpaqueIdTooLong {
maximum: ToolRecoveryHandle::MAX_OPAQUE_ID_BYTES,
actual: value.len(),
});
}
if value.chars().next().is_some_and(char::is_whitespace)
|| value.chars().next_back().is_some_and(char::is_whitespace)
{
return Err(ToolRecoveryHandleError::OpaqueIdBoundaryWhitespace);
}
if value.chars().any(|scalar| {
let code_point = scalar as u32;
scalar.is_control()
|| (0xfdd0..=0xfdef).contains(&code_point)
|| code_point & 0xfffe == 0xfffe
}) {
return Err(ToolRecoveryHandleError::OpaqueIdDisallowedCodePoint);
}
Ok(())
}
impl fmt::Debug for ToolRecoveryHandle {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolRecoveryHandle")
.field("namespace", &self.namespace)
.field("binding", &self.binding)
.field("opaque_id_bytes", &self.opaque_id.len())
.finish_non_exhaustive()
}
}
#[derive(Deserialize, JsonSchema, Serialize)]
#[serde(deny_unknown_fields)]
struct ToolRecoveryHandleWire {
namespace: FailureOrigin,
binding: Digest,
opaque_id: String,
}
impl Serialize for ToolRecoveryHandle {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
ToolRecoveryHandleWire {
namespace: self.namespace.clone(),
binding: self.binding,
opaque_id: self.opaque_id.to_string(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ToolRecoveryHandle {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let wire = ToolRecoveryHandleWire::deserialize(deserializer)?;
Self::new(wire.namespace, wire.binding, wire.opaque_id).map_err(de::Error::custom)
}
}
impl JsonSchema for ToolRecoveryHandle {
fn schema_name() -> std::borrow::Cow<'static, str> {
"ToolRecoveryHandle".into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
concat!(module_path!(), "::ToolRecoveryHandle").into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
ToolRecoveryHandleWire::json_schema(generator)
}
}
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolRecoveryHandleError {
#[error("tool recovery opaque identifier must not be empty")]
EmptyOpaqueId,
#[error("tool recovery opaque identifier is {actual} bytes; maximum is {maximum}")]
OpaqueIdTooLong {
maximum: usize,
actual: usize,
},
#[error("tool recovery opaque identifier must not have boundary whitespace")]
OpaqueIdBoundaryWhitespace,
#[error("tool recovery opaque identifier contains a disallowed code point")]
OpaqueIdDisallowedCodePoint,
}
#[derive(Clone)]
pub struct ToolReconciliationContext {
tenant_id: TenantId,
run_id: RunId,
thread_id: ThreadId,
invocation_id: InvocationId,
attempt_id: AttemptId,
tool: CapabilityIdentity,
idempotency: ToolIdempotency,
idempotency_key: Option<ToolIdempotencyKey>,
observed_at: Timestamp,
deadline: Timestamp,
deadline_instant: Instant,
effective_timeout: DurationMillis,
cancellation: CancellationSignal,
origin_event_id: Option<EventId>,
recovery_handle: Option<ToolRecoveryHandle>,
max_inline_result_bytes: ByteCount,
max_artifacts: ExecutionCount,
max_total_artifact_bytes: ByteCount,
}
impl ToolReconciliationContext {
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: TenantId,
run_id: RunId,
thread_id: ThreadId,
invocation_id: InvocationId,
attempt_id: AttemptId,
descriptor: &ToolDescriptor,
effective_timeout: DurationMillis,
observed_at: Timestamp,
observed_instant: Instant,
run_deadline: Timestamp,
cancellation: CancellationSignal,
) -> Result<Self, ToolReconciliationContextError> {
if !descriptor.semantics().supports_status_query() {
return Err(ToolReconciliationContextError::StatusQueryUnsupported);
}
if effective_timeout == DurationMillis::ZERO {
return Err(ToolReconciliationContextError::ZeroEffectiveTimeout);
}
let descriptor_timeout = descriptor.limits().timeout();
if effective_timeout > descriptor_timeout {
return Err(ToolReconciliationContextError::TimeoutExceedsDescriptor {
descriptor: descriptor_timeout,
actual: effective_timeout,
});
}
let run_remaining_micros = i128::from(run_deadline.unix_micros())
.checked_sub(i128::from(observed_at.unix_micros()))
.expect("subtracting two i64 timestamps cannot overflow i128");
if run_remaining_micros <= 0 {
return Err(ToolReconciliationContextError::DeadlineReached {
deadline: run_deadline,
observed_at,
});
}
let timeout_micros = i128::from(effective_timeout.as_i64()) * 1_000;
let remaining_micros = run_remaining_micros.min(timeout_micros);
let deadline_micros = i128::from(observed_at.unix_micros()) + remaining_micros;
let deadline_micros = i64::try_from(deadline_micros)
.expect("a reconciliation deadline bounded by a valid run deadline fits i64");
let deadline = Timestamp::from_unix_micros(deadline_micros)
.expect("a reconciliation deadline bounded by a valid run deadline is valid");
let remaining_micros = u64::try_from(remaining_micros)
.expect("a positive supported timestamp distance fits u64 microseconds");
let remaining = Duration::from_micros(remaining_micros);
let deadline_instant = observed_instant
.checked_add(remaining)
.ok_or(ToolReconciliationContextError::MonotonicDeadlineOutOfRange { remaining })?;
let idempotency = descriptor.semantics().idempotency();
let idempotency_key = descriptor
.semantics()
.requires_idempotency_key()
.then_some(ToolIdempotencyKey::from_invocation_id(invocation_id));
Ok(Self {
tenant_id,
run_id,
thread_id,
invocation_id,
attempt_id,
tool: descriptor.metadata().identity().clone(),
idempotency,
idempotency_key,
observed_at,
deadline,
deadline_instant,
effective_timeout,
cancellation,
origin_event_id: None,
recovery_handle: None,
max_inline_result_bytes: descriptor.limits().max_inline_result_bytes(),
max_artifacts: descriptor.limits().max_artifacts(),
max_total_artifact_bytes: descriptor.limits().max_total_artifact_bytes(),
})
}
#[must_use]
pub fn narrow_artifact_limits(mut self, limits: &ToolExecutionLimits) -> Self {
self.max_inline_result_bytes = self
.max_inline_result_bytes
.min(limits.max_inline_result_bytes());
self.max_artifacts = self.max_artifacts.min(limits.max_artifacts());
self.max_total_artifact_bytes = self
.max_total_artifact_bytes
.min(limits.max_total_artifact_bytes());
self
}
#[must_use]
pub fn with_durable_recovery(
mut self,
origin_event_id: EventId,
recovery_handle: Option<ToolRecoveryHandle>,
) -> Self {
self.origin_event_id = Some(origin_event_id);
self.recovery_handle = recovery_handle;
self
}
#[must_use]
pub const fn tenant_id(&self) -> &TenantId {
&self.tenant_id
}
#[must_use]
pub const fn run_id(&self) -> RunId {
self.run_id
}
#[must_use]
pub const fn thread_id(&self) -> ThreadId {
self.thread_id
}
#[must_use]
pub const fn invocation_id(&self) -> InvocationId {
self.invocation_id
}
#[must_use]
pub const fn attempt_id(&self) -> AttemptId {
self.attempt_id
}
#[must_use]
pub const fn tool(&self) -> &CapabilityIdentity {
&self.tool
}
#[must_use]
pub const fn idempotency(&self) -> ToolIdempotency {
self.idempotency
}
#[must_use]
pub const fn idempotency_key(&self) -> Option<ToolIdempotencyKey> {
self.idempotency_key
}
#[must_use]
pub const fn observed_at(&self) -> Timestamp {
self.observed_at
}
#[must_use]
pub const fn deadline(&self) -> Timestamp {
self.deadline
}
#[must_use]
pub const fn deadline_instant(&self) -> Instant {
self.deadline_instant
}
#[must_use]
pub const fn effective_timeout(&self) -> DurationMillis {
self.effective_timeout
}
#[must_use]
pub const fn cancellation(&self) -> &CancellationSignal {
&self.cancellation
}
#[must_use]
pub const fn origin_event_id(&self) -> Option<EventId> {
self.origin_event_id
}
#[must_use]
pub const fn recovery_handle(&self) -> Option<&ToolRecoveryHandle> {
self.recovery_handle.as_ref()
}
#[must_use]
pub const fn max_artifacts(&self) -> ExecutionCount {
self.max_artifacts
}
#[must_use]
pub const fn max_inline_result_bytes(&self) -> ByteCount {
self.max_inline_result_bytes
}
#[must_use]
pub const fn max_total_artifact_bytes(&self) -> ByteCount {
self.max_total_artifact_bytes
}
#[must_use]
pub fn stop_reason_at(&self, observed_instant: Instant) -> Option<ToolStopReason> {
if self.cancellation.is_cancelled() {
Some(ToolStopReason::Cancelled)
} else if self
.deadline_instant
.checked_duration_since(observed_instant)
.filter(|remaining| !remaining.is_zero())
.is_none()
{
Some(ToolStopReason::DeadlineExceeded)
} else {
None
}
}
pub fn validate_for(
&self,
descriptor: &ToolDescriptor,
) -> Result<(), ToolReconciliationContextBindingError> {
if !descriptor.semantics().supports_status_query() {
return Err(ToolReconciliationContextBindingError::StatusQueryUnsupported);
}
let expected_tool = descriptor.metadata().identity();
if &self.tool != expected_tool {
return Err(
ToolReconciliationContextBindingError::ToolIdentityMismatch {
expected: Box::new(expected_tool.clone()),
actual: Box::new(self.tool.clone()),
},
);
}
let expected_idempotency = descriptor.semantics().idempotency();
if self.idempotency != expected_idempotency {
return Err(ToolReconciliationContextBindingError::IdempotencyMismatch {
expected: expected_idempotency,
actual: self.idempotency,
});
}
if self.effective_timeout > descriptor.limits().timeout() {
return Err(
ToolReconciliationContextBindingError::TimeoutExceedsDescriptor {
descriptor: descriptor.limits().timeout(),
actual: self.effective_timeout,
},
);
}
let key_is_valid = matches!(
(self.idempotency, self.idempotency_key),
(ToolIdempotency::RequiredKey, Some(key)) if key.invocation_id() == self.invocation_id
) || (self.idempotency != ToolIdempotency::RequiredKey
&& self.idempotency_key.is_none());
if !key_is_valid {
return Err(ToolReconciliationContextBindingError::InvalidIdempotencyKeyBinding);
}
Ok(())
}
}
impl fmt::Debug for ToolReconciliationContext {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolReconciliationContext")
.field("tenant_id", &self.tenant_id)
.field("run_id", &self.run_id)
.field("thread_id", &self.thread_id)
.field("invocation_id", &self.invocation_id)
.field("attempt_id", &self.attempt_id)
.field("tool", &self.tool)
.field("idempotency", &self.idempotency)
.field("has_idempotency_key", &self.idempotency_key.is_some())
.field("observed_at", &self.observed_at)
.field("deadline", &self.deadline)
.field("effective_timeout", &self.effective_timeout)
.field("cancelled", &self.cancellation.is_cancelled())
.field("has_origin_event", &self.origin_event_id.is_some())
.field("has_recovery_handle", &self.recovery_handle.is_some())
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolReconciliationContextError {
#[error("tool descriptor does not support reconciliation status queries")]
StatusQueryUnsupported,
#[error("tool reconciliation effective timeout must be greater than zero")]
ZeroEffectiveTimeout,
#[error("tool reconciliation timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
TimeoutExceedsDescriptor {
descriptor: DurationMillis,
actual: DurationMillis,
},
#[error("tool reconciliation deadline {deadline} was reached at {observed_at}")]
DeadlineReached {
deadline: Timestamp,
observed_at: Timestamp,
},
#[error("tool reconciliation monotonic deadline is out of range after {remaining:?}")]
MonotonicDeadlineOutOfRange {
remaining: Duration,
},
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolReconciliationContextBindingError {
#[error("tool descriptor does not support reconciliation status queries")]
StatusQueryUnsupported,
#[error("tool reconciliation identity {actual:?} does not match descriptor {expected:?}")]
ToolIdentityMismatch {
expected: Box<CapabilityIdentity>,
actual: Box<CapabilityIdentity>,
},
#[error("tool reconciliation idempotency {actual:?} does not match descriptor {expected:?}")]
IdempotencyMismatch {
expected: ToolIdempotency,
actual: ToolIdempotency,
},
#[error("tool reconciliation timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
TimeoutExceedsDescriptor {
descriptor: DurationMillis,
actual: DurationMillis,
},
#[error("tool reconciliation idempotency key is not bound to its invocation")]
InvalidIdempotencyKeyBinding,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ToolStopReason {
Cancelled,
DeadlineExceeded,
}
#[derive(Clone)]
pub struct ToolContext {
tenant_id: TenantId,
run_id: RunId,
thread_id: ThreadId,
invocation_id: InvocationId,
attempt_id: AttemptId,
tool: CapabilityIdentity,
idempotency: ToolIdempotency,
idempotency_key: Option<ToolIdempotencyKey>,
budget: BudgetRemaining,
observed_at: Timestamp,
deadline: Timestamp,
deadline_instant: Instant,
effective_timeout: DurationMillis,
cancellation: CancellationSignal,
progress: Option<ToolProgressReporter>,
origin_event_id: Option<EventId>,
max_inline_result_bytes: ByteCount,
max_artifacts: ExecutionCount,
max_total_artifact_bytes: ByteCount,
}
impl ToolContext {
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: TenantId,
run_id: RunId,
thread_id: ThreadId,
invocation_id: InvocationId,
attempt_id: AttemptId,
descriptor: &ToolDescriptor,
budget: BudgetRemaining,
effective_timeout: DurationMillis,
observed_at: Timestamp,
observed_instant: Instant,
cancellation: CancellationSignal,
) -> Result<Self, ToolContextError> {
if effective_timeout == DurationMillis::ZERO {
return Err(ToolContextError::ZeroEffectiveTimeout);
}
let descriptor_timeout = descriptor.limits().timeout();
if effective_timeout > descriptor_timeout {
return Err(ToolContextError::TimeoutExceedsDescriptor {
descriptor: descriptor_timeout,
actual: effective_timeout,
});
}
let run_deadline = budget.deadline();
let run_remaining_micros = i128::from(run_deadline.unix_micros())
.checked_sub(i128::from(observed_at.unix_micros()))
.expect("subtracting two i64 timestamps cannot overflow i128");
if run_remaining_micros <= 0 {
return Err(ToolContextError::DeadlineReached {
deadline: run_deadline,
observed_at,
});
}
let timeout_micros = i128::from(effective_timeout.as_i64()) * 1_000;
let remaining_micros = run_remaining_micros.min(timeout_micros);
let deadline_micros = i128::from(observed_at.unix_micros()) + remaining_micros;
let deadline_micros = i64::try_from(deadline_micros)
.expect("an effective deadline bounded by a valid run deadline fits i64");
let deadline = Timestamp::from_unix_micros(deadline_micros)
.expect("an effective deadline bounded by a valid run deadline is a timestamp");
let remaining_micros = u64::try_from(remaining_micros)
.expect("a positive supported timestamp distance fits u64 microseconds");
let remaining = Duration::from_micros(remaining_micros);
let deadline_instant = observed_instant
.checked_add(remaining)
.ok_or(ToolContextError::MonotonicDeadlineOutOfRange { remaining })?;
let idempotency = descriptor.semantics().idempotency();
let idempotency_key = descriptor
.semantics()
.requires_idempotency_key()
.then_some(ToolIdempotencyKey::from_invocation_id(invocation_id));
let max_inline_result_bytes = descriptor
.limits()
.max_inline_result_bytes()
.min(budget.output_bytes());
let max_total_artifact_bytes = descriptor
.limits()
.max_total_artifact_bytes()
.min(budget.artifact_bytes());
Ok(Self {
tenant_id,
run_id,
thread_id,
invocation_id,
attempt_id,
tool: descriptor.metadata().identity().clone(),
idempotency,
idempotency_key,
budget,
observed_at,
deadline,
deadline_instant,
effective_timeout,
cancellation,
progress: None,
origin_event_id: None,
max_inline_result_bytes,
max_artifacts: descriptor.limits().max_artifacts(),
max_total_artifact_bytes,
})
}
#[must_use]
pub fn narrow_artifact_limits(mut self, limits: &ToolExecutionLimits) -> Self {
self.max_inline_result_bytes = self
.max_inline_result_bytes
.min(limits.max_inline_result_bytes());
self.max_artifacts = self.max_artifacts.min(limits.max_artifacts());
self.max_total_artifact_bytes = self
.max_total_artifact_bytes
.min(limits.max_total_artifact_bytes());
self
}
#[must_use]
pub fn with_durable_origin_event(mut self, event_id: EventId) -> Self {
self.origin_event_id = Some(event_id);
self
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_progress(
tenant_id: TenantId,
run_id: RunId,
thread_id: ThreadId,
invocation_id: InvocationId,
attempt_id: AttemptId,
descriptor: &ToolDescriptor,
budget: BudgetRemaining,
effective_timeout: DurationMillis,
observed_at: Timestamp,
observed_instant: Instant,
cancellation: CancellationSignal,
progress_sink: Arc<dyn ToolProgressSink>,
) -> Result<Self, ToolContextError> {
let mut context = Self::new(
tenant_id,
run_id,
thread_id,
invocation_id,
attempt_id,
descriptor,
budget,
effective_timeout,
observed_at,
observed_instant,
cancellation,
)?;
let maximum = descriptor.invocation().max_progress_events();
if maximum == ExecutionCount::ZERO {
return Err(ToolContextError::ProgressUnsupported);
}
context.progress = Some(ToolProgressReporter::new(
ToolProgressProvenance::new(
invocation_id,
attempt_id,
descriptor.metadata().identity().clone(),
),
maximum,
progress_sink,
));
Ok(context)
}
#[must_use]
pub const fn tenant_id(&self) -> &TenantId {
&self.tenant_id
}
#[must_use]
pub const fn run_id(&self) -> RunId {
self.run_id
}
#[must_use]
pub const fn thread_id(&self) -> ThreadId {
self.thread_id
}
#[must_use]
pub const fn invocation_id(&self) -> InvocationId {
self.invocation_id
}
#[must_use]
pub const fn attempt_id(&self) -> AttemptId {
self.attempt_id
}
#[must_use]
pub const fn tool(&self) -> &CapabilityIdentity {
&self.tool
}
#[must_use]
pub const fn idempotency(&self) -> ToolIdempotency {
self.idempotency
}
#[must_use]
pub const fn idempotency_key(&self) -> Option<ToolIdempotencyKey> {
self.idempotency_key
}
pub const fn required_idempotency_key(
&self,
) -> Result<ToolIdempotencyKey, ToolContextBindingError> {
match self.idempotency_key {
Some(key) => Ok(key),
None => Err(ToolContextBindingError::IdempotencyKeyNotRequired {
idempotency: self.idempotency,
}),
}
}
#[must_use]
pub const fn budget(&self) -> &BudgetRemaining {
&self.budget
}
#[must_use]
pub const fn observed_at(&self) -> Timestamp {
self.observed_at
}
#[must_use]
pub const fn deadline(&self) -> Timestamp {
self.deadline
}
#[must_use]
pub const fn deadline_instant(&self) -> Instant {
self.deadline_instant
}
#[must_use]
pub const fn effective_timeout(&self) -> DurationMillis {
self.effective_timeout
}
#[must_use]
pub const fn cancellation(&self) -> &CancellationSignal {
&self.cancellation
}
#[must_use]
pub const fn progress(&self) -> Option<&ToolProgressReporter> {
self.progress.as_ref()
}
#[must_use]
pub const fn origin_event_id(&self) -> Option<EventId> {
self.origin_event_id
}
#[must_use]
pub const fn max_artifacts(&self) -> ExecutionCount {
self.max_artifacts
}
#[must_use]
pub const fn max_inline_result_bytes(&self) -> ByteCount {
self.max_inline_result_bytes
}
#[must_use]
pub const fn max_total_artifact_bytes(&self) -> ByteCount {
self.max_total_artifact_bytes
}
#[must_use]
pub fn remaining_time_at(&self, observed_instant: Instant) -> Option<Duration> {
self.deadline_instant
.checked_duration_since(observed_instant)
.filter(|remaining| !remaining.is_zero())
}
#[must_use]
pub fn stop_reason_at(&self, observed_instant: Instant) -> Option<ToolStopReason> {
if self.cancellation.is_cancelled() {
Some(ToolStopReason::Cancelled)
} else if self.remaining_time_at(observed_instant).is_none() {
Some(ToolStopReason::DeadlineExceeded)
} else {
None
}
}
pub fn validate_for(&self, descriptor: &ToolDescriptor) -> Result<(), ToolContextBindingError> {
let expected_tool = descriptor.metadata().identity();
if &self.tool != expected_tool {
return Err(ToolContextBindingError::ToolIdentityMismatch {
expected: Box::new(expected_tool.clone()),
actual: Box::new(self.tool.clone()),
});
}
let expected_idempotency = descriptor.semantics().idempotency();
if self.idempotency != expected_idempotency {
return Err(ToolContextBindingError::IdempotencyMismatch {
expected: expected_idempotency,
actual: self.idempotency,
});
}
if self.effective_timeout > descriptor.limits().timeout() {
return Err(ToolContextBindingError::TimeoutExceedsDescriptor {
descriptor: descriptor.limits().timeout(),
actual: self.effective_timeout,
});
}
let key_is_valid = matches!(
(self.idempotency, self.idempotency_key),
(ToolIdempotency::RequiredKey, Some(key)) if key.invocation_id() == self.invocation_id
) || (self.idempotency != ToolIdempotency::RequiredKey
&& self.idempotency_key.is_none());
if !key_is_valid {
return Err(ToolContextBindingError::InvalidIdempotencyKeyBinding);
}
if let Some(progress) = &self.progress {
let maximum = descriptor.invocation().max_progress_events();
if maximum == ExecutionCount::ZERO || progress.maximum_events() != maximum {
return Err(ToolContextBindingError::ProgressLimitMismatch {
expected: maximum,
actual: progress.maximum_events(),
});
}
if progress.provenance().invocation_id() != self.invocation_id
|| progress.provenance().attempt_id() != self.attempt_id
|| progress.provenance().tool() != &self.tool
{
return Err(ToolContextBindingError::ProgressProvenanceMismatch);
}
}
Ok(())
}
}
impl fmt::Debug for ToolContext {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolContext")
.field("tenant_id", &self.tenant_id)
.field("run_id", &self.run_id)
.field("thread_id", &self.thread_id)
.field("invocation_id", &self.invocation_id)
.field("attempt_id", &self.attempt_id)
.field("tool", &self.tool)
.field("idempotency", &self.idempotency)
.field("has_idempotency_key", &self.idempotency_key.is_some())
.field("observed_at", &self.observed_at)
.field("deadline", &self.deadline)
.field("effective_timeout", &self.effective_timeout)
.field("cancelled", &self.cancellation.is_cancelled())
.field("progress_enabled", &self.progress.is_some())
.field("max_artifacts", &self.max_artifacts)
.field("max_total_artifact_bytes", &self.max_total_artifact_bytes)
.field("has_origin_event", &self.origin_event_id.is_some())
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolContextError {
#[error("tool context effective timeout must be greater than zero")]
ZeroEffectiveTimeout,
#[error("tool context timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
TimeoutExceedsDescriptor {
descriptor: DurationMillis,
actual: DurationMillis,
},
#[error("tool context deadline {deadline} was reached at {observed_at}")]
DeadlineReached {
deadline: Timestamp,
observed_at: Timestamp,
},
#[error("tool context monotonic deadline is out of range after {remaining:?}")]
MonotonicDeadlineOutOfRange {
remaining: Duration,
},
#[error("tool descriptor does not allow progress events")]
ProgressUnsupported,
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolContextBindingError {
#[error("tool context identity {actual:?} does not match descriptor {expected:?}")]
ToolIdentityMismatch {
expected: Box<CapabilityIdentity>,
actual: Box<CapabilityIdentity>,
},
#[error("tool context idempotency {actual:?} does not match descriptor {expected:?}")]
IdempotencyMismatch {
expected: ToolIdempotency,
actual: ToolIdempotency,
},
#[error("tool context timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
TimeoutExceedsDescriptor {
descriptor: DurationMillis,
actual: DurationMillis,
},
#[error("tool context idempotency key is not bound to its logical invocation")]
InvalidIdempotencyKeyBinding,
#[error("tool idempotency mechanism {idempotency:?} does not require a key")]
IdempotencyKeyNotRequired {
idempotency: ToolIdempotency,
},
#[error("tool progress maximum {actual} does not match descriptor {expected}")]
ProgressLimitMismatch {
expected: ExecutionCount,
actual: ExecutionCount,
},
#[error("tool progress reporter provenance does not match its context")]
ProgressProvenanceMismatch,
}
#[derive(Clone, Copy, Debug, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ToolProgressUpdate {
completed: ExecutionCount,
#[serde(skip_serializing_if = "Option::is_none")]
total: Option<ExecutionCount>,
}
impl ToolProgressUpdate {
pub const fn new(
completed: ExecutionCount,
total: Option<ExecutionCount>,
) -> Result<Self, ToolProgressUpdateError> {
if let Some(total) = total {
if total.get() == 0 {
return Err(ToolProgressUpdateError::ZeroTotal);
}
if completed.get() > total.get() {
return Err(ToolProgressUpdateError::CompletedExceedsTotal { completed, total });
}
}
Ok(Self { completed, total })
}
#[must_use]
pub const fn completed(self) -> ExecutionCount {
self.completed
}
#[must_use]
pub const fn total(self) -> Option<ExecutionCount> {
self.total
}
}
impl<'de> Deserialize<'de> for ToolProgressUpdate {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Wire {
completed: ExecutionCount,
total: Option<ExecutionCount>,
}
let wire = Wire::deserialize(deserializer)?;
Self::new(wire.completed, wire.total).map_err(de::Error::custom)
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolProgressUpdateError {
#[error("tool progress total must be greater than zero")]
ZeroTotal,
#[error("tool progress completed {completed} exceeds total {total}")]
CompletedExceedsTotal {
completed: ExecutionCount,
total: ExecutionCount,
},
}
#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ToolProgressProvenance {
invocation_id: InvocationId,
attempt_id: AttemptId,
tool: CapabilityIdentity,
}
impl ToolProgressProvenance {
#[must_use]
pub const fn new(
invocation_id: InvocationId,
attempt_id: AttemptId,
tool: CapabilityIdentity,
) -> Self {
Self {
invocation_id,
attempt_id,
tool,
}
}
#[must_use]
pub const fn invocation_id(&self) -> InvocationId {
self.invocation_id
}
#[must_use]
pub const fn attempt_id(&self) -> AttemptId {
self.attempt_id
}
#[must_use]
pub const fn tool(&self) -> &CapabilityIdentity {
&self.tool
}
}
impl fmt::Debug for ToolProgressProvenance {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolProgressProvenance")
.field("invocation_id", &self.invocation_id)
.field("attempt_id", &self.attempt_id)
.field("tool", &self.tool)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ToolProgressEvent {
provenance: ToolProgressProvenance,
sequence: ExecutionCount,
update: ToolProgressUpdate,
}
impl ToolProgressEvent {
#[must_use]
pub const fn new(
provenance: ToolProgressProvenance,
sequence: ExecutionCount,
update: ToolProgressUpdate,
) -> Self {
Self {
provenance,
sequence,
update,
}
}
#[must_use]
pub const fn provenance(&self) -> &ToolProgressProvenance {
&self.provenance
}
#[must_use]
pub const fn sequence(&self) -> ExecutionCount {
self.sequence
}
#[must_use]
pub const fn update(&self) -> ToolProgressUpdate {
self.update
}
pub fn validate_for(
&self,
context: &ToolContext,
descriptor: &ToolDescriptor,
) -> Result<(), ToolProgressEventValidationError> {
context
.validate_for(descriptor)
.map_err(ToolProgressEventValidationError::context)?;
if self.provenance.invocation_id != context.invocation_id() {
return Err(ToolProgressEventValidationError::InvocationMismatch {
expected: context.invocation_id(),
actual: self.provenance.invocation_id,
});
}
if self.provenance.attempt_id != context.attempt_id() {
return Err(ToolProgressEventValidationError::AttemptMismatch {
expected: context.attempt_id(),
actual: self.provenance.attempt_id,
});
}
let expected_tool = descriptor.metadata().identity();
if &self.provenance.tool != expected_tool {
return Err(ToolProgressEventValidationError::ToolIdentityMismatch {
expected: Box::new(expected_tool.clone()),
actual: Box::new(self.provenance.tool.clone()),
});
}
let maximum = descriptor.invocation().max_progress_events();
if self.sequence >= maximum {
return Err(ToolProgressEventValidationError::SequenceLimitExceeded {
maximum,
actual: self.sequence,
});
}
Ok(())
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolProgressEventValidationError {
#[error("tool progress context binding is invalid: {source}")]
Context {
#[source]
source: ToolContextBindingError,
},
#[error("tool progress invocation {actual} does not match context {expected}")]
InvocationMismatch {
expected: InvocationId,
actual: InvocationId,
},
#[error("tool progress attempt {actual} does not match context {expected}")]
AttemptMismatch {
expected: AttemptId,
actual: AttemptId,
},
#[error("tool progress identity {actual:?} does not match descriptor {expected:?}")]
ToolIdentityMismatch {
expected: Box<CapabilityIdentity>,
actual: Box<CapabilityIdentity>,
},
#[error("tool progress sequence {actual} exceeds event capacity {maximum}")]
SequenceLimitExceeded {
maximum: ExecutionCount,
actual: ExecutionCount,
},
}
impl ToolProgressEventValidationError {
const fn context(source: ToolContextBindingError) -> Self {
Self::Context { source }
}
}
type PrivateProgressSinkSource = dyn StdError + Send + Sync + 'static;
#[derive(Clone)]
pub struct ToolProgressSinkError {
private_source: Arc<PrivateProgressSinkSource>,
}
impl ToolProgressSinkError {
#[must_use]
pub fn new<E>(source: E) -> Self
where
E: StdError + Send + Sync + 'static,
{
Self {
private_source: Arc::new(source),
}
}
#[must_use]
pub fn private_source(&self) -> &(dyn StdError + Send + Sync + 'static) {
self.private_source.as_ref()
}
}
impl fmt::Debug for ToolProgressSinkError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolProgressSinkError")
.field("has_private_source", &true)
.finish_non_exhaustive()
}
}
impl fmt::Display for ToolProgressSinkError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("tool progress sink failed")
}
}
impl StdError for ToolProgressSinkError {}
pub trait ToolProgressSink: Send + Sync + 'static {
fn emit(
&self,
event: ToolProgressEvent,
) -> crate::BoxFuture<'_, Result<(), ToolProgressSinkError>>;
}
#[derive(Debug)]
struct ToolProgressState {
next_sequence: ExecutionCount,
last_completed: Option<ExecutionCount>,
total: Option<ExecutionCount>,
in_flight: bool,
poisoned: bool,
}
#[derive(Clone)]
pub struct ToolProgressReporter {
provenance: ToolProgressProvenance,
maximum_events: ExecutionCount,
sink: Arc<dyn ToolProgressSink>,
state: Arc<Mutex<ToolProgressState>>,
}
impl ToolProgressReporter {
fn new(
provenance: ToolProgressProvenance,
maximum_events: ExecutionCount,
sink: Arc<dyn ToolProgressSink>,
) -> Self {
debug_assert!(maximum_events != ExecutionCount::ZERO);
Self {
provenance,
maximum_events,
sink,
state: Arc::new(Mutex::new(ToolProgressState {
next_sequence: ExecutionCount::ZERO,
last_completed: None,
total: None,
in_flight: false,
poisoned: false,
})),
}
}
#[must_use]
pub const fn provenance(&self) -> &ToolProgressProvenance {
&self.provenance
}
#[must_use]
pub const fn maximum_events(&self) -> ExecutionCount {
self.maximum_events
}
pub fn emit(
&self,
update: ToolProgressUpdate,
) -> crate::BoxFuture<'_, Result<ToolProgressEvent, ToolProgressError>> {
Box::pin(async move {
let (event, mut reservation) = {
let mut state = self
.state
.lock()
.map_err(|_| ToolProgressError::StatePoisoned)?;
if state.poisoned {
return Err(ToolProgressError::StatePoisoned);
}
if state.in_flight {
return Err(ToolProgressError::ConcurrentEmission);
}
if state.next_sequence >= self.maximum_events {
return Err(ToolProgressError::MaximumReached {
maximum: self.maximum_events,
});
}
if let Some(previous) = state.last_completed {
if update.completed() <= previous {
return Err(ToolProgressError::NotIncreasing {
previous,
actual: update.completed(),
});
}
}
if let (Some(expected), Some(actual)) = (state.total, update.total()) {
if expected != actual {
return Err(ToolProgressError::TotalChanged { expected, actual });
}
}
let total = update.total().or(state.total);
if let Some(total) = total {
if update.completed() > total {
return Err(ToolProgressError::CompletedExceedsEstablishedTotal {
completed: update.completed(),
total,
});
}
}
let normalized = ToolProgressUpdate {
completed: update.completed(),
total,
};
let event = ToolProgressEvent::new(
self.provenance.clone(),
state.next_sequence,
normalized,
);
state.in_flight = true;
(event, ToolProgressReservation::new(Arc::clone(&self.state)))
};
match self.sink.emit(event.clone()).await {
Ok(()) => {
reservation.commit(event.update())?;
Ok(event)
}
Err(source) => {
reservation.fail();
Err(ToolProgressError::Sink { source })
}
}
})
}
}
impl fmt::Debug for ToolProgressReporter {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolProgressReporter")
.field("provenance", &self.provenance)
.field("maximum_events", &self.maximum_events)
.finish_non_exhaustive()
}
}
struct ToolProgressReservation {
state: Arc<Mutex<ToolProgressState>>,
active: bool,
}
impl ToolProgressReservation {
fn new(state: Arc<Mutex<ToolProgressState>>) -> Self {
Self {
state,
active: true,
}
}
fn commit(&mut self, update: ToolProgressUpdate) -> Result<(), ToolProgressError> {
let mut state = self
.state
.lock()
.map_err(|_| ToolProgressError::StatePoisoned)?;
state.next_sequence = state
.next_sequence
.checked_add(ExecutionCount::new(1))
.ok_or(ToolProgressError::StatePoisoned)?;
state.last_completed = Some(update.completed());
state.total = update.total();
state.in_flight = false;
self.active = false;
Ok(())
}
fn fail(&mut self) {
if let Ok(mut state) = self.state.lock() {
state.in_flight = false;
state.poisoned = true;
}
self.active = false;
}
}
impl Drop for ToolProgressReservation {
fn drop(&mut self) {
if self.active {
self.fail();
}
}
}
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum ToolProgressError {
#[error("tool progress reporter is poisoned")]
StatePoisoned,
#[error("concurrent tool progress emission is not allowed")]
ConcurrentEmission,
#[error("tool progress event maximum {maximum} was reached")]
MaximumReached {
maximum: ExecutionCount,
},
#[error("tool progress completed {actual} does not exceed previous {previous}")]
NotIncreasing {
previous: ExecutionCount,
actual: ExecutionCount,
},
#[error("tool progress total {actual} does not match established {expected}")]
TotalChanged {
expected: ExecutionCount,
actual: ExecutionCount,
},
#[error("tool progress completed {completed} exceeds established total {total}")]
CompletedExceedsEstablishedTotal {
completed: ExecutionCount,
total: ExecutionCount,
},
#[error("tool progress sink failed")]
Sink {
source: ToolProgressSinkError,
},
}
#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ToolInput {
schema: SchemaReference,
value: BoundedJson,
}
impl ToolInput {
pub fn new(schema: SchemaReference, value: BoundedJson) -> Result<Self, ToolInputError> {
if !value.as_value().is_object() {
return Err(ToolInputError::ObjectRootRequired);
}
Ok(Self { schema, value })
}
#[must_use]
pub const fn schema(&self) -> &SchemaReference {
&self.schema
}
#[must_use]
pub const fn value(&self) -> &BoundedJson {
&self.value
}
#[must_use]
pub fn into_parts(self) -> (SchemaReference, BoundedJson) {
(self.schema, self.value)
}
pub fn validate_for(
&self,
context: &ToolContext,
descriptor: &ToolDescriptor,
) -> Result<(), ToolInputValidationError> {
context
.validate_for(descriptor)
.map_err(ToolInputValidationError::context)?;
if &self.schema != descriptor.input_schema() {
return Err(ToolInputValidationError::SchemaMismatch {
expected: Box::new(descriptor.input_schema().clone()),
actual: Box::new(self.schema.clone()),
});
}
let actual = byte_count_from_usize(self.value.stats().compact_bytes());
let descriptor_maximum = descriptor.limits().max_input_bytes();
if actual > descriptor_maximum {
return Err(ToolInputValidationError::DescriptorLimitExceeded {
maximum: descriptor_maximum,
actual,
});
}
let budget_maximum = context.budget().input_bytes();
if actual > budget_maximum {
return Err(ToolInputValidationError::BudgetLimitExceeded {
maximum: budget_maximum,
actual,
});
}
Ok(())
}
}
impl fmt::Debug for ToolInput {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolInput")
.field("schema", &self.schema)
.field("stats", &self.value.stats())
.finish_non_exhaustive()
}
}
impl<'de> Deserialize<'de> for ToolInput {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Wire {
schema: SchemaReference,
value: BoundedJson,
}
let wire = Wire::deserialize(deserializer)?;
Self::new(wire.schema, wire.value).map_err(de::Error::custom)
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolInputError {
#[error("tool input JSON must have an object root")]
ObjectRootRequired,
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolInputValidationError {
#[error("tool input context binding is invalid: {source}")]
Context {
#[source]
source: ToolContextBindingError,
},
#[error("tool input schema {actual:?} does not match descriptor {expected:?}")]
SchemaMismatch {
expected: Box<SchemaReference>,
actual: Box<SchemaReference>,
},
#[error("tool input is {actual} bytes; descriptor maximum is {maximum}")]
DescriptorLimitExceeded {
maximum: ByteCount,
actual: ByteCount,
},
#[error("tool input is {actual} bytes; remaining run maximum is {maximum}")]
BudgetLimitExceeded {
maximum: ByteCount,
actual: ByteCount,
},
}
impl ToolInputValidationError {
const fn context(source: ToolContextBindingError) -> Self {
Self::Context { source }
}
}
#[derive(Clone, Default, Eq, PartialEq)]
pub struct ToolArtifacts {
values: Box<[ArtifactRef]>,
total_bytes: ByteCount,
}
impl ToolArtifacts {
pub const MAX_LEN: usize = 64;
#[must_use]
pub fn empty() -> Self {
Self::default()
}
pub fn try_new<I>(values: I) -> Result<Self, ToolArtifactsError>
where
I: IntoIterator<Item = ArtifactRef>,
{
let mut collected = Vec::new();
let mut total_bytes = ByteCount::ZERO;
for value in values {
if collected.len() == Self::MAX_LEN {
return Err(ToolArtifactsError::TooMany {
maximum: Self::MAX_LEN,
actual: Self::MAX_LEN + 1,
});
}
if collected
.iter()
.any(|existing: &ArtifactRef| existing.identity() == value.identity())
{
return Err(ToolArtifactsError::DuplicateIdentity);
}
total_bytes = total_bytes
.checked_add(value.representation().byte_length())
.ok_or(ToolArtifactsError::TotalBytesOverflow)?;
collected.push(value);
}
Ok(Self {
values: collected.into_boxed_slice(),
total_bytes,
})
}
#[must_use]
pub const fn len(&self) -> usize {
self.values.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.values.is_empty()
}
#[must_use]
pub const fn total_bytes(&self) -> ByteCount {
self.total_bytes
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = &ArtifactRef> {
self.values.iter()
}
#[must_use]
pub fn into_vec(self) -> Vec<ArtifactRef> {
self.values.into_vec()
}
}
impl fmt::Debug for ToolArtifacts {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolArtifacts")
.field("count", &self.len())
.field("total_bytes", &self.total_bytes)
.finish_non_exhaustive()
}
}
impl Serialize for ToolArtifacts {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.values.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ToolArtifacts {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_seq(ToolArtifactsVisitor)
}
}
struct ToolArtifactsVisitor;
impl<'de> de::Visitor<'de> for ToolArtifactsVisitor {
type Value = ToolArtifacts;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"at most {} unique artifact references",
ToolArtifacts::MAX_LEN
)
}
fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
where
A: de::SeqAccess<'de>,
{
let mut values = Vec::with_capacity(
sequence
.size_hint()
.unwrap_or_default()
.min(ToolArtifacts::MAX_LEN),
);
while let Some(value) = sequence.next_element::<ArtifactRef>()? {
if values.len() == ToolArtifacts::MAX_LEN {
return Err(de::Error::custom(ToolArtifactsError::TooMany {
maximum: ToolArtifacts::MAX_LEN,
actual: ToolArtifacts::MAX_LEN + 1,
}));
}
if values
.iter()
.any(|existing: &ArtifactRef| existing.identity() == value.identity())
{
return Err(de::Error::custom(ToolArtifactsError::DuplicateIdentity));
}
values.push(value);
}
Self::Value::try_new(values).map_err(de::Error::custom)
}
}
impl JsonSchema for ToolArtifacts {
fn schema_name() -> std::borrow::Cow<'static, str> {
"ToolArtifacts".into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
concat!(module_path!(), "::ToolArtifacts").into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "array",
"items": generator.subschema_for::<ArtifactRef>(),
"maxItems": 64,
"uniqueItems": true,
"description": "Ordered artifact references with unique tenant-qualified identities. Identity uniqueness is enforced at runtime."
})
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolArtifactsError {
#[error("tool result has {actual} artifacts; hard maximum is {maximum}")]
TooMany {
maximum: usize,
actual: usize,
},
#[error("tool result artifact identities must be unique")]
DuplicateIdentity,
#[error("tool result aggregate artifact bytes overflowed")]
TotalBytesOverflow,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ToolOutput<T> {
value: T,
artifacts: ToolArtifacts,
}
impl<T> ToolOutput<T> {
#[must_use]
pub fn inline(value: T) -> Self {
Self {
value,
artifacts: ToolArtifacts::empty(),
}
}
#[must_use]
pub const fn with_artifacts(value: T, artifacts: ToolArtifacts) -> Self {
Self { value, artifacts }
}
#[must_use]
pub const fn value(&self) -> &T {
&self.value
}
#[must_use]
pub const fn artifacts(&self) -> &ToolArtifacts {
&self.artifacts
}
#[must_use]
pub fn into_parts(self) -> (T, ToolArtifacts) {
(self.value, self.artifacts)
}
}
impl<T> From<T> for ToolOutput<T> {
fn from(value: T) -> Self {
Self::inline(value)
}
}
#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ToolResultProvenance {
invocation_id: InvocationId,
attempt_id: AttemptId,
tool: CapabilityIdentity,
}
impl ToolResultProvenance {
#[must_use]
pub const fn new(
invocation_id: InvocationId,
attempt_id: AttemptId,
tool: CapabilityIdentity,
) -> Self {
Self {
invocation_id,
attempt_id,
tool,
}
}
#[must_use]
pub const fn invocation_id(&self) -> InvocationId {
self.invocation_id
}
#[must_use]
pub const fn attempt_id(&self) -> AttemptId {
self.attempt_id
}
#[must_use]
pub const fn tool(&self) -> &CapabilityIdentity {
&self.tool
}
}
impl fmt::Debug for ToolResultProvenance {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolResultProvenance")
.field("invocation_id", &self.invocation_id)
.field("attempt_id", &self.attempt_id)
.field("tool", &self.tool)
.finish_non_exhaustive()
}
}
#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ToolResult {
provenance: ToolResultProvenance,
output_schema: SchemaReference,
output: BoundedJson,
artifacts: ToolArtifacts,
}
impl ToolResult {
#[must_use]
pub const fn new(
provenance: ToolResultProvenance,
output_schema: SchemaReference,
output: BoundedJson,
artifacts: ToolArtifacts,
) -> Self {
Self {
provenance,
output_schema,
output,
artifacts,
}
}
#[must_use]
pub fn for_invocation(
context: &ToolContext,
descriptor: &ToolDescriptor,
output: BoundedJson,
artifacts: ToolArtifacts,
) -> Self {
Self::new(
ToolResultProvenance::new(
context.invocation_id(),
context.attempt_id(),
descriptor.metadata().identity().clone(),
),
descriptor.output_schema().clone(),
output,
artifacts,
)
}
#[must_use]
pub const fn provenance(&self) -> &ToolResultProvenance {
&self.provenance
}
#[must_use]
pub const fn output_schema(&self) -> &SchemaReference {
&self.output_schema
}
#[must_use]
pub const fn output(&self) -> &BoundedJson {
&self.output
}
#[must_use]
pub const fn artifacts(&self) -> &ToolArtifacts {
&self.artifacts
}
#[must_use]
pub fn into_parts(
self,
) -> (
ToolResultProvenance,
SchemaReference,
BoundedJson,
ToolArtifacts,
) {
(
self.provenance,
self.output_schema,
self.output,
self.artifacts,
)
}
pub fn validate_for(
&self,
context: &ToolContext,
descriptor: &ToolDescriptor,
) -> Result<(), ToolResultValidationError> {
context
.validate_for(descriptor)
.map_err(ToolResultValidationError::context)?;
if self.provenance.invocation_id != context.invocation_id() {
return Err(ToolResultValidationError::InvocationMismatch {
expected: context.invocation_id(),
actual: self.provenance.invocation_id,
});
}
if self.provenance.attempt_id != context.attempt_id() {
return Err(ToolResultValidationError::AttemptMismatch {
expected: context.attempt_id(),
actual: self.provenance.attempt_id,
});
}
let expected_tool = descriptor.metadata().identity();
if &self.provenance.tool != expected_tool {
return Err(ToolResultValidationError::ToolIdentityMismatch {
expected: Box::new(expected_tool.clone()),
actual: Box::new(self.provenance.tool.clone()),
});
}
if &self.output_schema != descriptor.output_schema() {
return Err(ToolResultValidationError::SchemaMismatch {
expected: Box::new(descriptor.output_schema().clone()),
actual: Box::new(self.output_schema.clone()),
});
}
let output_bytes = byte_count_from_usize(self.output.stats().compact_bytes());
let descriptor_output_maximum = descriptor.limits().max_inline_result_bytes();
if output_bytes > descriptor_output_maximum {
return Err(ToolResultValidationError::InlineDescriptorLimitExceeded {
maximum: descriptor_output_maximum,
actual: output_bytes,
});
}
let budget_output_maximum = context.budget().output_bytes();
if output_bytes > budget_output_maximum {
return Err(ToolResultValidationError::InlineBudgetLimitExceeded {
maximum: budget_output_maximum,
actual: output_bytes,
});
}
let artifact_count = execution_count_from_usize(self.artifacts.len());
let descriptor_artifact_maximum = descriptor.limits().max_artifacts();
if artifact_count > descriptor_artifact_maximum {
return Err(ToolResultValidationError::ArtifactCountLimitExceeded {
maximum: descriptor_artifact_maximum,
actual: artifact_count,
});
}
let artifact_bytes = self.artifacts.total_bytes();
let descriptor_artifact_bytes = descriptor.limits().max_total_artifact_bytes();
if artifact_bytes > descriptor_artifact_bytes {
return Err(ToolResultValidationError::ArtifactDescriptorBytesExceeded {
maximum: descriptor_artifact_bytes,
actual: artifact_bytes,
});
}
let budget_artifact_bytes = context.budget().artifact_bytes();
if artifact_bytes > budget_artifact_bytes {
return Err(ToolResultValidationError::ArtifactBudgetBytesExceeded {
maximum: budget_artifact_bytes,
actual: artifact_bytes,
});
}
for (index, artifact) in self.artifacts.iter().enumerate() {
validate_artifact_binding(index, artifact, context, descriptor)?;
}
Ok(())
}
}
impl fmt::Debug for ToolResult {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolResult")
.field("provenance", &self.provenance)
.field("output_schema", &self.output_schema)
.field("output_stats", &self.output.stats())
.field("artifacts", &self.artifacts)
.finish_non_exhaustive()
}
}
fn validate_artifact_binding(
index: usize,
artifact: &ArtifactRef,
context: &ToolContext,
descriptor: &ToolDescriptor,
) -> Result<(), ToolResultValidationError> {
if artifact.identity().tenant_id() != context.tenant_id() {
return Err(ToolResultValidationError::ArtifactTenantMismatch {
index,
expected: Box::new(context.tenant_id().clone()),
actual: Box::new(artifact.identity().tenant_id().clone()),
});
}
if artifact.provenance().run_id() != context.run_id() {
return Err(ToolResultValidationError::ArtifactRunMismatch {
index,
expected: context.run_id(),
actual: artifact.provenance().run_id(),
});
}
let expected_principal = descriptor.metadata().identity().owner();
if artifact.provenance().principal() != expected_principal {
return Err(ToolResultValidationError::ArtifactPrincipalMismatch {
index,
expected: Box::new(expected_principal.clone()),
actual: Box::new(artifact.provenance().principal().clone()),
});
}
let expected_capability = descriptor.metadata().identity().capability();
if artifact.provenance().capability() != Some(expected_capability) {
return Err(ToolResultValidationError::ArtifactCapabilityMismatch {
index,
expected: Box::new(expected_capability.clone()),
actual: artifact
.provenance()
.capability()
.map(|value| Box::new(value.clone())),
});
}
Ok(())
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolResultValidationError {
#[error("tool result context binding is invalid: {source}")]
Context {
#[source]
source: ToolContextBindingError,
},
#[error("tool result invocation {actual} does not match context {expected}")]
InvocationMismatch {
expected: InvocationId,
actual: InvocationId,
},
#[error("tool result attempt {actual} does not match context {expected}")]
AttemptMismatch {
expected: AttemptId,
actual: AttemptId,
},
#[error("tool result identity {actual:?} does not match descriptor {expected:?}")]
ToolIdentityMismatch {
expected: Box<CapabilityIdentity>,
actual: Box<CapabilityIdentity>,
},
#[error("tool result schema {actual:?} does not match descriptor {expected:?}")]
SchemaMismatch {
expected: Box<SchemaReference>,
actual: Box<SchemaReference>,
},
#[error("tool inline output is {actual} bytes; descriptor maximum is {maximum}")]
InlineDescriptorLimitExceeded {
maximum: ByteCount,
actual: ByteCount,
},
#[error("tool inline output is {actual} bytes; remaining run maximum is {maximum}")]
InlineBudgetLimitExceeded {
maximum: ByteCount,
actual: ByteCount,
},
#[error("tool result has {actual} artifacts; descriptor maximum is {maximum}")]
ArtifactCountLimitExceeded {
maximum: ExecutionCount,
actual: ExecutionCount,
},
#[error("tool artifacts total {actual} bytes; descriptor maximum is {maximum}")]
ArtifactDescriptorBytesExceeded {
maximum: ByteCount,
actual: ByteCount,
},
#[error("tool artifacts total {actual} bytes; remaining run maximum is {maximum}")]
ArtifactBudgetBytesExceeded {
maximum: ByteCount,
actual: ByteCount,
},
#[error("tool artifact at index {index} tenant {actual} does not match {expected}")]
ArtifactTenantMismatch {
index: usize,
expected: Box<TenantId>,
actual: Box<TenantId>,
},
#[error("tool artifact at index {index} run {actual} does not match {expected}")]
ArtifactRunMismatch {
index: usize,
expected: RunId,
actual: RunId,
},
#[error("tool artifact at index {index} principal does not match the descriptor owner")]
ArtifactPrincipalMismatch {
index: usize,
expected: Box<PrincipalIdentity>,
actual: Box<PrincipalIdentity>,
},
#[error("tool artifact at index {index} capability does not match the descriptor")]
ArtifactCapabilityMismatch {
index: usize,
expected: Box<CapabilityReference>,
actual: Option<Box<CapabilityReference>>,
},
}
impl ToolResultValidationError {
const fn context(source: ToolContextBindingError) -> Self {
Self::Context { source }
}
}
#[derive(
Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum ToolErrorPhase {
Preparation,
Execution,
Result,
}
#[derive(
Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum ToolExternalEffect {
NotApplicable,
NotStarted,
NotApplied,
Applied,
Unknown,
}
#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ToolErrorProvenance {
invocation_id: InvocationId,
attempt_id: AttemptId,
tool: CapabilityIdentity,
}
impl ToolErrorProvenance {
#[must_use]
pub const fn new(
invocation_id: InvocationId,
attempt_id: AttemptId,
tool: CapabilityIdentity,
) -> Self {
Self {
invocation_id,
attempt_id,
tool,
}
}
#[must_use]
pub fn for_invocation(context: &ToolContext, descriptor: &ToolDescriptor) -> Self {
Self::new(
context.invocation_id(),
context.attempt_id(),
descriptor.metadata().identity().clone(),
)
}
#[must_use]
pub const fn invocation_id(&self) -> InvocationId {
self.invocation_id
}
#[must_use]
pub const fn attempt_id(&self) -> AttemptId {
self.attempt_id
}
#[must_use]
pub const fn tool(&self) -> &CapabilityIdentity {
&self.tool
}
}
impl fmt::Debug for ToolErrorProvenance {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolErrorProvenance")
.field("invocation_id", &self.invocation_id)
.field("attempt_id", &self.attempt_id)
.field("tool", &self.tool)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct ToolError {
failure: Failure,
phase: ToolErrorPhase,
external_effect: ToolExternalEffect,
provenance: ToolErrorProvenance,
recovery_handle: Option<ToolRecoveryHandle>,
}
impl ToolError {
pub fn new(
failure: Failure,
phase: ToolErrorPhase,
external_effect: ToolExternalEffect,
provenance: ToolErrorProvenance,
) -> Result<Self, ToolErrorBuildError> {
validate_tool_error_shape(&failure, phase, external_effect)?;
Ok(Self {
failure,
phase,
external_effect,
provenance,
recovery_handle: None,
})
}
pub fn with_recovery_handle(
mut self,
recovery_handle: ToolRecoveryHandle,
) -> Result<Self, ToolErrorBuildError> {
if self.external_effect != ToolExternalEffect::Unknown {
return Err(ToolErrorBuildError::RecoveryHandleRequiresUnknownEffect);
}
self.recovery_handle = Some(recovery_handle);
Ok(self)
}
pub fn validate_for(
&self,
context: &ToolContext,
descriptor: &ToolDescriptor,
) -> Result<(), ToolErrorValidationError> {
context
.validate_for(descriptor)
.map_err(ToolErrorValidationError::context)?;
if self.provenance.invocation_id != context.invocation_id() {
return Err(ToolErrorValidationError::InvocationMismatch {
expected: context.invocation_id(),
actual: self.provenance.invocation_id,
});
}
if self.provenance.attempt_id != context.attempt_id() {
return Err(ToolErrorValidationError::AttemptMismatch {
expected: context.attempt_id(),
actual: self.provenance.attempt_id,
});
}
let expected_tool = descriptor.metadata().identity();
if &self.provenance.tool != expected_tool {
return Err(ToolErrorValidationError::ToolIdentityMismatch {
expected: Box::new(expected_tool.clone()),
actual: Box::new(self.provenance.tool.clone()),
});
}
let risk = descriptor.semantics().risk();
match (risk, self.external_effect) {
(ToolRisk::ReadOnly, ToolExternalEffect::NotApplicable)
| (
ToolRisk::IdempotentWrite | ToolRisk::NonIdempotentWrite,
ToolExternalEffect::NotStarted
| ToolExternalEffect::NotApplied
| ToolExternalEffect::Applied
| ToolExternalEffect::Unknown,
) => {}
_ => {
return Err(ToolErrorValidationError::EffectRiskMismatch {
risk,
effect: self.external_effect,
});
}
}
if risk == ToolRisk::NonIdempotentWrite
&& self.external_effect == ToolExternalEffect::Applied
&& matches!(self.failure.retry_advice(), RetryAdvice::SafeAfter { .. })
{
return Err(ToolErrorValidationError::UnsafeRetryAfterAppliedNonIdempotentWrite);
}
Ok(())
}
#[must_use]
pub const fn failure(&self) -> &Failure {
&self.failure
}
#[must_use]
pub fn into_failure(self) -> Failure {
self.failure
}
#[must_use]
pub const fn phase(&self) -> ToolErrorPhase {
self.phase
}
#[must_use]
pub const fn external_effect(&self) -> ToolExternalEffect {
self.external_effect
}
#[must_use]
pub const fn provenance(&self) -> &ToolErrorProvenance {
&self.provenance
}
#[must_use]
pub const fn recovery_handle(&self) -> Option<&ToolRecoveryHandle> {
self.recovery_handle.as_ref()
}
}
fn validate_tool_error_shape(
failure: &Failure,
phase: ToolErrorPhase,
external_effect: ToolExternalEffect,
) -> Result<(), ToolErrorBuildError> {
let ambiguous = failure.category() == FailureCategory::AmbiguousExternalOutcome;
if external_effect == ToolExternalEffect::Unknown && !ambiguous {
return Err(ToolErrorBuildError::UnknownEffectRequiresAmbiguousFailure);
}
if ambiguous && external_effect != ToolExternalEffect::Unknown {
return Err(ToolErrorBuildError::AmbiguousFailureRequiresUnknownEffect);
}
let phase_effect_valid = match phase {
ToolErrorPhase::Preparation => matches!(
external_effect,
ToolExternalEffect::NotApplicable | ToolExternalEffect::NotStarted
),
ToolErrorPhase::Execution => true,
ToolErrorPhase::Result => matches!(
external_effect,
ToolExternalEffect::NotApplicable
| ToolExternalEffect::Applied
| ToolExternalEffect::Unknown
),
};
if !phase_effect_valid {
return Err(ToolErrorBuildError::PhaseEffectMismatch {
phase,
effect: external_effect,
});
}
Ok(())
}
impl fmt::Debug for ToolError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolError")
.field("failure", &self.failure)
.field("phase", &self.phase)
.field("external_effect", &self.external_effect)
.field("provenance", &self.provenance)
.field("has_recovery_handle", &self.recovery_handle.is_some())
.finish_non_exhaustive()
}
}
impl fmt::Display for ToolError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.failure, formatter)
}
}
impl StdError for ToolError {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&self.failure)
}
}
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ToolErrorWire {
failure: Failure,
phase: ToolErrorPhase,
external_effect: ToolExternalEffect,
provenance: ToolErrorProvenance,
#[serde(default)]
recovery_handle: Option<ToolRecoveryHandle>,
}
#[derive(Serialize)]
struct ToolErrorWireRef<'a> {
failure: &'a Failure,
phase: ToolErrorPhase,
external_effect: ToolExternalEffect,
provenance: &'a ToolErrorProvenance,
#[serde(skip_serializing_if = "Option::is_none")]
recovery_handle: Option<&'a ToolRecoveryHandle>,
}
impl Serialize for ToolError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
ToolErrorWireRef {
failure: &self.failure,
phase: self.phase,
external_effect: self.external_effect,
provenance: &self.provenance,
recovery_handle: self.recovery_handle.as_ref(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ToolError {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let wire = ToolErrorWire::deserialize(deserializer)?;
let error = Self::new(
wire.failure,
wire.phase,
wire.external_effect,
wire.provenance,
)
.map_err(de::Error::custom)?;
match wire.recovery_handle {
Some(handle) => error
.with_recovery_handle(handle)
.map_err(de::Error::custom),
None => Ok(error),
}
}
}
impl JsonSchema for ToolError {
fn schema_name() -> std::borrow::Cow<'static, str> {
"ToolError".into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
concat!(module_path!(), "::ToolError").into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
ToolErrorWire::json_schema(generator)
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolErrorBuildError {
#[error("unknown tool effect requires an ambiguous-external-outcome failure")]
UnknownEffectRequiresAmbiguousFailure,
#[error("ambiguous-external-outcome failure requires unknown tool effect")]
AmbiguousFailureRequiresUnknownEffect,
#[error("tool error phase {phase:?} is incompatible with effect {effect:?}")]
PhaseEffectMismatch {
phase: ToolErrorPhase,
effect: ToolExternalEffect,
},
#[error("tool recovery handles require unknown external-effect evidence")]
RecoveryHandleRequiresUnknownEffect,
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolErrorValidationError {
#[error("tool error context binding is invalid: {source}")]
Context {
#[source]
source: ToolContextBindingError,
},
#[error("tool error invocation {actual} does not match context {expected}")]
InvocationMismatch {
expected: InvocationId,
actual: InvocationId,
},
#[error("tool error attempt {actual} does not match context {expected}")]
AttemptMismatch {
expected: AttemptId,
actual: AttemptId,
},
#[error("tool error identity {actual:?} does not match descriptor {expected:?}")]
ToolIdentityMismatch {
expected: Box<CapabilityIdentity>,
actual: Box<CapabilityIdentity>,
},
#[error("tool risk {risk:?} is incompatible with external effect {effect:?}")]
EffectRiskMismatch {
risk: ToolRisk,
effect: ToolExternalEffect,
},
#[error("an applied non-idempotent write cannot use safe-after retry advice")]
UnsafeRetryAfterAppliedNonIdempotentWrite,
}
impl ToolErrorValidationError {
const fn context(source: ToolContextBindingError) -> Self {
Self::Context { source }
}
}
type PrivateSchemaSource = dyn StdError + Send + Sync + 'static;
#[derive(Clone)]
pub struct ToolSchemaValidationError {
private_source: Arc<PrivateSchemaSource>,
}
impl ToolSchemaValidationError {
#[must_use]
pub fn new<E>(source: E) -> Self
where
E: StdError + Send + Sync + 'static,
{
Self {
private_source: Arc::new(source),
}
}
#[must_use]
pub fn from_shared(source: Arc<PrivateSchemaSource>) -> Self {
Self {
private_source: source,
}
}
#[must_use]
pub fn private_source(&self) -> &(dyn StdError + Send + Sync + 'static) {
self.private_source.as_ref()
}
}
impl fmt::Debug for ToolSchemaValidationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolSchemaValidationError")
.field("has_private_source", &true)
.finish_non_exhaustive()
}
}
impl fmt::Display for ToolSchemaValidationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("tool schema validation failed")
}
}
impl StdError for ToolSchemaValidationError {}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ToolSchemaRole {
Input,
Output,
}
pub trait ToolSchemaRegistry: Send + Sync + 'static {
fn validate_type_schema(
&self,
reference: &SchemaReference,
role: ToolSchemaRole,
generated: &Schema,
) -> Result<(), ToolSchemaValidationError>;
fn validate_instance(
&self,
reference: &SchemaReference,
role: ToolSchemaRole,
value: &BoundedJson,
) -> Result<(), ToolSchemaValidationError>;
}
pub trait Tool: Send + Sync + 'static {
type Input: DeserializeOwned + JsonSchema + Send + 'static;
type Output: Serialize + JsonSchema + Send + 'static;
fn descriptor(&self) -> &ToolDescriptor;
fn call(
&self,
context: ToolContext,
input: Self::Input,
) -> crate::BoxFuture<'_, Result<ToolOutput<Self::Output>, ToolError>>;
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ToolReconciliationObservation {
Result(ToolResult),
Error(ToolError),
Pending {
retry_after: DurationMillis,
},
}
impl ToolReconciliationObservation {
pub const MAX_RETRY_AFTER: DurationMillis = match DurationMillis::new(3_600_000) {
Ok(value) => value,
Err(_) => panic!("one hour is a valid duration"),
};
pub fn pending(
retry_after: DurationMillis,
) -> Result<Self, ToolReconciliationObservationError> {
validate_reconciliation_retry_after(retry_after)?;
Ok(Self::Pending { retry_after })
}
pub fn validate(&self) -> Result<(), ToolReconciliationObservationError> {
match self {
Self::Result(_) | Self::Error(_) => Ok(()),
Self::Pending { retry_after } => validate_reconciliation_retry_after(*retry_after),
}
}
}
fn validate_reconciliation_retry_after(
retry_after: DurationMillis,
) -> Result<(), ToolReconciliationObservationError> {
if retry_after == DurationMillis::ZERO {
return Err(ToolReconciliationObservationError::ZeroRetryDelay);
}
if retry_after > ToolReconciliationObservation::MAX_RETRY_AFTER {
return Err(ToolReconciliationObservationError::RetryDelayTooLarge {
maximum: ToolReconciliationObservation::MAX_RETRY_AFTER,
actual: retry_after,
});
}
Ok(())
}
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolReconciliationObservationError {
#[error("tool reconciliation retry delay must be greater than zero")]
ZeroRetryDelay,
#[error("tool reconciliation retry delay {actual}ms exceeds maximum {maximum}ms")]
RetryDelayTooLarge {
maximum: DurationMillis,
actual: DurationMillis,
},
}
#[derive(Clone, Debug, Error)]
#[error("tool reconciliation probe failed: {failure}")]
pub struct ToolReconciliationProbeError {
failure: Box<Failure>,
}
impl ToolReconciliationProbeError {
pub fn new(failure: Failure) -> Result<Self, ToolReconciliationProbeErrorBuildError> {
if failure.retry_advice().requires_reconciliation() {
return Err(ToolReconciliationProbeErrorBuildError::RecursiveReconciliation);
}
if let Some(delay) = failure.retry_advice().safe_after_delay() {
validate_reconciliation_retry_after(delay)
.map_err(ToolReconciliationProbeErrorBuildError::invalid_retry)?;
}
Ok(Self {
failure: Box::new(failure),
})
}
#[must_use]
pub fn failure(&self) -> &Failure {
self.failure.as_ref()
}
fn unsupported() -> Self {
let failure = Failure::new(
FailureId::generate(),
FailureCategory::Unsupported,
FailureCode::new("stateknot.tool.reconciliation_unsupported")
.expect("static reconciliation failure code is valid"),
FailureOrigin::new("stateknot.tool")
.expect("static reconciliation failure origin is valid"),
FailureMessage::new("This tool does not implement reconciliation.")
.expect("static reconciliation failure message is valid"),
RetryAdvice::Never,
)
.expect("static reconciliation failure semantics are coherent");
Self {
failure: Box::new(failure),
}
}
}
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolReconciliationProbeErrorBuildError {
#[error("tool reconciliation probe failure cannot require reconciliation")]
RecursiveReconciliation,
#[error("tool reconciliation probe retry advice is invalid: {source}")]
InvalidRetry {
#[source]
source: ToolReconciliationObservationError,
},
}
impl ToolReconciliationProbeErrorBuildError {
const fn invalid_retry(source: ToolReconciliationObservationError) -> Self {
Self::InvalidRetry { source }
}
}
pub trait ErasedTool: Send + Sync + 'static {
fn descriptor(&self) -> &ToolDescriptor;
#[must_use]
fn supports_reconciliation(&self) -> bool {
false
}
fn call(
&self,
context: ToolContext,
input: ToolInput,
) -> crate::BoxFuture<'_, Result<ToolResult, ToolError>>;
fn reconcile(
&self,
_context: ToolReconciliationContext,
_input: ToolInput,
) -> crate::BoxFuture<'_, Result<ToolReconciliationObservation, ToolReconciliationProbeError>>
{
Box::pin(async { Err(ToolReconciliationProbeError::unsupported()) })
}
}
pub struct ToolAdapter<T, R> {
tool: T,
descriptor: ToolDescriptor,
registry: R,
}
impl<T, R> ToolAdapter<T, R>
where
T: Tool,
R: ToolSchemaRegistry,
{
pub fn new(tool: T, registry: R) -> Result<Self, ToolAdapterBuildError> {
let descriptor = tool.descriptor().clone();
let input_schema = SchemaGenerator::default().into_root_schema_for::<T::Input>();
registry
.validate_type_schema(
descriptor.input_schema(),
ToolSchemaRole::Input,
&input_schema,
)
.map_err(|source| ToolAdapterBuildError::SchemaContract {
role: ToolSchemaRole::Input,
source,
})?;
let output_schema = SchemaGenerator::default().into_root_schema_for::<T::Output>();
registry
.validate_type_schema(
descriptor.output_schema(),
ToolSchemaRole::Output,
&output_schema,
)
.map_err(|source| ToolAdapterBuildError::SchemaContract {
role: ToolSchemaRole::Output,
source,
})?;
Ok(Self {
tool,
descriptor,
registry,
})
}
#[must_use]
pub const fn tool(&self) -> &T {
&self.tool
}
#[must_use]
pub const fn registry(&self) -> &R {
&self.registry
}
#[must_use]
pub fn into_inner(self) -> (T, R) {
(self.tool, self.registry)
}
}
impl<T, R> ErasedTool for ToolAdapter<T, R>
where
T: Tool,
R: ToolSchemaRegistry,
{
fn descriptor(&self) -> &ToolDescriptor {
&self.descriptor
}
fn call(
&self,
context: ToolContext,
input: ToolInput,
) -> crate::BoxFuture<'_, Result<ToolResult, ToolError>> {
Box::pin(async move {
input
.validate_for(&context, &self.descriptor)
.map_err(|source| {
preparation_adapter_error(
&context,
&self.descriptor,
"stateknot.tool.input_binding_invalid",
"Tool input does not match the admitted invocation.",
source,
)
})?;
self.registry
.validate_instance(
self.descriptor.input_schema(),
ToolSchemaRole::Input,
input.value(),
)
.map_err(|source| {
preparation_adapter_error(
&context,
&self.descriptor,
"stateknot.tool.input_schema_invalid",
"Tool input does not satisfy its registered schema.",
source,
)
})?;
let (_, input) = input.into_parts();
let typed_input =
serde_json::from_value::<T::Input>(input.into_value()).map_err(|source| {
preparation_adapter_error(
&context,
&self.descriptor,
"stateknot.tool.input_decode_failed",
"Tool input could not be decoded into its registered type.",
source,
)
})?;
let output = match self.tool.call(context.clone(), typed_input).await {
Ok(output) => output,
Err(error) => {
return match error.validate_for(&context, &self.descriptor) {
Ok(()) => Err(error),
Err(source) => Err(invalid_tool_error(&context, &self.descriptor, source)),
};
}
};
let (typed_output, artifacts) = output.into_parts();
let output_value = serde_json::to_value(typed_output).map_err(|source| {
result_adapter_error(
&context,
&self.descriptor,
"stateknot.tool.output_encode_failed",
"Tool output could not be encoded from its registered type.",
source,
)
})?;
let bounded_output = BoundedJson::try_from_value_with_limits(
output_value,
tool_output_json_limits(&self.descriptor),
)
.map_err(|source| {
result_adapter_error(
&context,
&self.descriptor,
"stateknot.tool.output_limit_exceeded",
"Tool output exceeded its registered resource limits.",
source,
)
})?;
self.registry
.validate_instance(
self.descriptor.output_schema(),
ToolSchemaRole::Output,
&bounded_output,
)
.map_err(|source| {
result_adapter_error(
&context,
&self.descriptor,
"stateknot.tool.output_schema_invalid",
"Tool output does not satisfy its registered schema.",
source,
)
})?;
let result =
ToolResult::for_invocation(&context, &self.descriptor, bounded_output, artifacts);
result
.validate_for(&context, &self.descriptor)
.map_err(|source| {
result_adapter_error(
&context,
&self.descriptor,
"stateknot.tool.result_binding_invalid",
"Tool result does not match the admitted invocation.",
source,
)
})?;
Ok(result)
})
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ToolAdapterBuildError {
#[error("registered {role:?} tool schema rejected the generated Rust type schema: {source}")]
SchemaContract {
role: ToolSchemaRole,
#[source]
source: ToolSchemaValidationError,
},
}
fn tool_output_json_limits(descriptor: &ToolDescriptor) -> JsonLimits {
let descriptor_bytes =
usize::try_from(descriptor.limits().max_inline_result_bytes().get()).unwrap_or(usize::MAX);
let max_bytes = descriptor_bytes.min(JsonLimits::MAXIMUM.max_bytes());
JsonLimits::try_new(
max_bytes,
JsonLimits::MAXIMUM.max_depth(),
JsonLimits::MAXIMUM.max_container_entries(),
JsonLimits::MAXIMUM.max_nodes(),
JsonLimits::MAXIMUM.max_string_bytes(),
JsonLimits::MAXIMUM.max_object_key_bytes(),
)
.expect("positive descriptor bytes narrowed to static JSON hard limits are valid")
}
fn preparation_adapter_error<E>(
context: &ToolContext,
descriptor: &ToolDescriptor,
code: &str,
message: &str,
source: E,
) -> ToolError
where
E: StdError + Send + Sync + 'static,
{
let effect = if descriptor.semantics().risk() == ToolRisk::ReadOnly {
ToolExternalEffect::NotApplicable
} else {
ToolExternalEffect::NotStarted
};
adapter_error(
context,
descriptor,
FailureCategory::InvalidInput,
RetryAdvice::Never,
code,
message,
ToolErrorPhase::Preparation,
effect,
source,
)
}
fn result_adapter_error<E>(
context: &ToolContext,
descriptor: &ToolDescriptor,
code: &str,
message: &str,
source: E,
) -> ToolError
where
E: StdError + Send + Sync + 'static,
{
let effect = if descriptor.semantics().risk() == ToolRisk::ReadOnly {
ToolExternalEffect::NotApplicable
} else {
ToolExternalEffect::Applied
};
adapter_error(
context,
descriptor,
FailureCategory::Internal,
RetryAdvice::Never,
code,
message,
ToolErrorPhase::Result,
effect,
source,
)
}
fn invalid_tool_error<E>(context: &ToolContext, descriptor: &ToolDescriptor, source: E) -> ToolError
where
E: StdError + Send + Sync + 'static,
{
let (category, advice, effect) = if descriptor.semantics().risk() == ToolRisk::ReadOnly {
(
FailureCategory::Internal,
RetryAdvice::Never,
ToolExternalEffect::NotApplicable,
)
} else {
(
FailureCategory::AmbiguousExternalOutcome,
RetryAdvice::ReconcileFirst,
ToolExternalEffect::Unknown,
)
};
adapter_error(
context,
descriptor,
category,
advice,
"stateknot.tool.invalid_error_evidence",
"Tool returned failure evidence that does not match its admitted invocation.",
ToolErrorPhase::Execution,
effect,
source,
)
}
#[allow(clippy::too_many_arguments)]
fn adapter_error<E>(
context: &ToolContext,
descriptor: &ToolDescriptor,
category: FailureCategory,
advice: RetryAdvice,
code: &str,
message: &str,
phase: ToolErrorPhase,
effect: ToolExternalEffect,
source: E,
) -> ToolError
where
E: StdError + Send + Sync + 'static,
{
let failure = Failure::new(
FailureId::generate(),
category,
FailureCode::new(code).expect("static adapter failure code must be valid"),
FailureOrigin::new("stateknot.tool_adapter")
.expect("static adapter failure origin must be valid"),
FailureMessage::new(message).expect("static adapter failure message must be valid"),
advice,
)
.expect("adapter category and retry advice must be compatible")
.with_private_source(source);
ToolError::new(
failure,
phase,
effect,
ToolErrorProvenance::for_invocation(context, descriptor),
)
.expect("adapter phase and effect evidence must be compatible")
}
fn byte_count_from_usize(value: usize) -> ByteCount {
ByteCount::new(u64::try_from(value).unwrap_or(u64::MAX))
}
fn execution_count_from_usize(value: usize) -> ExecutionCount {
ExecutionCount::new(u64::try_from(value).unwrap_or(u64::MAX))
}
#[cfg(test)]
mod tests {
use std::{
future::Future,
sync::atomic::{AtomicUsize, Ordering},
task::{Context, Poll, Wake, Waker},
};
use serde_json::{Value, json, to_value};
use super::*;
use crate::{
ArtifactId, BudgetUsage, FailureBuildError, ResolvedBudget, ToolCancellationSupport,
};
const ATTEMPT_ID: &str = "01912345-6789-7abc-8def-0123456789ab";
const SECOND_ATTEMPT_ID: &str = "01912345-6789-7abc-8def-0123456789ac";
const INVOCATION_ID: &str = "01912345-6789-7abc-8def-0123456789ad";
const RUN_ID: &str = "01912345-6789-7abc-8def-0123456789ae";
const THREAD_ID: &str = "01912345-6789-7abc-8def-0123456789af";
const FAILURE_ID: &str = "01912345-6789-7abc-8def-0123456789b0";
const OBSERVED_AT: &str = "2029-12-31T23:59:59.000000Z";
fn descriptor() -> ToolDescriptor {
let fixture: Value =
serde_json::from_str(include_str!("../tests/fixtures/core-tool-v1.json")).unwrap();
serde_json::from_value(fixture["descriptors"]["valid"][0].clone()).unwrap()
}
fn descriptor_with_progress(maximum: u64) -> ToolDescriptor {
let fixture: Value =
serde_json::from_str(include_str!("../tests/fixtures/core-tool-v1.json")).unwrap();
let mut value = fixture["descriptors"]["valid"][0].clone();
value["invocation"]["max_progress_events"] = Value::from(maximum.to_string());
serde_json::from_value(value).unwrap()
}
fn remaining_budget(observed_at: Timestamp) -> BudgetRemaining {
let fixture: Value =
serde_json::from_str(include_str!("../tests/fixtures/core-budget-v1.json")).unwrap();
let resolved =
serde_json::from_value::<ResolvedBudget>(fixture["resolved"]["valid"][0].clone())
.unwrap();
resolved
.remaining(&BudgetUsage::zero(), observed_at)
.unwrap()
}
fn context_with_attempt(attempt_id: AttemptId) -> ToolContext {
let descriptor = descriptor();
let observed_at = OBSERVED_AT.parse::<Timestamp>().unwrap();
ToolContext::new(
TenantId::new("tenant-production").unwrap(),
RUN_ID.parse().unwrap(),
THREAD_ID.parse().unwrap(),
INVOCATION_ID.parse().unwrap(),
attempt_id,
&descriptor,
remaining_budget(observed_at),
DurationMillis::new(30_000).unwrap(),
observed_at,
Instant::now(),
CancellationSignal::never(),
)
.unwrap()
}
fn context() -> ToolContext {
context_with_attempt(ATTEMPT_ID.parse().unwrap())
}
fn failure(category: FailureCategory, advice: RetryAdvice) -> Failure {
Failure::new(
FAILURE_ID.parse().unwrap(),
category,
FailureCode::new("tool.execution_failed").unwrap(),
FailureOrigin::new("tool.example").unwrap(),
FailureMessage::new("The tool operation did not complete.").unwrap(),
advice,
)
.unwrap()
}
fn provenance() -> ToolErrorProvenance {
let descriptor = descriptor();
ToolErrorProvenance::new(
INVOCATION_ID.parse().unwrap(),
ATTEMPT_ID.parse().unwrap(),
descriptor.metadata().identity().clone(),
)
}
#[test]
fn context_intersects_deadlines_and_reuses_key_across_attempts() {
let first = context_with_attempt(ATTEMPT_ID.parse().unwrap());
let second = context_with_attempt(SECOND_ATTEMPT_ID.parse().unwrap());
assert_eq!(first.invocation_id(), second.invocation_id());
assert_ne!(first.attempt_id(), second.attempt_id());
assert_eq!(
first.required_idempotency_key().unwrap(),
second.required_idempotency_key().unwrap()
);
assert_eq!(
first.required_idempotency_key().unwrap().to_string(),
INVOCATION_ID
);
assert_eq!(
first.deadline(),
"2030-01-01T00:00:00.000000Z".parse().unwrap()
);
assert_eq!(first.remaining_time_at(first.deadline_instant()), None);
}
#[test]
fn context_rejects_zero_and_widened_timeouts() {
let descriptor = descriptor();
let observed_at = OBSERVED_AT.parse::<Timestamp>().unwrap();
let make = |timeout| {
ToolContext::new(
TenantId::new("tenant-production").unwrap(),
RUN_ID.parse().unwrap(),
THREAD_ID.parse().unwrap(),
INVOCATION_ID.parse().unwrap(),
ATTEMPT_ID.parse().unwrap(),
&descriptor,
remaining_budget(observed_at),
timeout,
observed_at,
Instant::now(),
CancellationSignal::never(),
)
};
assert_eq!(
make(DurationMillis::ZERO).unwrap_err(),
ToolContextError::ZeroEffectiveTimeout
);
assert!(matches!(
make(DurationMillis::new(30_001).unwrap()),
Err(ToolContextError::TimeoutExceedsDescriptor { .. })
));
}
#[test]
fn reconciliation_context_preserves_original_identity_and_is_finite() {
let descriptor = descriptor();
let observed_at = OBSERVED_AT.parse::<Timestamp>().unwrap();
let handle = ToolRecoveryHandle::new(
FailureOrigin::new("protocol.a2a.task").unwrap(),
Digest::sha256(b"agent-card"),
"remote-task-42",
)
.unwrap();
let origin_event_id = FAILURE_ID.parse().unwrap();
let context = ToolReconciliationContext::new(
TenantId::new("tenant-production").unwrap(),
RUN_ID.parse().unwrap(),
THREAD_ID.parse().unwrap(),
INVOCATION_ID.parse().unwrap(),
ATTEMPT_ID.parse().unwrap(),
&descriptor,
DurationMillis::new(30_000).unwrap(),
observed_at,
Instant::now(),
"2030-01-01T00:00:00.000000Z".parse().unwrap(),
CancellationSignal::never(),
)
.unwrap()
.with_durable_recovery(origin_event_id, Some(handle.clone()));
context.validate_for(&descriptor).unwrap();
assert_eq!(context.invocation_id().to_string(), INVOCATION_ID);
assert_eq!(context.attempt_id().to_string(), ATTEMPT_ID);
assert_eq!(
context.idempotency_key().unwrap().to_string(),
INVOCATION_ID
);
assert_eq!(
context.deadline(),
"2030-01-01T00:00:00.000000Z".parse().unwrap()
);
assert_eq!(context.origin_event_id(), Some(origin_event_id));
assert_eq!(context.recovery_handle(), Some(&handle));
assert!(format!("{context:?}").contains("has_idempotency_key: true"));
}
#[test]
fn reconciliation_polling_and_probe_failures_are_bounded() {
assert_eq!(
ToolReconciliationObservation::pending(DurationMillis::ZERO).unwrap_err(),
ToolReconciliationObservationError::ZeroRetryDelay
);
let excessive = DurationMillis::new(3_600_001).unwrap();
assert!(matches!(
ToolReconciliationObservation::pending(excessive),
Err(ToolReconciliationObservationError::RetryDelayTooLarge { .. })
));
let ambiguous = failure(
FailureCategory::AmbiguousExternalOutcome,
RetryAdvice::ReconcileFirst,
);
assert_eq!(
ToolReconciliationProbeError::new(ambiguous).unwrap_err(),
ToolReconciliationProbeErrorBuildError::RecursiveReconciliation
);
let zero_retry = failure(
FailureCategory::DependencyUnavailable,
RetryAdvice::SafeAfter {
delay: DurationMillis::ZERO,
},
);
assert!(matches!(
ToolReconciliationProbeError::new(zero_retry),
Err(ToolReconciliationProbeErrorBuildError::InvalidRetry { .. })
));
}
#[test]
fn input_requires_an_object_and_binds_schema_and_limits() {
let descriptor = descriptor();
assert_eq!(
ToolInput::new(
descriptor.input_schema().clone(),
BoundedJson::try_from_value(json!([1, 2])).unwrap(),
),
Err(ToolInputError::ObjectRootRequired)
);
let input = ToolInput::new(
descriptor.input_schema().clone(),
BoundedJson::try_from_value(json!({ "amount": 42 })).unwrap(),
)
.unwrap();
input.validate_for(&context(), &descriptor).unwrap();
assert!(!format!("{input:?}").contains("amount"));
}
fn artifact_value() -> Value {
let fixture: Value =
serde_json::from_str(include_str!("../tests/fixtures/core-artifact-v1.json")).unwrap();
fixture["artifact_refs"]["valid"][0].clone()
}
fn bound_artifact(tenant: &str, artifact_id: ArtifactId) -> ArtifactRef {
let descriptor = descriptor();
let mut value = artifact_value();
value["identity"]["tenant_id"] = Value::from(tenant);
value["identity"]["artifact_id"] = Value::from(artifact_id.to_string());
value["provenance"]["principal"] =
to_value(descriptor.metadata().identity().owner()).unwrap();
value["provenance"]["capability"] =
to_value(descriptor.metadata().identity().capability()).unwrap();
value["provenance"]["run_id"] = Value::from(RUN_ID);
serde_json::from_value(value).unwrap()
}
#[test]
fn artifacts_are_unique_bounded_and_checked_against_tenant() {
let first = bound_artifact("tenant-production", ArtifactId::generate());
assert_eq!(
ToolArtifacts::try_new([first.clone(), first]),
Err(ToolArtifactsError::DuplicateIdentity)
);
let too_many = (0..=ToolArtifacts::MAX_LEN)
.map(|_| bound_artifact("tenant-production", ArtifactId::generate()));
assert!(matches!(
ToolArtifacts::try_new(too_many),
Err(ToolArtifactsError::TooMany { .. })
));
let descriptor = descriptor();
let context = context();
let artifacts =
ToolArtifacts::try_new([bound_artifact("tenant-other", ArtifactId::generate())])
.unwrap();
let result = ToolResult::for_invocation(
&context,
&descriptor,
BoundedJson::try_from_value(json!({ "accepted": true })).unwrap(),
artifacts,
);
assert!(matches!(
result.validate_for(&context, &descriptor),
Err(ToolResultValidationError::ArtifactTenantMismatch { .. })
));
}
#[test]
fn tool_error_requires_exact_unknown_effect_and_ambiguity_pair() {
assert_eq!(
ToolError::new(
failure(FailureCategory::Internal, RetryAdvice::Never),
ToolErrorPhase::Execution,
ToolExternalEffect::Unknown,
provenance(),
)
.unwrap_err(),
ToolErrorBuildError::UnknownEffectRequiresAmbiguousFailure
);
let ambiguous = ToolError::new(
failure(
FailureCategory::AmbiguousExternalOutcome,
RetryAdvice::ReconcileFirst,
),
ToolErrorPhase::Execution,
ToolExternalEffect::Unknown,
provenance(),
)
.unwrap();
ambiguous.validate_for(&context(), &descriptor()).unwrap();
assert_eq!(ambiguous.external_effect(), ToolExternalEffect::Unknown);
assert!(matches!(
Failure::new(
FailureId::generate(),
FailureCategory::AmbiguousExternalOutcome,
FailureCode::new("tool.ambiguous").unwrap(),
FailureOrigin::new("tool.example").unwrap(),
FailureMessage::new("The external outcome is unknown.").unwrap(),
RetryAdvice::Never,
),
Err(FailureBuildError::AmbiguousOutcomeRequiresReconciliation)
));
}
#[test]
fn recovery_handles_are_bounded_redacted_and_only_bind_unknown_outcomes() {
let handle = ToolRecoveryHandle::new(
FailureOrigin::new("protocol.a2a.task").unwrap(),
Digest::sha256(b"agent-card"),
"remote-task-secret-42",
)
.unwrap();
assert!(!format!("{handle:?}").contains("remote-task-secret-42"));
assert_eq!(
ToolRecoveryHandle::new(
FailureOrigin::new("protocol.a2a.task").unwrap(),
Digest::sha256(b"agent-card"),
" remote-task",
)
.unwrap_err(),
ToolRecoveryHandleError::OpaqueIdBoundaryWhitespace
);
let ambiguous = ToolError::new(
failure(
FailureCategory::AmbiguousExternalOutcome,
RetryAdvice::ReconcileFirst,
),
ToolErrorPhase::Execution,
ToolExternalEffect::Unknown,
provenance(),
)
.unwrap()
.with_recovery_handle(handle.clone())
.unwrap();
assert_eq!(ambiguous.recovery_handle(), Some(&handle));
let encoded = to_value(&ambiguous).unwrap();
assert_eq!(
encoded["recovery_handle"]["opaque_id"],
"remote-task-secret-42"
);
let decoded: ToolError = serde_json::from_value(encoded).unwrap();
assert_eq!(decoded.recovery_handle(), Some(&handle));
let known = ToolError::new(
failure(FailureCategory::Internal, RetryAdvice::Never),
ToolErrorPhase::Execution,
ToolExternalEffect::Applied,
provenance(),
)
.unwrap();
assert_eq!(
known.with_recovery_handle(handle).unwrap_err(),
ToolErrorBuildError::RecoveryHandleRequiresUnknownEffect
);
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct CaptureInput {
amount: u64,
}
#[derive(Debug, JsonSchema, Serialize)]
#[serde(deny_unknown_fields)]
struct CaptureOutput {
accepted: bool,
key: String,
}
struct CaptureTool {
descriptor: ToolDescriptor,
}
impl Tool for CaptureTool {
type Input = CaptureInput;
type Output = CaptureOutput;
fn descriptor(&self) -> &ToolDescriptor {
&self.descriptor
}
fn call(
&self,
context: ToolContext,
input: Self::Input,
) -> crate::BoxFuture<'_, Result<ToolOutput<Self::Output>, ToolError>> {
let key = context.required_idempotency_key().unwrap().to_string();
Box::pin(async move {
Ok(ToolOutput::inline(CaptureOutput {
accepted: input.amount > 0,
key,
}))
})
}
}
#[derive(Default)]
struct AcceptingRegistry {
type_validations: AtomicUsize,
instance_validations: AtomicUsize,
}
impl ToolSchemaRegistry for AcceptingRegistry {
fn validate_type_schema(
&self,
_: &SchemaReference,
_: ToolSchemaRole,
_: &Schema,
) -> Result<(), ToolSchemaValidationError> {
self.type_validations.fetch_add(1, Ordering::Relaxed);
Ok(())
}
fn validate_instance(
&self,
_: &SchemaReference,
_: ToolSchemaRole,
_: &BoundedJson,
) -> Result<(), ToolSchemaValidationError> {
self.instance_validations.fetch_add(1, Ordering::Relaxed);
Ok(())
}
}
struct NoopWake;
impl Wake for NoopWake {
fn wake(self: Arc<Self>) {}
}
fn poll_ready<F>(future: F) -> F::Output
where
F: Future,
{
let waker = Waker::from(Arc::new(NoopWake));
let mut context = Context::from_waker(&waker);
let mut future = std::pin::pin!(future);
match future.as_mut().poll(&mut context) {
Poll::Ready(output) => output,
Poll::Pending => panic!("test future unexpectedly remained pending"),
}
}
#[derive(Default)]
struct RecordingProgressSink {
events: Mutex<Vec<ToolProgressEvent>>,
}
impl ToolProgressSink for RecordingProgressSink {
fn emit(
&self,
event: ToolProgressEvent,
) -> crate::BoxFuture<'_, Result<(), ToolProgressSinkError>> {
Box::pin(async move {
self.events.lock().unwrap().push(event);
Ok(())
})
}
}
struct PendingProgressSink;
impl ToolProgressSink for PendingProgressSink {
fn emit(
&self,
_: ToolProgressEvent,
) -> crate::BoxFuture<'_, Result<(), ToolProgressSinkError>> {
Box::pin(std::future::pending())
}
}
struct FailingProgressSink;
impl ToolProgressSink for FailingProgressSink {
fn emit(
&self,
_: ToolProgressEvent,
) -> crate::BoxFuture<'_, Result<(), ToolProgressSinkError>> {
Box::pin(async {
Err(ToolProgressSinkError::new(std::io::Error::other(
"private sink detail",
)))
})
}
}
fn progress_context(
descriptor: &ToolDescriptor,
sink: Arc<dyn ToolProgressSink>,
) -> ToolContext {
let observed_at = OBSERVED_AT.parse::<Timestamp>().unwrap();
ToolContext::new_with_progress(
TenantId::new("tenant-production").unwrap(),
RUN_ID.parse().unwrap(),
THREAD_ID.parse().unwrap(),
INVOCATION_ID.parse().unwrap(),
ATTEMPT_ID.parse().unwrap(),
descriptor,
remaining_budget(observed_at),
DurationMillis::new(30_000).unwrap(),
observed_at,
Instant::now(),
CancellationSignal::never(),
sink,
)
.unwrap()
}
#[test]
fn progress_reporter_orders_normalizes_and_bounds_events() {
let descriptor = descriptor_with_progress(2);
let sink = Arc::new(RecordingProgressSink::default());
let context = progress_context(&descriptor, sink.clone());
let reporter = context.progress().unwrap();
let first = poll_ready(
reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(1), None).unwrap()),
)
.unwrap();
let second = poll_ready(reporter.emit(
ToolProgressUpdate::new(ExecutionCount::new(2), Some(ExecutionCount::new(10))).unwrap(),
))
.unwrap();
assert_eq!(first.sequence(), ExecutionCount::ZERO);
assert_eq!(second.sequence(), ExecutionCount::new(1));
assert_eq!(second.update().total(), Some(ExecutionCount::new(10)));
first.validate_for(&context, &descriptor).unwrap();
second.validate_for(&context, &descriptor).unwrap();
let outside_capacity = ToolProgressEvent::new(
first.provenance().clone(),
ExecutionCount::new(2),
first.update(),
);
assert!(matches!(
outside_capacity.validate_for(&context, &descriptor),
Err(ToolProgressEventValidationError::SequenceLimitExceeded { .. })
));
assert_eq!(sink.events.lock().unwrap().as_slice(), &[first, second]);
assert!(matches!(
poll_ready(
reporter.emit(
ToolProgressUpdate::new(ExecutionCount::new(3), Some(ExecutionCount::new(10)),)
.unwrap(),
)
),
Err(ToolProgressError::MaximumReached { .. })
));
}
#[test]
fn progress_reporter_rejects_reordering_and_changed_totals() {
let descriptor = descriptor_with_progress(4);
let context = progress_context(&descriptor, Arc::new(RecordingProgressSink::default()));
let reporter = context.progress().unwrap();
poll_ready(reporter.emit(
ToolProgressUpdate::new(ExecutionCount::new(2), Some(ExecutionCount::new(10))).unwrap(),
))
.unwrap();
assert!(matches!(
poll_ready(
reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(2), None).unwrap(),)
),
Err(ToolProgressError::NotIncreasing { .. })
));
assert!(matches!(
poll_ready(
reporter.emit(
ToolProgressUpdate::new(ExecutionCount::new(3), Some(ExecutionCount::new(11)),)
.unwrap(),
)
),
Err(ToolProgressError::TotalChanged { .. })
));
}
#[test]
fn progress_failure_or_dropped_future_poison_the_reporter() {
let descriptor = descriptor_with_progress(4);
let failed = progress_context(&descriptor, Arc::new(FailingProgressSink));
let error = poll_ready(
failed
.progress()
.unwrap()
.emit(ToolProgressUpdate::new(ExecutionCount::new(1), None).unwrap()),
)
.unwrap_err();
assert!(matches!(error, ToolProgressError::Sink { .. }));
assert!(!format!("{error:?}").contains("private sink detail"));
assert!(matches!(
poll_ready(
failed
.progress()
.unwrap()
.emit(ToolProgressUpdate::new(ExecutionCount::new(2), None).unwrap(),)
),
Err(ToolProgressError::StatePoisoned)
));
let pending = progress_context(&descriptor, Arc::new(PendingProgressSink));
let reporter = pending.progress().unwrap();
let mut first =
reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(1), None).unwrap());
let waker = Waker::from(Arc::new(NoopWake));
let mut task_context = Context::from_waker(&waker);
assert!(matches!(
first.as_mut().poll(&mut task_context),
Poll::Pending
));
assert!(matches!(
poll_ready(
reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(2), None).unwrap(),)
),
Err(ToolProgressError::ConcurrentEmission)
));
drop(first);
assert!(matches!(
poll_ready(
reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(2), None).unwrap(),)
),
Err(ToolProgressError::StatePoisoned)
));
}
#[test]
fn progress_updates_reject_impossible_totals() {
assert_eq!(
ToolProgressUpdate::new(ExecutionCount::ZERO, Some(ExecutionCount::ZERO)),
Err(ToolProgressUpdateError::ZeroTotal)
);
assert!(matches!(
ToolProgressUpdate::new(ExecutionCount::new(2), Some(ExecutionCount::new(1)),),
Err(ToolProgressUpdateError::CompletedExceedsTotal { .. })
));
}
#[test]
fn typed_adapter_validates_both_schemas_and_is_object_safe() {
fn accept_object(_: &dyn ErasedTool) {}
fn assert_send_sync<T: Send + Sync>() {}
let adapter = ToolAdapter::new(
CaptureTool {
descriptor: descriptor(),
},
AcceptingRegistry::default(),
)
.unwrap();
assert_eq!(
adapter.registry().type_validations.load(Ordering::Relaxed),
2
);
accept_object(&adapter);
assert_send_sync::<ToolContext>();
assert_send_sync::<ToolResult>();
assert_send_sync::<ToolError>();
let descriptor = adapter.descriptor().clone();
let context = context();
let input = ToolInput::new(
descriptor.input_schema().clone(),
BoundedJson::try_from_value(json!({ "amount": 42 })).unwrap(),
)
.unwrap();
let result = poll_ready(ErasedTool::call(&adapter, context.clone(), input)).unwrap();
result.validate_for(&context, &descriptor).unwrap();
assert_eq!(result.output().as_value()["accepted"], true);
assert_eq!(result.output().as_value()["key"], INVOCATION_ID);
assert_eq!(
adapter
.registry()
.instance_validations
.load(Ordering::Relaxed),
2
);
}
#[test]
fn wire_contracts_are_closed_and_redact_inline_values() {
let descriptor = descriptor();
let context = context();
let result = ToolResult::for_invocation(
&context,
&descriptor,
BoundedJson::try_from_value(json!({ "secret": "do-not-log" })).unwrap(),
ToolArtifacts::empty(),
);
let value = to_value(&result).unwrap();
let decoded = serde_json::from_value::<ToolResult>(value.clone()).unwrap();
assert_eq!(to_value(decoded).unwrap(), value);
assert!(!format!("{result:?}").contains("do-not-log"));
for schema in [
to_value(schemars::schema_for!(ToolProgressUpdate)).unwrap(),
to_value(schemars::schema_for!(ToolProgressProvenance)).unwrap(),
to_value(schemars::schema_for!(ToolProgressEvent)).unwrap(),
to_value(schemars::schema_for!(ToolInput)).unwrap(),
to_value(schemars::schema_for!(ToolResultProvenance)).unwrap(),
to_value(schemars::schema_for!(ToolResult)).unwrap(),
to_value(schemars::schema_for!(ToolErrorProvenance)).unwrap(),
to_value(schemars::schema_for!(ToolError)).unwrap(),
] {
assert_eq!(schema["type"], "object");
assert_eq!(schema["additionalProperties"], false);
}
let mut invalid = value;
invalid["provider_payload"] = json!({ "secret": true });
assert!(serde_json::from_value::<ToolResult>(invalid).is_err());
assert_eq!(
descriptor.invocation().cancellation(),
ToolCancellationSupport::Cooperative
);
}
}