Skip to main content

stateknot_core/
model_transcript.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Durable, lossless model/tool continuation evidence.
5
6use std::{collections::BTreeSet, fmt, str::FromStr};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use thiserror::Error;
11
12use crate::{
13    AttemptId, BoundedJson, ByteCount, CapabilityIdentity, Digest, FailureCategory, FailureCode,
14    FailureId, FailureMessage, InvocationId, ModelFinishReason, ModelProviderToolCallId,
15    ModelResponse, RetryAdvice, ToolError, ToolExternalEffect, ToolResult,
16};
17
18const MEBIBYTE: u64 = 1024 * 1024;
19const FORMAT_PATTERN: &str = "^[a-z][a-z0-9]*(\\.[a-z0-9]+){2,7}$";
20const REPLAY_DIGEST_DOMAIN: &[u8] = b"stateknot.model-provider-replay.v1\0";
21
22/// Versioned adapter-owned syntax for one exact provider replay fragment.
23///
24/// The identifier is data, not executable dispatch authority. A selected
25/// adapter must explicitly recognize the exact value before provider I/O.
26#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
27pub struct ModelProviderReplayFormat(Box<str>);
28
29impl ModelProviderReplayFormat {
30    /// Maximum encoded format identifier length.
31    pub const MAX_BYTES: usize = 128;
32
33    /// Validates one lowercase dot-separated adapter format identifier.
34    ///
35    /// # Errors
36    ///
37    /// Returns [`ModelProviderReplayFormatError`] for an empty, oversized, or
38    /// syntactically unstable identifier.
39    pub fn new(value: impl Into<String>) -> Result<Self, ModelProviderReplayFormatError> {
40        let value = value.into();
41        validate_format(&value)?;
42        Ok(Self(value.into_boxed_str()))
43    }
44
45    /// Returns the exact case-sensitive identifier.
46    #[must_use]
47    pub fn as_str(&self) -> &str {
48        &self.0
49    }
50}
51
52impl fmt::Debug for ModelProviderReplayFormat {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        formatter
55            .debug_tuple("ModelProviderReplayFormat")
56            .field(&self.as_str())
57            .finish()
58    }
59}
60
61impl fmt::Display for ModelProviderReplayFormat {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        formatter.write_str(self.as_str())
64    }
65}
66
67impl FromStr for ModelProviderReplayFormat {
68    type Err = ModelProviderReplayFormatError;
69
70    fn from_str(value: &str) -> Result<Self, Self::Err> {
71        Self::new(value)
72    }
73}
74
75impl TryFrom<&str> for ModelProviderReplayFormat {
76    type Error = ModelProviderReplayFormatError;
77
78    fn try_from(value: &str) -> Result<Self, Self::Error> {
79        Self::new(value)
80    }
81}
82
83impl Serialize for ModelProviderReplayFormat {
84    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
85    where
86        S: Serializer,
87    {
88        serializer.serialize_str(self.as_str())
89    }
90}
91
92impl<'de> Deserialize<'de> for ModelProviderReplayFormat {
93    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
94    where
95        D: Deserializer<'de>,
96    {
97        let value = String::deserialize(deserializer)?;
98        Self::new(value).map_err(de::Error::custom)
99    }
100}
101
102impl JsonSchema for ModelProviderReplayFormat {
103    fn schema_name() -> std::borrow::Cow<'static, str> {
104        "ModelProviderReplayFormat".into()
105    }
106
107    fn schema_id() -> std::borrow::Cow<'static, str> {
108        concat!(module_path!(), "::ModelProviderReplayFormat").into()
109    }
110
111    fn json_schema(_: &mut SchemaGenerator) -> Schema {
112        json_schema!({
113            "type": "string",
114            "minLength": 5,
115            "maxLength": 128,
116            "pattern": FORMAT_PATTERN
117        })
118    }
119
120    fn inline_schema() -> bool {
121        true
122    }
123}
124
125fn validate_format(value: &str) -> Result<(), ModelProviderReplayFormatError> {
126    if value.is_empty() {
127        return Err(ModelProviderReplayFormatError::Empty);
128    }
129    if value.len() > ModelProviderReplayFormat::MAX_BYTES {
130        return Err(ModelProviderReplayFormatError::TooLong {
131            maximum: ModelProviderReplayFormat::MAX_BYTES,
132            actual: value.len(),
133        });
134    }
135    let segments = value.split('.').collect::<Vec<_>>();
136    if !(3..=8).contains(&segments.len())
137        || segments.iter().any(|segment| {
138            segment.is_empty()
139                || !segment.as_bytes()[0].is_ascii_lowercase()
140                || segment
141                    .bytes()
142                    .any(|byte| !byte.is_ascii_lowercase() && !byte.is_ascii_digit())
143        })
144    {
145        return Err(ModelProviderReplayFormatError::InvalidSyntax);
146    }
147    Ok(())
148}
149
150/// Invalid provider replay format identifier.
151#[derive(Clone, Debug, Eq, Error, PartialEq)]
152#[non_exhaustive]
153pub enum ModelProviderReplayFormatError {
154    /// No identifier was supplied.
155    #[error("model provider replay format must not be empty")]
156    Empty,
157    /// The encoded identifier exceeded the immutable ceiling.
158    #[error("model provider replay format is {actual} bytes; maximum is {maximum}")]
159    TooLong {
160        /// Immutable byte ceiling.
161        maximum: usize,
162        /// Rejected encoded length.
163        actual: usize,
164    },
165    /// The identifier was not a stable lowercase dot-separated value.
166    #[error("model provider replay format has invalid syntax")]
167    InvalidSyntax,
168}
169
170/// Exact bounded provider response fragment required for stateless continuation.
171///
172/// The payload is deliberately opaque to core semantics. Adapters validate its
173/// complete provider shape when producing and consuming it. The
174/// domain-separated digest binds both the format and canonical payload so a
175/// stored fragment cannot be reinterpreted as another continuation syntax.
176#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
177#[serde(deny_unknown_fields)]
178pub struct ModelProviderReplay {
179    format: ModelProviderReplayFormat,
180    payload: BoundedJson,
181    digest: Digest,
182}
183
184impl ModelProviderReplay {
185    /// Constructs an array-root replay fragment and computes its digest.
186    ///
187    /// # Errors
188    ///
189    /// Returns [`ModelProviderReplayError`] unless the payload is an array.
190    pub fn new(
191        format: ModelProviderReplayFormat,
192        payload: BoundedJson,
193    ) -> Result<Self, ModelProviderReplayError> {
194        if !payload.as_value().is_array() {
195            return Err(ModelProviderReplayError::PayloadMustBeArray);
196        }
197        let digest = replay_digest(&format, &payload);
198        Ok(Self {
199            format,
200            payload,
201            digest,
202        })
203    }
204
205    /// Returns the exact adapter-owned format identity.
206    #[must_use]
207    pub const fn format(&self) -> &ModelProviderReplayFormat {
208        &self.format
209    }
210
211    /// Returns the opaque bounded array without permitting mutation.
212    #[must_use]
213    pub const fn payload(&self) -> &BoundedJson {
214        &self.payload
215    }
216
217    /// Returns the digest binding format and canonical payload bytes.
218    #[must_use]
219    pub const fn digest(&self) -> Digest {
220        self.digest
221    }
222
223    /// Returns compact payload bytes retained by this fragment.
224    #[must_use]
225    pub fn payload_bytes(&self) -> ByteCount {
226        ByteCount::new(self.payload.stats().compact_bytes() as u64)
227    }
228}
229
230#[derive(Serialize)]
231struct ReplayDigestWire<'a> {
232    format: &'a ModelProviderReplayFormat,
233    payload: &'a BoundedJson,
234}
235
236fn replay_digest(format: &ModelProviderReplayFormat, payload: &BoundedJson) -> Digest {
237    let canonical = serde_json_canonicalizer::to_vec(&ReplayDigestWire { format, payload })
238        .expect("bounded provider replay always has canonical JSON");
239    let mut preimage = Vec::with_capacity(REPLAY_DIGEST_DOMAIN.len() + canonical.len());
240    preimage.extend_from_slice(REPLAY_DIGEST_DOMAIN);
241    preimage.extend_from_slice(&canonical);
242    Digest::sha256(preimage)
243}
244
245impl fmt::Debug for ModelProviderReplay {
246    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
247        formatter
248            .debug_struct("ModelProviderReplay")
249            .field("format", &self.format)
250            .field("payload_stats", &self.payload.stats())
251            .field("digest", &self.digest)
252            .finish_non_exhaustive()
253    }
254}
255
256impl<'de> Deserialize<'de> for ModelProviderReplay {
257    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
258    where
259        D: Deserializer<'de>,
260    {
261        #[derive(Deserialize)]
262        #[serde(deny_unknown_fields)]
263        struct Wire {
264            format: ModelProviderReplayFormat,
265            payload: BoundedJson,
266            digest: Digest,
267        }
268
269        let wire = Wire::deserialize(deserializer)?;
270        let replay = Self::new(wire.format, wire.payload).map_err(de::Error::custom)?;
271        if replay.digest != wire.digest {
272            return Err(de::Error::custom(ModelProviderReplayError::DigestMismatch));
273        }
274        Ok(replay)
275    }
276}
277
278/// Invalid opaque provider replay evidence.
279#[derive(Clone, Debug, Eq, Error, PartialEq)]
280#[non_exhaustive]
281pub enum ModelProviderReplayError {
282    /// Provider continuation fragments are ordered arrays.
283    #[error("model provider replay payload must be a JSON array")]
284    PayloadMustBeArray,
285    /// Persisted digest did not match canonical payload bytes.
286    #[error("model provider replay digest does not match its payload")]
287    DigestMismatch,
288}
289
290/// Public-safe durable failure snapshot supplied back to a model.
291#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
292#[serde(deny_unknown_fields)]
293pub struct ModelToolFailure {
294    invocation_id: InvocationId,
295    attempt_id: AttemptId,
296    tool: CapabilityIdentity,
297    failure_id: FailureId,
298    category: FailureCategory,
299    code: FailureCode,
300    message: FailureMessage,
301    retry_advice: RetryAdvice,
302    external_effect: ToolExternalEffect,
303}
304
305impl ModelToolFailure {
306    /// Copies only public-safe, identity-bound evidence from a tool error.
307    #[must_use]
308    pub fn from_tool_error(error: &ToolError) -> Self {
309        Self {
310            invocation_id: error.provenance().invocation_id(),
311            attempt_id: error.provenance().attempt_id(),
312            tool: error.provenance().tool().clone(),
313            failure_id: error.failure().id(),
314            category: error.failure().category(),
315            code: error.failure().code().clone(),
316            message: error.failure().message().clone(),
317            retry_advice: error.failure().retry_advice(),
318            external_effect: error.external_effect(),
319        }
320    }
321
322    fn validate(&self) -> Result<(), ModelToolFailureError> {
323        let ambiguous = self.category == FailureCategory::AmbiguousExternalOutcome;
324        if ambiguous != matches!(self.retry_advice, RetryAdvice::ReconcileFirst)
325            || ambiguous != (self.external_effect == ToolExternalEffect::Unknown)
326        {
327            return Err(ModelToolFailureError::InvalidAmbiguityEvidence);
328        }
329        Ok(())
330    }
331
332    /// Returns the durable logical invocation identity.
333    #[must_use]
334    pub const fn invocation_id(&self) -> InvocationId {
335        self.invocation_id
336    }
337
338    /// Returns the physical failed attempt identity.
339    #[must_use]
340    pub const fn attempt_id(&self) -> AttemptId {
341        self.attempt_id
342    }
343
344    /// Returns the exact tool descriptor identity.
345    #[must_use]
346    pub const fn tool(&self) -> &CapabilityIdentity {
347        &self.tool
348    }
349
350    /// Returns the public failure occurrence identity.
351    #[must_use]
352    pub const fn failure_id(&self) -> FailureId {
353        self.failure_id
354    }
355
356    /// Returns the public failure category.
357    #[must_use]
358    pub const fn category(&self) -> FailureCategory {
359        self.category
360    }
361
362    /// Returns the stable public failure code.
363    #[must_use]
364    pub const fn code(&self) -> &FailureCode {
365        &self.code
366    }
367
368    /// Returns the bounded public-safe failure message.
369    #[must_use]
370    pub const fn message(&self) -> &FailureMessage {
371        &self.message
372    }
373
374    /// Returns explicit retry advice from the originating tool boundary.
375    #[must_use]
376    pub const fn retry_advice(&self) -> RetryAdvice {
377        self.retry_advice
378    }
379
380    /// Returns authoritative external-effect evidence.
381    #[must_use]
382    pub const fn external_effect(&self) -> ToolExternalEffect {
383        self.external_effect
384    }
385}
386
387impl<'de> Deserialize<'de> for ModelToolFailure {
388    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
389    where
390        D: Deserializer<'de>,
391    {
392        #[derive(Deserialize)]
393        #[serde(deny_unknown_fields)]
394        struct Wire {
395            invocation_id: InvocationId,
396            attempt_id: AttemptId,
397            tool: CapabilityIdentity,
398            failure_id: FailureId,
399            category: FailureCategory,
400            code: FailureCode,
401            message: FailureMessage,
402            retry_advice: RetryAdvice,
403            external_effect: ToolExternalEffect,
404        }
405        let wire = Wire::deserialize(deserializer)?;
406        let failure = Self {
407            invocation_id: wire.invocation_id,
408            attempt_id: wire.attempt_id,
409            tool: wire.tool,
410            failure_id: wire.failure_id,
411            category: wire.category,
412            code: wire.code,
413            message: wire.message,
414            retry_advice: wire.retry_advice,
415            external_effect: wire.external_effect,
416        };
417        failure.validate().map_err(de::Error::custom)?;
418        Ok(failure)
419    }
420}
421
422/// Invalid public-safe tool failure continuation evidence.
423#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
424#[non_exhaustive]
425pub enum ModelToolFailureError {
426    /// Ambiguous category, reconcile advice, and unknown effect must be exact peers.
427    #[error("model tool failure ambiguity evidence is inconsistent")]
428    InvalidAmbiguityEvidence,
429}
430
431/// One exact tool outcome paired to a provider call identifier.
432#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
433#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
434pub enum ModelToolOutcome {
435    /// A committed successful tool invocation.
436    Succeeded {
437        /// Exact provider call identity from the preceding model output.
438        provider_call_id: ModelProviderToolCallId,
439        /// Complete durable tool result.
440        result: ToolResult,
441    },
442    /// A committed known failure safe to expose to the next model turn.
443    Failed {
444        /// Exact provider call identity from the preceding model output.
445        provider_call_id: ModelProviderToolCallId,
446        /// Redacted durable failure evidence.
447        error: ModelToolFailure,
448    },
449}
450
451impl ModelToolOutcome {
452    /// Constructs one successful provider-call outcome.
453    #[must_use]
454    pub const fn succeeded(provider_call_id: ModelProviderToolCallId, result: ToolResult) -> Self {
455        Self::Succeeded {
456            provider_call_id,
457            result,
458        }
459    }
460
461    /// Constructs one public-safe failed provider-call outcome.
462    #[must_use]
463    pub fn failed(provider_call_id: ModelProviderToolCallId, error: &ToolError) -> Self {
464        Self::Failed {
465            provider_call_id,
466            error: ModelToolFailure::from_tool_error(error),
467        }
468    }
469
470    /// Returns the provider call identity being answered.
471    #[must_use]
472    pub const fn provider_call_id(&self) -> &ModelProviderToolCallId {
473        match self {
474            Self::Succeeded {
475                provider_call_id, ..
476            }
477            | Self::Failed {
478                provider_call_id, ..
479            } => provider_call_id,
480        }
481    }
482
483    /// Returns the durable logical tool invocation identity.
484    #[must_use]
485    pub const fn invocation_id(&self) -> InvocationId {
486        match self {
487            Self::Succeeded { result, .. } => result.provenance().invocation_id(),
488            Self::Failed { error, .. } => error.invocation_id(),
489        }
490    }
491
492    /// Returns the exact physical tool attempt that produced this outcome.
493    #[must_use]
494    pub const fn attempt_id(&self) -> AttemptId {
495        match self {
496            Self::Succeeded { result, .. } => result.provenance().attempt_id(),
497            Self::Failed { error, .. } => error.attempt_id(),
498        }
499    }
500
501    /// Returns the exact tool descriptor identity.
502    #[must_use]
503    pub const fn tool(&self) -> &CapabilityIdentity {
504        match self {
505            Self::Succeeded { result, .. } => result.provenance().tool(),
506            Self::Failed { error, .. } => error.tool(),
507        }
508    }
509
510    /// Returns a committed successful result when present.
511    #[must_use]
512    pub const fn result(&self) -> Option<&ToolResult> {
513        match self {
514            Self::Succeeded { result, .. } => Some(result),
515            Self::Failed { .. } => None,
516        }
517    }
518
519    /// Returns public-safe committed failure evidence when present.
520    #[must_use]
521    pub const fn error(&self) -> Option<&ModelToolFailure> {
522        match self {
523            Self::Succeeded { .. } => None,
524            Self::Failed { error, .. } => Some(error),
525        }
526    }
527
528    /// Returns whether this outcome represents a known failure.
529    #[must_use]
530    pub const fn is_error(&self) -> bool {
531        matches!(self, Self::Failed { .. })
532    }
533}
534
535impl fmt::Debug for ModelToolOutcome {
536    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
537        formatter
538            .debug_struct("ModelToolOutcome")
539            .field("provider_call_id", self.provider_call_id())
540            .field("invocation_id", &self.invocation_id())
541            .field("tool", self.tool())
542            .field("is_error", &self.is_error())
543            .finish_non_exhaustive()
544    }
545}
546
547impl<'de> Deserialize<'de> for ModelToolOutcome {
548    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
549    where
550        D: Deserializer<'de>,
551    {
552        #[derive(Deserialize)]
553        #[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
554        enum Wire {
555            Succeeded {
556                provider_call_id: ModelProviderToolCallId,
557                result: ToolResult,
558            },
559            Failed {
560                provider_call_id: ModelProviderToolCallId,
561                error: ModelToolFailure,
562            },
563        }
564        Ok(match Wire::deserialize(deserializer)? {
565            Wire::Succeeded {
566                provider_call_id,
567                result,
568            } => Self::Succeeded {
569                provider_call_id,
570                result,
571            },
572            Wire::Failed {
573                provider_call_id,
574                error,
575            } => Self::Failed {
576                provider_call_id,
577                error,
578            },
579        })
580    }
581}
582
583/// One completed model tool-call turn and its complete durable outcomes.
584#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
585#[serde(deny_unknown_fields)]
586pub struct ModelTranscriptTurn {
587    response: ModelResponse,
588    outcomes: Box<[ModelToolOutcome]>,
589}
590
591impl ModelTranscriptTurn {
592    /// Binds every provider call to exactly one durable tool outcome in model order.
593    ///
594    /// # Errors
595    ///
596    /// Rejects missing replay data, missing or substituted provider call IDs,
597    /// tool identity drift, duplicate invocation IDs, and ambiguous external
598    /// write outcomes that require reconciliation rather than model continuation.
599    pub fn new<I>(response: ModelResponse, outcomes: I) -> Result<Self, ModelTranscriptTurnError>
600    where
601        I: IntoIterator<Item = ModelToolOutcome>,
602    {
603        if response.finish_reason() != ModelFinishReason::ToolCalls {
604            return Err(ModelTranscriptTurnError::ResponseHasNoToolCalls);
605        }
606        if response.provider_replay().is_none() {
607            return Err(ModelTranscriptTurnError::MissingProviderReplay);
608        }
609        let outcomes = outcomes.into_iter().collect::<Vec<_>>();
610        if outcomes.len() != response.tool_call_count() {
611            return Err(ModelTranscriptTurnError::OutcomeCountMismatch {
612                expected: response.tool_call_count(),
613                actual: outcomes.len(),
614            });
615        }
616        let mut invocation_ids = BTreeSet::new();
617        for (index, (proposal, outcome)) in response.tool_calls().zip(&outcomes).enumerate() {
618            let expected_call_id = proposal
619                .provider_call_id()
620                .ok_or(ModelTranscriptTurnError::MissingProviderCallId { index })?;
621            if outcome.provider_call_id() != expected_call_id {
622                return Err(ModelTranscriptTurnError::ProviderCallIdMismatch { index });
623            }
624            if outcome.tool() != proposal.tool() {
625                return Err(ModelTranscriptTurnError::ToolIdentityMismatch {
626                    index,
627                    expected: Box::new(proposal.tool().clone()),
628                    actual: Box::new(outcome.tool().clone()),
629                });
630            }
631            if !invocation_ids.insert(outcome.invocation_id()) {
632                return Err(ModelTranscriptTurnError::DuplicateInvocationId {
633                    invocation_id: outcome.invocation_id(),
634                });
635            }
636            if outcome
637                .error()
638                .is_some_and(|error| error.external_effect() == ToolExternalEffect::Unknown)
639            {
640                return Err(ModelTranscriptTurnError::AmbiguousExternalOutcome { index });
641            }
642        }
643        Ok(Self {
644            response,
645            outcomes: outcomes.into_boxed_slice(),
646        })
647    }
648
649    /// Returns the complete normalized preceding response.
650    #[must_use]
651    pub const fn response(&self) -> &ModelResponse {
652        &self.response
653    }
654
655    /// Returns complete tool outcomes in proposal order.
656    #[must_use]
657    pub const fn outcomes(&self) -> &[ModelToolOutcome] {
658        &self.outcomes
659    }
660}
661
662impl fmt::Debug for ModelTranscriptTurn {
663    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
664        formatter
665            .debug_struct("ModelTranscriptTurn")
666            .field("attempt_id", &self.response.provenance().attempt_id())
667            .field("model", self.response.provenance().model())
668            .field(
669                "provider_replay",
670                self.response
671                    .provider_replay()
672                    .expect("constructor invariant"),
673            )
674            .field("outcomes", &self.outcomes)
675            .finish_non_exhaustive()
676    }
677}
678
679impl<'de> Deserialize<'de> for ModelTranscriptTurn {
680    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
681    where
682        D: Deserializer<'de>,
683    {
684        #[derive(Deserialize)]
685        #[serde(deny_unknown_fields)]
686        struct Wire {
687            response: ModelResponse,
688            outcomes: Vec<ModelToolOutcome>,
689        }
690        let wire = Wire::deserialize(deserializer)?;
691        Self::new(wire.response, wire.outcomes).map_err(de::Error::custom)
692    }
693}
694
695/// Invalid model/tool transcript turn.
696#[derive(Clone, Debug, Eq, Error, PartialEq)]
697#[non_exhaustive]
698pub enum ModelTranscriptTurnError {
699    /// Only a tool-calling response can precede tool results.
700    #[error("model transcript turn response must finish with tool calls")]
701    ResponseHasNoToolCalls,
702    /// Stateless continuation requires exact provider output evidence.
703    #[error("model transcript turn is missing provider replay evidence")]
704    MissingProviderReplay,
705    /// The complete proposal set was not answered exactly once.
706    #[error("model transcript expects {expected} tool outcomes, received {actual}")]
707    OutcomeCountMismatch {
708        /// Number of model proposals.
709        expected: usize,
710        /// Number of supplied outcomes.
711        actual: usize,
712    },
713    /// One model proposal omitted its provider correlation identity.
714    #[error("model transcript proposal {index} has no provider call identifier")]
715    MissingProviderCallId {
716        /// Zero-based proposal position.
717        index: usize,
718    },
719    /// An outcome answered another provider call.
720    #[error("model transcript outcome {index} provider call identifier does not match")]
721    ProviderCallIdMismatch {
722        /// Zero-based proposal position.
723        index: usize,
724    },
725    /// An outcome claimed another registered tool version.
726    #[error("model transcript outcome {index} tool identity does not match its proposal")]
727    ToolIdentityMismatch {
728        /// Zero-based proposal position.
729        index: usize,
730        /// Exact proposed tool identity.
731        expected: Box<CapabilityIdentity>,
732        /// Rejected outcome identity.
733        actual: Box<CapabilityIdentity>,
734    },
735    /// One logical tool invocation was reused for two proposals.
736    #[error("model transcript repeats tool invocation {invocation_id}")]
737    DuplicateInvocationId {
738        /// Reused durable invocation identity.
739        invocation_id: InvocationId,
740    },
741    /// Unknown external effects must be reconciled before continuation.
742    #[error("model transcript outcome {index} has an ambiguous external effect")]
743    AmbiguousExternalOutcome {
744        /// Zero-based proposal position.
745        index: usize,
746    },
747}
748
749/// Bounded ordered prior model/tool turns for one stateless request.
750#[derive(Clone, Default, Eq, PartialEq)]
751pub struct ModelTranscript {
752    turns: Box<[ModelTranscriptTurn]>,
753    payload_bytes: ByteCount,
754}
755
756impl ModelTranscript {
757    /// Maximum retained prior tool-calling turns.
758    pub const MAX_TURNS: usize = 1024;
759    /// Maximum canonical transcript bytes in one request.
760    pub const MAX_PAYLOAD_BYTES: ByteCount = ByteCount::new(64 * MEBIBYTE);
761
762    /// Returns an empty first-turn transcript.
763    #[must_use]
764    pub fn empty() -> Self {
765        Self::default()
766    }
767
768    /// Validates a complete ordered transcript.
769    ///
770    /// # Errors
771    ///
772    /// Rejects excessive size/count, model or provider-format drift, and reuse
773    /// of any attempt, provider-call, or logical tool-invocation identity.
774    pub fn try_new<I>(turns: I) -> Result<Self, ModelTranscriptError>
775    where
776        I: IntoIterator<Item = ModelTranscriptTurn>,
777    {
778        let mut values = Vec::new();
779        let mut payload_bytes = ByteCount::ZERO;
780        let mut model: Option<CapabilityIdentity> = None;
781        let mut format: Option<ModelProviderReplayFormat> = None;
782        let mut attempt_ids = BTreeSet::new();
783        let mut provider_call_ids = BTreeSet::new();
784        let mut invocation_ids = BTreeSet::new();
785        for turn in turns {
786            if values.len() == Self::MAX_TURNS {
787                return Err(ModelTranscriptError::TooManyTurns {
788                    maximum: Self::MAX_TURNS,
789                    actual: Self::MAX_TURNS + 1,
790                });
791            }
792            let turn_model = turn.response.provenance().model();
793            if let Some(expected) = model.as_ref() {
794                if turn_model != expected {
795                    return Err(ModelTranscriptError::ModelIdentityDrift);
796                }
797            } else {
798                model = Some(turn_model.clone());
799            }
800            let turn_format = turn
801                .response
802                .provider_replay()
803                .expect("turn constructor requires provider replay")
804                .format();
805            if let Some(expected) = format.as_ref() {
806                if turn_format != expected {
807                    return Err(ModelTranscriptError::ProviderFormatDrift);
808                }
809            } else {
810                format = Some(turn_format.clone());
811            }
812            let attempt_id = turn.response.provenance().attempt_id();
813            if !attempt_ids.insert(attempt_id) {
814                return Err(ModelTranscriptError::DuplicateAttemptId { attempt_id });
815            }
816            for outcome in &turn.outcomes {
817                let attempt_id = outcome.attempt_id();
818                if !attempt_ids.insert(attempt_id) {
819                    return Err(ModelTranscriptError::DuplicateAttemptId { attempt_id });
820                }
821                if !provider_call_ids.insert(outcome.provider_call_id().clone()) {
822                    return Err(ModelTranscriptError::DuplicateProviderCallId);
823                }
824                let invocation_id = outcome.invocation_id();
825                if !invocation_ids.insert(invocation_id) {
826                    return Err(ModelTranscriptError::DuplicateInvocationId { invocation_id });
827                }
828            }
829            let encoded = serde_json_canonicalizer::to_vec(&turn)
830                .expect("closed transcript turn always has canonical JSON");
831            let encoded_bytes = u64::try_from(encoded.len())
832                .map_err(|_| ModelTranscriptError::PayloadBytesOverflow)?;
833            let framing_bytes = if values.is_empty() { 2 } else { 1 };
834            let additional = encoded_bytes
835                .checked_add(framing_bytes)
836                .map(ByteCount::new)
837                .ok_or(ModelTranscriptError::PayloadBytesOverflow)?;
838            let Some(actual) = payload_bytes.checked_add(additional) else {
839                return Err(ModelTranscriptError::PayloadBytesOverflow);
840            };
841            if actual > Self::MAX_PAYLOAD_BYTES {
842                return Err(ModelTranscriptError::PayloadTooLarge {
843                    maximum: Self::MAX_PAYLOAD_BYTES,
844                    actual,
845                });
846            }
847            payload_bytes = actual;
848            values.push(turn);
849        }
850        Ok(Self {
851            turns: values.into_boxed_slice(),
852            payload_bytes,
853        })
854    }
855
856    /// Returns the number of prior tool-calling turns.
857    #[must_use]
858    pub const fn len(&self) -> usize {
859        self.turns.len()
860    }
861
862    /// Returns whether this is the first provider turn.
863    #[must_use]
864    pub const fn is_empty(&self) -> bool {
865        self.turns.is_empty()
866    }
867
868    /// Returns turns in exact provider continuation order.
869    #[must_use]
870    pub const fn as_slice(&self) -> &[ModelTranscriptTurn] {
871        &self.turns
872    }
873
874    /// Iterates turns in exact provider continuation order.
875    pub fn iter(&self) -> std::slice::Iter<'_, ModelTranscriptTurn> {
876        self.turns.iter()
877    }
878
879    /// Returns aggregate canonical bytes retained by the transcript.
880    #[must_use]
881    pub const fn payload_bytes(&self) -> ByteCount {
882        self.payload_bytes
883    }
884
885    /// Returns the pinned model identity, absent for an empty transcript.
886    #[must_use]
887    pub fn model(&self) -> Option<&CapabilityIdentity> {
888        self.turns
889            .first()
890            .map(|turn| turn.response.provenance().model())
891    }
892
893    /// Returns the pinned provider replay format, absent for an empty transcript.
894    #[must_use]
895    pub fn format(&self) -> Option<&ModelProviderReplayFormat> {
896        self.turns.first().map(|turn| {
897            turn.response
898                .provider_replay()
899                .expect("turn constructor requires replay")
900                .format()
901        })
902    }
903}
904
905impl fmt::Debug for ModelTranscript {
906    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
907        formatter
908            .debug_struct("ModelTranscript")
909            .field("turns", &self.len())
910            .field("payload_bytes", &self.payload_bytes)
911            .field("model", &self.model())
912            .field("format", &self.format())
913            .finish_non_exhaustive()
914    }
915}
916
917impl<'a> IntoIterator for &'a ModelTranscript {
918    type Item = &'a ModelTranscriptTurn;
919    type IntoIter = std::slice::Iter<'a, ModelTranscriptTurn>;
920
921    fn into_iter(self) -> Self::IntoIter {
922        self.iter()
923    }
924}
925
926impl Serialize for ModelTranscript {
927    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
928    where
929        S: Serializer,
930    {
931        self.turns.serialize(serializer)
932    }
933}
934
935impl<'de> Deserialize<'de> for ModelTranscript {
936    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
937    where
938        D: Deserializer<'de>,
939    {
940        let turns = Vec::<ModelTranscriptTurn>::deserialize(deserializer)?;
941        Self::try_new(turns).map_err(de::Error::custom)
942    }
943}
944
945impl JsonSchema for ModelTranscript {
946    fn schema_name() -> std::borrow::Cow<'static, str> {
947        "ModelTranscript".into()
948    }
949
950    fn schema_id() -> std::borrow::Cow<'static, str> {
951        concat!(module_path!(), "::ModelTranscript").into()
952    }
953
954    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
955        json_schema!({
956            "type": "array",
957            "items": generator.subschema_for::<ModelTranscriptTurn>(),
958            "maxItems": 1024,
959            "description": "Ordered durable model/tool turns. Runtime additionally enforces one model and provider format, globally unique attempt/call/invocation identities, and at most 67108864 canonical bytes."
960        })
961    }
962}
963
964/// Invalid complete model/tool transcript.
965#[derive(Clone, Debug, Eq, Error, PartialEq)]
966#[non_exhaustive]
967pub enum ModelTranscriptError {
968    /// The immutable prior-turn ceiling was exceeded.
969    #[error("model transcript has {actual} turns; maximum is {maximum}")]
970    TooManyTurns {
971        /// Immutable turn ceiling.
972        maximum: usize,
973        /// First observed count above the ceiling.
974        actual: usize,
975    },
976    /// A later turn used another pinned model binding.
977    #[error("model transcript changes model identity between turns")]
978    ModelIdentityDrift,
979    /// A later turn changed provider continuation syntax.
980    #[error("model transcript changes provider replay format between turns")]
981    ProviderFormatDrift,
982    /// One physical model or tool attempt appeared twice.
983    #[error("model transcript repeats physical attempt {attempt_id}")]
984    DuplicateAttemptId {
985        /// Reused model attempt identity.
986        attempt_id: AttemptId,
987    },
988    /// A provider tool-call identifier was reused.
989    #[error("model transcript repeats a provider tool call identifier")]
990    DuplicateProviderCallId,
991    /// A logical tool invocation was reused.
992    #[error("model transcript repeats tool invocation {invocation_id}")]
993    DuplicateInvocationId {
994        /// Reused logical invocation identity.
995        invocation_id: InvocationId,
996    },
997    /// Aggregate byte accounting overflowed.
998    #[error("model transcript payload byte accounting overflowed")]
999    PayloadBytesOverflow,
1000    /// Aggregate canonical transcript bytes exceeded the hard request boundary.
1001    #[error("model transcript is {actual}; maximum is {maximum}")]
1002    PayloadTooLarge {
1003        /// Immutable transcript byte ceiling.
1004        maximum: ByteCount,
1005        /// Rejected aggregate bytes.
1006        actual: ByteCount,
1007    },
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use serde_json::json;
1013
1014    use super::*;
1015
1016    #[test]
1017    fn provider_replay_deserialization_rejects_payload_substitution() {
1018        let replay = ModelProviderReplay::new(
1019            ModelProviderReplayFormat::new("provider.responses.output.v1").unwrap(),
1020            BoundedJson::try_from(json!([{
1021                "type": "function_call",
1022                "call_id": "call_01",
1023                "name": "weather.lookup",
1024                "arguments": "{}"
1025            }]))
1026            .unwrap(),
1027        )
1028        .unwrap();
1029        let mut wire = serde_json::to_value(replay).unwrap();
1030        wire["payload"][0]["arguments"] = json!("{\"city\":\"Shanghai\"}");
1031
1032        let error = serde_json::from_value::<ModelProviderReplay>(wire).unwrap_err();
1033        assert!(error.to_string().contains("digest does not match"));
1034    }
1035
1036    #[test]
1037    fn replay_debug_never_formats_opaque_provider_payload() {
1038        let replay = ModelProviderReplay::new(
1039            ModelProviderReplayFormat::new("provider.responses.output.v1").unwrap(),
1040            BoundedJson::try_from(json!([{
1041                "type": "reasoning",
1042                "encrypted_content": "must-not-appear-in-debug"
1043            }]))
1044            .unwrap(),
1045        )
1046        .unwrap();
1047
1048        assert!(!format!("{replay:?}").contains("must-not-appear-in-debug"));
1049    }
1050}