1use super::commands::InteractiveCommand;
2use super::{
3 InteractiveError, InteractiveRunId, InteractiveSettingsUpdate, InterruptReason, QueuedInputId,
4 types::{InputRecord, InputRecords},
5};
6use crate::bridge::BridgeToolResultCommand;
7use crate::{CompactionOutcome, FileSessionStore, UserMessageInput};
8use merry_core::{PendingToolCallBatch, PlanId, RuntimeEvent, ToolCallBatchId, ToolCallId};
9use std::sync::{
10 Arc,
11 atomic::{AtomicU64, Ordering},
12};
13use tokio::{
14 sync::{mpsc, oneshot, watch},
15 task::JoinHandle,
16};
17use tokio_stream::wrappers::ReceiverStream;
18use tokio_util::sync::CancellationToken;
19
20pub use crate::agent_loop::AgentRunMessage as InteractiveRunMessage;
22
23pub struct InteractiveRunEventStream {
31 inner: Option<ReceiverStream<InteractiveRunMessage>>,
32 inner_closed: bool,
33 rate_updates: watch::Receiver<Option<RuntimeEvent>>,
34 rate_updates_closed: bool,
35 cancellation_token: CancellationToken,
36 producer_handle: Option<JoinHandle<Result<(), InteractiveError>>>,
37 bridge_sender: mpsc::Sender<BridgeToolResultCommand>,
38 run_id: InteractiveRunId,
39 pending_tool_invocations: Option<PendingToolCallBatch>,
40 unread_message: Option<InteractiveRunMessage>,
41 bridge_resolution_epoch: Arc<AtomicU64>,
42 observed_bridge_resolution_epoch: u64,
43 closed_event_observed: bool,
44}
45
46impl InteractiveRunEventStream {
47 pub(super) fn new(
48 run_id: InteractiveRunId,
49 inner: ReceiverStream<InteractiveRunMessage>,
50 rate_updates: watch::Receiver<Option<RuntimeEvent>>,
51 cancellation_token: CancellationToken,
52 producer_handle: JoinHandle<Result<(), InteractiveError>>,
53 bridge_sender: mpsc::Sender<BridgeToolResultCommand>,
54 bridge_resolution_epoch: Arc<AtomicU64>,
55 ) -> Self {
56 let observed_bridge_resolution_epoch = bridge_resolution_epoch.load(Ordering::Acquire);
57 Self {
58 inner: Some(inner),
59 inner_closed: false,
60 rate_updates,
61 rate_updates_closed: false,
62 cancellation_token,
63 producer_handle: Some(producer_handle),
64 bridge_sender,
65 run_id,
66 pending_tool_invocations: None,
67 unread_message: None,
68 bridge_resolution_epoch,
69 observed_bridge_resolution_epoch,
70 closed_event_observed: false,
71 }
72 }
73
74 fn synchronize_bridge_resolution(&mut self) {
75 let epoch = self.bridge_resolution_epoch.load(Ordering::Acquire);
76 if epoch != self.observed_bridge_resolution_epoch {
77 self.pending_tool_invocations = None;
78 self.unread_message = None;
79 self.observed_bridge_resolution_epoch = epoch;
80 }
81 }
82
83 pub async fn next_message(
89 &mut self,
90 ) -> Result<Option<InteractiveRunMessage>, InteractiveError> {
91 self.synchronize_bridge_resolution();
92 if self.pending_tool_invocations.is_some() {
93 return Err(InteractiveError::ToolInvocationsPending {
94 run_id: self.run_id,
95 });
96 }
97
98 let message = self.receive_message().await;
99 let Some(message) = message else {
100 self.finish_after_eof().await?;
101 return Ok(None);
102 };
103
104 self.observe_terminal_message(&message);
105 self.mark_pending_tool_invocations(&message)?;
106 Ok(Some(message))
107 }
108
109 async fn receive_message(&mut self) -> Option<InteractiveRunMessage> {
110 if let Some(message) = self.unread_message.take() {
111 return Some(message);
112 }
113 use futures_util::StreamExt;
114 loop {
115 if self.inner_closed && self.rate_updates_closed {
116 return None;
117 }
118 if self.inner_closed {
119 match self.rate_updates.changed().await {
120 Ok(()) => {
121 if let Some(event) = self.rate_updates.borrow_and_update().clone() {
122 return Some(InteractiveRunMessage::Event(event));
123 }
124 }
125 Err(_) => self.rate_updates_closed = true,
126 }
127 continue;
128 }
129 let Some(inner) = self.inner.as_mut() else {
130 self.inner_closed = true;
131 continue;
132 };
133 if self.rate_updates_closed {
134 let message = inner.next().await;
135 if message.is_none() {
136 self.inner_closed = true;
137 }
138 return message;
139 }
140 tokio::select! {
141 biased;
142 message = inner.next() => {
143 if message.is_none() {
144 self.inner_closed = true;
145 }
146 return message;
147 }
148 changed = self.rate_updates.changed() => {
149 match changed {
150 Ok(()) => {
151 if let Some(event) = self.rate_updates.borrow_and_update().clone() {
152 return Some(InteractiveRunMessage::Event(event));
153 }
154 }
155 Err(_) => self.rate_updates_closed = true,
156 }
157 }
158 }
159 }
160 }
161
162 fn observe_terminal_message(&mut self, message: &InteractiveRunMessage) {
163 if matches!(message, InteractiveRunMessage::Event(RuntimeEvent::Closed)) {
164 self.closed_event_observed = true;
165 }
166 }
167
168 async fn finish_producer(&mut self) -> Result<(), InteractiveError> {
169 let Some(handle) = self.producer_handle.take() else {
170 return Ok(());
171 };
172 match handle.await {
173 Ok(result) => result,
174 Err(_) => Err(InteractiveError::ProducerTaskFailed {
175 run_id: self.run_id,
176 }),
177 }
178 }
179
180 async fn finish_after_eof(&mut self) -> Result<(), InteractiveError> {
181 self.finish_producer().await?;
182 if self.closed_event_observed {
183 Ok(())
184 } else {
185 Err(InteractiveError::ProducerStopped {
186 run_id: self.run_id,
187 message: "output channel closed unexpectedly",
188 })
189 }
190 }
191
192 fn mark_pending_tool_invocations(
193 &mut self,
194 message: &InteractiveRunMessage,
195 ) -> Result<(), InteractiveError> {
196 let InteractiveRunMessage::ToolInvocations { batch } = message else {
197 return Ok(());
198 };
199 if batch.calls().is_empty() {
200 return Err(InteractiveError::InvalidToolInvocationBatch {
201 run_id: self.run_id,
202 });
203 }
204 self.pending_tool_invocations = Some(batch.clone());
205 Ok(())
206 }
207
208 pub async fn next_event(&mut self) -> Result<Option<RuntimeEvent>, InteractiveError> {
215 self.synchronize_bridge_resolution();
216 if self.pending_tool_invocations.is_some() {
217 return Err(InteractiveError::ToolInvocationsPending {
218 run_id: self.run_id,
219 });
220 }
221 let Some(message) = self.receive_message().await else {
222 self.finish_after_eof().await?;
223 return Ok(None);
224 };
225 match message {
226 InteractiveRunMessage::Event(event) => {
227 if matches!(event, RuntimeEvent::Closed) {
228 self.closed_event_observed = true;
229 }
230 Ok(Some(event))
231 }
232 InteractiveRunMessage::ToolInvocations { batch } => {
233 let count = batch.calls().len();
234 self.unread_message = Some(InteractiveRunMessage::ToolInvocations { batch });
235 Err(InteractiveError::ToolInvocationsRequireMessageProtocol {
236 run_id: self.run_id,
237 count,
238 })
239 }
240 }
241 }
242
243 pub async fn submit_tool_invocation_outcomes(
251 &mut self,
252 batch_id: &ToolCallBatchId,
253 outcomes: Vec<(ToolCallId, crate::ToolExecutionOutcome)>,
254 ) -> Result<(), InteractiveError> {
255 if self.pending_tool_invocations.is_none() {
256 return Err(InteractiveError::NoPendingToolInvocations {
257 run_id: self.run_id,
258 });
259 }
260 if outcomes.is_empty() {
261 return Err(InteractiveError::InvalidToolInvocationBatch {
262 run_id: self.run_id,
263 });
264 }
265 let (ack_sender, ack_receiver) = oneshot::channel();
266 self.bridge_sender
267 .send(BridgeToolResultCommand::outcomes(
268 batch_id.clone(),
269 outcomes,
270 ack_sender,
271 ))
272 .await
273 .map_err(|_| InteractiveError::RunClosed {
274 run_id: self.run_id,
275 })?;
276 let result = ack_receiver
277 .await
278 .map_err(|_| InteractiveError::RunClosed {
279 run_id: self.run_id,
280 })?;
281 if result.is_ok() {
282 self.pending_tool_invocations = None;
283 } else if let Err(error) = result {
284 if !error.is_retryable_bridge_tool_result() {
285 self.pending_tool_invocations = None;
286 }
287 return Err(InteractiveError::Runtime { source: error });
288 }
289 Ok(())
290 }
291
292 pub fn request_cancel(&self) {
297 self.cancellation_token.cancel();
298 }
299
300 pub async fn wait_until_closed(&mut self) -> Result<(), InteractiveError> {
308 while let Some(event) = self.next_event().await? {
309 if matches!(event, RuntimeEvent::Closed) {
310 break;
311 }
312 }
313 self.inner.take();
314 self.finish_producer().await
315 }
316
317 pub async fn cancel_and_wait_until_closed(&mut self) -> Result<(), InteractiveError> {
320 self.cancellation_token.cancel();
321 self.pending_tool_invocations = None;
322 self.unread_message = None;
323 while let Some(message) = self.receive_message().await {
324 self.observe_terminal_message(&message);
325 if self.closed_event_observed {
326 break;
327 }
328 }
329 self.inner.take();
330 self.finish_producer().await
331 }
332}
333
334impl Drop for InteractiveRunEventStream {
335 fn drop(&mut self) {
336 self.inner.take();
337 self.cancellation_token.cancel();
338
339 if let Some(handle) = self.producer_handle.take() {
340 handle.abort();
341 }
342 }
343}
344
345pub struct InteractiveAgentRun {
346 stream: InteractiveRunEventStream,
347 input: AgentLoopInput,
348 control: AgentLoopControl,
349}
350
351impl InteractiveAgentRun {
352 pub(super) fn new(
353 stream: InteractiveRunEventStream,
354 input: AgentLoopInput,
355 control: AgentLoopControl,
356 ) -> Self {
357 Self {
358 stream,
359 input,
360 control,
361 }
362 }
363
364 #[must_use]
365 pub fn split(self) -> (InteractiveRunEventStream, AgentLoopInput, AgentLoopControl) {
366 (self.stream, self.input, self.control)
367 }
368}
369
370#[derive(Clone)]
371pub struct AgentLoopInput {
372 run_id: InteractiveRunId,
373 command_sender: mpsc::Sender<InteractiveCommand>,
374}
375
376impl AgentLoopInput {
377 pub(super) fn new(
378 run_id: InteractiveRunId,
379 command_sender: mpsc::Sender<InteractiveCommand>,
380 ) -> Self {
381 Self {
382 run_id,
383 command_sender,
384 }
385 }
386
387 #[must_use]
388 pub fn run_id(&self) -> InteractiveRunId {
389 self.run_id
390 }
391
392 pub async fn submit(&self, text: &str) -> Result<InteractiveInputItem, InteractiveError> {
394 let message = UserMessageInput::text_only(text)?;
395 self.submit_message(message).await
396 }
397
398 pub async fn submit_message(
400 &self,
401 message: UserMessageInput,
402 ) -> Result<InteractiveInputItem, InteractiveError> {
403 let text = message.text().to_owned();
404 let (ack_sender, ack_receiver) = oneshot::channel();
405 self.command_sender
406 .send(InteractiveCommand::Submit {
407 message,
408 ack_sender,
409 })
410 .await
411 .map_err(|_| InteractiveError::CommandChannelClosed {
412 run_id: self.run_id,
413 })?;
414 ack_receiver
415 .await
416 .map_err(|_| InteractiveError::CommandChannelClosed {
417 run_id: self.run_id,
418 })?
419 .map(|id| InteractiveInputItem::new(self.clone(), id, text))
420 }
421
422 pub async fn update_by_id(
424 &self,
425 id: QueuedInputId,
426 text: &str,
427 ) -> Result<(), InteractiveError> {
428 let (ack_sender, ack_receiver) = oneshot::channel();
429 self.command_sender
430 .send(InteractiveCommand::Update {
431 id,
432 text: text.to_owned(),
433 ack_sender,
434 })
435 .await
436 .map_err(|_| InteractiveError::CommandChannelClosed {
437 run_id: self.run_id,
438 })?;
439 ack_receiver
440 .await
441 .map_err(|_| InteractiveError::CommandChannelClosed {
442 run_id: self.run_id,
443 })?
444 }
445
446 pub async fn remove_by_id(&self, id: QueuedInputId) -> Result<(), InteractiveError> {
448 let (ack_sender, ack_receiver) = oneshot::channel();
449 self.command_sender
450 .send(InteractiveCommand::Remove { id, ack_sender })
451 .await
452 .map_err(|_| InteractiveError::CommandChannelClosed {
453 run_id: self.run_id,
454 })?;
455 ack_receiver
456 .await
457 .map_err(|_| InteractiveError::CommandChannelClosed {
458 run_id: self.run_id,
459 })?
460 }
461
462 pub async fn set_paused(&self, paused: bool) -> Result<(), InteractiveError> {
468 let (ack_sender, ack_receiver) = oneshot::channel();
469 self.command_sender
470 .send(InteractiveCommand::SetPendingPaused { paused, ack_sender })
471 .await
472 .map_err(|_| InteractiveError::CommandChannelClosed {
473 run_id: self.run_id,
474 })?;
475 ack_receiver
476 .await
477 .map_err(|_| InteractiveError::CommandChannelClosed {
478 run_id: self.run_id,
479 })?
480 }
481
482 pub async fn flush(&self) -> Result<(), InteractiveError> {
484 let (ack_sender, ack_receiver) = oneshot::channel();
485 self.command_sender
486 .send(InteractiveCommand::FlushPending { ack_sender })
487 .await
488 .map_err(|_| InteractiveError::CommandChannelClosed {
489 run_id: self.run_id,
490 })?;
491 ack_receiver
492 .await
493 .map_err(|_| InteractiveError::CommandChannelClosed {
494 run_id: self.run_id,
495 })?
496 }
497
498 pub async fn replace_pending_order(
499 &self,
500 items: &[InteractiveInputItem],
501 ) -> Result<(), InteractiveError> {
502 if items.iter().any(|item| item.input.run_id != self.run_id) {
503 return Err(InteractiveError::InvalidPendingOrder {
504 reason: "input item belongs to another interactive run",
505 });
506 }
507 let ids = items.iter().map(|item| item.id).collect::<Vec<_>>();
508 let (ack_sender, ack_receiver) = oneshot::channel();
509 self.command_sender
510 .send(InteractiveCommand::ReplacePendingOrder { ids, ack_sender })
511 .await
512 .map_err(|_| InteractiveError::CommandChannelClosed {
513 run_id: self.run_id,
514 })?;
515 ack_receiver
516 .await
517 .map_err(|_| InteractiveError::CommandChannelClosed {
518 run_id: self.run_id,
519 })?
520 }
521
522 pub async fn snapshot(&self) -> Result<InteractiveInputSnapshot, InteractiveError> {
523 let (ack_sender, ack_receiver) = oneshot::channel();
524 self.command_sender
525 .send(InteractiveCommand::Snapshot { ack_sender })
526 .await
527 .map_err(|_| InteractiveError::CommandChannelClosed {
528 run_id: self.run_id,
529 })?;
530 let records = ack_receiver
531 .await
532 .map_err(|_| InteractiveError::CommandChannelClosed {
533 run_id: self.run_id,
534 })?;
535 Ok(InteractiveInputSnapshot::from_records(
536 self.clone(),
537 records,
538 ))
539 }
540}
541
542#[derive(Clone)]
543pub struct InteractiveInputItem {
544 input: AgentLoopInput,
545 id: QueuedInputId,
546 text: String,
547}
548
549impl InteractiveInputItem {
550 fn new(input: AgentLoopInput, id: QueuedInputId, text: String) -> Self {
551 Self { input, id, text }
552 }
553
554 #[must_use]
555 pub fn id(&self) -> QueuedInputId {
556 self.id
557 }
558
559 #[must_use]
560 pub fn text(&self) -> &str {
561 self.text.as_str()
562 }
563
564 pub async fn update(&mut self, text: impl Into<String>) -> Result<(), InteractiveError> {
565 let text = text.into();
566 self.input.update_by_id(self.id, &text).await?;
567 self.text = text;
568 Ok(())
569 }
570
571 pub async fn remove(self) -> Result<(), InteractiveError> {
572 self.input.remove_by_id(self.id).await
573 }
574}
575
576#[derive(Clone)]
577pub struct InteractiveInputSnapshot {
578 pub items: Vec<InteractiveInputItem>,
579 pub paused: bool,
580}
581
582impl InteractiveInputSnapshot {
583 fn from_records(input: AgentLoopInput, records: InputRecords) -> Self {
584 Self {
585 items: records_to_items(input, records.items),
586 paused: records.paused,
587 }
588 }
589}
590
591fn records_to_items(input: AgentLoopInput, records: Vec<InputRecord>) -> Vec<InteractiveInputItem> {
592 records
593 .into_iter()
594 .map(|record| InteractiveInputItem::new(input.clone(), record.id, record.text))
595 .collect()
596}
597
598#[derive(Clone)]
599pub struct AgentLoopControl {
600 run_id: InteractiveRunId,
601 command_sender: mpsc::Sender<InteractiveCommand>,
602}
603
604impl AgentLoopControl {
605 pub(super) fn new(
606 run_id: InteractiveRunId,
607 command_sender: mpsc::Sender<InteractiveCommand>,
608 ) -> Self {
609 Self {
610 run_id,
611 command_sender,
612 }
613 }
614
615 #[must_use]
616 pub fn run_id(&self) -> InteractiveRunId {
617 self.run_id
618 }
619
620 pub async fn update_settings(
621 &self,
622 update: InteractiveSettingsUpdate,
623 ) -> Result<(), InteractiveError> {
624 let (ack_sender, ack_receiver) = oneshot::channel();
625 self.command_sender
626 .send(InteractiveCommand::UpdateSettings {
627 update: Box::new(update),
628 ack_sender,
629 })
630 .await
631 .map_err(|_| InteractiveError::CommandChannelClosed {
632 run_id: self.run_id,
633 })?;
634 ack_receiver
635 .await
636 .map_err(|_| InteractiveError::CommandChannelClosed {
637 run_id: self.run_id,
638 })?
639 }
640
641 pub async fn interrupt(&self, reason: InterruptReason) -> Result<(), InteractiveError> {
642 let (ack_sender, ack_receiver) = oneshot::channel();
643 self.command_sender
644 .send(InteractiveCommand::Interrupt { reason, ack_sender })
645 .await
646 .map_err(|_| InteractiveError::CommandChannelClosed {
647 run_id: self.run_id,
648 })?;
649 ack_receiver
650 .await
651 .map_err(|_| InteractiveError::CommandChannelClosed {
652 run_id: self.run_id,
653 })?
654 }
655
656 pub async fn save_session_to(&self, store: FileSessionStore) -> Result<(), InteractiveError> {
661 let (ack_sender, ack_receiver) = oneshot::channel();
662 self.command_sender
663 .send(InteractiveCommand::SaveSession { store, ack_sender })
664 .await
665 .map_err(|_| InteractiveError::CommandChannelClosed {
666 run_id: self.run_id,
667 })?;
668 ack_receiver
669 .await
670 .map_err(|_| InteractiveError::CommandChannelClosed {
671 run_id: self.run_id,
672 })?
673 }
674
675 pub async fn compact_context(
682 &self,
683 focus: Option<String>,
684 ) -> Result<Option<CompactionOutcome>, InteractiveError> {
685 let (ack_sender, ack_receiver) = oneshot::channel();
686 self.command_sender
687 .send(InteractiveCommand::CompactContext { focus, ack_sender })
688 .await
689 .map_err(|_| InteractiveError::CommandChannelClosed {
690 run_id: self.run_id,
691 })?;
692 ack_receiver
693 .await
694 .map_err(|_| InteractiveError::CommandChannelClosed {
695 run_id: self.run_id,
696 })?
697 }
698
699 pub async fn set_plan_mode(&self, enabled: bool) -> Result<(), InteractiveError> {
701 let (ack_sender, ack_receiver) = oneshot::channel();
702 self.command_sender
703 .send(InteractiveCommand::SetPlanMode {
704 enabled,
705 ack_sender,
706 })
707 .await
708 .map_err(|_| InteractiveError::CommandChannelClosed {
709 run_id: self.run_id,
710 })?;
711 ack_receiver
712 .await
713 .map_err(|_| InteractiveError::CommandChannelClosed {
714 run_id: self.run_id,
715 })?
716 }
717
718 pub async fn approve_plan(
720 &self,
721 plan_id: PlanId,
722 note: Option<String>,
723 ) -> Result<(), InteractiveError> {
724 let (ack_sender, ack_receiver) = oneshot::channel();
725 self.command_sender
726 .send(InteractiveCommand::ApprovePlan {
727 plan_id,
728 note,
729 ack_sender,
730 })
731 .await
732 .map_err(|_| InteractiveError::CommandChannelClosed {
733 run_id: self.run_id,
734 })?;
735 ack_receiver
736 .await
737 .map_err(|_| InteractiveError::CommandChannelClosed {
738 run_id: self.run_id,
739 })?
740 }
741
742 pub async fn request_plan_changes(
744 &self,
745 plan_id: PlanId,
746 feedback: String,
747 ) -> Result<(), InteractiveError> {
748 let (ack_sender, ack_receiver) = oneshot::channel();
749 self.command_sender
750 .send(InteractiveCommand::RequestPlanChanges {
751 plan_id,
752 feedback,
753 ack_sender,
754 })
755 .await
756 .map_err(|_| InteractiveError::CommandChannelClosed {
757 run_id: self.run_id,
758 })?;
759 ack_receiver
760 .await
761 .map_err(|_| InteractiveError::CommandChannelClosed {
762 run_id: self.run_id,
763 })?
764 }
765
766 pub async fn abandon_plan(&self, plan_id: PlanId) -> Result<(), InteractiveError> {
768 let (ack_sender, ack_receiver) = oneshot::channel();
769 self.command_sender
770 .send(InteractiveCommand::AbandonPlan {
771 plan_id,
772 ack_sender,
773 })
774 .await
775 .map_err(|_| InteractiveError::CommandChannelClosed {
776 run_id: self.run_id,
777 })?;
778 ack_receiver
779 .await
780 .map_err(|_| InteractiveError::CommandChannelClosed {
781 run_id: self.run_id,
782 })?
783 }
784
785 pub async fn close(&self) -> Result<(), InteractiveError> {
786 let (ack_sender, ack_receiver) = oneshot::channel();
787 self.command_sender
788 .send(InteractiveCommand::Close { ack_sender })
789 .await
790 .map_err(|_| InteractiveError::CommandChannelClosed {
791 run_id: self.run_id,
792 })?;
793 ack_receiver
794 .await
795 .map_err(|_| InteractiveError::CommandChannelClosed {
796 run_id: self.run_id,
797 })?
798 }
799}