Skip to main content

agent_provider_config/
protocol.rs

1//! Serializable model conversation shared by frontends and the model gateway.
2//!
3//! These are not provider wire envelopes. Credentials, endpoints and HTTP do
4//! not belong here. Stream deltas are presentation data; only a validated final
5//! response may be handed to an action dispatcher. Retrying inference never
6//! authorizes replaying a tool result or an action.
7
8use std::collections::BTreeSet;
9use std::future::Future;
10use std::pin::Pin;
11
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
16pub struct ModelRequest {
17    pub messages: Vec<Message>,
18    #[serde(default)]
19    pub tools: Vec<ToolDefinition>,
20    pub tool_choice: ToolChoice,
21    pub max_output_tokens: u32,
22}
23
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum ToolChoice {
27    #[default]
28    Auto,
29    Required,
30    None,
31}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum Role {
36    System,
37    User,
38    Assistant,
39    Tool,
40}
41
42#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
43pub struct Message {
44    pub role: Role,
45    pub content: Vec<Content>,
46}
47
48impl Message {
49    pub fn text(role: Role, text: impl Into<String>) -> Self {
50        Self {
51            role,
52            content: vec![Content::Text { text: text.into() }],
53        }
54    }
55}
56
57#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
58#[serde(tag = "type", rename_all = "snake_case")]
59pub enum Content {
60    Text {
61        text: String,
62    },
63    /// A provider-exposed reasoning summary, not hidden chain-of-thought.
64    /// Presentation only: never interpreted as an instruction or tool call.
65    Reasoning {
66        text: String,
67        /// Opaque provider state that carries the reasoning into the next
68        /// turn, such as `OpenAI` Responses' encrypted reasoning; never shown.
69        #[serde(default, skip_serializing_if = "Option::is_none")]
70        extra_content: Option<Value>,
71    },
72    /// Inline bytes, never a local path or an implicit URL fetch.
73    Image {
74        media_type: String,
75        base64: String,
76    },
77    ToolCall(ToolCall),
78    ToolResult(ToolResult),
79}
80
81/// The same schema is used to advertise a tool and validate its arguments.
82/// Business validation and permission checks remain with the tool dispatcher.
83#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
84pub struct ToolDefinition {
85    pub name: String,
86    pub description: String,
87    pub input_schema: Value,
88}
89
90impl ToolDefinition {
91    /// Validate the structural vocabulary used by the advertised tool schemas.
92    /// Permission and application-specific checks still belong to dispatch.
93    pub fn validate_input(&self, input: &Value) -> Result<(), ModelError> {
94        validate_input(input, &self.input_schema)
95            .map_err(|reason| ModelError::invalid(format!("{}: {reason}", self.name)))
96    }
97}
98
99fn validate_input(input: &Value, schema: &Value) -> Result<(), String> {
100    if let Some(variants) = schema.get("anyOf").and_then(Value::as_array)
101        && !variants
102            .iter()
103            .any(|variant| validate_input(input, variant).is_ok())
104    {
105        return Err("arguments do not match any allowed type".into());
106    }
107    if let Some(kind) = schema.get("type").and_then(Value::as_str) {
108        let valid = match kind {
109            "object" => input.is_object(),
110            "array" => input.is_array(),
111            "string" => input.is_string(),
112            "boolean" => input.is_boolean(),
113            "null" => input.is_null(),
114            "integer" => input.is_i64() || input.is_u64(),
115            "number" => input.is_number(),
116            _ => return Err("unsupported schema type".into()),
117        };
118        if !valid {
119            return Err(format!("expected {kind}"));
120        }
121    }
122    if let Some(values) = schema.get("enum").and_then(Value::as_array)
123        && !values.contains(input)
124    {
125        return Err("value is not one of the advertised choices".into());
126    }
127    if let Some(object) = input.as_object() {
128        if let Some(required) = schema.get("required").and_then(Value::as_array) {
129            for key in required.iter().filter_map(Value::as_str) {
130                if !object.contains_key(key) {
131                    return Err(format!("missing {key}"));
132                }
133            }
134        }
135        let required = |key: &str| {
136            schema
137                .get("required")
138                .and_then(Value::as_array)
139                .is_some_and(|required| required.iter().any(|name| name == key))
140        };
141        for (key, value) in object {
142            // An optional argument a model writes as `null` is one it left out: the schemas
143            // declare no `null` type (every provider's dialect takes them), and a model filling
144            // every field it was shown writes the ones it means to omit as `null`.
145            if value.is_null() && !required(key) {
146                continue;
147            }
148            if let Some(property) = schema.get("properties").and_then(|p| p.get(key)) {
149                validate_input(value, property).map_err(|error| format!("{key}: {error}"))?;
150            } else if schema.get("additionalProperties") == Some(&Value::Bool(false)) {
151                return Err(format!("unexpected argument {key}"));
152            }
153        }
154    }
155    if let Some(items) = input.as_array() {
156        if let Some(max) = schema.get("maxItems").and_then(Value::as_u64)
157            && items.len() as u64 > max
158        {
159            return Err("too many items".into());
160        }
161        if let Some(item_schema) = schema.get("items") {
162            for item in items {
163                validate_input(item, item_schema)?;
164            }
165        }
166    }
167    Ok(())
168}
169
170#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
171pub struct ToolCall {
172    pub id: String,
173    pub name: String,
174    pub input: Value,
175    /// Opaque provider extensions, including Gemini thought signatures.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub extra_content: Option<Value>,
178}
179
180impl ToolCall {
181    /// # Errors
182    /// Rejects missing identifiers, missing names, and non-object arguments.
183    pub fn validate(&self) -> Result<(), ModelError> {
184        if self.id.trim().is_empty()
185            || self.name.trim().is_empty()
186            || !self.input.is_object()
187            || self
188                .extra_content
189                .as_ref()
190                .is_some_and(|extra| !extra.is_object())
191        {
192            return Err(ModelError::invalid(
193                "tool calls need an id, a name and an argument object",
194            ));
195        }
196        Ok(())
197    }
198}
199
200#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
201pub struct ToolResult {
202    pub call_id: String,
203    pub content: String,
204    pub is_error: bool,
205}
206
207#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "snake_case")]
209pub enum StopReason {
210    EndTurn,
211    ToolCalls,
212    OutputLimit,
213    Refusal,
214}
215
216/// Normalized token accounting. Missing provider counters remain zero.
217#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
218pub struct Usage {
219    /// Every input token: uncached, read from a cache and written to one.
220    pub input_tokens: u64,
221    /// Every output token, reasoning included.
222    pub output_tokens: u64,
223    pub total_tokens: u64,
224    /// The part of `input_tokens` read from the provider's prompt cache.
225    #[serde(default, skip_serializing_if = "is_zero")]
226    pub cached_input_tokens: u64,
227    /// The part of `input_tokens` written to the provider's prompt cache.
228    #[serde(default, skip_serializing_if = "is_zero")]
229    pub cache_write_tokens: u64,
230    /// The part of `output_tokens` spent reasoning.
231    #[serde(default, skip_serializing_if = "is_zero")]
232    pub reasoning_tokens: u64,
233}
234
235#[allow(
236    clippy::trivially_copy_pass_by_ref,
237    reason = "serde's skip_serializing_if passes a reference"
238)]
239const fn is_zero(count: &u64) -> bool {
240    *count == 0
241}
242
243#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
244pub struct ModelResponse {
245    pub message: Message,
246    pub stop_reason: StopReason,
247    #[serde(default)]
248    pub usage: Usage,
249    /// What the gateway charged for this answer, in millionths of the
250    /// currency, at its price table's list price for the model: the number a
251    /// caller spends its own budget against. Zero for a model the table has
252    /// no price for (a local model, or an endpoint's own hosting of one).
253    #[serde(default, skip_serializing_if = "is_zero")]
254    pub cost_micros: u64,
255}
256
257impl ModelResponse {
258    /// Validate the entire turn before exposing any calls, in source order.
259    /// A truncated turn is never executable, even if an earlier call parsed.
260    pub fn tool_calls(&self) -> Result<Vec<&ToolCall>, ModelError> {
261        if self.stop_reason == StopReason::Refusal {
262            return Err(ModelError {
263                kind: ErrorKind::Refused,
264                message: "the model declined the request".into(),
265            });
266        }
267        if self.stop_reason == StopReason::OutputLimit {
268            return Err(ModelError {
269                kind: ErrorKind::Truncated,
270                message: "the model turn was truncated; no actions from this turn were run".into(),
271            });
272        }
273        if self.message.role != Role::Assistant {
274            return Err(ModelError::invalid(
275                "model response was not an assistant message",
276            ));
277        }
278        let mut ids = BTreeSet::new();
279        let mut calls = Vec::new();
280        for content in &self.message.content {
281            if let Content::ToolCall(call) = content {
282                call.validate()?;
283                if !ids.insert(&call.id) {
284                    return Err(ModelError::invalid("duplicate tool call id"));
285                }
286                calls.push(call);
287            }
288        }
289        Ok(calls)
290    }
291}
292
293/// Portable conversation history. A turn is appended atomically only when
294/// every result matches its call, in order. Reusing an executed call id is
295/// refused rather than silently replaying an action after an inference retry.
296#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
297pub struct Conversation {
298    messages: Vec<Message>,
299}
300
301impl Conversation {
302    pub fn new(system: impl Into<String>, user: impl Into<String>) -> Self {
303        Self {
304            messages: vec![
305                Message::text(Role::System, system),
306                Message::text(Role::User, user),
307            ],
308        }
309    }
310
311    pub fn request(&self, tools: Vec<ToolDefinition>, max_output_tokens: u32) -> ModelRequest {
312        ModelRequest {
313            messages: self.messages.clone(),
314            tool_choice: if tools.is_empty() {
315                ToolChoice::None
316            } else {
317                ToolChoice::Required
318            },
319            tools,
320            max_output_tokens,
321        }
322    }
323
324    /// Commit a validated turn and its matching tool results.
325    pub fn push(
326        &mut self,
327        response: ModelResponse,
328        results: Vec<ToolResult>,
329    ) -> Result<(), ModelError> {
330        let calls = self.validate_response(&response)?;
331        if calls.len() != results.len()
332            || calls
333                .iter()
334                .zip(&results)
335                .any(|(call, result)| call.id != result.call_id)
336        {
337            return Err(ModelError::invalid(
338                "tool results must match every call in order",
339            ));
340        }
341        self.messages.push(response.message);
342        if !results.is_empty() {
343            self.messages.push(Message {
344                role: Role::Tool,
345                content: results.into_iter().map(Content::ToolResult).collect(),
346            });
347        }
348        Ok(())
349    }
350
351    /// Call before dispatch as well as before committing the results.
352    ///
353    /// # Errors
354    /// Rejects invalid turns and call identifiers already present in history.
355    pub fn validate_response<'a>(
356        &self,
357        response: &'a ModelResponse,
358    ) -> Result<Vec<&'a ToolCall>, ModelError> {
359        let calls = response.tool_calls()?;
360        let previous: BTreeSet<&str> = self
361            .messages
362            .iter()
363            .flat_map(|message| &message.content)
364            .filter_map(|content| {
365                if let Content::ToolCall(call) = content {
366                    Some(call.id.as_str())
367                } else {
368                    None
369                }
370            })
371            .collect();
372        if calls.iter().any(|call| previous.contains(call.id.as_str())) {
373            return Err(ModelError::invalid("tool call id was already consumed"));
374        }
375        Ok(calls)
376    }
377
378    pub fn messages(&self) -> &[Message] {
379        &self.messages
380    }
381}
382
383/// Presentation-only updates. A call delta, including a complete-looking JSON
384/// argument string, must never trigger dispatch. `Finished` is authoritative.
385#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
386#[serde(tag = "event", rename_all = "snake_case")]
387pub enum StreamEvent {
388    TextDelta {
389        text: String,
390    },
391    /// Only summaries explicitly exposed by the provider. Never synthesized.
392    ReasoningDelta {
393        text: String,
394    },
395    ToolCallDelta {
396        index: u32,
397        id: Option<String>,
398        name: Option<String>,
399        arguments: String,
400    },
401    Finished {
402        response: ModelResponse,
403    },
404    Failed {
405        error: ModelError,
406    },
407}
408
409#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
410#[serde(rename_all = "snake_case")]
411pub enum ErrorKind {
412    Unavailable,
413    /// No model provider is set up for this person yet: nothing failed,
414    /// there is just nothing to ask.
415    NoProvider,
416    Authentication,
417    PermissionDenied,
418    InvalidRequest,
419    /// Provider descriptions changed since the administration snapshot.
420    Conflict,
421    InvalidResponse,
422    Unsupported,
423    RateLimited,
424    /// Billing or quota exhaustion; retrying without funding cannot help.
425    CreditsExhausted,
426    /// The conversation exceeds the selected model's context window.
427    ContextLimit,
428    /// A provider failure not classified more specifically.
429    Provider,
430    TimedOut,
431    Cancelled,
432    Truncated,
433    Refused,
434    Transport,
435    /// This computer can't reach the server that keeps the person's
436    /// workspace, where their model is asked: there is no model while it is
437    /// offline, and nothing on this computer answers instead.
438    Offline,
439}
440
441/// Safe frontend diagnostic. Backends must not place credentials or raw
442/// provider bodies in `message`.
443#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
444pub struct ModelError {
445    pub kind: ErrorKind,
446    pub message: String,
447}
448
449impl ModelError {
450    /// Stable diagnostic for failures whose source may contain credentials or
451    /// provider-controlled text. Never echo that source into a frontend error.
452    pub fn new(kind: ErrorKind) -> Self {
453        let message = match kind {
454            ErrorKind::Unavailable => "Model service unavailable",
455            ErrorKind::Offline => {
456                "No model while offline: your model is asked on your workspace's server, which \
457                 this computer can't reach right now"
458            }
459            ErrorKind::NoProvider => "No model provider is set up yet",
460            ErrorKind::Authentication => {
461                "Provider authentication failed; check the credential in Settings"
462            }
463            ErrorKind::PermissionDenied => "Provider permission denied",
464            ErrorKind::InvalidRequest => "Invalid model request",
465            ErrorKind::Conflict => "Provider settings changed; refresh before saving",
466            ErrorKind::InvalidResponse => "Invalid model response",
467            ErrorKind::Unsupported => "Model operation unsupported; update the gateway",
468            ErrorKind::RateLimited => "Provider rate limit reached",
469            ErrorKind::CreditsExhausted => "Provider credits exhausted",
470            ErrorKind::ContextLimit => "Model context limit exceeded",
471            ErrorKind::Provider => "Provider request failed",
472            ErrorKind::TimedOut => "Model request timed out",
473            ErrorKind::Cancelled => "Model request cancelled",
474            ErrorKind::Truncated => {
475                "Model stream ended without a final response; partial output retained"
476            }
477            ErrorKind::Refused => "Model declined the request",
478            ErrorKind::Transport => "Model network transport failed",
479        };
480        Self {
481            kind,
482            message: message.into(),
483        }
484    }
485
486    pub fn invalid(message: impl Into<String>) -> Self {
487        Self {
488            kind: ErrorKind::InvalidResponse,
489            message: message.into(),
490        }
491    }
492}
493
494/// What a person can do next. None of these authorize replaying actions.
495#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
496#[serde(rename_all = "snake_case")]
497pub enum Recovery {
498    /// Set up a model provider (an API key) in Model Providers.
499    AddProvider,
500    /// Reload the authoritative snapshot; do not overwrite concurrent edits.
501    RefreshSettings,
502    SignIn,
503    AddCredits,
504    WaitAndRetry,
505    ReduceContext,
506    /// Start fresh inference from committed history, never from a partial call.
507    RetryInference,
508    /// Explicitly request continuation of prose; partial tool calls are discarded.
509    ContinueText,
510    ChangeRequest,
511}
512
513impl Recovery {
514    /// What may happen next, as an agent's own instruction. It names no
515    /// session, setting or vocabulary a person would not know: a person
516    /// reads the page's own sentence for the failure, never this.
517    pub fn guidance(self) -> &'static str {
518        match self {
519            Self::AddProvider => "a provider with a model must be set up",
520            Self::RefreshSettings => "the provider settings must be read again",
521            Self::SignIn => "the provider credential must be checked",
522            Self::AddCredits => "the provider needs credit",
523            Self::WaitAndRetry => "the provider's rate limit has not reset yet",
524            Self::ReduceContext => "the conversation has more context than the model takes",
525            Self::RetryInference => "the turn starts again from committed history",
526            Self::ContinueText => "the partial answer may be continued as text",
527            Self::ChangeRequest => "the request or the model must change",
528        }
529    }
530}
531
532impl ModelError {
533    pub fn recovery(&self) -> Recovery {
534        match self.kind {
535            ErrorKind::Conflict => Recovery::RefreshSettings,
536            ErrorKind::NoProvider => Recovery::AddProvider,
537            ErrorKind::Authentication => Recovery::SignIn,
538            ErrorKind::CreditsExhausted => Recovery::AddCredits,
539            ErrorKind::RateLimited => Recovery::WaitAndRetry,
540            ErrorKind::ContextLimit => Recovery::ReduceContext,
541            ErrorKind::Truncated => Recovery::ContinueText,
542            ErrorKind::Unavailable
543            | ErrorKind::Offline
544            | ErrorKind::TimedOut
545            | ErrorKind::Transport
546            | ErrorKind::Provider => Recovery::RetryInference,
547            _ => Recovery::ChangeRequest,
548        }
549    }
550}
551
552/// Explicit terminal status: transport EOF is never completion.
553#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(rename_all = "snake_case")]
555pub enum StreamStatus {
556    #[default]
557    Streaming,
558    Completed,
559    Truncated,
560    Refused,
561    Cancelled,
562    Failed,
563}
564
565/// Retained presentation state for one inference attempt. Deltas are inert;
566/// only `response()` exposes a validated, completed turn for dispatch. There is
567/// deliberately no automatic retry: callers keep committed conversation/results
568/// and start new inference rather than re-executing a previous action batch.
569#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
570pub struct StreamState {
571    pub status: StreamStatus,
572    pub text: String,
573    pub reasoning: String,
574    pub error: Option<ModelError>,
575    final_response: Option<ModelResponse>,
576}
577
578impl StreamState {
579    /// Terminal states are sticky, including cancellation racing a late finish.
580    pub fn apply(&mut self, event: &StreamEvent) {
581        if self.status != StreamStatus::Streaming {
582            return;
583        }
584        match event {
585            StreamEvent::TextDelta { text } => self.text.push_str(text),
586            StreamEvent::ReasoningDelta { text } => self.reasoning.push_str(text),
587            StreamEvent::ToolCallDelta { .. } => {}
588            StreamEvent::Failed { error } => {
589                self.status = match error.kind {
590                    ErrorKind::Cancelled => StreamStatus::Cancelled,
591                    ErrorKind::Truncated => StreamStatus::Truncated,
592                    ErrorKind::Refused => StreamStatus::Refused,
593                    _ => StreamStatus::Failed,
594                };
595                self.error = Some(error.clone());
596            }
597            StreamEvent::Finished { response } => {
598                let validation = response.tool_calls();
599                if let Err(error) = &validation
600                    && !matches!(error.kind, ErrorKind::Truncated | ErrorKind::Refused)
601                {
602                    self.fail(error.clone());
603                    return;
604                }
605                // Finals are authoritative where present; absent fields must not
606                // erase partial output on a refusal or truncated response.
607                let mut text = String::new();
608                let mut reasoning = String::new();
609                for block in &response.message.content {
610                    match block {
611                        Content::Text { text: part } => text.push_str(part),
612                        Content::Reasoning { text: part, .. } => reasoning.push_str(part),
613                        _ => {}
614                    }
615                }
616                if !text.is_empty() {
617                    self.text = text;
618                }
619                if !reasoning.is_empty() {
620                    self.reasoning = reasoning;
621                }
622                match validation {
623                    Ok(_) => {
624                        self.status = StreamStatus::Completed;
625                        self.final_response = Some(response.clone());
626                    }
627                    Err(error) => self.apply(&StreamEvent::Failed { error }),
628                }
629            }
630        }
631    }
632
633    /// Called on EOF, missing final frame or watchdog expiration. Partial
634    /// prose and reasoning remain available, but no calls become executable.
635    pub fn fail(&mut self, error: ModelError) {
636        self.apply(&StreamEvent::Failed { error });
637    }
638
639    pub fn cancel(&mut self) {
640        self.fail(ModelError {
641            kind: ErrorKind::Cancelled,
642            message: "Generation cancelled; partial output retained".into(),
643        });
644    }
645
646    pub fn response(&self) -> Option<&ModelResponse> {
647        self.final_response.as_ref()
648    }
649
650    /// Explicit prose-only continuation. Uses committed history plus retained
651    /// answer text, never partial tool arguments or reasoning. Tools are disabled
652    /// so continuation cannot replay an action. The original history is unchanged.
653    ///
654    /// # Errors
655    /// Rejects states without a truncated, nonempty prose answer.
656    pub fn continue_text(
657        &self,
658        history: &Conversation,
659        max_output_tokens: u32,
660    ) -> Result<ModelRequest, ModelError> {
661        if self.status != StreamStatus::Truncated || self.text.is_empty() {
662            return Err(ModelError::invalid(
663                "only truncated answer text can be continued",
664            ));
665        }
666        let mut request = history.request(Vec::new(), max_output_tokens);
667        request
668            .messages
669            .push(Message::text(Role::Assistant, &self.text));
670        request.messages.push(Message::text(
671            Role::User,
672            "Continue the interrupted answer from where it stopped. Do not repeat or perform actions.",
673        ));
674        Ok(request)
675    }
676}
677
678impl std::fmt::Display for ModelError {
679    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
680        formatter.write_str(&self.message)
681    }
682}
683
684impl std::error::Error for ModelError {}
685
686/// No sockets, threads or `Send` requirement: a browser frontend can implement
687/// this using a lightweight backend, while native callers use the gateway.
688pub type CompletionFuture<'a> =
689    Pin<Box<dyn Future<Output = Result<ModelResponse, ModelError>> + 'a>>;
690
691/// Local presentation sink. Tool deltas are never authorization to execute.
692pub type StreamSink<'a> = Box<dyn FnMut(StreamEvent) + 'a>;
693
694pub trait ModelBackend {
695    fn complete<'a>(&'a self, request: &'a ModelRequest) -> CompletionFuture<'a>;
696
697    /// Backends may override for live deltas. Dropping the future cancels the
698    /// local subscription. The returned response, not EOF, is authoritative.
699    fn stream<'a>(
700        &'a self,
701        request: &'a ModelRequest,
702        mut sink: StreamSink<'a>,
703    ) -> CompletionFuture<'a> {
704        Box::pin(async move {
705            let response = self.complete(request).await?;
706            for content in &response.message.content {
707                match content {
708                    Content::Text { text } => sink(StreamEvent::TextDelta { text: text.clone() }),
709                    Content::Reasoning { text, .. } => {
710                        sink(StreamEvent::ReasoningDelta { text: text.clone() });
711                    }
712                    _ => {}
713                }
714            }
715            Ok(response)
716        })
717    }
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723    use serde_json::json;
724
725    fn response(ids: &[&str]) -> ModelResponse {
726        ModelResponse {
727            message: Message {
728                role: Role::Assistant,
729                content: ids
730                    .iter()
731                    .map(|id| {
732                        Content::ToolCall(ToolCall {
733                            id: (*id).into(),
734                            name: "invoke".into(),
735                            input: json!({"enabled": false, "count": 2}),
736                            extra_content: None,
737                        })
738                    })
739                    .collect(),
740            },
741            stop_reason: StopReason::ToolCalls,
742            usage: Usage::default(),
743            cost_micros: 0,
744        }
745    }
746
747    #[test]
748    fn partial_output_survives_every_non_success_terminal_state() {
749        for (kind, status) in [
750            (ErrorKind::Truncated, StreamStatus::Truncated),
751            (ErrorKind::Refused, StreamStatus::Refused),
752            (ErrorKind::Cancelled, StreamStatus::Cancelled),
753            (ErrorKind::Transport, StreamStatus::Failed),
754            (ErrorKind::TimedOut, StreamStatus::Failed),
755            (ErrorKind::InvalidResponse, StreamStatus::Failed),
756        ] {
757            let mut state = StreamState::default();
758            state.apply(&StreamEvent::TextDelta {
759                text: "Partial answer".into(),
760            });
761            state.apply(&StreamEvent::ReasoningDelta {
762                text: "Exposed summary".into(),
763            });
764            state.apply(&StreamEvent::ToolCallDelta {
765                index: 0,
766                id: Some("a".into()),
767                name: Some("invoke".into()),
768                arguments: "{}".into(),
769            });
770            assert!(state.response().is_none());
771            state.fail(ModelError {
772                kind,
773                message: "interrupted".into(),
774            });
775            // Late success and late deltas cannot resurrect an interrupted turn.
776            state.apply(&StreamEvent::Finished {
777                response: response(&["a"]),
778            });
779            state.apply(&StreamEvent::TextDelta {
780                text: "late".into(),
781            });
782            assert_eq!(state.status, status);
783            assert_eq!(state.text, "Partial answer");
784            assert_eq!(state.reasoning, "Exposed summary");
785            assert!(state.response().is_none());
786        }
787    }
788
789    #[test]
790    fn authoritative_stop_reason_controls_dispatch_and_continuation() {
791        let history = Conversation::new("system", "user");
792        for (reason, status) in [
793            (StopReason::ToolCalls, StreamStatus::Completed),
794            (StopReason::OutputLimit, StreamStatus::Truncated),
795            (StopReason::Refusal, StreamStatus::Refused),
796        ] {
797            let mut state = StreamState::default();
798            let mut final_response = response(&["a"]);
799            final_response.stop_reason = reason;
800            final_response.message.content.push(Content::Text {
801                text: "Answer".into(),
802            });
803            final_response.message.content.push(Content::Reasoning {
804                text: "Summary".into(),
805                extra_content: None,
806            });
807            state.apply(&StreamEvent::Finished {
808                response: final_response,
809            });
810            assert_eq!(state.status, status);
811            assert_eq!(
812                state.response().is_some(),
813                status == StreamStatus::Completed
814            );
815            if status == StreamStatus::Truncated {
816                let request = state.continue_text(&history, 100).unwrap();
817                assert_eq!(request.tool_choice, ToolChoice::None);
818                assert!(request.tools.is_empty());
819                assert_eq!(
820                    request.messages[2],
821                    Message::text(Role::Assistant, "Answer")
822                );
823                assert_eq!(request.messages.len(), 4);
824                assert_eq!(history.messages().len(), 2);
825                assert!(!serde_json::to_string(&request).unwrap().contains("Summary"));
826            } else {
827                assert!(state.continue_text(&history, 100).is_err());
828            }
829            let decoded: StreamState =
830                serde_json::from_str(&serde_json::to_string(&state).unwrap()).unwrap();
831            assert_eq!(decoded, state);
832        }
833    }
834
835    #[test]
836    fn malformed_final_keeps_partial_output_and_is_not_dispatchable() {
837        let mut state = StreamState::default();
838        state.apply(&StreamEvent::TextDelta {
839            text: "partial".into(),
840        });
841        let mut malformed = response(&["a", "a"]);
842        malformed.message.content.push(Content::Text {
843            text: "invalid replacement".into(),
844        });
845        state.apply(&StreamEvent::Finished {
846            response: malformed,
847        });
848        assert_eq!(state.status, StreamStatus::Failed);
849        assert_eq!(state.error.unwrap().kind, ErrorKind::InvalidResponse);
850        assert_eq!(state.text, "partial");
851        assert!(state.final_response.is_none());
852    }
853
854    #[test]
855    fn recovery_is_actionable_without_automatic_action_replay() {
856        for (kind, recovery) in [
857            (ErrorKind::Conflict, Recovery::RefreshSettings),
858            (ErrorKind::Authentication, Recovery::SignIn),
859            (ErrorKind::CreditsExhausted, Recovery::AddCredits),
860            (ErrorKind::RateLimited, Recovery::WaitAndRetry),
861            (ErrorKind::ContextLimit, Recovery::ReduceContext),
862            (ErrorKind::TimedOut, Recovery::RetryInference),
863            (ErrorKind::Transport, Recovery::RetryInference),
864            (ErrorKind::Provider, Recovery::RetryInference),
865            (ErrorKind::Truncated, Recovery::ContinueText),
866            (ErrorKind::InvalidResponse, Recovery::ChangeRequest),
867        ] {
868            assert_eq!(
869                ModelError {
870                    kind,
871                    message: String::new()
872                }
873                .recovery(),
874                recovery
875            );
876        }
877    }
878
879    #[test]
880    fn usage_round_trips_and_older_responses_default_to_zero() {
881        let mut answer = response(&["a"]);
882        answer.usage = Usage {
883            input_tokens: 12,
884            output_tokens: 3,
885            total_tokens: 15,
886            cached_input_tokens: 8,
887            cache_write_tokens: 2,
888            reasoning_tokens: 1,
889        };
890        let encoded = serde_json::to_value(&answer).unwrap();
891        assert_eq!(
892            serde_json::from_value::<ModelResponse>(encoded.clone()).unwrap(),
893            answer
894        );
895        let mut older = encoded;
896        older.as_object_mut().unwrap().remove("usage");
897        assert_eq!(
898            serde_json::from_value::<ModelResponse>(older)
899                .unwrap()
900                .usage,
901            Usage::default()
902        );
903    }
904
905    #[test]
906    fn tool_schema_checks_nested_types_and_unknown_arguments() {
907        let tool = ToolDefinition {
908            name: "test".into(),
909            description: String::new(),
910            input_schema: json!({
911                "type": "object", "required": ["steps"], "additionalProperties": false,
912                "properties": {"steps": {"type": "array", "items": {
913                    "type": "object", "required": ["enabled"],
914                    "properties": {"enabled": {"type": "boolean"}}
915                }}}
916            }),
917        };
918        assert!(
919            tool.validate_input(&json!({"steps": [{"enabled": false}]}))
920                .is_ok()
921        );
922        for input in [
923            json!({}),
924            json!({"steps": [{"enabled": "false"}]}),
925            json!({"steps": [], "extra": true}),
926        ] {
927            assert!(tool.validate_input(&input).is_err());
928        }
929    }
930
931    /// An optional argument written as `null` is left out, as a model filling every field it was
932    /// shown writes one it does not mean; a required one written as `null` is still refused.
933    #[test]
934    fn tool_schema_takes_an_optional_argument_written_as_null_as_left_out() {
935        let tool = ToolDefinition {
936            name: "place".into(),
937            description: String::new(),
938            input_schema: json!({
939                "type": "object", "required": ["resource"], "additionalProperties": false,
940                "properties": {
941                    "resource": {"type": "string"},
942                    "view": {"type": "string"},
943                }
944            }),
945        };
946        assert!(
947            tool.validate_input(&json!({"resource": "r", "view": null}))
948                .is_ok()
949        );
950        assert!(tool.validate_input(&json!({"resource": null})).is_err());
951        assert!(
952            tool.validate_input(&json!({"resource": "r", "other": null}))
953                .is_ok(),
954            "a null is no argument at all"
955        );
956    }
957
958    #[test]
959    fn complete_calls_keep_ids_order_and_argument_types() {
960        let original = response(&["second", "first"]);
961        let decoded: ModelResponse =
962            serde_json::from_str(&serde_json::to_string(&original).unwrap()).unwrap();
963        assert_eq!(decoded, original);
964        let calls = decoded.tool_calls().unwrap();
965        assert_eq!(
966            calls
967                .iter()
968                .map(|call| call.id.as_str())
969                .collect::<Vec<_>>(),
970            ["second", "first"]
971        );
972        assert_eq!(calls[0].input["enabled"], false);
973        assert_eq!(calls[0].input["count"], 2);
974    }
975
976    #[test]
977    fn history_is_atomic_and_retries_cannot_replay_consumed_calls() {
978        let mut history = Conversation::new("system", "user");
979        let answer = response(&["a", "b"]);
980        let result = |id: &str| ToolResult {
981            call_id: id.into(),
982            content: "ok".into(),
983            is_error: false,
984        };
985        assert!(
986            history
987                .push(answer.clone(), vec![result("b"), result("a")])
988                .is_err()
989        );
990        assert_eq!(history.messages().len(), 2);
991        history
992            .push(answer.clone(), vec![result("a"), result("b")])
993            .unwrap();
994        assert_eq!(history.messages().len(), 4);
995        assert!(
996            history
997                .push(answer, vec![result("a"), result("b")])
998                .is_err()
999        );
1000        assert_eq!(history.messages().len(), 4);
1001    }
1002
1003    #[test]
1004    fn malformed_duplicate_and_truncated_calls_are_not_dispatchable() {
1005        assert!(response(&["same", "same"]).tool_calls().is_err());
1006        assert!(response(&[""]).tool_calls().is_err());
1007        let mut partial = response(&["valid"]);
1008        partial.stop_reason = StopReason::OutputLimit;
1009        assert!(partial.tool_calls().is_err());
1010        let Content::ToolCall(call) = &mut partial.message.content[0] else {
1011            panic!()
1012        };
1013        call.input = json!("not an object");
1014        partial.stop_reason = StopReason::ToolCalls;
1015        assert!(partial.tool_calls().is_err());
1016    }
1017}