use crate::{
agent::{
ToolInvocation, ToolInvocationResult, ToolInvocationSubmission,
order_tool_invocation_results,
},
errors::AgentError,
};
use merry_core::{RuntimeEvent, ToolCallBatchId};
use merry_runtime::{
AgentLoopControl, AgentLoopInput, InteractiveAgentRun as RuntimeInteractiveRun,
InteractiveInputItem as RuntimeInteractiveInputItem,
InteractiveInputSnapshot as RuntimeInteractiveInputSnapshot,
InteractiveRunEventStream as RuntimeInteractiveStream,
InteractiveRunMessage as RuntimeInteractiveMessage,
};
use std::fmt;
pub struct InteractiveRun {
inner: RuntimeInteractiveRun,
}
impl InteractiveRun {
pub(crate) fn new(inner: RuntimeInteractiveRun) -> Self {
Self { inner }
}
#[must_use]
pub fn split(self) -> (InteractiveEventStream, InteractiveInput, InteractiveControl) {
let (stream, input, control) = self.inner.split();
(InteractiveEventStream { inner: stream }, input, control)
}
}
pub struct InteractiveEventStream {
inner: RuntimeInteractiveStream,
}
impl InteractiveEventStream {
#[doc(hidden)]
pub async fn next_message(&mut self) -> Result<Option<InteractiveMessage<'_>>, AgentError> {
let message = self.inner.next_message().await.map_err(AgentError::from)?;
match message {
Some(RuntimeInteractiveMessage::Event(event)) => {
Ok(Some(InteractiveMessage::Event(Box::new(event))))
}
Some(RuntimeInteractiveMessage::ToolInvocations { batch }) => {
let invocations = batch
.calls()
.iter()
.cloned()
.map(ToolInvocation::new)
.collect();
Ok(Some(InteractiveMessage::ToolInvocations {
batch: InteractiveToolInvocationBatch {
invocations,
batch_id: batch.id().clone(),
stream: self,
resolved: false,
},
}))
}
None => Ok(None),
_ => Err(AgentError::InteractiveProtocol {
message: "runtime emitted an unsupported interactive message",
}),
}
}
pub async fn next(&mut self) -> Result<Option<RuntimeEvent>, AgentError> {
self.next_event().await
}
pub async fn next_event(&mut self) -> Result<Option<RuntimeEvent>, AgentError> {
self.inner.next_event().await.map_err(AgentError::from)
}
pub async fn wait_until_closed(&mut self) -> Result<(), AgentError> {
self.inner
.wait_until_closed()
.await
.map_err(AgentError::from)
}
pub(crate) fn request_cancel(&self) {
self.inner.request_cancel();
}
pub(crate) async fn cancel_and_wait_until_closed(&mut self) -> Result<(), AgentError> {
self.inner
.cancel_and_wait_until_closed()
.await
.map_err(AgentError::from)
}
pub(crate) async fn next_owned_message(
&mut self,
) -> Result<Option<crate::binding::OwnedAgentRunMessage>, AgentError> {
let message = self.inner.next_message().await.map_err(AgentError::from)?;
match message {
Some(RuntimeInteractiveMessage::Event(event)) => Ok(Some(
crate::binding::OwnedAgentRunMessage::Event(Box::new(event)),
)),
Some(RuntimeInteractiveMessage::ToolInvocations { batch }) => {
let Some(batch) = crate::binding::OwnedToolInvocationBatch::new(
batch.id().clone(),
batch.calls().to_vec(),
) else {
return Err(AgentError::InteractiveProtocol {
message: "runtime emitted an empty tool invocation batch",
});
};
Ok(Some(
crate::binding::OwnedAgentRunMessage::ToolInvocations { batch },
))
}
None => Ok(None),
_ => Err(AgentError::InteractiveProtocol {
message: "runtime emitted an unsupported interactive message",
}),
}
}
pub(crate) async fn submit_owned_tool_invocation_results(
&mut self,
batch_id: &ToolCallBatchId,
invocations: &[ToolInvocation],
results: Vec<ToolInvocationResult>,
) -> Result<ToolInvocationSubmission, AgentError> {
let ordered_results = order_tool_invocation_results(invocations, results)?;
let result = self
.inner
.submit_tool_invocation_outcomes(batch_id, ordered_results)
.await
.map_err(AgentError::from);
match result {
Ok(()) => Ok(ToolInvocationSubmission::Accepted),
Err(AgentError::Runtime {
source: merry_runtime::RuntimeError::BridgeToolResultRejected { .. },
}) => Ok(ToolInvocationSubmission::RejectedAndRecorded),
Err(error) => Err(error),
}
}
}
#[non_exhaustive]
pub enum InteractiveMessage<'a> {
Event(Box<RuntimeEvent>),
ToolInvocations {
batch: InteractiveToolInvocationBatch<'a>,
},
}
impl InteractiveMessage<'_> {
#[must_use]
pub fn as_event(&self) -> Option<&RuntimeEvent> {
match self {
Self::Event(event) => Some(event.as_ref()),
Self::ToolInvocations { .. } => None,
}
}
}
pub type InteractiveToolInvocation = ToolInvocation;
pub struct InteractiveToolInvocationBatch<'a> {
invocations: Vec<InteractiveToolInvocation>,
batch_id: ToolCallBatchId,
stream: &'a mut InteractiveEventStream,
resolved: bool,
}
impl InteractiveToolInvocationBatch<'_> {
#[must_use]
pub fn invocations(&self) -> &[InteractiveToolInvocation] {
&self.invocations
}
#[must_use]
pub fn len(&self) -> usize {
self.invocations.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.invocations.is_empty()
}
pub async fn submit(
&mut self,
results: Vec<ToolInvocationResult>,
) -> Result<ToolInvocationSubmission, AgentError> {
if self.resolved {
return Err(AgentError::ToolInvocationBatchResolved);
}
let ordered_results = order_tool_invocation_results(&self.invocations, results)?;
let result = self
.stream
.inner
.submit_tool_invocation_outcomes(&self.batch_id, ordered_results)
.await
.map_err(AgentError::from);
match result {
Ok(()) => {
self.resolved = true;
Ok(ToolInvocationSubmission::Accepted)
}
Err(AgentError::Runtime {
source: merry_runtime::RuntimeError::BridgeToolResultRejected { .. },
}) => {
self.resolved = true;
Ok(ToolInvocationSubmission::RejectedAndRecorded)
}
Err(error) => Err(error),
}
}
}
impl fmt::Debug for InteractiveToolInvocationBatch<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("InteractiveToolInvocationBatch")
.field("invocations", &self.invocations)
.finish()
}
}
impl Drop for InteractiveToolInvocationBatch<'_> {
fn drop(&mut self) {
if !self.resolved {
self.stream.inner.request_cancel();
}
}
}
pub type InteractiveInput = AgentLoopInput;
pub type InteractiveControl = AgentLoopControl;
pub type InteractiveInputItem = RuntimeInteractiveInputItem;
pub type InteractiveInputSnapshot = RuntimeInteractiveInputSnapshot;