1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
//! Execution phase for assistant messages in multi-step tool-calling flows.
//!
//! This is a provider-wire concept: phases are parsed off the provider stream
//! and, for providers with native support, sent back on the request. It lives in
//! the provider abstraction so both the driver types (`Message`,
//! `LlmStreamEvent`) and core's `Message` can share it.
use serde::{Deserialize, Serialize};
#[cfg(feature = "openapi")]
use utoipa::ToSchema;
/// Execution phase for assistant messages in multi-step tool-calling flows.
///
/// Providers that natively support phases (OpenAI GPT-5.x) send the phase value
/// directly in the API request. For providers without native support (Anthropic,
/// Gemini), the phase is still tracked internally and derived from state in the
/// ReasonAtom, but is not sent to the provider API.
///
/// Serialized as lowercase strings for backward compatibility with existing
/// persisted messages: `"commentary"` and `"final_answer"`.
///
/// Legacy values `"in_progress"` and `"completed"` are accepted during
/// deserialization for backward compatibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
// The serde impls below are hand-written, so utoipa cannot infer the wire
// casing from a `serde(rename_all)` attribute and would otherwise publish the
// Rust variant names. Keep this in lockstep with `as_provider_str`.
#[cfg_attr(feature = "openapi", schema(rename_all = "snake_case"))]
pub enum ExecutionPhase {
/// Intermediate update — preamble or commentary before/between tool calls.
/// The model is still working and may issue more tool calls.
Commentary,
/// Final completed response — no more tool calls expected.
FinalAnswer,
}
/// Where a message's [`ExecutionPhase`] came from.
///
/// Only some providers report a phase. For the rest the runtime infers one from
/// tool-call presence, where "commentary" means nothing more than "this message
/// called tools" — so a text-only preamble is indistinguishable from a final
/// answer. Those are different claims, and a consumer cannot tell them apart
/// from the phase value alone, so the source travels with it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(rename_all = "snake_case"))]
pub enum PhaseSource {
/// The provider reported this phase on the wire.
Provider,
/// The runtime inferred it from tool-call presence. A weak signal.
Derived,
}
impl PhaseSource {
pub fn as_str(&self) -> &'static str {
match self {
Self::Provider => "provider",
Self::Derived => "derived",
}
}
pub fn from_str_opt(s: &str) -> Option<Self> {
match s {
"provider" => Some(Self::Provider),
"derived" => Some(Self::Derived),
_ => None,
}
}
}
impl Serialize for PhaseSource {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for PhaseSource {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Self::from_str_opt(&s)
.ok_or_else(|| serde::de::Error::unknown_variant(&s, &["provider", "derived"]))
}
}
impl ExecutionPhase {
/// Derive phase from whether the response contains tool calls.
pub fn from_has_tool_calls(has_tool_calls: bool) -> Self {
if has_tool_calls {
Self::Commentary
} else {
Self::FinalAnswer
}
}
/// Parse a provider wire value into an ExecutionPhase.
/// Returns `None` for unrecognized values.
pub fn from_provider_str(s: &str) -> Option<Self> {
match s {
"commentary" | "in_progress" => Some(Self::Commentary),
"final_answer" | "completed" => Some(Self::FinalAnswer),
_ => None,
}
}
/// Wire value used by providers that support native phases (OpenAI).
pub fn as_provider_str(&self) -> &'static str {
match self {
Self::Commentary => "commentary",
Self::FinalAnswer => "final_answer",
}
}
/// Monotonic refinement for the streamed phase *hint* on
/// `output.message.started` / `output.message.delta`.
///
/// The hint may advance `None -> Commentary | FinalAnswer` exactly once and
/// then never changes: it never flip-flops between variants and never
/// reverts to `None`. Once a message has been classified mid-stream that
/// classification stays put; the authoritative value remains the completed
/// `Message.phase`. Returns the (possibly unchanged) refined hint.
pub fn refine_streamed_hint(current: Option<Self>, incoming: Self) -> Option<Self> {
// First classification wins; a later hint cannot overwrite it.
Some(current.unwrap_or(incoming))
}
}
impl std::fmt::Display for ExecutionPhase {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_provider_str())
}
}
impl Serialize for ExecutionPhase {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_provider_str())
}
}
impl<'de> Deserialize<'de> for ExecutionPhase {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
match s.as_str() {
"commentary" | "in_progress" => Ok(Self::Commentary),
"final_answer" | "completed" => Ok(Self::FinalAnswer),
other => Err(serde::de::Error::unknown_variant(
other,
&["commentary", "final_answer", "in_progress", "completed"],
)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_execution_phase_from_provider_str() {
assert_eq!(
ExecutionPhase::from_provider_str("commentary"),
Some(ExecutionPhase::Commentary)
);
assert_eq!(
ExecutionPhase::from_provider_str("final_answer"),
Some(ExecutionPhase::FinalAnswer)
);
assert_eq!(
ExecutionPhase::from_provider_str("in_progress"),
Some(ExecutionPhase::Commentary)
);
assert_eq!(
ExecutionPhase::from_provider_str("completed"),
Some(ExecutionPhase::FinalAnswer)
);
assert_eq!(ExecutionPhase::from_provider_str("unknown"), None);
}
#[test]
fn tool_call_presence_derives_execution_phase() {
assert_eq!(
ExecutionPhase::from_has_tool_calls(true),
ExecutionPhase::Commentary
);
assert_eq!(
ExecutionPhase::from_has_tool_calls(false),
ExecutionPhase::FinalAnswer
);
}
#[test]
fn streamed_hint_keeps_first_classification() {
use ExecutionPhase::{Commentary, FinalAnswer};
for (current, incoming, expected) in [
(None, Commentary, Commentary),
(None, FinalAnswer, FinalAnswer),
(Some(Commentary), Commentary, Commentary),
(Some(Commentary), FinalAnswer, Commentary),
(Some(FinalAnswer), Commentary, FinalAnswer),
(Some(FinalAnswer), FinalAnswer, FinalAnswer),
] {
assert_eq!(
ExecutionPhase::refine_streamed_hint(current, incoming),
Some(expected)
);
}
}
#[test]
fn phase_wire_values_accept_legacy_spellings_and_reject_invalid_input() {
for (input, phase, canonical) in [
("commentary", ExecutionPhase::Commentary, "commentary"),
("in_progress", ExecutionPhase::Commentary, "commentary"),
("final_answer", ExecutionPhase::FinalAnswer, "final_answer"),
("completed", ExecutionPhase::FinalAnswer, "final_answer"),
] {
let decoded: ExecutionPhase = serde_json::from_value(serde_json::json!(input)).unwrap();
assert_eq!(decoded, phase);
assert_eq!(
serde_json::to_value(decoded).unwrap(),
serde_json::json!(canonical)
);
assert_eq!(decoded.as_provider_str(), canonical);
assert_eq!(decoded.to_string(), canonical);
}
for input in [
serde_json::json!("bogus"),
serde_json::json!("Commentary"),
serde_json::Value::Null,
serde_json::json!(42),
] {
assert!(serde_json::from_value::<ExecutionPhase>(input).is_err());
}
}
}