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