Skip to main content

ag_ui/server/
context.rs

1//! What an agent is handed for one run.
2
3use std::collections::HashSet;
4use std::future::Future;
5
6use crate::{
7    Context, Event, Message, MessageId, ResumeEntry, RunAgentInput, RunId, StepName, SubagentRunId,
8    SubagentStartedEvent, TextMessageRole, ThreadId, TokenUsage, Tool, ToolCallId,
9    ToolCallStartEvent,
10};
11use futures_channel::mpsc;
12use futures_util::future::{Either, select};
13use serde_json::Value;
14
15use crate::server::agent::AgentState;
16use crate::server::cancel::{CancellationToken, Cancelled};
17use crate::server::emit::{
18    EventReceiver, EventSink, MessageHandle, ReasoningHandle, StepGuard, SubagentHandle,
19    ToolCallHandle,
20};
21use crate::server::error::{Error, Result};
22use crate::server::state::RunState;
23use crate::server::transform::TransformerChain;
24
25/// The request, the state, the event sink and the cancellation flag — one
26/// run's whole world.
27///
28/// An agent gets `&mut RunContext<S>` and emits through it. Every emitter takes
29/// `&mut self`, which is what makes two overlapping messages a borrow-check
30/// error rather than a protocol violation discovered by a confused frontend.
31///
32/// ```
33/// # use ag_ui::RunAgentInput;
34/// # use ag_ui::server::RunContext;
35/// # let (mut ctx, _events) = RunContext::<()>::new(RunAgentInput::new("thread-1", "run-1"))?;
36/// assert_eq!(ctx.thread_id().as_str(), "thread-1");
37/// assert!(ctx.messages().is_empty());
38///
39/// let mut message = ctx.assistant_message()?;
40/// message.delta("Hello")?;
41/// message.end()?;
42/// # Ok::<(), ag_ui::server::Error>(())
43/// ```
44#[derive(Debug)]
45pub struct RunContext<S> {
46    input: RunAgentInput,
47    state: RunState<S>,
48    sink: EventSink,
49    terminal: Terminal,
50}
51
52/// The message, tool-call and subagent IDs reserved in this run.
53///
54/// An id is the run id and a counter, so a context that continues a run
55/// counts on from where the earlier one stopped. A message id handed out
56/// twice does not start a second message: it re-opens the first.
57#[derive(Debug)]
58pub(crate) struct Minted {
59    run_id: RunId,
60    messages: IdCounter,
61    tool_calls: IdCounter,
62    subagents: IdCounter,
63}
64
65/// The counter behind the ids of one kind.
66///
67/// The numbers a run already uses are not this crate's to choose. An id of
68/// the shape a context hands out can come from a request, which a run
69/// echoes, or from an agent that names its own ids. So the counter trusts
70/// none of them to be small: it never overflows, and it never hands out a
71/// number that was noted.
72#[derive(Clone, Debug, Default, PartialEq, Eq)]
73struct IdCounter {
74    /// The last number handed out, or the highest that was noted.
75    last: u64,
76    /// Consecutive reserved numbers from 1. A run using only generated IDs
77    /// needs no set entries.
78    used_through: u64,
79    /// Other reserved numbers beyond that prefix.
80    taken: HashSet<u64>,
81}
82
83impl IdCounter {
84    fn note(&mut self, number: u64) {
85        if number <= self.used_through {
86            return;
87        }
88        self.last = self.last.max(number);
89        if number == self.used_through + 1 {
90            self.used_through = number;
91            while let Some(next) = self.used_through.checked_add(1) {
92                if !self.taken.remove(&next) {
93                    break;
94                }
95                self.used_through = next;
96            }
97        } else {
98            self.taken.insert(number);
99        }
100    }
101
102    fn note_id(&mut self, prefix: &str, kind: &str, id: &str) {
103        if let Some(number) = id
104            .strip_prefix(prefix)
105            .and_then(|rest| rest.strip_prefix(kind))
106            .and_then(|number| number.parse::<u64>().ok())
107        {
108            self.note(number);
109        }
110    }
111
112    /// Continue above the highest number in use. A caller may have reserved
113    /// u64::MAX, in which case the first gap above the contiguous prefix is free.
114    fn next(&mut self) -> u64 {
115        let number = self
116            .last
117            .checked_add(1)
118            .unwrap_or_else(|| self.used_through + 1);
119        self.note(number);
120        number
121    }
122}
123
124impl Minted {
125    pub(super) fn new(run_id: RunId) -> Self {
126        Self {
127            run_id,
128            messages: IdCounter::default(),
129            tool_calls: IdCounter::default(),
130            subagents: IdCounter::default(),
131        }
132    }
133
134    pub(super) fn note_history(&mut self, messages: &[Message]) {
135        let prefix = id_prefix(&self.run_id);
136        for message in messages {
137            self.messages.note_id(prefix, MESSAGE_ID, message.id());
138            if let Some(owner) = message.subagent_run_id() {
139                self.subagents.note_id(prefix, SUBAGENT_ID, owner);
140            }
141            match message {
142                Message::Assistant(assistant) => {
143                    for call in assistant.tool_calls.iter().flatten() {
144                        self.tool_calls.note_id(prefix, TOOL_CALL_ID, &call.id);
145                    }
146                }
147                Message::Tool(tool) => {
148                    self.tool_calls
149                        .note_id(prefix, TOOL_CALL_ID, &tool.tool_call_id)
150                }
151                _ => {}
152            }
153        }
154    }
155
156    /// Reserve entity IDs introduced by an event, including the references
157    /// that introduce an implicit tool-call carrier or subagent.
158    pub(super) fn note(&mut self, event: &Event) {
159        let prefix = id_prefix(&self.run_id);
160        let mut message = |id: &MessageId| self.messages.note_id(prefix, MESSAGE_ID, id);
161        let mut call = |id: &ToolCallId| self.tool_calls.note_id(prefix, TOOL_CALL_ID, id);
162        let mut subagent = |id: &SubagentRunId| self.subagents.note_id(prefix, SUBAGENT_ID, id);
163        if let Some(owner) = event.subagent_run_id() {
164            subagent(owner);
165        }
166        match event {
167            Event::TextMessageStart(e) => message(&e.message_id),
168            Event::ReasoningStart(e) => message(&e.message_id),
169            Event::ReasoningMessageStart(e) => message(&e.message_id),
170            Event::ActivitySnapshot(e) => message(&e.message_id),
171            Event::ToolCallResult(e) => {
172                message(&e.message_id);
173                call(&e.tool_call_id);
174            }
175            Event::TextMessageChunk(e) => e.message_id.iter().for_each(message),
176            Event::ReasoningMessageChunk(e) => e.message_id.iter().for_each(message),
177            Event::MessagesSnapshot(e) => self.note_history(&e.messages),
178            Event::RunStarted(e) => {
179                if let Some(input) = &e.input {
180                    self.note_history(&input.messages);
181                }
182            }
183            Event::SubagentStarted(e) => {
184                e.parent_subagent_run_id.iter().for_each(subagent);
185                e.parent_tool_call_id.iter().for_each(call);
186                e.parent_message_id.iter().for_each(message);
187            }
188            Event::ToolCallStart(e) => {
189                call(&e.tool_call_id);
190                e.parent_message_id.iter().for_each(message);
191            }
192            Event::ToolCallChunk(e) => {
193                e.tool_call_id.iter().for_each(call);
194                e.parent_message_id.iter().for_each(message);
195            }
196            _ => {}
197        }
198    }
199}
200
201/// What separates the run id from the counter in an id a context hands out.
202const MESSAGE_ID: &str = "-msg-";
203const TOOL_CALL_ID: &str = "-call-";
204const SUBAGENT_ID: &str = "-sub-";
205
206/// What the ids a context hands out begin with.
207fn id_prefix(run_id: &RunId) -> &str {
208    if run_id.is_empty() {
209        "run"
210    } else {
211        run_id.as_str()
212    }
213}
214
215/// What the agent asked the driver to put on the terminal event.
216#[derive(Debug, Default)]
217pub(crate) struct Terminal {
218    /// `RUN_FINISHED.result`.
219    pub(crate) result: Option<Value>,
220    /// One entry per model call, summed per `(provider, model)` at the end.
221    pub(crate) usage: Vec<TokenUsage>,
222}
223
224impl Terminal {
225    /// The `usage` list for a terminal event, or `None` when nothing was
226    /// reported.
227    pub(crate) fn usage(&self) -> Option<Vec<TokenUsage>> {
228        let usage = crate::aggregate_token_usage(&self.usage);
229        (!usage.is_empty()).then_some(usage)
230    }
231}
232
233impl<S: AgentState> RunContext<S> {
234    /// Builds a context and the receiving half of its event stream.
235    ///
236    /// This is the harness for unit-testing an [`Agent`](crate::server::Agent) without
237    /// the run driver: call the agent's body, then assert on
238    /// [`EventReceiver::drain`]. Nothing emits `RUN_STARTED` here — that is the
239    /// driver's job, and skipping it lets a test exercise one method in
240    /// isolation. The ordering verifier takes the run as started.
241    pub fn new(input: RunAgentInput) -> Result<(Self, EventReceiver)> {
242        let (tx, rx) = mpsc::unbounded();
243        let mut sink = EventSink::new(
244            input.run_id.clone(),
245            tx,
246            TransformerChain::new(),
247            CancellationToken::new(),
248        );
249        // As the driver does, so an agent that answers a call from an earlier
250        // run behaves here as it will in a real one.
251        sink.seed(&input.messages);
252        sink.assume_run_started();
253        let state = decode_state(&input.state)?;
254        Ok((Self::from_parts(input, state, sink), EventReceiver::new(rx)))
255    }
256
257    /// Assembles a context from an already-decoded state.
258    ///
259    /// The run driver decodes first so that a state that does not fit `S` is
260    /// reported through the sink it still owns, as a `RUN_ERROR`.
261    pub(crate) fn from_parts(input: RunAgentInput, state: S, sink: EventSink) -> Self {
262        Self {
263            input,
264            state: RunState::new(state),
265            sink,
266            terminal: Terminal::default(),
267        }
268    }
269
270    /// The typed state, as of the last publish.
271    pub fn state(&self) -> &S {
272        self.state.get()
273    }
274
275    /// The typed state, mutably. Nothing is emitted until you call
276    /// [`publish_state`](Self::publish_state).
277    pub fn state_mut(&mut self) -> &mut S {
278        self.state.get_mut()
279    }
280
281    /// Replaces the state and publishes the change.
282    ///
283    /// The first publish of a run is a `STATE_SNAPSHOT`; later ones are a
284    /// `STATE_DELTA` unless the patch would be no smaller than the snapshot.
285    /// See [`StateManager`](crate::server::StateManager).
286    pub fn set_state(&mut self, state: &S) -> Result<()> {
287        self.state.replace(&mut self.sink, state)
288    }
289
290    /// Mutates the state in place and publishes the change.
291    ///
292    /// ```
293    /// # use ag_ui::RunAgentInput;
294    /// # use ag_ui::server::RunContext;
295    /// # use serde::{Deserialize, Serialize};
296    /// #[derive(Default, Serialize, Deserialize)]
297    /// struct Draft { revision: u32 }
298    ///
299    /// # let (mut ctx, _events) = RunContext::<Draft>::new(RunAgentInput::new("t", "r"))?;
300    /// ctx.update_state(|draft| draft.revision += 1)?;
301    /// assert_eq!(ctx.state().revision, 1);
302    /// # Ok::<(), ag_ui::server::Error>(())
303    /// ```
304    pub fn update_state(&mut self, update: impl FnOnce(&mut S)) -> Result<()> {
305        update(self.state.get_mut());
306        self.publish_state()
307    }
308
309    /// Publishes whatever [`state_mut`](Self::state_mut) left behind.
310    ///
311    /// A no-op when nothing changed since the last publish.
312    pub fn publish_state(&mut self) -> Result<()> {
313        self.state.publish(&mut self.sink)
314    }
315}
316
317impl<S> RunContext<S> {
318    /// The whole request, for anything the accessors do not cover.
319    pub fn input(&self) -> &RunAgentInput {
320        &self.input
321    }
322
323    /// The conversation this run belongs to.
324    pub fn thread_id(&self) -> &ThreadId {
325        &self.input.thread_id
326    }
327
328    /// This run's id.
329    pub fn run_id(&self) -> &RunId {
330        &self.input.run_id
331    }
332
333    /// The run that spawned this one, for nested agents.
334    pub fn parent_run_id(&self) -> Option<&RunId> {
335        self.input.parent_run_id.as_ref()
336    }
337
338    /// Conversation history, oldest first.
339    pub fn messages(&self) -> &[Message] {
340        &self.input.messages
341    }
342
343    /// What the user said last, as text.
344    ///
345    /// The turn an agent is almost always answering. Non-text parts of a
346    /// multimodal message are dropped — see
347    /// [`UserContent::to_text`](crate::message::UserContent::to_text); reach into
348    /// [`RunContext::messages`] directly if the images matter.
349    ///
350    /// `None` when the history holds no user message at all, which is distinct
351    /// from a user who sent an empty one.
352    ///
353    /// ```
354    /// # use ag_ui::{RunAgentInput, Message};
355    /// # use ag_ui::server::RunContext;
356    /// let mut input = RunAgentInput::new("thread-1", "run-1");
357    /// input.messages = vec![Message::user("msg-1", "add milk")];
358    /// let (ctx, _events) = RunContext::<()>::new(input)?;
359    ///
360    /// assert_eq!(ctx.last_user_text().as_deref(), Some("add milk"));
361    /// # Ok::<(), ag_ui::server::Error>(())
362    /// ```
363    pub fn last_user_text(&self) -> Option<String> {
364        self.input
365            .messages
366            .iter()
367            .rev()
368            .find_map(|message| match message {
369                Message::User(user) => Some(user.content.to_text()),
370                _ => None,
371            })
372    }
373
374    /// Tools the client is offering for this run.
375    pub fn tools(&self) -> &[Tool] {
376        &self.input.tools
377    }
378
379    /// One offered tool by name.
380    pub fn tool(&self, name: &str) -> Option<&Tool> {
381        self.input.tools.iter().find(|tool| tool.name == name)
382    }
383
384    /// Ambient context entries.
385    pub fn context(&self) -> &[Context] {
386        &self.input.context
387    }
388
389    /// Arbitrary passthrough properties, opaque to the protocol.
390    pub fn forwarded_props(&self) -> &Value {
391        &self.input.forwarded_props
392    }
393
394    /// Answers to the interrupts a previous run paused on.
395    ///
396    /// Empty unless this request resumes a paused run.
397    pub fn resume(&self) -> &[ResumeEntry] {
398        self.input.resume.as_deref().unwrap_or_default()
399    }
400
401    /// The answer to one interrupt, by its [`Interrupt::id`].
402    ///
403    /// [`Interrupt::id`]: crate::outcome::Interrupt::id
404    pub fn resume_for(&self, interrupt_id: &str) -> Option<&ResumeEntry> {
405        self.resume()
406            .iter()
407            .find(|entry| entry.interrupt_id == interrupt_id)
408    }
409
410    /// Whether this request resumes a paused run.
411    pub fn is_resume(&self) -> bool {
412        self.input.is_resume()
413    }
414
415    /// Whether the run has been cancelled.
416    pub fn is_cancelled(&self) -> bool {
417        self.sink.cancel_token().is_cancelled()
418    }
419
420    /// [`Error::Cancelled`] once the run is cancelled, for use with `?`.
421    pub fn check_cancelled(&self) -> Result<()> {
422        if self.is_cancelled() {
423            return Err(Error::Cancelled);
424        }
425        Ok(())
426    }
427
428    /// A handle a transport can trip on client disconnect. The same token
429    /// [`Runner::cancellation_token`](crate::server::Runner::cancellation_token)
430    /// returns.
431    pub fn cancellation_token(&self) -> CancellationToken {
432        self.sink.cancel_token().clone()
433    }
434
435    /// The old name of [`cancellation_token`](Self::cancellation_token).
436    #[deprecated(since = "0.5.0", note = "renamed to `cancellation_token`")]
437    pub fn cancel_token(&self) -> CancellationToken {
438        self.cancellation_token()
439    }
440
441    /// Resolves once the run is cancelled.
442    pub fn cancelled(&self) -> Cancelled {
443        self.sink.cancel_token().cancelled()
444    }
445
446    /// Races `future` against cancellation, returning `None` if cancellation
447    /// won.
448    ///
449    /// The way to make a long model call interruptible:
450    ///
451    /// ```
452    /// # use ag_ui::RunAgentInput;
453    /// # use ag_ui::server::{Error, RunContext};
454    /// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
455    /// # rt.block_on(async {
456    /// # let (ctx, _events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
457    /// let answer = ctx
458    ///     .until_cancelled(async { "the model's reply" })
459    ///     .await
460    ///     .ok_or(Error::Cancelled)?;
461    /// assert_eq!(answer, "the model's reply");
462    /// # Ok::<(), Error>(())
463    /// # })?;
464    /// # Ok::<(), Error>(())
465    /// ```
466    /// Deliberately not an `async fn`: that would capture `&self` in the
467    /// returned future, and a future holding a borrow of the run context is
468    /// only `Send` if the context is `Sync` — which it is not, since a
469    /// transformer only has to be `Send`.
470    pub fn until_cancelled<F: Future>(&self, future: F) -> impl Future<Output = Option<F::Output>> {
471        let cancelled = self.cancelled();
472        async move {
473            futures_util::pin_mut!(future, cancelled);
474            match select(future, cancelled).await {
475                Either::Left((output, _)) => Some(output),
476                Either::Right(((), _)) => None,
477            }
478        }
479    }
480
481    /// Emits an event as-is — the escape hatch under the typed emitters.
482    ///
483    /// Everything the handles emit goes through here, so a raw event is
484    /// transformed and verified like any other.
485    pub fn emit(&mut self, event: Event) -> Result<()> {
486        self.sink.emit(event)
487    }
488
489    /// Emits a terminator, even after cancellation. Only the scope handles
490    /// call this, to close the step or subagent they opened.
491    pub(crate) fn emit_forced(&mut self, event: Event) -> Result<()> {
492        self.sink.emit_forced(event)
493    }
494
495    /// A fresh message id, unique within the run.
496    ///
497    /// The counter skips IDs from the request history, replayed events and
498    /// IDs chosen by the agent or its transformers during this run.
499    /// Derived from the run id and a counter rather than a UUID: the protocol
500    /// asks for opaque strings, this crate takes no `uuid` dependency, and a
501    /// deterministic id makes a recorded stream diffable. Pass your own id to
502    /// [`message_with_id`](Self::message_with_id) when you need one.
503    pub fn new_message_id(&mut self) -> MessageId {
504        let number = self.sink.minted.messages.next();
505        let prefix = id_prefix(&self.input.run_id);
506        MessageId::new(format!("{prefix}{MESSAGE_ID}{number}"))
507    }
508
509    /// A fresh tool call id, unique within the run.
510    pub fn new_tool_call_id(&mut self) -> ToolCallId {
511        let number = self.sink.minted.tool_calls.next();
512        let prefix = id_prefix(&self.input.run_id);
513        ToolCallId::new(format!("{prefix}{TOOL_CALL_ID}{number}"))
514    }
515
516    /// A fresh subagent invocation id, unique within the run.
517    ///
518    /// Derived like the others, from the run id and a counter — so, like
519    /// message ids, it is unique across runs only while run ids are. A
520    /// resuming run that continues a *suspended* subagent should reuse the
521    /// suspended id instead — see [`subagent_with`](Self::subagent_with).
522    pub fn new_subagent_run_id(&mut self) -> SubagentRunId {
523        let number = self.sink.minted.subagents.next();
524        let prefix = id_prefix(&self.input.run_id);
525        SubagentRunId::new(format!("{prefix}{SUBAGENT_ID}{number}"))
526    }
527
528    /// The subagent everything emitted right now is attributed to — `None`
529    /// outside any [`subagent`](Self::subagent) scope.
530    pub fn subagent_run_id(&self) -> Option<&SubagentRunId> {
531        self.sink.attribution()
532    }
533
534    /// Replaces the attribution scope and returns the previous one. Only the
535    /// subagent handle calls this, on the way in and on the way out.
536    pub(crate) fn set_attribution(
537        &mut self,
538        attribution: Option<SubagentRunId>,
539    ) -> Option<SubagentRunId> {
540        self.sink.set_attribution(attribution)
541    }
542
543    /// Announces a subagent under a fresh id and scopes everything emitted
544    /// through the returned handle to it. Call `finish`, `fail` or `suspend`
545    /// explicitly; dropping the handle only restores the parent's attribution.
546    ///
547    /// `name` is the subagent's reusable type or name, for display; the id is
548    /// this invocation's alone. See [`SubagentHandle`].
549    pub fn subagent(&mut self, name: impl Into<String>) -> Result<SubagentHandle<'_, S>> {
550        self.subagent_events(name)
551    }
552
553    /// Opens an event scope for work executed by the application or framework.
554    ///
555    /// Announces the invocation and attributes output to it. It does not create,
556    /// schedule or execute an agent. Explicitly finish, fail or suspend the
557    /// returned handle; a dropped handle never assumes success.
558    pub fn subagent_events(&mut self, name: impl Into<String>) -> Result<SubagentHandle<'_, S>> {
559        let id = self.new_subagent_run_id();
560        self.subagent_with(SubagentStartedEvent::new(id, name))
561    }
562
563    /// The same, from an announcement you built — for a description, an
564    /// explicit id, or the agents-as-tools links.
565    ///
566    /// A `parent_subagent_run_id` left absent is filled from the enclosing
567    /// scope, so nesting needs no help. An explicit id is how a resuming run
568    /// continues a subagent that suspended: announce the id the suspended
569    /// invocation had, and a client transitions its group from waiting back
570    /// to running rather than drawing a second one.
571    ///
572    /// ```
573    /// # use ag_ui::{Event, EventType, RunAgentInput, SubagentStartedEvent};
574    /// # use ag_ui::server::RunContext;
575    /// # let (mut ctx, mut events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
576    /// let mut call = ctx.tool_call("task")?;
577    /// call.args(r#"{"brief":"find sources"}"#)?;
578    /// let (call_id, result_id) = (call.id().clone(), call.result_message_id().clone());
579    /// call.end()?;                                   // the client sees the call close…
580    ///
581    /// let announce = SubagentStartedEvent::new("researcher-7", "researcher")
582    ///     .with_parent_tool_call(call_id.clone());
583    /// let mut researcher = ctx.subagent_with(announce)?;
584    /// researcher.say("Three sources found.")?;       // …then the subagent it spawned…
585    /// researcher.finish()?;
586    ///
587    /// ctx.emit(Event::tool_call_result(result_id, call_id, "3 sources"))?;  // …then its result
588    /// let types: Vec<_> = events.drain().iter().map(Event::event_type).collect();
589    /// assert_eq!(types[3], EventType::SubagentStarted);
590    /// assert_eq!(types[7], EventType::SubagentFinished);
591    /// assert_eq!(types[8], EventType::ToolCallResult);
592    /// # Ok::<(), ag_ui::server::Error>(())
593    /// ```
594    pub fn subagent_with(
595        &mut self,
596        started: SubagentStartedEvent,
597    ) -> Result<SubagentHandle<'_, S>> {
598        SubagentHandle::start(self, started)
599    }
600
601    /// Opens an assistant message under a fresh id — `TEXT_MESSAGE_START`.
602    pub fn assistant_message(&mut self) -> Result<MessageHandle<'_, S>> {
603        self.message(TextMessageRole::Assistant)
604    }
605
606    /// Opens a message with the given role under a fresh id.
607    pub fn message(&mut self, role: TextMessageRole) -> Result<MessageHandle<'_, S>> {
608        let id = self.new_message_id();
609        self.message_with_id(id, role)
610    }
611
612    /// Opens a message under an id you choose.
613    pub fn message_with_id(
614        &mut self,
615        id: impl Into<MessageId>,
616        role: TextMessageRole,
617    ) -> Result<MessageHandle<'_, S>> {
618        // Two disjoint field borrows, not a borrow of the context: the handle
619        // reaches the state without being able to open a second block.
620        MessageHandle::start(&mut self.sink, &mut self.state, id.into(), role)
621    }
622
623    /// Emits a whole assistant message — start, content, end — and returns its
624    /// id.
625    pub fn say(&mut self, text: impl Into<String>) -> Result<MessageId> {
626        let mut message = self.message(TextMessageRole::Assistant)?;
627        message.delta(text)?;
628        let id = message.id().clone();
629        message.end()?;
630        Ok(id)
631    }
632
633    /// Opens a reasoning block under a fresh id — `REASONING_START`.
634    pub fn reasoning(&mut self) -> Result<ReasoningHandle<'_, S>> {
635        let id = self.new_message_id();
636        self.reasoning_with_id(id)
637    }
638
639    /// Opens a reasoning block under an id you choose.
640    pub fn reasoning_with_id(
641        &mut self,
642        id: impl Into<MessageId>,
643    ) -> Result<ReasoningHandle<'_, S>> {
644        ReasoningHandle::start(&mut self.sink, &mut self.state, id.into())
645    }
646
647    /// Emits a whole reasoning block in one call and returns its id.
648    pub fn think(&mut self, text: impl Into<String>) -> Result<MessageId> {
649        let mut reasoning = self.reasoning()?;
650        reasoning.delta(text)?;
651        let id = reasoning.id().clone();
652        reasoning.end()?;
653        Ok(id)
654    }
655
656    /// Opens a call to `name` under a fresh id — `TOOL_CALL_START`.
657    pub fn tool_call(&mut self, name: &str) -> Result<ToolCallHandle<'_, S>> {
658        let id = self.new_tool_call_id();
659        self.tool_call_with_id(id, name)
660    }
661
662    /// Opens a call to `name` under an id you choose.
663    pub fn tool_call_with_id(
664        &mut self,
665        id: impl Into<ToolCallId>,
666        name: &str,
667    ) -> Result<ToolCallHandle<'_, S>> {
668        self.tool_call_with(ToolCallStartEvent::new(id, name))
669    }
670
671    /// Opens a call from a `TOOL_CALL_START` you built — for
672    /// `parentMessageId`, the assistant message that requested the call.
673    ///
674    /// ```
675    /// # use ag_ui::{Event, RunAgentInput, ToolCallStartEvent};
676    /// # use ag_ui::server::RunContext;
677    /// # let (mut ctx, mut events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
678    /// let message_id = ctx.say("Let me check the forecast.")?;
679    ///
680    /// let id = ctx.new_tool_call_id();
681    /// let start = ToolCallStartEvent::new(id, "get_weather").with_parent_message_id(message_id.clone());
682    /// ctx.tool_call_with(start)?.result("21 C")?;
683    ///
684    /// let Event::ToolCallStart(start) = &events.drain()[3] else { unreachable!() };
685    /// assert_eq!(start.parent_message_id.as_ref(), Some(&message_id));
686    /// # Ok::<(), ag_ui::server::Error>(())
687    /// ```
688    pub fn tool_call_with(&mut self, start: ToolCallStartEvent) -> Result<ToolCallHandle<'_, S>> {
689        let result_message_id = self.new_message_id();
690        ToolCallHandle::start(&mut self.sink, &mut self.state, start, result_message_id)
691    }
692
693    /// Sets the run's return value: the `result` of `RUN_FINISHED`.
694    ///
695    /// The driver writes it when the run finishes, whatever the outcome. A run
696    /// that ends in `RUN_ERROR` has no result. `Value::Null` clears it.
697    pub fn set_result(&mut self, result: impl Into<Value>) {
698        let result = result.into();
699        self.terminal.result = (!result.is_null()).then_some(result);
700    }
701
702    /// Records the token usage of one model call.
703    ///
704    /// The driver sums the entries per `(provider, model)` and reports them as
705    /// `usage` on the terminal event, `RUN_FINISHED` or `RUN_ERROR`. An entry
706    /// with no counts is ignored.
707    pub fn add_usage(&mut self, usage: TokenUsage) {
708        if usage.has_counts() {
709            self.terminal.usage.push(usage);
710        }
711    }
712
713    /// Opens a named step — `STEP_STARTED`.
714    ///
715    /// The returned guard dereferences to this context, and emits
716    /// `STEP_FINISHED` when it drops.
717    pub fn step(&mut self, name: impl Into<StepName>) -> Result<StepGuard<'_, S>> {
718        StepGuard::start(self, name.into())
719    }
720
721    /// Whether a terminal event has already gone out.
722    pub(crate) fn is_terminated(&self) -> bool {
723        self.sink.is_terminated()
724    }
725
726    /// Recovers the sink so the run driver can emit the terminal event through
727    /// the same transformers and the same verifier the agent used, with what
728    /// the agent asked to have written on it.
729    pub(crate) fn into_parts(self) -> (EventSink, Terminal) {
730        (self.sink, self.terminal)
731    }
732}
733
734/// Reads `RunAgentInput::state` as `S`.
735///
736/// An absent state — JSON `null`, or the empty object clients send for "no
737/// state yet" — becomes `S::default()` rather than a deserialization error, so
738/// a stateless agent (`State = ()`) works against every client.
739pub(crate) fn decode_state<S: AgentState>(value: &Value) -> Result<S> {
740    let empty = value.is_null() || value.as_object().is_some_and(serde_json::Map::is_empty);
741    if empty {
742        return Ok(S::default());
743    }
744    Ok(serde_json::from_value(value.clone())?)
745}
746
747#[cfg(test)]
748mod tests {
749    use super::*;
750    use serde::{Deserialize, Serialize};
751    use serde_json::json;
752
753    #[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
754    struct Counter {
755        clicks: u32,
756    }
757
758    fn context<S: AgentState>(input: RunAgentInput) -> (RunContext<S>, EventReceiver) {
759        RunContext::new(input).expect("state should decode")
760    }
761
762    #[test]
763    fn ids_are_derived_from_the_run_id() {
764        let (mut ctx, _events) = context::<()>(RunAgentInput::new("t", "run-7"));
765        assert_eq!(ctx.new_message_id().as_str(), "run-7-msg-1");
766        assert_eq!(ctx.new_message_id().as_str(), "run-7-msg-2");
767        assert_eq!(ctx.new_tool_call_id().as_str(), "run-7-call-1");
768    }
769
770    #[test]
771    fn a_counter_counts_on_from_the_highest_number_noted() {
772        let mut counter = IdCounter::default();
773        assert_eq!([counter.next(), counter.next()], [1, 2]);
774
775        let mut counter = IdCounter::default();
776        for noted in [3, 1, 7] {
777            counter.note(noted);
778        }
779        assert_eq!([counter.next(), counter.next()], [8, 9]);
780    }
781
782    #[test]
783    fn a_counter_never_overflows_and_never_repeats_a_number_that_was_noted() {
784        // The largest number there is cannot be counted past. The count
785        // starts again from 1, over what is in use.
786        let mut counter = IdCounter::default();
787        for noted in [1, 2, 4, u64::MAX] {
788            counter.note(noted);
789        }
790        assert_eq!([counter.next(), counter.next(), counter.next()], [3, 5, 6]);
791
792        // One short of it: the largest number is handed out, once, and the
793        // count starts again after it.
794        let mut counter = IdCounter::default();
795        counter.note(1);
796        counter.note(u64::MAX - 1);
797        assert_eq!([counter.next(), counter.next()], [u64::MAX, 2]);
798    }
799
800    #[test]
801    fn only_an_id_of_the_shape_a_context_hands_out_is_noted() {
802        let run_id = RunId::new("run-7");
803        let mut minted = Minted::new(run_id);
804        for id in [
805            "run-7-msg-12",
806            "run-7-msg-twelve",
807            "run-7-msg-",
808            "run-7-msg-99999999999999999999",
809            "run-8-msg-40",
810            "msg-40",
811        ] {
812            let start = Event::text_message_start(id, TextMessageRole::Assistant);
813            minted.note(&start);
814        }
815        assert_eq!(minted.messages.next(), 13);
816        assert_eq!(minted.tool_calls.next(), 1);
817    }
818
819    #[test]
820    fn the_last_user_turn_is_the_one_returned_and_absence_is_not_emptiness() {
821        let (ctx, _events) = context::<()>(RunAgentInput::new("t", "r"));
822        assert_eq!(ctx.last_user_text(), None, "no user message is not \"\"");
823
824        let mut input = RunAgentInput::new("t", "r");
825        input.messages = vec![
826            Message::user("m-1", "add milk"),
827            Message::assistant("m-2", "milk it is"),
828            Message::user("m-3", "and bread"),
829        ];
830        let (ctx, _events) = context::<()>(input);
831        assert_eq!(ctx.last_user_text().as_deref(), Some("and bread"));
832    }
833
834    #[test]
835    fn an_empty_state_object_decodes_to_the_default() {
836        let mut input = RunAgentInput::new("t", "r");
837        input.state = json!({});
838        let (ctx, _events) = context::<Counter>(input);
839        assert_eq!(ctx.state(), &Counter::default());
840    }
841
842    #[test]
843    fn typed_state_comes_from_the_input() {
844        let mut input = RunAgentInput::new("t", "r");
845        input.state = json!({"clicks": 3});
846        let (ctx, _events) = context::<Counter>(input);
847        assert_eq!(ctx.state().clicks, 3);
848    }
849
850    #[test]
851    fn a_state_that_does_not_fit_is_an_error() {
852        let mut input = RunAgentInput::new("t", "r");
853        input.state = json!({"clicks": "three"});
854        let error = RunContext::<Counter>::new(input).expect_err("should not decode");
855        assert!(matches!(error, Error::Json(_)), "{error}");
856    }
857
858    #[test]
859    fn resume_entries_are_addressable_by_interrupt_id() {
860        let mut input = RunAgentInput::new("t", "r");
861        input.resume = Some(vec![ResumeEntry::resolved("i-1", json!(true))]);
862        let (ctx, _events) = context::<()>(input);
863        assert!(ctx.is_resume());
864        assert_eq!(ctx.resume().len(), 1);
865        assert!(ctx.resume_for("i-1").is_some());
866        assert!(ctx.resume_for("i-2").is_none());
867    }
868
869    #[test]
870    fn a_cancelled_run_fails_every_emit() {
871        let (mut ctx, _events) = context::<()>(RunAgentInput::new("t", "r"));
872        ctx.cancellation_token().cancel();
873        assert!(ctx.is_cancelled());
874        let error = ctx.say("too late").expect_err("emit should fail");
875        assert!(error.is_cancelled(), "{error}");
876    }
877
878    #[test]
879    fn a_dropped_receiver_disconnects_the_run() {
880        let (mut ctx, events) = context::<()>(RunAgentInput::new("t", "r"));
881        drop(events);
882        let error = ctx.say("nobody home").expect_err("emit should fail");
883        assert!(error.is_disconnected(), "{error}");
884    }
885}