Skip to main content

mutil_ai/
native_tool_stream.rs

1//! Protocol-level accumulation for one native custom tool call.
2//!
3//! This module is independent of the Responses adapter until it is integrated
4//! with terminal response reconciliation and result pairing.
5
6use crate::{
7    Error, NativeToolCall, NativeToolCompletion, NativeToolKind, NativeToolPayload, Result,
8};
9
10/// Identity fields as they become available across streamed frames.
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub struct NativeToolIdentity {
13    pub namespace: Option<String>,
14    pub name: Option<String>,
15    pub call_id: Option<String>,
16    pub item_id: Option<String>,
17}
18
19/// Accumulates a single custom call; deltas are fragments and done inputs are
20/// authoritative snapshots. Identical completion snapshots are idempotent.
21///
22/// The caller must route events by response and output index and deduplicate
23/// repeated delta frames using transport event identity when available.
24#[derive(Debug, Default)]
25pub struct CustomToolAccumulator {
26    identity: NativeToolIdentity,
27    input: String,
28    snapshot: Option<String>,
29    item_completed: bool,
30    interrupted: bool,
31    invalid: bool,
32}
33
34impl CustomToolAccumulator {
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// Merge identity from a frame without replacing an existing value.
40    pub fn merge_identity(&mut self, identity: &NativeToolIdentity) -> Result<()> {
41        fn merge(target: &mut Option<String>, incoming: &Option<String>) -> Result<()> {
42            if let Some(value) = incoming {
43                if value.is_empty() || target.as_ref().is_some_and(|old| old != value) {
44                    return Err(Error::StreamProtocol("tool_identity_conflict".into()));
45                }
46                *target = Some(value.clone());
47            }
48            Ok(())
49        }
50        // Apply transactionally so a failed frame cannot partially mutate identity.
51        let mut merged = self.identity.clone();
52        let result = (|| {
53            merge(&mut merged.namespace, &identity.namespace)?;
54            merge(&mut merged.name, &identity.name)?;
55            merge(&mut merged.call_id, &identity.call_id)?;
56            merge(&mut merged.item_id, &identity.item_id)
57        })();
58        if result.is_err() {
59            self.invalid = true;
60        }
61        result?;
62        self.identity = merged;
63        Ok(())
64    }
65
66    /// Append a delta fragment before a completion snapshot.
67    pub fn push_delta(&mut self, delta: &str) -> Result<()> {
68        if self.snapshot.is_some() || self.interrupted {
69            self.invalid = true;
70            return Err(Error::StreamProtocol("tool_payload_conflict".into()));
71        }
72        self.input.push_str(delta);
73        Ok(())
74    }
75
76    /// Merge a full input snapshot. A partially delivered delta sequence may be
77    /// a prefix of the snapshot; disagreement is always an error.
78    pub fn finish_input(&mut self, snapshot: &str) -> Result<()> {
79        if self.interrupted
80            || self.snapshot.as_ref().is_some_and(|old| old != snapshot)
81            || !snapshot.starts_with(&self.input)
82        {
83            self.invalid = true;
84            return Err(Error::StreamProtocol("tool_payload_conflict".into()));
85        }
86        self.input = snapshot.to_owned();
87        self.snapshot = Some(snapshot.to_owned());
88        Ok(())
89    }
90
91    /// Record an authoritative completed item after validating its full input.
92    /// An input-done frame alone does not establish that the item completed.
93    pub fn finish_item(&mut self, snapshot: &str) -> Result<()> {
94        self.finish_input(snapshot)?;
95        self.item_completed = true;
96        Ok(())
97    }
98
99    /// Mark an unfinished call interrupted; an already completed item remains
100    /// a completed fact, leaving cancellation scheduling to the caller.
101    pub fn interrupt(&mut self) {
102        if !self.item_completed {
103            self.interrupted = true;
104        }
105    }
106
107    /// Snapshot of accumulated raw input, including incomplete input.
108    pub fn input(&self) -> &str {
109        &self.input
110    }
111
112    /// Whether a completed item snapshot was observed.
113    pub fn is_completed(&self) -> bool {
114        self.item_completed && !self.invalid
115    }
116
117    /// Obtain a completed call only with a full snapshot and real identity.
118    pub fn completed_call(&self) -> Result<NativeToolCall> {
119        if self.invalid {
120            return Err(Error::StreamProtocol("tool_call_invalid".into()));
121        }
122        if self.interrupted || !self.item_completed {
123            return Err(Error::StreamProtocol("tool_call_incomplete".into()));
124        }
125        let call = NativeToolCall {
126            kind: NativeToolKind::Custom,
127            namespace: self.identity.namespace.clone(),
128            name: self.identity.name.clone().unwrap_or_default(),
129            call_id: self.identity.call_id.clone().unwrap_or_default(),
130            item_id: self.identity.item_id.clone(),
131            payload: NativeToolPayload::RawText(self.input.clone()),
132            completion: NativeToolCompletion::Completed,
133            provider_state: None,
134        };
135        call.validate_completed()?;
136        Ok(call)
137    }
138}