Skip to main content

ag_ui/server/emit/
reasoning.rs

1//! Streaming one reasoning block.
2
3use crate::{Event, MessageId, ReasoningEncryptedValueSubtype};
4
5use crate::server::emit::EventSink;
6use crate::server::error::Result;
7use crate::server::state::RunState;
8
9/// One open reasoning block.
10///
11/// Created by [`RunContext::reasoning`](crate::server::RunContext::reasoning). The
12/// `REASONING_*` family nests a message inside a block, so the handle brackets
13/// four events rather than two:
14///
15/// ```text
16/// REASONING_START          ← on creation
17/// REASONING_MESSAGE_START  ← on creation
18/// REASONING_MESSAGE_CONTENT × n
19/// REASONING_MESSAGE_END    ← on end() or Drop
20/// REASONING_END            ← on end() or Drop
21/// ```
22///
23/// Use it for model reasoning you want the client to render. Reasoning a
24/// provider returns only as an opaque blob goes through
25/// [`encrypted_value`](Self::encrypted_value) instead.
26#[derive(Debug)]
27pub struct ReasoningHandle<'a, S> {
28    sink: &'a mut EventSink,
29    state: &'a mut RunState<S>,
30    id: MessageId,
31    ended: bool,
32}
33
34impl<'a, S> ReasoningHandle<'a, S> {
35    /// Emits `REASONING_START` and `REASONING_MESSAGE_START`.
36    pub(crate) fn start(
37        sink: &'a mut EventSink,
38        state: &'a mut RunState<S>,
39        id: MessageId,
40    ) -> Result<Self> {
41        sink.emit(Event::reasoning_start(id.clone()))?;
42        // The block is open now and the message inside it is not, so a failure
43        // here closes the block alone: a cancellation landing between the two
44        // must not send an end for a message that never started.
45        if let Err(error) = sink.emit(Event::reasoning_message_start(id.clone())) {
46            let _ = sink.emit_forced(Event::reasoning_end(id));
47            return Err(error);
48        }
49        Ok(Self {
50            sink,
51            state,
52            id,
53            ended: false,
54        })
55    }
56
57    /// The id every event of this block carries.
58    pub fn id(&self) -> &MessageId {
59        &self.id
60    }
61
62    /// Appends reasoning text — `REASONING_MESSAGE_CONTENT`.
63    pub fn delta(&mut self, text: impl Into<String>) -> Result<()> {
64        self.sink
65            .emit(Event::reasoning_message_content(self.id.clone(), text))
66    }
67
68    /// Attaches the provider's opaque reasoning signature —
69    /// `REASONING_ENCRYPTED_VALUE`.
70    ///
71    /// Under zero-data-retention the provider returns no readable reasoning,
72    /// only a blob that must be replayed on the next request for the model to
73    /// stay coherent.
74    pub fn encrypted_value(&mut self, value: impl Into<String>) -> Result<()> {
75        self.sink.emit(Event::reasoning_encrypted_value(
76            ReasoningEncryptedValueSubtype::Message,
77            self.id.clone(),
78            value,
79        ))
80    }
81
82    /// Emits an unrelated event without closing the block. See
83    /// [`MessageHandle::emit`](crate::server::MessageHandle::emit).
84    pub fn emit(&mut self, event: Event) -> Result<()> {
85        self.sink.emit(event)
86    }
87
88    /// Emits `REASONING_MESSAGE_END` then `REASONING_END`, and consumes the
89    /// handle.
90    pub fn end(mut self) -> Result<()> {
91        self.ended = true;
92        self.close()
93    }
94
95    /// Closes both halves, after cancellation too. The block terminator is
96    /// attempted even when the message terminator failed, so a half-open block
97    /// cannot outlive the handle.
98    fn close(&mut self) -> Result<()> {
99        let message = self
100            .sink
101            .emit_forced(Event::reasoning_message_end(self.id.clone()));
102        let block = self.sink.emit_forced(Event::reasoning_end(self.id.clone()));
103        message.and(block)
104    }
105}
106
107state_access! {
108    /// The run's state, reachable while the block is open. See
109    /// [`ToolCallHandle`](crate::server::ToolCallHandle), where this matters most.
110    ReasoningHandle, published "inside this block's brackets"
111}
112
113impl<S> Drop for ReasoningHandle<'_, S> {
114    fn drop(&mut self) {
115        if !self.ended {
116            let _ = self.close();
117        }
118    }
119}