1use 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#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
27pub struct ModelProviderReplayFormat(Box<str>);
28
29impl ModelProviderReplayFormat {
30 pub const MAX_BYTES: usize = 128;
32
33 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 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
152#[non_exhaustive]
153pub enum ModelProviderReplayFormatError {
154 #[error("model provider replay format must not be empty")]
156 Empty,
157 #[error("model provider replay format is {actual} bytes; maximum is {maximum}")]
159 TooLong {
160 maximum: usize,
162 actual: usize,
164 },
165 #[error("model provider replay format has invalid syntax")]
167 InvalidSyntax,
168}
169
170#[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 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 #[must_use]
207 pub const fn format(&self) -> &ModelProviderReplayFormat {
208 &self.format
209 }
210
211 #[must_use]
213 pub const fn payload(&self) -> &BoundedJson {
214 &self.payload
215 }
216
217 #[must_use]
219 pub const fn digest(&self) -> Digest {
220 self.digest
221 }
222
223 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
280#[non_exhaustive]
281pub enum ModelProviderReplayError {
282 #[error("model provider replay payload must be a JSON array")]
284 PayloadMustBeArray,
285 #[error("model provider replay digest does not match its payload")]
287 DigestMismatch,
288}
289
290#[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 #[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 #[must_use]
334 pub const fn invocation_id(&self) -> InvocationId {
335 self.invocation_id
336 }
337
338 #[must_use]
340 pub const fn attempt_id(&self) -> AttemptId {
341 self.attempt_id
342 }
343
344 #[must_use]
346 pub const fn tool(&self) -> &CapabilityIdentity {
347 &self.tool
348 }
349
350 #[must_use]
352 pub const fn failure_id(&self) -> FailureId {
353 self.failure_id
354 }
355
356 #[must_use]
358 pub const fn category(&self) -> FailureCategory {
359 self.category
360 }
361
362 #[must_use]
364 pub const fn code(&self) -> &FailureCode {
365 &self.code
366 }
367
368 #[must_use]
370 pub const fn message(&self) -> &FailureMessage {
371 &self.message
372 }
373
374 #[must_use]
376 pub const fn retry_advice(&self) -> RetryAdvice {
377 self.retry_advice
378 }
379
380 #[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#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
424#[non_exhaustive]
425pub enum ModelToolFailureError {
426 #[error("model tool failure ambiguity evidence is inconsistent")]
428 InvalidAmbiguityEvidence,
429}
430
431#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
433#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
434pub enum ModelToolOutcome {
435 Succeeded {
437 provider_call_id: ModelProviderToolCallId,
439 result: ToolResult,
441 },
442 Failed {
444 provider_call_id: ModelProviderToolCallId,
446 error: ModelToolFailure,
448 },
449}
450
451impl ModelToolOutcome {
452 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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#[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 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 #[must_use]
651 pub const fn response(&self) -> &ModelResponse {
652 &self.response
653 }
654
655 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
697#[non_exhaustive]
698pub enum ModelTranscriptTurnError {
699 #[error("model transcript turn response must finish with tool calls")]
701 ResponseHasNoToolCalls,
702 #[error("model transcript turn is missing provider replay evidence")]
704 MissingProviderReplay,
705 #[error("model transcript expects {expected} tool outcomes, received {actual}")]
707 OutcomeCountMismatch {
708 expected: usize,
710 actual: usize,
712 },
713 #[error("model transcript proposal {index} has no provider call identifier")]
715 MissingProviderCallId {
716 index: usize,
718 },
719 #[error("model transcript outcome {index} provider call identifier does not match")]
721 ProviderCallIdMismatch {
722 index: usize,
724 },
725 #[error("model transcript outcome {index} tool identity does not match its proposal")]
727 ToolIdentityMismatch {
728 index: usize,
730 expected: Box<CapabilityIdentity>,
732 actual: Box<CapabilityIdentity>,
734 },
735 #[error("model transcript repeats tool invocation {invocation_id}")]
737 DuplicateInvocationId {
738 invocation_id: InvocationId,
740 },
741 #[error("model transcript outcome {index} has an ambiguous external effect")]
743 AmbiguousExternalOutcome {
744 index: usize,
746 },
747}
748
749#[derive(Clone, Default, Eq, PartialEq)]
751pub struct ModelTranscript {
752 turns: Box<[ModelTranscriptTurn]>,
753 payload_bytes: ByteCount,
754}
755
756impl ModelTranscript {
757 pub const MAX_TURNS: usize = 1024;
759 pub const MAX_PAYLOAD_BYTES: ByteCount = ByteCount::new(64 * MEBIBYTE);
761
762 #[must_use]
764 pub fn empty() -> Self {
765 Self::default()
766 }
767
768 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 #[must_use]
858 pub const fn len(&self) -> usize {
859 self.turns.len()
860 }
861
862 #[must_use]
864 pub const fn is_empty(&self) -> bool {
865 self.turns.is_empty()
866 }
867
868 #[must_use]
870 pub const fn as_slice(&self) -> &[ModelTranscriptTurn] {
871 &self.turns
872 }
873
874 pub fn iter(&self) -> std::slice::Iter<'_, ModelTranscriptTurn> {
876 self.turns.iter()
877 }
878
879 #[must_use]
881 pub const fn payload_bytes(&self) -> ByteCount {
882 self.payload_bytes
883 }
884
885 #[must_use]
887 pub fn model(&self) -> Option<&CapabilityIdentity> {
888 self.turns
889 .first()
890 .map(|turn| turn.response.provenance().model())
891 }
892
893 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
966#[non_exhaustive]
967pub enum ModelTranscriptError {
968 #[error("model transcript has {actual} turns; maximum is {maximum}")]
970 TooManyTurns {
971 maximum: usize,
973 actual: usize,
975 },
976 #[error("model transcript changes model identity between turns")]
978 ModelIdentityDrift,
979 #[error("model transcript changes provider replay format between turns")]
981 ProviderFormatDrift,
982 #[error("model transcript repeats physical attempt {attempt_id}")]
984 DuplicateAttemptId {
985 attempt_id: AttemptId,
987 },
988 #[error("model transcript repeats a provider tool call identifier")]
990 DuplicateProviderCallId,
991 #[error("model transcript repeats tool invocation {invocation_id}")]
993 DuplicateInvocationId {
994 invocation_id: InvocationId,
996 },
997 #[error("model transcript payload byte accounting overflowed")]
999 PayloadBytesOverflow,
1000 #[error("model transcript is {actual}; maximum is {maximum}")]
1002 PayloadTooLarge {
1003 maximum: ByteCount,
1005 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}