1use std::{
7 error::Error as StdError,
8 fmt,
9 sync::{Arc, Mutex},
10 time::{Duration, Instant},
11};
12
13use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
14use serde::{Deserialize, Deserializer, Serialize, Serializer, de, de::DeserializeOwned};
15use thiserror::Error;
16
17use crate::{
18 ArtifactRef, AttemptId, BoundedJson, BudgetRemaining, ByteCount, CancellationSignal,
19 CapabilityIdentity, CapabilityReference, Digest, DurationMillis, EventId, ExecutionCount,
20 Failure, FailureCategory, FailureCode, FailureId, FailureMessage, FailureOrigin, InvocationId,
21 JsonLimits, PrincipalIdentity, RetryAdvice, RunId, SchemaReference, TenantId, ThreadId,
22 Timestamp, ToolDescriptor, ToolExecutionLimits, ToolIdempotency, ToolRisk,
23};
24
25#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
33pub struct ToolIdempotencyKey(InvocationId);
34
35impl ToolIdempotencyKey {
36 #[must_use]
38 pub const fn from_invocation_id(invocation_id: InvocationId) -> Self {
39 Self(invocation_id)
40 }
41
42 #[must_use]
44 pub const fn invocation_id(self) -> InvocationId {
45 self.0
46 }
47}
48
49impl fmt::Display for ToolIdempotencyKey {
50 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51 fmt::Display::fmt(&self.0, formatter)
52 }
53}
54
55impl fmt::Debug for ToolIdempotencyKey {
56 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
57 formatter.write_str("ToolIdempotencyKey([REDACTED])")
58 }
59}
60
61#[derive(Clone, Eq, PartialEq)]
67pub struct ToolRecoveryHandle {
68 namespace: FailureOrigin,
69 binding: Digest,
70 opaque_id: Box<str>,
71}
72
73impl ToolRecoveryHandle {
74 pub const MAX_OPAQUE_ID_BYTES: usize = 1024;
76
77 pub fn new(
84 namespace: FailureOrigin,
85 binding: Digest,
86 opaque_id: impl Into<String>,
87 ) -> Result<Self, ToolRecoveryHandleError> {
88 let opaque_id = opaque_id.into();
89 validate_recovery_opaque_id(&opaque_id)?;
90 Ok(Self {
91 namespace,
92 binding,
93 opaque_id: opaque_id.into_boxed_str(),
94 })
95 }
96
97 #[must_use]
99 pub const fn namespace(&self) -> &FailureOrigin {
100 &self.namespace
101 }
102
103 #[must_use]
105 pub const fn binding(&self) -> Digest {
106 self.binding
107 }
108
109 #[must_use]
111 pub fn opaque_id(&self) -> &str {
112 &self.opaque_id
113 }
114}
115
116fn validate_recovery_opaque_id(value: &str) -> Result<(), ToolRecoveryHandleError> {
117 if value.is_empty() {
118 return Err(ToolRecoveryHandleError::EmptyOpaqueId);
119 }
120 if value.len() > ToolRecoveryHandle::MAX_OPAQUE_ID_BYTES {
121 return Err(ToolRecoveryHandleError::OpaqueIdTooLong {
122 maximum: ToolRecoveryHandle::MAX_OPAQUE_ID_BYTES,
123 actual: value.len(),
124 });
125 }
126 if value.chars().next().is_some_and(char::is_whitespace)
127 || value.chars().next_back().is_some_and(char::is_whitespace)
128 {
129 return Err(ToolRecoveryHandleError::OpaqueIdBoundaryWhitespace);
130 }
131 if value.chars().any(|scalar| {
132 let code_point = scalar as u32;
133 scalar.is_control()
134 || (0xfdd0..=0xfdef).contains(&code_point)
135 || code_point & 0xfffe == 0xfffe
136 }) {
137 return Err(ToolRecoveryHandleError::OpaqueIdDisallowedCodePoint);
138 }
139 Ok(())
140}
141
142impl fmt::Debug for ToolRecoveryHandle {
143 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
144 formatter
145 .debug_struct("ToolRecoveryHandle")
146 .field("namespace", &self.namespace)
147 .field("binding", &self.binding)
148 .field("opaque_id_bytes", &self.opaque_id.len())
149 .finish_non_exhaustive()
150 }
151}
152
153#[derive(Deserialize, JsonSchema, Serialize)]
154#[serde(deny_unknown_fields)]
155struct ToolRecoveryHandleWire {
156 namespace: FailureOrigin,
157 binding: Digest,
158 opaque_id: String,
159}
160
161impl Serialize for ToolRecoveryHandle {
162 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
163 where
164 S: Serializer,
165 {
166 ToolRecoveryHandleWire {
167 namespace: self.namespace.clone(),
168 binding: self.binding,
169 opaque_id: self.opaque_id.to_string(),
170 }
171 .serialize(serializer)
172 }
173}
174
175impl<'de> Deserialize<'de> for ToolRecoveryHandle {
176 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
177 where
178 D: Deserializer<'de>,
179 {
180 let wire = ToolRecoveryHandleWire::deserialize(deserializer)?;
181 Self::new(wire.namespace, wire.binding, wire.opaque_id).map_err(de::Error::custom)
182 }
183}
184
185impl JsonSchema for ToolRecoveryHandle {
186 fn schema_name() -> std::borrow::Cow<'static, str> {
187 "ToolRecoveryHandle".into()
188 }
189
190 fn schema_id() -> std::borrow::Cow<'static, str> {
191 concat!(module_path!(), "::ToolRecoveryHandle").into()
192 }
193
194 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
195 ToolRecoveryHandleWire::json_schema(generator)
196 }
197}
198
199#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
201#[non_exhaustive]
202pub enum ToolRecoveryHandleError {
203 #[error("tool recovery opaque identifier must not be empty")]
205 EmptyOpaqueId,
206 #[error("tool recovery opaque identifier is {actual} bytes; maximum is {maximum}")]
208 OpaqueIdTooLong {
209 maximum: usize,
211 actual: usize,
213 },
214 #[error("tool recovery opaque identifier must not have boundary whitespace")]
216 OpaqueIdBoundaryWhitespace,
217 #[error("tool recovery opaque identifier contains a disallowed code point")]
219 OpaqueIdDisallowedCodePoint,
220}
221
222#[derive(Clone)]
230pub struct ToolReconciliationContext {
231 tenant_id: TenantId,
232 run_id: RunId,
233 thread_id: ThreadId,
234 invocation_id: InvocationId,
235 attempt_id: AttemptId,
236 tool: CapabilityIdentity,
237 idempotency: ToolIdempotency,
238 idempotency_key: Option<ToolIdempotencyKey>,
239 observed_at: Timestamp,
240 deadline: Timestamp,
241 deadline_instant: Instant,
242 effective_timeout: DurationMillis,
243 cancellation: CancellationSignal,
244 origin_event_id: Option<EventId>,
245 recovery_handle: Option<ToolRecoveryHandle>,
246 max_inline_result_bytes: ByteCount,
247 max_artifacts: ExecutionCount,
248 max_total_artifact_bytes: ByteCount,
249}
250
251impl ToolReconciliationContext {
252 #[allow(clippy::too_many_arguments)]
259 pub fn new(
260 tenant_id: TenantId,
261 run_id: RunId,
262 thread_id: ThreadId,
263 invocation_id: InvocationId,
264 attempt_id: AttemptId,
265 descriptor: &ToolDescriptor,
266 effective_timeout: DurationMillis,
267 observed_at: Timestamp,
268 observed_instant: Instant,
269 run_deadline: Timestamp,
270 cancellation: CancellationSignal,
271 ) -> Result<Self, ToolReconciliationContextError> {
272 if !descriptor.semantics().supports_status_query() {
273 return Err(ToolReconciliationContextError::StatusQueryUnsupported);
274 }
275 if effective_timeout == DurationMillis::ZERO {
276 return Err(ToolReconciliationContextError::ZeroEffectiveTimeout);
277 }
278 let descriptor_timeout = descriptor.limits().timeout();
279 if effective_timeout > descriptor_timeout {
280 return Err(ToolReconciliationContextError::TimeoutExceedsDescriptor {
281 descriptor: descriptor_timeout,
282 actual: effective_timeout,
283 });
284 }
285
286 let run_remaining_micros = i128::from(run_deadline.unix_micros())
287 .checked_sub(i128::from(observed_at.unix_micros()))
288 .expect("subtracting two i64 timestamps cannot overflow i128");
289 if run_remaining_micros <= 0 {
290 return Err(ToolReconciliationContextError::DeadlineReached {
291 deadline: run_deadline,
292 observed_at,
293 });
294 }
295 let timeout_micros = i128::from(effective_timeout.as_i64()) * 1_000;
296 let remaining_micros = run_remaining_micros.min(timeout_micros);
297 let deadline_micros = i128::from(observed_at.unix_micros()) + remaining_micros;
298 let deadline_micros = i64::try_from(deadline_micros)
299 .expect("a reconciliation deadline bounded by a valid run deadline fits i64");
300 let deadline = Timestamp::from_unix_micros(deadline_micros)
301 .expect("a reconciliation deadline bounded by a valid run deadline is valid");
302 let remaining_micros = u64::try_from(remaining_micros)
303 .expect("a positive supported timestamp distance fits u64 microseconds");
304 let remaining = Duration::from_micros(remaining_micros);
305 let deadline_instant = observed_instant
306 .checked_add(remaining)
307 .ok_or(ToolReconciliationContextError::MonotonicDeadlineOutOfRange { remaining })?;
308
309 let idempotency = descriptor.semantics().idempotency();
310 let idempotency_key = descriptor
311 .semantics()
312 .requires_idempotency_key()
313 .then_some(ToolIdempotencyKey::from_invocation_id(invocation_id));
314 Ok(Self {
315 tenant_id,
316 run_id,
317 thread_id,
318 invocation_id,
319 attempt_id,
320 tool: descriptor.metadata().identity().clone(),
321 idempotency,
322 idempotency_key,
323 observed_at,
324 deadline,
325 deadline_instant,
326 effective_timeout,
327 cancellation,
328 origin_event_id: None,
329 recovery_handle: None,
330 max_inline_result_bytes: descriptor.limits().max_inline_result_bytes(),
331 max_artifacts: descriptor.limits().max_artifacts(),
332 max_total_artifact_bytes: descriptor.limits().max_total_artifact_bytes(),
333 })
334 }
335
336 #[must_use]
343 pub fn narrow_artifact_limits(mut self, limits: &ToolExecutionLimits) -> Self {
344 self.max_inline_result_bytes = self
345 .max_inline_result_bytes
346 .min(limits.max_inline_result_bytes());
347 self.max_artifacts = self.max_artifacts.min(limits.max_artifacts());
348 self.max_total_artifact_bytes = self
349 .max_total_artifact_bytes
350 .min(limits.max_total_artifact_bytes());
351 self
352 }
353
354 #[must_use]
361 pub fn with_durable_recovery(
362 mut self,
363 origin_event_id: EventId,
364 recovery_handle: Option<ToolRecoveryHandle>,
365 ) -> Self {
366 self.origin_event_id = Some(origin_event_id);
367 self.recovery_handle = recovery_handle;
368 self
369 }
370
371 #[must_use]
373 pub const fn tenant_id(&self) -> &TenantId {
374 &self.tenant_id
375 }
376
377 #[must_use]
379 pub const fn run_id(&self) -> RunId {
380 self.run_id
381 }
382
383 #[must_use]
385 pub const fn thread_id(&self) -> ThreadId {
386 self.thread_id
387 }
388
389 #[must_use]
391 pub const fn invocation_id(&self) -> InvocationId {
392 self.invocation_id
393 }
394
395 #[must_use]
397 pub const fn attempt_id(&self) -> AttemptId {
398 self.attempt_id
399 }
400
401 #[must_use]
403 pub const fn tool(&self) -> &CapabilityIdentity {
404 &self.tool
405 }
406
407 #[must_use]
409 pub const fn idempotency(&self) -> ToolIdempotency {
410 self.idempotency
411 }
412
413 #[must_use]
415 pub const fn idempotency_key(&self) -> Option<ToolIdempotencyKey> {
416 self.idempotency_key
417 }
418
419 #[must_use]
421 pub const fn observed_at(&self) -> Timestamp {
422 self.observed_at
423 }
424
425 #[must_use]
427 pub const fn deadline(&self) -> Timestamp {
428 self.deadline
429 }
430
431 #[must_use]
433 pub const fn deadline_instant(&self) -> Instant {
434 self.deadline_instant
435 }
436
437 #[must_use]
439 pub const fn effective_timeout(&self) -> DurationMillis {
440 self.effective_timeout
441 }
442
443 #[must_use]
445 pub const fn cancellation(&self) -> &CancellationSignal {
446 &self.cancellation
447 }
448
449 #[must_use]
451 pub const fn origin_event_id(&self) -> Option<EventId> {
452 self.origin_event_id
453 }
454
455 #[must_use]
457 pub const fn recovery_handle(&self) -> Option<&ToolRecoveryHandle> {
458 self.recovery_handle.as_ref()
459 }
460
461 #[must_use]
463 pub const fn max_artifacts(&self) -> ExecutionCount {
464 self.max_artifacts
465 }
466
467 #[must_use]
469 pub const fn max_inline_result_bytes(&self) -> ByteCount {
470 self.max_inline_result_bytes
471 }
472
473 #[must_use]
475 pub const fn max_total_artifact_bytes(&self) -> ByteCount {
476 self.max_total_artifact_bytes
477 }
478
479 #[must_use]
481 pub fn stop_reason_at(&self, observed_instant: Instant) -> Option<ToolStopReason> {
482 if self.cancellation.is_cancelled() {
483 Some(ToolStopReason::Cancelled)
484 } else if self
485 .deadline_instant
486 .checked_duration_since(observed_instant)
487 .filter(|remaining| !remaining.is_zero())
488 .is_none()
489 {
490 Some(ToolStopReason::DeadlineExceeded)
491 } else {
492 None
493 }
494 }
495
496 pub fn validate_for(
498 &self,
499 descriptor: &ToolDescriptor,
500 ) -> Result<(), ToolReconciliationContextBindingError> {
501 if !descriptor.semantics().supports_status_query() {
502 return Err(ToolReconciliationContextBindingError::StatusQueryUnsupported);
503 }
504 let expected_tool = descriptor.metadata().identity();
505 if &self.tool != expected_tool {
506 return Err(
507 ToolReconciliationContextBindingError::ToolIdentityMismatch {
508 expected: Box::new(expected_tool.clone()),
509 actual: Box::new(self.tool.clone()),
510 },
511 );
512 }
513 let expected_idempotency = descriptor.semantics().idempotency();
514 if self.idempotency != expected_idempotency {
515 return Err(ToolReconciliationContextBindingError::IdempotencyMismatch {
516 expected: expected_idempotency,
517 actual: self.idempotency,
518 });
519 }
520 if self.effective_timeout > descriptor.limits().timeout() {
521 return Err(
522 ToolReconciliationContextBindingError::TimeoutExceedsDescriptor {
523 descriptor: descriptor.limits().timeout(),
524 actual: self.effective_timeout,
525 },
526 );
527 }
528 let key_is_valid = matches!(
529 (self.idempotency, self.idempotency_key),
530 (ToolIdempotency::RequiredKey, Some(key)) if key.invocation_id() == self.invocation_id
531 ) || (self.idempotency != ToolIdempotency::RequiredKey
532 && self.idempotency_key.is_none());
533 if !key_is_valid {
534 return Err(ToolReconciliationContextBindingError::InvalidIdempotencyKeyBinding);
535 }
536 Ok(())
537 }
538}
539
540impl fmt::Debug for ToolReconciliationContext {
541 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
542 formatter
543 .debug_struct("ToolReconciliationContext")
544 .field("tenant_id", &self.tenant_id)
545 .field("run_id", &self.run_id)
546 .field("thread_id", &self.thread_id)
547 .field("invocation_id", &self.invocation_id)
548 .field("attempt_id", &self.attempt_id)
549 .field("tool", &self.tool)
550 .field("idempotency", &self.idempotency)
551 .field("has_idempotency_key", &self.idempotency_key.is_some())
552 .field("observed_at", &self.observed_at)
553 .field("deadline", &self.deadline)
554 .field("effective_timeout", &self.effective_timeout)
555 .field("cancelled", &self.cancellation.is_cancelled())
556 .field("has_origin_event", &self.origin_event_id.is_some())
557 .field("has_recovery_handle", &self.recovery_handle.is_some())
558 .finish_non_exhaustive()
559 }
560}
561
562#[derive(Clone, Debug, Eq, Error, PartialEq)]
564#[non_exhaustive]
565pub enum ToolReconciliationContextError {
566 #[error("tool descriptor does not support reconciliation status queries")]
568 StatusQueryUnsupported,
569 #[error("tool reconciliation effective timeout must be greater than zero")]
571 ZeroEffectiveTimeout,
572 #[error("tool reconciliation timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
574 TimeoutExceedsDescriptor {
575 descriptor: DurationMillis,
577 actual: DurationMillis,
579 },
580 #[error("tool reconciliation deadline {deadline} was reached at {observed_at}")]
582 DeadlineReached {
583 deadline: Timestamp,
585 observed_at: Timestamp,
587 },
588 #[error("tool reconciliation monotonic deadline is out of range after {remaining:?}")]
590 MonotonicDeadlineOutOfRange {
591 remaining: Duration,
593 },
594}
595
596#[derive(Clone, Debug, Eq, Error, PartialEq)]
598#[non_exhaustive]
599pub enum ToolReconciliationContextBindingError {
600 #[error("tool descriptor does not support reconciliation status queries")]
602 StatusQueryUnsupported,
603 #[error("tool reconciliation identity {actual:?} does not match descriptor {expected:?}")]
605 ToolIdentityMismatch {
606 expected: Box<CapabilityIdentity>,
608 actual: Box<CapabilityIdentity>,
610 },
611 #[error("tool reconciliation idempotency {actual:?} does not match descriptor {expected:?}")]
613 IdempotencyMismatch {
614 expected: ToolIdempotency,
616 actual: ToolIdempotency,
618 },
619 #[error("tool reconciliation timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
621 TimeoutExceedsDescriptor {
622 descriptor: DurationMillis,
624 actual: DurationMillis,
626 },
627 #[error("tool reconciliation idempotency key is not bound to its invocation")]
629 InvalidIdempotencyKeyBinding,
630}
631
632#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
634#[non_exhaustive]
635pub enum ToolStopReason {
636 Cancelled,
638 DeadlineExceeded,
640}
641
642#[derive(Clone)]
654pub struct ToolContext {
655 tenant_id: TenantId,
656 run_id: RunId,
657 thread_id: ThreadId,
658 invocation_id: InvocationId,
659 attempt_id: AttemptId,
660 tool: CapabilityIdentity,
661 idempotency: ToolIdempotency,
662 idempotency_key: Option<ToolIdempotencyKey>,
663 budget: BudgetRemaining,
664 observed_at: Timestamp,
665 deadline: Timestamp,
666 deadline_instant: Instant,
667 effective_timeout: DurationMillis,
668 cancellation: CancellationSignal,
669 progress: Option<ToolProgressReporter>,
670 origin_event_id: Option<EventId>,
671 max_inline_result_bytes: ByteCount,
672 max_artifacts: ExecutionCount,
673 max_total_artifact_bytes: ByteCount,
674}
675
676impl ToolContext {
677 #[allow(clippy::too_many_arguments)]
688 pub fn new(
689 tenant_id: TenantId,
690 run_id: RunId,
691 thread_id: ThreadId,
692 invocation_id: InvocationId,
693 attempt_id: AttemptId,
694 descriptor: &ToolDescriptor,
695 budget: BudgetRemaining,
696 effective_timeout: DurationMillis,
697 observed_at: Timestamp,
698 observed_instant: Instant,
699 cancellation: CancellationSignal,
700 ) -> Result<Self, ToolContextError> {
701 if effective_timeout == DurationMillis::ZERO {
702 return Err(ToolContextError::ZeroEffectiveTimeout);
703 }
704 let descriptor_timeout = descriptor.limits().timeout();
705 if effective_timeout > descriptor_timeout {
706 return Err(ToolContextError::TimeoutExceedsDescriptor {
707 descriptor: descriptor_timeout,
708 actual: effective_timeout,
709 });
710 }
711
712 let run_deadline = budget.deadline();
713 let run_remaining_micros = i128::from(run_deadline.unix_micros())
714 .checked_sub(i128::from(observed_at.unix_micros()))
715 .expect("subtracting two i64 timestamps cannot overflow i128");
716 if run_remaining_micros <= 0 {
717 return Err(ToolContextError::DeadlineReached {
718 deadline: run_deadline,
719 observed_at,
720 });
721 }
722
723 let timeout_micros = i128::from(effective_timeout.as_i64()) * 1_000;
724 let remaining_micros = run_remaining_micros.min(timeout_micros);
725 let deadline_micros = i128::from(observed_at.unix_micros()) + remaining_micros;
726 let deadline_micros = i64::try_from(deadline_micros)
727 .expect("an effective deadline bounded by a valid run deadline fits i64");
728 let deadline = Timestamp::from_unix_micros(deadline_micros)
729 .expect("an effective deadline bounded by a valid run deadline is a timestamp");
730 let remaining_micros = u64::try_from(remaining_micros)
731 .expect("a positive supported timestamp distance fits u64 microseconds");
732 let remaining = Duration::from_micros(remaining_micros);
733 let deadline_instant = observed_instant
734 .checked_add(remaining)
735 .ok_or(ToolContextError::MonotonicDeadlineOutOfRange { remaining })?;
736
737 let idempotency = descriptor.semantics().idempotency();
738 let idempotency_key = descriptor
739 .semantics()
740 .requires_idempotency_key()
741 .then_some(ToolIdempotencyKey::from_invocation_id(invocation_id));
742 let max_inline_result_bytes = descriptor
743 .limits()
744 .max_inline_result_bytes()
745 .min(budget.output_bytes());
746 let max_total_artifact_bytes = descriptor
747 .limits()
748 .max_total_artifact_bytes()
749 .min(budget.artifact_bytes());
750
751 Ok(Self {
752 tenant_id,
753 run_id,
754 thread_id,
755 invocation_id,
756 attempt_id,
757 tool: descriptor.metadata().identity().clone(),
758 idempotency,
759 idempotency_key,
760 budget,
761 observed_at,
762 deadline,
763 deadline_instant,
764 effective_timeout,
765 cancellation,
766 progress: None,
767 origin_event_id: None,
768 max_inline_result_bytes,
769 max_artifacts: descriptor.limits().max_artifacts(),
770 max_total_artifact_bytes,
771 })
772 }
773
774 #[must_use]
780 pub fn narrow_artifact_limits(mut self, limits: &ToolExecutionLimits) -> Self {
781 self.max_inline_result_bytes = self
782 .max_inline_result_bytes
783 .min(limits.max_inline_result_bytes());
784 self.max_artifacts = self.max_artifacts.min(limits.max_artifacts());
785 self.max_total_artifact_bytes = self
786 .max_total_artifact_bytes
787 .min(limits.max_total_artifact_bytes());
788 self
789 }
790
791 #[must_use]
797 pub fn with_durable_origin_event(mut self, event_id: EventId) -> Self {
798 self.origin_event_id = Some(event_id);
799 self
800 }
801
802 #[allow(clippy::too_many_arguments)]
813 pub fn new_with_progress(
814 tenant_id: TenantId,
815 run_id: RunId,
816 thread_id: ThreadId,
817 invocation_id: InvocationId,
818 attempt_id: AttemptId,
819 descriptor: &ToolDescriptor,
820 budget: BudgetRemaining,
821 effective_timeout: DurationMillis,
822 observed_at: Timestamp,
823 observed_instant: Instant,
824 cancellation: CancellationSignal,
825 progress_sink: Arc<dyn ToolProgressSink>,
826 ) -> Result<Self, ToolContextError> {
827 let mut context = Self::new(
828 tenant_id,
829 run_id,
830 thread_id,
831 invocation_id,
832 attempt_id,
833 descriptor,
834 budget,
835 effective_timeout,
836 observed_at,
837 observed_instant,
838 cancellation,
839 )?;
840 let maximum = descriptor.invocation().max_progress_events();
841 if maximum == ExecutionCount::ZERO {
842 return Err(ToolContextError::ProgressUnsupported);
843 }
844 context.progress = Some(ToolProgressReporter::new(
845 ToolProgressProvenance::new(
846 invocation_id,
847 attempt_id,
848 descriptor.metadata().identity().clone(),
849 ),
850 maximum,
851 progress_sink,
852 ));
853 Ok(context)
854 }
855
856 #[must_use]
858 pub const fn tenant_id(&self) -> &TenantId {
859 &self.tenant_id
860 }
861
862 #[must_use]
864 pub const fn run_id(&self) -> RunId {
865 self.run_id
866 }
867
868 #[must_use]
870 pub const fn thread_id(&self) -> ThreadId {
871 self.thread_id
872 }
873
874 #[must_use]
876 pub const fn invocation_id(&self) -> InvocationId {
877 self.invocation_id
878 }
879
880 #[must_use]
882 pub const fn attempt_id(&self) -> AttemptId {
883 self.attempt_id
884 }
885
886 #[must_use]
888 pub const fn tool(&self) -> &CapabilityIdentity {
889 &self.tool
890 }
891
892 #[must_use]
894 pub const fn idempotency(&self) -> ToolIdempotency {
895 self.idempotency
896 }
897
898 #[must_use]
900 pub const fn idempotency_key(&self) -> Option<ToolIdempotencyKey> {
901 self.idempotency_key
902 }
903
904 pub const fn required_idempotency_key(
911 &self,
912 ) -> Result<ToolIdempotencyKey, ToolContextBindingError> {
913 match self.idempotency_key {
914 Some(key) => Ok(key),
915 None => Err(ToolContextBindingError::IdempotencyKeyNotRequired {
916 idempotency: self.idempotency,
917 }),
918 }
919 }
920
921 #[must_use]
923 pub const fn budget(&self) -> &BudgetRemaining {
924 &self.budget
925 }
926
927 #[must_use]
929 pub const fn observed_at(&self) -> Timestamp {
930 self.observed_at
931 }
932
933 #[must_use]
935 pub const fn deadline(&self) -> Timestamp {
936 self.deadline
937 }
938
939 #[must_use]
941 pub const fn deadline_instant(&self) -> Instant {
942 self.deadline_instant
943 }
944
945 #[must_use]
947 pub const fn effective_timeout(&self) -> DurationMillis {
948 self.effective_timeout
949 }
950
951 #[must_use]
953 pub const fn cancellation(&self) -> &CancellationSignal {
954 &self.cancellation
955 }
956
957 #[must_use]
959 pub const fn progress(&self) -> Option<&ToolProgressReporter> {
960 self.progress.as_ref()
961 }
962
963 #[must_use]
965 pub const fn origin_event_id(&self) -> Option<EventId> {
966 self.origin_event_id
967 }
968
969 #[must_use]
971 pub const fn max_artifacts(&self) -> ExecutionCount {
972 self.max_artifacts
973 }
974
975 #[must_use]
977 pub const fn max_inline_result_bytes(&self) -> ByteCount {
978 self.max_inline_result_bytes
979 }
980
981 #[must_use]
983 pub const fn max_total_artifact_bytes(&self) -> ByteCount {
984 self.max_total_artifact_bytes
985 }
986
987 #[must_use]
989 pub fn remaining_time_at(&self, observed_instant: Instant) -> Option<Duration> {
990 self.deadline_instant
991 .checked_duration_since(observed_instant)
992 .filter(|remaining| !remaining.is_zero())
993 }
994
995 #[must_use]
999 pub fn stop_reason_at(&self, observed_instant: Instant) -> Option<ToolStopReason> {
1000 if self.cancellation.is_cancelled() {
1001 Some(ToolStopReason::Cancelled)
1002 } else if self.remaining_time_at(observed_instant).is_none() {
1003 Some(ToolStopReason::DeadlineExceeded)
1004 } else {
1005 None
1006 }
1007 }
1008
1009 pub fn validate_for(&self, descriptor: &ToolDescriptor) -> Result<(), ToolContextBindingError> {
1016 let expected_tool = descriptor.metadata().identity();
1017 if &self.tool != expected_tool {
1018 return Err(ToolContextBindingError::ToolIdentityMismatch {
1019 expected: Box::new(expected_tool.clone()),
1020 actual: Box::new(self.tool.clone()),
1021 });
1022 }
1023 let expected_idempotency = descriptor.semantics().idempotency();
1024 if self.idempotency != expected_idempotency {
1025 return Err(ToolContextBindingError::IdempotencyMismatch {
1026 expected: expected_idempotency,
1027 actual: self.idempotency,
1028 });
1029 }
1030 if self.effective_timeout > descriptor.limits().timeout() {
1031 return Err(ToolContextBindingError::TimeoutExceedsDescriptor {
1032 descriptor: descriptor.limits().timeout(),
1033 actual: self.effective_timeout,
1034 });
1035 }
1036 let key_is_valid = matches!(
1037 (self.idempotency, self.idempotency_key),
1038 (ToolIdempotency::RequiredKey, Some(key)) if key.invocation_id() == self.invocation_id
1039 ) || (self.idempotency != ToolIdempotency::RequiredKey
1040 && self.idempotency_key.is_none());
1041 if !key_is_valid {
1042 return Err(ToolContextBindingError::InvalidIdempotencyKeyBinding);
1043 }
1044 if let Some(progress) = &self.progress {
1045 let maximum = descriptor.invocation().max_progress_events();
1046 if maximum == ExecutionCount::ZERO || progress.maximum_events() != maximum {
1047 return Err(ToolContextBindingError::ProgressLimitMismatch {
1048 expected: maximum,
1049 actual: progress.maximum_events(),
1050 });
1051 }
1052 if progress.provenance().invocation_id() != self.invocation_id
1053 || progress.provenance().attempt_id() != self.attempt_id
1054 || progress.provenance().tool() != &self.tool
1055 {
1056 return Err(ToolContextBindingError::ProgressProvenanceMismatch);
1057 }
1058 }
1059 Ok(())
1060 }
1061}
1062
1063impl fmt::Debug for ToolContext {
1064 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1065 formatter
1066 .debug_struct("ToolContext")
1067 .field("tenant_id", &self.tenant_id)
1068 .field("run_id", &self.run_id)
1069 .field("thread_id", &self.thread_id)
1070 .field("invocation_id", &self.invocation_id)
1071 .field("attempt_id", &self.attempt_id)
1072 .field("tool", &self.tool)
1073 .field("idempotency", &self.idempotency)
1074 .field("has_idempotency_key", &self.idempotency_key.is_some())
1075 .field("observed_at", &self.observed_at)
1076 .field("deadline", &self.deadline)
1077 .field("effective_timeout", &self.effective_timeout)
1078 .field("cancelled", &self.cancellation.is_cancelled())
1079 .field("progress_enabled", &self.progress.is_some())
1080 .field("max_artifacts", &self.max_artifacts)
1081 .field("max_total_artifact_bytes", &self.max_total_artifact_bytes)
1082 .field("has_origin_event", &self.origin_event_id.is_some())
1083 .finish_non_exhaustive()
1084 }
1085}
1086
1087#[derive(Clone, Debug, Eq, Error, PartialEq)]
1089#[non_exhaustive]
1090pub enum ToolContextError {
1091 #[error("tool context effective timeout must be greater than zero")]
1093 ZeroEffectiveTimeout,
1094 #[error("tool context timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
1096 TimeoutExceedsDescriptor {
1097 descriptor: DurationMillis,
1099 actual: DurationMillis,
1101 },
1102 #[error("tool context deadline {deadline} was reached at {observed_at}")]
1104 DeadlineReached {
1105 deadline: Timestamp,
1107 observed_at: Timestamp,
1109 },
1110 #[error("tool context monotonic deadline is out of range after {remaining:?}")]
1112 MonotonicDeadlineOutOfRange {
1113 remaining: Duration,
1115 },
1116 #[error("tool descriptor does not allow progress events")]
1118 ProgressUnsupported,
1119}
1120
1121#[derive(Clone, Debug, Eq, Error, PartialEq)]
1123#[non_exhaustive]
1124pub enum ToolContextBindingError {
1125 #[error("tool context identity {actual:?} does not match descriptor {expected:?}")]
1127 ToolIdentityMismatch {
1128 expected: Box<CapabilityIdentity>,
1130 actual: Box<CapabilityIdentity>,
1132 },
1133 #[error("tool context idempotency {actual:?} does not match descriptor {expected:?}")]
1135 IdempotencyMismatch {
1136 expected: ToolIdempotency,
1138 actual: ToolIdempotency,
1140 },
1141 #[error("tool context timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
1143 TimeoutExceedsDescriptor {
1144 descriptor: DurationMillis,
1146 actual: DurationMillis,
1148 },
1149 #[error("tool context idempotency key is not bound to its logical invocation")]
1151 InvalidIdempotencyKeyBinding,
1152 #[error("tool idempotency mechanism {idempotency:?} does not require a key")]
1154 IdempotencyKeyNotRequired {
1155 idempotency: ToolIdempotency,
1157 },
1158 #[error("tool progress maximum {actual} does not match descriptor {expected}")]
1160 ProgressLimitMismatch {
1161 expected: ExecutionCount,
1163 actual: ExecutionCount,
1165 },
1166 #[error("tool progress reporter provenance does not match its context")]
1168 ProgressProvenanceMismatch,
1169}
1170
1171#[derive(Clone, Copy, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1177#[serde(deny_unknown_fields)]
1178pub struct ToolProgressUpdate {
1179 completed: ExecutionCount,
1180 #[serde(skip_serializing_if = "Option::is_none")]
1181 total: Option<ExecutionCount>,
1182}
1183
1184impl ToolProgressUpdate {
1185 pub const fn new(
1192 completed: ExecutionCount,
1193 total: Option<ExecutionCount>,
1194 ) -> Result<Self, ToolProgressUpdateError> {
1195 if let Some(total) = total {
1196 if total.get() == 0 {
1197 return Err(ToolProgressUpdateError::ZeroTotal);
1198 }
1199 if completed.get() > total.get() {
1200 return Err(ToolProgressUpdateError::CompletedExceedsTotal { completed, total });
1201 }
1202 }
1203 Ok(Self { completed, total })
1204 }
1205
1206 #[must_use]
1208 pub const fn completed(self) -> ExecutionCount {
1209 self.completed
1210 }
1211
1212 #[must_use]
1214 pub const fn total(self) -> Option<ExecutionCount> {
1215 self.total
1216 }
1217}
1218
1219impl<'de> Deserialize<'de> for ToolProgressUpdate {
1220 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1221 where
1222 D: Deserializer<'de>,
1223 {
1224 #[derive(Deserialize)]
1225 #[serde(deny_unknown_fields)]
1226 struct Wire {
1227 completed: ExecutionCount,
1228 total: Option<ExecutionCount>,
1229 }
1230
1231 let wire = Wire::deserialize(deserializer)?;
1232 Self::new(wire.completed, wire.total).map_err(de::Error::custom)
1233 }
1234}
1235
1236#[derive(Clone, Debug, Eq, Error, PartialEq)]
1238#[non_exhaustive]
1239pub enum ToolProgressUpdateError {
1240 #[error("tool progress total must be greater than zero")]
1242 ZeroTotal,
1243 #[error("tool progress completed {completed} exceeds total {total}")]
1245 CompletedExceedsTotal {
1246 completed: ExecutionCount,
1248 total: ExecutionCount,
1250 },
1251}
1252
1253#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
1255#[serde(deny_unknown_fields)]
1256pub struct ToolProgressProvenance {
1257 invocation_id: InvocationId,
1258 attempt_id: AttemptId,
1259 tool: CapabilityIdentity,
1260}
1261
1262impl ToolProgressProvenance {
1263 #[must_use]
1265 pub const fn new(
1266 invocation_id: InvocationId,
1267 attempt_id: AttemptId,
1268 tool: CapabilityIdentity,
1269 ) -> Self {
1270 Self {
1271 invocation_id,
1272 attempt_id,
1273 tool,
1274 }
1275 }
1276
1277 #[must_use]
1279 pub const fn invocation_id(&self) -> InvocationId {
1280 self.invocation_id
1281 }
1282
1283 #[must_use]
1285 pub const fn attempt_id(&self) -> AttemptId {
1286 self.attempt_id
1287 }
1288
1289 #[must_use]
1291 pub const fn tool(&self) -> &CapabilityIdentity {
1292 &self.tool
1293 }
1294}
1295
1296impl fmt::Debug for ToolProgressProvenance {
1297 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1298 formatter
1299 .debug_struct("ToolProgressProvenance")
1300 .field("invocation_id", &self.invocation_id)
1301 .field("attempt_id", &self.attempt_id)
1302 .field("tool", &self.tool)
1303 .finish_non_exhaustive()
1304 }
1305}
1306
1307#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
1309#[serde(deny_unknown_fields)]
1310pub struct ToolProgressEvent {
1311 provenance: ToolProgressProvenance,
1312 sequence: ExecutionCount,
1313 update: ToolProgressUpdate,
1314}
1315
1316impl ToolProgressEvent {
1317 #[must_use]
1319 pub const fn new(
1320 provenance: ToolProgressProvenance,
1321 sequence: ExecutionCount,
1322 update: ToolProgressUpdate,
1323 ) -> Self {
1324 Self {
1325 provenance,
1326 sequence,
1327 update,
1328 }
1329 }
1330
1331 #[must_use]
1333 pub const fn provenance(&self) -> &ToolProgressProvenance {
1334 &self.provenance
1335 }
1336
1337 #[must_use]
1339 pub const fn sequence(&self) -> ExecutionCount {
1340 self.sequence
1341 }
1342
1343 #[must_use]
1345 pub const fn update(&self) -> ToolProgressUpdate {
1346 self.update
1347 }
1348
1349 pub fn validate_for(
1359 &self,
1360 context: &ToolContext,
1361 descriptor: &ToolDescriptor,
1362 ) -> Result<(), ToolProgressEventValidationError> {
1363 context
1364 .validate_for(descriptor)
1365 .map_err(ToolProgressEventValidationError::context)?;
1366 if self.provenance.invocation_id != context.invocation_id() {
1367 return Err(ToolProgressEventValidationError::InvocationMismatch {
1368 expected: context.invocation_id(),
1369 actual: self.provenance.invocation_id,
1370 });
1371 }
1372 if self.provenance.attempt_id != context.attempt_id() {
1373 return Err(ToolProgressEventValidationError::AttemptMismatch {
1374 expected: context.attempt_id(),
1375 actual: self.provenance.attempt_id,
1376 });
1377 }
1378 let expected_tool = descriptor.metadata().identity();
1379 if &self.provenance.tool != expected_tool {
1380 return Err(ToolProgressEventValidationError::ToolIdentityMismatch {
1381 expected: Box::new(expected_tool.clone()),
1382 actual: Box::new(self.provenance.tool.clone()),
1383 });
1384 }
1385 let maximum = descriptor.invocation().max_progress_events();
1386 if self.sequence >= maximum {
1387 return Err(ToolProgressEventValidationError::SequenceLimitExceeded {
1388 maximum,
1389 actual: self.sequence,
1390 });
1391 }
1392 Ok(())
1393 }
1394}
1395
1396#[derive(Clone, Debug, Eq, Error, PartialEq)]
1398#[non_exhaustive]
1399pub enum ToolProgressEventValidationError {
1400 #[error("tool progress context binding is invalid: {source}")]
1402 Context {
1403 #[source]
1405 source: ToolContextBindingError,
1406 },
1407 #[error("tool progress invocation {actual} does not match context {expected}")]
1409 InvocationMismatch {
1410 expected: InvocationId,
1412 actual: InvocationId,
1414 },
1415 #[error("tool progress attempt {actual} does not match context {expected}")]
1417 AttemptMismatch {
1418 expected: AttemptId,
1420 actual: AttemptId,
1422 },
1423 #[error("tool progress identity {actual:?} does not match descriptor {expected:?}")]
1425 ToolIdentityMismatch {
1426 expected: Box<CapabilityIdentity>,
1428 actual: Box<CapabilityIdentity>,
1430 },
1431 #[error("tool progress sequence {actual} exceeds event capacity {maximum}")]
1433 SequenceLimitExceeded {
1434 maximum: ExecutionCount,
1436 actual: ExecutionCount,
1438 },
1439}
1440
1441impl ToolProgressEventValidationError {
1442 const fn context(source: ToolContextBindingError) -> Self {
1443 Self::Context { source }
1444 }
1445}
1446
1447type PrivateProgressSinkSource = dyn StdError + Send + Sync + 'static;
1448
1449#[derive(Clone)]
1451pub struct ToolProgressSinkError {
1452 private_source: Arc<PrivateProgressSinkSource>,
1453}
1454
1455impl ToolProgressSinkError {
1456 #[must_use]
1458 pub fn new<E>(source: E) -> Self
1459 where
1460 E: StdError + Send + Sync + 'static,
1461 {
1462 Self {
1463 private_source: Arc::new(source),
1464 }
1465 }
1466
1467 #[must_use]
1469 pub fn private_source(&self) -> &(dyn StdError + Send + Sync + 'static) {
1470 self.private_source.as_ref()
1471 }
1472}
1473
1474impl fmt::Debug for ToolProgressSinkError {
1475 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1476 formatter
1477 .debug_struct("ToolProgressSinkError")
1478 .field("has_private_source", &true)
1479 .finish_non_exhaustive()
1480 }
1481}
1482
1483impl fmt::Display for ToolProgressSinkError {
1484 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1485 formatter.write_str("tool progress sink failed")
1486 }
1487}
1488
1489impl StdError for ToolProgressSinkError {}
1490
1491pub trait ToolProgressSink: Send + Sync + 'static {
1497 fn emit(
1499 &self,
1500 event: ToolProgressEvent,
1501 ) -> crate::BoxFuture<'_, Result<(), ToolProgressSinkError>>;
1502}
1503
1504#[derive(Debug)]
1505struct ToolProgressState {
1506 next_sequence: ExecutionCount,
1507 last_completed: Option<ExecutionCount>,
1508 total: Option<ExecutionCount>,
1509 in_flight: bool,
1510 poisoned: bool,
1511}
1512
1513#[derive(Clone)]
1520pub struct ToolProgressReporter {
1521 provenance: ToolProgressProvenance,
1522 maximum_events: ExecutionCount,
1523 sink: Arc<dyn ToolProgressSink>,
1524 state: Arc<Mutex<ToolProgressState>>,
1525}
1526
1527impl ToolProgressReporter {
1528 fn new(
1529 provenance: ToolProgressProvenance,
1530 maximum_events: ExecutionCount,
1531 sink: Arc<dyn ToolProgressSink>,
1532 ) -> Self {
1533 debug_assert!(maximum_events != ExecutionCount::ZERO);
1534 Self {
1535 provenance,
1536 maximum_events,
1537 sink,
1538 state: Arc::new(Mutex::new(ToolProgressState {
1539 next_sequence: ExecutionCount::ZERO,
1540 last_completed: None,
1541 total: None,
1542 in_flight: false,
1543 poisoned: false,
1544 })),
1545 }
1546 }
1547
1548 #[must_use]
1550 pub const fn provenance(&self) -> &ToolProgressProvenance {
1551 &self.provenance
1552 }
1553
1554 #[must_use]
1556 pub const fn maximum_events(&self) -> ExecutionCount {
1557 self.maximum_events
1558 }
1559
1560 pub fn emit(
1567 &self,
1568 update: ToolProgressUpdate,
1569 ) -> crate::BoxFuture<'_, Result<ToolProgressEvent, ToolProgressError>> {
1570 Box::pin(async move {
1571 let (event, mut reservation) = {
1572 let mut state = self
1573 .state
1574 .lock()
1575 .map_err(|_| ToolProgressError::StatePoisoned)?;
1576 if state.poisoned {
1577 return Err(ToolProgressError::StatePoisoned);
1578 }
1579 if state.in_flight {
1580 return Err(ToolProgressError::ConcurrentEmission);
1581 }
1582 if state.next_sequence >= self.maximum_events {
1583 return Err(ToolProgressError::MaximumReached {
1584 maximum: self.maximum_events,
1585 });
1586 }
1587 if let Some(previous) = state.last_completed {
1588 if update.completed() <= previous {
1589 return Err(ToolProgressError::NotIncreasing {
1590 previous,
1591 actual: update.completed(),
1592 });
1593 }
1594 }
1595 if let (Some(expected), Some(actual)) = (state.total, update.total()) {
1596 if expected != actual {
1597 return Err(ToolProgressError::TotalChanged { expected, actual });
1598 }
1599 }
1600 let total = update.total().or(state.total);
1601 if let Some(total) = total {
1602 if update.completed() > total {
1603 return Err(ToolProgressError::CompletedExceedsEstablishedTotal {
1604 completed: update.completed(),
1605 total,
1606 });
1607 }
1608 }
1609 let normalized = ToolProgressUpdate {
1610 completed: update.completed(),
1611 total,
1612 };
1613 let event = ToolProgressEvent::new(
1614 self.provenance.clone(),
1615 state.next_sequence,
1616 normalized,
1617 );
1618 state.in_flight = true;
1619 (event, ToolProgressReservation::new(Arc::clone(&self.state)))
1620 };
1621
1622 match self.sink.emit(event.clone()).await {
1623 Ok(()) => {
1624 reservation.commit(event.update())?;
1625 Ok(event)
1626 }
1627 Err(source) => {
1628 reservation.fail();
1629 Err(ToolProgressError::Sink { source })
1630 }
1631 }
1632 })
1633 }
1634}
1635
1636impl fmt::Debug for ToolProgressReporter {
1637 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1638 formatter
1639 .debug_struct("ToolProgressReporter")
1640 .field("provenance", &self.provenance)
1641 .field("maximum_events", &self.maximum_events)
1642 .finish_non_exhaustive()
1643 }
1644}
1645
1646struct ToolProgressReservation {
1647 state: Arc<Mutex<ToolProgressState>>,
1648 active: bool,
1649}
1650
1651impl ToolProgressReservation {
1652 fn new(state: Arc<Mutex<ToolProgressState>>) -> Self {
1653 Self {
1654 state,
1655 active: true,
1656 }
1657 }
1658
1659 fn commit(&mut self, update: ToolProgressUpdate) -> Result<(), ToolProgressError> {
1660 let mut state = self
1661 .state
1662 .lock()
1663 .map_err(|_| ToolProgressError::StatePoisoned)?;
1664 state.next_sequence = state
1665 .next_sequence
1666 .checked_add(ExecutionCount::new(1))
1667 .ok_or(ToolProgressError::StatePoisoned)?;
1668 state.last_completed = Some(update.completed());
1669 state.total = update.total();
1670 state.in_flight = false;
1671 self.active = false;
1672 Ok(())
1673 }
1674
1675 fn fail(&mut self) {
1676 if let Ok(mut state) = self.state.lock() {
1677 state.in_flight = false;
1678 state.poisoned = true;
1679 }
1680 self.active = false;
1681 }
1682}
1683
1684impl Drop for ToolProgressReservation {
1685 fn drop(&mut self) {
1686 if self.active {
1687 self.fail();
1688 }
1689 }
1690}
1691
1692#[derive(Clone, Debug, Error)]
1694#[non_exhaustive]
1695pub enum ToolProgressError {
1696 #[error("tool progress reporter is poisoned")]
1698 StatePoisoned,
1699 #[error("concurrent tool progress emission is not allowed")]
1701 ConcurrentEmission,
1702 #[error("tool progress event maximum {maximum} was reached")]
1704 MaximumReached {
1705 maximum: ExecutionCount,
1707 },
1708 #[error("tool progress completed {actual} does not exceed previous {previous}")]
1710 NotIncreasing {
1711 previous: ExecutionCount,
1713 actual: ExecutionCount,
1715 },
1716 #[error("tool progress total {actual} does not match established {expected}")]
1718 TotalChanged {
1719 expected: ExecutionCount,
1721 actual: ExecutionCount,
1723 },
1724 #[error("tool progress completed {completed} exceeds established total {total}")]
1726 CompletedExceedsEstablishedTotal {
1727 completed: ExecutionCount,
1729 total: ExecutionCount,
1731 },
1732 #[error("tool progress sink failed")]
1734 Sink {
1735 source: ToolProgressSinkError,
1737 },
1738}
1739
1740#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1747#[serde(deny_unknown_fields)]
1748pub struct ToolInput {
1749 schema: SchemaReference,
1750 value: BoundedJson,
1751}
1752
1753impl ToolInput {
1754 pub fn new(schema: SchemaReference, value: BoundedJson) -> Result<Self, ToolInputError> {
1760 if !value.as_value().is_object() {
1761 return Err(ToolInputError::ObjectRootRequired);
1762 }
1763 Ok(Self { schema, value })
1764 }
1765
1766 #[must_use]
1768 pub const fn schema(&self) -> &SchemaReference {
1769 &self.schema
1770 }
1771
1772 #[must_use]
1774 pub const fn value(&self) -> &BoundedJson {
1775 &self.value
1776 }
1777
1778 #[must_use]
1780 pub fn into_parts(self) -> (SchemaReference, BoundedJson) {
1781 (self.schema, self.value)
1782 }
1783
1784 pub fn validate_for(
1794 &self,
1795 context: &ToolContext,
1796 descriptor: &ToolDescriptor,
1797 ) -> Result<(), ToolInputValidationError> {
1798 context
1799 .validate_for(descriptor)
1800 .map_err(ToolInputValidationError::context)?;
1801 if &self.schema != descriptor.input_schema() {
1802 return Err(ToolInputValidationError::SchemaMismatch {
1803 expected: Box::new(descriptor.input_schema().clone()),
1804 actual: Box::new(self.schema.clone()),
1805 });
1806 }
1807 let actual = byte_count_from_usize(self.value.stats().compact_bytes());
1808 let descriptor_maximum = descriptor.limits().max_input_bytes();
1809 if actual > descriptor_maximum {
1810 return Err(ToolInputValidationError::DescriptorLimitExceeded {
1811 maximum: descriptor_maximum,
1812 actual,
1813 });
1814 }
1815 let budget_maximum = context.budget().input_bytes();
1816 if actual > budget_maximum {
1817 return Err(ToolInputValidationError::BudgetLimitExceeded {
1818 maximum: budget_maximum,
1819 actual,
1820 });
1821 }
1822 Ok(())
1823 }
1824}
1825
1826impl fmt::Debug for ToolInput {
1827 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1828 formatter
1829 .debug_struct("ToolInput")
1830 .field("schema", &self.schema)
1831 .field("stats", &self.value.stats())
1832 .finish_non_exhaustive()
1833 }
1834}
1835
1836impl<'de> Deserialize<'de> for ToolInput {
1837 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1838 where
1839 D: Deserializer<'de>,
1840 {
1841 #[derive(Deserialize)]
1842 #[serde(deny_unknown_fields)]
1843 struct Wire {
1844 schema: SchemaReference,
1845 value: BoundedJson,
1846 }
1847
1848 let wire = Wire::deserialize(deserializer)?;
1849 Self::new(wire.schema, wire.value).map_err(de::Error::custom)
1850 }
1851}
1852
1853#[derive(Clone, Debug, Eq, Error, PartialEq)]
1855#[non_exhaustive]
1856pub enum ToolInputError {
1857 #[error("tool input JSON must have an object root")]
1859 ObjectRootRequired,
1860}
1861
1862#[derive(Clone, Debug, Eq, Error, PartialEq)]
1864#[non_exhaustive]
1865pub enum ToolInputValidationError {
1866 #[error("tool input context binding is invalid: {source}")]
1868 Context {
1869 #[source]
1871 source: ToolContextBindingError,
1872 },
1873 #[error("tool input schema {actual:?} does not match descriptor {expected:?}")]
1875 SchemaMismatch {
1876 expected: Box<SchemaReference>,
1878 actual: Box<SchemaReference>,
1880 },
1881 #[error("tool input is {actual} bytes; descriptor maximum is {maximum}")]
1883 DescriptorLimitExceeded {
1884 maximum: ByteCount,
1886 actual: ByteCount,
1888 },
1889 #[error("tool input is {actual} bytes; remaining run maximum is {maximum}")]
1891 BudgetLimitExceeded {
1892 maximum: ByteCount,
1894 actual: ByteCount,
1896 },
1897}
1898
1899impl ToolInputValidationError {
1900 const fn context(source: ToolContextBindingError) -> Self {
1901 Self::Context { source }
1902 }
1903}
1904
1905#[derive(Clone, Default, Eq, PartialEq)]
1910pub struct ToolArtifacts {
1911 values: Box<[ArtifactRef]>,
1912 total_bytes: ByteCount,
1913}
1914
1915impl ToolArtifacts {
1916 pub const MAX_LEN: usize = 64;
1918
1919 #[must_use]
1921 pub fn empty() -> Self {
1922 Self::default()
1923 }
1924
1925 pub fn try_new<I>(values: I) -> Result<Self, ToolArtifactsError>
1932 where
1933 I: IntoIterator<Item = ArtifactRef>,
1934 {
1935 let mut collected = Vec::new();
1936 let mut total_bytes = ByteCount::ZERO;
1937 for value in values {
1938 if collected.len() == Self::MAX_LEN {
1939 return Err(ToolArtifactsError::TooMany {
1940 maximum: Self::MAX_LEN,
1941 actual: Self::MAX_LEN + 1,
1942 });
1943 }
1944 if collected
1945 .iter()
1946 .any(|existing: &ArtifactRef| existing.identity() == value.identity())
1947 {
1948 return Err(ToolArtifactsError::DuplicateIdentity);
1949 }
1950 total_bytes = total_bytes
1951 .checked_add(value.representation().byte_length())
1952 .ok_or(ToolArtifactsError::TotalBytesOverflow)?;
1953 collected.push(value);
1954 }
1955 Ok(Self {
1956 values: collected.into_boxed_slice(),
1957 total_bytes,
1958 })
1959 }
1960
1961 #[must_use]
1963 pub const fn len(&self) -> usize {
1964 self.values.len()
1965 }
1966
1967 #[must_use]
1969 pub const fn is_empty(&self) -> bool {
1970 self.values.is_empty()
1971 }
1972
1973 #[must_use]
1975 pub const fn total_bytes(&self) -> ByteCount {
1976 self.total_bytes
1977 }
1978
1979 pub fn iter(&self) -> impl ExactSizeIterator<Item = &ArtifactRef> {
1981 self.values.iter()
1982 }
1983
1984 #[must_use]
1986 pub fn into_vec(self) -> Vec<ArtifactRef> {
1987 self.values.into_vec()
1988 }
1989}
1990
1991impl fmt::Debug for ToolArtifacts {
1992 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1993 formatter
1994 .debug_struct("ToolArtifacts")
1995 .field("count", &self.len())
1996 .field("total_bytes", &self.total_bytes)
1997 .finish_non_exhaustive()
1998 }
1999}
2000
2001impl Serialize for ToolArtifacts {
2002 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2003 where
2004 S: Serializer,
2005 {
2006 self.values.serialize(serializer)
2007 }
2008}
2009
2010impl<'de> Deserialize<'de> for ToolArtifacts {
2011 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2012 where
2013 D: Deserializer<'de>,
2014 {
2015 deserializer.deserialize_seq(ToolArtifactsVisitor)
2016 }
2017}
2018
2019struct ToolArtifactsVisitor;
2020
2021impl<'de> de::Visitor<'de> for ToolArtifactsVisitor {
2022 type Value = ToolArtifacts;
2023
2024 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2025 write!(
2026 formatter,
2027 "at most {} unique artifact references",
2028 ToolArtifacts::MAX_LEN
2029 )
2030 }
2031
2032 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
2033 where
2034 A: de::SeqAccess<'de>,
2035 {
2036 let mut values = Vec::with_capacity(
2037 sequence
2038 .size_hint()
2039 .unwrap_or_default()
2040 .min(ToolArtifacts::MAX_LEN),
2041 );
2042 while let Some(value) = sequence.next_element::<ArtifactRef>()? {
2043 if values.len() == ToolArtifacts::MAX_LEN {
2044 return Err(de::Error::custom(ToolArtifactsError::TooMany {
2045 maximum: ToolArtifacts::MAX_LEN,
2046 actual: ToolArtifacts::MAX_LEN + 1,
2047 }));
2048 }
2049 if values
2050 .iter()
2051 .any(|existing: &ArtifactRef| existing.identity() == value.identity())
2052 {
2053 return Err(de::Error::custom(ToolArtifactsError::DuplicateIdentity));
2054 }
2055 values.push(value);
2056 }
2057 Self::Value::try_new(values).map_err(de::Error::custom)
2058 }
2059}
2060
2061impl JsonSchema for ToolArtifacts {
2062 fn schema_name() -> std::borrow::Cow<'static, str> {
2063 "ToolArtifacts".into()
2064 }
2065
2066 fn schema_id() -> std::borrow::Cow<'static, str> {
2067 concat!(module_path!(), "::ToolArtifacts").into()
2068 }
2069
2070 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
2071 json_schema!({
2072 "type": "array",
2073 "items": generator.subschema_for::<ArtifactRef>(),
2074 "maxItems": 64,
2075 "uniqueItems": true,
2076 "description": "Ordered artifact references with unique tenant-qualified identities. Identity uniqueness is enforced at runtime."
2077 })
2078 }
2079}
2080
2081#[derive(Clone, Debug, Eq, Error, PartialEq)]
2083#[non_exhaustive]
2084pub enum ToolArtifactsError {
2085 #[error("tool result has {actual} artifacts; hard maximum is {maximum}")]
2087 TooMany {
2088 maximum: usize,
2090 actual: usize,
2092 },
2093 #[error("tool result artifact identities must be unique")]
2095 DuplicateIdentity,
2096 #[error("tool result aggregate artifact bytes overflowed")]
2098 TotalBytesOverflow,
2099}
2100
2101#[derive(Clone, Debug, Eq, PartialEq)]
2108pub struct ToolOutput<T> {
2109 value: T,
2110 artifacts: ToolArtifacts,
2111}
2112
2113impl<T> ToolOutput<T> {
2114 #[must_use]
2116 pub fn inline(value: T) -> Self {
2117 Self {
2118 value,
2119 artifacts: ToolArtifacts::empty(),
2120 }
2121 }
2122
2123 #[must_use]
2125 pub const fn with_artifacts(value: T, artifacts: ToolArtifacts) -> Self {
2126 Self { value, artifacts }
2127 }
2128
2129 #[must_use]
2131 pub const fn value(&self) -> &T {
2132 &self.value
2133 }
2134
2135 #[must_use]
2137 pub const fn artifacts(&self) -> &ToolArtifacts {
2138 &self.artifacts
2139 }
2140
2141 #[must_use]
2143 pub fn into_parts(self) -> (T, ToolArtifacts) {
2144 (self.value, self.artifacts)
2145 }
2146}
2147
2148impl<T> From<T> for ToolOutput<T> {
2149 fn from(value: T) -> Self {
2150 Self::inline(value)
2151 }
2152}
2153
2154#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
2156#[serde(deny_unknown_fields)]
2157pub struct ToolResultProvenance {
2158 invocation_id: InvocationId,
2159 attempt_id: AttemptId,
2160 tool: CapabilityIdentity,
2161}
2162
2163impl ToolResultProvenance {
2164 #[must_use]
2166 pub const fn new(
2167 invocation_id: InvocationId,
2168 attempt_id: AttemptId,
2169 tool: CapabilityIdentity,
2170 ) -> Self {
2171 Self {
2172 invocation_id,
2173 attempt_id,
2174 tool,
2175 }
2176 }
2177
2178 #[must_use]
2180 pub const fn invocation_id(&self) -> InvocationId {
2181 self.invocation_id
2182 }
2183
2184 #[must_use]
2186 pub const fn attempt_id(&self) -> AttemptId {
2187 self.attempt_id
2188 }
2189
2190 #[must_use]
2192 pub const fn tool(&self) -> &CapabilityIdentity {
2193 &self.tool
2194 }
2195}
2196
2197impl fmt::Debug for ToolResultProvenance {
2198 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2199 formatter
2200 .debug_struct("ToolResultProvenance")
2201 .field("invocation_id", &self.invocation_id)
2202 .field("attempt_id", &self.attempt_id)
2203 .field("tool", &self.tool)
2204 .finish_non_exhaustive()
2205 }
2206}
2207
2208#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
2214#[serde(deny_unknown_fields)]
2215pub struct ToolResult {
2216 provenance: ToolResultProvenance,
2217 output_schema: SchemaReference,
2218 output: BoundedJson,
2219 artifacts: ToolArtifacts,
2220}
2221
2222impl ToolResult {
2223 #[must_use]
2225 pub const fn new(
2226 provenance: ToolResultProvenance,
2227 output_schema: SchemaReference,
2228 output: BoundedJson,
2229 artifacts: ToolArtifacts,
2230 ) -> Self {
2231 Self {
2232 provenance,
2233 output_schema,
2234 output,
2235 artifacts,
2236 }
2237 }
2238
2239 #[must_use]
2241 pub fn for_invocation(
2242 context: &ToolContext,
2243 descriptor: &ToolDescriptor,
2244 output: BoundedJson,
2245 artifacts: ToolArtifacts,
2246 ) -> Self {
2247 Self::new(
2248 ToolResultProvenance::new(
2249 context.invocation_id(),
2250 context.attempt_id(),
2251 descriptor.metadata().identity().clone(),
2252 ),
2253 descriptor.output_schema().clone(),
2254 output,
2255 artifacts,
2256 )
2257 }
2258
2259 #[must_use]
2261 pub const fn provenance(&self) -> &ToolResultProvenance {
2262 &self.provenance
2263 }
2264
2265 #[must_use]
2267 pub const fn output_schema(&self) -> &SchemaReference {
2268 &self.output_schema
2269 }
2270
2271 #[must_use]
2273 pub const fn output(&self) -> &BoundedJson {
2274 &self.output
2275 }
2276
2277 #[must_use]
2279 pub const fn artifacts(&self) -> &ToolArtifacts {
2280 &self.artifacts
2281 }
2282
2283 #[must_use]
2285 pub fn into_parts(
2286 self,
2287 ) -> (
2288 ToolResultProvenance,
2289 SchemaReference,
2290 BoundedJson,
2291 ToolArtifacts,
2292 ) {
2293 (
2294 self.provenance,
2295 self.output_schema,
2296 self.output,
2297 self.artifacts,
2298 )
2299 }
2300
2301 pub fn validate_for(
2309 &self,
2310 context: &ToolContext,
2311 descriptor: &ToolDescriptor,
2312 ) -> Result<(), ToolResultValidationError> {
2313 context
2314 .validate_for(descriptor)
2315 .map_err(ToolResultValidationError::context)?;
2316 if self.provenance.invocation_id != context.invocation_id() {
2317 return Err(ToolResultValidationError::InvocationMismatch {
2318 expected: context.invocation_id(),
2319 actual: self.provenance.invocation_id,
2320 });
2321 }
2322 if self.provenance.attempt_id != context.attempt_id() {
2323 return Err(ToolResultValidationError::AttemptMismatch {
2324 expected: context.attempt_id(),
2325 actual: self.provenance.attempt_id,
2326 });
2327 }
2328 let expected_tool = descriptor.metadata().identity();
2329 if &self.provenance.tool != expected_tool {
2330 return Err(ToolResultValidationError::ToolIdentityMismatch {
2331 expected: Box::new(expected_tool.clone()),
2332 actual: Box::new(self.provenance.tool.clone()),
2333 });
2334 }
2335 if &self.output_schema != descriptor.output_schema() {
2336 return Err(ToolResultValidationError::SchemaMismatch {
2337 expected: Box::new(descriptor.output_schema().clone()),
2338 actual: Box::new(self.output_schema.clone()),
2339 });
2340 }
2341
2342 let output_bytes = byte_count_from_usize(self.output.stats().compact_bytes());
2343 let descriptor_output_maximum = descriptor.limits().max_inline_result_bytes();
2344 if output_bytes > descriptor_output_maximum {
2345 return Err(ToolResultValidationError::InlineDescriptorLimitExceeded {
2346 maximum: descriptor_output_maximum,
2347 actual: output_bytes,
2348 });
2349 }
2350 let budget_output_maximum = context.budget().output_bytes();
2351 if output_bytes > budget_output_maximum {
2352 return Err(ToolResultValidationError::InlineBudgetLimitExceeded {
2353 maximum: budget_output_maximum,
2354 actual: output_bytes,
2355 });
2356 }
2357
2358 let artifact_count = execution_count_from_usize(self.artifacts.len());
2359 let descriptor_artifact_maximum = descriptor.limits().max_artifacts();
2360 if artifact_count > descriptor_artifact_maximum {
2361 return Err(ToolResultValidationError::ArtifactCountLimitExceeded {
2362 maximum: descriptor_artifact_maximum,
2363 actual: artifact_count,
2364 });
2365 }
2366 let artifact_bytes = self.artifacts.total_bytes();
2367 let descriptor_artifact_bytes = descriptor.limits().max_total_artifact_bytes();
2368 if artifact_bytes > descriptor_artifact_bytes {
2369 return Err(ToolResultValidationError::ArtifactDescriptorBytesExceeded {
2370 maximum: descriptor_artifact_bytes,
2371 actual: artifact_bytes,
2372 });
2373 }
2374 let budget_artifact_bytes = context.budget().artifact_bytes();
2375 if artifact_bytes > budget_artifact_bytes {
2376 return Err(ToolResultValidationError::ArtifactBudgetBytesExceeded {
2377 maximum: budget_artifact_bytes,
2378 actual: artifact_bytes,
2379 });
2380 }
2381
2382 for (index, artifact) in self.artifacts.iter().enumerate() {
2383 validate_artifact_binding(index, artifact, context, descriptor)?;
2384 }
2385 Ok(())
2386 }
2387}
2388
2389impl fmt::Debug for ToolResult {
2390 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2391 formatter
2392 .debug_struct("ToolResult")
2393 .field("provenance", &self.provenance)
2394 .field("output_schema", &self.output_schema)
2395 .field("output_stats", &self.output.stats())
2396 .field("artifacts", &self.artifacts)
2397 .finish_non_exhaustive()
2398 }
2399}
2400
2401fn validate_artifact_binding(
2402 index: usize,
2403 artifact: &ArtifactRef,
2404 context: &ToolContext,
2405 descriptor: &ToolDescriptor,
2406) -> Result<(), ToolResultValidationError> {
2407 if artifact.identity().tenant_id() != context.tenant_id() {
2408 return Err(ToolResultValidationError::ArtifactTenantMismatch {
2409 index,
2410 expected: Box::new(context.tenant_id().clone()),
2411 actual: Box::new(artifact.identity().tenant_id().clone()),
2412 });
2413 }
2414 if artifact.provenance().run_id() != context.run_id() {
2415 return Err(ToolResultValidationError::ArtifactRunMismatch {
2416 index,
2417 expected: context.run_id(),
2418 actual: artifact.provenance().run_id(),
2419 });
2420 }
2421 let expected_principal = descriptor.metadata().identity().owner();
2422 if artifact.provenance().principal() != expected_principal {
2423 return Err(ToolResultValidationError::ArtifactPrincipalMismatch {
2424 index,
2425 expected: Box::new(expected_principal.clone()),
2426 actual: Box::new(artifact.provenance().principal().clone()),
2427 });
2428 }
2429 let expected_capability = descriptor.metadata().identity().capability();
2430 if artifact.provenance().capability() != Some(expected_capability) {
2431 return Err(ToolResultValidationError::ArtifactCapabilityMismatch {
2432 index,
2433 expected: Box::new(expected_capability.clone()),
2434 actual: artifact
2435 .provenance()
2436 .capability()
2437 .map(|value| Box::new(value.clone())),
2438 });
2439 }
2440 Ok(())
2441}
2442
2443#[derive(Clone, Debug, Eq, Error, PartialEq)]
2445#[non_exhaustive]
2446pub enum ToolResultValidationError {
2447 #[error("tool result context binding is invalid: {source}")]
2449 Context {
2450 #[source]
2452 source: ToolContextBindingError,
2453 },
2454 #[error("tool result invocation {actual} does not match context {expected}")]
2456 InvocationMismatch {
2457 expected: InvocationId,
2459 actual: InvocationId,
2461 },
2462 #[error("tool result attempt {actual} does not match context {expected}")]
2464 AttemptMismatch {
2465 expected: AttemptId,
2467 actual: AttemptId,
2469 },
2470 #[error("tool result identity {actual:?} does not match descriptor {expected:?}")]
2472 ToolIdentityMismatch {
2473 expected: Box<CapabilityIdentity>,
2475 actual: Box<CapabilityIdentity>,
2477 },
2478 #[error("tool result schema {actual:?} does not match descriptor {expected:?}")]
2480 SchemaMismatch {
2481 expected: Box<SchemaReference>,
2483 actual: Box<SchemaReference>,
2485 },
2486 #[error("tool inline output is {actual} bytes; descriptor maximum is {maximum}")]
2488 InlineDescriptorLimitExceeded {
2489 maximum: ByteCount,
2491 actual: ByteCount,
2493 },
2494 #[error("tool inline output is {actual} bytes; remaining run maximum is {maximum}")]
2496 InlineBudgetLimitExceeded {
2497 maximum: ByteCount,
2499 actual: ByteCount,
2501 },
2502 #[error("tool result has {actual} artifacts; descriptor maximum is {maximum}")]
2504 ArtifactCountLimitExceeded {
2505 maximum: ExecutionCount,
2507 actual: ExecutionCount,
2509 },
2510 #[error("tool artifacts total {actual} bytes; descriptor maximum is {maximum}")]
2512 ArtifactDescriptorBytesExceeded {
2513 maximum: ByteCount,
2515 actual: ByteCount,
2517 },
2518 #[error("tool artifacts total {actual} bytes; remaining run maximum is {maximum}")]
2520 ArtifactBudgetBytesExceeded {
2521 maximum: ByteCount,
2523 actual: ByteCount,
2525 },
2526 #[error("tool artifact at index {index} tenant {actual} does not match {expected}")]
2528 ArtifactTenantMismatch {
2529 index: usize,
2531 expected: Box<TenantId>,
2533 actual: Box<TenantId>,
2535 },
2536 #[error("tool artifact at index {index} run {actual} does not match {expected}")]
2538 ArtifactRunMismatch {
2539 index: usize,
2541 expected: RunId,
2543 actual: RunId,
2545 },
2546 #[error("tool artifact at index {index} principal does not match the descriptor owner")]
2548 ArtifactPrincipalMismatch {
2549 index: usize,
2551 expected: Box<PrincipalIdentity>,
2553 actual: Box<PrincipalIdentity>,
2555 },
2556 #[error("tool artifact at index {index} capability does not match the descriptor")]
2558 ArtifactCapabilityMismatch {
2559 index: usize,
2561 expected: Box<CapabilityReference>,
2563 actual: Option<Box<CapabilityReference>>,
2565 },
2566}
2567
2568impl ToolResultValidationError {
2569 const fn context(source: ToolContextBindingError) -> Self {
2570 Self::Context { source }
2571 }
2572}
2573
2574#[derive(
2579 Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
2580)]
2581#[non_exhaustive]
2582#[serde(rename_all = "snake_case")]
2583pub enum ToolErrorPhase {
2584 Preparation,
2586 Execution,
2588 Result,
2590}
2591
2592#[derive(
2599 Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
2600)]
2601#[non_exhaustive]
2602#[serde(rename_all = "snake_case")]
2603pub enum ToolExternalEffect {
2604 NotApplicable,
2606 NotStarted,
2608 NotApplied,
2610 Applied,
2612 Unknown,
2614}
2615
2616#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
2618#[serde(deny_unknown_fields)]
2619pub struct ToolErrorProvenance {
2620 invocation_id: InvocationId,
2621 attempt_id: AttemptId,
2622 tool: CapabilityIdentity,
2623}
2624
2625impl ToolErrorProvenance {
2626 #[must_use]
2628 pub const fn new(
2629 invocation_id: InvocationId,
2630 attempt_id: AttemptId,
2631 tool: CapabilityIdentity,
2632 ) -> Self {
2633 Self {
2634 invocation_id,
2635 attempt_id,
2636 tool,
2637 }
2638 }
2639
2640 #[must_use]
2642 pub fn for_invocation(context: &ToolContext, descriptor: &ToolDescriptor) -> Self {
2643 Self::new(
2644 context.invocation_id(),
2645 context.attempt_id(),
2646 descriptor.metadata().identity().clone(),
2647 )
2648 }
2649
2650 #[must_use]
2652 pub const fn invocation_id(&self) -> InvocationId {
2653 self.invocation_id
2654 }
2655
2656 #[must_use]
2658 pub const fn attempt_id(&self) -> AttemptId {
2659 self.attempt_id
2660 }
2661
2662 #[must_use]
2664 pub const fn tool(&self) -> &CapabilityIdentity {
2665 &self.tool
2666 }
2667}
2668
2669impl fmt::Debug for ToolErrorProvenance {
2670 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2671 formatter
2672 .debug_struct("ToolErrorProvenance")
2673 .field("invocation_id", &self.invocation_id)
2674 .field("attempt_id", &self.attempt_id)
2675 .field("tool", &self.tool)
2676 .finish_non_exhaustive()
2677 }
2678}
2679
2680#[derive(Clone)]
2687pub struct ToolError {
2688 failure: Failure,
2689 phase: ToolErrorPhase,
2690 external_effect: ToolExternalEffect,
2691 provenance: ToolErrorProvenance,
2692 recovery_handle: Option<ToolRecoveryHandle>,
2693}
2694
2695impl ToolError {
2696 pub fn new(
2703 failure: Failure,
2704 phase: ToolErrorPhase,
2705 external_effect: ToolExternalEffect,
2706 provenance: ToolErrorProvenance,
2707 ) -> Result<Self, ToolErrorBuildError> {
2708 validate_tool_error_shape(&failure, phase, external_effect)?;
2709 Ok(Self {
2710 failure,
2711 phase,
2712 external_effect,
2713 provenance,
2714 recovery_handle: None,
2715 })
2716 }
2717
2718 pub fn with_recovery_handle(
2726 mut self,
2727 recovery_handle: ToolRecoveryHandle,
2728 ) -> Result<Self, ToolErrorBuildError> {
2729 if self.external_effect != ToolExternalEffect::Unknown {
2730 return Err(ToolErrorBuildError::RecoveryHandleRequiresUnknownEffect);
2731 }
2732 self.recovery_handle = Some(recovery_handle);
2733 Ok(self)
2734 }
2735
2736 pub fn validate_for(
2743 &self,
2744 context: &ToolContext,
2745 descriptor: &ToolDescriptor,
2746 ) -> Result<(), ToolErrorValidationError> {
2747 context
2748 .validate_for(descriptor)
2749 .map_err(ToolErrorValidationError::context)?;
2750 if self.provenance.invocation_id != context.invocation_id() {
2751 return Err(ToolErrorValidationError::InvocationMismatch {
2752 expected: context.invocation_id(),
2753 actual: self.provenance.invocation_id,
2754 });
2755 }
2756 if self.provenance.attempt_id != context.attempt_id() {
2757 return Err(ToolErrorValidationError::AttemptMismatch {
2758 expected: context.attempt_id(),
2759 actual: self.provenance.attempt_id,
2760 });
2761 }
2762 let expected_tool = descriptor.metadata().identity();
2763 if &self.provenance.tool != expected_tool {
2764 return Err(ToolErrorValidationError::ToolIdentityMismatch {
2765 expected: Box::new(expected_tool.clone()),
2766 actual: Box::new(self.provenance.tool.clone()),
2767 });
2768 }
2769
2770 let risk = descriptor.semantics().risk();
2771 match (risk, self.external_effect) {
2772 (ToolRisk::ReadOnly, ToolExternalEffect::NotApplicable)
2773 | (
2774 ToolRisk::IdempotentWrite | ToolRisk::NonIdempotentWrite,
2775 ToolExternalEffect::NotStarted
2776 | ToolExternalEffect::NotApplied
2777 | ToolExternalEffect::Applied
2778 | ToolExternalEffect::Unknown,
2779 ) => {}
2780 _ => {
2781 return Err(ToolErrorValidationError::EffectRiskMismatch {
2782 risk,
2783 effect: self.external_effect,
2784 });
2785 }
2786 }
2787
2788 if risk == ToolRisk::NonIdempotentWrite
2789 && self.external_effect == ToolExternalEffect::Applied
2790 && matches!(self.failure.retry_advice(), RetryAdvice::SafeAfter { .. })
2791 {
2792 return Err(ToolErrorValidationError::UnsafeRetryAfterAppliedNonIdempotentWrite);
2793 }
2794 Ok(())
2795 }
2796
2797 #[must_use]
2799 pub const fn failure(&self) -> &Failure {
2800 &self.failure
2801 }
2802
2803 #[must_use]
2805 pub fn into_failure(self) -> Failure {
2806 self.failure
2807 }
2808
2809 #[must_use]
2811 pub const fn phase(&self) -> ToolErrorPhase {
2812 self.phase
2813 }
2814
2815 #[must_use]
2817 pub const fn external_effect(&self) -> ToolExternalEffect {
2818 self.external_effect
2819 }
2820
2821 #[must_use]
2823 pub const fn provenance(&self) -> &ToolErrorProvenance {
2824 &self.provenance
2825 }
2826
2827 #[must_use]
2830 pub const fn recovery_handle(&self) -> Option<&ToolRecoveryHandle> {
2831 self.recovery_handle.as_ref()
2832 }
2833}
2834
2835fn validate_tool_error_shape(
2836 failure: &Failure,
2837 phase: ToolErrorPhase,
2838 external_effect: ToolExternalEffect,
2839) -> Result<(), ToolErrorBuildError> {
2840 let ambiguous = failure.category() == FailureCategory::AmbiguousExternalOutcome;
2841 if external_effect == ToolExternalEffect::Unknown && !ambiguous {
2842 return Err(ToolErrorBuildError::UnknownEffectRequiresAmbiguousFailure);
2843 }
2844 if ambiguous && external_effect != ToolExternalEffect::Unknown {
2845 return Err(ToolErrorBuildError::AmbiguousFailureRequiresUnknownEffect);
2846 }
2847 let phase_effect_valid = match phase {
2848 ToolErrorPhase::Preparation => matches!(
2849 external_effect,
2850 ToolExternalEffect::NotApplicable | ToolExternalEffect::NotStarted
2851 ),
2852 ToolErrorPhase::Execution => true,
2853 ToolErrorPhase::Result => matches!(
2854 external_effect,
2855 ToolExternalEffect::NotApplicable
2856 | ToolExternalEffect::Applied
2857 | ToolExternalEffect::Unknown
2858 ),
2859 };
2860 if !phase_effect_valid {
2861 return Err(ToolErrorBuildError::PhaseEffectMismatch {
2862 phase,
2863 effect: external_effect,
2864 });
2865 }
2866 Ok(())
2867}
2868
2869impl fmt::Debug for ToolError {
2870 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2871 formatter
2872 .debug_struct("ToolError")
2873 .field("failure", &self.failure)
2874 .field("phase", &self.phase)
2875 .field("external_effect", &self.external_effect)
2876 .field("provenance", &self.provenance)
2877 .field("has_recovery_handle", &self.recovery_handle.is_some())
2878 .finish_non_exhaustive()
2879 }
2880}
2881
2882impl fmt::Display for ToolError {
2883 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2884 fmt::Display::fmt(&self.failure, formatter)
2885 }
2886}
2887
2888impl StdError for ToolError {
2889 fn source(&self) -> Option<&(dyn StdError + 'static)> {
2890 Some(&self.failure)
2891 }
2892}
2893
2894#[derive(Deserialize, JsonSchema)]
2895#[serde(deny_unknown_fields)]
2896struct ToolErrorWire {
2897 failure: Failure,
2898 phase: ToolErrorPhase,
2899 external_effect: ToolExternalEffect,
2900 provenance: ToolErrorProvenance,
2901 #[serde(default)]
2902 recovery_handle: Option<ToolRecoveryHandle>,
2903}
2904
2905#[derive(Serialize)]
2906struct ToolErrorWireRef<'a> {
2907 failure: &'a Failure,
2908 phase: ToolErrorPhase,
2909 external_effect: ToolExternalEffect,
2910 provenance: &'a ToolErrorProvenance,
2911 #[serde(skip_serializing_if = "Option::is_none")]
2912 recovery_handle: Option<&'a ToolRecoveryHandle>,
2913}
2914
2915impl Serialize for ToolError {
2916 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2917 where
2918 S: Serializer,
2919 {
2920 ToolErrorWireRef {
2921 failure: &self.failure,
2922 phase: self.phase,
2923 external_effect: self.external_effect,
2924 provenance: &self.provenance,
2925 recovery_handle: self.recovery_handle.as_ref(),
2926 }
2927 .serialize(serializer)
2928 }
2929}
2930
2931impl<'de> Deserialize<'de> for ToolError {
2932 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2933 where
2934 D: Deserializer<'de>,
2935 {
2936 let wire = ToolErrorWire::deserialize(deserializer)?;
2937 let error = Self::new(
2938 wire.failure,
2939 wire.phase,
2940 wire.external_effect,
2941 wire.provenance,
2942 )
2943 .map_err(de::Error::custom)?;
2944 match wire.recovery_handle {
2945 Some(handle) => error
2946 .with_recovery_handle(handle)
2947 .map_err(de::Error::custom),
2948 None => Ok(error),
2949 }
2950 }
2951}
2952
2953impl JsonSchema for ToolError {
2954 fn schema_name() -> std::borrow::Cow<'static, str> {
2955 "ToolError".into()
2956 }
2957
2958 fn schema_id() -> std::borrow::Cow<'static, str> {
2959 concat!(module_path!(), "::ToolError").into()
2960 }
2961
2962 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
2963 ToolErrorWire::json_schema(generator)
2964 }
2965}
2966
2967#[derive(Clone, Debug, Eq, Error, PartialEq)]
2969#[non_exhaustive]
2970pub enum ToolErrorBuildError {
2971 #[error("unknown tool effect requires an ambiguous-external-outcome failure")]
2973 UnknownEffectRequiresAmbiguousFailure,
2974 #[error("ambiguous-external-outcome failure requires unknown tool effect")]
2976 AmbiguousFailureRequiresUnknownEffect,
2977 #[error("tool error phase {phase:?} is incompatible with effect {effect:?}")]
2979 PhaseEffectMismatch {
2980 phase: ToolErrorPhase,
2982 effect: ToolExternalEffect,
2984 },
2985 #[error("tool recovery handles require unknown external-effect evidence")]
2987 RecoveryHandleRequiresUnknownEffect,
2988}
2989
2990#[derive(Clone, Debug, Eq, Error, PartialEq)]
2992#[non_exhaustive]
2993pub enum ToolErrorValidationError {
2994 #[error("tool error context binding is invalid: {source}")]
2996 Context {
2997 #[source]
2999 source: ToolContextBindingError,
3000 },
3001 #[error("tool error invocation {actual} does not match context {expected}")]
3003 InvocationMismatch {
3004 expected: InvocationId,
3006 actual: InvocationId,
3008 },
3009 #[error("tool error attempt {actual} does not match context {expected}")]
3011 AttemptMismatch {
3012 expected: AttemptId,
3014 actual: AttemptId,
3016 },
3017 #[error("tool error identity {actual:?} does not match descriptor {expected:?}")]
3019 ToolIdentityMismatch {
3020 expected: Box<CapabilityIdentity>,
3022 actual: Box<CapabilityIdentity>,
3024 },
3025 #[error("tool risk {risk:?} is incompatible with external effect {effect:?}")]
3027 EffectRiskMismatch {
3028 risk: ToolRisk,
3030 effect: ToolExternalEffect,
3032 },
3033 #[error("an applied non-idempotent write cannot use safe-after retry advice")]
3035 UnsafeRetryAfterAppliedNonIdempotentWrite,
3036}
3037
3038impl ToolErrorValidationError {
3039 const fn context(source: ToolContextBindingError) -> Self {
3040 Self::Context { source }
3041 }
3042}
3043
3044type PrivateSchemaSource = dyn StdError + Send + Sync + 'static;
3045
3046#[derive(Clone)]
3053pub struct ToolSchemaValidationError {
3054 private_source: Arc<PrivateSchemaSource>,
3055}
3056
3057impl ToolSchemaValidationError {
3058 #[must_use]
3060 pub fn new<E>(source: E) -> Self
3061 where
3062 E: StdError + Send + Sync + 'static,
3063 {
3064 Self {
3065 private_source: Arc::new(source),
3066 }
3067 }
3068
3069 #[must_use]
3071 pub fn from_shared(source: Arc<PrivateSchemaSource>) -> Self {
3072 Self {
3073 private_source: source,
3074 }
3075 }
3076
3077 #[must_use]
3079 pub fn private_source(&self) -> &(dyn StdError + Send + Sync + 'static) {
3080 self.private_source.as_ref()
3081 }
3082}
3083
3084impl fmt::Debug for ToolSchemaValidationError {
3085 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3086 formatter
3087 .debug_struct("ToolSchemaValidationError")
3088 .field("has_private_source", &true)
3089 .finish_non_exhaustive()
3090 }
3091}
3092
3093impl fmt::Display for ToolSchemaValidationError {
3094 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3095 formatter.write_str("tool schema validation failed")
3096 }
3097}
3098
3099impl StdError for ToolSchemaValidationError {}
3100
3101#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3103#[non_exhaustive]
3104pub enum ToolSchemaRole {
3105 Input,
3107 Output,
3109}
3110
3111pub trait ToolSchemaRegistry: Send + Sync + 'static {
3120 fn validate_type_schema(
3122 &self,
3123 reference: &SchemaReference,
3124 role: ToolSchemaRole,
3125 generated: &Schema,
3126 ) -> Result<(), ToolSchemaValidationError>;
3127
3128 fn validate_instance(
3130 &self,
3131 reference: &SchemaReference,
3132 role: ToolSchemaRole,
3133 value: &BoundedJson,
3134 ) -> Result<(), ToolSchemaValidationError>;
3135}
3136
3137pub trait Tool: Send + Sync + 'static {
3147 type Input: DeserializeOwned + JsonSchema + Send + 'static;
3149 type Output: Serialize + JsonSchema + Send + 'static;
3151
3152 fn descriptor(&self) -> &ToolDescriptor;
3154
3155 fn call(
3157 &self,
3158 context: ToolContext,
3159 input: Self::Input,
3160 ) -> crate::BoxFuture<'_, Result<ToolOutput<Self::Output>, ToolError>>;
3161}
3162
3163#[derive(Clone, Debug)]
3170#[non_exhaustive]
3171pub enum ToolReconciliationObservation {
3172 Result(ToolResult),
3174 Error(ToolError),
3176 Pending {
3178 retry_after: DurationMillis,
3180 },
3181}
3182
3183impl ToolReconciliationObservation {
3184 pub const MAX_RETRY_AFTER: DurationMillis = match DurationMillis::new(3_600_000) {
3186 Ok(value) => value,
3187 Err(_) => panic!("one hour is a valid duration"),
3188 };
3189
3190 pub fn pending(
3198 retry_after: DurationMillis,
3199 ) -> Result<Self, ToolReconciliationObservationError> {
3200 validate_reconciliation_retry_after(retry_after)?;
3201 Ok(Self::Pending { retry_after })
3202 }
3203
3204 pub fn validate(&self) -> Result<(), ToolReconciliationObservationError> {
3209 match self {
3210 Self::Result(_) | Self::Error(_) => Ok(()),
3211 Self::Pending { retry_after } => validate_reconciliation_retry_after(*retry_after),
3212 }
3213 }
3214}
3215
3216fn validate_reconciliation_retry_after(
3217 retry_after: DurationMillis,
3218) -> Result<(), ToolReconciliationObservationError> {
3219 if retry_after == DurationMillis::ZERO {
3220 return Err(ToolReconciliationObservationError::ZeroRetryDelay);
3221 }
3222 if retry_after > ToolReconciliationObservation::MAX_RETRY_AFTER {
3223 return Err(ToolReconciliationObservationError::RetryDelayTooLarge {
3224 maximum: ToolReconciliationObservation::MAX_RETRY_AFTER,
3225 actual: retry_after,
3226 });
3227 }
3228 Ok(())
3229}
3230
3231#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
3233#[non_exhaustive]
3234pub enum ToolReconciliationObservationError {
3235 #[error("tool reconciliation retry delay must be greater than zero")]
3237 ZeroRetryDelay,
3238 #[error("tool reconciliation retry delay {actual}ms exceeds maximum {maximum}ms")]
3240 RetryDelayTooLarge {
3241 maximum: DurationMillis,
3243 actual: DurationMillis,
3245 },
3246}
3247
3248#[derive(Clone, Debug, Error)]
3254#[error("tool reconciliation probe failed: {failure}")]
3255pub struct ToolReconciliationProbeError {
3256 failure: Box<Failure>,
3257}
3258
3259impl ToolReconciliationProbeError {
3260 pub fn new(failure: Failure) -> Result<Self, ToolReconciliationProbeErrorBuildError> {
3266 if failure.retry_advice().requires_reconciliation() {
3267 return Err(ToolReconciliationProbeErrorBuildError::RecursiveReconciliation);
3268 }
3269 if let Some(delay) = failure.retry_advice().safe_after_delay() {
3270 validate_reconciliation_retry_after(delay)
3271 .map_err(ToolReconciliationProbeErrorBuildError::invalid_retry)?;
3272 }
3273 Ok(Self {
3274 failure: Box::new(failure),
3275 })
3276 }
3277
3278 #[must_use]
3280 pub fn failure(&self) -> &Failure {
3281 self.failure.as_ref()
3282 }
3283
3284 fn unsupported() -> Self {
3285 let failure = Failure::new(
3286 FailureId::generate(),
3287 FailureCategory::Unsupported,
3288 FailureCode::new("stateknot.tool.reconciliation_unsupported")
3289 .expect("static reconciliation failure code is valid"),
3290 FailureOrigin::new("stateknot.tool")
3291 .expect("static reconciliation failure origin is valid"),
3292 FailureMessage::new("This tool does not implement reconciliation.")
3293 .expect("static reconciliation failure message is valid"),
3294 RetryAdvice::Never,
3295 )
3296 .expect("static reconciliation failure semantics are coherent");
3297 Self {
3298 failure: Box::new(failure),
3299 }
3300 }
3301}
3302
3303#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
3305#[non_exhaustive]
3306pub enum ToolReconciliationProbeErrorBuildError {
3307 #[error("tool reconciliation probe failure cannot require reconciliation")]
3309 RecursiveReconciliation,
3310 #[error("tool reconciliation probe retry advice is invalid: {source}")]
3312 InvalidRetry {
3313 #[source]
3315 source: ToolReconciliationObservationError,
3316 },
3317}
3318
3319impl ToolReconciliationProbeErrorBuildError {
3320 const fn invalid_retry(source: ToolReconciliationObservationError) -> Self {
3321 Self::InvalidRetry { source }
3322 }
3323}
3324
3325pub trait ErasedTool: Send + Sync + 'static {
3331 fn descriptor(&self) -> &ToolDescriptor;
3333
3334 #[must_use]
3341 fn supports_reconciliation(&self) -> bool {
3342 false
3343 }
3344
3345 fn call(
3347 &self,
3348 context: ToolContext,
3349 input: ToolInput,
3350 ) -> crate::BoxFuture<'_, Result<ToolResult, ToolError>>;
3351
3352 fn reconcile(
3359 &self,
3360 _context: ToolReconciliationContext,
3361 _input: ToolInput,
3362 ) -> crate::BoxFuture<'_, Result<ToolReconciliationObservation, ToolReconciliationProbeError>>
3363 {
3364 Box::pin(async { Err(ToolReconciliationProbeError::unsupported()) })
3365 }
3366}
3367
3368pub struct ToolAdapter<T, R> {
3370 tool: T,
3371 descriptor: ToolDescriptor,
3372 registry: R,
3373}
3374
3375impl<T, R> ToolAdapter<T, R>
3376where
3377 T: Tool,
3378 R: ToolSchemaRegistry,
3379{
3380 pub fn new(tool: T, registry: R) -> Result<Self, ToolAdapterBuildError> {
3387 let descriptor = tool.descriptor().clone();
3388 let input_schema = SchemaGenerator::default().into_root_schema_for::<T::Input>();
3389 registry
3390 .validate_type_schema(
3391 descriptor.input_schema(),
3392 ToolSchemaRole::Input,
3393 &input_schema,
3394 )
3395 .map_err(|source| ToolAdapterBuildError::SchemaContract {
3396 role: ToolSchemaRole::Input,
3397 source,
3398 })?;
3399 let output_schema = SchemaGenerator::default().into_root_schema_for::<T::Output>();
3400 registry
3401 .validate_type_schema(
3402 descriptor.output_schema(),
3403 ToolSchemaRole::Output,
3404 &output_schema,
3405 )
3406 .map_err(|source| ToolAdapterBuildError::SchemaContract {
3407 role: ToolSchemaRole::Output,
3408 source,
3409 })?;
3410 Ok(Self {
3411 tool,
3412 descriptor,
3413 registry,
3414 })
3415 }
3416
3417 #[must_use]
3419 pub const fn tool(&self) -> &T {
3420 &self.tool
3421 }
3422
3423 #[must_use]
3425 pub const fn registry(&self) -> &R {
3426 &self.registry
3427 }
3428
3429 #[must_use]
3431 pub fn into_inner(self) -> (T, R) {
3432 (self.tool, self.registry)
3433 }
3434}
3435
3436impl<T, R> ErasedTool for ToolAdapter<T, R>
3437where
3438 T: Tool,
3439 R: ToolSchemaRegistry,
3440{
3441 fn descriptor(&self) -> &ToolDescriptor {
3442 &self.descriptor
3443 }
3444
3445 fn call(
3446 &self,
3447 context: ToolContext,
3448 input: ToolInput,
3449 ) -> crate::BoxFuture<'_, Result<ToolResult, ToolError>> {
3450 Box::pin(async move {
3451 input
3452 .validate_for(&context, &self.descriptor)
3453 .map_err(|source| {
3454 preparation_adapter_error(
3455 &context,
3456 &self.descriptor,
3457 "stateknot.tool.input_binding_invalid",
3458 "Tool input does not match the admitted invocation.",
3459 source,
3460 )
3461 })?;
3462
3463 self.registry
3464 .validate_instance(
3465 self.descriptor.input_schema(),
3466 ToolSchemaRole::Input,
3467 input.value(),
3468 )
3469 .map_err(|source| {
3470 preparation_adapter_error(
3471 &context,
3472 &self.descriptor,
3473 "stateknot.tool.input_schema_invalid",
3474 "Tool input does not satisfy its registered schema.",
3475 source,
3476 )
3477 })?;
3478
3479 let (_, input) = input.into_parts();
3480 let typed_input =
3481 serde_json::from_value::<T::Input>(input.into_value()).map_err(|source| {
3482 preparation_adapter_error(
3483 &context,
3484 &self.descriptor,
3485 "stateknot.tool.input_decode_failed",
3486 "Tool input could not be decoded into its registered type.",
3487 source,
3488 )
3489 })?;
3490
3491 let output = match self.tool.call(context.clone(), typed_input).await {
3492 Ok(output) => output,
3493 Err(error) => {
3494 return match error.validate_for(&context, &self.descriptor) {
3495 Ok(()) => Err(error),
3496 Err(source) => Err(invalid_tool_error(&context, &self.descriptor, source)),
3497 };
3498 }
3499 };
3500
3501 let (typed_output, artifacts) = output.into_parts();
3502 let output_value = serde_json::to_value(typed_output).map_err(|source| {
3503 result_adapter_error(
3504 &context,
3505 &self.descriptor,
3506 "stateknot.tool.output_encode_failed",
3507 "Tool output could not be encoded from its registered type.",
3508 source,
3509 )
3510 })?;
3511 let bounded_output = BoundedJson::try_from_value_with_limits(
3512 output_value,
3513 tool_output_json_limits(&self.descriptor),
3514 )
3515 .map_err(|source| {
3516 result_adapter_error(
3517 &context,
3518 &self.descriptor,
3519 "stateknot.tool.output_limit_exceeded",
3520 "Tool output exceeded its registered resource limits.",
3521 source,
3522 )
3523 })?;
3524
3525 self.registry
3526 .validate_instance(
3527 self.descriptor.output_schema(),
3528 ToolSchemaRole::Output,
3529 &bounded_output,
3530 )
3531 .map_err(|source| {
3532 result_adapter_error(
3533 &context,
3534 &self.descriptor,
3535 "stateknot.tool.output_schema_invalid",
3536 "Tool output does not satisfy its registered schema.",
3537 source,
3538 )
3539 })?;
3540
3541 let result =
3542 ToolResult::for_invocation(&context, &self.descriptor, bounded_output, artifacts);
3543 result
3544 .validate_for(&context, &self.descriptor)
3545 .map_err(|source| {
3546 result_adapter_error(
3547 &context,
3548 &self.descriptor,
3549 "stateknot.tool.result_binding_invalid",
3550 "Tool result does not match the admitted invocation.",
3551 source,
3552 )
3553 })?;
3554 Ok(result)
3555 })
3556 }
3557}
3558
3559#[derive(Debug, Error)]
3561#[non_exhaustive]
3562pub enum ToolAdapterBuildError {
3563 #[error("registered {role:?} tool schema rejected the generated Rust type schema: {source}")]
3565 SchemaContract {
3566 role: ToolSchemaRole,
3568 #[source]
3570 source: ToolSchemaValidationError,
3571 },
3572}
3573
3574fn tool_output_json_limits(descriptor: &ToolDescriptor) -> JsonLimits {
3575 let descriptor_bytes =
3576 usize::try_from(descriptor.limits().max_inline_result_bytes().get()).unwrap_or(usize::MAX);
3577 let max_bytes = descriptor_bytes.min(JsonLimits::MAXIMUM.max_bytes());
3578 JsonLimits::try_new(
3579 max_bytes,
3580 JsonLimits::MAXIMUM.max_depth(),
3581 JsonLimits::MAXIMUM.max_container_entries(),
3582 JsonLimits::MAXIMUM.max_nodes(),
3583 JsonLimits::MAXIMUM.max_string_bytes(),
3584 JsonLimits::MAXIMUM.max_object_key_bytes(),
3585 )
3586 .expect("positive descriptor bytes narrowed to static JSON hard limits are valid")
3587}
3588
3589fn preparation_adapter_error<E>(
3590 context: &ToolContext,
3591 descriptor: &ToolDescriptor,
3592 code: &str,
3593 message: &str,
3594 source: E,
3595) -> ToolError
3596where
3597 E: StdError + Send + Sync + 'static,
3598{
3599 let effect = if descriptor.semantics().risk() == ToolRisk::ReadOnly {
3600 ToolExternalEffect::NotApplicable
3601 } else {
3602 ToolExternalEffect::NotStarted
3603 };
3604 adapter_error(
3605 context,
3606 descriptor,
3607 FailureCategory::InvalidInput,
3608 RetryAdvice::Never,
3609 code,
3610 message,
3611 ToolErrorPhase::Preparation,
3612 effect,
3613 source,
3614 )
3615}
3616
3617fn result_adapter_error<E>(
3618 context: &ToolContext,
3619 descriptor: &ToolDescriptor,
3620 code: &str,
3621 message: &str,
3622 source: E,
3623) -> ToolError
3624where
3625 E: StdError + Send + Sync + 'static,
3626{
3627 let effect = if descriptor.semantics().risk() == ToolRisk::ReadOnly {
3628 ToolExternalEffect::NotApplicable
3629 } else {
3630 ToolExternalEffect::Applied
3631 };
3632 adapter_error(
3633 context,
3634 descriptor,
3635 FailureCategory::Internal,
3636 RetryAdvice::Never,
3637 code,
3638 message,
3639 ToolErrorPhase::Result,
3640 effect,
3641 source,
3642 )
3643}
3644
3645fn invalid_tool_error<E>(context: &ToolContext, descriptor: &ToolDescriptor, source: E) -> ToolError
3646where
3647 E: StdError + Send + Sync + 'static,
3648{
3649 let (category, advice, effect) = if descriptor.semantics().risk() == ToolRisk::ReadOnly {
3650 (
3651 FailureCategory::Internal,
3652 RetryAdvice::Never,
3653 ToolExternalEffect::NotApplicable,
3654 )
3655 } else {
3656 (
3657 FailureCategory::AmbiguousExternalOutcome,
3658 RetryAdvice::ReconcileFirst,
3659 ToolExternalEffect::Unknown,
3660 )
3661 };
3662 adapter_error(
3663 context,
3664 descriptor,
3665 category,
3666 advice,
3667 "stateknot.tool.invalid_error_evidence",
3668 "Tool returned failure evidence that does not match its admitted invocation.",
3669 ToolErrorPhase::Execution,
3670 effect,
3671 source,
3672 )
3673}
3674
3675#[allow(clippy::too_many_arguments)]
3676fn adapter_error<E>(
3677 context: &ToolContext,
3678 descriptor: &ToolDescriptor,
3679 category: FailureCategory,
3680 advice: RetryAdvice,
3681 code: &str,
3682 message: &str,
3683 phase: ToolErrorPhase,
3684 effect: ToolExternalEffect,
3685 source: E,
3686) -> ToolError
3687where
3688 E: StdError + Send + Sync + 'static,
3689{
3690 let failure = Failure::new(
3691 FailureId::generate(),
3692 category,
3693 FailureCode::new(code).expect("static adapter failure code must be valid"),
3694 FailureOrigin::new("stateknot.tool_adapter")
3695 .expect("static adapter failure origin must be valid"),
3696 FailureMessage::new(message).expect("static adapter failure message must be valid"),
3697 advice,
3698 )
3699 .expect("adapter category and retry advice must be compatible")
3700 .with_private_source(source);
3701 ToolError::new(
3702 failure,
3703 phase,
3704 effect,
3705 ToolErrorProvenance::for_invocation(context, descriptor),
3706 )
3707 .expect("adapter phase and effect evidence must be compatible")
3708}
3709
3710fn byte_count_from_usize(value: usize) -> ByteCount {
3711 ByteCount::new(u64::try_from(value).unwrap_or(u64::MAX))
3712}
3713
3714fn execution_count_from_usize(value: usize) -> ExecutionCount {
3715 ExecutionCount::new(u64::try_from(value).unwrap_or(u64::MAX))
3716}
3717
3718#[cfg(test)]
3719mod tests {
3720 use std::{
3721 future::Future,
3722 sync::atomic::{AtomicUsize, Ordering},
3723 task::{Context, Poll, Wake, Waker},
3724 };
3725
3726 use serde_json::{Value, json, to_value};
3727
3728 use super::*;
3729 use crate::{
3730 ArtifactId, BudgetUsage, FailureBuildError, ResolvedBudget, ToolCancellationSupport,
3731 };
3732
3733 const ATTEMPT_ID: &str = "01912345-6789-7abc-8def-0123456789ab";
3734 const SECOND_ATTEMPT_ID: &str = "01912345-6789-7abc-8def-0123456789ac";
3735 const INVOCATION_ID: &str = "01912345-6789-7abc-8def-0123456789ad";
3736 const RUN_ID: &str = "01912345-6789-7abc-8def-0123456789ae";
3737 const THREAD_ID: &str = "01912345-6789-7abc-8def-0123456789af";
3738 const FAILURE_ID: &str = "01912345-6789-7abc-8def-0123456789b0";
3739 const OBSERVED_AT: &str = "2029-12-31T23:59:59.000000Z";
3740
3741 fn descriptor() -> ToolDescriptor {
3742 let fixture: Value =
3743 serde_json::from_str(include_str!("../tests/fixtures/core-tool-v1.json")).unwrap();
3744 serde_json::from_value(fixture["descriptors"]["valid"][0].clone()).unwrap()
3745 }
3746
3747 fn descriptor_with_progress(maximum: u64) -> ToolDescriptor {
3748 let fixture: Value =
3749 serde_json::from_str(include_str!("../tests/fixtures/core-tool-v1.json")).unwrap();
3750 let mut value = fixture["descriptors"]["valid"][0].clone();
3751 value["invocation"]["max_progress_events"] = Value::from(maximum.to_string());
3752 serde_json::from_value(value).unwrap()
3753 }
3754
3755 fn remaining_budget(observed_at: Timestamp) -> BudgetRemaining {
3756 let fixture: Value =
3757 serde_json::from_str(include_str!("../tests/fixtures/core-budget-v1.json")).unwrap();
3758 let resolved =
3759 serde_json::from_value::<ResolvedBudget>(fixture["resolved"]["valid"][0].clone())
3760 .unwrap();
3761 resolved
3762 .remaining(&BudgetUsage::zero(), observed_at)
3763 .unwrap()
3764 }
3765
3766 fn context_with_attempt(attempt_id: AttemptId) -> ToolContext {
3767 let descriptor = descriptor();
3768 let observed_at = OBSERVED_AT.parse::<Timestamp>().unwrap();
3769 ToolContext::new(
3770 TenantId::new("tenant-production").unwrap(),
3771 RUN_ID.parse().unwrap(),
3772 THREAD_ID.parse().unwrap(),
3773 INVOCATION_ID.parse().unwrap(),
3774 attempt_id,
3775 &descriptor,
3776 remaining_budget(observed_at),
3777 DurationMillis::new(30_000).unwrap(),
3778 observed_at,
3779 Instant::now(),
3780 CancellationSignal::never(),
3781 )
3782 .unwrap()
3783 }
3784
3785 fn context() -> ToolContext {
3786 context_with_attempt(ATTEMPT_ID.parse().unwrap())
3787 }
3788
3789 fn failure(category: FailureCategory, advice: RetryAdvice) -> Failure {
3790 Failure::new(
3791 FAILURE_ID.parse().unwrap(),
3792 category,
3793 FailureCode::new("tool.execution_failed").unwrap(),
3794 FailureOrigin::new("tool.example").unwrap(),
3795 FailureMessage::new("The tool operation did not complete.").unwrap(),
3796 advice,
3797 )
3798 .unwrap()
3799 }
3800
3801 fn provenance() -> ToolErrorProvenance {
3802 let descriptor = descriptor();
3803 ToolErrorProvenance::new(
3804 INVOCATION_ID.parse().unwrap(),
3805 ATTEMPT_ID.parse().unwrap(),
3806 descriptor.metadata().identity().clone(),
3807 )
3808 }
3809
3810 #[test]
3811 fn context_intersects_deadlines_and_reuses_key_across_attempts() {
3812 let first = context_with_attempt(ATTEMPT_ID.parse().unwrap());
3813 let second = context_with_attempt(SECOND_ATTEMPT_ID.parse().unwrap());
3814
3815 assert_eq!(first.invocation_id(), second.invocation_id());
3816 assert_ne!(first.attempt_id(), second.attempt_id());
3817 assert_eq!(
3818 first.required_idempotency_key().unwrap(),
3819 second.required_idempotency_key().unwrap()
3820 );
3821 assert_eq!(
3822 first.required_idempotency_key().unwrap().to_string(),
3823 INVOCATION_ID
3824 );
3825 assert_eq!(
3826 first.deadline(),
3827 "2030-01-01T00:00:00.000000Z".parse().unwrap()
3828 );
3829 assert_eq!(first.remaining_time_at(first.deadline_instant()), None);
3830 }
3831
3832 #[test]
3833 fn context_rejects_zero_and_widened_timeouts() {
3834 let descriptor = descriptor();
3835 let observed_at = OBSERVED_AT.parse::<Timestamp>().unwrap();
3836 let make = |timeout| {
3837 ToolContext::new(
3838 TenantId::new("tenant-production").unwrap(),
3839 RUN_ID.parse().unwrap(),
3840 THREAD_ID.parse().unwrap(),
3841 INVOCATION_ID.parse().unwrap(),
3842 ATTEMPT_ID.parse().unwrap(),
3843 &descriptor,
3844 remaining_budget(observed_at),
3845 timeout,
3846 observed_at,
3847 Instant::now(),
3848 CancellationSignal::never(),
3849 )
3850 };
3851 assert_eq!(
3852 make(DurationMillis::ZERO).unwrap_err(),
3853 ToolContextError::ZeroEffectiveTimeout
3854 );
3855 assert!(matches!(
3856 make(DurationMillis::new(30_001).unwrap()),
3857 Err(ToolContextError::TimeoutExceedsDescriptor { .. })
3858 ));
3859 }
3860
3861 #[test]
3862 fn reconciliation_context_preserves_original_identity_and_is_finite() {
3863 let descriptor = descriptor();
3864 let observed_at = OBSERVED_AT.parse::<Timestamp>().unwrap();
3865 let handle = ToolRecoveryHandle::new(
3866 FailureOrigin::new("protocol.a2a.task").unwrap(),
3867 Digest::sha256(b"agent-card"),
3868 "remote-task-42",
3869 )
3870 .unwrap();
3871 let origin_event_id = FAILURE_ID.parse().unwrap();
3872 let context = ToolReconciliationContext::new(
3873 TenantId::new("tenant-production").unwrap(),
3874 RUN_ID.parse().unwrap(),
3875 THREAD_ID.parse().unwrap(),
3876 INVOCATION_ID.parse().unwrap(),
3877 ATTEMPT_ID.parse().unwrap(),
3878 &descriptor,
3879 DurationMillis::new(30_000).unwrap(),
3880 observed_at,
3881 Instant::now(),
3882 "2030-01-01T00:00:00.000000Z".parse().unwrap(),
3883 CancellationSignal::never(),
3884 )
3885 .unwrap()
3886 .with_durable_recovery(origin_event_id, Some(handle.clone()));
3887
3888 context.validate_for(&descriptor).unwrap();
3889 assert_eq!(context.invocation_id().to_string(), INVOCATION_ID);
3890 assert_eq!(context.attempt_id().to_string(), ATTEMPT_ID);
3891 assert_eq!(
3892 context.idempotency_key().unwrap().to_string(),
3893 INVOCATION_ID
3894 );
3895 assert_eq!(
3896 context.deadline(),
3897 "2030-01-01T00:00:00.000000Z".parse().unwrap()
3898 );
3899 assert_eq!(context.origin_event_id(), Some(origin_event_id));
3900 assert_eq!(context.recovery_handle(), Some(&handle));
3901 assert!(format!("{context:?}").contains("has_idempotency_key: true"));
3902 }
3903
3904 #[test]
3905 fn reconciliation_polling_and_probe_failures_are_bounded() {
3906 assert_eq!(
3907 ToolReconciliationObservation::pending(DurationMillis::ZERO).unwrap_err(),
3908 ToolReconciliationObservationError::ZeroRetryDelay
3909 );
3910 let excessive = DurationMillis::new(3_600_001).unwrap();
3911 assert!(matches!(
3912 ToolReconciliationObservation::pending(excessive),
3913 Err(ToolReconciliationObservationError::RetryDelayTooLarge { .. })
3914 ));
3915 let ambiguous = failure(
3916 FailureCategory::AmbiguousExternalOutcome,
3917 RetryAdvice::ReconcileFirst,
3918 );
3919 assert_eq!(
3920 ToolReconciliationProbeError::new(ambiguous).unwrap_err(),
3921 ToolReconciliationProbeErrorBuildError::RecursiveReconciliation
3922 );
3923 let zero_retry = failure(
3924 FailureCategory::DependencyUnavailable,
3925 RetryAdvice::SafeAfter {
3926 delay: DurationMillis::ZERO,
3927 },
3928 );
3929 assert!(matches!(
3930 ToolReconciliationProbeError::new(zero_retry),
3931 Err(ToolReconciliationProbeErrorBuildError::InvalidRetry { .. })
3932 ));
3933 }
3934
3935 #[test]
3936 fn input_requires_an_object_and_binds_schema_and_limits() {
3937 let descriptor = descriptor();
3938 assert_eq!(
3939 ToolInput::new(
3940 descriptor.input_schema().clone(),
3941 BoundedJson::try_from_value(json!([1, 2])).unwrap(),
3942 ),
3943 Err(ToolInputError::ObjectRootRequired)
3944 );
3945 let input = ToolInput::new(
3946 descriptor.input_schema().clone(),
3947 BoundedJson::try_from_value(json!({ "amount": 42 })).unwrap(),
3948 )
3949 .unwrap();
3950 input.validate_for(&context(), &descriptor).unwrap();
3951 assert!(!format!("{input:?}").contains("amount"));
3952 }
3953
3954 fn artifact_value() -> Value {
3955 let fixture: Value =
3956 serde_json::from_str(include_str!("../tests/fixtures/core-artifact-v1.json")).unwrap();
3957 fixture["artifact_refs"]["valid"][0].clone()
3958 }
3959
3960 fn bound_artifact(tenant: &str, artifact_id: ArtifactId) -> ArtifactRef {
3961 let descriptor = descriptor();
3962 let mut value = artifact_value();
3963 value["identity"]["tenant_id"] = Value::from(tenant);
3964 value["identity"]["artifact_id"] = Value::from(artifact_id.to_string());
3965 value["provenance"]["principal"] =
3966 to_value(descriptor.metadata().identity().owner()).unwrap();
3967 value["provenance"]["capability"] =
3968 to_value(descriptor.metadata().identity().capability()).unwrap();
3969 value["provenance"]["run_id"] = Value::from(RUN_ID);
3970 serde_json::from_value(value).unwrap()
3971 }
3972
3973 #[test]
3974 fn artifacts_are_unique_bounded_and_checked_against_tenant() {
3975 let first = bound_artifact("tenant-production", ArtifactId::generate());
3976 assert_eq!(
3977 ToolArtifacts::try_new([first.clone(), first]),
3978 Err(ToolArtifactsError::DuplicateIdentity)
3979 );
3980
3981 let too_many = (0..=ToolArtifacts::MAX_LEN)
3982 .map(|_| bound_artifact("tenant-production", ArtifactId::generate()));
3983 assert!(matches!(
3984 ToolArtifacts::try_new(too_many),
3985 Err(ToolArtifactsError::TooMany { .. })
3986 ));
3987
3988 let descriptor = descriptor();
3989 let context = context();
3990 let artifacts =
3991 ToolArtifacts::try_new([bound_artifact("tenant-other", ArtifactId::generate())])
3992 .unwrap();
3993 let result = ToolResult::for_invocation(
3994 &context,
3995 &descriptor,
3996 BoundedJson::try_from_value(json!({ "accepted": true })).unwrap(),
3997 artifacts,
3998 );
3999 assert!(matches!(
4000 result.validate_for(&context, &descriptor),
4001 Err(ToolResultValidationError::ArtifactTenantMismatch { .. })
4002 ));
4003 }
4004
4005 #[test]
4006 fn tool_error_requires_exact_unknown_effect_and_ambiguity_pair() {
4007 assert_eq!(
4008 ToolError::new(
4009 failure(FailureCategory::Internal, RetryAdvice::Never),
4010 ToolErrorPhase::Execution,
4011 ToolExternalEffect::Unknown,
4012 provenance(),
4013 )
4014 .unwrap_err(),
4015 ToolErrorBuildError::UnknownEffectRequiresAmbiguousFailure
4016 );
4017 let ambiguous = ToolError::new(
4018 failure(
4019 FailureCategory::AmbiguousExternalOutcome,
4020 RetryAdvice::ReconcileFirst,
4021 ),
4022 ToolErrorPhase::Execution,
4023 ToolExternalEffect::Unknown,
4024 provenance(),
4025 )
4026 .unwrap();
4027 ambiguous.validate_for(&context(), &descriptor()).unwrap();
4028 assert_eq!(ambiguous.external_effect(), ToolExternalEffect::Unknown);
4029
4030 assert!(matches!(
4031 Failure::new(
4032 FailureId::generate(),
4033 FailureCategory::AmbiguousExternalOutcome,
4034 FailureCode::new("tool.ambiguous").unwrap(),
4035 FailureOrigin::new("tool.example").unwrap(),
4036 FailureMessage::new("The external outcome is unknown.").unwrap(),
4037 RetryAdvice::Never,
4038 ),
4039 Err(FailureBuildError::AmbiguousOutcomeRequiresReconciliation)
4040 ));
4041 }
4042
4043 #[test]
4044 fn recovery_handles_are_bounded_redacted_and_only_bind_unknown_outcomes() {
4045 let handle = ToolRecoveryHandle::new(
4046 FailureOrigin::new("protocol.a2a.task").unwrap(),
4047 Digest::sha256(b"agent-card"),
4048 "remote-task-secret-42",
4049 )
4050 .unwrap();
4051 assert!(!format!("{handle:?}").contains("remote-task-secret-42"));
4052 assert_eq!(
4053 ToolRecoveryHandle::new(
4054 FailureOrigin::new("protocol.a2a.task").unwrap(),
4055 Digest::sha256(b"agent-card"),
4056 " remote-task",
4057 )
4058 .unwrap_err(),
4059 ToolRecoveryHandleError::OpaqueIdBoundaryWhitespace
4060 );
4061
4062 let ambiguous = ToolError::new(
4063 failure(
4064 FailureCategory::AmbiguousExternalOutcome,
4065 RetryAdvice::ReconcileFirst,
4066 ),
4067 ToolErrorPhase::Execution,
4068 ToolExternalEffect::Unknown,
4069 provenance(),
4070 )
4071 .unwrap()
4072 .with_recovery_handle(handle.clone())
4073 .unwrap();
4074 assert_eq!(ambiguous.recovery_handle(), Some(&handle));
4075 let encoded = to_value(&ambiguous).unwrap();
4076 assert_eq!(
4077 encoded["recovery_handle"]["opaque_id"],
4078 "remote-task-secret-42"
4079 );
4080 let decoded: ToolError = serde_json::from_value(encoded).unwrap();
4081 assert_eq!(decoded.recovery_handle(), Some(&handle));
4082
4083 let known = ToolError::new(
4084 failure(FailureCategory::Internal, RetryAdvice::Never),
4085 ToolErrorPhase::Execution,
4086 ToolExternalEffect::Applied,
4087 provenance(),
4088 )
4089 .unwrap();
4090 assert_eq!(
4091 known.with_recovery_handle(handle).unwrap_err(),
4092 ToolErrorBuildError::RecoveryHandleRequiresUnknownEffect
4093 );
4094 }
4095
4096 #[derive(Debug, Deserialize, JsonSchema)]
4097 #[serde(deny_unknown_fields)]
4098 struct CaptureInput {
4099 amount: u64,
4100 }
4101
4102 #[derive(Debug, JsonSchema, Serialize)]
4103 #[serde(deny_unknown_fields)]
4104 struct CaptureOutput {
4105 accepted: bool,
4106 key: String,
4107 }
4108
4109 struct CaptureTool {
4110 descriptor: ToolDescriptor,
4111 }
4112
4113 impl Tool for CaptureTool {
4114 type Input = CaptureInput;
4115 type Output = CaptureOutput;
4116
4117 fn descriptor(&self) -> &ToolDescriptor {
4118 &self.descriptor
4119 }
4120
4121 fn call(
4122 &self,
4123 context: ToolContext,
4124 input: Self::Input,
4125 ) -> crate::BoxFuture<'_, Result<ToolOutput<Self::Output>, ToolError>> {
4126 let key = context.required_idempotency_key().unwrap().to_string();
4127 Box::pin(async move {
4128 Ok(ToolOutput::inline(CaptureOutput {
4129 accepted: input.amount > 0,
4130 key,
4131 }))
4132 })
4133 }
4134 }
4135
4136 #[derive(Default)]
4137 struct AcceptingRegistry {
4138 type_validations: AtomicUsize,
4139 instance_validations: AtomicUsize,
4140 }
4141
4142 impl ToolSchemaRegistry for AcceptingRegistry {
4143 fn validate_type_schema(
4144 &self,
4145 _: &SchemaReference,
4146 _: ToolSchemaRole,
4147 _: &Schema,
4148 ) -> Result<(), ToolSchemaValidationError> {
4149 self.type_validations.fetch_add(1, Ordering::Relaxed);
4150 Ok(())
4151 }
4152
4153 fn validate_instance(
4154 &self,
4155 _: &SchemaReference,
4156 _: ToolSchemaRole,
4157 _: &BoundedJson,
4158 ) -> Result<(), ToolSchemaValidationError> {
4159 self.instance_validations.fetch_add(1, Ordering::Relaxed);
4160 Ok(())
4161 }
4162 }
4163
4164 struct NoopWake;
4165
4166 impl Wake for NoopWake {
4167 fn wake(self: Arc<Self>) {}
4168 }
4169
4170 fn poll_ready<F>(future: F) -> F::Output
4171 where
4172 F: Future,
4173 {
4174 let waker = Waker::from(Arc::new(NoopWake));
4175 let mut context = Context::from_waker(&waker);
4176 let mut future = std::pin::pin!(future);
4177 match future.as_mut().poll(&mut context) {
4178 Poll::Ready(output) => output,
4179 Poll::Pending => panic!("test future unexpectedly remained pending"),
4180 }
4181 }
4182
4183 #[derive(Default)]
4184 struct RecordingProgressSink {
4185 events: Mutex<Vec<ToolProgressEvent>>,
4186 }
4187
4188 impl ToolProgressSink for RecordingProgressSink {
4189 fn emit(
4190 &self,
4191 event: ToolProgressEvent,
4192 ) -> crate::BoxFuture<'_, Result<(), ToolProgressSinkError>> {
4193 Box::pin(async move {
4194 self.events.lock().unwrap().push(event);
4195 Ok(())
4196 })
4197 }
4198 }
4199
4200 struct PendingProgressSink;
4201
4202 impl ToolProgressSink for PendingProgressSink {
4203 fn emit(
4204 &self,
4205 _: ToolProgressEvent,
4206 ) -> crate::BoxFuture<'_, Result<(), ToolProgressSinkError>> {
4207 Box::pin(std::future::pending())
4208 }
4209 }
4210
4211 struct FailingProgressSink;
4212
4213 impl ToolProgressSink for FailingProgressSink {
4214 fn emit(
4215 &self,
4216 _: ToolProgressEvent,
4217 ) -> crate::BoxFuture<'_, Result<(), ToolProgressSinkError>> {
4218 Box::pin(async {
4219 Err(ToolProgressSinkError::new(std::io::Error::other(
4220 "private sink detail",
4221 )))
4222 })
4223 }
4224 }
4225
4226 fn progress_context(
4227 descriptor: &ToolDescriptor,
4228 sink: Arc<dyn ToolProgressSink>,
4229 ) -> ToolContext {
4230 let observed_at = OBSERVED_AT.parse::<Timestamp>().unwrap();
4231 ToolContext::new_with_progress(
4232 TenantId::new("tenant-production").unwrap(),
4233 RUN_ID.parse().unwrap(),
4234 THREAD_ID.parse().unwrap(),
4235 INVOCATION_ID.parse().unwrap(),
4236 ATTEMPT_ID.parse().unwrap(),
4237 descriptor,
4238 remaining_budget(observed_at),
4239 DurationMillis::new(30_000).unwrap(),
4240 observed_at,
4241 Instant::now(),
4242 CancellationSignal::never(),
4243 sink,
4244 )
4245 .unwrap()
4246 }
4247
4248 #[test]
4249 fn progress_reporter_orders_normalizes_and_bounds_events() {
4250 let descriptor = descriptor_with_progress(2);
4251 let sink = Arc::new(RecordingProgressSink::default());
4252 let context = progress_context(&descriptor, sink.clone());
4253 let reporter = context.progress().unwrap();
4254
4255 let first = poll_ready(
4256 reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(1), None).unwrap()),
4257 )
4258 .unwrap();
4259 let second = poll_ready(reporter.emit(
4260 ToolProgressUpdate::new(ExecutionCount::new(2), Some(ExecutionCount::new(10))).unwrap(),
4261 ))
4262 .unwrap();
4263 assert_eq!(first.sequence(), ExecutionCount::ZERO);
4264 assert_eq!(second.sequence(), ExecutionCount::new(1));
4265 assert_eq!(second.update().total(), Some(ExecutionCount::new(10)));
4266 first.validate_for(&context, &descriptor).unwrap();
4267 second.validate_for(&context, &descriptor).unwrap();
4268 let outside_capacity = ToolProgressEvent::new(
4269 first.provenance().clone(),
4270 ExecutionCount::new(2),
4271 first.update(),
4272 );
4273 assert!(matches!(
4274 outside_capacity.validate_for(&context, &descriptor),
4275 Err(ToolProgressEventValidationError::SequenceLimitExceeded { .. })
4276 ));
4277 assert_eq!(sink.events.lock().unwrap().as_slice(), &[first, second]);
4278
4279 assert!(matches!(
4280 poll_ready(
4281 reporter.emit(
4282 ToolProgressUpdate::new(ExecutionCount::new(3), Some(ExecutionCount::new(10)),)
4283 .unwrap(),
4284 )
4285 ),
4286 Err(ToolProgressError::MaximumReached { .. })
4287 ));
4288 }
4289
4290 #[test]
4291 fn progress_reporter_rejects_reordering_and_changed_totals() {
4292 let descriptor = descriptor_with_progress(4);
4293 let context = progress_context(&descriptor, Arc::new(RecordingProgressSink::default()));
4294 let reporter = context.progress().unwrap();
4295 poll_ready(reporter.emit(
4296 ToolProgressUpdate::new(ExecutionCount::new(2), Some(ExecutionCount::new(10))).unwrap(),
4297 ))
4298 .unwrap();
4299
4300 assert!(matches!(
4301 poll_ready(
4302 reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(2), None).unwrap(),)
4303 ),
4304 Err(ToolProgressError::NotIncreasing { .. })
4305 ));
4306 assert!(matches!(
4307 poll_ready(
4308 reporter.emit(
4309 ToolProgressUpdate::new(ExecutionCount::new(3), Some(ExecutionCount::new(11)),)
4310 .unwrap(),
4311 )
4312 ),
4313 Err(ToolProgressError::TotalChanged { .. })
4314 ));
4315 }
4316
4317 #[test]
4318 fn progress_failure_or_dropped_future_poison_the_reporter() {
4319 let descriptor = descriptor_with_progress(4);
4320 let failed = progress_context(&descriptor, Arc::new(FailingProgressSink));
4321 let error = poll_ready(
4322 failed
4323 .progress()
4324 .unwrap()
4325 .emit(ToolProgressUpdate::new(ExecutionCount::new(1), None).unwrap()),
4326 )
4327 .unwrap_err();
4328 assert!(matches!(error, ToolProgressError::Sink { .. }));
4329 assert!(!format!("{error:?}").contains("private sink detail"));
4330 assert!(matches!(
4331 poll_ready(
4332 failed
4333 .progress()
4334 .unwrap()
4335 .emit(ToolProgressUpdate::new(ExecutionCount::new(2), None).unwrap(),)
4336 ),
4337 Err(ToolProgressError::StatePoisoned)
4338 ));
4339
4340 let pending = progress_context(&descriptor, Arc::new(PendingProgressSink));
4341 let reporter = pending.progress().unwrap();
4342 let mut first =
4343 reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(1), None).unwrap());
4344 let waker = Waker::from(Arc::new(NoopWake));
4345 let mut task_context = Context::from_waker(&waker);
4346 assert!(matches!(
4347 first.as_mut().poll(&mut task_context),
4348 Poll::Pending
4349 ));
4350 assert!(matches!(
4351 poll_ready(
4352 reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(2), None).unwrap(),)
4353 ),
4354 Err(ToolProgressError::ConcurrentEmission)
4355 ));
4356 drop(first);
4357 assert!(matches!(
4358 poll_ready(
4359 reporter.emit(ToolProgressUpdate::new(ExecutionCount::new(2), None).unwrap(),)
4360 ),
4361 Err(ToolProgressError::StatePoisoned)
4362 ));
4363 }
4364
4365 #[test]
4366 fn progress_updates_reject_impossible_totals() {
4367 assert_eq!(
4368 ToolProgressUpdate::new(ExecutionCount::ZERO, Some(ExecutionCount::ZERO)),
4369 Err(ToolProgressUpdateError::ZeroTotal)
4370 );
4371 assert!(matches!(
4372 ToolProgressUpdate::new(ExecutionCount::new(2), Some(ExecutionCount::new(1)),),
4373 Err(ToolProgressUpdateError::CompletedExceedsTotal { .. })
4374 ));
4375 }
4376
4377 #[test]
4378 fn typed_adapter_validates_both_schemas_and_is_object_safe() {
4379 fn accept_object(_: &dyn ErasedTool) {}
4380 fn assert_send_sync<T: Send + Sync>() {}
4381
4382 let adapter = ToolAdapter::new(
4383 CaptureTool {
4384 descriptor: descriptor(),
4385 },
4386 AcceptingRegistry::default(),
4387 )
4388 .unwrap();
4389 assert_eq!(
4390 adapter.registry().type_validations.load(Ordering::Relaxed),
4391 2
4392 );
4393 accept_object(&adapter);
4394 assert_send_sync::<ToolContext>();
4395 assert_send_sync::<ToolResult>();
4396 assert_send_sync::<ToolError>();
4397
4398 let descriptor = adapter.descriptor().clone();
4399 let context = context();
4400 let input = ToolInput::new(
4401 descriptor.input_schema().clone(),
4402 BoundedJson::try_from_value(json!({ "amount": 42 })).unwrap(),
4403 )
4404 .unwrap();
4405 let result = poll_ready(ErasedTool::call(&adapter, context.clone(), input)).unwrap();
4406 result.validate_for(&context, &descriptor).unwrap();
4407 assert_eq!(result.output().as_value()["accepted"], true);
4408 assert_eq!(result.output().as_value()["key"], INVOCATION_ID);
4409 assert_eq!(
4410 adapter
4411 .registry()
4412 .instance_validations
4413 .load(Ordering::Relaxed),
4414 2
4415 );
4416 }
4417
4418 #[test]
4419 fn wire_contracts_are_closed_and_redact_inline_values() {
4420 let descriptor = descriptor();
4421 let context = context();
4422 let result = ToolResult::for_invocation(
4423 &context,
4424 &descriptor,
4425 BoundedJson::try_from_value(json!({ "secret": "do-not-log" })).unwrap(),
4426 ToolArtifacts::empty(),
4427 );
4428 let value = to_value(&result).unwrap();
4429 let decoded = serde_json::from_value::<ToolResult>(value.clone()).unwrap();
4430 assert_eq!(to_value(decoded).unwrap(), value);
4431 assert!(!format!("{result:?}").contains("do-not-log"));
4432
4433 for schema in [
4434 to_value(schemars::schema_for!(ToolProgressUpdate)).unwrap(),
4435 to_value(schemars::schema_for!(ToolProgressProvenance)).unwrap(),
4436 to_value(schemars::schema_for!(ToolProgressEvent)).unwrap(),
4437 to_value(schemars::schema_for!(ToolInput)).unwrap(),
4438 to_value(schemars::schema_for!(ToolResultProvenance)).unwrap(),
4439 to_value(schemars::schema_for!(ToolResult)).unwrap(),
4440 to_value(schemars::schema_for!(ToolErrorProvenance)).unwrap(),
4441 to_value(schemars::schema_for!(ToolError)).unwrap(),
4442 ] {
4443 assert_eq!(schema["type"], "object");
4444 assert_eq!(schema["additionalProperties"], false);
4445 }
4446
4447 let mut invalid = value;
4448 invalid["provider_payload"] = json!({ "secret": true });
4449 assert!(serde_json::from_value::<ToolResult>(invalid).is_err());
4450 assert_eq!(
4451 descriptor.invocation().cancellation(),
4452 ToolCancellationSupport::Cooperative
4453 );
4454 }
4455}