Skip to main content

stateknot_core/
tool_runtime.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Runtime-neutral typed and erased tool execution contracts.
5
6use 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/// Stable provider-facing idempotency key for one logical tool invocation.
26///
27/// The key is derived only from [`InvocationId`], so every physical
28/// [`AttemptId`] for the same logical invocation receives identical text. It
29/// contains no tenant name, tool arguments, credential, or user-provided
30/// secret. The value is deliberately not serializable as a general payload;
31/// durable invocation records persist the underlying invocation identifier.
32#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
33pub struct ToolIdempotencyKey(InvocationId);
34
35impl ToolIdempotencyKey {
36    /// Derives the stable key for one logical invocation.
37    #[must_use]
38    pub const fn from_invocation_id(invocation_id: InvocationId) -> Self {
39        Self(invocation_id)
40    }
41
42    /// Returns the logical invocation from which this key was derived.
43    #[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/// Bounded opaque reference used to resume one provider-side operation.
62///
63/// The namespace identifies the adapter-owned format and `binding` pins the
64/// exact discovered endpoint or provider configuration. The opaque identifier
65/// is durable but redacted from `Debug`; possessing it never grants access.
66#[derive(Clone, Eq, PartialEq)]
67pub struct ToolRecoveryHandle {
68    namespace: FailureOrigin,
69    binding: Digest,
70    opaque_id: Box<str>,
71}
72
73impl ToolRecoveryHandle {
74    /// Maximum UTF-8 length of the provider-owned identifier.
75    pub const MAX_OPAQUE_ID_BYTES: usize = 1024;
76
77    /// Constructs a provider-bound durable operation handle.
78    ///
79    /// # Errors
80    ///
81    /// Rejects empty, oversized, whitespace-ambiguous, control-bearing, or
82    /// Unicode-noncharacter identifiers.
83    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    /// Returns the adapter-owned handle namespace.
98    #[must_use]
99    pub const fn namespace(&self) -> &FailureOrigin {
100        &self.namespace
101    }
102
103    /// Returns the exact immutable provider/endpoint binding digest.
104    #[must_use]
105    pub const fn binding(&self) -> Digest {
106        self.binding
107    }
108
109    /// Returns the provider-owned identifier to the matching trusted adapter.
110    #[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/// Invalid provider operation handle.
200#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
201#[non_exhaustive]
202pub enum ToolRecoveryHandleError {
203    /// The provider reference was empty.
204    #[error("tool recovery opaque identifier must not be empty")]
205    EmptyOpaqueId,
206    /// The provider reference exceeded the durable wire ceiling.
207    #[error("tool recovery opaque identifier is {actual} bytes; maximum is {maximum}")]
208    OpaqueIdTooLong {
209        /// Maximum accepted UTF-8 byte length.
210        maximum: usize,
211        /// Observed UTF-8 byte length.
212        actual: usize,
213    },
214    /// Leading or trailing whitespace made the identity ambiguous.
215    #[error("tool recovery opaque identifier must not have boundary whitespace")]
216    OpaqueIdBoundaryWhitespace,
217    /// The identifier contained a control or Unicode noncharacter.
218    #[error("tool recovery opaque identifier contains a disallowed code point")]
219    OpaqueIdDisallowedCodePoint,
220}
221
222/// Ephemeral, capability-limited context for reconciling one physical tool attempt.
223///
224/// Reconciliation is not a new business attempt: it receives the original
225/// invocation and attempt identities, never a fresh attempt identifier or a
226/// mutable property bag. The finite deadline is independently bounded by the
227/// run deadline and the frozen tool timeout. A descriptor must explicitly
228/// declare status-query support before this context can be constructed.
229#[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    /// Constructs a finite context for the original ambiguous attempt.
253    ///
254    /// # Errors
255    ///
256    /// Rejects descriptors without status-query support, zero or widened
257    /// timeouts, expired run deadlines, and unrepresentable monotonic deadlines.
258    #[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    /// Intersects artifact capacity with a previously resolved durable limit.
337    ///
338    /// Passing a wider value cannot increase capacity. The runtime supplies the
339    /// invocation intent's system/tenant/policy/run intersection here so a
340    /// reconciliation adapter can reject oversized remote output before it
341    /// creates durable artifacts.
342    #[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    /// Binds the probe to the already committed journal event that caused the
355    /// external operation and to its optional durable provider handle.
356    ///
357    /// The runtime obtains both values from the verified invocation ledger.
358    /// Adapters use the event for artifact provenance and the handle for a
359    /// direct status lookup; neither value grants authorization by itself.
360    #[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    /// Returns the tenant boundary.
372    #[must_use]
373    pub const fn tenant_id(&self) -> &TenantId {
374        &self.tenant_id
375    }
376
377    /// Returns the enclosing run identity.
378    #[must_use]
379    pub const fn run_id(&self) -> RunId {
380        self.run_id
381    }
382
383    /// Returns the enclosing conversation thread identity.
384    #[must_use]
385    pub const fn thread_id(&self) -> ThreadId {
386        self.thread_id
387    }
388
389    /// Returns the original logical invocation identity.
390    #[must_use]
391    pub const fn invocation_id(&self) -> InvocationId {
392        self.invocation_id
393    }
394
395    /// Returns the original physical attempt identity.
396    #[must_use]
397    pub const fn attempt_id(&self) -> AttemptId {
398        self.attempt_id
399    }
400
401    /// Returns the frozen owner-qualified tool identity.
402    #[must_use]
403    pub const fn tool(&self) -> &CapabilityIdentity {
404        &self.tool
405    }
406
407    /// Returns the descriptor-declared idempotency mechanism.
408    #[must_use]
409    pub const fn idempotency(&self) -> ToolIdempotency {
410        self.idempotency
411    }
412
413    /// Returns the stable original invocation key when required.
414    #[must_use]
415    pub const fn idempotency_key(&self) -> Option<ToolIdempotencyKey> {
416        self.idempotency_key
417    }
418
419    /// Returns the trusted wall-clock observation.
420    #[must_use]
421    pub const fn observed_at(&self) -> Timestamp {
422        self.observed_at
423    }
424
425    /// Returns the finite wall-clock probe deadline.
426    #[must_use]
427    pub const fn deadline(&self) -> Timestamp {
428        self.deadline
429    }
430
431    /// Returns the equivalent process-local monotonic deadline.
432    #[must_use]
433    pub const fn deadline_instant(&self) -> Instant {
434        self.deadline_instant
435    }
436
437    /// Returns the effective probe timeout.
438    #[must_use]
439    pub const fn effective_timeout(&self) -> DurationMillis {
440        self.effective_timeout
441    }
442
443    /// Returns the cooperative cancellation signal.
444    #[must_use]
445    pub const fn cancellation(&self) -> &CancellationSignal {
446        &self.cancellation
447    }
448
449    /// Returns the already committed journal event causing this operation.
450    #[must_use]
451    pub const fn origin_event_id(&self) -> Option<EventId> {
452        self.origin_event_id
453    }
454
455    /// Returns the durable, provider-bound operation handle when one exists.
456    #[must_use]
457    pub const fn recovery_handle(&self) -> Option<&ToolRecoveryHandle> {
458        self.recovery_handle.as_ref()
459    }
460
461    /// Returns the resolved maximum number of result artifacts.
462    #[must_use]
463    pub const fn max_artifacts(&self) -> ExecutionCount {
464        self.max_artifacts
465    }
466
467    /// Returns the resolved maximum compact inline result bytes.
468    #[must_use]
469    pub const fn max_inline_result_bytes(&self) -> ByteCount {
470        self.max_inline_result_bytes
471    }
472
473    /// Returns resolved aggregate result-artifact byte capacity.
474    #[must_use]
475    pub const fn max_total_artifact_bytes(&self) -> ByteCount {
476        self.max_total_artifact_bytes
477    }
478
479    /// Returns a stop reason at one monotonic observation.
480    #[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    /// Revalidates this context against the immutable descriptor snapshot.
497    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/// Failure to construct a finite reconciliation context.
563#[derive(Clone, Debug, Eq, Error, PartialEq)]
564#[non_exhaustive]
565pub enum ToolReconciliationContextError {
566    /// The descriptor did not declare an executable status query.
567    #[error("tool descriptor does not support reconciliation status queries")]
568    StatusQueryUnsupported,
569    /// A zero timeout would create an immediately ineligible probe.
570    #[error("tool reconciliation effective timeout must be greater than zero")]
571    ZeroEffectiveTimeout,
572    /// A runtime layer attempted to widen the immutable tool timeout.
573    #[error("tool reconciliation timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
574    TimeoutExceedsDescriptor {
575        /// Immutable descriptor ceiling.
576        descriptor: DurationMillis,
577        /// Rejected effective timeout.
578        actual: DurationMillis,
579    },
580    /// The run deadline was already reached.
581    #[error("tool reconciliation deadline {deadline} was reached at {observed_at}")]
582    DeadlineReached {
583        /// Durable run deadline.
584        deadline: Timestamp,
585        /// Wall-clock observation.
586        observed_at: Timestamp,
587    },
588    /// The finite deadline could not be represented by the monotonic clock.
589    #[error("tool reconciliation monotonic deadline is out of range after {remaining:?}")]
590    MonotonicDeadlineOutOfRange {
591        /// Positive duration to the deadline.
592        remaining: Duration,
593    },
594}
595
596/// Invalid relationship between a reconciliation context and descriptor.
597#[derive(Clone, Debug, Eq, Error, PartialEq)]
598#[non_exhaustive]
599pub enum ToolReconciliationContextBindingError {
600    /// The descriptor no longer declares a status query.
601    #[error("tool descriptor does not support reconciliation status queries")]
602    StatusQueryUnsupported,
603    /// The context names a different immutable tool version.
604    #[error("tool reconciliation identity {actual:?} does not match descriptor {expected:?}")]
605    ToolIdentityMismatch {
606        /// Expected identity.
607        expected: Box<CapabilityIdentity>,
608        /// Actual identity.
609        actual: Box<CapabilityIdentity>,
610    },
611    /// The descriptor idempotency mechanism changed.
612    #[error("tool reconciliation idempotency {actual:?} does not match descriptor {expected:?}")]
613    IdempotencyMismatch {
614        /// Expected mechanism.
615        expected: ToolIdempotency,
616        /// Actual mechanism.
617        actual: ToolIdempotency,
618    },
619    /// The context widened the immutable timeout ceiling.
620    #[error("tool reconciliation timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
621    TimeoutExceedsDescriptor {
622        /// Immutable descriptor ceiling.
623        descriptor: DurationMillis,
624        /// Actual timeout.
625        actual: DurationMillis,
626    },
627    /// The stable idempotency key does not belong to the original invocation.
628    #[error("tool reconciliation idempotency key is not bound to its invocation")]
629    InvalidIdempotencyKeyBinding,
630}
631
632/// Reason a tool boundary must stop before accepting another result.
633#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
634#[non_exhaustive]
635pub enum ToolStopReason {
636    /// The enclosing run requested cooperative cancellation.
637    Cancelled,
638    /// The effective monotonic invocation deadline was reached.
639    DeadlineExceeded,
640}
641
642/// Ephemeral, capability-limited context for exactly one tool attempt.
643///
644/// The context binds stable logical invocation identity to one physical
645/// attempt and one immutable tool version. Its effective deadline is the
646/// intersection of the remaining run deadline and an already narrowed tool
647/// timeout. It exposes a durable idempotency key only when the descriptor
648/// requires one. It contains no arguments, raw credentials, database handle,
649/// provider client, artifact storage coordinates, or mutable property bag.
650///
651/// Cancellation is cooperative and may race with completion. Neither a
652/// cancellation observation nor a timeout proves that a write did not occur.
653#[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    /// Constructs one attempt context from paired wall and monotonic clocks.
678    ///
679    /// `effective_timeout` must already be narrowed by system, tenant, policy,
680    /// and run limits and cannot exceed the descriptor ceiling. `observed_at`
681    /// and `observed_instant` must describe the same runtime observation.
682    ///
683    /// # Errors
684    ///
685    /// Returns [`ToolContextError`] for a zero or widened timeout, an expired
686    /// run deadline, or a monotonic deadline that the platform cannot represent.
687    #[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    /// Intersects artifact capacity with the fully resolved invocation limits.
775    ///
776    /// The runtime calls this before dispatch. It lets an adapter reject a
777    /// remote result before creating objects that a later result validator
778    /// would have to discard.
779    #[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    /// Binds this attempt to its preallocated durable-before-dispatch event.
792    ///
793    /// The runtime calls this before invoking provider code and commits that
794    /// exact event before dispatch. Artifact producers require the value so
795    /// every immutable result has a durable causation anchor.
796    #[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    /// Constructs a context with a durable, ordered progress sink.
803    ///
804    /// This has the same clock and timeout invariants as [`Self::new`]. The
805    /// reporter enforces the descriptor's finite progress-event ceiling and
806    /// serial ordering before forwarding events to `progress_sink`.
807    ///
808    /// # Errors
809    ///
810    /// Returns [`ToolContextError`] under the same conditions as [`Self::new`],
811    /// or when the descriptor declares zero progress events.
812    #[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    /// Returns the tenant boundary for policy, storage, and audit correlation.
857    #[must_use]
858    pub const fn tenant_id(&self) -> &TenantId {
859        &self.tenant_id
860    }
861
862    /// Returns the enclosing durable run identifier.
863    #[must_use]
864    pub const fn run_id(&self) -> RunId {
865        self.run_id
866    }
867
868    /// Returns the enclosing durable conversation thread identifier.
869    #[must_use]
870    pub const fn thread_id(&self) -> ThreadId {
871        self.thread_id
872    }
873
874    /// Returns the stable logical tool invocation identifier.
875    #[must_use]
876    pub const fn invocation_id(&self) -> InvocationId {
877        self.invocation_id
878    }
879
880    /// Returns the exact physical execution-attempt identifier.
881    #[must_use]
882    pub const fn attempt_id(&self) -> AttemptId {
883        self.attempt_id
884    }
885
886    /// Returns the immutable owner-qualified tool version.
887    #[must_use]
888    pub const fn tool(&self) -> &CapabilityIdentity {
889        &self.tool
890    }
891
892    /// Returns the descriptor-declared idempotency mechanism.
893    #[must_use]
894    pub const fn idempotency(&self) -> ToolIdempotency {
895        self.idempotency
896    }
897
898    /// Returns the stable key when this exact tool version requires one.
899    #[must_use]
900    pub const fn idempotency_key(&self) -> Option<ToolIdempotencyKey> {
901        self.idempotency_key
902    }
903
904    /// Returns the required stable idempotency key.
905    ///
906    /// # Errors
907    ///
908    /// Returns [`ToolContextBindingError::IdempotencyKeyNotRequired`] when the
909    /// descriptor uses another mechanism.
910    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    /// Returns the finite remaining run capacity captured for this attempt.
922    #[must_use]
923    pub const fn budget(&self) -> &BudgetRemaining {
924        &self.budget
925    }
926
927    /// Returns the wall-clock observation paired with the monotonic clock.
928    #[must_use]
929    pub const fn observed_at(&self) -> Timestamp {
930        self.observed_at
931    }
932
933    /// Returns the intersected durable wall-clock deadline.
934    #[must_use]
935    pub const fn deadline(&self) -> Timestamp {
936        self.deadline
937    }
938
939    /// Returns the equivalent process-local monotonic deadline.
940    #[must_use]
941    pub const fn deadline_instant(&self) -> Instant {
942        self.deadline_instant
943    }
944
945    /// Returns the already narrowed positive invocation timeout.
946    #[must_use]
947    pub const fn effective_timeout(&self) -> DurationMillis {
948        self.effective_timeout
949    }
950
951    /// Returns the cooperative cancellation signal.
952    #[must_use]
953    pub const fn cancellation(&self) -> &CancellationSignal {
954        &self.cancellation
955    }
956
957    /// Returns the ordered progress reporter when the runtime supplied a sink.
958    #[must_use]
959    pub const fn progress(&self) -> Option<&ToolProgressReporter> {
960        self.progress.as_ref()
961    }
962
963    /// Returns the durable-before-dispatch event causing this attempt.
964    #[must_use]
965    pub const fn origin_event_id(&self) -> Option<EventId> {
966        self.origin_event_id
967    }
968
969    /// Returns the resolved maximum number of result artifacts.
970    #[must_use]
971    pub const fn max_artifacts(&self) -> ExecutionCount {
972        self.max_artifacts
973    }
974
975    /// Returns the resolved maximum compact inline result bytes.
976    #[must_use]
977    pub const fn max_inline_result_bytes(&self) -> ByteCount {
978        self.max_inline_result_bytes
979    }
980
981    /// Returns the resolved aggregate result-artifact byte capacity.
982    #[must_use]
983    pub const fn max_total_artifact_bytes(&self) -> ByteCount {
984        self.max_total_artifact_bytes
985    }
986
987    /// Returns remaining monotonic time, or `None` at and after the deadline.
988    #[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    /// Returns the deterministic stop reason at one monotonic observation.
996    ///
997    /// Cancellation wins when both cancellation and deadline are observable.
998    #[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    /// Rebinds this context to the immutable descriptor used by an executor.
1010    ///
1011    /// # Errors
1012    ///
1013    /// Returns [`ToolContextBindingError`] if identity, idempotency, or timeout
1014    /// differs from the descriptor snapshot.
1015    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/// Failure to construct a finite tool-attempt context.
1088#[derive(Clone, Debug, Eq, Error, PartialEq)]
1089#[non_exhaustive]
1090pub enum ToolContextError {
1091    /// An effective zero timeout would make the attempt immediately ineligible.
1092    #[error("tool context effective timeout must be greater than zero")]
1093    ZeroEffectiveTimeout,
1094    /// A runtime layer attempted to widen the immutable tool timeout.
1095    #[error("tool context timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
1096    TimeoutExceedsDescriptor {
1097        /// Immutable descriptor ceiling.
1098        descriptor: DurationMillis,
1099        /// Rejected effective timeout.
1100        actual: DurationMillis,
1101    },
1102    /// The wall-clock observation reached or passed the run deadline.
1103    #[error("tool context deadline {deadline} was reached at {observed_at}")]
1104    DeadlineReached {
1105        /// Durable run deadline.
1106        deadline: Timestamp,
1107        /// Wall-clock observation used to construct the context.
1108        observed_at: Timestamp,
1109    },
1110    /// The platform monotonic clock could not represent the finite deadline.
1111    #[error("tool context monotonic deadline is out of range after {remaining:?}")]
1112    MonotonicDeadlineOutOfRange {
1113        /// Positive duration between the paired observation and deadline.
1114        remaining: Duration,
1115    },
1116    /// A progress sink was supplied to a descriptor that forbids progress.
1117    #[error("tool descriptor does not allow progress events")]
1118    ProgressUnsupported,
1119}
1120
1121/// Invalid relationship between a tool context and descriptor snapshot.
1122#[derive(Clone, Debug, Eq, Error, PartialEq)]
1123#[non_exhaustive]
1124pub enum ToolContextBindingError {
1125    /// The context names a different owner-qualified tool version.
1126    #[error("tool context identity {actual:?} does not match descriptor {expected:?}")]
1127    ToolIdentityMismatch {
1128        /// Exact descriptor identity.
1129        expected: Box<CapabilityIdentity>,
1130        /// Rejected context identity.
1131        actual: Box<CapabilityIdentity>,
1132    },
1133    /// The captured idempotency mechanism differs from the descriptor.
1134    #[error("tool context idempotency {actual:?} does not match descriptor {expected:?}")]
1135    IdempotencyMismatch {
1136        /// Exact descriptor mechanism.
1137        expected: ToolIdempotency,
1138        /// Rejected context mechanism.
1139        actual: ToolIdempotency,
1140    },
1141    /// A decoded or substituted context widened the timeout ceiling.
1142    #[error("tool context timeout {actual}ms exceeds descriptor timeout {descriptor}ms")]
1143    TimeoutExceedsDescriptor {
1144        /// Immutable descriptor ceiling.
1145        descriptor: DurationMillis,
1146        /// Rejected context timeout.
1147        actual: DurationMillis,
1148    },
1149    /// The stable key was absent, unexpected, or derived from another invocation.
1150    #[error("tool context idempotency key is not bound to its logical invocation")]
1151    InvalidIdempotencyKeyBinding,
1152    /// The caller requested a key for a mechanism that does not use one.
1153    #[error("tool idempotency mechanism {idempotency:?} does not require a key")]
1154    IdempotencyKeyNotRequired {
1155        /// Descriptor mechanism that does not use a runtime-supplied key.
1156        idempotency: ToolIdempotency,
1157    },
1158    /// The reporter ceiling differed from the immutable descriptor snapshot.
1159    #[error("tool progress maximum {actual} does not match descriptor {expected}")]
1160    ProgressLimitMismatch {
1161        /// Descriptor progress-event ceiling.
1162        expected: ExecutionCount,
1163        /// Rejected reporter ceiling.
1164        actual: ExecutionCount,
1165    },
1166    /// The reporter was bound to another invocation, attempt, or tool version.
1167    #[error("tool progress reporter provenance does not match its context")]
1168    ProgressProvenanceMismatch,
1169}
1170
1171/// One normalized numeric progress observation requested by a tool.
1172///
1173/// Units are tool-defined by its registered contract. A known `total` is
1174/// positive and cannot be smaller than `completed`. The reporter enforces
1175/// strict monotonicity across observations and freezes a total once declared.
1176#[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    /// Constructs a structurally valid progress observation.
1186    ///
1187    /// # Errors
1188    ///
1189    /// Returns [`ToolProgressUpdateError`] for a zero total or completed value
1190    /// greater than the known total.
1191    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    /// Returns completed tool-defined units.
1207    #[must_use]
1208    pub const fn completed(self) -> ExecutionCount {
1209        self.completed
1210    }
1211
1212    /// Returns the known total tool-defined units, when declared.
1213    #[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/// Invalid structural progress observation.
1237#[derive(Clone, Debug, Eq, Error, PartialEq)]
1238#[non_exhaustive]
1239pub enum ToolProgressUpdateError {
1240    /// A known total cannot be zero.
1241    #[error("tool progress total must be greater than zero")]
1242    ZeroTotal,
1243    /// Completed units exceeded the known total.
1244    #[error("tool progress completed {completed} exceeds total {total}")]
1245    CompletedExceedsTotal {
1246        /// Rejected completed units.
1247        completed: ExecutionCount,
1248        /// Known total units.
1249        total: ExecutionCount,
1250    },
1251}
1252
1253/// Stable identity attached to every progress event from one attempt.
1254#[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    /// Constructs exact progress provenance.
1264    #[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    /// Returns the stable logical invocation identifier.
1278    #[must_use]
1279    pub const fn invocation_id(&self) -> InvocationId {
1280        self.invocation_id
1281    }
1282
1283    /// Returns the physical attempt emitting progress.
1284    #[must_use]
1285    pub const fn attempt_id(&self) -> AttemptId {
1286        self.attempt_id
1287    }
1288
1289    /// Returns the exact owner-qualified tool version.
1290    #[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/// Ordered, identity-bound progress event accepted by the runtime sink.
1308#[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    /// Constructs an event from reporter-assigned identity and sequence.
1318    #[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    /// Returns exact invocation provenance.
1332    #[must_use]
1333    pub const fn provenance(&self) -> &ToolProgressProvenance {
1334        &self.provenance
1335    }
1336
1337    /// Returns the contiguous zero-based event sequence.
1338    #[must_use]
1339    pub const fn sequence(&self) -> ExecutionCount {
1340        self.sequence
1341    }
1342
1343    /// Returns the normalized numeric update.
1344    #[must_use]
1345    pub const fn update(&self) -> ToolProgressUpdate {
1346        self.update
1347    }
1348
1349    /// Revalidates identity and the descriptor event ceiling.
1350    ///
1351    /// Contiguous ordering and monotonic progress across multiple events remain
1352    /// the reporter or durable replay accumulator's responsibility.
1353    ///
1354    /// # Errors
1355    ///
1356    /// Returns [`ToolProgressEventValidationError`] for substituted context,
1357    /// invocation, attempt, tool, or an impossible sequence.
1358    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/// Invalid relationship between a progress event and invocation snapshot.
1397#[derive(Clone, Debug, Eq, Error, PartialEq)]
1398#[non_exhaustive]
1399pub enum ToolProgressEventValidationError {
1400    /// Context identity or invocation semantics did not match the descriptor.
1401    #[error("tool progress context binding is invalid: {source}")]
1402    Context {
1403        /// Underlying context binding failure.
1404        #[source]
1405        source: ToolContextBindingError,
1406    },
1407    /// Event named another logical invocation.
1408    #[error("tool progress invocation {actual} does not match context {expected}")]
1409    InvocationMismatch {
1410        /// Exact context invocation.
1411        expected: InvocationId,
1412        /// Rejected event invocation.
1413        actual: InvocationId,
1414    },
1415    /// Event named another physical attempt.
1416    #[error("tool progress attempt {actual} does not match context {expected}")]
1417    AttemptMismatch {
1418        /// Exact context attempt.
1419        expected: AttemptId,
1420        /// Rejected event attempt.
1421        actual: AttemptId,
1422    },
1423    /// Event named another owner-qualified tool version.
1424    #[error("tool progress identity {actual:?} does not match descriptor {expected:?}")]
1425    ToolIdentityMismatch {
1426        /// Exact descriptor identity.
1427        expected: Box<CapabilityIdentity>,
1428        /// Rejected event identity.
1429        actual: Box<CapabilityIdentity>,
1430    },
1431    /// Sequence lies outside the descriptor's zero-based event capacity.
1432    #[error("tool progress sequence {actual} exceeds event capacity {maximum}")]
1433    SequenceLimitExceeded {
1434        /// Descriptor event-count ceiling.
1435        maximum: ExecutionCount,
1436        /// Rejected zero-based sequence.
1437        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/// Private diagnostic returned by a runtime progress sink.
1450#[derive(Clone)]
1451pub struct ToolProgressSinkError {
1452    private_source: Arc<PrivateProgressSinkSource>,
1453}
1454
1455impl ToolProgressSinkError {
1456    /// Wraps one private sink diagnostic.
1457    #[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    /// Returns the private diagnostic to trusted in-process callers only.
1468    #[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
1491/// Runtime-owned durable sink for already ordered tool progress events.
1492///
1493/// A successful future asserts that the sink accepted the event in sequence.
1494/// Implementations must not reorder events and must apply their own durable
1495/// fencing before exposing them externally.
1496pub trait ToolProgressSink: Send + Sync + 'static {
1497    /// Accepts one identity-bound progress event.
1498    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/// Cloneable ordered progress handle bound to one physical attempt.
1514///
1515/// Concurrent emissions are rejected because async completion order cannot be
1516/// inferred safely. Dropping an in-flight emission future or observing a sink
1517/// failure permanently poisons the reporter, preventing gaps from being hidden
1518/// by later events.
1519#[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    /// Returns exact invocation provenance attached to emitted events.
1549    #[must_use]
1550    pub const fn provenance(&self) -> &ToolProgressProvenance {
1551        &self.provenance
1552    }
1553
1554    /// Returns the finite descriptor event ceiling.
1555    #[must_use]
1556    pub const fn maximum_events(&self) -> ExecutionCount {
1557        self.maximum_events
1558    }
1559
1560    /// Emits one strictly increasing progress observation.
1561    ///
1562    /// # Errors
1563    ///
1564    /// Returns [`ToolProgressError`] for concurrency, non-monotonic values,
1565    /// total changes, exhaustion, poisoned state, or a runtime sink failure.
1566    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/// Failure to emit an ordered tool progress event.
1693#[derive(Clone, Debug, Error)]
1694#[non_exhaustive]
1695pub enum ToolProgressError {
1696    /// A previous sink failure, dropped future, or mutex panic poisoned ordering.
1697    #[error("tool progress reporter is poisoned")]
1698    StatePoisoned,
1699    /// Another progress emission has not completed.
1700    #[error("concurrent tool progress emission is not allowed")]
1701    ConcurrentEmission,
1702    /// The finite descriptor event ceiling was reached.
1703    #[error("tool progress event maximum {maximum} was reached")]
1704    MaximumReached {
1705        /// Descriptor progress-event ceiling.
1706        maximum: ExecutionCount,
1707    },
1708    /// Completed units did not strictly increase.
1709    #[error("tool progress completed {actual} does not exceed previous {previous}")]
1710    NotIncreasing {
1711        /// Last accepted completed units.
1712        previous: ExecutionCount,
1713        /// Rejected completed units.
1714        actual: ExecutionCount,
1715    },
1716    /// A tool tried to change a previously established total.
1717    #[error("tool progress total {actual} does not match established {expected}")]
1718    TotalChanged {
1719        /// Previously established total.
1720        expected: ExecutionCount,
1721        /// Rejected new total.
1722        actual: ExecutionCount,
1723    },
1724    /// Completed units exceeded a total established by an earlier event.
1725    #[error("tool progress completed {completed} exceeds established total {total}")]
1726    CompletedExceedsEstablishedTotal {
1727        /// Rejected completed units.
1728        completed: ExecutionCount,
1729        /// Previously established total.
1730        total: ExecutionCount,
1731    },
1732    /// Runtime progress sink rejected an otherwise valid ordered event.
1733    #[error("tool progress sink failed")]
1734    Sink {
1735        /// Private sink diagnostic.
1736        source: ToolProgressSinkError,
1737    },
1738}
1739
1740/// Schema-bound, resource-limited arguments for one erased tool invocation.
1741///
1742/// Tool arguments must have an object root. Construction provides structural
1743/// and resource safety but does not execute JSON Schema validation; the trusted
1744/// [`ToolSchemaRegistry`] performs validation against the digest-pinned schema
1745/// before typed deserialization and before any tool code runs.
1746#[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    /// Constructs object-root arguments from a bounded JSON value.
1755    ///
1756    /// # Errors
1757    ///
1758    /// Returns [`ToolInputError::ObjectRootRequired`] for a scalar or array root.
1759    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    /// Returns the immutable input schema identity.
1767    #[must_use]
1768    pub const fn schema(&self) -> &SchemaReference {
1769        &self.schema
1770    }
1771
1772    /// Returns the bounded arguments without permitting mutation.
1773    #[must_use]
1774    pub const fn value(&self) -> &BoundedJson {
1775        &self.value
1776    }
1777
1778    /// Consumes the input and returns schema identity and arguments.
1779    #[must_use]
1780    pub fn into_parts(self) -> (SchemaReference, BoundedJson) {
1781        (self.schema, self.value)
1782    }
1783
1784    /// Revalidates schema identity plus descriptor and run byte ceilings.
1785    ///
1786    /// Actual JSON Schema evaluation is deliberately separate and must be
1787    /// performed through the registered local schema implementation.
1788    ///
1789    /// # Errors
1790    ///
1791    /// Returns [`ToolInputValidationError`] for a substituted context/schema or
1792    /// input that exceeds a descriptor or remaining-run ceiling.
1793    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/// Invalid structural tool input.
1854#[derive(Clone, Debug, Eq, Error, PartialEq)]
1855#[non_exhaustive]
1856pub enum ToolInputError {
1857    /// Registered tool argument schemas and values require an object root.
1858    #[error("tool input JSON must have an object root")]
1859    ObjectRootRequired,
1860}
1861
1862/// Invalid relationship between tool input and an invocation snapshot.
1863#[derive(Clone, Debug, Eq, Error, PartialEq)]
1864#[non_exhaustive]
1865pub enum ToolInputValidationError {
1866    /// Context identity or invocation semantics did not match the descriptor.
1867    #[error("tool input context binding is invalid: {source}")]
1868    Context {
1869        /// Underlying context binding failure.
1870        #[source]
1871        source: ToolContextBindingError,
1872    },
1873    /// Input named a schema other than the descriptor's pinned schema.
1874    #[error("tool input schema {actual:?} does not match descriptor {expected:?}")]
1875    SchemaMismatch {
1876        /// Exact descriptor schema.
1877        expected: Box<SchemaReference>,
1878        /// Rejected input schema.
1879        actual: Box<SchemaReference>,
1880    },
1881    /// Compact arguments exceeded the immutable descriptor ceiling.
1882    #[error("tool input is {actual} bytes; descriptor maximum is {maximum}")]
1883    DescriptorLimitExceeded {
1884        /// Descriptor input-byte ceiling.
1885        maximum: ByteCount,
1886        /// Exact compact input size.
1887        actual: ByteCount,
1888    },
1889    /// Compact arguments exceeded the remaining run capacity.
1890    #[error("tool input is {actual} bytes; remaining run maximum is {maximum}")]
1891    BudgetLimitExceeded {
1892        /// Remaining run input-byte capacity.
1893        maximum: ByteCount,
1894        /// Exact compact input size.
1895        actual: ByteCount,
1896    },
1897}
1898
1899impl ToolInputValidationError {
1900    const fn context(source: ToolContextBindingError) -> Self {
1901        Self::Context { source }
1902    }
1903}
1904
1905/// Canonical bounded set of artifact references returned by one tool call.
1906///
1907/// The global limit protects generic deserialization before a descriptor can
1908/// be selected. Descriptor and remaining-budget ceilings can only narrow it.
1909#[derive(Clone, Default, Eq, PartialEq)]
1910pub struct ToolArtifacts {
1911    values: Box<[ArtifactRef]>,
1912    total_bytes: ByteCount,
1913}
1914
1915impl ToolArtifacts {
1916    /// Absolute v1 artifact-reference count for one tool result.
1917    pub const MAX_LEN: usize = 64;
1918
1919    /// Constructs an empty artifact set.
1920    #[must_use]
1921    pub fn empty() -> Self {
1922        Self::default()
1923    }
1924
1925    /// Validates count, identity uniqueness, and aggregate byte arithmetic.
1926    ///
1927    /// # Errors
1928    ///
1929    /// Returns [`ToolArtifactsError`] for too many artifacts, duplicate
1930    /// tenant-qualified identities, or byte-count overflow.
1931    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    /// Returns the number of artifact references.
1962    #[must_use]
1963    pub const fn len(&self) -> usize {
1964        self.values.len()
1965    }
1966
1967    /// Returns whether no artifact references were returned.
1968    #[must_use]
1969    pub const fn is_empty(&self) -> bool {
1970        self.values.is_empty()
1971    }
1972
1973    /// Returns the checked aggregate immutable representation size.
1974    #[must_use]
1975    pub const fn total_bytes(&self) -> ByteCount {
1976        self.total_bytes
1977    }
1978
1979    /// Iterates over artifact references in their semantic output order.
1980    pub fn iter(&self) -> impl ExactSizeIterator<Item = &ArtifactRef> {
1981        self.values.iter()
1982    }
1983
1984    /// Consumes this set and returns its ordered artifact references.
1985    #[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/// Invalid artifact collection returned by one tool attempt.
2082#[derive(Clone, Debug, Eq, Error, PartialEq)]
2083#[non_exhaustive]
2084pub enum ToolArtifactsError {
2085    /// The global pre-descriptor artifact count ceiling was exceeded.
2086    #[error("tool result has {actual} artifacts; hard maximum is {maximum}")]
2087    TooMany {
2088        /// Absolute v1 count ceiling.
2089        maximum: usize,
2090        /// First observed count beyond the ceiling.
2091        actual: usize,
2092    },
2093    /// The same tenant-qualified artifact identity appeared more than once.
2094    #[error("tool result artifact identities must be unique")]
2095    DuplicateIdentity,
2096    /// Aggregate representation byte arithmetic overflowed.
2097    #[error("tool result aggregate artifact bytes overflowed")]
2098    TotalBytesOverflow,
2099}
2100
2101/// Typed output plus independently bounded artifact references.
2102///
2103/// The inline value is serialized and validated against the descriptor output
2104/// schema by [`ToolAdapter`]. Artifact bytes are never embedded here; tools
2105/// publish immutable bytes through their capability-scoped artifact binding and
2106/// return only authorized [`ArtifactRef`] values.
2107#[derive(Clone, Debug, Eq, PartialEq)]
2108pub struct ToolOutput<T> {
2109    value: T,
2110    artifacts: ToolArtifacts,
2111}
2112
2113impl<T> ToolOutput<T> {
2114    /// Constructs an inline-only typed output.
2115    #[must_use]
2116    pub fn inline(value: T) -> Self {
2117        Self {
2118            value,
2119            artifacts: ToolArtifacts::empty(),
2120        }
2121    }
2122
2123    /// Constructs typed output with already bounded artifact references.
2124    #[must_use]
2125    pub const fn with_artifacts(value: T, artifacts: ToolArtifacts) -> Self {
2126        Self { value, artifacts }
2127    }
2128
2129    /// Returns the typed inline value.
2130    #[must_use]
2131    pub const fn value(&self) -> &T {
2132        &self.value
2133    }
2134
2135    /// Returns independently bounded artifact references.
2136    #[must_use]
2137    pub const fn artifacts(&self) -> &ToolArtifacts {
2138        &self.artifacts
2139    }
2140
2141    /// Consumes this output into inline value and artifacts.
2142    #[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/// Stable invocation and tool identity attached to a successful tool result.
2155#[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    /// Constructs result provenance from exact execution identity.
2165    #[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    /// Returns the stable logical invocation identifier.
2179    #[must_use]
2180    pub const fn invocation_id(&self) -> InvocationId {
2181        self.invocation_id
2182    }
2183
2184    /// Returns the physical attempt that produced this result.
2185    #[must_use]
2186    pub const fn attempt_id(&self) -> AttemptId {
2187        self.attempt_id
2188    }
2189
2190    /// Returns the exact owner-qualified tool version.
2191    #[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/// Successful erased tool result ready for durable validation and commit.
2209///
2210/// Construction proves only intrinsic resource safety. Before committing or
2211/// exposing a decoded value, runtimes must call [`Self::validate_for`] and the
2212/// trusted schema registry must validate `output` against `output_schema`.
2213#[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    /// Constructs an intrinsically bounded erased result.
2224    #[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    /// Constructs a result whose identity and schema come from trusted snapshots.
2240    #[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    /// Returns stable execution provenance.
2260    #[must_use]
2261    pub const fn provenance(&self) -> &ToolResultProvenance {
2262        &self.provenance
2263    }
2264
2265    /// Returns the pinned output schema identity.
2266    #[must_use]
2267    pub const fn output_schema(&self) -> &SchemaReference {
2268        &self.output_schema
2269    }
2270
2271    /// Returns the bounded inline output without permitting mutation.
2272    #[must_use]
2273    pub const fn output(&self) -> &BoundedJson {
2274        &self.output
2275    }
2276
2277    /// Returns bounded artifact references in semantic output order.
2278    #[must_use]
2279    pub const fn artifacts(&self) -> &ToolArtifacts {
2280        &self.artifacts
2281    }
2282
2283    /// Consumes the result into its validated components.
2284    #[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    /// Revalidates identity, output, artifacts, descriptor limits, and budget.
2302    ///
2303    /// # Errors
2304    ///
2305    /// Returns [`ToolResultValidationError`] for substituted provenance/schema,
2306    /// excessive output, or artifact ownership/provenance that does not belong
2307    /// to this exact tenant, run, and registered tool version.
2308    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/// Invalid relationship between a successful result and invocation snapshot.
2444#[derive(Clone, Debug, Eq, Error, PartialEq)]
2445#[non_exhaustive]
2446pub enum ToolResultValidationError {
2447    /// Context identity or invocation semantics did not match the descriptor.
2448    #[error("tool result context binding is invalid: {source}")]
2449    Context {
2450        /// Underlying context binding failure.
2451        #[source]
2452        source: ToolContextBindingError,
2453    },
2454    /// Result named another logical invocation.
2455    #[error("tool result invocation {actual} does not match context {expected}")]
2456    InvocationMismatch {
2457        /// Exact context invocation.
2458        expected: InvocationId,
2459        /// Rejected result invocation.
2460        actual: InvocationId,
2461    },
2462    /// Result named another physical attempt.
2463    #[error("tool result attempt {actual} does not match context {expected}")]
2464    AttemptMismatch {
2465        /// Exact context attempt.
2466        expected: AttemptId,
2467        /// Rejected result attempt.
2468        actual: AttemptId,
2469    },
2470    /// Result named another owner-qualified tool version.
2471    #[error("tool result identity {actual:?} does not match descriptor {expected:?}")]
2472    ToolIdentityMismatch {
2473        /// Exact descriptor identity.
2474        expected: Box<CapabilityIdentity>,
2475        /// Rejected result identity.
2476        actual: Box<CapabilityIdentity>,
2477    },
2478    /// Result named another pinned output schema.
2479    #[error("tool result schema {actual:?} does not match descriptor {expected:?}")]
2480    SchemaMismatch {
2481        /// Exact descriptor schema.
2482        expected: Box<SchemaReference>,
2483        /// Rejected result schema.
2484        actual: Box<SchemaReference>,
2485    },
2486    /// Inline output exceeded the descriptor ceiling.
2487    #[error("tool inline output is {actual} bytes; descriptor maximum is {maximum}")]
2488    InlineDescriptorLimitExceeded {
2489        /// Descriptor inline-output ceiling.
2490        maximum: ByteCount,
2491        /// Exact compact output size.
2492        actual: ByteCount,
2493    },
2494    /// Inline output exceeded remaining run capacity.
2495    #[error("tool inline output is {actual} bytes; remaining run maximum is {maximum}")]
2496    InlineBudgetLimitExceeded {
2497        /// Remaining run output capacity.
2498        maximum: ByteCount,
2499        /// Exact compact output size.
2500        actual: ByteCount,
2501    },
2502    /// Artifact count exceeded the descriptor ceiling.
2503    #[error("tool result has {actual} artifacts; descriptor maximum is {maximum}")]
2504    ArtifactCountLimitExceeded {
2505        /// Descriptor artifact-count ceiling.
2506        maximum: ExecutionCount,
2507        /// Actual result count.
2508        actual: ExecutionCount,
2509    },
2510    /// Aggregate artifact bytes exceeded the descriptor ceiling.
2511    #[error("tool artifacts total {actual} bytes; descriptor maximum is {maximum}")]
2512    ArtifactDescriptorBytesExceeded {
2513        /// Descriptor aggregate artifact-byte ceiling.
2514        maximum: ByteCount,
2515        /// Actual aggregate artifact bytes.
2516        actual: ByteCount,
2517    },
2518    /// Aggregate artifact bytes exceeded remaining run capacity.
2519    #[error("tool artifacts total {actual} bytes; remaining run maximum is {maximum}")]
2520    ArtifactBudgetBytesExceeded {
2521        /// Remaining run artifact-byte capacity.
2522        maximum: ByteCount,
2523        /// Actual aggregate artifact bytes.
2524        actual: ByteCount,
2525    },
2526    /// An artifact belongs to another tenant.
2527    #[error("tool artifact at index {index} tenant {actual} does not match {expected}")]
2528    ArtifactTenantMismatch {
2529        /// Zero-based artifact position.
2530        index: usize,
2531        /// Exact invocation tenant.
2532        expected: Box<TenantId>,
2533        /// Rejected artifact tenant.
2534        actual: Box<TenantId>,
2535    },
2536    /// An artifact provenance record belongs to another run.
2537    #[error("tool artifact at index {index} run {actual} does not match {expected}")]
2538    ArtifactRunMismatch {
2539        /// Zero-based artifact position.
2540        index: usize,
2541        /// Exact invocation run.
2542        expected: RunId,
2543        /// Rejected artifact run.
2544        actual: RunId,
2545    },
2546    /// An artifact names another registry principal.
2547    #[error("tool artifact at index {index} principal does not match the descriptor owner")]
2548    ArtifactPrincipalMismatch {
2549        /// Zero-based artifact position.
2550        index: usize,
2551        /// Exact descriptor owner.
2552        expected: Box<PrincipalIdentity>,
2553        /// Rejected artifact principal.
2554        actual: Box<PrincipalIdentity>,
2555    },
2556    /// An artifact omits or substitutes the producing tool version.
2557    #[error("tool artifact at index {index} capability does not match the descriptor")]
2558    ArtifactCapabilityMismatch {
2559        /// Zero-based artifact position.
2560        index: usize,
2561        /// Exact descriptor capability reference.
2562        expected: Box<CapabilityReference>,
2563        /// Rejected optional artifact capability.
2564        actual: Option<Box<CapabilityReference>>,
2565    },
2566}
2567
2568impl ToolResultValidationError {
2569    const fn context(source: ToolContextBindingError) -> Self {
2570        Self::Context { source }
2571    }
2572}
2573
2574/// Stage at which one physical tool attempt failed.
2575///
2576/// Phase is observation evidence only. It never implies retry safety or an
2577/// external side-effect outcome; those are represented separately.
2578#[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    /// Input binding, schema validation, or typed decoding failed before tool code ran.
2585    Preparation,
2586    /// The typed tool implementation ran and returned or raised a failure.
2587    Execution,
2588    /// A nominal success failed output serialization, schema, or result validation.
2589    Result,
2590}
2591
2592/// Best available evidence about externally observable write effects.
2593///
2594/// This is not inferred from HTTP status, transport closure, timeout, or
2595/// cancellation. `Applied` and `NotApplied` require authoritative adapter/tool
2596/// evidence. `Unknown` means reconciliation is mandatory before retry or
2597/// compensation. Read-only tools always use `NotApplicable`.
2598#[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    /// The tool is read-only, so write-effect evidence does not apply.
2605    NotApplicable,
2606    /// Tool implementation code was not invoked.
2607    NotStarted,
2608    /// Authoritative evidence proves that the intended write was not applied.
2609    NotApplied,
2610    /// Authoritative evidence proves that the intended write was applied.
2611    Applied,
2612    /// The intended write may or may not have been applied.
2613    Unknown,
2614}
2615
2616/// Stable invocation and tool identity attached to a failed tool attempt.
2617#[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    /// Constructs failure provenance from exact invocation identity.
2627    #[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    /// Constructs provenance from trusted context and descriptor snapshots.
2641    #[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    /// Returns the stable logical invocation identifier.
2651    #[must_use]
2652    pub const fn invocation_id(&self) -> InvocationId {
2653        self.invocation_id
2654    }
2655
2656    /// Returns the failed physical attempt identifier.
2657    #[must_use]
2658    pub const fn attempt_id(&self) -> AttemptId {
2659        self.attempt_id
2660    }
2661
2662    /// Returns the exact owner-qualified tool version.
2663    #[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/// Public-safe typed failure returned by a tool implementation or adapter.
2681///
2682/// `external_effect` is deliberately independent of failure category. The one
2683/// exception is an exact invariant: `Unknown` is paired with
2684/// [`FailureCategory::AmbiguousExternalOutcome`] and therefore with
2685/// [`RetryAdvice::ReconcileFirst`].
2686#[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    /// Constructs a failure while enforcing phase/effect/ambiguity invariants.
2697    ///
2698    /// # Errors
2699    ///
2700    /// Returns [`ToolErrorBuildError`] when effect evidence contradicts the
2701    /// failure category or claims an impossible preparation/result phase.
2702    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    /// Attaches the exact provider operation needed to reconcile an unknown
2719    /// external outcome without replaying the business request.
2720    ///
2721    /// # Errors
2722    ///
2723    /// A recovery handle is accepted only with explicit `Unknown` effect
2724    /// evidence; known failures and successes must not carry one.
2725    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    /// Revalidates invocation, tool identity, risk, and retry safety.
2737    ///
2738    /// # Errors
2739    ///
2740    /// Returns [`ToolErrorValidationError`] when public evidence does not belong
2741    /// to the exact context/descriptor or would permit an unsafe repeated write.
2742    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    /// Returns the common public-safe failure occurrence.
2798    #[must_use]
2799    pub const fn failure(&self) -> &Failure {
2800        &self.failure
2801    }
2802
2803    /// Consumes this value and returns the common failure occurrence.
2804    #[must_use]
2805    pub fn into_failure(self) -> Failure {
2806        self.failure
2807    }
2808
2809    /// Returns the failed boundary stage.
2810    #[must_use]
2811    pub const fn phase(&self) -> ToolErrorPhase {
2812        self.phase
2813    }
2814
2815    /// Returns authoritative or explicitly unknown external-effect evidence.
2816    #[must_use]
2817    pub const fn external_effect(&self) -> ToolExternalEffect {
2818        self.external_effect
2819    }
2820
2821    /// Returns stable invocation correlation evidence.
2822    #[must_use]
2823    pub const fn provenance(&self) -> &ToolErrorProvenance {
2824        &self.provenance
2825    }
2826
2827    /// Returns the durable provider operation handle when reconciliation can
2828    /// target a known remote operation directly.
2829    #[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/// Invalid intrinsic relationship within a [`ToolError`].
2968#[derive(Clone, Debug, Eq, Error, PartialEq)]
2969#[non_exhaustive]
2970pub enum ToolErrorBuildError {
2971    /// Unknown write outcome must use the common ambiguous failure category.
2972    #[error("unknown tool effect requires an ambiguous-external-outcome failure")]
2973    UnknownEffectRequiresAmbiguousFailure,
2974    /// The common ambiguous category must carry explicit unknown effect evidence.
2975    #[error("ambiguous-external-outcome failure requires unknown tool effect")]
2976    AmbiguousFailureRequiresUnknownEffect,
2977    /// The claimed effect cannot occur at the stated boundary phase.
2978    #[error("tool error phase {phase:?} is incompatible with effect {effect:?}")]
2979    PhaseEffectMismatch {
2980        /// Failed boundary phase.
2981        phase: ToolErrorPhase,
2982        /// Contradictory effect evidence.
2983        effect: ToolExternalEffect,
2984    },
2985    /// A provider handle was attached after the outcome became authoritative.
2986    #[error("tool recovery handles require unknown external-effect evidence")]
2987    RecoveryHandleRequiresUnknownEffect,
2988}
2989
2990/// Invalid relationship between a tool failure and invocation snapshot.
2991#[derive(Clone, Debug, Eq, Error, PartialEq)]
2992#[non_exhaustive]
2993pub enum ToolErrorValidationError {
2994    /// Context identity or invocation semantics did not match the descriptor.
2995    #[error("tool error context binding is invalid: {source}")]
2996    Context {
2997        /// Underlying context binding failure.
2998        #[source]
2999        source: ToolContextBindingError,
3000    },
3001    /// Failure named another logical invocation.
3002    #[error("tool error invocation {actual} does not match context {expected}")]
3003    InvocationMismatch {
3004        /// Exact context invocation.
3005        expected: InvocationId,
3006        /// Rejected failure invocation.
3007        actual: InvocationId,
3008    },
3009    /// Failure named another physical attempt.
3010    #[error("tool error attempt {actual} does not match context {expected}")]
3011    AttemptMismatch {
3012        /// Exact context attempt.
3013        expected: AttemptId,
3014        /// Rejected failure attempt.
3015        actual: AttemptId,
3016    },
3017    /// Failure named another owner-qualified tool version.
3018    #[error("tool error identity {actual:?} does not match descriptor {expected:?}")]
3019    ToolIdentityMismatch {
3020        /// Exact descriptor identity.
3021        expected: Box<CapabilityIdentity>,
3022        /// Rejected failure identity.
3023        actual: Box<CapabilityIdentity>,
3024    },
3025    /// Effect evidence did not match the descriptor risk class.
3026    #[error("tool risk {risk:?} is incompatible with external effect {effect:?}")]
3027    EffectRiskMismatch {
3028        /// Immutable descriptor risk.
3029        risk: ToolRisk,
3030        /// Rejected effect evidence.
3031        effect: ToolExternalEffect,
3032    },
3033    /// A repeated non-idempotent write was advised after the effect was applied.
3034    #[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/// Private diagnostic returned by a trusted local tool schema registry.
3047///
3048/// Public formatting is intentionally generic because schema engines can
3049/// include tool arguments, outputs, filesystem paths, or implementation details
3050/// in their native diagnostics. Trusted diagnostics can retrieve the private
3051/// source explicitly.
3052#[derive(Clone)]
3053pub struct ToolSchemaValidationError {
3054    private_source: Arc<PrivateSchemaSource>,
3055}
3056
3057impl ToolSchemaValidationError {
3058    /// Wraps one private schema-registry diagnostic.
3059    #[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    /// Wraps a diagnostic already shared by the trusted registry.
3070    #[must_use]
3071    pub fn from_shared(source: Arc<PrivateSchemaSource>) -> Self {
3072        Self {
3073            private_source: source,
3074        }
3075    }
3076
3077    /// Returns the private diagnostic to trusted in-process callers only.
3078    #[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/// Whether a schema participates in typed input or output validation.
3102#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3103#[non_exhaustive]
3104pub enum ToolSchemaRole {
3105    /// Object-root input schema validated before tool code runs.
3106    Input,
3107    /// Output schema validated after typed serialization.
3108    Output,
3109}
3110
3111/// Trusted offline registry for digest-pinned tool JSON schemas.
3112///
3113/// `validate_type_schema` runs during adapter construction. Implementations
3114/// resolve `reference` only from local configuration, verify its canonical
3115/// bytes and digest, require JSON Schema 2020-12, require an object-root input,
3116/// and prove that the generated Rust type schema is compatible with the pinned
3117/// contract. `validate_instance` evaluates a bounded value against that exact
3118/// schema without network access or schema-supplied code execution.
3119pub trait ToolSchemaRegistry: Send + Sync + 'static {
3120    /// Validates one generated Rust type schema against its pinned contract.
3121    fn validate_type_schema(
3122        &self,
3123        reference: &SchemaReference,
3124        role: ToolSchemaRole,
3125        generated: &Schema,
3126    ) -> Result<(), ToolSchemaValidationError>;
3127
3128    /// Validates one bounded runtime instance against its pinned contract.
3129    fn validate_instance(
3130        &self,
3131        reference: &SchemaReference,
3132        role: ToolSchemaRole,
3133        value: &BoundedJson,
3134    ) -> Result<(), ToolSchemaValidationError>;
3135}
3136
3137/// Strongly typed application-authoring boundary for one immutable tool version.
3138///
3139/// Returning `Ok` is an authoritative assertion that the intended tool
3140/// operation completed; for a write, post-call serialization/schema failures
3141/// therefore carry `Applied` effect evidence. Returning `Err` must truthfully
3142/// report effect evidence. Implementations must not hide retries beneath one
3143/// [`AttemptId`]; every actual external exchange requires a separately admitted
3144/// and budgeted attempt, with the same logical [`InvocationId`] and idempotency
3145/// key when applicable.
3146pub trait Tool: Send + Sync + 'static {
3147    /// Typed object-root arguments.
3148    type Input: DeserializeOwned + JsonSchema + Send + 'static;
3149    /// Typed inline result governed by the descriptor output schema.
3150    type Output: Serialize + JsonSchema + Send + 'static;
3151
3152    /// Returns the immutable descriptor for this exact registered tool version.
3153    fn descriptor(&self) -> &ToolDescriptor;
3154
3155    /// Executes exactly one physical attempt.
3156    fn call(
3157        &self,
3158        context: ToolContext,
3159        input: Self::Input,
3160    ) -> crate::BoxFuture<'_, Result<ToolOutput<Self::Output>, ToolError>>;
3161}
3162
3163/// One bounded observation produced by a tool reconciliation probe.
3164///
3165/// Result and error evidence must describe the original physical attempt; the
3166/// durable runtime revalidates that binding before commit. `Pending` means the
3167/// remote system supplied no authoritative terminal fact and therefore causes
3168/// no invocation-ledger mutation.
3169#[derive(Clone, Debug)]
3170#[non_exhaustive]
3171pub enum ToolReconciliationObservation {
3172    /// Authoritative successful evidence for the original attempt.
3173    Result(ToolResult),
3174    /// Authoritative failure/effect evidence for the original attempt.
3175    Error(ToolError),
3176    /// No authoritative outcome is available yet.
3177    Pending {
3178        /// Minimum delay before the next bounded probe.
3179        retry_after: DurationMillis,
3180    },
3181}
3182
3183impl ToolReconciliationObservation {
3184    /// Maximum provider-selected polling interval accepted by the core API.
3185    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    /// Constructs a positive, bounded pending observation.
3191    ///
3192    /// # Errors
3193    ///
3194    /// Rejects zero and intervals greater than one hour. Longer waits are
3195    /// represented by repeated durable probes so cancellation and leases stay
3196    /// observable.
3197    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    /// Revalidates provider-authored polling bounds.
3205    ///
3206    /// Runtimes call this even when a provider constructed the public enum
3207    /// variant directly.
3208    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/// Invalid polling advice returned by a reconciliation provider.
3232#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
3233#[non_exhaustive]
3234pub enum ToolReconciliationObservationError {
3235    /// An immediate durable retry would create a hot loop.
3236    #[error("tool reconciliation retry delay must be greater than zero")]
3237    ZeroRetryDelay,
3238    /// Provider advice exceeded the bounded polling ceiling.
3239    #[error("tool reconciliation retry delay {actual}ms exceeds maximum {maximum}ms")]
3240    RetryDelayTooLarge {
3241        /// Maximum accepted delay.
3242        maximum: DurationMillis,
3243        /// Rejected delay.
3244        actual: DurationMillis,
3245    },
3246}
3247
3248/// Public-safe failure of the reconciliation probe itself.
3249///
3250/// This is not evidence about the original tool outcome. In particular it may
3251/// never request `ReconcileFirst`, which would recursively turn a read/replay
3252/// probe failure into another ambiguous business operation.
3253#[derive(Clone, Debug, Error)]
3254#[error("tool reconciliation probe failed: {failure}")]
3255pub struct ToolReconciliationProbeError {
3256    failure: Box<Failure>,
3257}
3258
3259impl ToolReconciliationProbeError {
3260    /// Wraps a public-safe probe failure with finite recovery advice.
3261    ///
3262    /// # Errors
3263    ///
3264    /// Rejects reconcile-first advice and unbounded or zero safe-after delays.
3265    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    /// Returns the public-safe probe failure.
3279    #[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/// Invalid recovery advice attached to a reconciliation-probe failure.
3304#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
3305#[non_exhaustive]
3306pub enum ToolReconciliationProbeErrorBuildError {
3307    /// A probe failure cannot itself claim an ambiguous business outcome.
3308    #[error("tool reconciliation probe failure cannot require reconciliation")]
3309    RecursiveReconciliation,
3310    /// Safe retry advice violated polling bounds.
3311    #[error("tool reconciliation probe retry advice is invalid: {source}")]
3312    InvalidRetry {
3313        /// Exact polling-bound violation.
3314        #[source]
3315        source: ToolReconciliationObservationError,
3316    },
3317}
3318
3319impl ToolReconciliationProbeErrorBuildError {
3320    const fn invalid_retry(source: ToolReconciliationObservationError) -> Self {
3321        Self::InvalidRetry { source }
3322    }
3323}
3324
3325/// Object-safe tool boundary used by heterogeneous registries and runtimes.
3326///
3327/// Only adapters that have passed typed schema registration should enter an
3328/// executable registry. A successful future resolves to a fully bounded result;
3329/// the runtime still persists and fences the result before it becomes committed.
3330pub trait ErasedTool: Send + Sync + 'static {
3331    /// Returns the immutable descriptor snapshot used by this adapter.
3332    fn descriptor(&self) -> &ToolDescriptor;
3333
3334    /// Returns whether this executable binding implements reconciliation.
3335    ///
3336    /// Immutable registries reject an implementation claim that was not
3337    /// declared by the descriptor. A descriptor may still declare a status
3338    /// query while leaving execution to a separately authorized manual
3339    /// reconciler, in which case this returns `false`.
3340    #[must_use]
3341    fn supports_reconciliation(&self) -> bool {
3342        false
3343    }
3344
3345    /// Validates, decodes, executes, encodes, and revalidates one attempt.
3346    fn call(
3347        &self,
3348        context: ToolContext,
3349        input: ToolInput,
3350    ) -> crate::BoxFuture<'_, Result<ToolResult, ToolError>>;
3351
3352    /// Reconciles the outcome of the original ambiguous physical attempt.
3353    ///
3354    /// Implementations must query authoritative provider state or perform an
3355    /// operator-attested deduplicated replay. They must never issue an
3356    /// unprotected duplicate write. The default fails closed so older and
3357    /// ordinary tools cannot accidentally claim recovery support.
3358    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
3368/// Framework-owned typed-to-erased adapter with pinned schema enforcement.
3369pub 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    /// Validates generated type schemas and freezes the descriptor snapshot.
3381    ///
3382    /// # Errors
3383    ///
3384    /// Returns [`ToolAdapterBuildError`] unless both generated Rust type schemas
3385    /// match their digest-pinned local registry contracts.
3386    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    /// Returns the strongly typed implementation.
3418    #[must_use]
3419    pub const fn tool(&self) -> &T {
3420        &self.tool
3421    }
3422
3423    /// Returns the trusted local schema registry binding.
3424    #[must_use]
3425    pub const fn registry(&self) -> &R {
3426        &self.registry
3427    }
3428
3429    /// Consumes the adapter into the typed tool and schema registry.
3430    #[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/// Registration failure for a typed tool adapter.
3560#[derive(Debug, Error)]
3561#[non_exhaustive]
3562pub enum ToolAdapterBuildError {
3563    /// A generated Rust type schema did not match the pinned local contract.
3564    #[error("registered {role:?} tool schema rejected the generated Rust type schema: {source}")]
3565    SchemaContract {
3566        /// Schema boundary that failed registration.
3567        role: ToolSchemaRole,
3568        /// Private registry diagnostic.
3569        #[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}