Skip to main content

merry_runtime/agent_loop/
driver.rs

1//! Synchronous and streaming entry points for the runtime agent loop.
2
3use super::hook_step::{
4    AfterStepHookAction, BeforeStepHookAction, StepHookContext, run_after_model_step_hook,
5    run_before_model_step_hook,
6};
7use super::producer::{
8    AgentLoopStreamProducer, AgentLoopStreamProducerInput, run_agent_loop_stream_producer,
9};
10use super::{
11    AgentLoopBlockedReason, AgentLoopConfig, AgentLoopError, AgentLoopResult, AgentLoopStatus,
12    AgentRun, FinalOutputStepDecision, PendingLoopToolCall, StepOutcome, blocked_reason_code,
13    build_step_context, can_retry_structured_output, classify_step_events, collect_step_events,
14    continuation_step_input, evaluate_and_record_final_output_call,
15    final_assistant_output_from_step, finish_agent_loop_result, max_model_turns_blocked_result,
16    preempt_next_input_with_subagent_notification, structured_output_failure_result,
17    take_subagent_notification, take_subagent_notification_input,
18    tool_execution_cancelled_diagnostic, tool_resolution_diagnostic_code,
19    tool_resolution_is_policy_denied, tool_resolution_status, trace_loop_error, trace_loop_finish,
20};
21use crate::{
22    HookPoint, Runtime, RuntimeError, StepContext, StepInput, ToolExecutionContext,
23    hooks::wave::{
24        HookWaveContext, PostRuntimeToolOutcome, PreToolWaveOutcome, run_post_runtime_tool_hooks,
25        run_pre_tool_wave_hooks,
26    },
27};
28use std::sync::{Arc, atomic::AtomicU64};
29use tokio::sync::{mpsc, oneshot};
30use tokio_stream::wrappers::ReceiverStream;
31
32impl Runtime {
33    /// Runs a bounded runtime-owned agent loop.
34    ///
35    /// The loop starts with one [`Runtime::step`]. If the step completes, fails,
36    /// or is cancelled, the corresponding status is returned with all observed
37    /// events. If the step records pending tool calls and more step budget
38    /// remains, the loop executes registered runtime tools, appends their
39    /// events, and starts a continuation step without adding a new user
40    /// message.
41    ///
42    /// A batch preserves model order around exclusive tools. Adjacent tools
43    /// explicitly registered as parallel-safe may execute concurrently up to
44    /// the runtime limit; all other tools execute serially. The loop does not
45    /// introduce provider conversation state. It owns the runtime active-step
46    /// permit for the full step -> tool execution -> continuation sequence.
47    /// While the loop is running, cloned runtime handles reject concurrent
48    /// direct mutation APIs with [`RuntimeError::StepAlreadyActive`].
49    /// Cancellation and generation controls are reused from `context` for
50    /// every step and tool execution.
51    pub async fn run_agent_loop(
52        &self,
53        input: StepInput,
54        context: StepContext,
55        config: AgentLoopConfig,
56    ) -> Result<AgentLoopResult, AgentLoopError> {
57        let (loop_token, generation_config, context_contract) = context.into_parts();
58        let config = config
59            .merge_context_final_output_contract(context_contract)
60            .map_err(|source| {
61                AgentLoopError::new(Vec::new(), RuntimeError::AgentLoopConfig { source })
62            })?;
63        let loop_permit = self
64            .acquire_active_step_permit()
65            .map_err(|source| AgentLoopError::new(Vec::new(), source))?;
66        let mut next_input = Some(input);
67        let mut deferred_user_input = None;
68        let mut events = Vec::new();
69        let mut subagent_event_receiver = self.subscribe_subagent_events();
70        let mut model_turns_run = 0;
71        let mut structured_output_retries: usize = 0;
72
73        tracing::info!(
74            event = "runtime.loop.start",
75            session_id = self.session_id().as_str(),
76            max_model_turns = config.max_model_turns(),
77            "runtime loop start"
78        );
79
80        loop {
81            preempt_next_input_with_subagent_notification(
82                self,
83                &mut next_input,
84                &mut deferred_user_input,
85            )
86            .await;
87            let mut input = next_input
88                .take()
89                .expect("agent loop always installs the next step input before continuing");
90            let step_index = model_turns_run + 1;
91            let before_ctx = StepHookContext {
92                runtime: self,
93                model_turn: step_index,
94                max_model_turns: config.max_model_turns(),
95                loop_token: &loop_token,
96                loop_permit: &loop_permit,
97            };
98            let step_generation_config = match run_before_model_step_hook(
99                &before_ctx,
100                &mut input,
101                generation_config.clone(),
102                None,
103            )
104            .await
105            {
106                Ok(BeforeStepHookAction::Proceed(gen_cfg)) => gen_cfg,
107                Ok(BeforeStepHookAction::Finish {
108                    status,
109                    final_output,
110                }) => {
111                    if matches!(status, AgentLoopStatus::StoppedByHook { .. }) {
112                        trace_loop_finish(
113                            self.session_id().as_str(),
114                            "stopped_by_hook",
115                            model_turns_run,
116                            Some("before_model_step"),
117                        );
118                    }
119                    return Ok(finish_agent_loop_result(
120                        self,
121                        status,
122                        events,
123                        model_turns_run,
124                        final_output,
125                    )
126                    .await);
127                }
128                Err(source) => {
129                    trace_loop_error(self.session_id().as_str(), model_turns_run, &source);
130                    return Err(AgentLoopError::new(events, source));
131                }
132            };
133            tracing::info!(
134                event = "runtime.step.start",
135                session_id = self.session_id().as_str(),
136                step_index,
137                "runtime loop step start"
138            );
139            let step_context = build_step_context(
140                loop_token.clone(),
141                step_generation_config,
142                config.final_output_contract(),
143            );
144            let stream =
145                match self.step_with_active_permit(input, step_context, loop_permit.clone()) {
146                    Ok(stream) => stream,
147                    Err(source) => {
148                        trace_loop_error(self.session_id().as_str(), model_turns_run, &source);
149                        return Err(AgentLoopError::new(events, source));
150                    }
151                };
152            model_turns_run += 1;
153
154            let mut step_events = collect_step_events(stream).await;
155            let step_final_output = final_assistant_output_from_step(&step_events);
156            let outcome = classify_step_events(&step_events, config.final_output_contract());
157            events.append(&mut step_events);
158            drain_subagent_events(&mut subagent_event_receiver, &mut events);
159
160            let after_ctx = StepHookContext {
161                runtime: self,
162                model_turn: model_turns_run,
163                max_model_turns: config.max_model_turns(),
164                loop_token: &loop_token,
165                loop_permit: &loop_permit,
166            };
167            match run_after_model_step_hook(&after_ctx, &outcome, &step_final_output, None).await {
168                Ok(AfterStepHookAction::Accept) => {}
169                Ok(AfterStepHookAction::ContinueWithInput {
170                    settled_events,
171                    input,
172                }) => {
173                    events.extend(settled_events);
174                    next_input = Some(input);
175                    continue;
176                }
177                Ok(AfterStepHookAction::Finish {
178                    settled_events,
179                    status,
180                    final_output,
181                }) => {
182                    events.extend(settled_events);
183                    return Ok(finish_agent_loop_result(
184                        self,
185                        status,
186                        events,
187                        model_turns_run,
188                        final_output,
189                    )
190                    .await);
191                }
192                Err(source) => {
193                    trace_loop_error(self.session_id().as_str(), model_turns_run, &source);
194                    return Err(AgentLoopError::new(events, source));
195                }
196            }
197
198            match outcome {
199                StepOutcome::Completed => {
200                    loop {
201                        if let Some(notification_input) =
202                            take_subagent_notification_input(self).await
203                        {
204                            if model_turns_run >= config.max_model_turns() {
205                                trace_loop_finish(
206                                    self.session_id().as_str(),
207                                    "blocked",
208                                    model_turns_run,
209                                    Some("max_model_turns_reached"),
210                                );
211                                return Ok(max_model_turns_blocked_result(
212                                    self,
213                                    &config,
214                                    events,
215                                    model_turns_run,
216                                )
217                                .await);
218                            }
219                            next_input = Some(notification_input);
220                            break;
221                        }
222                        if let Some(deferred_user_input) = deferred_user_input.take() {
223                            next_input = Some(deferred_user_input);
224                            break;
225                        }
226                        if !self.has_active_subagents().await {
227                            break;
228                        }
229                        let Some(notify) = self.subagent_completion_notify() else {
230                            break;
231                        };
232                        let notified = notify.notified();
233                        tokio::pin!(notified);
234                        notified.as_mut().enable();
235                        if self.has_subagent_completion_notifications().await
236                            || !self.has_active_subagents().await
237                        {
238                            continue;
239                        }
240                        tokio::select! {
241                            biased;
242                            () = loop_token.cancelled() => {
243                                let diagnostic = crate::agent_loop::agent_loop_cancelled_diagnostic();
244                                trace_loop_finish(
245                                    self.session_id().as_str(),
246                                    "cancelled",
247                                    model_turns_run,
248                                    Some(diagnostic.code()),
249                                );
250                                return Ok(finish_agent_loop_result(
251                                    self,
252                                    AgentLoopStatus::Cancelled { diagnostic },
253                                    events,
254                                    model_turns_run,
255                                    None,
256                                )
257                                .await);
258                            }
259                            subagent_event = subagent_event_receiver.recv() => {
260                                if let Ok(event) = subagent_event {
261                                    events.push(event);
262                                }
263                            }
264                            () = notified.as_mut() => {}
265                        }
266                    }
267                    drain_subagent_events(&mut subagent_event_receiver, &mut events);
268                    if next_input.is_some() {
269                        continue;
270                    }
271                    trace_loop_finish(
272                        self.session_id().as_str(),
273                        "completed",
274                        model_turns_run,
275                        None,
276                    );
277                    self.schedule_memory_maintenance();
278                    return Ok(finish_agent_loop_result(
279                        self,
280                        AgentLoopStatus::Completed,
281                        events,
282                        model_turns_run,
283                        step_final_output,
284                    )
285                    .await);
286                }
287                StepOutcome::Failed(diagnostic) => {
288                    trace_loop_finish(
289                        self.session_id().as_str(),
290                        "failed",
291                        model_turns_run,
292                        Some(diagnostic.code()),
293                    );
294                    return Ok(finish_agent_loop_result(
295                        self,
296                        AgentLoopStatus::Failed { diagnostic },
297                        events,
298                        model_turns_run,
299                        None,
300                    )
301                    .await);
302                }
303                StepOutcome::Cancelled(diagnostic) => {
304                    trace_loop_finish(
305                        self.session_id().as_str(),
306                        "cancelled",
307                        model_turns_run,
308                        Some(diagnostic.code()),
309                    );
310                    return Ok(finish_agent_loop_result(
311                        self,
312                        AgentLoopStatus::Cancelled { diagnostic },
313                        events,
314                        model_turns_run,
315                        None,
316                    )
317                    .await);
318                }
319                StepOutcome::Blocked(reason) => {
320                    trace_loop_finish(
321                        self.session_id().as_str(),
322                        "blocked",
323                        model_turns_run,
324                        Some(blocked_reason_code(&reason)),
325                    );
326                    return Ok(finish_agent_loop_result(
327                        self,
328                        AgentLoopStatus::Blocked { reason },
329                        events,
330                        model_turns_run,
331                        None,
332                    )
333                    .await);
334                }
335                StepOutcome::Pending(PendingLoopToolCall::Bridge(call)) => {
336                    trace_loop_finish(
337                        self.session_id().as_str(),
338                        "blocked",
339                        model_turns_run,
340                        Some("bridge_tool_call_requested"),
341                    );
342                    return Ok(finish_agent_loop_result(
343                        self,
344                        AgentLoopStatus::Blocked {
345                            reason: AgentLoopBlockedReason::BridgeToolCallRequested {
346                                call_id: call.id().clone(),
347                                tool_name: call.name().clone(),
348                            },
349                        },
350                        events,
351                        model_turns_run,
352                        None,
353                    )
354                    .await);
355                }
356                StepOutcome::ToolResultRecorded => {
357                    if model_turns_run >= config.max_model_turns() {
358                        trace_loop_finish(
359                            self.session_id().as_str(),
360                            "blocked",
361                            model_turns_run,
362                            Some("max_model_turns_reached"),
363                        );
364                        return Ok(max_model_turns_blocked_result(
365                            self,
366                            &config,
367                            events,
368                            model_turns_run,
369                        )
370                        .await);
371                    }
372
373                    next_input = Some(continuation_step_input());
374                }
375                StepOutcome::Pending(PendingLoopToolCall::FinalOutput(call)) => {
376                    if let Some((notification_input, notification_text)) =
377                        take_subagent_notification(self).await
378                    {
379                        let mut failure_events = match self
380                            .submit_tool_execution_failure_with_active_permit(
381                                call.id(),
382                                &notification_text,
383                                &loop_permit,
384                            )
385                            .await
386                        {
387                            Ok(events) => events,
388                            Err(source) => {
389                                trace_loop_error(
390                                    self.session_id().as_str(),
391                                    model_turns_run,
392                                    &source,
393                                );
394                                return Err(AgentLoopError::new(events, source));
395                            }
396                        };
397                        events.append(&mut failure_events);
398                        if model_turns_run >= config.max_model_turns() {
399                            trace_loop_finish(
400                                self.session_id().as_str(),
401                                "blocked",
402                                model_turns_run,
403                                Some("max_model_turns_reached"),
404                            );
405                            return Ok(max_model_turns_blocked_result(
406                                self,
407                                &config,
408                                events,
409                                model_turns_run,
410                            )
411                            .await);
412                        }
413                        next_input = Some(notification_input);
414                        continue;
415                    }
416                    match evaluate_and_record_final_output_call(
417                        self,
418                        config.final_output_contract(),
419                        call,
420                        &loop_permit,
421                    )
422                    .await
423                    {
424                        Ok(FinalOutputStepDecision::ValidationFailed {
425                            events: mut failure_events,
426                            error_message,
427                        }) => {
428                            events.append(&mut failure_events);
429                            structured_output_retries = structured_output_retries.saturating_add(1);
430                            if can_retry_structured_output(
431                                &config,
432                                structured_output_retries,
433                                model_turns_run,
434                            ) {
435                                next_input = Some(continuation_step_input());
436                                continue;
437                            }
438                            return Ok(structured_output_failure_result(
439                                self,
440                                events,
441                                model_turns_run,
442                                error_message,
443                            )
444                            .await);
445                        }
446                        Ok(FinalOutputStepDecision::Recorded {
447                            final_output,
448                            events: mut final_events,
449                        }) => {
450                            events.append(&mut final_events);
451                            trace_loop_finish(
452                                self.session_id().as_str(),
453                                "completed",
454                                model_turns_run,
455                                None,
456                            );
457                            let session_usage = self.usage().await;
458                            return Ok(AgentLoopResult::new_with_final_output_json(
459                                AgentLoopStatus::Completed,
460                                events,
461                                model_turns_run,
462                                None,
463                                Some(final_output),
464                                session_usage,
465                            ));
466                        }
467                        Err(source) => {
468                            trace_loop_error(self.session_id().as_str(), model_turns_run, &source);
469                            return Err(AgentLoopError::new(events, source));
470                        }
471                    }
472                }
473                StepOutcome::PendingBatch(calls) => {
474                    if model_turns_run >= config.max_model_turns() {
475                        return Ok(max_model_turns_blocked_result(
476                            self,
477                            &config,
478                            events,
479                            model_turns_run,
480                        )
481                        .await);
482                    }
483
484                    if let Some(call) = calls.iter().find_map(|call| match call {
485                        PendingLoopToolCall::Bridge(call) => Some(call),
486                        PendingLoopToolCall::Runtime(_) | PendingLoopToolCall::FinalOutput(_) => {
487                            None
488                        }
489                    }) {
490                        return Ok(finish_agent_loop_result(
491                            self,
492                            AgentLoopStatus::Blocked {
493                                reason: AgentLoopBlockedReason::BridgeToolCallRequested {
494                                    call_id: call.id().clone(),
495                                    tool_name: call.name().clone(),
496                                },
497                            },
498                            events,
499                            model_turns_run,
500                            None,
501                        )
502                        .await);
503                    }
504
505                    let runtime_calls = calls
506                        .into_iter()
507                        .map(|call| match call {
508                            PendingLoopToolCall::Runtime(call) => call,
509                            PendingLoopToolCall::FinalOutput(_) => {
510                                unreachable!(
511                                    "mixed final-output batches are rejected by provider step"
512                                )
513                            }
514                            PendingLoopToolCall::Bridge(_) => {
515                                unreachable!("bridge batches return before runtime execution")
516                            }
517                        })
518                        .collect();
519                    let wave = HookWaveContext {
520                        runtime: self,
521                        model_turn: model_turns_run,
522                        token: &loop_token,
523                        loop_permit: &loop_permit,
524                    };
525                    let allowed_calls =
526                        match run_driver_pre_tool_hooks(&wave, runtime_calls, &mut events).await {
527                            DriverPreHookOutcome::Proceed(calls) => calls,
528                            DriverPreHookOutcome::Finish(res) => return *res,
529                        };
530
531                    if !allowed_calls.is_empty() {
532                        let execution = self
533                            .execute_tool_call_batch_with_active_permit(
534                                allowed_calls.clone(),
535                                ToolExecutionContext::new(loop_token.clone()),
536                                &loop_permit,
537                            )
538                            .await;
539                        let (mut execution_events, error) = execution.into_parts();
540                        let post_outcome = run_post_runtime_tool_hooks(
541                            &wave,
542                            &allowed_calls,
543                            &execution_events,
544                            None,
545                        )
546                        .await;
547                        events.append(&mut execution_events);
548
549                        if let Some(early) =
550                            handle_driver_post_tool_outcome(&wave, post_outcome, &mut events).await
551                        {
552                            return early;
553                        }
554
555                        if let Some(error) = error {
556                            if let RuntimeError::ToolExecutionCancelled { call_id, .. } = error {
557                                return Ok(finish_agent_loop_result(
558                                    self,
559                                    AgentLoopStatus::Cancelled {
560                                        diagnostic: tool_execution_cancelled_diagnostic(&call_id),
561                                    },
562                                    events,
563                                    model_turns_run,
564                                    None,
565                                )
566                                .await);
567                            }
568                            trace_loop_error(self.session_id().as_str(), model_turns_run, &error);
569                            return Err(AgentLoopError::new(events, error));
570                        }
571                    }
572
573                    next_input = Some(continuation_step_input());
574                }
575                StepOutcome::Pending(PendingLoopToolCall::Runtime(call)) => {
576                    if model_turns_run >= config.max_model_turns() {
577                        trace_loop_finish(
578                            self.session_id().as_str(),
579                            "blocked",
580                            model_turns_run,
581                            Some("max_model_turns_reached"),
582                        );
583                        return Ok(max_model_turns_blocked_result(
584                            self,
585                            &config,
586                            events,
587                            model_turns_run,
588                        )
589                        .await);
590                    }
591
592                    let wave = HookWaveContext {
593                        runtime: self,
594                        model_turn: model_turns_run,
595                        token: &loop_token,
596                        loop_permit: &loop_permit,
597                    };
598                    let allowed_calls =
599                        match run_driver_pre_tool_hooks(&wave, vec![call], &mut events).await {
600                            DriverPreHookOutcome::Proceed(calls) => calls,
601                            DriverPreHookOutcome::Finish(res) => return *res,
602                        };
603
604                    if let Some(allowed_call) = allowed_calls.into_iter().next() {
605                        tracing::info!(
606                            event = "runtime.tool.pending",
607                            session_id = self.session_id().as_str(),
608                            step_index = model_turns_run,
609                            tool_call_id = allowed_call.id().as_str(),
610                            tool_name = allowed_call.name().as_str(),
611                            "runtime loop saw pending tool"
612                        );
613                        tracing::info!(
614                            event = "runtime.tool.execute.start",
615                            session_id = self.session_id().as_str(),
616                            step_index = model_turns_run,
617                            tool_call_id = allowed_call.id().as_str(),
618                            tool_name = allowed_call.name().as_str(),
619                            "runtime loop tool execution start"
620                        );
621                        match self
622                            .execute_tool_call_with_active_permit(
623                                allowed_call.id(),
624                                ToolExecutionContext::new(loop_token.clone()),
625                                &loop_permit,
626                            )
627                            .await
628                        {
629                            Ok(execution_events) => {
630                                let post_outcome = run_post_runtime_tool_hooks(
631                                    &wave,
632                                    std::slice::from_ref(&allowed_call),
633                                    &execution_events,
634                                    None,
635                                )
636                                .await;
637                                if !tool_resolution_is_policy_denied(&execution_events) {
638                                    tracing::info!(
639                                        event = "runtime.tool.execute.finish",
640                                        session_id = self.session_id().as_str(),
641                                        step_index = model_turns_run,
642                                        tool_call_id = allowed_call.id().as_str(),
643                                        tool_name = allowed_call.name().as_str(),
644                                        status = tool_resolution_status(&execution_events),
645                                        diagnostic_code =
646                                            tool_resolution_diagnostic_code(&execution_events)
647                                                .unwrap_or(""),
648                                        "runtime loop tool execution finish"
649                                    );
650                                }
651                                events.extend(execution_events);
652                                if let Some(early) = handle_driver_post_tool_outcome(
653                                    &wave,
654                                    post_outcome,
655                                    &mut events,
656                                )
657                                .await
658                                {
659                                    return early;
660                                }
661                            }
662                            Err(RuntimeError::ToolExecutionCancelled { call_id, .. }) => {
663                                trace_loop_finish(
664                                    self.session_id().as_str(),
665                                    "cancelled",
666                                    model_turns_run,
667                                    Some("tool_execution_cancelled"),
668                                );
669                                return Ok(finish_agent_loop_result(
670                                    self,
671                                    AgentLoopStatus::Cancelled {
672                                        diagnostic: tool_execution_cancelled_diagnostic(&call_id),
673                                    },
674                                    events,
675                                    model_turns_run,
676                                    None,
677                                )
678                                .await);
679                            }
680                            Err(source) => {
681                                trace_loop_error(
682                                    self.session_id().as_str(),
683                                    model_turns_run,
684                                    &source,
685                                );
686                                return Err(AgentLoopError::new(events, source));
687                            }
688                        }
689                    }
690
691                    next_input = Some(continuation_step_input());
692                }
693            }
694        }
695    }
696
697    /// Starts a bounded runtime-owned agent loop and returns live events.
698    ///
699    /// This has the same loop semantics as [`Runtime::run_agent_loop`], but it
700    /// returns an [`AgentRun`] handle that yields each observed
701    /// [`merry_core::RuntimeJournalEvent`] as soon as the underlying step or tool execution
702    /// produces it. Dropping the handle cancels the loop token and aborts the
703    /// loop producer as a final cleanup guard.
704    pub fn run_agent_loop_stream(
705        &self,
706        input: StepInput,
707        context: StepContext,
708        config: AgentLoopConfig,
709    ) -> Result<AgentRun, RuntimeError> {
710        let (parent_token, generation_config, context_contract) = context.into_parts();
711        let config = config
712            .merge_context_final_output_contract(context_contract)
713            .map_err(|source| RuntimeError::AgentLoopConfig { source })?;
714        let loop_permit = self.acquire_active_step_permit()?;
715        let loop_token = parent_token.child_token();
716        let producer_token = loop_token.clone();
717        let (sender, receiver) = mpsc::channel(16);
718        let (result_sender, result_receiver) = oneshot::channel();
719        let (bridge_sender, bridge_receiver) = mpsc::channel(1);
720        let bridge_resolution_epoch = Arc::new(AtomicU64::new(0));
721        let producer_bridge_resolution_epoch = Arc::clone(&bridge_resolution_epoch);
722        let (hook_sender, hook_receiver) = mpsc::channel(1);
723        let hook_resolution_epoch = Arc::new(AtomicU64::new(0));
724        let producer_hook_resolution_epoch = Arc::clone(&hook_resolution_epoch);
725        let runtime = self.clone();
726        let session_id = self.session_id().clone();
727        let producer_handle = tokio::spawn(async move {
728            let result = run_agent_loop_stream_producer(AgentLoopStreamProducer::new(
729                AgentLoopStreamProducerInput {
730                    runtime,
731                    input,
732                    loop_token: producer_token,
733                    generation_config,
734                    config,
735                    loop_permit,
736                    sender,
737                    bridge_receiver,
738                    bridge_resolution_epoch: producer_bridge_resolution_epoch,
739                    hook_receiver,
740                    hook_resolution_epoch: producer_hook_resolution_epoch,
741                },
742            ))
743            .await;
744            let _ = result_sender.send(result);
745        });
746
747        Ok(AgentRun::new(
748            session_id,
749            ReceiverStream::new(receiver),
750            loop_token,
751            producer_handle,
752            result_receiver,
753            bridge_sender,
754            bridge_resolution_epoch,
755            hook_sender,
756            hook_resolution_epoch,
757        ))
758    }
759}
760
761fn drain_subagent_events(
762    receiver: &mut tokio::sync::broadcast::Receiver<merry_core::RuntimeJournalEvent>,
763    events: &mut Vec<merry_core::RuntimeJournalEvent>,
764) {
765    loop {
766        match receiver.try_recv() {
767            Ok(event) => events.push(event),
768            Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,
769            Err(
770                tokio::sync::broadcast::error::TryRecvError::Empty
771                | tokio::sync::broadcast::error::TryRecvError::Closed,
772            ) => return,
773        }
774    }
775}
776
777enum DriverPreHookOutcome {
778    Proceed(Vec<merry_core::PendingToolCall>),
779    Finish(Box<Result<AgentLoopResult, AgentLoopError>>),
780}
781
782async fn run_driver_pre_tool_hooks(
783    wave: &HookWaveContext<'_>,
784    calls: Vec<merry_core::PendingToolCall>,
785    events: &mut Vec<merry_core::RuntimeJournalEvent>,
786) -> DriverPreHookOutcome {
787    match run_pre_tool_wave_hooks(wave, calls, false, None).await {
788        Ok(PreToolWaveOutcome::Proceed {
789            pre_events,
790            allowed_calls,
791        }) => {
792            events.extend(pre_events);
793            DriverPreHookOutcome::Proceed(allowed_calls)
794        }
795        Ok(PreToolWaveOutcome::StoppedByHook {
796            pre_events,
797            reason,
798            final_output,
799        }) => {
800            events.extend(pre_events);
801            let settled = match wave
802                .runtime
803                .settle_pending_tool_calls_stopped_by_hook_with_active_permit(
804                    &reason,
805                    wave.loop_permit,
806                )
807                .await
808            {
809                Ok(settled) => settled,
810                Err(source) => {
811                    return DriverPreHookOutcome::Finish(Box::new(Err(AgentLoopError::new(
812                        std::mem::take(events),
813                        source,
814                    ))));
815                }
816            };
817            events.extend(settled);
818            DriverPreHookOutcome::Finish(Box::new(Ok(finish_agent_loop_result(
819                wave.runtime,
820                AgentLoopStatus::StoppedByHook {
821                    hook_point: HookPoint::BeforeToolCall,
822                    reason,
823                },
824                std::mem::take(events),
825                wave.model_turn,
826                final_output,
827            )
828            .await)))
829        }
830        Err(RuntimeError::HookCancelled { .. }) => {
831            let _ = wave
832                .runtime
833                .settle_pending_tool_calls_stopped_by_hook_with_active_permit(
834                    "cancelled during before_tool_call hook",
835                    wave.loop_permit,
836                )
837                .await;
838            DriverPreHookOutcome::Finish(Box::new(Ok(finish_agent_loop_result(
839                wave.runtime,
840                AgentLoopStatus::Cancelled {
841                    diagnostic: crate::agent_loop::agent_loop_cancelled_diagnostic(),
842                },
843                std::mem::take(events),
844                wave.model_turn,
845                None,
846            )
847            .await)))
848        }
849        Err(source) => {
850            let _ = wave
851                .runtime
852                .settle_pending_tool_calls_stopped_by_hook_with_active_permit(
853                    "failed during before_tool_call hook",
854                    wave.loop_permit,
855                )
856                .await;
857            trace_loop_error(wave.runtime.session_id().as_str(), wave.model_turn, &source);
858            DriverPreHookOutcome::Finish(Box::new(Err(AgentLoopError::new(
859                std::mem::take(events),
860                source,
861            ))))
862        }
863    }
864}
865
866async fn handle_driver_post_tool_outcome(
867    wave: &HookWaveContext<'_>,
868    post_outcome: Result<PostRuntimeToolOutcome, RuntimeError>,
869    events: &mut Vec<merry_core::RuntimeJournalEvent>,
870) -> Option<Result<AgentLoopResult, AgentLoopError>> {
871    match post_outcome {
872        Ok(PostRuntimeToolOutcome::Continue) => None,
873        Ok(PostRuntimeToolOutcome::StoppedByHook {
874            reason,
875            final_output,
876        }) => {
877            let settled = match wave
878                .runtime
879                .settle_pending_tool_calls_stopped_by_hook_with_active_permit(
880                    &reason,
881                    wave.loop_permit,
882                )
883                .await
884            {
885                Ok(settled) => settled,
886                Err(source) => {
887                    return Some(Err(AgentLoopError::new(std::mem::take(events), source)));
888                }
889            };
890            events.extend(settled);
891            Some(Ok(finish_agent_loop_result(
892                wave.runtime,
893                AgentLoopStatus::StoppedByHook {
894                    hook_point: HookPoint::AfterToolCall,
895                    reason,
896                },
897                std::mem::take(events),
898                wave.model_turn,
899                final_output,
900            )
901            .await))
902        }
903        Err(RuntimeError::HookCancelled { .. }) => Some(Ok(finish_agent_loop_result(
904            wave.runtime,
905            AgentLoopStatus::Cancelled {
906                diagnostic: crate::agent_loop::agent_loop_cancelled_diagnostic(),
907            },
908            std::mem::take(events),
909            wave.model_turn,
910            None,
911        )
912        .await)),
913        Err(source) => {
914            trace_loop_error(wave.runtime.session_id().as_str(), wave.model_turn, &source);
915            Some(Err(AgentLoopError::new(std::mem::take(events), source)))
916        }
917    }
918}