use crate::context::block::{
BlockContent, BlockMeta, ContentPart, ContextBlock, TextPayload, ToolCallPayload,
};
use crate::context::ids::{
BlockId, BlockSequence, ContextVersion, ConversationId, FrameId, FrameScope, RoundId, TurnId,
};
use crate::context::model::{ModelResponse, ModelStopReason};
use crate::context::tool_data::{ToolCallId, ToolResultPayload};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::{HashMap, HashSet};
pub mod turn_context_as_snapshot {
use super::*;
pub fn serialize<S: Serializer>(value: &TurnContext, s: S) -> Result<S::Ok, S::Error> {
TurnSnapshot::serialize(&value.snapshot(), s)
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<TurnContext, D::Error> {
let snap = TurnSnapshot::deserialize(d)?;
let mut ctx = TurnContext::from_validated_blocks(
snap.turn_id,
snap.blocks.into_inner(),
snap.source_version,
)
.map_err(serde::de::Error::custom)?;
if snap.sealed {
ctx.seal();
}
Ok(ctx)
}
}
pub mod option_turn_context_as_snapshot {
use super::*;
pub fn serialize<S: Serializer>(value: &Option<TurnContext>, s: S) -> Result<S::Ok, S::Error> {
match value {
Some(ctx) => turn_context_as_snapshot::serialize(ctx, s),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<TurnContext>, D::Error> {
let opt: Option<TurnSnapshot> = Option::deserialize(d)?;
opt.map(|snap| {
let mut ctx = TurnContext::from_validated_blocks(
snap.turn_id,
snap.blocks.into_inner(),
snap.source_version,
)
.map_err(serde::de::Error::custom)?;
if snap.sealed {
ctx.seal();
}
Ok(ctx)
})
.transpose()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnLifecycle {
Open,
Sealed,
}
#[derive(Debug, Clone)]
pub struct ModelContext {
pub blocks: Vec<ContextBlock>,
}
#[derive(Debug, Clone)]
pub struct ContextFrame {
pub frame_id: FrameId,
pub scope: FrameScope,
pub round_id: RoundId,
pub model_context: ModelContext,
}
#[derive(Debug, thiserror::Error)]
pub enum ContextError {
#[error("sealed turn")]
SealedTurn,
#[error("foreign invocation: expected turn {expected:?}, got {actual:?}")]
ForeignInvocation {
expected: TurnId,
actual: TurnId,
},
#[error("invalid model output: {0}")]
InvalidModelOutput(String),
#[error("invalid sequence: {0}")]
InvalidSequence(String),
#[error("duplicate tool call id: {0:?}")]
DuplicateToolCallId(crate::context::tool_data::ToolCallId),
#[error("unpaired tool result: {0:?}")]
UnpairedToolResult(crate::context::tool_data::ToolCallId),
}
#[derive(Debug, Clone)]
pub struct AppliedModelOutput {
pub block_ids: Vec<BlockId>,
pub tool_calls: Vec<ToolCallPayload>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OrderedBlocks(Vec<ContextBlock>);
impl OrderedBlocks {
pub fn empty() -> Self {
Self(Vec::new())
}
pub fn as_slice(&self) -> &[ContextBlock] {
&self.0
}
pub fn into_inner(self) -> Vec<ContextBlock> {
self.0
}
}
#[derive(Clone)]
pub struct TurnContext {
turn_id: TurnId,
blocks: OrderedBlocks,
version: ContextVersion,
lifecycle: TurnLifecycle,
next_seq: u64,
}
impl std::fmt::Debug for TurnContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TurnContext")
.field("turn_id", &self.turn_id)
.field("version", &self.version)
.field("lifecycle", &self.lifecycle)
.field("blocks_len", &self.blocks.0.len())
.field("next_seq", &self.next_seq)
.finish()
}
}
impl TurnContext {
pub fn new(turn_id: TurnId) -> Self {
Self {
turn_id,
blocks: OrderedBlocks::empty(),
version: ContextVersion(0),
lifecycle: TurnLifecycle::Open,
next_seq: 0,
}
}
pub fn is_sealed(&self) -> bool {
matches!(self.lifecycle, TurnLifecycle::Sealed)
}
pub fn blocks(&self) -> &[ContextBlock] {
&self.blocks.0
}
pub fn version(&self) -> ContextVersion {
self.version
}
pub fn turn_id(&self) -> TurnId {
self.turn_id.clone()
}
pub fn lifecycle(&self) -> TurnLifecycle {
self.lifecycle
}
pub fn snapshot_blocks(&self) -> Vec<ContextBlock> {
self.blocks.0.clone()
}
pub fn append_input(
&mut self,
text: TextPayload,
source: impl Into<String>,
) -> Result<BlockId, ContextError> {
self.append_parts(vec![ContentPart::Text(text)], source)
}
pub fn append_parts(
&mut self,
parts: Vec<ContentPart>,
source: impl Into<String>,
) -> Result<BlockId, ContextError> {
self.ensure_open()?;
if parts.is_empty() {
return Err(ContextError::InvalidSequence(
"append_parts: empty parts are not a fact".into(),
));
}
let meta = BlockMeta {
source: Some(source.into()),
..BlockMeta::default()
};
let mut ids = self.commit_blocks(vec![(BlockContent::Parts(parts), meta)]);
Ok(ids.pop().expect("single-block commit yields one id"))
}
pub fn append_model_output(
&mut self,
invocation: crate::context::ids::InvocationId,
response: &ModelResponse,
stop_reason: ModelStopReason,
) -> Result<AppliedModelOutput, ContextError> {
self.ensure_open()?;
if invocation.turn_id != self.turn_id {
return Err(ContextError::ForeignInvocation {
expected: self.turn_id.clone(),
actual: invocation.turn_id.clone(),
});
}
match stop_reason {
ModelStopReason::EndTurn if !response.tool_calls.is_empty() => {
return Err(ContextError::InvalidModelOutput(
"EndTurn must have empty tool_calls".into(),
));
}
ModelStopReason::ToolUse if response.tool_calls.is_empty() => {
return Err(ContextError::InvalidModelOutput(
"ToolUse must have non-empty tool_calls".into(),
));
}
_ => {}
}
let mut prepared: Vec<(BlockContent, BlockMeta)> = Vec::new();
let mut tool_calls: Vec<ToolCallPayload> = Vec::new();
if !response.text.0.trim().is_empty() {
prepared.push((
BlockContent::Parts(vec![ContentPart::Text(TextPayload(
response.text.0.clone(),
))]),
BlockMeta::default(),
));
}
for (pos, draft) in response.tool_calls.iter().enumerate() {
if draft.tool_name.trim().is_empty() {
return Err(ContextError::InvalidModelOutput("tool_name empty".into()));
}
if !draft.arguments.is_object() {
return Err(ContextError::InvalidModelOutput(
"arguments must be object".into(),
));
}
let call_id =
ToolCallId::generate(invocation.round_id, &draft.tool_name, &draft.arguments, pos);
for b in &self.blocks.0 {
if let BlockContent::ToolCall(tc) = &b.content
&& tc.call_id == call_id
{
return Err(ContextError::DuplicateToolCallId(call_id));
}
}
let payload = ToolCallPayload {
call_id: call_id.clone(),
tool_name: draft.tool_name.clone(),
arguments: draft.arguments.clone(),
};
tool_calls.push(payload.clone());
prepared.push((
BlockContent::ToolCall(payload),
BlockMeta {
provider_call_id: draft.provider_call_id.clone(),
..BlockMeta::default()
},
));
}
let block_ids = self.commit_blocks(prepared);
Ok(AppliedModelOutput {
block_ids,
tool_calls,
})
}
pub fn append_tool_results(
&mut self,
results: Vec<ToolResultPayload>,
) -> Result<Vec<BlockId>, ContextError> {
self.ensure_open()?;
if results.is_empty() {
return Ok(vec![]);
}
let mut call_seq: HashMap<ToolCallId, BlockSequence> = HashMap::new();
let mut paired: HashSet<ToolCallId> = HashSet::new();
for b in &self.blocks.0 {
match &b.content {
BlockContent::ToolCall(tc) => {
call_seq.insert(tc.call_id.clone(), b.sequence);
}
BlockContent::ToolResult(tr) => {
paired.insert(tr.call_id.clone());
}
_ => {}
}
}
let mut batch: HashSet<ToolCallId> = HashSet::new();
let mut ordered: Vec<(BlockSequence, &ToolResultPayload)> = Vec::new();
for r in &results {
let seq = match call_seq.get(&r.call_id) {
Some(seq) => *seq,
None => return Err(ContextError::UnpairedToolResult(r.call_id.clone())),
};
if paired.contains(&r.call_id) {
return Err(ContextError::InvalidSequence(format!(
"tool call already paired: {:?}",
r.call_id
)));
}
if !batch.insert(r.call_id.clone()) {
return Err(ContextError::InvalidSequence(format!(
"duplicate tool result in batch: {:?}",
r.call_id
)));
}
ordered.push((seq, r));
}
ordered.sort_by_key(|(seq, _)| *seq);
let prepared = ordered
.into_iter()
.map(|(_, r)| {
(
BlockContent::ToolResult(ToolResultPayload {
call_id: r.call_id.clone(),
status: r.status.clone(),
output: r.output.clone(),
media: r.media.clone(),
}),
BlockMeta::default(),
)
})
.collect();
Ok(self.commit_blocks(prepared))
}
pub fn frame(&self, round_id: RoundId) -> ContextFrame {
self.frame_with(round_id, self.blocks.0.clone())
}
pub(crate) fn frame_with(&self, round_id: RoundId, blocks: Vec<ContextBlock>) -> ContextFrame {
let frame_id =
crate::context::ids::FrameId::deterministic(&self.turn_id, self.version, round_id);
ContextFrame {
frame_id,
scope: FrameScope::Turn {
turn_id: self.turn_id.clone(),
source_version: self.version,
},
round_id,
model_context: ModelContext { blocks },
}
}
pub fn seal(&mut self) {
self.lifecycle = TurnLifecycle::Sealed;
}
fn ensure_open(&self) -> Result<(), ContextError> {
if self.is_sealed() {
Err(ContextError::SealedTurn)
} else {
Ok(())
}
}
fn commit_blocks(&mut self, prepared: Vec<(BlockContent, BlockMeta)>) -> Vec<BlockId> {
if prepared.is_empty() {
return Vec::new();
}
let mut ids = Vec::with_capacity(prepared.len());
for (content, meta) in prepared {
ids.push(self.push_block(content, meta));
}
self.version = self.version.next();
ids
}
fn push_block(&mut self, content: BlockContent, meta: BlockMeta) -> BlockId {
let seq = BlockSequence(self.next_seq);
let id = BlockId {
turn_id: self.turn_id.clone(),
sequence: seq,
};
let block = ContextBlock {
id: id.clone(),
sequence: seq,
content,
meta,
};
self.blocks.0.push(block);
self.next_seq += 1;
id
}
pub fn from_validated_blocks(
turn_id: TurnId,
blocks: Vec<ContextBlock>,
version: ContextVersion,
) -> Result<Self, ContextError> {
Self::validate_blocks(&turn_id, &blocks)?;
let next_seq = blocks.len() as u64;
Ok(Self {
turn_id,
blocks: OrderedBlocks(blocks),
version,
lifecycle: TurnLifecycle::Open,
next_seq,
})
}
pub fn validate_blocks(turn_id: &TurnId, blocks: &[ContextBlock]) -> Result<(), ContextError> {
for (idx, b) in blocks.iter().enumerate() {
if b.id.turn_id != *turn_id {
return Err(ContextError::InvalidSequence(format!(
"block turn_id mismatch at {}",
idx
)));
}
if b.sequence.0 != idx as u64 {
return Err(ContextError::InvalidSequence(format!(
"block sequence not monotonic at {} expected {} got {}",
idx, idx, b.sequence.0
)));
}
if b.id.sequence != b.sequence {
return Err(ContextError::InvalidSequence(format!(
"block id sequence mismatch at {}",
idx
)));
}
}
let mut call_set = HashSet::new();
let mut seen_results = HashSet::new();
for b in blocks {
match &b.content {
BlockContent::Parts(parts) => {
if parts.is_empty() {
return Err(ContextError::InvalidSequence("empty parts block".into()));
}
}
BlockContent::ToolCall(tc) => {
if !call_set.insert(tc.call_id.clone()) {
return Err(ContextError::DuplicateToolCallId(tc.call_id.clone()));
}
}
BlockContent::ToolResult(tr) => {
if !call_set.contains(&tr.call_id) {
return Err(ContextError::UnpairedToolResult(tr.call_id.clone()));
}
if !seen_results.insert(tr.call_id.clone()) {
return Err(ContextError::InvalidSequence(format!(
"duplicate tool result for {:?}",
tr.call_id
)));
}
}
}
}
Ok(())
}
pub fn snapshot(&self) -> TurnSnapshot {
TurnSnapshot {
turn_id: self.turn_id.clone(),
blocks: self.blocks.clone(),
source_version: self.version,
sealed: self.is_sealed(),
}
}
}
fn default_sealed() -> bool {
true
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TurnSnapshot {
pub turn_id: TurnId,
pub blocks: OrderedBlocks,
pub source_version: ContextVersion,
#[serde(default = "default_sealed")]
pub sealed: bool,
}
pub fn merged_frame(
conversation_id: &ConversationId,
history: &[TurnSnapshot],
active: &TurnContext,
round_id: RoundId,
) -> ContextFrame {
let mut blocks = Vec::new();
for snapshot in history {
blocks.extend(snapshot.blocks.as_slice().iter().cloned());
}
blocks.extend(active.blocks().iter().cloned());
let scope = FrameScope::Conversation {
conversation_id: conversation_id.clone(),
active_turn_id: active.turn_id(),
source_version: active.version(),
};
ContextFrame {
frame_id: FrameId::from_scope(&scope, round_id),
scope,
round_id,
model_context: ModelContext { blocks },
}
}