pub use crate::agent::{
ToolInvocation, ToolInvocationContent, ToolInvocationContentError, ToolInvocationResult,
ToolInvocationSubmission,
};
use crate::{
AgentError, HookDecision, HookInvocation, HookInvocationId, InteractiveControl,
InteractiveEventStream, InteractiveInput, InteractiveRun, RunResult, RuntimeEvent,
agent::AgentRun,
};
use merry_core::{PendingToolCall, ToolCallBatchId};
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq)]
pub enum OwnedAgentRunMessage {
Event(Box<RuntimeEvent>),
ToolInvocations {
batch: OwnedToolInvocationBatch,
},
HookInvocation {
invocation: Box<HookInvocation>,
},
}
impl OwnedAgentRunMessage {
#[must_use]
pub fn as_event(&self) -> Option<&RuntimeEvent> {
match self {
Self::Event(event) => Some(event.as_ref()),
Self::ToolInvocations { .. } | Self::HookInvocation { .. } => None,
}
}
#[must_use]
pub fn as_tool_invocations(&self) -> Option<&OwnedToolInvocationBatch> {
match self {
Self::Event(_) | Self::HookInvocation { .. } => None,
Self::ToolInvocations { batch } => Some(batch),
}
}
#[must_use]
pub fn as_hook_invocation(&self) -> Option<&HookInvocation> {
match self {
Self::HookInvocation { invocation } => Some(invocation.as_ref()),
Self::Event(_) | Self::ToolInvocations { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnedToolInvocationBatch {
batch_id: ToolCallBatchId,
invocations: Vec<ToolInvocation>,
}
impl OwnedToolInvocationBatch {
pub(crate) fn new(batch_id: ToolCallBatchId, calls: Vec<PendingToolCall>) -> Option<Self> {
if calls.is_empty() {
return None;
}
Some(Self {
batch_id,
invocations: calls.into_iter().map(ToolInvocation::new).collect(),
})
}
#[must_use]
pub fn id(&self) -> &ToolCallBatchId {
&self.batch_id
}
#[must_use]
pub fn invocations(&self) -> &[ToolInvocation] {
&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 struct OwnedAgentRun {
inner: AgentRun,
pending_batch: Option<OwnedToolInvocationBatch>,
pending_hook: Option<HookInvocation>,
terminal_result: Option<RunResult>,
}
impl OwnedAgentRun {
pub(crate) fn new(inner: AgentRun) -> Self {
Self {
inner,
pending_batch: None,
pending_hook: None,
terminal_result: None,
}
}
pub async fn next_message(&mut self) -> Result<Option<OwnedAgentRunMessage>, AgentError> {
if self.pending_batch.is_some() {
return Err(AgentError::ToolInvocationBatchPending);
}
if self.pending_hook.is_some() {
return Err(AgentError::HookInvocationPending);
}
let message = self.inner.next_owned_message().await?;
match &message {
Some(OwnedAgentRunMessage::ToolInvocations { batch }) => {
self.pending_batch = Some(batch.clone());
}
Some(OwnedAgentRunMessage::HookInvocation { invocation }) => {
self.pending_hook = Some((**invocation).clone());
}
Some(OwnedAgentRunMessage::Event(_)) | None => {}
}
Ok(message)
}
pub async fn next(&mut self) -> Result<Option<OwnedAgentRunMessage>, AgentError> {
self.next_message().await
}
pub async fn submit_tool_invocation_results(
&mut self,
batch_id: &ToolCallBatchId,
results: Vec<ToolInvocationResult>,
) -> Result<ToolInvocationSubmission, AgentError> {
let Some(batch) = self.pending_batch.as_ref() else {
return Err(AgentError::ToolInvocationBatchNotPending);
};
let invocations = batch.invocations.clone();
let result = self
.inner
.submit_tool_invocation_results(batch_id, &invocations, results)
.await;
if result.is_ok() {
self.pending_batch = None;
}
result
}
pub async fn submit_hook_decision(
&mut self,
invocation_id: &HookInvocationId,
decision: HookDecision,
) -> Result<(), AgentError> {
if self.pending_hook.is_none() {
return Err(AgentError::HookInvocationNotPending);
}
let result = self
.inner
.submit_hook_decision(invocation_id, decision)
.await;
if result.is_ok() {
self.pending_hook = None;
}
result
}
pub async fn fail_hook_invocation(
&mut self,
invocation_id: &HookInvocationId,
message: String,
) -> Result<(), AgentError> {
if self.pending_hook.is_none() {
return Err(AgentError::HookInvocationNotPending);
}
let result = self
.inner
.fail_hook_invocation(invocation_id, message)
.await;
if result.is_ok() {
self.pending_hook = None;
}
result
}
pub async fn result(&mut self) -> Result<RunResult, AgentError> {
if let Some(result) = self.terminal_result.as_ref() {
return Ok(result.clone());
}
let result = self.inner.result().await?;
self.terminal_result = Some(result.clone());
Ok(result)
}
pub async fn cancel(&mut self) -> Result<RunResult, AgentError> {
if let Some(result) = self.terminal_result.as_ref() {
return Ok(result.clone());
}
self.pending_batch = None;
self.pending_hook = None;
let result = self.inner.cancel().await?;
self.terminal_result = Some(result.clone());
Ok(result)
}
}
impl From<AgentRun> for OwnedAgentRun {
fn from(run: AgentRun) -> Self {
run.into_owned()
}
}
pub struct OwnedInteractiveStream {
inner: InteractiveEventStream,
pending_batch: Option<OwnedToolInvocationBatch>,
pending_hook: Option<HookInvocation>,
}
impl OwnedInteractiveStream {
pub(crate) fn new(inner: InteractiveEventStream) -> Self {
Self {
inner,
pending_batch: None,
pending_hook: None,
}
}
pub async fn next_message(&mut self) -> Result<Option<OwnedAgentRunMessage>, AgentError> {
let message = self.inner.next_owned_message().await?;
match &message {
Some(OwnedAgentRunMessage::ToolInvocations { batch }) => {
self.pending_batch = Some(batch.clone());
self.pending_hook = None;
}
Some(OwnedAgentRunMessage::HookInvocation { invocation }) => {
self.pending_hook = Some((**invocation).clone());
self.pending_batch = None;
}
Some(OwnedAgentRunMessage::Event(_)) | None => {
self.pending_batch = None;
self.pending_hook = None;
}
}
Ok(message)
}
pub async fn submit_tool_invocation_results(
&mut self,
batch_id: &ToolCallBatchId,
results: Vec<ToolInvocationResult>,
) -> Result<ToolInvocationSubmission, AgentError> {
let Some(batch) = self.pending_batch.as_ref() else {
return Err(AgentError::ToolInvocationBatchNotPending);
};
let invocations = batch.invocations.clone();
let result = self
.inner
.submit_owned_tool_invocation_results(batch_id, &invocations, results)
.await;
match &result {
Ok(_) => {
self.pending_batch = None;
}
Err(AgentError::Interactive {
source:
merry_runtime::InteractiveError::NoPendingToolInvocations { .. }
| merry_runtime::InteractiveError::RunClosed { .. },
}) => {
self.pending_batch = None;
}
Err(_) => {}
}
result
}
pub async fn submit_hook_decision(
&mut self,
invocation_id: &HookInvocationId,
decision: HookDecision,
) -> Result<(), AgentError> {
if self.pending_hook.is_none() {
return Err(AgentError::HookInvocationNotPending);
}
let result = self
.inner
.submit_owned_hook_decision(invocation_id, decision)
.await;
match &result {
Ok(()) => self.pending_hook = None,
Err(AgentError::Interactive {
source:
merry_runtime::InteractiveError::NoPendingHookInvocation { .. }
| merry_runtime::InteractiveError::RunClosed { .. },
}) => self.pending_hook = None,
Err(_) => {}
}
result
}
pub async fn fail_hook_invocation(
&mut self,
invocation_id: &HookInvocationId,
message: String,
) -> Result<(), AgentError> {
if self.pending_hook.is_none() {
return Err(AgentError::HookInvocationNotPending);
}
let result = self
.inner
.fail_owned_hook_invocation(invocation_id, message)
.await;
match &result {
Ok(()) => self.pending_hook = None,
Err(AgentError::Interactive {
source:
merry_runtime::InteractiveError::NoPendingHookInvocation { .. }
| merry_runtime::InteractiveError::RunClosed { .. },
}) => self.pending_hook = None,
Err(_) => {}
}
result
}
pub fn request_cancel(&self) {
self.inner.request_cancel();
}
pub async fn cancel_and_wait_until_closed(&mut self) -> Result<(), AgentError> {
self.pending_batch = None;
self.pending_hook = None;
self.inner.cancel_and_wait_until_closed().await
}
}
pub struct OwnedInteractiveRun {
stream: OwnedInteractiveStream,
input: InteractiveInput,
control: InteractiveControl,
}
impl OwnedInteractiveRun {
pub(crate) fn new(run: InteractiveRun) -> Self {
let (stream, input, control) = run.split();
Self {
stream: OwnedInteractiveStream::new(stream),
input,
control,
}
}
#[must_use]
pub fn split(self) -> (OwnedInteractiveStream, InteractiveInput, InteractiveControl) {
(self.stream, self.input, self.control)
}
}