use std::future::Future;
use crate::{
Context, Event, Message, MessageId, ResumeEntry, RunAgentInput, RunId, StepName, SubagentRunId,
SubagentStartedEvent, TextMessageRole, ThreadId, Tool, ToolCallId,
};
use futures_channel::mpsc;
use futures_util::future::{Either, select};
use serde_json::Value;
use crate::server::agent::AgentState;
use crate::server::cancel::{CancellationToken, Cancelled};
use crate::server::emit::{
EventReceiver, EventSink, MessageHandle, ReasoningHandle, StepGuard, SubagentHandle,
ToolCallHandle,
};
use crate::server::error::{Error, Result};
use crate::server::state::RunState;
use crate::server::transform::TransformerChain;
#[derive(Debug)]
pub struct RunContext<S> {
input: RunAgentInput,
state: RunState<S>,
sink: EventSink,
next_message: u64,
next_tool_call: u64,
next_subagent: u64,
}
impl<S: AgentState> RunContext<S> {
pub fn new(input: RunAgentInput) -> Result<(Self, EventReceiver)> {
let (tx, rx) = mpsc::unbounded();
let sink = EventSink::new(tx, TransformerChain::new(), CancellationToken::new());
let state = decode_state(&input.state)?;
Ok((Self::from_parts(input, state, sink), EventReceiver::new(rx)))
}
pub(crate) fn from_parts(input: RunAgentInput, state: S, sink: EventSink) -> Self {
Self {
input,
state: RunState::new(state),
sink,
next_message: 0,
next_tool_call: 0,
next_subagent: 0,
}
}
pub fn state(&self) -> &S {
self.state.get()
}
pub fn state_mut(&mut self) -> &mut S {
self.state.get_mut()
}
pub fn set_state(&mut self, state: &S) -> Result<()> {
self.state.replace(&mut self.sink, state)
}
pub fn update_state(&mut self, update: impl FnOnce(&mut S)) -> Result<()> {
update(self.state.get_mut());
self.publish_state()
}
pub fn publish_state(&mut self) -> Result<()> {
self.state.publish(&mut self.sink)
}
}
impl<S> RunContext<S> {
pub fn input(&self) -> &RunAgentInput {
&self.input
}
pub fn thread_id(&self) -> &ThreadId {
&self.input.thread_id
}
pub fn run_id(&self) -> &RunId {
&self.input.run_id
}
pub fn parent_run_id(&self) -> Option<&RunId> {
self.input.parent_run_id.as_ref()
}
pub fn messages(&self) -> &[Message] {
&self.input.messages
}
pub fn last_user_text(&self) -> Option<String> {
self.input
.messages
.iter()
.rev()
.find_map(|message| match message {
Message::User(user) => Some(user.content.to_text()),
_ => None,
})
}
pub fn tools(&self) -> &[Tool] {
&self.input.tools
}
pub fn tool(&self, name: &str) -> Option<&Tool> {
self.input.tools.iter().find(|tool| tool.name == name)
}
pub fn context(&self) -> &[Context] {
&self.input.context
}
pub fn forwarded_props(&self) -> &Value {
&self.input.forwarded_props
}
pub fn resume(&self) -> &[ResumeEntry] {
self.input.resume.as_deref().unwrap_or_default()
}
pub fn resume_for(&self, interrupt_id: &str) -> Option<&ResumeEntry> {
self.resume()
.iter()
.find(|entry| entry.interrupt_id == interrupt_id)
}
pub fn is_resume(&self) -> bool {
self.input.is_resume()
}
pub fn is_cancelled(&self) -> bool {
self.sink.cancel_token().is_cancelled()
}
pub fn check_cancelled(&self) -> Result<()> {
if self.is_cancelled() {
return Err(Error::Cancelled);
}
Ok(())
}
pub fn cancel_token(&self) -> CancellationToken {
self.sink.cancel_token().clone()
}
pub fn cancelled(&self) -> Cancelled {
self.sink.cancel_token().cancelled()
}
pub fn until_cancelled<F: Future>(&self, future: F) -> impl Future<Output = Option<F::Output>> {
let cancelled = self.cancelled();
async move {
futures_util::pin_mut!(future, cancelled);
match select(future, cancelled).await {
Either::Left((output, _)) => Some(output),
Either::Right(((), _)) => None,
}
}
}
pub fn emit(&mut self, event: Event) -> Result<()> {
self.sink.emit(event)
}
pub fn new_message_id(&mut self) -> MessageId {
self.next_message += 1;
MessageId::new(format!("{}-msg-{}", self.id_prefix(), self.next_message))
}
pub fn new_tool_call_id(&mut self) -> ToolCallId {
self.next_tool_call += 1;
ToolCallId::new(format!("{}-call-{}", self.id_prefix(), self.next_tool_call))
}
pub fn new_subagent_run_id(&mut self) -> SubagentRunId {
self.next_subagent += 1;
SubagentRunId::new(format!("{}-sub-{}", self.id_prefix(), self.next_subagent))
}
pub fn subagent_run_id(&self) -> Option<&SubagentRunId> {
self.sink.attribution()
}
pub(crate) fn set_attribution(
&mut self,
attribution: Option<SubagentRunId>,
) -> Option<SubagentRunId> {
self.sink.set_attribution(attribution)
}
pub fn subagent(&mut self, name: impl Into<String>) -> Result<SubagentHandle<'_, S>> {
self.subagent_events(name)
}
pub fn subagent_events(&mut self, name: impl Into<String>) -> Result<SubagentHandle<'_, S>> {
let id = self.new_subagent_run_id();
self.subagent_with(SubagentStartedEvent::new(id, name))
}
pub fn subagent_with(
&mut self,
started: SubagentStartedEvent,
) -> Result<SubagentHandle<'_, S>> {
SubagentHandle::start(self, started)
}
fn id_prefix(&self) -> &str {
if self.input.run_id.is_empty() {
"run"
} else {
self.input.run_id.as_str()
}
}
pub fn assistant_message(&mut self) -> Result<MessageHandle<'_, S>> {
self.message(TextMessageRole::Assistant)
}
pub fn message(&mut self, role: TextMessageRole) -> Result<MessageHandle<'_, S>> {
let id = self.new_message_id();
self.message_with_id(id, role)
}
pub fn message_with_id(
&mut self,
id: impl Into<MessageId>,
role: TextMessageRole,
) -> Result<MessageHandle<'_, S>> {
MessageHandle::start(&mut self.sink, &mut self.state, id.into(), role)
}
pub fn say(&mut self, text: impl Into<String>) -> Result<MessageId> {
let mut message = self.message(TextMessageRole::Assistant)?;
message.delta(text)?;
let id = message.id().clone();
message.end()?;
Ok(id)
}
pub fn reasoning(&mut self) -> Result<ReasoningHandle<'_, S>> {
let id = self.new_message_id();
self.reasoning_with_id(id)
}
pub fn reasoning_with_id(
&mut self,
id: impl Into<MessageId>,
) -> Result<ReasoningHandle<'_, S>> {
ReasoningHandle::start(&mut self.sink, &mut self.state, id.into())
}
pub fn think(&mut self, text: impl Into<String>) -> Result<MessageId> {
let mut reasoning = self.reasoning()?;
reasoning.delta(text)?;
let id = reasoning.id().clone();
reasoning.end()?;
Ok(id)
}
pub fn tool_call(&mut self, name: &str) -> Result<ToolCallHandle<'_, S>> {
let id = self.new_tool_call_id();
self.tool_call_with_id(id, name)
}
pub fn tool_call_with_id(
&mut self,
id: impl Into<ToolCallId>,
name: &str,
) -> Result<ToolCallHandle<'_, S>> {
let id = id.into();
let result_message_id = self.new_message_id();
ToolCallHandle::start(
&mut self.sink,
&mut self.state,
id,
name,
None,
result_message_id,
)
}
pub fn step(&mut self, name: impl Into<StepName>) -> Result<StepGuard<'_, S>> {
StepGuard::start(self, name.into())
}
pub(crate) fn is_terminated(&self) -> bool {
self.sink.is_terminated()
}
pub(crate) fn into_sink(self) -> EventSink {
self.sink
}
}
pub(crate) fn decode_state<S: AgentState>(value: &Value) -> Result<S> {
let empty = value.is_null() || value.as_object().is_some_and(serde_json::Map::is_empty);
if empty {
return Ok(S::default());
}
Ok(serde_json::from_value(value.clone())?)
}
#[cfg(test)]
mod tests {
use super::*;
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
struct Counter {
clicks: u32,
}
fn context<S: AgentState>(input: RunAgentInput) -> (RunContext<S>, EventReceiver) {
RunContext::new(input).expect("state should decode")
}
#[test]
fn ids_are_derived_from_the_run_id() {
let (mut ctx, _events) = context::<()>(RunAgentInput::new("t", "run-7"));
assert_eq!(ctx.new_message_id().as_str(), "run-7-msg-1");
assert_eq!(ctx.new_message_id().as_str(), "run-7-msg-2");
assert_eq!(ctx.new_tool_call_id().as_str(), "run-7-call-1");
}
#[test]
fn the_last_user_turn_is_the_one_returned_and_absence_is_not_emptiness() {
let (ctx, _events) = context::<()>(RunAgentInput::new("t", "r"));
assert_eq!(ctx.last_user_text(), None, "no user message is not \"\"");
let mut input = RunAgentInput::new("t", "r");
input.messages = vec![
Message::user("m-1", "add milk"),
Message::assistant("m-2", "milk it is"),
Message::user("m-3", "and bread"),
];
let (ctx, _events) = context::<()>(input);
assert_eq!(ctx.last_user_text().as_deref(), Some("and bread"));
}
#[test]
fn an_empty_state_object_decodes_to_the_default() {
let mut input = RunAgentInput::new("t", "r");
input.state = json!({});
let (ctx, _events) = context::<Counter>(input);
assert_eq!(ctx.state(), &Counter::default());
}
#[test]
fn typed_state_comes_from_the_input() {
let mut input = RunAgentInput::new("t", "r");
input.state = json!({"clicks": 3});
let (ctx, _events) = context::<Counter>(input);
assert_eq!(ctx.state().clicks, 3);
}
#[test]
fn a_state_that_does_not_fit_is_an_error() {
let mut input = RunAgentInput::new("t", "r");
input.state = json!({"clicks": "three"});
let error = RunContext::<Counter>::new(input).expect_err("should not decode");
assert!(matches!(error, Error::Json(_)), "{error}");
}
#[test]
fn resume_entries_are_addressable_by_interrupt_id() {
let mut input = RunAgentInput::new("t", "r");
input.resume = Some(vec![ResumeEntry::resolved("i-1", json!(true))]);
let (ctx, _events) = context::<()>(input);
assert!(ctx.is_resume());
assert_eq!(ctx.resume().len(), 1);
assert!(ctx.resume_for("i-1").is_some());
assert!(ctx.resume_for("i-2").is_none());
}
#[test]
fn a_cancelled_run_fails_every_emit() {
let (mut ctx, _events) = context::<()>(RunAgentInput::new("t", "r"));
ctx.cancel_token().cancel();
assert!(ctx.is_cancelled());
let error = ctx.say("too late").expect_err("emit should fail");
assert!(error.is_cancelled(), "{error}");
}
#[test]
fn a_dropped_receiver_disconnects_the_run() {
let (mut ctx, events) = context::<()>(RunAgentInput::new("t", "r"));
drop(events);
let error = ctx.say("nobody home").expect_err("emit should fail");
assert!(error.is_disconnected(), "{error}");
}
}