Skip to main content

causa_kernel/context/model/
value.rs

1//! Fact vocabulary of the model door — what the fact machine validates and
2//! records. The gateway envelope (`ModelOutput`), the transport error, and
3//! request parameters (`ModelRef`, `GenerationOptions`, `ToolSurface`) are
4//! port vocabulary and live in `crate::ports::gateway`.
5
6use serde::{Deserialize, Serialize};
7
8use crate::context::block::{ContentPart, TextPayload, WireMeta};
9
10/// A tool call as the model proposed it, before the caller assigns its declaration `BlockId`. Exactly what the gateway parsed off the wire.
11#[derive(Debug, Clone, Default, Serialize, Deserialize)]
12#[non_exhaustive]
13pub struct ToolCallDraft {
14    /// Name of the tool the model asked to invoke.
15    pub tool_name: String,
16    /// Tool arguments as a JSON object; validated by the kernel before commit.
17    pub arguments: serde_json::Value,
18    /// Provider-issued identifier for this tool call, if the upstream model
19    /// API assigned one. The kernel records it verbatim (on the envelope
20    /// `BlockMeta`) and pairs tool results by the declaration `BlockId`, never by this field.
21    /// `ToolCallId` remains a borrowed content key for concurrent deduplication.
22    #[serde(default)]
23    pub provider_call_id: Option<String>,
24}
25impl ToolCallDraft {
26    /// A draft call with no provider call id.
27    pub fn new(tool_name: impl Into<String>, arguments: serde_json::Value) -> Self {
28        Self {
29            tool_name: tool_name.into(),
30            arguments,
31            provider_call_id: None,
32        }
33    }
34
35    /// Sets the provider-issued identifier for this tool call.
36    pub fn with_provider_call_id(mut self, provider_call_id: impl Into<String>) -> Self {
37        self.provider_call_id = Some(provider_call_id.into());
38        self
39    }
40}
41
42/// Why the model stopped producing output for this round, as reported by
43/// the gateway. The kernel validates only the EndTurn/ToolUse structural
44/// pairing; interpreting terminal reasons is driver policy.
45///
46/// Exhaustive on purpose: the runtime decides what a turn does next from this value, so a new one is a breaking change.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum ModelStopReason {
50    /// The model ended its turn without requesting tools; `tool_calls` must
51    /// be empty.
52    EndTurn,
53    /// The model requested tool invocations; `tool_calls` must be non-empty.
54    ToolUse,
55    /// Output was cut off at the token limit.
56    MaxTokens,
57    /// The model (or a provider content filter) refused to produce output.
58    Refusal,
59    /// The provider stopped because the context window was exhausted. The
60    /// output was not committed; the runner reports it as an interruption.
61    ContextWindowExceeded,
62    /// The provider reported a stop value this kernel has no meaning for. The
63    /// output was not committed and the wire value is preserved on
64    /// `ModelOutput::raw_stop_reason`.
65    Unrecognized,
66}
67
68/// The model door's fact shape: what the model produced, as an ordered list
69/// of items. One item becomes one block on commit, in item order. Named for
70/// the participant, not for any wire role.
71#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct ModelResponse {
73    /// What the model said and asked, in the order the provider returned it.
74    pub items: Vec<ModelItem>,
75}
76
77impl ModelResponse {
78    /// The tool calls the model asked for, in item order; ids are assigned
79    /// at commit.
80    pub fn tool_calls(&self) -> impl Iterator<Item = &ToolCallDraft> {
81        self.items.iter().filter_map(|item| match &item.content {
82            ModelItemContent::ToolCall(call) => Some(call),
83            ModelItemContent::Parts(_) => None,
84        })
85    }
86
87    /// Every text part of every readable item, concatenated in order with no
88    /// separator. Media and sealed parts contribute nothing.
89    pub fn text(&self) -> String {
90        let mut text = String::new();
91        for item in &self.items {
92            if let ModelItemContent::Parts(parts) = &item.content {
93                for part in parts {
94                    if let ContentPart::Text(t) = part {
95                        text.push_str(&t.0);
96                    }
97                }
98            }
99        }
100        text
101    }
102}
103
104/// One item the model produced: its content plus the wire fields that
105/// content does not hold.
106#[derive(Debug, Clone, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct ModelItem {
109    /// What the item says or asks.
110    pub content: ModelItemContent,
111    /// What the provider's item carried beyond `content`; copied to
112    /// [`BlockMeta::wire`](crate::BlockMeta::wire) on commit. The kernel
113    /// never reads it.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub wire: Option<WireMeta>,
116}
117impl ModelItem {
118    /// An item with no wire residue.
119    pub fn new(content: ModelItemContent) -> Self {
120        Self {
121            content,
122            wire: None,
123        }
124    }
125}
126
127impl ModelItem {
128    /// An item of one text part and no wire fields.
129    pub fn text(text: impl Into<String>) -> Self {
130        Self {
131            content: ModelItemContent::Parts(vec![ContentPart::Text(TextPayload::new(text))]),
132            wire: None,
133        }
134    }
135
136    /// A tool-call item with no wire fields.
137    pub fn tool_call(call: ToolCallDraft) -> Self {
138        Self {
139            content: ModelItemContent::ToolCall(call),
140            wire: None,
141        }
142    }
143}
144
145/// The content of a [`ModelItem`].
146///
147/// Exhaustive on purpose: conversion to blocks handles every shape, so a new one is a breaking change.
148#[derive(Debug, Clone, Serialize, Deserialize)]
149#[serde(rename_all = "snake_case")]
150pub enum ModelItemContent {
151    /// Ordered content parts (text and sealed items) that commit as one
152    /// `Parts` block.
153    Parts(Vec<ContentPart>),
154    /// A tool call that commits as one `ToolCall` block.
155    ToolCall(ToolCallDraft),
156}