Skip to main content

merry_runtime/interactive/
handles.rs

1use super::commands::InteractiveCommand;
2use super::{
3    InteractiveError, InteractiveRunId, InteractiveSettingsUpdate, InterruptReason, QueuedInputId,
4    types::{InputRecord, InputRecords},
5};
6use crate::bridge::BridgeToolResultCommand;
7use crate::hooks::bridge::HookDecisionCommand;
8use crate::{
9    CitationCompactionPolicy, CompactionOutcome, FileSessionStore, HookDecision, HookInvocation,
10    HookInvocationId, UserMessageInput,
11};
12use merry_core::{PendingToolCallBatch, PlanId, RuntimeEvent, ToolCallBatchId, ToolCallId};
13use std::sync::{
14    Arc,
15    atomic::{AtomicU64, Ordering},
16};
17use tokio::{
18    sync::{mpsc, oneshot, watch},
19    task::JoinHandle,
20};
21use tokio_stream::wrappers::ReceiverStream;
22use tokio_util::sync::CancellationToken;
23
24/// Runtime message contract shared by interactive and non-interactive runs.
25pub use crate::agent_loop::AgentRunMessage as InteractiveRunMessage;
26
27/// Single-consumer output stream for one interactive run.
28///
29/// This stream intentionally does not implement `futures::Stream`: a host
30/// handoff is a protocol phase, not an ordinary event. Callers use
31/// [`Self::next_message`] and must submit the complete batch before reading the
32/// next message. This contract is shared by Rust and future foreign-language
33/// bindings.
34pub struct InteractiveRunEventStream {
35    inner: Option<ReceiverStream<InteractiveRunMessage>>,
36    inner_closed: bool,
37    rate_updates: watch::Receiver<Option<RuntimeEvent>>,
38    rate_updates_closed: bool,
39    cancellation_token: CancellationToken,
40    producer_handle: Option<JoinHandle<Result<(), InteractiveError>>>,
41    bridge_sender: mpsc::Sender<BridgeToolResultCommand>,
42    run_id: InteractiveRunId,
43    pending_tool_invocations: Option<PendingToolCallBatch>,
44    unread_message: Option<InteractiveRunMessage>,
45    bridge_resolution_epoch: Arc<AtomicU64>,
46    observed_bridge_resolution_epoch: u64,
47    hook_sender: mpsc::Sender<HookDecisionCommand>,
48    pending_hook_invocation: Option<HookInvocation>,
49    hook_resolution_epoch: Arc<AtomicU64>,
50    observed_hook_resolution_epoch: u64,
51    closed_event_observed: bool,
52}
53
54impl InteractiveRunEventStream {
55    #[allow(clippy::too_many_arguments)]
56    pub(super) fn new(
57        run_id: InteractiveRunId,
58        inner: ReceiverStream<InteractiveRunMessage>,
59        rate_updates: watch::Receiver<Option<RuntimeEvent>>,
60        cancellation_token: CancellationToken,
61        producer_handle: JoinHandle<Result<(), InteractiveError>>,
62        bridge_sender: mpsc::Sender<BridgeToolResultCommand>,
63        bridge_resolution_epoch: Arc<AtomicU64>,
64        hook_sender: mpsc::Sender<HookDecisionCommand>,
65        hook_resolution_epoch: Arc<AtomicU64>,
66    ) -> Self {
67        let observed_bridge_resolution_epoch = bridge_resolution_epoch.load(Ordering::Acquire);
68        let observed_hook_resolution_epoch = hook_resolution_epoch.load(Ordering::Acquire);
69        Self {
70            inner: Some(inner),
71            inner_closed: false,
72            rate_updates,
73            rate_updates_closed: false,
74            cancellation_token,
75            producer_handle: Some(producer_handle),
76            bridge_sender,
77            run_id,
78            pending_tool_invocations: None,
79            unread_message: None,
80            bridge_resolution_epoch,
81            observed_bridge_resolution_epoch,
82            hook_sender,
83            pending_hook_invocation: None,
84            hook_resolution_epoch,
85            observed_hook_resolution_epoch,
86            closed_event_observed: false,
87        }
88    }
89
90    fn synchronize_bridge_resolution(&mut self) {
91        let epoch = self.bridge_resolution_epoch.load(Ordering::Acquire);
92        if epoch != self.observed_bridge_resolution_epoch {
93            self.pending_tool_invocations = None;
94            self.unread_message = None;
95            self.observed_bridge_resolution_epoch = epoch;
96        }
97        let hook_epoch = self.hook_resolution_epoch.load(Ordering::Acquire);
98        if hook_epoch != self.observed_hook_resolution_epoch {
99            self.pending_hook_invocation = None;
100            self.unread_message = None;
101            self.observed_hook_resolution_epoch = hook_epoch;
102        }
103    }
104
105    /// Returns the next ordered event, host tool handoff, or subscribed hook invocation.
106    pub async fn next_message(
107        &mut self,
108    ) -> Result<Option<InteractiveRunMessage>, InteractiveError> {
109        self.synchronize_bridge_resolution();
110        if self.pending_tool_invocations.is_some() {
111            return Err(InteractiveError::ToolInvocationsPending {
112                run_id: self.run_id,
113            });
114        }
115        if self.pending_hook_invocation.is_some() {
116            return Err(InteractiveError::HookInvocationPending {
117                run_id: self.run_id,
118            });
119        }
120
121        let message = self.receive_message().await;
122        let Some(message) = message else {
123            self.finish_after_eof().await?;
124            return Ok(None);
125        };
126
127        self.observe_terminal_message(&message);
128        self.mark_pending_tool_invocations(&message)?;
129        Ok(Some(message))
130    }
131
132    async fn receive_message(&mut self) -> Option<InteractiveRunMessage> {
133        if let Some(message) = self.unread_message.take() {
134            return Some(message);
135        }
136        use futures_util::StreamExt;
137        loop {
138            if self.inner_closed && self.rate_updates_closed {
139                return None;
140            }
141            if self.inner_closed {
142                match self.rate_updates.changed().await {
143                    Ok(()) => {
144                        if let Some(event) = self.rate_updates.borrow_and_update().clone() {
145                            return Some(InteractiveRunMessage::Event(event));
146                        }
147                    }
148                    Err(_) => self.rate_updates_closed = true,
149                }
150                continue;
151            }
152            let Some(inner) = self.inner.as_mut() else {
153                self.inner_closed = true;
154                continue;
155            };
156            if self.rate_updates_closed {
157                let message = inner.next().await;
158                if message.is_none() {
159                    self.inner_closed = true;
160                }
161                return message;
162            }
163            tokio::select! {
164                biased;
165                message = inner.next() => {
166                    if message.is_none() {
167                        self.inner_closed = true;
168                    }
169                    return message;
170                }
171                changed = self.rate_updates.changed() => {
172                    match changed {
173                        Ok(()) => {
174                            if let Some(event) = self.rate_updates.borrow_and_update().clone() {
175                                return Some(InteractiveRunMessage::Event(event));
176                            }
177                        }
178                        Err(_) => self.rate_updates_closed = true,
179                    }
180                }
181            }
182        }
183    }
184
185    fn observe_terminal_message(&mut self, message: &InteractiveRunMessage) {
186        if matches!(message, InteractiveRunMessage::Event(RuntimeEvent::Closed)) {
187            self.closed_event_observed = true;
188        }
189    }
190
191    async fn finish_producer(&mut self) -> Result<(), InteractiveError> {
192        let Some(handle) = self.producer_handle.take() else {
193            return Ok(());
194        };
195        match handle.await {
196            Ok(result) => result,
197            Err(error) => {
198                let reason = error.to_string();
199                tracing::error!(
200                    run_id = self.run_id.as_u64(),
201                    reason = %reason,
202                    "interactive run producer task failed"
203                );
204                Err(InteractiveError::ProducerTaskFailed {
205                    run_id: self.run_id,
206                    reason,
207                })
208            }
209        }
210    }
211
212    async fn finish_after_eof(&mut self) -> Result<(), InteractiveError> {
213        self.finish_producer().await?;
214        if self.closed_event_observed {
215            Ok(())
216        } else {
217            Err(InteractiveError::ProducerStopped {
218                run_id: self.run_id,
219                message: "output channel closed unexpectedly",
220            })
221        }
222    }
223
224    fn mark_pending_tool_invocations(
225        &mut self,
226        message: &InteractiveRunMessage,
227    ) -> Result<(), InteractiveError> {
228        match message {
229            InteractiveRunMessage::ToolInvocations { batch } => {
230                if batch.calls().is_empty() {
231                    return Err(InteractiveError::InvalidToolInvocationBatch {
232                        run_id: self.run_id,
233                    });
234                }
235                self.pending_tool_invocations = Some(batch.clone());
236            }
237            InteractiveRunMessage::HookInvocation { invocation } => {
238                self.pending_hook_invocation = Some(invocation.clone());
239            }
240            InteractiveRunMessage::Event(_) => {}
241        }
242        Ok(())
243    }
244
245    /// Returns the next runtime event when no host handoff is encountered.
246    ///
247    /// Hosts that register bridge tools or hooks must use [`Self::next_message`].
248    pub async fn next_event(&mut self) -> Result<Option<RuntimeEvent>, InteractiveError> {
249        self.synchronize_bridge_resolution();
250        if self.pending_tool_invocations.is_some() {
251            return Err(InteractiveError::ToolInvocationsPending {
252                run_id: self.run_id,
253            });
254        }
255        if self.pending_hook_invocation.is_some() {
256            return Err(InteractiveError::HookInvocationPending {
257                run_id: self.run_id,
258            });
259        }
260        let Some(message) = self.receive_message().await else {
261            self.finish_after_eof().await?;
262            return Ok(None);
263        };
264        match message {
265            InteractiveRunMessage::Event(event) => {
266                if matches!(event, RuntimeEvent::Closed) {
267                    self.closed_event_observed = true;
268                }
269                Ok(Some(event))
270            }
271            InteractiveRunMessage::ToolInvocations { batch } => {
272                let count = batch.calls().len();
273                self.unread_message = Some(InteractiveRunMessage::ToolInvocations { batch });
274                Err(InteractiveError::ToolInvocationsRequireMessageProtocol {
275                    run_id: self.run_id,
276                    count,
277                })
278            }
279            InteractiveRunMessage::HookInvocation { invocation } => {
280                self.unread_message = Some(InteractiveRunMessage::HookInvocation { invocation });
281                Err(InteractiveError::HookInvocationRequiresMessageProtocol {
282                    run_id: self.run_id,
283                })
284            }
285        }
286    }
287
288    /// Submits a typed decision for the active host-bridged hook invocation.
289    pub async fn submit_hook_decision(
290        &mut self,
291        invocation_id: &HookInvocationId,
292        decision: HookDecision,
293    ) -> Result<(), InteractiveError> {
294        self.submit_hook_outcome(invocation_id, Ok(decision)).await
295    }
296
297    /// Reports a fail-closed host hook error for the active hook invocation.
298    pub async fn fail_hook_invocation(
299        &mut self,
300        invocation_id: &HookInvocationId,
301        message: String,
302    ) -> Result<(), InteractiveError> {
303        self.submit_hook_outcome(invocation_id, Err(message)).await
304    }
305
306    async fn submit_hook_outcome(
307        &mut self,
308        invocation_id: &HookInvocationId,
309        outcome: Result<HookDecision, String>,
310    ) -> Result<(), InteractiveError> {
311        self.synchronize_bridge_resolution();
312        if self.pending_hook_invocation.is_none() {
313            return Err(InteractiveError::NoPendingHookInvocation {
314                run_id: self.run_id,
315            });
316        }
317        let (ack_sender, ack_receiver) = oneshot::channel();
318        self.hook_sender
319            .send(HookDecisionCommand {
320                invocation_id: invocation_id.clone(),
321                outcome,
322                ack_sender,
323            })
324            .await
325            .map_err(|_| InteractiveError::RunClosed {
326                run_id: self.run_id,
327            })?;
328        let result = ack_receiver
329            .await
330            .map_err(|_| InteractiveError::RunClosed {
331                run_id: self.run_id,
332            })?;
333        match result {
334            Ok(()) => {
335                self.pending_hook_invocation = None;
336                Ok(())
337            }
338            Err(source) => Err(InteractiveError::Runtime { source }),
339        }
340    }
341
342    /// Submits all outcomes for the currently emitted host tool batch.
343    ///
344    /// The runtime validates call ids, content, and result status. Validation
345    /// failures that are safe to correct are returned while the batch remains
346    /// pending. If runtime has already recorded the calls as failed, the
347    /// rejection is returned but the batch is released and the producer can
348    /// continue.
349    pub async fn submit_tool_invocation_outcomes(
350        &mut self,
351        batch_id: &ToolCallBatchId,
352        outcomes: Vec<(ToolCallId, crate::ToolExecutionOutcome)>,
353    ) -> Result<(), InteractiveError> {
354        if self.pending_tool_invocations.is_none() {
355            return Err(InteractiveError::NoPendingToolInvocations {
356                run_id: self.run_id,
357            });
358        }
359        if outcomes.is_empty() {
360            return Err(InteractiveError::InvalidToolInvocationBatch {
361                run_id: self.run_id,
362            });
363        }
364        let (ack_sender, ack_receiver) = oneshot::channel();
365        self.bridge_sender
366            .send(BridgeToolResultCommand::outcomes(
367                batch_id.clone(),
368                outcomes,
369                ack_sender,
370            ))
371            .await
372            .map_err(|_| InteractiveError::RunClosed {
373                run_id: self.run_id,
374            })?;
375        let result = ack_receiver
376            .await
377            .map_err(|_| InteractiveError::RunClosed {
378                run_id: self.run_id,
379            })?;
380        if result.is_ok() {
381            self.pending_tool_invocations = None;
382        } else if let Err(error) = result {
383            if !error.is_retryable_bridge_tool_result() {
384                self.pending_tool_invocations = None;
385            }
386            return Err(InteractiveError::Runtime { source: error });
387        }
388        Ok(())
389    }
390
391    /// Requests cancellation of the producer without awaiting its shutdown.
392    ///
393    /// This is used by synchronous drop guards at the facade boundary. Callers
394    /// that own the async lifecycle should use `wait_until_closed` afterwards.
395    pub fn request_cancel(&self) {
396        self.cancellation_token.cancel();
397    }
398
399    /// Waits for the interactive producer to emit its terminal closed event.
400    ///
401    /// Ordinary runtime events are drained. If a host-tool handoff is reached,
402    /// this returns [`InteractiveError::ToolInvocationsRequireMessageProtocol`]
403    /// without consuming the handoff, so the caller can switch to
404    /// [`Self::next_message`] and resolve it. This method is therefore a
405    /// lifecycle drain, not an implicit host-tool executor.
406    pub async fn wait_until_closed(&mut self) -> Result<(), InteractiveError> {
407        while let Some(event) = self.next_event().await? {
408            if matches!(event, RuntimeEvent::Closed) {
409                break;
410            }
411        }
412        self.inner.take();
413        self.finish_producer().await
414    }
415
416    /// Cancels the producer, drains all buffered events and handoffs, and waits
417    /// for durable shutdown (including settling any pending bridge tool calls).
418    pub async fn cancel_and_wait_until_closed(&mut self) -> Result<(), InteractiveError> {
419        self.cancellation_token.cancel();
420        self.pending_tool_invocations = None;
421        self.pending_hook_invocation = None;
422        self.unread_message = None;
423        while let Some(message) = self.receive_message().await {
424            self.observe_terminal_message(&message);
425            if self.closed_event_observed {
426                break;
427            }
428        }
429        self.inner.take();
430        self.finish_producer().await
431    }
432}
433
434impl Drop for InteractiveRunEventStream {
435    fn drop(&mut self) {
436        self.inner.take();
437        self.cancellation_token.cancel();
438
439        if let Some(handle) = self.producer_handle.take() {
440            handle.abort();
441        }
442    }
443}
444
445pub struct InteractiveAgentRun {
446    stream: InteractiveRunEventStream,
447    input: AgentLoopInput,
448    control: AgentLoopControl,
449}
450
451impl InteractiveAgentRun {
452    pub(super) fn new(
453        stream: InteractiveRunEventStream,
454        input: AgentLoopInput,
455        control: AgentLoopControl,
456    ) -> Self {
457        Self {
458            stream,
459            input,
460            control,
461        }
462    }
463
464    #[must_use]
465    pub fn split(self) -> (InteractiveRunEventStream, AgentLoopInput, AgentLoopControl) {
466        (self.stream, self.input, self.control)
467    }
468}
469
470#[derive(Clone)]
471pub struct AgentLoopInput {
472    run_id: InteractiveRunId,
473    command_sender: mpsc::Sender<InteractiveCommand>,
474}
475
476impl AgentLoopInput {
477    pub(super) fn new(
478        run_id: InteractiveRunId,
479        command_sender: mpsc::Sender<InteractiveCommand>,
480    ) -> Self {
481        Self {
482            run_id,
483            command_sender,
484        }
485    }
486
487    #[must_use]
488    pub fn run_id(&self) -> InteractiveRunId {
489        self.run_id
490    }
491
492    /// Appends text to the pending queue (runs immediately when idle and not paused).
493    pub async fn submit(&self, text: &str) -> Result<InteractiveInputItem, InteractiveError> {
494        let message = UserMessageInput::text_only(text)?;
495        self.submit_message(message).await
496    }
497
498    /// Appends a user message to the pending queue (runs immediately when idle and not paused).
499    pub async fn submit_message(
500        &self,
501        message: UserMessageInput,
502    ) -> Result<InteractiveInputItem, InteractiveError> {
503        let text = message.text().to_owned();
504        let (ack_sender, ack_receiver) = oneshot::channel();
505        self.command_sender
506            .send(InteractiveCommand::Submit {
507                message,
508                ack_sender,
509            })
510            .await
511            .map_err(|_| InteractiveError::CommandChannelClosed {
512                run_id: self.run_id,
513            })?;
514        ack_receiver
515            .await
516            .map_err(|_| InteractiveError::CommandChannelClosed {
517                run_id: self.run_id,
518            })?
519            .map(|id| InteractiveInputItem::new(self.clone(), id, text))
520    }
521
522    /// Updates a pending item's text by its stable [`QueuedInputId`].
523    pub async fn update_by_id(
524        &self,
525        id: QueuedInputId,
526        text: &str,
527    ) -> Result<(), InteractiveError> {
528        let (ack_sender, ack_receiver) = oneshot::channel();
529        self.command_sender
530            .send(InteractiveCommand::Update {
531                id,
532                text: text.to_owned(),
533                ack_sender,
534            })
535            .await
536            .map_err(|_| InteractiveError::CommandChannelClosed {
537                run_id: self.run_id,
538            })?;
539        ack_receiver
540            .await
541            .map_err(|_| InteractiveError::CommandChannelClosed {
542                run_id: self.run_id,
543            })?
544    }
545
546    /// Removes a pending item by its stable [`QueuedInputId`].
547    pub async fn remove_by_id(&self, id: QueuedInputId) -> Result<(), InteractiveError> {
548        let (ack_sender, ack_receiver) = oneshot::channel();
549        self.command_sender
550            .send(InteractiveCommand::Remove { id, ack_sender })
551            .await
552            .map_err(|_| InteractiveError::CommandChannelClosed {
553                run_id: self.run_id,
554            })?;
555        ack_receiver
556            .await
557            .map_err(|_| InteractiveError::CommandChannelClosed {
558                run_id: self.run_id,
559            })?
560    }
561
562    /// Pauses or resumes automatic dispatch of pending items.
563    ///
564    /// While paused (for example, when any pending item is being edited in a UI),
565    /// pending items will not auto-send at turn boundaries. Passing `false` resumes
566    /// auto-dispatch and immediately sends all pending items together if the loop is idle.
567    pub async fn set_paused(&self, paused: bool) -> Result<(), InteractiveError> {
568        let (ack_sender, ack_receiver) = oneshot::channel();
569        self.command_sender
570            .send(InteractiveCommand::SetPendingPaused { paused, ack_sender })
571            .await
572            .map_err(|_| InteractiveError::CommandChannelClosed {
573                run_id: self.run_id,
574            })?;
575        ack_receiver
576            .await
577            .map_err(|_| InteractiveError::CommandChannelClosed {
578                run_id: self.run_id,
579            })?
580    }
581
582    /// Resumes and immediately dispatches all pending items together if the loop is idle.
583    pub async fn flush(&self) -> Result<(), InteractiveError> {
584        let (ack_sender, ack_receiver) = oneshot::channel();
585        self.command_sender
586            .send(InteractiveCommand::FlushPending { ack_sender })
587            .await
588            .map_err(|_| InteractiveError::CommandChannelClosed {
589                run_id: self.run_id,
590            })?;
591        ack_receiver
592            .await
593            .map_err(|_| InteractiveError::CommandChannelClosed {
594                run_id: self.run_id,
595            })?
596    }
597
598    pub async fn replace_pending_order(
599        &self,
600        items: &[InteractiveInputItem],
601    ) -> Result<(), InteractiveError> {
602        if items.iter().any(|item| item.input.run_id != self.run_id) {
603            return Err(InteractiveError::InvalidPendingOrder {
604                reason: "input item belongs to another interactive run",
605            });
606        }
607        let ids = items.iter().map(|item| item.id).collect::<Vec<_>>();
608        let (ack_sender, ack_receiver) = oneshot::channel();
609        self.command_sender
610            .send(InteractiveCommand::ReplacePendingOrder { ids, ack_sender })
611            .await
612            .map_err(|_| InteractiveError::CommandChannelClosed {
613                run_id: self.run_id,
614            })?;
615        ack_receiver
616            .await
617            .map_err(|_| InteractiveError::CommandChannelClosed {
618                run_id: self.run_id,
619            })?
620    }
621
622    pub async fn snapshot(&self) -> Result<InteractiveInputSnapshot, InteractiveError> {
623        let (ack_sender, ack_receiver) = oneshot::channel();
624        self.command_sender
625            .send(InteractiveCommand::Snapshot { ack_sender })
626            .await
627            .map_err(|_| InteractiveError::CommandChannelClosed {
628                run_id: self.run_id,
629            })?;
630        let records = ack_receiver
631            .await
632            .map_err(|_| InteractiveError::CommandChannelClosed {
633                run_id: self.run_id,
634            })?;
635        Ok(InteractiveInputSnapshot::from_records(
636            self.clone(),
637            records,
638        ))
639    }
640}
641
642#[derive(Clone)]
643pub struct InteractiveInputItem {
644    input: AgentLoopInput,
645    id: QueuedInputId,
646    text: String,
647}
648
649impl InteractiveInputItem {
650    fn new(input: AgentLoopInput, id: QueuedInputId, text: String) -> Self {
651        Self { input, id, text }
652    }
653
654    #[must_use]
655    pub fn id(&self) -> QueuedInputId {
656        self.id
657    }
658
659    #[must_use]
660    pub fn text(&self) -> &str {
661        self.text.as_str()
662    }
663
664    pub async fn update(&mut self, text: impl Into<String>) -> Result<(), InteractiveError> {
665        let text = text.into();
666        self.input.update_by_id(self.id, &text).await?;
667        self.text = text;
668        Ok(())
669    }
670
671    pub async fn remove(self) -> Result<(), InteractiveError> {
672        self.input.remove_by_id(self.id).await
673    }
674}
675
676#[derive(Clone)]
677pub struct InteractiveInputSnapshot {
678    pub items: Vec<InteractiveInputItem>,
679    pub paused: bool,
680}
681
682impl InteractiveInputSnapshot {
683    fn from_records(input: AgentLoopInput, records: InputRecords) -> Self {
684        Self {
685            items: records_to_items(input, records.items),
686            paused: records.paused,
687        }
688    }
689}
690
691fn records_to_items(input: AgentLoopInput, records: Vec<InputRecord>) -> Vec<InteractiveInputItem> {
692    records
693        .into_iter()
694        .map(|record| InteractiveInputItem::new(input.clone(), record.id, record.text))
695        .collect()
696}
697
698#[derive(Clone)]
699pub struct AgentLoopControl {
700    run_id: InteractiveRunId,
701    command_sender: mpsc::Sender<InteractiveCommand>,
702}
703
704impl AgentLoopControl {
705    pub(super) fn new(
706        run_id: InteractiveRunId,
707        command_sender: mpsc::Sender<InteractiveCommand>,
708    ) -> Self {
709        Self {
710            run_id,
711            command_sender,
712        }
713    }
714
715    #[must_use]
716    pub fn run_id(&self) -> InteractiveRunId {
717        self.run_id
718    }
719
720    pub async fn update_settings(
721        &self,
722        update: InteractiveSettingsUpdate,
723    ) -> Result<(), InteractiveError> {
724        let (ack_sender, ack_receiver) = oneshot::channel();
725        self.command_sender
726            .send(InteractiveCommand::UpdateSettings {
727                update: Box::new(update),
728                ack_sender,
729            })
730            .await
731            .map_err(|_| InteractiveError::CommandChannelClosed {
732                run_id: self.run_id,
733            })?;
734        ack_receiver
735            .await
736            .map_err(|_| InteractiveError::CommandChannelClosed {
737                run_id: self.run_id,
738            })?
739    }
740
741    pub async fn interrupt(&self, reason: InterruptReason) -> Result<(), InteractiveError> {
742        let (ack_sender, ack_receiver) = oneshot::channel();
743        self.command_sender
744            .send(InteractiveCommand::Interrupt { reason, ack_sender })
745            .await
746            .map_err(|_| InteractiveError::CommandChannelClosed {
747                run_id: self.run_id,
748            })?;
749        ack_receiver
750            .await
751            .map_err(|_| InteractiveError::CommandChannelClosed {
752                run_id: self.run_id,
753            })?
754    }
755
756    /// Saves the session only while the interactive producer is at an idle boundary.
757    ///
758    /// Returns [`InteractiveError::SessionSaveRequiresIdle`] immediately when a model, tool, or
759    /// interrupt phase is active.
760    pub async fn save_session_to(&self, store: FileSessionStore) -> Result<(), InteractiveError> {
761        let (ack_sender, ack_receiver) = oneshot::channel();
762        self.command_sender
763            .send(InteractiveCommand::SaveSession { store, ack_sender })
764            .await
765            .map_err(|_| InteractiveError::CommandChannelClosed {
766                run_id: self.run_id,
767            })?;
768        ack_receiver
769            .await
770            .map_err(|_| InteractiveError::CommandChannelClosed {
771                run_id: self.run_id,
772            })?
773    }
774
775    /// Manually compacts session history at an idle boundary, optionally
776    /// emphasizing `focus` instructions in the generated summary.
777    ///
778    /// Returns `Ok(None)` when no compressible history exists before the
779    /// retained tail, and [`InteractiveError::CompactRequiresIdle`] immediately
780    /// when a model, tool, compaction, or interrupt phase is already active.
781    pub async fn compact_context(
782        &self,
783        focus: Option<String>,
784    ) -> Result<Option<CompactionOutcome>, InteractiveError> {
785        self.compact_context_with_policy(focus, None).await
786    }
787
788    /// Manually compacts session history at an idle boundary with optional
789    /// `focus` instructions and an optional per-call [`CitationCompactionPolicy`]
790    /// override.
791    ///
792    /// When `policy` is `None`, the runtime's configured compaction policy is used.
793    pub async fn compact_context_with_policy(
794        &self,
795        focus: Option<String>,
796        policy: Option<CitationCompactionPolicy>,
797    ) -> Result<Option<CompactionOutcome>, InteractiveError> {
798        let (ack_sender, ack_receiver) = oneshot::channel();
799        self.command_sender
800            .send(InteractiveCommand::CompactContext {
801                focus,
802                policy,
803                ack_sender,
804            })
805            .await
806            .map_err(|_| InteractiveError::CommandChannelClosed {
807                run_id: self.run_id,
808            })?;
809        ack_receiver
810            .await
811            .map_err(|_| InteractiveError::CommandChannelClosed {
812                run_id: self.run_id,
813            })?
814    }
815
816    /// Toggles Plan Mode on or off (works both while idle and mid-turn).
817    pub async fn set_plan_mode(&self, enabled: bool) -> Result<(), InteractiveError> {
818        let (ack_sender, ack_receiver) = oneshot::channel();
819        self.command_sender
820            .send(InteractiveCommand::SetPlanMode {
821                enabled,
822                ack_sender,
823            })
824            .await
825            .map_err(|_| InteractiveError::CommandChannelClosed {
826                run_id: self.run_id,
827            })?;
828        ack_receiver
829            .await
830            .map_err(|_| InteractiveError::CommandChannelClosed {
831                run_id: self.run_id,
832            })?
833    }
834
835    /// Approves a submitted plan, exits Plan Mode, and continues execution.
836    pub async fn approve_plan(
837        &self,
838        plan_id: PlanId,
839        note: Option<String>,
840    ) -> Result<(), InteractiveError> {
841        let (ack_sender, ack_receiver) = oneshot::channel();
842        self.command_sender
843            .send(InteractiveCommand::ApprovePlan {
844                plan_id,
845                note,
846                ack_sender,
847            })
848            .await
849            .map_err(|_| InteractiveError::CommandChannelClosed {
850                run_id: self.run_id,
851            })?;
852        ack_receiver
853            .await
854            .map_err(|_| InteractiveError::CommandChannelClosed {
855                run_id: self.run_id,
856            })?
857    }
858
859    /// Keeps Plan Mode active and delivers revision feedback to the agent.
860    pub async fn request_plan_changes(
861        &self,
862        plan_id: PlanId,
863        feedback: String,
864    ) -> Result<(), InteractiveError> {
865        let (ack_sender, ack_receiver) = oneshot::channel();
866        self.command_sender
867            .send(InteractiveCommand::RequestPlanChanges {
868                plan_id,
869                feedback,
870                ack_sender,
871            })
872            .await
873            .map_err(|_| InteractiveError::CommandChannelClosed {
874                run_id: self.run_id,
875            })?;
876        ack_receiver
877            .await
878            .map_err(|_| InteractiveError::CommandChannelClosed {
879                run_id: self.run_id,
880            })?
881    }
882
883    /// Abandons a submitted plan and exits Plan Mode without implementing.
884    pub async fn abandon_plan(&self, plan_id: PlanId) -> Result<(), InteractiveError> {
885        let (ack_sender, ack_receiver) = oneshot::channel();
886        self.command_sender
887            .send(InteractiveCommand::AbandonPlan {
888                plan_id,
889                ack_sender,
890            })
891            .await
892            .map_err(|_| InteractiveError::CommandChannelClosed {
893                run_id: self.run_id,
894            })?;
895        ack_receiver
896            .await
897            .map_err(|_| InteractiveError::CommandChannelClosed {
898                run_id: self.run_id,
899            })?
900    }
901
902    pub async fn close(&self) -> Result<(), InteractiveError> {
903        let (ack_sender, ack_receiver) = oneshot::channel();
904        self.command_sender
905            .send(InteractiveCommand::Close { ack_sender })
906            .await
907            .map_err(|_| InteractiveError::CommandChannelClosed {
908                run_id: self.run_id,
909            })?;
910        ack_receiver
911            .await
912            .map_err(|_| InteractiveError::CommandChannelClosed {
913                run_id: self.run_id,
914            })?
915    }
916}
917
918#[cfg(test)]
919mod tests {
920    use super::*;
921
922    #[tokio::test]
923    async fn producer_panic_preserves_join_error_reason() {
924        let (message_tx, message_rx) = mpsc::channel(1);
925        let (rate_tx, rate_rx) = watch::channel(None);
926        let (bridge_tx, _bridge_rx) = mpsc::channel(1);
927        let (hook_tx, _hook_rx) = mpsc::channel(1);
928        let producer = tokio::spawn(async move {
929            let _tx = message_tx;
930            let _rate = rate_tx;
931            panic!("injected thread spawn failure: os error 11");
932        });
933
934        let mut stream = InteractiveRunEventStream::new(
935            InteractiveRunId(42),
936            ReceiverStream::new(message_rx),
937            rate_rx,
938            CancellationToken::new(),
939            producer,
940            bridge_tx,
941            Arc::new(AtomicU64::new(0)),
942            hook_tx,
943            Arc::new(AtomicU64::new(0)),
944        );
945
946        let err = stream
947            .next_message()
948            .await
949            .expect_err("panicked producer should surface ProducerTaskFailed");
950        match &err {
951            InteractiveError::ProducerTaskFailed { run_id, reason } => {
952                assert_eq!(*run_id, InteractiveRunId(42));
953                assert!(
954                    reason.contains("injected thread spawn failure: os error 11"),
955                    "unexpected reason: {reason}"
956                );
957            }
958            other => panic!("expected ProducerTaskFailed, got {other:?}"),
959        }
960        assert!(
961            err.to_string()
962                .contains("injected thread spawn failure: os error 11")
963        );
964    }
965}