Skip to main content

aither_agent/
agent.rs

1//! Core agent implementation.
2//!
3//! The `Agent` struct is the main entry point for the agent framework.
4//! It manages the context window, forks compaction in the background, and
5//! handles tool execution in an agent-controlled loop.
6
7use std::collections::VecDeque;
8use std::ops::ControlFlow;
9use std::pin::Pin;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicU64, Ordering};
12use std::task::Poll;
13use std::time::{Duration, Instant};
14
15#[cfg(feature = "skills")]
16use crate::context::SkillCatalogEntry;
17use crate::{
18    checkpoint::{AgentCheckpoint, Checkpoints},
19    compaction_state::CompactionState,
20    config::AgentConfig,
21    context::{
22        AnyContextSource, AnyFileReferences, AnyLiveSource, AttachmentRef, Block, CacheLifetime,
23        CompactionFork, CompletedCompaction, Context, ContextBlock, ContextBudget, HandoffDocument,
24        Moment, PendingCompaction, Placement, PrefixChain, PrefixRewrites, PromptCache,
25        PromptPrefix, SourceId,
26        recovery::{SpillLimits, clean_for_recovery},
27        restore_context,
28    },
29    context_window::{ContextWindowMetrics, ContextWindowPhase, ContextWindowSnapshot},
30    error::{AgentError, ToolPanic},
31    event::{
32        AgentEvent, AgentPath, BlockId, CheckpointReason, CompactionOutcome, CompactionTrigger,
33        InjectionKind, OutputKind, PauseId, RequestId, RequestOutcome, RunId, RunOutcome, RunPause,
34        TimedEvent, ToolOrigin, ToolVerdict,
35    },
36    hook::{
37        AfterTool, Hooks, RequestCx, StopCx, StopDecision, ToolDecision, ToolInvocation,
38        ToolOutcome, TurnBoundaryAction, TurnBoundaryContext,
39    },
40    request_parameters::WithParameters,
41    tools::AgentTools,
42};
43use aither_core::{
44    LanguageModel,
45    llm::{
46        AnyApprover, Approval, ApprovalRequest, Approver, ApproverFailure, Attachment,
47        CancelSignal, Canceller, Event, LLMRequest, Message, ReasoningState, RetryPolicy, Role,
48        TokenCounting, ToolCall, ToolCallId,
49        model::{Ability, Parameters, Profile as ModelProfile},
50        tool::{Progress, ProgressSink},
51    },
52};
53use askama::Template;
54use futures_core::Stream;
55use futures_lite::StreamExt;
56use sha2::{Digest, Sha256};
57use std::collections::HashSet;
58use std::path::PathBuf;
59
60/// Which of the two futures raced during a turn finished first.
61enum TurnStep {
62    /// The model turn completed.
63    Turn(Result<ModelTurn, AgentError>),
64    /// The forked compaction landed while the turn was still running.
65    Compacted(Result<CompletedCompaction, crate::context::CompactionError>),
66}
67
68/// The number of characters an assembled request renders to, tool calls
69/// and tool definitions included — the provider counts all of them.
70fn request_chars(
71    messages: &[Message],
72    definitions: &[aither_core::llm::tool::ToolDefinition],
73) -> usize {
74    let messages: usize = messages
75        .iter()
76        .map(|message| {
77            let calls: usize = message
78                .tool_calls()
79                .iter()
80                .map(|call| call.name.len() + call.arguments.to_string().len())
81                .sum();
82            message.content().len() + calls
83        })
84        .sum();
85    let definitions: usize = definitions
86        .iter()
87        .map(|definition| {
88            definition.name().len()
89                + definition.description().len()
90                + definition.arguments_openai_schema().to_string().len()
91        })
92        .sum();
93    messages + definitions
94}
95
96struct ModelTurn {
97    response_text: String,
98    tool_calls: Vec<ToolCall>,
99    /// Opaque provider reasoning produced this turn, in the order it arrived.
100    ///
101    /// Replayed on the next request: providers that verify their own reasoning
102    /// reject a turn whose blocks were reordered or partially dropped.
103    reasoning: Vec<ReasoningState>,
104    /// What the provider reported the request used, if it did.
105    usage: Option<aither_core::llm::Usage>,
106    malformed_function_call: bool,
107}
108
109/// Streams agent events to the consumer as they happen.
110///
111/// Wraps an unbounded channel: emitting never blocks, and events emitted
112/// after the consumer dropped the stream are discarded.
113#[derive(Clone)]
114struct EventSink {
115    sender: async_channel::Sender<TimedEvent>,
116    /// The agent the sink emits for, stamped on every event.
117    agent: AgentPath,
118    /// Where the run records its checkpoints for [`Run::checkpoints`].
119    checkpoints: Checkpoints,
120}
121
122/// What the loop waits on while tools run.
123enum ToolStep {
124    Finished(Option<ToolExecutionResult>),
125    Child(Option<TimedEvent>),
126}
127
128impl EventSink {
129    /// Puts an event another agent stamped on this stream as it is.
130    fn forward(&self, event: TimedEvent) {
131        let _ = self.sender.try_send(event);
132    }
133
134    fn emit(&self, event: AgentEvent) {
135        let _ = self.sender.try_send(TimedEvent {
136            at: jiff::Timestamp::now(),
137            agent: self.agent.clone(),
138            event,
139        });
140    }
141}
142
143/// Cancels a [`Run`] from outside, such as from another task while the run is
144/// being driven. Cloneable and cheap.
145#[derive(Debug, Clone, Default)]
146pub struct CancelHandle(Arc<Canceller>);
147
148impl CancelHandle {
149    /// Cancels the run: it stops at its next await point and ends with
150    /// [`RunOutcome::Cancelled`]. Calling it again, or after the run ended,
151    /// does nothing.
152    pub fn cancel(&self) {
153        self.0.cancel();
154    }
155
156    /// Whether the run was cancelled.
157    #[must_use]
158    pub fn is_cancelled(&self) -> bool {
159        self.0.is_cancelled()
160    }
161
162    pub(crate) fn signal(&self) -> CancelSignal {
163        self.0.signal()
164    }
165}
166
167/// One run of an [`Agent`], from [`Agent::run`] or [`Agent::resume`].
168///
169/// A run does nothing until [`drive`](Self::drive) consumes it. Driving hands
170/// each event to the caller's handler while the run itself keeps going, so a
171/// handler that waits on something the run holds lets the run release it.
172///
173/// A run ends with exactly one [`AgentEvent::RunEnded`]: cancelling it with
174/// [`cancel`](Self::cancel) or a [`CancelHandle`] ends it with
175/// [`RunOutcome::Cancelled`], and so does dropping it unfinished (though a
176/// dropped run has no consumer left to read the event).
177#[must_use = "a run does nothing until it is driven"]
178pub struct Run<F> {
179    /// The run's state machine spans every turn and is tens of kilobytes;
180    /// boxed so a `Run` moves into the caller's future without copying it.
181    body: Pin<Box<F>>,
182    events: async_channel::Receiver<TimedEvent>,
183    cancel: CancelHandle,
184    checkpoints: Checkpoints,
185}
186
187impl<F> std::fmt::Debug for Run<F> {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        f.debug_struct("Run")
190            .field("queued_events", &self.events.len())
191            .field("cancelled", &self.cancel.is_cancelled())
192            .finish_non_exhaustive()
193    }
194}
195
196impl<F> Run<F>
197where
198    F: Future<Output = Result<(), AgentError>>,
199{
200    fn new(agent: AgentPath, start: impl FnOnce(EventSink, CancelSignal) -> F) -> Self {
201        let (sender, events) = async_channel::unbounded();
202        let cancel = CancelHandle::default();
203        let checkpoints = Checkpoints::default();
204        // The run owns the sink and drops it as it finishes.
205        let sink = EventSink {
206            sender,
207            agent,
208            checkpoints: checkpoints.clone(),
209        };
210        Self {
211            body: Box::pin(start(sink, cancel.signal())),
212            events,
213            cancel,
214            checkpoints,
215        }
216    }
217
218    /// A handle to the run's checkpoints, usable after [`drive`](Self::drive)
219    /// took the run.
220    ///
221    /// The run holds the agent, so the embedder cannot export from it
222    /// mid-run; the run records a checkpoint at every
223    /// [`AgentEvent::Checkpoint`] it emits, before the event is queued, and
224    /// the handle reads the newest from the event handler. An embedder
225    /// persists it there, so a crash mid-run loses no completed turn.
226    #[must_use]
227    pub fn checkpoints(&self) -> Checkpoints {
228        self.checkpoints.clone()
229    }
230
231    /// Cancels the run. Driving a cancelled run ends it at once with
232    /// [`RunOutcome::Cancelled`].
233    pub fn cancel(&self) {
234        self.cancel.cancel();
235    }
236
237    /// A handle that cancels this run after [`drive`](Self::drive) took it.
238    #[must_use]
239    pub fn cancel_handle(&self) -> CancelHandle {
240        self.cancel.clone()
241    }
242
243    /// Runs to the end, handing each event to `handler` in the order the run
244    /// emitted it, one call at a time.
245    ///
246    /// The run is polled together with every handler call, so it keeps
247    /// making progress while the handler awaits; events it emits meanwhile
248    /// queue for the next call. The run stays on the caller's task.
249    ///
250    /// `state` is what the handler works on, typically `&mut` borrows of the
251    /// caller's locals: each call takes it and returns it in
252    /// [`ControlFlow::Continue`] for the next. Threading it through, rather
253    /// than capturing it in an async closure, keeps the driven future `Send`
254    /// whenever the state is. A handler returns [`ControlFlow::Break`] to
255    /// stop: the run is cancelled and dropped, its queued events are
256    /// discarded, and `drive` returns that `Break`. Otherwise `drive` returns
257    /// the state in `Continue` once the run has finished and its every event
258    /// was handled.
259    ///
260    /// `stop` cancels the run from outside, such as on a user's request: it
261    /// is polled, ahead of the run and its next event, only while no handler
262    /// call is in progress, so a call already running always finishes. Once
263    /// it completes, the run is cancelled and driven to its end, so the
264    /// handler still sees the run's [`RunEnded`](AgentEvent::RunEnded) with
265    /// [`RunOutcome::Cancelled`], and `drive` returns the value in `Break`. A
266    /// caller with nothing to stop on passes [`std::future::pending`].
267    ///
268    /// # Errors
269    ///
270    /// The run's error, after the handler has seen every event emitted
271    /// before it.
272    pub async fn drive<S, B, H>(
273        self,
274        mut state: S,
275        stop: impl Future<Output = B>,
276        mut handler: impl FnMut(S, TimedEvent) -> H,
277    ) -> Result<ControlFlow<B, S>, AgentError>
278    where
279        H: Future<Output = ControlFlow<B, S>>,
280    {
281        let Self {
282            body: mut run,
283            events,
284            cancel,
285            ..
286        } = self;
287        futures_lite::pin!(events);
288        futures_lite::pin!(stop);
289        let mut outcome = None;
290        let mut stopped = None;
291        loop {
292            // Read before the closure: borrowing `stopped` across the await
293            // would make the future need `B: Sync`.
294            let stopping = stopped.is_none();
295            let next = std::future::poll_fn(|cx| {
296                if stopping && let Poll::Ready(value) = stop.as_mut().poll(cx) {
297                    return Poll::Ready(RunStep::Stopped(value));
298                }
299                poll_run(run.as_mut(), &mut outcome, cx);
300                if let Some(result) = outcome.take() {
301                    // Finished: what it emitted is all queued.
302                    return Poll::Ready(match events.try_recv() {
303                        Ok(event) => {
304                            outcome = Some(result);
305                            RunStep::Event(event)
306                        }
307                        Err(_) => RunStep::Finished(result),
308                    });
309                }
310                match Stream::poll_next(events.as_mut(), cx) {
311                    Poll::Ready(Some(event)) => Poll::Ready(RunStep::Event(event)),
312                    // Every sink is gone but the run has not returned; its
313                    // own wake-up reports the end.
314                    Poll::Ready(None) | Poll::Pending => Poll::Pending,
315                }
316            })
317            .await;
318            let event = match next {
319                RunStep::Event(event) => event,
320                RunStep::Finished(result) => {
321                    result?;
322                    return Ok(
323                        stopped.map_or_else(|| ControlFlow::Continue(state), ControlFlow::Break)
324                    );
325                }
326                RunStep::Stopped(value) => {
327                    stopped = Some(value);
328                    cancel.cancel();
329                    continue;
330                }
331            };
332            let call = handler(state, event);
333            futures_lite::pin!(call);
334            let flow = std::future::poll_fn(|cx| {
335                poll_run(run.as_mut(), &mut outcome, cx);
336                call.as_mut().poll(cx)
337            })
338            .await;
339            state = match flow {
340                ControlFlow::Continue(state) => state,
341                ControlFlow::Break(value) => {
342                    cancel.cancel();
343                    return Ok(ControlFlow::Break(value));
344                }
345            };
346        }
347    }
348}
349
350/// What [`Run::drive`] waits for between handler calls.
351enum RunStep<B> {
352    Event(TimedEvent),
353    Finished(Result<(), AgentError>),
354    Stopped(B),
355}
356
357/// Polls `run` unless it already finished, recording its result.
358fn poll_run<F>(
359    run: Pin<&mut F>,
360    outcome: &mut Option<Result<(), AgentError>>,
361    cx: &mut std::task::Context<'_>,
362) where
363    F: Future<Output = Result<(), AgentError>>,
364{
365    if outcome.is_none()
366        && let Poll::Ready(result) = run.poll(cx)
367    {
368        *outcome = Some(result);
369    }
370}
371
372/// How the loop of a run ended, short of an error.
373enum LoopEnd {
374    /// The model answered and nothing held the run, on turn `turn`.
375    Answered { final_text: String, turn: usize },
376    /// The run stopped for a reason that needs the embedder.
377    Paused(RunPause),
378}
379
380/// What the loop of one run works with.
381#[derive(Clone, Copy)]
382struct RunCx<'a> {
383    events: &'a EventSink,
384    cancel: &'a CancelSignal,
385    run: &'a RunId,
386}
387
388enum TurnControl {
389    Continue,
390    Break(LoopEnd),
391}
392
393/// A response stream that ended with an error instead of finishing.
394struct BrokenStream {
395    error: AgentError,
396    /// Whether an event arrived before the error: the stream had opened.
397    opened: bool,
398    /// What the provider reported the broken request used, if it did.
399    usage: Option<aither_core::llm::Usage>,
400}
401
402/// A finished tool call, waiting to be paired with its call in the context.
403#[derive(Debug)]
404pub struct FinishedToolCall {
405    id: String,
406    outcome: ToolOutcome,
407    /// Context an `after_tool` hook appended, to follow the turn's results.
408    appended: Option<String>,
409}
410
411pub type ToolExecutionResult = Result<FinishedToolCall, AgentError>;
412
413/// One tool call on its way through the hooks and the tool.
414struct ToolRun<'a, H> {
415    hooks: &'a H,
416    tools: &'a AgentTools,
417    events: &'a EventSink,
418    cancel: &'a CancelSignal,
419    approver: Option<&'a AnyApprover>,
420    identity: aither_core::llm::CallIdentity,
421    turn: usize,
422    message_count: usize,
423}
424
425impl<H: Hooks> ToolRun<'_, H> {
426    fn decided(&self, decision: ToolVerdict) {
427        self.events.emit(AgentEvent::ToolCallDecided {
428            call: self.identity.call().clone(),
429            decision,
430        });
431    }
432
433    /// What the tool is given besides its arguments.
434    fn context(&self) -> aither_core::llm::ToolContext {
435        let mut cx = aither_core::llm::ToolContext::with_progress(ProgressEvents {
436            events: self.events.clone(),
437            call: self.identity.call().clone(),
438        })
439        .with_identity(self.identity.clone())
440        .with_cancellation(self.cancel.clone());
441        if let Some(approver) = self.approver {
442            cx = cx.with_approver(approver.clone());
443        }
444        cx
445    }
446
447    /// Puts `request` to the approver.
448    async fn ask(&self, request: ApprovalRequest) -> Result<Approval, AgentError> {
449        let kind = request.kind().clone();
450        let Some(approver) = self.approver else {
451            return Err(AgentError::Approval(Arc::new(
452                aither_core::llm::ApprovalError::NoApprover { kind },
453            )));
454        };
455        let request = if request.call().is_some() {
456            request
457        } else {
458            request.with_call(self.identity.clone())
459        };
460        approver.approve(request).await.map_err(|failure| {
461            AgentError::Approval(Arc::new(aither_core::llm::ApprovalError::Failed {
462                kind,
463                failure,
464            }))
465        })
466    }
467
468    async fn execute(self, call: &ToolCall) -> ToolExecutionResult {
469        let invocation = ToolInvocation {
470            call: &self.identity,
471            name: &call.name,
472            arguments: &call.arguments,
473            turn: self.turn,
474            message_count: self.message_count,
475        };
476        let mut arguments = call.arguments.clone();
477        let mut denied = None;
478        match self.hooks.before_tool(&invocation).await {
479            ToolDecision::Allow => self.decided(ToolVerdict::Allowed),
480            ToolDecision::Deny(reason) => {
481                self.decided(ToolVerdict::Denied {
482                    reason: reason.clone(),
483                });
484                denied = Some(reason);
485            }
486            ToolDecision::Rewrite(rewritten) => {
487                self.decided(ToolVerdict::Rewritten);
488                arguments = rewritten;
489            }
490            ToolDecision::Ask(request) => {
491                self.decided(ToolVerdict::AwaitingApproval);
492                match self.ask(request).await? {
493                    Approval::Approved => self.decided(ToolVerdict::Allowed),
494                    Approval::Denied { reason } => {
495                        self.decided(ToolVerdict::Denied {
496                            reason: reason.clone(),
497                        });
498                        denied = Some(reason);
499                    }
500                }
501            }
502            ToolDecision::Abort(reason) => {
503                return Err(AgentError::HookRejected {
504                    hook: "before_tool".into(),
505                    reason,
506                });
507            }
508        }
509
510        let (result, duration) = if let Some(reason) = denied {
511            (
512                Ok(aither_core::llm::ToolResult::error(reason)),
513                Duration::ZERO,
514            )
515        } else {
516            let start = Instant::now();
517            // A panic from the tool ends only this call: it becomes the
518            // call's failed result, so the other calls of the turn finish and
519            // the run goes on. The panic hook has already run by the time the
520            // unwind is caught.
521            let result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
522                self.tools
523                    .call(&call.name, &arguments.to_string(), self.context())
524                    .await
525            }))
526            .await
527            .unwrap_or_else(|payload| {
528                let panic = ToolPanic::caught(&call.name, payload.as_ref());
529                tracing::error!(tool = %panic.name, message = %panic.message, "tool panicked");
530                Err(panic.into())
531            });
532            (result, start.elapsed())
533        };
534        let mut outcome = ToolOutcome {
535            call: self.identity.clone(),
536            name: call.name.clone(),
537            arguments,
538            result,
539            duration,
540        };
541        let mut appended = None;
542        match self.hooks.after_tool(&outcome).await {
543            AfterTool::Keep => {}
544            AfterTool::Replace(replacement) => outcome.result = Ok(replacement),
545            AfterTool::Append(context) => appended = Some(context),
546            AfterTool::Abort(reason) => {
547                return Err(AgentError::HookRejected {
548                    hook: "after_tool".into(),
549                    reason,
550                });
551            }
552        }
553        self.events.emit(AgentEvent::ToolCallEnded {
554            call: self.identity.call().clone(),
555            result: outcome.for_model(),
556        });
557        Ok(FinishedToolCall {
558            id: call.id.clone(),
559            outcome,
560            appended,
561        })
562    }
563}
564
565/// Reports a running tool's progress as events.
566struct ProgressEvents {
567    events: EventSink,
568    call: ToolCallId,
569}
570
571impl ProgressSink for ProgressEvents {
572    async fn report(&mut self, progress: Progress) {
573        self.events.emit(AgentEvent::ToolProgress {
574            call: self.call.clone(),
575            progress,
576        });
577    }
578}
579
580/// Wraps the embedder's approver so a wait for an answer is visible: a
581/// [`Paused`](AgentEvent::Paused) goes out only when the answer is not there
582/// on the first poll, and a [`Resumed`](AgentEvent::Resumed) when it comes.
583struct PausingApprover {
584    inner: AnyApprover,
585    events: EventSink,
586    pauses: Arc<AtomicU64>,
587}
588
589impl Approver for PausingApprover {
590    async fn approve(&self, request: ApprovalRequest) -> Result<Approval, ApproverFailure> {
591        let call = request.call().map(|identity| identity.call().clone());
592        let kind = request.kind().clone();
593        let subject = request.subject().to_string();
594        let answer = self.inner.approve(request);
595        futures_lite::pin!(answer);
596        if let Some(settled) = futures_lite::future::poll_once(answer.as_mut()).await {
597            return settled;
598        }
599        let pause = PauseId::new(self.pauses.fetch_add(1, Ordering::Relaxed));
600        self.events.emit(AgentEvent::Paused {
601            pause,
602            call,
603            kind,
604            subject,
605        });
606        let settled = answer.await;
607        self.events.emit(AgentEvent::Resumed { pause });
608        settled
609    }
610}
611
612/// Ends the run's event stream with [`RunOutcome::Cancelled`] when the run
613/// is dropped before it ended itself.
614struct RunEndGuard {
615    events: EventSink,
616    run: RunId,
617    ended: bool,
618}
619
620impl RunEndGuard {
621    fn end(&mut self, outcome: RunOutcome) {
622        self.ended = true;
623        self.events.emit(AgentEvent::RunEnded {
624            run: self.run.clone(),
625            outcome,
626        });
627    }
628}
629
630impl Drop for RunEndGuard {
631    fn drop(&mut self) {
632        if !self.ended {
633            self.end(RunOutcome::Cancelled);
634        }
635    }
636}
637
638/// The blocks of one response, as they stream in.
639struct Response<'a> {
640    events: &'a EventSink,
641    request: RequestId,
642    text_chunks: Vec<String>,
643    tool_calls: Vec<ToolCall>,
644    reasoning: Vec<ReasoningState>,
645    /// The block open now, and the id the next one gets.
646    open: Option<(BlockId, OutputKind)>,
647    next_block: u32,
648    usage: Option<aither_core::llm::Usage>,
649}
650
651impl<'a> Response<'a> {
652    const fn new(events: &'a EventSink, request: RequestId) -> Self {
653        Self {
654            events,
655            request,
656            text_chunks: Vec::new(),
657            tool_calls: Vec::new(),
658            reasoning: Vec::new(),
659            open: None,
660            next_block: 0,
661            usage: None,
662        }
663    }
664
665    /// Streams `text` into a block of `kind`, closing the open block when it
666    /// is of another kind.
667    fn delta(&mut self, kind: OutputKind, text: String) {
668        let block = match self.open {
669            Some((block, open)) if open == kind => block,
670            _ => {
671                self.end_block();
672                let block = BlockId::new(self.next_block);
673                self.next_block += 1;
674                self.open = Some((block, kind));
675                block
676            }
677        };
678        self.events.emit(AgentEvent::BlockDelta {
679            request: self.request,
680            block,
681            kind,
682            text,
683        });
684    }
685
686    fn end_block(&mut self) {
687        if let Some((block, kind)) = self.open.take() {
688            self.events.emit(AgentEvent::BlockEnded {
689                request: self.request,
690                block,
691                kind,
692            });
693        }
694    }
695}
696
697/// What a model event asks the stream loop to do.
698enum ModelEventAction {
699    Continue,
700    RetryMalformed,
701}
702
703fn handle_model_event(
704    cache_stats: &mut crate::CacheStats,
705    budget: &mut ContextBudget,
706    event: Result<Event, AgentError>,
707    response: &mut Response<'_>,
708) -> Result<ModelEventAction, AgentError> {
709    match event {
710        Ok(Event::Text(text)) => {
711            response.text_chunks.push(text.clone());
712            response.delta(OutputKind::Text, text);
713            Ok(ModelEventAction::Continue)
714        }
715        Ok(Event::Reasoning(reasoning)) => {
716            response.delta(OutputKind::Reasoning, reasoning);
717            Ok(ModelEventAction::Continue)
718        }
719        Ok(Event::ToolCallDelta {
720            id,
721            name,
722            arguments_fragment,
723        }) => {
724            response.end_block();
725            response.events.emit(AgentEvent::ToolCallDelta {
726                call: ToolCallId::new(id),
727                name,
728                arguments_fragment,
729            });
730            Ok(ModelEventAction::Continue)
731        }
732        Ok(Event::ToolCall(call)) => {
733            response.end_block();
734            response.tool_calls.push(call);
735            Ok(ModelEventAction::Continue)
736        }
737        // State, unlike Reasoning, is not for the reader: it is collected so
738        // the next request can hand it back to the provider.
739        Ok(Event::ReasoningState(state)) => {
740            response.reasoning.push(state);
741            Ok(ModelEventAction::Continue)
742        }
743        Ok(Event::BuiltInToolCall { id, tool, detail }) => {
744            response.end_block();
745            if !detail.is_empty() {
746                response
747                    .text_chunks
748                    .push(format_builtin_tool_result(&tool, &detail));
749            }
750            let call = ToolCallId::new(id);
751            response.events.emit(AgentEvent::ToolCallStarted {
752                call,
753                name: tool,
754                arguments: serde_json::Value::String(detail),
755                origin: ToolOrigin::Hosted,
756            });
757            Ok(ModelEventAction::Continue)
758        }
759        Ok(Event::BuiltInToolResult { id, tool, result }) => {
760            response.end_block();
761            response
762                .text_chunks
763                .push(format_builtin_tool_result(&tool, &result));
764            response.events.emit(AgentEvent::ToolCallEnded {
765                call: ToolCallId::new(id),
766                result: aither_core::llm::ToolResult::text(result),
767            });
768            Ok(ModelEventAction::Continue)
769        }
770        Ok(Event::Usage(usage)) => {
771            cache_stats.record(&usage);
772            // The provider just counted the prompt it received; that is the
773            // only honest measure of how much window the window costs.
774            budget.calibrate(&usage);
775            response.usage = Some(usage);
776            Ok(ModelEventAction::Continue)
777        }
778        Err(AgentError::Llm { message, .. }) if message.contains("malformed function call") => {
779            tracing::warn!("Model generated malformed function call, retrying...");
780            Ok(ModelEventAction::RetryMalformed)
781        }
782        Err(error) => Err(error),
783    }
784}
785
786fn ensure_non_empty_tool_call_ids(
787    tool_calls: &[ToolCall],
788    response_text: &str,
789) -> Result<(), AgentError> {
790    if tool_calls.iter().all(|call| !call.id.trim().is_empty()) {
791        return Ok(());
792    }
793    tracing::error!(
794        response_text,
795        ?tool_calls,
796        "provider emitted tool call with empty id"
797    );
798    let tool_calls_text = tool_calls
799        .iter()
800        .map(|call| format!("{} ({})", call.name, call.id))
801        .collect::<Vec<_>>()
802        .join(", ");
803    Err(AgentError::llm_local(format!(
804        "provider emitted tool call with empty id; response_text={response_text:?}; tool_calls=[{tool_calls_text}]"
805    )))
806}
807
808/// The blocks collected into a request's tail, each with the context source
809/// that returned it, so a commit reaches only that source.
810#[derive(Debug, Default)]
811struct RenderedTail {
812    blocks: Vec<Block>,
813    /// The index into the agent's context sources of the source that returned
814    /// the block at the same position; `None` for a hook's block.
815    sources: Vec<Option<usize>>,
816}
817
818impl std::ops::Deref for RenderedTail {
819    type Target = [Block];
820
821    fn deref(&self) -> &[Block] {
822        &self.blocks
823    }
824}
825
826/// Result of a compaction operation.
827#[derive(Debug, Clone)]
828#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
829pub struct CompactResult {
830    /// Number of messages that were compacted.
831    pub messages_compacted: usize,
832    /// Number of messages remaining (preserved).
833    pub messages_remaining: usize,
834    /// The generated summary.
835    pub summary: String,
836}
837
838/// A stop hook's reminder, as the model reads it.
839#[derive(Template)]
840#[template(path = "system_reminder.txt", escape = "none")]
841struct SystemReminderTemplate {
842    content: String,
843}
844
845/// The result of a tool call the run left unfinished.
846#[derive(Template)]
847#[template(path = "tool_call_cancelled.txt", escape = "none")]
848struct CancelledToolCallTemplate<'a> {
849    tool: &'a str,
850}
851
852/// An autonomous agent that runs a conversation with a language model,
853/// executing the tool calls it makes.
854///
855/// The agent manages conversation context, handles tool execution in a loop,
856/// and applies context compression when needed. Unlike the raw `LanguageModel`
857/// trait which only emits events, the agent handles the full tool execution
858/// cycle.
859///
860/// # Type Parameters
861///
862/// - `M`: The conversation model
863/// - `H`: Composed hooks for customizing behavior (defaults to `()`)
864/// - `C`: The optional compaction model, see
865///   [`AgentBuilder::compaction_model`](crate::builder::AgentBuilder::compaction_model)
866///   (defaults to `M`; unused while none is set)
867/// - `Schema`: the [`HandoffSchema`](crate::HandoffSchema) every compaction
868///   asks the model for; [`HandoffDocument`] unless the builder's
869///   [`handoff`](crate::AgentBuilder::handoff) sets another.
870///
871/// Compaction runs on the conversation model, so it reads the conversation's
872/// prompt cache, unless a compaction model is set.
873///
874/// # Example
875///
876/// ```rust,ignore
877/// let agent = Agent::new(claude);
878/// let response = agent.query("What is 2+2?").await?;
879/// ```
880#[derive(Debug)]
881#[allow(clippy::struct_excessive_bools)]
882pub struct Agent<M, H = (), C = M, Schema = HandoffDocument> {
883    /// The conversation model, behind an Arc so a forked compaction can own
884    /// it while the run continues.
885    pub(crate) model: Arc<M>,
886
887    /// The model compaction runs on, when it is not the conversation's own.
888    ///
889    /// A different model cannot read the conversation's prompt cache, so with
890    /// one set compaction is never run early to catch the cache warm (see
891    /// [`Agent::compact_when_idle`]), and an idle gap past the cache lifetime
892    /// reassembles the window instead. Its requests carry its own parameters.
893    pub(crate) compaction_model: Option<WithParameters<Arc<C>>>,
894
895    /// The parameters of the requests sent on the model.
896    pub(crate) parameters: Box<Parameters>,
897
898    /// The request-level reasoning effort the agent's own requests carry.
899    pub(crate) effort: crate::effort::EffortAnchor,
900
901    /// Whether the idle compaction already ran since the last request, so one
902    /// idle gap compacts once.
903    pub(crate) idle_compacted: bool,
904
905    /// Registered tools.
906    pub(crate) tools: AgentTools,
907
908    /// The embedder's decisions.
909    pub(crate) hooks: H,
910
911    /// Answers the approvals tool calls and hooks ask for; without one an
912    /// approval fails.
913    pub(crate) approver: Option<AnyApprover>,
914
915    /// The children in flight, whose events join this agent's stream.
916    pub(crate) subagents: Option<crate::SubagentRuns>,
917
918    /// The pauses emitted, numbering the next.
919    pub(crate) pauses: Arc<AtomicU64>,
920
921    /// Agent configuration.
922    pub(crate) config: AgentConfig,
923
924    /// Unified context manager.
925    pub(crate) context: Context,
926
927    /// Window accounting, calibrated against the provider's token counts.
928    pub(crate) budget: ContextBudget,
929
930    /// Prompt cache controls derived from the current window layout.
931    pub(crate) prompt_cache: PromptCache,
932
933    /// Sources rendered into the volatile tail of every request.
934    pub(crate) context_sources: Vec<AnyContextSource>,
935
936    /// Live content: sources rendered into the cacheable prefix, after the
937    /// system prompt, in this order.
938    pub(crate) live_sources: Vec<AnyLiveSource>,
939
940    /// The tail of the request assembled last, which a preview or a
941    /// measurement of the window shows.
942    pub(crate) last_tail: Vec<Block>,
943
944    /// Whether the window was rewritten since the sources last heard a
945    /// request begin, which wipes every durable alert they pushed before.
946    pub(crate) reassembled: bool,
947
948    /// What rewrote the prompt prefix since the previous request, reported
949    /// with the next one's [`AgentEvent::RequestStarted`].
950    pub(crate) prefix_rewrites: PrefixRewrites,
951
952    /// How many requests this agent has assembled.
953    pub(crate) requests_sent: u64,
954
955    /// The next [`RequestId`]: every attempt at a response is one.
956    pub(crate) request_ids: u64,
957
958    /// The one compaction in the making: running alongside the turn, or
959    /// finished and waiting for a request boundary.
960    pub(crate) compaction: CompactionState,
961
962    /// Why the compaction forked alongside the run failed, until one lands:
963    /// the next compaction the window forces recovers first.
964    pub(crate) compaction_failure: Option<crate::context::CompactionError>,
965
966    /// Whether an [`AgentEvent::CompactionStarted`] was emitted whose
967    /// [`AgentEvent::CompactionEnded`] is still owed.
968    pub(crate) compaction_announced: bool,
969
970    /// Results of the tool calls of the turn in flight, in completion order,
971    /// until they are moved into the context.
972    pub(crate) tool_results: VecDeque<ToolExecutionResult>,
973
974    /// Cached model profile.
975    pub(crate) profile: Option<ModelProfile>,
976
977    /// The compaction model's profile, when one is set. It tells the cache
978    /// controls of a compaction request what that model's client will do with
979    /// the messages.
980    pub(crate) compaction_profile: Option<ModelProfile>,
981
982    /// Whether the profile was fetched and the window sized.
983    pub(crate) initialized: bool,
984
985    /// Ends a provider stream in flight when the machine wakes or goes
986    /// offline.
987    pub(crate) connectivity: crate::connectivity::Watch,
988
989    /// Directory files are restored from after a forked compaction.
990    pub(crate) restore_dir: Option<PathBuf>,
991
992    /// How the handoff's file index finds the files tool results name.
993    pub(crate) file_references: Option<AnyFileReferences>,
994
995    /// Whether the provider's prompt-cache entry is warm; stamped on every
996    /// request and keep-alive, shared with hosts through
997    /// [`Agent::cache_warmth`].
998    pub(crate) warmth: crate::CacheWarmth,
999
1000    /// The most recent LLM request issued by this agent, retained so a
1001    /// prompt-cache keep-alive can re-send it verbatim.
1002    pub(crate) last_request: Option<LLMRequest>,
1003
1004    /// The items of the request in flight, as the sequence number after the
1005    /// last of them, until the provider begins answering it: only then has
1006    /// the model been delivered what it carried.
1007    pub(crate) delivering: Option<u64>,
1008
1009    /// Where every request this agent sends is published for a fork
1010    /// subagent to start from; `None` when no fork reads this agent.
1011    pub(crate) fork_source: Option<crate::fork::ForkSource>,
1012
1013    /// The agent every tool call of this loop is made by.
1014    pub(crate) identity: aither_core::llm::AgentIdentity,
1015
1016    /// Rolling KV-cache statistics accumulated from emitted `Usage` events.
1017    ///
1018    /// Hosts can read [`Agent::cache_stats`] at any time to observe the
1019    /// cumulative prompt-caching hit rate for this agent session.
1020    pub(crate) cache_stats: crate::CacheStats,
1021
1022    /// Runtime skill registry loaded by host integrations.
1023    #[cfg(feature = "skills")]
1024    pub(crate) skill_registry: Option<Arc<aither_skills::SkillRegistry>>,
1025
1026    /// The schema compactions ask for; no value is held.
1027    pub(crate) handoff_schema: std::marker::PhantomData<fn() -> Schema>,
1028}
1029
1030impl<M: LanguageModel> Agent<M> {
1031    /// Creates a new agent with default configuration.
1032    #[must_use]
1033    pub fn new(llm: M) -> Self {
1034        Self::with_config(llm, AgentConfig::default())
1035    }
1036
1037    /// Creates a new agent with the specified configuration.
1038    #[must_use]
1039    pub fn with_config(llm: M, config: AgentConfig) -> Self {
1040        let prompt_cache = PromptCache::new(uuid::Uuid::new_v4().to_string());
1041        Self {
1042            warmth: crate::CacheWarmth::new(prompt_cache.lifetime(), crate::AnyClock::default()),
1043            model: Arc::new(llm),
1044            compaction_model: None,
1045            parameters: Box::default(),
1046            effort: crate::effort::EffortAnchor::default(),
1047            idle_compacted: false,
1048            tools: AgentTools::new(),
1049            hooks: (),
1050            approver: None,
1051            pauses: Arc::default(),
1052            config,
1053            context: Context::default(),
1054            budget: ContextBudget::default(),
1055            prompt_cache,
1056            context_sources: Vec::new(),
1057            live_sources: Vec::new(),
1058            last_tail: Vec::new(),
1059            reassembled: false,
1060            prefix_rewrites: PrefixRewrites::default(),
1061            requests_sent: 0,
1062            request_ids: 0,
1063            compaction: CompactionState::default(),
1064            compaction_failure: None,
1065            compaction_announced: false,
1066            tool_results: VecDeque::new(),
1067            profile: None,
1068            compaction_profile: None,
1069            initialized: false,
1070            connectivity: crate::connectivity::Watch::default(),
1071            restore_dir: None,
1072            file_references: None,
1073            last_request: None,
1074            delivering: None,
1075            fork_source: None,
1076            identity: aither_core::llm::AgentIdentity::Main,
1077            subagents: None,
1078            cache_stats: crate::CacheStats::new(),
1079            #[cfg(feature = "skills")]
1080            skill_registry: None,
1081            handoff_schema: std::marker::PhantomData,
1082        }
1083    }
1084
1085    /// Returns a builder for more complex agent construction.
1086    pub fn builder(llm: M) -> crate::builder::AgentBuilder<M> {
1087        crate::builder::AgentBuilder::new(llm)
1088    }
1089}
1090
1091impl<M, H, C, Schema> Agent<M, H, C, Schema>
1092where
1093    Schema: crate::HandoffSchema,
1094    M: LanguageModel + 'static,
1095    // Owned by the compaction future, which outlives the turn it races
1096    // against.
1097    C: LanguageModel + 'static,
1098    H: Hooks,
1099{
1100    /// Response stream of the model, boxed so the provider's concrete stream
1101    /// type does not inflate this async chain's poll frames in debug builds
1102    /// (aither#143).
1103    fn respond_stream<'a>(
1104        model: &'a Arc<M>,
1105        connectivity: &crate::connectivity::Watch,
1106        request: LLMRequest,
1107    ) -> Pin<Box<dyn Stream<Item = Result<Event, AgentError>> + Send + 'a>> {
1108        let stream: crate::connectivity::EventStream<'a> = Box::pin(
1109            model
1110                .respond(request)
1111                .map(|event| event.map_err(|error| AgentError::from_model_error(&error))),
1112        );
1113        connectivity.guard(stream)
1114    }
1115
1116    /// The retry policy of the conversation model.
1117    fn retry_policy(&self) -> RetryPolicy {
1118        self.model.retry_policy()
1119    }
1120
1121    /// Streams the model's response to `request`, sending the request again
1122    /// when the stream breaks after it opened.
1123    ///
1124    /// A failure before the first event is the provider's to retry, since it
1125    /// retries establishing the stream itself; a break after it is retried
1126    /// here, under the model's [`RetryPolicy`], unless the machine is
1127    /// offline. The broken attempt's text, calls and reasoning are dropped
1128    /// with it, and the request sent again is the one recorded as the last
1129    /// request, so the provider reads the same cached prefix.
1130    async fn collect_model_turn(
1131        &mut self,
1132        mut request: LLMRequest,
1133        prefix: &PromptPrefix,
1134        events: &EventSink,
1135    ) -> Result<ModelTurn, AgentError> {
1136        let policy = self.retry_policy();
1137        let mut retries = 0;
1138        loop {
1139            let id = RequestId::new(self.request_ids);
1140            self.request_ids += 1;
1141            events.emit(AgentEvent::RequestStarted {
1142                request: id,
1143                prefix: prefix.clone(),
1144            });
1145            let broken = match self.stream_model_turn(request, id, events).await {
1146                Ok(turn) => {
1147                    events.emit(AgentEvent::RequestEnded {
1148                        request: id,
1149                        usage: turn.usage.clone(),
1150                        outcome: RequestOutcome::Completed,
1151                    });
1152                    return Ok(turn);
1153                }
1154                Err(broken) => broken,
1155            };
1156            let failure = match broken.error.failure() {
1157                Some(failure)
1158                    if broken.opened
1159                        && policy.allows(retries, failure)
1160                        && !self.connectivity.is_offline() =>
1161                {
1162                    *failure
1163                }
1164                _ => {
1165                    events.emit(AgentEvent::RequestEnded {
1166                        request: id,
1167                        usage: broken.usage,
1168                        outcome: RequestOutcome::Failed {
1169                            error: broken.error.clone(),
1170                        },
1171                    });
1172                    return Err(broken.error);
1173                }
1174            };
1175            let delay = policy.delay(retries, &failure);
1176            retries += 1;
1177            tracing::warn!(
1178                retry = retries,
1179                max_retries = policy.max_retries,
1180                delay_ms = delay.as_millis(),
1181                error = %broken.error,
1182                "model response stream broke mid-response; sending the request again"
1183            );
1184            events.emit(AgentEvent::RequestEnded {
1185                request: id,
1186                usage: broken.usage,
1187                outcome: RequestOutcome::Retrying {
1188                    error: broken.error,
1189                    retry: retries,
1190                    max_retries: policy.max_retries,
1191                    delay,
1192                },
1193            });
1194            async_io::Timer::after(delay).await;
1195            request = self
1196                .last_request
1197                .clone()
1198                .expect("a request that reached the model is recorded as the last request");
1199        }
1200    }
1201
1202    /// One attempt at streaming the model's response to `request`.
1203    async fn stream_model_turn(
1204        &mut self,
1205        request: LLMRequest,
1206        id: RequestId,
1207        events: &EventSink,
1208    ) -> Result<ModelTurn, Box<BrokenStream>> {
1209        let mut response = Response::new(events, id);
1210        let mut malformed_function_call = false;
1211        let mut opened = false;
1212
1213        let stream = Self::respond_stream(&self.model, &self.connectivity, request);
1214        futures_lite::pin!(stream);
1215        while let Some(event) = stream.next().await {
1216            let received = event.is_ok();
1217            let action = handle_model_event(
1218                &mut self.cache_stats,
1219                &mut self.budget,
1220                event,
1221                &mut response,
1222            )
1223            .map_err(|error| {
1224                response.end_block();
1225                Box::new(BrokenStream {
1226                    error,
1227                    opened,
1228                    usage: response.usage.take(),
1229                })
1230            })?;
1231            if received && let Some(carried) = self.delivering.take() {
1232                self.context.mark_delivered_below(carried);
1233            }
1234            opened |= received;
1235            if matches!(action, ModelEventAction::RetryMalformed) {
1236                malformed_function_call = true;
1237                break;
1238            }
1239        }
1240        response.end_block();
1241
1242        Ok(ModelTurn {
1243            response_text: response.text_chunks.join(""),
1244            tool_calls: response.tool_calls,
1245            reasoning: response.reasoning,
1246            usage: response.usage,
1247            malformed_function_call,
1248        })
1249    }
1250
1251    /// Runs on the user's `prompt`.
1252    async fn run_streaming(
1253        &mut self,
1254        prompt: String,
1255        attachments: Vec<Attachment>,
1256        events: &EventSink,
1257        cancel: &CancelSignal,
1258    ) -> Result<(), AgentError> {
1259        self.run_to_end(
1260            events,
1261            cancel,
1262            Some(Message::user(prompt).with_attachments(attachments)),
1263        )
1264        .await
1265    }
1266
1267    /// A run without a new user message: the model acts on what the host
1268    /// pushed with [`push_message`](Self::push_message).
1269    async fn resume_streaming(
1270        &mut self,
1271        events: &EventSink,
1272        cancel: &CancelSignal,
1273    ) -> Result<(), AgentError> {
1274        self.run_to_end(events, cancel, None).await
1275    }
1276
1277    /// Runs the loop on `message` (when there is one) and ends the run's
1278    /// event stream with exactly one [`AgentEvent::RunEnded`], whatever way
1279    /// the run ends.
1280    async fn run_to_end(
1281        &mut self,
1282        events: &EventSink,
1283        cancel: &CancelSignal,
1284        message: Option<Message>,
1285    ) -> Result<(), AgentError> {
1286        let run = RunId::new(uuid::Uuid::new_v4().to_string());
1287        events.emit(AgentEvent::RunStarted {
1288            run: run.clone(),
1289            agent: events.agent.clone(),
1290        });
1291        let mut guard = RunEndGuard {
1292            events: events.clone(),
1293            run: run.clone(),
1294            ended: false,
1295        };
1296        let cx = RunCx {
1297            events,
1298            cancel,
1299            run: &run,
1300        };
1301        // Cancellation is polled first: a run cancelled before it started
1302        // must not get a turn in.
1303        let finished = futures_lite::future::or(
1304            async {
1305                cancel.cancelled().await;
1306                None
1307            },
1308            async { Some(self.run_body(&cx, message).await) },
1309        )
1310        .await;
1311        match finished {
1312            Some(Ok(LoopEnd::Answered { final_text, .. })) => {
1313                guard.end(RunOutcome::Completed { final_text });
1314                Ok(())
1315            }
1316            Some(Ok(LoopEnd::Paused(pause))) => {
1317                guard.end(RunOutcome::Paused { pause });
1318                Ok(())
1319            }
1320            Some(Err(error @ AgentError::MaxIterations { .. })) => {
1321                guard.end(RunOutcome::IterationLimit);
1322                Err(error)
1323            }
1324            Some(Err(error)) => {
1325                guard.end(RunOutcome::Failed {
1326                    error: error.clone(),
1327                });
1328                Err(error)
1329            }
1330            None => {
1331                guard.end(RunOutcome::Cancelled);
1332                Ok(())
1333            }
1334        }
1335    }
1336
1337    async fn run_body(
1338        &mut self,
1339        cx: &RunCx<'_>,
1340        message: Option<Message>,
1341    ) -> Result<LoopEnd, AgentError> {
1342        self.finish_lost_compaction(cx.events);
1343        self.ensure_initialized().await?;
1344        self.settle_interrupted_tool_calls();
1345        // An effort change lands before the user message it applies to.
1346        self.settle_effort()?;
1347        if let Some(message) = message {
1348            self.context.push(message);
1349        }
1350        let end = self.run_agent_loop(cx).await?;
1351        if let LoopEnd::Answered { turn, .. } = &end {
1352            self.emit_checkpoint(cx, CheckpointReason::Stop, *turn);
1353        }
1354        Ok(end)
1355    }
1356
1357    async fn run_agent_loop(&mut self, cx: &RunCx<'_>) -> Result<LoopEnd, AgentError> {
1358        let mut turn = 0;
1359        loop {
1360            turn += 1;
1361            if turn > self.config.max_iterations {
1362                return Err(AgentError::MaxIterations {
1363                    limit: self.config.max_iterations,
1364                });
1365            }
1366            cx.events.emit(AgentEvent::TurnStarted {
1367                run: cx.run.clone(),
1368                turn,
1369            });
1370            match self.run_agent_turn(cx, turn).await? {
1371                TurnControl::Continue => {}
1372                TurnControl::Break(end) => return Ok(end),
1373            }
1374        }
1375    }
1376
1377    async fn run_agent_turn(
1378        &mut self,
1379        cx: &RunCx<'_>,
1380        turn: usize,
1381    ) -> Result<TurnControl, AgentError> {
1382        let events = cx.events;
1383        let Some((request, prefix)) = self.prepare_request(cx, turn).await? else {
1384            Self::end_turn(cx, turn, 0);
1385            return Ok(TurnControl::Break(LoopEnd::Paused(
1386                RunPause::ContextExhausted,
1387            )));
1388        };
1389        let model_turn = self
1390            .run_turn_racing_compaction(request, &prefix, events)
1391            .await?;
1392
1393        if model_turn.malformed_function_call {
1394            Self::end_turn(cx, turn, 0);
1395            return Ok(TurnControl::Continue);
1396        }
1397        let response_text = model_turn.response_text;
1398        let tool_calls = model_turn.tool_calls;
1399        ensure_non_empty_tool_call_ids(&tool_calls, &response_text)?;
1400
1401        self.commit_assistant_turn(&response_text, &tool_calls, model_turn.reasoning);
1402        if tool_calls.is_empty() {
1403            return self.finish_no_tool_turn(cx, response_text, turn).await;
1404        }
1405
1406        Self::push_tool_start_events(&tool_calls, events);
1407        self.execute_tool_calls(cx, &tool_calls, turn).await;
1408        let (outcomes, appended) = self.apply_tool_results()?;
1409        self.push_tool_turn_context(cx, appended).await;
1410        self.push_turn_boundary_events(cx, turn, &response_text, &outcomes)
1411            .await
1412    }
1413
1414    fn end_turn(cx: &RunCx<'_>, turn: usize, tool_calls: usize) {
1415        cx.events.emit(AgentEvent::TurnEnded {
1416            run: cx.run.clone(),
1417            turn,
1418            tool_calls,
1419        });
1420    }
1421
1422    /// Runs one model turn while a forked compaction keeps running.
1423    ///
1424    /// The two are polled together instead of sequenced: compaction is a full
1425    /// request, and waiting for it would stall the run at exactly the moment
1426    /// the window is tightest. Whichever finishes first is handled — a landed
1427    /// handoff is parked for the next request boundary, where replacing the
1428    /// conversation is safe.
1429    async fn run_turn_racing_compaction(
1430        &mut self,
1431        request: LLMRequest,
1432        prefix: &PromptPrefix,
1433        events: &EventSink,
1434    ) -> Result<ModelTurn, AgentError> {
1435        let mut pending = self.compaction.take_running();
1436        let mut landed = None;
1437
1438        let turn = {
1439            let turn = self.collect_model_turn(request, prefix, events);
1440            futures_lite::pin!(turn);
1441            loop {
1442                let step = match pending.as_mut() {
1443                    Some(compaction) => {
1444                        futures_lite::future::or(
1445                            async { TurnStep::Turn((&mut turn).await) },
1446                            async { TurnStep::Compacted(compaction.wait().await) },
1447                        )
1448                        .await
1449                    }
1450                    None => TurnStep::Turn((&mut turn).await),
1451                };
1452                match step {
1453                    TurnStep::Turn(turn) => break turn,
1454                    TurnStep::Compacted(result) => {
1455                        landed = Some(result);
1456                        pending = None;
1457                    }
1458                }
1459            }
1460        };
1461
1462        match landed {
1463            Some(Ok(completed)) => self.compaction.land(completed),
1464            Some(Err(error)) => {
1465                tracing::warn!(%error, "forked compaction failed");
1466                self.finish_compaction(events, CompactionOutcome::Failed(error.clone().into()));
1467                self.compaction_failure = Some(error);
1468            }
1469            None => {}
1470        }
1471        self.compaction.resume(pending);
1472        turn
1473    }
1474
1475    /// Stores what the model produced this turn: its text, calls and reasoning.
1476    ///
1477    /// The reasoning travels with the turn that produced it, or later requests
1478    /// carry the calls and the answer without the thinking behind them. A turn
1479    /// that produced nothing at all stores nothing.
1480    fn commit_assistant_turn(
1481        &mut self,
1482        response_text: &str,
1483        tool_calls: &[ToolCall],
1484        reasoning: Vec<ReasoningState>,
1485    ) {
1486        if response_text.is_empty() && tool_calls.is_empty() && reasoning.is_empty() {
1487            return;
1488        }
1489        self.context.push(Message::assistant_with_reasoning(
1490            response_text,
1491            tool_calls.to_vec(),
1492            reasoning,
1493        ));
1494    }
1495
1496    async fn finish_no_tool_turn(
1497        &mut self,
1498        cx: &RunCx<'_>,
1499        response_text: String,
1500        turn: usize,
1501    ) -> Result<TurnControl, AgentError> {
1502        Self::end_turn(cx, turn, 0);
1503        let objected = self.push_final_turn_context(cx).await;
1504        let held = self.decide_stop(cx, &response_text, turn).await;
1505        if objected || held {
1506            // The alerts stay in the conversation either way; a host that has
1507            // a message waiting ends the run here so the message travels with
1508            // them in the next request instead of one request later.
1509            let boundary_ctx = TurnBoundaryContext {
1510                assistant_text: &response_text,
1511                turn,
1512                message_count: self.context.len_recent(),
1513                outcomes: &[],
1514            };
1515            if self.hooks.on_turn_boundary(&boundary_ctx).await == TurnBoundaryAction::EndTurn {
1516                return Ok(TurnControl::Break(LoopEnd::Answered {
1517                    final_text: response_text,
1518                    turn,
1519                }));
1520            }
1521            return Ok(TurnControl::Continue);
1522        }
1523        Ok(TurnControl::Break(LoopEnd::Answered {
1524            final_text: response_text,
1525            turn,
1526        }))
1527    }
1528
1529    /// Gives every tool call in the context a result.
1530    ///
1531    /// A run stream dropped while tools execute leaves the assistant message
1532    /// carrying the calls with no results behind it, and providers reject a
1533    /// request holding such calls. Runs at the start of the next run (and of a
1534    /// manual compaction), so the repair needs nothing from the host and only
1535    /// appends: the prefix, thinking blocks included, stays byte-identical.
1536    /// Calls whose results had already landed keep them; the rest get a
1537    /// cancelled result.
1538    fn settle_interrupted_tool_calls(&mut self) {
1539        let mut parked = std::mem::take(&mut self.tool_results);
1540        let mut unresolved: Vec<ToolCall> = Vec::new();
1541        for message in self.context.recent() {
1542            unresolved.extend(message.tool_calls().iter().cloned());
1543            if let Some(id) = message.tool_call_id() {
1544                unresolved.retain(|call| call.id != id);
1545            }
1546        }
1547        for call in unresolved {
1548            let finished = parked
1549                .iter()
1550                .position(|result| matches!(result, Ok(finished) if finished.id == call.id))
1551                .and_then(|index| parked.remove(index));
1552            let content = match finished {
1553                Some(Ok(finished)) => finished.outcome.for_model().render_for_model(),
1554                _ => CancelledToolCallTemplate { tool: &call.name }
1555                    .render()
1556                    .expect("cancelled tool call template must render"),
1557            };
1558            self.context.push(Message::tool(&call.id, content));
1559        }
1560    }
1561
1562    fn push_tool_start_events(tool_calls: &[ToolCall], events: &EventSink) {
1563        for call in tool_calls {
1564            events.emit(AgentEvent::ToolCallStarted {
1565                call: ToolCallId::new(call.id.clone()),
1566                name: call.name.clone(),
1567                arguments: call.arguments.clone(),
1568                origin: ToolOrigin::Local,
1569            });
1570        }
1571    }
1572
1573    /// Runs `tool_calls` concurrently, parking each result in
1574    /// `self.tool_results` the moment it lands.
1575    ///
1576    /// The results live on the agent rather than in this future so a run
1577    /// stream dropped mid-execution still leaves the finished ones for
1578    /// [`Self::settle_interrupted_tool_calls`] to pair.
1579    async fn execute_tool_calls(&mut self, cx: &RunCx<'_>, tool_calls: &[ToolCall], turn: usize) {
1580        let message_count = self.context.len_recent();
1581        let approver = self.approver.clone().map(|inner| {
1582            AnyApprover::new(PausingApprover {
1583                inner,
1584                events: cx.events.clone(),
1585                pauses: Arc::clone(&self.pauses),
1586            })
1587        });
1588        let incoming = self.subagents.as_ref().map(|runs| runs.incoming().clone());
1589        let (hooks, tools, agent) = (&self.hooks, &self.tools, &self.identity);
1590        let results = &mut self.tool_results;
1591        let tool_futures = tool_calls.iter().map(|call| {
1592            let identity = aither_core::llm::CallIdentity::new(
1593                ToolCallId::new(call.id.clone()),
1594                agent.clone(),
1595            );
1596            let approver = approver.clone();
1597            async move {
1598                let run = ToolRun {
1599                    hooks,
1600                    tools,
1601                    events: cx.events,
1602                    cancel: cx.cancel,
1603                    approver: approver.as_ref(),
1604                    identity,
1605                    turn,
1606                    message_count,
1607                };
1608                run.execute(call).await
1609            }
1610        });
1611
1612        let mut pending = tool_futures.collect::<futures::stream::FuturesUnordered<_>>();
1613        loop {
1614            // A child a tool runs reports through the registry; its events
1615            // join this stream as they arrive, not when the tool returns.
1616            let step = futures_lite::future::or(
1617                async { ToolStep::Finished(pending.next().await) },
1618                async {
1619                    match &incoming {
1620                        Some(incoming) => ToolStep::Child(incoming.recv().await.ok()),
1621                        None => std::future::pending().await,
1622                    }
1623                },
1624            )
1625            .await;
1626            match step {
1627                ToolStep::Finished(Some(result)) => results.push_back(result),
1628                ToolStep::Finished(None) => break,
1629                ToolStep::Child(Some(event)) => cx.events.forward(event),
1630                ToolStep::Child(None) => {}
1631            }
1632        }
1633        drop(pending);
1634        self.forward_child_events(cx.events);
1635    }
1636
1637    /// Puts the events children reported onto this agent's stream.
1638    fn forward_child_events(&self, events: &EventSink) {
1639        if let Some(runs) = &self.subagents {
1640            while let Ok(event) = runs.incoming().try_recv() {
1641                events.forward(event);
1642            }
1643        }
1644    }
1645
1646    /// Moves the parked tool results into the context, and returns the
1647    /// turn's outcomes and the context its `after_tool` hooks appended.
1648    ///
1649    /// Results not reached because one failed stay parked for
1650    /// [`Self::settle_interrupted_tool_calls`].
1651    fn apply_tool_results(&mut self) -> Result<(Vec<ToolOutcome>, Vec<String>), AgentError> {
1652        let mut outcomes = Vec::new();
1653        let mut appended = Vec::new();
1654        while let Some(result) = self.tool_results.pop_front() {
1655            let finished = result?;
1656            self.context.push(Message::tool(
1657                &finished.id,
1658                finished.outcome.for_model().render_for_model(),
1659            ));
1660            outcomes.push(finished.outcome);
1661            appended.extend(finished.appended);
1662        }
1663        Ok((outcomes, appended))
1664    }
1665
1666    async fn push_turn_boundary_events(
1667        &self,
1668        cx: &RunCx<'_>,
1669        turn: usize,
1670        response_text: &str,
1671        outcomes: &[ToolOutcome],
1672    ) -> Result<TurnControl, AgentError> {
1673        let boundary_ctx = TurnBoundaryContext {
1674            assistant_text: response_text,
1675            turn,
1676            message_count: self.context.len_recent(),
1677            outcomes,
1678        };
1679        self.emit_checkpoint(cx, CheckpointReason::TurnBoundary, turn);
1680        Self::end_turn(cx, turn, outcomes.len());
1681        if self.hooks.on_turn_boundary(&boundary_ctx).await == TurnBoundaryAction::EndTurn {
1682            Ok(TurnControl::Break(LoopEnd::Answered {
1683                final_text: response_text.to_string(),
1684                turn,
1685            }))
1686        } else {
1687            Ok(TurnControl::Continue)
1688        }
1689    }
1690
1691    /// Re-sends the last request to refresh the cache entry of an idle agent.
1692    ///
1693    /// Re-sends the last request with no output (`max_tokens: 0`,
1694    /// non-streaming, the same thinking and effort settings), so the
1695    /// provider restarts the entry's lifetime. The history is untouched, the
1696    /// request's usage is recorded in [`cache_stats`](Self::cache_stats) and
1697    /// the entry's [`cache_warmth`](Self::cache_warmth) restarts. The caller
1698    /// decides when to call it, shortly before the entry goes cold.
1699    ///
1700    /// Returns the request's usage so the caller can account for its cost
1701    /// (all fields empty when the provider reported none), or `None` when
1702    /// there is nothing to refresh: no request was sent yet, or the entry is
1703    /// permanent or already cold.
1704    ///
1705    /// # Errors
1706    ///
1707    /// Returns the provider error when the keep-alive request fails.
1708    pub async fn keep_cache_warm(&mut self) -> Result<Option<aither_core::llm::Usage>, AgentError> {
1709        if self.warmth.cold_in().is_none() {
1710            return Ok(None);
1711        }
1712        let Some(last_request) = self.last_request.clone() else {
1713            return Ok(None);
1714        };
1715        let (messages, parameters, tool_definitions) = last_request.into_parts();
1716        let request = LLMRequest::new(messages)
1717            .with_tool_definitions(tool_definitions)
1718            .with_parameters(parameters.max_tokens(0).stream(false));
1719        let stream = Self::respond_stream(&self.model, &self.connectivity, request);
1720        futures_lite::pin!(stream);
1721        let mut refreshed = aither_core::llm::Usage::default();
1722        while let Some(event) = stream.next().await {
1723            match event {
1724                Ok(Event::Usage(usage)) => {
1725                    self.cache_stats.record(&usage);
1726                    refreshed = usage;
1727                }
1728                Ok(_) => {}
1729                Err(error) => return Err(error),
1730            }
1731        }
1732        self.warmth.start_entry_now();
1733        Ok(Some(refreshed))
1734    }
1735
1736    /// A shared handle on whether the provider's prompt-cache entry for this
1737    /// agent's context is warm and how long until it goes cold. It keeps
1738    /// tracking this agent's later requests and keep-alives.
1739    #[must_use]
1740    pub fn cache_warmth(&self) -> crate::CacheWarmth {
1741        self.warmth.clone()
1742    }
1743
1744    /// How long the provider's prompt-cache entry for this agent's context
1745    /// stays warm without a hit.
1746    #[must_use]
1747    pub const fn cache_lifetime(&self) -> CacheLifetime {
1748        self.prompt_cache.lifetime()
1749    }
1750
1751    /// Performs a one-shot query and returns the final response.
1752    ///
1753    /// This is the simplest way to use the agent. The agent handles tool
1754    /// execution internally and returns the final text response.
1755    ///
1756    /// # Errors
1757    ///
1758    /// Returns an error if:
1759    /// - The LLM returns an error
1760    /// - A hook aborts the operation
1761    /// - Tool execution fails
1762    /// - The run paused ([`AgentError::Paused`]) or was cancelled
1763    ///   ([`AgentError::Cancelled`]) before it had a reply
1764    pub async fn query(&mut self, prompt: &str) -> Result<String, AgentError> {
1765        let limit = self.config.max_iterations;
1766        let agent = AgentPath::of(&self.identity);
1767        let flow = self
1768            .run(prompt, std::iter::empty())
1769            .drive((), std::future::pending(), |(), timed| {
1770                let own_end = timed.agent == agent;
1771                std::future::ready(match timed.event {
1772                    AgentEvent::RunEnded { outcome, .. } if own_end => ControlFlow::Break(outcome),
1773                    _ => ControlFlow::Continue(()),
1774                })
1775            })
1776            .await?;
1777        match flow {
1778            ControlFlow::Break(RunOutcome::Completed { final_text }) => Ok(final_text),
1779            ControlFlow::Break(RunOutcome::Paused { pause }) => Err(AgentError::Paused(pause)),
1780            ControlFlow::Break(RunOutcome::Failed { error }) => Err(error),
1781            ControlFlow::Break(RunOutcome::IterationLimit) => {
1782                Err(AgentError::MaxIterations { limit })
1783            }
1784            ControlFlow::Break(_) | ControlFlow::Continue(()) => Err(AgentError::Cancelled),
1785        }
1786    }
1787
1788    /// Starts a run on `prompt`; [`Run::drive`] runs it and hands each event
1789    /// to the caller as it happens, text chunks as they arrive from the LLM.
1790    ///
1791    /// # Example
1792    ///
1793    /// ```rust,ignore
1794    /// use std::ops::ControlFlow;
1795    ///
1796    /// let mut shown = String::new();
1797    /// agent
1798    ///     .run("Implement the feature", std::iter::empty())
1799    ///     .drive(&mut shown, std::future::pending(), |shown, timed| async move {
1800    ///         if let AgentEvent::BlockDelta { kind: OutputKind::Text, text, .. } = timed.event {
1801    ///             shown.push_str(&text);
1802    ///         }
1803    ///         ControlFlow::<(), _>::Continue(shown)
1804    ///     })
1805    ///     .await?;
1806    /// ```
1807    pub fn run(
1808        &mut self,
1809        prompt: &str,
1810        attachments: impl IntoIterator<Item = Attachment>,
1811    ) -> Run<impl Future<Output = Result<(), AgentError>> + '_> {
1812        let prompt = prompt.to_string();
1813        let attachments: Vec<Attachment> = attachments.into_iter().collect();
1814        Run::new(
1815            AgentPath::of(&self.identity),
1816            move |sink, cancel| async move {
1817                self.run_streaming(prompt, attachments, &sink, &cancel)
1818                    .await
1819            },
1820        )
1821    }
1822
1823    /// Continues the conversation without a new user message, so the model
1824    /// acts on the messages the host added with
1825    /// [`push_message`](Self::push_message). Driven like [`run`](Self::run).
1826    pub fn resume(&mut self) -> Run<impl Future<Output = Result<(), AgentError>> + '_> {
1827        Run::new(
1828            AgentPath::of(&self.identity),
1829            move |sink, cancel| async move { self.resume_streaming(&sink, &cancel).await },
1830        )
1831    }
1832
1833    /// Registers a tool for the agent to use.
1834    ///
1835    /// # Errors
1836    ///
1837    /// Returns [`RegisterError`](aither_core::llm::tool::RegisterError) if the
1838    /// name collides with a registered tool, or the tool has no description.
1839    pub fn register_tool<T: aither_core::llm::Tool + 'static>(
1840        &mut self,
1841        tool: T,
1842    ) -> Result<(), aither_core::llm::tool::RegisterError> {
1843        self.tools.register(tool)
1844    }
1845
1846    /// Returns a reference to the unified context manager.
1847    #[must_use]
1848    pub const fn context(&self) -> &Context {
1849        &self.context
1850    }
1851
1852    /// Returns a mutable reference to the unified context manager.
1853    ///
1854    /// Use this to insert/update system blocks, push messages, etc.
1855    pub const fn context_mut(&mut self) -> &mut Context {
1856        &mut self.context
1857    }
1858
1859    /// Adds a message to the conversation history.
1860    pub fn push_message(&mut self, message: Message) {
1861        self.context.push(message);
1862    }
1863
1864    /// Returns the rolling KV-cache statistics for this agent session.
1865    ///
1866    /// The stats are updated every time the underlying provider emits a
1867    /// `Usage` event (which, for providers like Claude with prompt
1868    /// caching, includes `cache_read_tokens` and `cache_write_tokens`).
1869    /// Hosts can read the hit rate, reset the accumulator, or snapshot
1870    /// it for per-turn diffs.
1871    #[must_use]
1872    pub const fn cache_stats(&self) -> &crate::CacheStats {
1873        &self.cache_stats
1874    }
1875
1876    /// Returns a mutable reference to the KV-cache statistics accumulator.
1877    ///
1878    /// Hosts typically only use this to [`CacheStats::reset`] between
1879    /// distinct sessions, since the agent itself records new observations.
1880    ///
1881    /// [`CacheStats::reset`]: crate::CacheStats::reset
1882    pub const fn cache_stats_mut(&mut self) -> &mut crate::CacheStats {
1883        &mut self.cache_stats
1884    }
1885
1886    /// Clears the conversation history.
1887    pub fn clear_history(&mut self) {
1888        self.compaction.retire();
1889        self.context.clear_history();
1890    }
1891
1892    /// Compacts the conversation by generating a structured handoff and
1893    /// starting fresh, focused on `focus` when one is given. Driven like
1894    /// [`run`](Self::run).
1895    ///
1896    /// The run emits [`AgentEvent::CompactionStarted`] and then
1897    /// [`AgentEvent::CompactionEnded`], whose
1898    /// [`CompactionOutcome`] carries the [`CompactResult`] when the handoff
1899    /// applied. A compaction forked earlier alongside a run is stale once this
1900    /// one starts: it finishes as [`CompactionOutcome::Discarded`] first.
1901    ///
1902    /// # Errors
1903    ///
1904    /// [`drive`](Run::drive) returns the failure when handoff generation
1905    /// fails, after the finish event reported it.
1906    pub fn compact(
1907        &mut self,
1908        focus: Option<&str>,
1909    ) -> Run<impl Future<Output = Result<(), AgentError>> + '_> {
1910        let focus = focus.map(str::to_string);
1911        Run::new(
1912            AgentPath::of(&self.identity),
1913            move |sink, _cancel| async move {
1914                self.finish_lost_compaction(&sink);
1915                Box::pin(self.compact_streaming(
1916                    focus.as_deref(),
1917                    CompactionTrigger::Requested,
1918                    &sink,
1919                ))
1920                .await
1921                .map(drop)
1922            },
1923        )
1924    }
1925
1926    /// Runs one compaction to its end, announcing it on `events`.
1927    async fn compact_streaming(
1928        &mut self,
1929        focus: Option<&str>,
1930        trigger: CompactionTrigger,
1931        events: &EventSink,
1932    ) -> Result<Option<CompactResult>, AgentError> {
1933        self.ensure_initialized().await?;
1934        self.settle_interrupted_tool_calls();
1935        // This handoff describes the whole conversation as it stands, so a
1936        // compaction forked earlier, running or landed, is stale from here.
1937        self.compaction.retire();
1938        self.finish_compaction(events, CompactionOutcome::Discarded);
1939        self.announce_compaction(events, trigger);
1940        match self.fork_and_apply(focus, events).await {
1941            Ok(Some(result)) => Ok(Some(result)),
1942            Ok(None) => {
1943                self.finish_compaction(events, CompactionOutcome::NothingToCompact);
1944                Ok(None)
1945            }
1946            Err(error) => {
1947                self.finish_compaction(events, CompactionOutcome::Failed(error.clone()));
1948                Err(error)
1949            }
1950        }
1951    }
1952
1953    /// Generates the handoff for the whole conversation and applies it;
1954    /// `None` when there is no conversation to compact.
1955    async fn fork_and_apply(
1956        &mut self,
1957        focus: Option<&str>,
1958        events: &EventSink,
1959    ) -> Result<Option<CompactResult>, AgentError> {
1960        if self.context.is_conversation_empty() {
1961            return Ok(None);
1962        }
1963        let definitions = self.tools.active_definitions();
1964        let messages = self.request_messages(&self.last_tail);
1965        let request = self.compaction_request(messages, definitions);
1966        #[cfg(feature = "skills")]
1967        let skills = self.skill_catalog();
1968        #[cfg(not(feature = "skills"))]
1969        let skills = Vec::new();
1970        let attachments = self.context.attachment_catalog(self.context.fork_point());
1971        let fork = match CompactionFork::<Schema>::new(
1972            &request,
1973            self.context.fork_point(),
1974            self.context.handoff_file_index(),
1975            focus,
1976            &skills,
1977            &attachments,
1978        ) {
1979            Ok(fork) => fork.with_file_references(self.file_references.clone()),
1980            // Only system messages: nothing a handoff could summarize.
1981            Err(crate::context::CompactionError::Empty) => return Ok(None),
1982            Err(error) => return Err(error.into()),
1983        };
1984        let completed = self
1985            .compaction_future(fork)
1986            .await
1987            .map_err(AgentError::from)?;
1988
1989        self.compaction.land(completed);
1990        Ok(Some(
1991            self.apply_completed_compaction(events)
1992                .await
1993                .expect("the compaction just landed"),
1994        ))
1995    }
1996
1997    /// The parameters of the requests the agent sends on its model.
1998    #[must_use]
1999    pub fn parameters(&self) -> &Parameters {
2000        &self.parameters
2001    }
2002
2003    /// Changes the parameters of the requests sent on the model, from the
2004    /// next request on.
2005    ///
2006    /// A reasoning effort change keeps the prompt cache warm when the model
2007    /// takes per-message effort updates
2008    /// ([`Ability::PerMessageEffort`](aither_core::llm::model::Ability::PerMessageEffort)):
2009    /// the next request carries the update inside the conversation, before
2010    /// the next user message when one starts the turn, and the request-level
2011    /// effort stays as the first request sent it. Clearing the effort there
2012    /// is an update to the model's documented default
2013    /// ([`Profile::default_reasoning_effort`](aither_core::llm::model::Profile::default_reasoning_effort));
2014    /// with none recorded, the next turn fails with [`AgentError::Config`]
2015    /// rather than leave the earlier level in force. Any other model, and any
2016    /// other parameter, takes the new value at the request level, which
2017    /// restarts the cache.
2018    pub fn set_parameters(&mut self, parameters: Parameters) {
2019        *self.parameters = parameters;
2020    }
2021
2022    /// Replaces the conversation model.
2023    ///
2024    /// The next request goes to `model`; history, context and tools stay. A
2025    /// new model reads none of the old one's prompt cache, so the change
2026    /// applies at once. A compaction already running finishes on the model it
2027    /// started on.
2028    pub fn set_model(&mut self, model: M) {
2029        self.model = Arc::new(model);
2030        // Forget what belonged to the replaced model: its profile, fetched
2031        // again before the next request, and the last request, which a
2032        // keep-alive would otherwise send it.
2033        self.profile = None;
2034        self.last_request = None;
2035    }
2036
2037    /// Whether the agent's own model takes reasoning effort changes inside
2038    /// the conversation.
2039    fn takes_per_message_effort(&self) -> bool {
2040        self.profile
2041            .as_ref()
2042            .is_some_and(|profile| profile.abilities.contains(&Ability::PerMessageEffort))
2043    }
2044
2045    /// Whether the agent's own model takes a system message inside the
2046    /// conversation, which decides whether a provider that cannot keeps the
2047    /// live tail out of its system prompt.
2048    fn takes_mid_conversation_system(&self) -> bool {
2049        Self::profile_takes_mid_conversation_system(self.profile.as_ref())
2050    }
2051
2052    /// Whether the model a compaction request goes to takes a system message
2053    /// inside the conversation: the compaction model when one is set, else the
2054    /// agent's own.
2055    ///
2056    /// A model's client decides this from the same ability its profile
2057    /// reports, so the cache controls and the client cannot disagree.
2058    ///
2059    /// # Panics
2060    ///
2061    /// Panics when a compaction model is set and its profile is not loaded,
2062    /// which initialization does before any request.
2063    fn compaction_takes_mid_conversation_system(&self) -> bool {
2064        if self.compaction_model.is_none() {
2065            return self.takes_mid_conversation_system();
2066        }
2067        let profile = self
2068            .compaction_profile
2069            .as_ref()
2070            .expect("an initialized agent has its compaction model's profile");
2071        Self::profile_takes_mid_conversation_system(Some(profile))
2072    }
2073
2074    fn profile_takes_mid_conversation_system(profile: Option<&ModelProfile>) -> bool {
2075        profile.is_some_and(|profile| profile.abilities.contains(&Ability::MidConversationSystem))
2076    }
2077
2078    /// Brings the effort in force to the one the agent wants: appends a
2079    /// per-message update when its model takes one, clearing the effort to
2080    /// the model's default level, and otherwise settles the request-level
2081    /// effort.
2082    ///
2083    /// # Errors
2084    ///
2085    /// Returns [`AgentError::Config`] when the effort is cleared on a model
2086    /// that takes per-message updates but whose default effort is not
2087    /// recorded, while another level is in force: no update can undo it.
2088    ///
2089    /// # Panics
2090    ///
2091    /// Panics before the agent is initialized, since only the model's profile
2092    /// says how an effort change is sent.
2093    fn settle_effort(&mut self) -> Result<(), AgentError> {
2094        let profile = self
2095            .profile
2096            .as_ref()
2097            .expect("the effort is settled only by an initialized agent, which has its profile");
2098        let changes = if profile.abilities.contains(&Ability::PerMessageEffort) {
2099            crate::effort::EffortChanges::PerMessage {
2100                default: profile.default_reasoning_effort,
2101            }
2102        } else {
2103            crate::effort::EffortChanges::RequestLevel
2104        };
2105        let update = self
2106            .effort
2107            .plan(
2108                self.parameters.reasoning_effort,
2109                changes,
2110                self.context.configured_effort(),
2111            )
2112            .map_err(|crate::effort::UnknownDefaultEffort| {
2113                AgentError::Config(format!(
2114                    "the reasoning effort was cleared, but model '{}' takes effort changes \
2115                     inside the conversation and its default effort is not recorded, so no \
2116                     update can undo the level in force; set an explicit effort",
2117                    profile.name
2118                ))
2119            })?;
2120        if let Some(effort) = update {
2121            self.context.push(Message::configuration(effort));
2122        }
2123        Ok(())
2124    }
2125
2126    /// The parameters of the agent's own requests as they are sent: the
2127    /// configured ones, with the request-level effort
2128    /// [`settle_effort`](Self::settle_effort) settled on.
2129    fn request_parameters(&self) -> Parameters {
2130        let mut parameters = (*self.parameters).clone();
2131        parameters.reasoning_effort = self.effort.request_effort(parameters.reasoning_effort);
2132        parameters
2133    }
2134
2135    /// The window as a request to the agent's own model carries it, with the
2136    /// live `tail`: its effort updates are left out when the model cannot
2137    /// read them.
2138    fn request_messages(&self, tail: &[Block]) -> Vec<Message> {
2139        let mut messages = self.context.build_request(tail);
2140        if !self.takes_per_message_effort() {
2141            messages.retain(|message| message.role() != Role::Configuration);
2142        }
2143        messages
2144    }
2145
2146    /// A compaction request over `messages` and `definitions`: the
2147    /// compaction model's parameters when one is set, else the session
2148    /// model's, under the cache controls the requests that wrote the prefix
2149    /// carry, so a compaction on the session's own model is served from that
2150    /// cache.
2151    ///
2152    /// `messages` is the window as the session model's requests carry it. A
2153    /// compaction model runs at its own effort, so the session's effort
2154    /// updates are left out of its request.
2155    fn compaction_request(
2156        &self,
2157        mut messages: Vec<Message>,
2158        definitions: Vec<aither_core::llm::tool::ToolDefinition>,
2159    ) -> LLMRequest {
2160        if self.compaction_model.is_some() {
2161            messages.retain(|message| message.role() != Role::Configuration);
2162        }
2163        let parameters = self.compaction_model.as_ref().map_or_else(
2164            || self.request_parameters(),
2165            |compactor| (*compactor.parameters).clone(),
2166        );
2167        let parameters = self.prompt_cache.apply(
2168            parameters,
2169            &messages,
2170            !definitions.is_empty(),
2171            self.compaction_takes_mid_conversation_system(),
2172        );
2173        LLMRequest::new(messages)
2174            .with_parameters(parameters)
2175            .with_tool_definitions(definitions)
2176    }
2177
2178    /// Runs `fork` to completion on the compaction model: the configured one,
2179    /// or else the conversation model.
2180    async fn compaction_future(
2181        &self,
2182        fork: CompactionFork<Schema>,
2183    ) -> Result<CompletedCompaction, crate::context::CompactionError> {
2184        if let Some(compactor) = &self.compaction_model {
2185            return fork.run(Arc::clone(&compactor.model)).await;
2186        }
2187        fork.run(Arc::clone(&self.model)).await
2188    }
2189
2190    /// Starts `fork` in the background on the compaction model: the
2191    /// configured one, or else the conversation model.
2192    fn start_pending_compaction(&self, fork: CompactionFork<Schema>) -> PendingCompaction {
2193        if let Some(compactor) = &self.compaction_model {
2194            return PendingCompaction::start(fork, Arc::clone(&compactor.model));
2195        }
2196        PendingCompaction::start(fork, Arc::clone(&self.model))
2197    }
2198
2199    /// How long from now the idle compaction is due: `Some(Duration::ZERO)`
2200    /// when it is due now, `None` when none is pending.
2201    ///
2202    /// The window is compacted once, shortly before the conversation's cache
2203    /// lifetime ends ([`ContextPolicy::idle_compact_before_expiry`] ahead of
2204    /// it), counted from the entry's last use, so the compaction reads the
2205    /// still-warm cache. None is pending when:
2206    ///
2207    /// - a compaction model is set, which cannot read that cache;
2208    /// - the lifetime is [`CacheLifetime::Permanent`];
2209    /// - nothing has been sent yet, or the conversation is empty;
2210    /// - the context holds fewer tokens than the policy's
2211    ///   [`compaction_floor`](crate::ContextPolicy::compaction_floor);
2212    /// - it already ran since the last request;
2213    /// - the cache has expired already, when compacting would only pay to
2214    ///   write the whole context again.
2215    ///
2216    /// The agent has no timer of its own: the host sleeps this long while the
2217    /// session is idle, then calls [`compact_when_idle`](Self::compact_when_idle).
2218    ///
2219    /// [`ContextPolicy::idle_compact_before_expiry`]: crate::ContextPolicy::idle_compact_before_expiry
2220    #[must_use]
2221    pub fn idle_compaction_due_in(&self) -> Option<Duration> {
2222        if self.compaction_model.is_some()
2223            || self.idle_compacted
2224            || self.compaction.is_active()
2225            || self.context.is_conversation_empty()
2226            || self
2227                .config
2228                .context_policy
2229                .below_floor(self.budget.estimated_tokens())
2230        {
2231            return None;
2232        }
2233        let cold_in = self.warmth.cold_in()?;
2234        Some(cold_in.saturating_sub(self.config.context_policy.idle_compact_before_expiry))
2235    }
2236
2237    /// Compacts the idle session once its cache is about to expire.
2238    ///
2239    /// Runs one compaction through the normal fork and apply path when
2240    /// [`idle_compaction_due_in`](Self::idle_compaction_due_in) says it is due
2241    /// now, and returns `None` otherwise, so a host may call it whenever its
2242    /// idle timer fires. One idle gap compacts once: the next request re-arms
2243    /// it. Nothing is kept across the handoff, so no thinking produced under
2244    /// the old prefix is replayed after it.
2245    ///
2246    /// Driven like [`compact`](Self::compact), and emits its compaction
2247    /// events only when the compaction is due; otherwise the run emits
2248    /// nothing.
2249    ///
2250    /// # Errors
2251    ///
2252    /// [`drive`](Run::drive) returns the compaction failure; the window is
2253    /// left as it was.
2254    pub fn compact_when_idle(&mut self) -> Run<impl Future<Output = Result<(), AgentError>> + '_> {
2255        Run::new(
2256            AgentPath::of(&self.identity),
2257            move |sink, _cancel| async move {
2258                self.finish_lost_compaction(&sink);
2259                if self.idle_compaction_due_in() != Some(Duration::ZERO) {
2260                    return Ok(());
2261                }
2262                let result =
2263                    Box::pin(self.compact_streaming(None, CompactionTrigger::Idle, &sink)).await?;
2264                self.idle_compacted = true;
2265                if let Some(result) = &result {
2266                    tracing::info!(
2267                        compacted = result.messages_compacted,
2268                        "compacted the idle context shortly before its cache expires"
2269                    );
2270                }
2271                Ok(())
2272            },
2273        )
2274    }
2275
2276    /// Forks a compaction off `request` to run alongside the turns that follow.
2277    ///
2278    /// The compaction replays the session's current model unless a compaction
2279    /// model is set: the handoff has to carry the same understanding of the
2280    /// conversation the next requests are made of, and only that model reads
2281    /// the cache the run just paid for.
2282    ///
2283    /// A failure to even start — an empty conversation — is not an error for
2284    /// the run: there is simply nothing to compact yet, and nothing is
2285    /// announced.
2286    fn start_compaction(&mut self, request: &LLMRequest, focus: Option<&str>, events: &EventSink) {
2287        #[cfg(feature = "skills")]
2288        let skills = self.skill_catalog();
2289        #[cfg(not(feature = "skills"))]
2290        let skills = Vec::new();
2291        let attachments = self.context.attachment_catalog(self.context.fork_point());
2292        match CompactionFork::<Schema>::new(
2293            request,
2294            self.context.fork_point(),
2295            self.context.handoff_file_index(),
2296            focus,
2297            &skills,
2298            &attachments,
2299        )
2300        .map(|fork| fork.with_file_references(self.file_references.clone()))
2301        {
2302            Ok(fork) => {
2303                tracing::debug!(
2304                    fork_point = fork.fork_point(),
2305                    usage = self.budget.usage(),
2306                    "forking compaction alongside the run"
2307                );
2308                self.announce_compaction(events, CompactionTrigger::WindowFilling);
2309                self.compaction.start(self.start_pending_compaction(fork));
2310            }
2311            Err(error) => {
2312                tracing::debug!(%error, "compaction not forked");
2313            }
2314        }
2315    }
2316
2317    /// The session's skill catalog, offered to compaction prompts and used to
2318    /// resolve skill names during restoration.
2319    #[cfg(feature = "skills")]
2320    fn skill_catalog(&self) -> Vec<SkillCatalogEntry> {
2321        if let Some(registry) = &self.skill_registry {
2322            return registry
2323                .all()
2324                .into_iter()
2325                .map(|skill| SkillCatalogEntry {
2326                    name: skill.name.clone(),
2327                    description: skill.description.clone(),
2328                    instructions: skill.instructions.clone(),
2329                })
2330                .collect();
2331        }
2332        Vec::new()
2333    }
2334
2335    /// Announces on `events` that a compaction starts.
2336    ///
2337    /// # Panics
2338    ///
2339    /// Panics when the compaction announced before it has not finished:
2340    /// compactions never overlap.
2341    fn announce_compaction(&mut self, events: &EventSink, trigger: CompactionTrigger) {
2342        assert!(
2343            !self.compaction_announced,
2344            "a compaction started before the previous one finished"
2345        );
2346        self.compaction_announced = true;
2347        events.emit(AgentEvent::CompactionStarted { trigger });
2348    }
2349
2350    /// Reports on `events` how the announced compaction ended, if one is
2351    /// announced and not yet finished.
2352    fn finish_compaction(&mut self, events: &EventSink, outcome: CompactionOutcome) {
2353        if std::mem::take(&mut self.compaction_announced) {
2354            events.emit(AgentEvent::CompactionEnded { outcome });
2355        }
2356    }
2357
2358    /// Finishes as discarded an announced compaction that is gone: retired,
2359    /// or dropped with its run, where no stream was open to report it.
2360    fn finish_lost_compaction(&mut self, events: &EventSink) {
2361        if !self.compaction.is_active() {
2362            self.finish_compaction(events, CompactionOutcome::Discarded);
2363        }
2364    }
2365
2366    /// Folds a landed handoff into the window and restores what it named,
2367    /// reporting it on `events`; `None` when no handoff had landed.
2368    ///
2369    /// Called only at request boundaries: the conversation is whole there, so
2370    /// replacing everything below the fork point cannot strand a tool call
2371    /// from its result.
2372    async fn apply_completed_compaction(&mut self, events: &EventSink) -> Option<CompactResult> {
2373        // The files are read while the completed compaction is still stored:
2374        // a caller that drops this future during the read leaves it pending
2375        // for the next boundary, with nothing half applied.
2376        let completed = self.compaction.landed()?;
2377        let handoff = completed.handoff.clone();
2378        let restoration = completed.restoration.clone();
2379        let attachment_catalog = completed.attachment_catalog.clone();
2380        let restored = match self.restore_dir.clone() {
2381            Some(restore_dir) => {
2382                let tokens = self
2383                    .budget
2384                    .fraction_tokens(self.config.context_policy.restore_budget);
2385                let budget_chars = self.budget.chars_for_tokens(tokens);
2386                #[cfg(feature = "skills")]
2387                let skills = self.skill_catalog();
2388                #[cfg(not(feature = "skills"))]
2389                let skills = Vec::new();
2390                restore_context(
2391                    &restoration,
2392                    handoff.file_index(),
2393                    &[restore_dir],
2394                    &skills,
2395                    &attachment_catalog,
2396                    budget_chars,
2397                )
2398                .await
2399            }
2400            None => None,
2401        };
2402
2403        // From here there is no await: the handoff, the cleanup and the
2404        // restored block commit together.
2405        let CompletedCompaction { fork_point, .. } = self.compaction.take_landed()?;
2406        let messages_compacted = self.context.len_below(fork_point);
2407        let summary = handoff.text().to_string();
2408        // Compaction rewrites the cacheable prefix anyway, so this is where
2409        // staged system-block updates and superseded tool results fold in.
2410        self.context.reassemble_below(fork_point);
2411        let user_message_chars = self
2412            .budget
2413            .chars_for_tokens(self.config.context_policy.user_message_budget);
2414        let kept_attachments: HashSet<AttachmentRef> = restoration
2415            .attachments
2416            .iter()
2417            .filter_map(|id| {
2418                attachment_catalog
2419                    .iter()
2420                    .find(|entry| &entry.id == id)
2421                    .map(|entry| entry.reference)
2422            })
2423            .collect();
2424        self.context
2425            .apply_handoff(handoff, fork_point, user_message_chars, &kept_attachments);
2426        if let Some(block) = restored {
2427            self.context.push_block_alert(&block);
2428        }
2429        self.reassembled = true;
2430        self.prefix_rewrites.compacted = true;
2431        self.compaction_failure = None;
2432        tracing::info!(
2433            fork_point,
2434            kept = self.context.len_recent(),
2435            "applied handoff from forked compaction"
2436        );
2437        let result = CompactResult {
2438            messages_compacted,
2439            messages_remaining: self.context.len_recent(),
2440            summary,
2441        };
2442        self.finish_compaction(events, CompactionOutcome::Applied(result.clone()));
2443        Some(result)
2444    }
2445
2446    /// Makes room at the pause point: waits for the compaction in flight and
2447    /// applies it, or runs one now when none is.
2448    ///
2449    /// A compaction that fails — the one in flight, one that failed earlier
2450    /// alongside the run, or the one run here — sends the context through
2451    /// recovery: alerts and reminders are removed, long tool outputs move to
2452    /// files, [`AgentEvent::CompactionRecovery`] tells the host, and the
2453    /// compaction reruns synchronously.
2454    ///
2455    /// Returns `false` when there was nothing to compact, so the window is
2456    /// still over the pause point and the run cannot issue another request.
2457    ///
2458    /// # Errors
2459    ///
2460    /// Returns the error of the rerun when it fails too, or of the file
2461    /// write recovery needed.
2462    async fn make_room(&mut self, events: &EventSink) -> Result<bool, AgentError> {
2463        let mut failure = self.compaction_failure.take().map(AgentError::from);
2464        if let Some(mut pending) = self.compaction.take_running() {
2465            match pending.wait().await {
2466                Ok(completed) => {
2467                    self.compaction.land(completed);
2468                    self.apply_completed_compaction(events).await;
2469                    return Ok(true);
2470                }
2471                Err(error) => {
2472                    tracing::warn!(%error, "compaction failed with the window exhausted");
2473                    let error = AgentError::from(error);
2474                    self.finish_compaction(events, CompactionOutcome::Failed(error.clone()));
2475                    failure = Some(error);
2476                }
2477            }
2478        }
2479        let failure = match failure {
2480            Some(failure) => failure,
2481            None => {
2482                match Box::pin(self.compact_streaming(None, CompactionTrigger::PausePoint, events))
2483                    .await
2484                {
2485                    Ok(result) => return Ok(result.is_some()),
2486                    Err(error) => {
2487                        tracing::warn!(%error, "compaction failed with the window exhausted");
2488                        error
2489                    }
2490                }
2491            }
2492        };
2493
2494        let policy = self.config.context_policy;
2495        let limits = SpillLimits {
2496            threshold: self.budget.chars_for_tokens(policy.spill_threshold),
2497            head: self.budget.chars_for_tokens(policy.spill_head),
2498        };
2499        let fork_point = self.context.fork_point();
2500        let report = clean_for_recovery(
2501            &mut self.context,
2502            fork_point,
2503            self.restore_dir.as_deref(),
2504            limits,
2505        )
2506        .await
2507        .map_err(|error| {
2508            AgentError::llm_local(format!(
2509                "compaction recovery could not move a long tool output to a file: {error}"
2510            ))
2511        })?;
2512        tracing::warn!(
2513            alerts_removed = report.alerts_removed,
2514            outputs_spilled = report.outputs_spilled,
2515            "rerunning the failed compaction on the cleaned context"
2516        );
2517        events.emit(AgentEvent::CompactionRecovery {
2518            error: failure,
2519            alerts_removed: report.alerts_removed,
2520            outputs_spilled: report.outputs_spilled,
2521        });
2522        self.reassembled = true;
2523        self.prefix_rewrites.reassembled = true;
2524        let result =
2525            Box::pin(self.compact_streaming(None, CompactionTrigger::PausePoint, events)).await?;
2526        Ok(result.is_some())
2527    }
2528
2529    /// Tells each source which of its tail blocks have been sent.
2530    ///
2531    /// Separate from assembling the tail so that only a request that
2532    /// actually goes out advances a source's baseline.
2533    async fn commit_tail(&mut self, tail: &RenderedTail) {
2534        for (index, source) in self.context_sources.iter_mut().enumerate() {
2535            let sent: Vec<Block> = tail
2536                .blocks
2537                .iter()
2538                .zip(&tail.sources)
2539                .filter(|(_, owner)| **owner == Some(index))
2540                .map(|(block, _)| block.clone())
2541                .collect();
2542            if !sent.is_empty() {
2543                source.committed(&sent).await;
2544            }
2545        }
2546    }
2547
2548    /// Brings every live source's block to what it renders now.
2549    ///
2550    /// The blocks are prefix content: a change the model has not heard of is
2551    /// announced once, by the alert the source writes for it, and the next
2552    /// reassembly folds the new block into the prefix. Rendering is
2553    /// concurrent because the sources are independent.
2554    async fn sync_live_sources(&mut self, events: &EventSink) {
2555        let rendered =
2556            futures::future::join_all(self.live_sources.iter().map(AnyLiveSource::render)).await;
2557        for (source, desired) in self.live_sources.iter().zip(rendered) {
2558            // An empty block costs a message and says nothing.
2559            let desired = desired.filter(|content| !content.is_empty());
2560            if let Some(alert) =
2561                self.context
2562                    .update_live_source(&source.slot(), desired, |change| source.announce(change))
2563            {
2564                self.budget.append(alert);
2565                events.emit(AgentEvent::ContextInjected {
2566                    source: SourceId::new(source.tag()),
2567                    kind: InjectionKind::LiveChange,
2568                });
2569            }
2570        }
2571    }
2572
2573    /// Appends a source's durable block to the conversation.
2574    fn push_stable_block(&mut self, events: &EventSink, source: &SourceId, block: &Block) {
2575        self.budget.append(block.len());
2576        self.context.push_block_alert(block);
2577        events.emit(AgentEvent::ContextInjected {
2578            source: source.clone(),
2579            kind: InjectionKind::Stable,
2580        });
2581    }
2582
2583    /// Takes in the blocks one source or hook returned at `moment`: a stable
2584    /// block becomes a durable alert at once, a tail block joins `tail`.
2585    ///
2586    /// Returns whether any block was stable.
2587    ///
2588    /// # Panics
2589    ///
2590    /// Panics on a tail block at any moment but a request: only a request
2591    /// has a tail, so the source breaks its contract.
2592    fn take_blocks(
2593        &mut self,
2594        events: &EventSink,
2595        source: &SourceId,
2596        owner: Option<usize>,
2597        moment: Moment,
2598        blocks: Vec<ContextBlock>,
2599        tail: &mut RenderedTail,
2600    ) -> bool {
2601        let mut stable = false;
2602        for block in blocks {
2603            match block.placement() {
2604                Placement::Stable => {
2605                    self.push_stable_block(events, source, block.block());
2606                    stable = true;
2607                }
2608                Placement::Tail => {
2609                    assert!(
2610                        matches!(moment, Moment::Request { .. }),
2611                        "context source `{}` returned a tail block at {moment:?}; only a request has a tail",
2612                        source.as_str(),
2613                    );
2614                    events.emit(AgentEvent::ContextInjected {
2615                        source: source.clone(),
2616                        kind: InjectionKind::Tail,
2617                    });
2618                    tail.blocks.push(block.block().clone());
2619                    tail.sources.push(owner);
2620                }
2621            }
2622        }
2623        stable
2624    }
2625
2626    /// Collects what the sources and the `before_request` hook put in front
2627    /// of a request: the one moment live content and sources are read, so
2628    /// nothing is written while the agent is idle.
2629    ///
2630    /// Stable blocks are appended to the conversation; tail blocks are
2631    /// returned, and kept as the tail previews and snapshots show. Sources
2632    /// are told whether the window was reassembled since the last time,
2633    /// which is when their earlier stable blocks stopped being in it.
2634    async fn collect_request_context(&mut self, cx: &RunCx<'_>, turn: usize) -> RenderedTail {
2635        self.sync_live_sources(cx.events).await;
2636        let reassembled = std::mem::take(&mut self.reassembled);
2637        let moment = Moment::Request { reassembled };
2638        let mut tail = RenderedTail::default();
2639        for index in 0..self.context_sources.len() {
2640            let blocks = self.context_sources[index].blocks(moment).await;
2641            let id = self.context_sources[index].id();
2642            self.take_blocks(cx.events, &id, Some(index), moment, blocks, &mut tail);
2643        }
2644        let request = RequestCx {
2645            run: cx.run,
2646            turn,
2647            message_count: self.context.len_recent(),
2648        };
2649        let blocks = self.hooks.before_request(&request).await;
2650        self.take_blocks(
2651            cx.events,
2652            &SourceId::new("hooks"),
2653            None,
2654            moment,
2655            blocks,
2656            &mut tail,
2657        );
2658        tail
2659    }
2660
2661    /// Collects what sources return after a tool turn, and the context the
2662    /// turn's `after_tool` hooks appended.
2663    async fn push_tool_turn_context(&mut self, cx: &RunCx<'_>, appended: Vec<String>) {
2664        let mut tail = RenderedTail::default();
2665        for index in 0..self.context_sources.len() {
2666            let blocks = self.context_sources[index]
2667                .blocks(Moment::ToolTurnEnd)
2668                .await;
2669            let id = self.context_sources[index].id();
2670            self.take_blocks(
2671                cx.events,
2672                &id,
2673                Some(index),
2674                Moment::ToolTurnEnd,
2675                blocks,
2676                &mut tail,
2677            );
2678        }
2679        let hooks = SourceId::new("hooks");
2680        for content in appended {
2681            self.push_stable_block(cx.events, &hooks, &Block::new("tool-context", content));
2682        }
2683    }
2684
2685    /// Collects what sources return when the model wants to stop.
2686    ///
2687    /// Returns `true` when at least one source objected, which keeps the loop
2688    /// running for another turn so the model can act on the objection.
2689    async fn push_final_turn_context(&mut self, cx: &RunCx<'_>) -> bool {
2690        let mut tail = RenderedTail::default();
2691        let mut objected = false;
2692        for index in 0..self.context_sources.len() {
2693            let blocks = self.context_sources[index].blocks(Moment::FinalTurn).await;
2694            let id = self.context_sources[index].id();
2695            objected |= self.take_blocks(
2696                cx.events,
2697                &id,
2698                Some(index),
2699                Moment::FinalTurn,
2700                blocks,
2701                &mut tail,
2702            );
2703        }
2704        objected
2705    }
2706
2707    /// Asks the `on_stop` hook whether the run ends as the model ends its
2708    /// turn, and pushes the hook's reason as a reminder when it holds the
2709    /// run.
2710    ///
2711    /// Returns whether the hook holds the run.
2712    async fn decide_stop(&mut self, cx: &RunCx<'_>, response_text: &str, turn: usize) -> bool {
2713        let stop = StopCx {
2714            final_text: response_text,
2715            turn,
2716            message_count: self.context.len_recent(),
2717        };
2718        match self.hooks.on_stop(&stop).await {
2719            StopDecision::End => false,
2720            StopDecision::Continue { reason } => {
2721                let block = Block::new(
2722                    "system_reminder",
2723                    SystemReminderTemplate { content: reason }
2724                        .render()
2725                        .expect("system reminder template must render"),
2726                );
2727                self.push_stable_block(cx.events, &SourceId::new("hooks"), &block);
2728                true
2729            }
2730        }
2731    }
2732
2733    /// Returns the current conversation history.
2734    #[must_use]
2735    pub fn history(&self) -> Vec<Message> {
2736        self.context.conversation_messages()
2737    }
2738
2739    fn tool_surface_hash(&self) -> String {
2740        let mut names = self
2741            .tools
2742            .active_definitions()
2743            .into_iter()
2744            .map(|definition| definition.name().to_string())
2745            .collect::<Vec<_>>();
2746        names.sort();
2747        let mut hasher = Sha256::new();
2748        for name in names {
2749            hasher.update(name.as_bytes());
2750            hasher.update(b"\n");
2751        }
2752        hex_encode(hasher.finalize().as_slice())
2753    }
2754
2755    /// Export a checkpoint bundle for restart-safe persistence.
2756    ///
2757    /// # Errors
2758    ///
2759    /// Returns an error when checkpoint construction or checkpoint hooks fail.
2760    pub async fn export_checkpoint(&mut self) -> Result<AgentCheckpoint, AgentError> {
2761        self.ensure_initialized().await?;
2762        let context_window = self.snapshot_context_window().await?;
2763        Ok(AgentCheckpoint {
2764            context: self.context.checkpoint(),
2765            tool_surface_hash: self.tool_surface_hash(),
2766            context_window,
2767        })
2768    }
2769
2770    /// Restore a previously exported checkpoint bundle.
2771    ///
2772    /// # Errors
2773    ///
2774    /// Returns an error when the checkpoint cannot be restored into this agent.
2775    pub fn restore_checkpoint(&mut self, checkpoint: AgentCheckpoint) -> Result<(), AgentError> {
2776        self.context.restore(checkpoint.context);
2777        // Everything below belongs to the window just replaced: its fork
2778        // point, its failure, its parked tool results and its last request
2779        // mean nothing in the restored one.
2780        self.compaction.retire();
2781        self.compaction_failure = None;
2782        self.idle_compacted = false;
2783        self.tool_results.clear();
2784        self.last_request = None;
2785        Ok(())
2786    }
2787
2788    /// Returns a structured snapshot of the current context window.
2789    ///
2790    /// This is a pure measurement: no source baseline is advanced and no
2791    /// alert is consumed, so a host may poll it as often as it likes.
2792    ///
2793    /// # Errors
2794    ///
2795    /// Returns an error when the model profiles cannot be fetched during
2796    /// initialization.
2797    pub async fn snapshot_context_window(&mut self) -> Result<ContextWindowSnapshot, AgentError> {
2798        self.ensure_initialized().await?;
2799        Ok(self.context_window_snapshot(&self.last_tail))
2800    }
2801
2802    /// The identity this agent was built with.
2803    #[must_use]
2804    pub const fn identity(&self) -> &aither_core::llm::AgentIdentity {
2805        &self.identity
2806    }
2807
2808    /// Returns the model profile if available.
2809    #[must_use]
2810    pub const fn profile(&self) -> Option<&ModelProfile> {
2811        self.profile.as_ref()
2812    }
2813
2814    /// Ensures the agent is initialized: the profiles fetched and the window
2815    /// sized to the model.
2816    ///
2817    /// The profile is fetched again after the agent's own model was
2818    /// replaced.
2819    async fn ensure_initialized(&mut self) -> Result<(), AgentError> {
2820        if self.profile.is_none() {
2821            self.load_profile().await?;
2822        }
2823        if self.compaction_profile.is_none()
2824            && let Some(compactor) = &self.compaction_model
2825        {
2826            self.compaction_profile = Some(
2827                compactor
2828                    .model
2829                    .profile()
2830                    .await
2831                    .map_err(|e| AgentError::from_model_error(&e))?,
2832            );
2833        }
2834        self.initialized = true;
2835        Ok(())
2836    }
2837
2838    /// Fetches the profile of the agent's own model and sizes the window to
2839    /// it.
2840    async fn load_profile(&mut self) -> Result<(), AgentError> {
2841        // The window of the conversation model is the only one the budget
2842        // may spend: compaction replays the main request's prefix through the
2843        // same model, so no second profile is involved.
2844        let profile = self
2845            .model
2846            .profile()
2847            .await
2848            .map_err(|e| AgentError::from_model_error(&e))?;
2849        let policy = self.config.context_policy;
2850        if !policy.admits(profile.context_length) {
2851            return Err(AgentError::Config(format!(
2852                "the {}-token context window is no larger than the {}-token handoff reserve, \
2853                 so nothing fits below the pause point; lower `ContextPolicy::handoff_reserve`",
2854                profile.context_length, policy.handoff_reserve,
2855            )));
2856        }
2857        self.budget.set_window(profile.context_length);
2858        self.profile = Some(profile);
2859        Ok(())
2860    }
2861
2862    /// How the conversation model counts prompt tokens, if it can.
2863    fn active_token_counting(&self) -> TokenCounting {
2864        self.model.token_counting()
2865    }
2866
2867    /// Asks the conversation model for the request's exact prompt tokens.
2868    ///
2869    /// Local counters run on every assembly; an endpoint counter costs a
2870    /// round trip, so it counts only once the estimate is within
2871    /// [`ContextPolicy::count_distance`] of the warn point. A counting
2872    /// failure never fails the request — the estimate stands.
2873    async fn count_active_request(&self, request: &LLMRequest) -> Option<u32> {
2874        let should_count = match self.active_token_counting() {
2875            TokenCounting::None => return None,
2876            TokenCounting::Local => true,
2877            TokenCounting::Endpoint => self
2878                .config
2879                .context_policy
2880                .should_count_endpoint(self.budget.estimated_tokens(), self.budget.window()),
2881        };
2882        if !should_count {
2883            return None;
2884        }
2885        match self
2886            .model
2887            .count_tokens(request)
2888            .await
2889            .map_err(|error| error.to_string())
2890        {
2891            Ok(tokens) => tokens,
2892            Err(error) => {
2893                tracing::warn!(%error, "token counting failed; using the estimate");
2894                None
2895            }
2896        }
2897    }
2898
2899    /// Records the assembled prompt's size — exactly, when the model can
2900    /// count it.
2901    async fn measure_assembled(
2902        &mut self,
2903        messages: &[Message],
2904        definitions: &[aither_core::llm::tool::ToolDefinition],
2905    ) {
2906        self.budget
2907            .observe_assembled(request_chars(messages, definitions));
2908        if matches!(self.active_token_counting(), TokenCounting::None) {
2909            return;
2910        }
2911        let request =
2912            LLMRequest::new(messages.to_vec()).with_tool_definitions(definitions.to_vec());
2913        if let Some(tokens) = self.count_active_request(&request).await {
2914            self.budget.observe_counted(tokens);
2915        }
2916    }
2917
2918    /// Assembles the next request, handling the window's lifecycle first.
2919    ///
2920    /// This is the only request boundary there is, and everything that must
2921    /// not happen mid-turn happens here, in order: a landed handoff is
2922    /// folded in, the window is measured against the provider's own token
2923    /// counts, a compaction is forked if usage crossed
2924    /// [`ContextPolicy::start_point`], and the compaction is awaited (or run,
2925    /// with recovery when it fails) once the room left before the
2926    /// pause point is reached — the window is down to the handoff reserve.
2927    ///
2928    /// With a compaction model set, a cache that went cold since the last
2929    /// request is rebuilt first (`rebuild_if_cache_is_cold`).
2930    ///
2931    /// Returns `None` when the window is exhausted and no compaction can
2932    /// relieve it: the caller pauses the run rather than sending a request
2933    /// the provider would reject for length.
2934    ///
2935    /// # Errors
2936    ///
2937    /// Returns the compaction failure when the cold-cache compaction fails;
2938    /// nothing is sent on an uncompacted context.
2939    ///
2940    /// [`ContextPolicy::start_point`]: crate::ContextPolicy::start_point
2941    async fn prepare_request(
2942        &mut self,
2943        cx: &RunCx<'_>,
2944        turn: usize,
2945    ) -> Result<Option<(LLMRequest, PromptPrefix)>, AgentError> {
2946        let events = cx.events;
2947        self.forward_child_events(events);
2948        self.apply_completed_compaction(events).await;
2949        self.rebuild_if_cache_is_cold(events).await?;
2950        self.settle_effort()?;
2951
2952        let definitions = self.tools.active_definitions();
2953        let mut tail = self.collect_request_context(cx, turn).await;
2954        let mut messages = self.request_messages(&tail);
2955        self.measure_assembled(&messages, &definitions).await;
2956
2957        if self
2958            .config
2959            .context_policy
2960            .should_compact(self.budget.estimated_tokens(), self.budget.window())
2961            && !self.compaction.is_active()
2962        {
2963            let fork_request = self.compaction_request(messages.clone(), definitions.clone());
2964            self.start_compaction(&fork_request, None, events);
2965        }
2966
2967        if self
2968            .config
2969            .context_policy
2970            .should_pause(self.budget.estimated_tokens(), self.budget.window())
2971        {
2972            tracing::warn!(
2973                tokens = self.budget.estimated_tokens(),
2974                "context window at the safe buffer; waiting for compaction"
2975            );
2976            if !self.make_room(events).await? {
2977                return Ok(None);
2978            }
2979            tail = self.collect_request_context(cx, turn).await;
2980            messages = self.request_messages(&tail);
2981            self.measure_assembled(&messages, &definitions).await;
2982            // A landed compaction is still no guarantee the rebuilt request
2983            // fits; an unshrinkable request is paused rather than sent.
2984            if self
2985                .config
2986                .context_policy
2987                .should_pause(self.budget.estimated_tokens(), self.budget.window())
2988            {
2989                return Ok(None);
2990            }
2991        }
2992
2993        self.commit_tail(&tail).await;
2994        self.context.mark_prefix_carried();
2995        self.delivering = Some(self.context.fork_point());
2996        self.warmth.start_entry_now();
2997        self.idle_compacted = false;
2998        self.publish_fork_snapshot(&tail, &definitions);
2999        self.last_tail.clone_from(&tail.blocks);
3000
3001        let has_tools = !definitions.is_empty();
3002        let prefix = PromptPrefix {
3003            chain: PrefixChain::of(&definitions, &messages),
3004            rewrites: std::mem::take(&mut self.prefix_rewrites),
3005            first_request: self.requests_sent == 0,
3006        };
3007        self.requests_sent += 1;
3008        self.prompt_cache
3009            .observe_prefix(self.context.stable_prefix_fingerprint());
3010        let parameters = self.prompt_cache.apply(
3011            self.request_parameters(),
3012            &messages,
3013            has_tools,
3014            self.takes_mid_conversation_system(),
3015        );
3016        let request = LLMRequest::new(messages)
3017            .with_parameters(parameters)
3018            .with_tool_definitions(definitions);
3019        self.last_request = Some(request.clone());
3020        Ok(Some((request, prefix)))
3021    }
3022
3023    /// Publishes the request about to be sent for a fork to start from.
3024    fn publish_fork_snapshot(
3025        &self,
3026        tail: &[Block],
3027        definitions: &[aither_core::llm::tool::ToolDefinition],
3028    ) {
3029        let Some(source) = &self.fork_source else {
3030            return;
3031        };
3032        let mut context = self.context.clone();
3033        context.push_tail(tail);
3034        source.publish(crate::fork::ForkSnapshot {
3035            context,
3036            prompt_cache: self.prompt_cache.clone(),
3037            budget: self.budget,
3038            profile: self
3039                .profile
3040                .clone()
3041                .expect("a request is only sent by an initialized agent, which has its profile"),
3042            request_parameters: (*self.parameters).clone(),
3043            effort: self.effort,
3044            context_policy: self.config.context_policy,
3045            definitions: definitions.to_vec(),
3046            usage: self.budget.usage(),
3047        });
3048    }
3049
3050    /// Rebuilds the prefix once, before a send, when the provider's cache has
3051    /// gone cold.
3052    ///
3053    /// Only with a compaction model set (otherwise the session is compacted
3054    /// shortly before the cache expires, see [`Agent::compact_when_idle`], and
3055    /// a send never rebuilds). The cache is cold when the conversation's
3056    /// [`CacheLifetime`] has passed since the entry was last used; a permanent
3057    /// lifetime never is, and nothing runs while the session is idle.
3058    ///
3059    /// The compaction model reads the context uncached whatever the timing, so
3060    /// compacting now costs no more than later, and the send then pays its
3061    /// cache write on the compacted context instead of the whole one. The
3062    /// compaction's apply already reassembles the window, so the prefix is
3063    /// rewritten once: reassembly alone runs only when there is no
3064    /// conversation to compact. Nothing is kept across the handoff, so no
3065    /// thinking produced under the old prefix is replayed after it.
3066    ///
3067    /// A forked compaction already in flight lands and rebuilds the prefix
3068    /// itself, so it is left alone.
3069    ///
3070    /// [`CacheLifetime`]: crate::context::CacheLifetime
3071    async fn rebuild_if_cache_is_cold(&mut self, events: &EventSink) -> Result<(), AgentError> {
3072        if self.compaction_model.is_none() || self.compaction.is_running() {
3073            return Ok(());
3074        }
3075        if !self.warmth.has_expired() {
3076            return Ok(());
3077        }
3078        if self.context.is_conversation_empty() {
3079            self.reassemble_if_cache_is_cold();
3080            return Ok(());
3081        }
3082        // Boxed: the compaction future is large and sits on every run's path
3083        // (see `run_futures_stay_small_with_a_real_provider_type`).
3084        if let Some(result) =
3085            Box::pin(self.compact_streaming(None, CompactionTrigger::ColdCache, events)).await?
3086        {
3087            tracing::info!(
3088                compacted = result.messages_compacted,
3089                "compacted the context before sending on a cold cache"
3090            );
3091        }
3092        Ok(())
3093    }
3094
3095    /// Rebuilds the window once the provider's cache has gone cold anyway.
3096    ///
3097    /// Reached only for a session with a compaction model and nothing to
3098    /// compact (`rebuild_if_cache_is_cold`).
3099    ///
3100    /// Reassembly rewrites the cacheable prefix, so it is only free once the
3101    /// cached copy has expired — an idle gap at least as long as the
3102    /// conversation's [`CacheLifetime`]. A staged system-block rewrite and
3103    /// superseded tool results wait for exactly that moment; a permanent
3104    /// cache lifetime means no idle gap ever justifies the rewrite.
3105    ///
3106    /// [`CacheLifetime`]: crate::context::CacheLifetime
3107    fn reassemble_if_cache_is_cold(&mut self) -> crate::context::ReassemblyReport {
3108        let unchanged = crate::context::ReassemblyReport::default();
3109        if !self.warmth.has_expired() {
3110            return unchanged;
3111        }
3112        let report = self.context.reassemble();
3113        self.reassembled |= report.system_messages_pruned > 0;
3114        self.prefix_rewrites.reassembled |= report.changed();
3115        if report.changed() {
3116            tracing::debug!(
3117                system_messages = report.system_messages_pruned,
3118                deduped = report.tool_results_deduped,
3119                bytes_freed = report.bytes_freed,
3120                "rebuilt the context window on a cold cache"
3121            );
3122        }
3123        report
3124    }
3125
3126    /// Measures the window exactly as it stands, against a rendered `tail`.
3127    ///
3128    /// Pure, so checkpoints and status displays can call it at any point in
3129    /// a turn without disturbing what the next request will carry.
3130    fn context_window_snapshot(&self, tail: &[Block]) -> ContextWindowSnapshot {
3131        let messages = self.context.build_request(tail);
3132        let metrics = self.context_window_metrics(&messages);
3133        ContextWindowSnapshot {
3134            phase: self.classify_context_window_phase(&metrics),
3135            metrics,
3136            messages,
3137        }
3138    }
3139
3140    fn context_window_metrics(&self, messages: &[Message]) -> ContextWindowMetrics {
3141        let mut budget = self.budget;
3142        budget.observe_assembled(request_chars(messages, &self.tools.active_definitions()));
3143        ContextWindowMetrics {
3144            usage_fraction: budget.usage(),
3145            context_window: budget.window(),
3146            estimated_tokens: budget.estimated_tokens(),
3147            chars_per_token: budget.chars_per_token(),
3148            system_block_count: self.context.system_block_count(),
3149            recent_message_count: self.context.len_recent(),
3150            recent_system_message_count: self.context.count_recent_system_messages(),
3151            has_handoff: self.context.handoff().is_some(),
3152            has_staged_system_updates: self.context.has_staged_system_updates(),
3153            prompt_cache_epoch: self.prompt_cache.epoch(),
3154        }
3155    }
3156
3157    fn classify_context_window_phase(&self, metrics: &ContextWindowMetrics) -> ContextWindowPhase {
3158        let policy = &self.config.context_policy;
3159        if policy.should_pause(metrics.estimated_tokens, metrics.context_window) {
3160            return ContextWindowPhase::Exhausted;
3161        }
3162        if self.compaction.is_active() {
3163            return ContextWindowPhase::Compacting;
3164        }
3165        if metrics.has_staged_system_updates
3166            || (self.compaction_model.is_some() && self.warmth.has_expired())
3167        {
3168            return ContextWindowPhase::ReassemblyDue;
3169        }
3170        ContextWindowPhase::Stable
3171    }
3172
3173    /// Returns the exact request message sequence that would be sent for the next turn.
3174    ///
3175    /// Intended for observability and debug UIs: the prompt is added to a
3176    /// forked context and the sources are rendered without committing, so a
3177    /// preview cannot consume a change the real request should surface.
3178    ///
3179    /// # Errors
3180    ///
3181    /// Returns an error when the model profiles cannot be fetched during
3182    /// initialization.
3183    pub async fn preview_request_messages(
3184        &mut self,
3185        prompt: &str,
3186        attachments: impl IntoIterator<Item = Attachment>,
3187    ) -> Result<Vec<Message>, AgentError> {
3188        self.preview_request_messages_with(prompt, std::iter::empty(), attachments)
3189            .await
3190    }
3191
3192    /// Returns the exact request message sequence that would be sent for the
3193    /// next turn, with `extra_messages` appended at the conversation tail
3194    /// before the prompt.
3195    ///
3196    /// This is the non-mutating counterpart of pushing those messages onto the
3197    /// live context and then running the turn — the shape a host gets for
3198    /// per-turn hidden context injected ahead of the user's message. The
3199    /// extras are not persisted: the context and the sources' committed state
3200    /// are left exactly as a normal first assembly would, because sources are
3201    /// only told about a request once it is actually sent.
3202    ///
3203    /// The tail and the stable blocks are the ones the request would carry:
3204    /// the sources are asked through [`ContextSource::peek`] and the
3205    /// `before_request` hook is asked as it would be, so nothing a source
3206    /// holds for delivery is consumed. A live source's change is not
3207    /// previewed, since staging it writes to the context.
3208    ///
3209    /// # Errors
3210    ///
3211    /// Returns an error when the model profiles cannot be fetched during
3212    /// initialization.
3213    pub async fn preview_request_messages_with(
3214        &mut self,
3215        prompt: &str,
3216        extra_messages: impl IntoIterator<Item = Message>,
3217        attachments: impl IntoIterator<Item = Attachment>,
3218    ) -> Result<Vec<Message>, AgentError> {
3219        self.ensure_initialized().await?;
3220        let moment = Moment::Request {
3221            reassembled: self.reassembled,
3222        };
3223        let mut blocks = Vec::new();
3224        for source in &self.context_sources {
3225            blocks.extend(source.peek(moment).await);
3226        }
3227        let checkpoint = self.context.checkpoint();
3228        self.context.extend(extra_messages);
3229        self.context
3230            .push(Message::user(prompt).with_attachments(attachments));
3231        let run = RunId::new("preview");
3232        let request = RequestCx {
3233            run: &run,
3234            turn: 1,
3235            message_count: self.context.len_recent(),
3236        };
3237        blocks.extend(self.hooks.before_request(&request).await);
3238        let mut tail = Vec::new();
3239        for block in blocks {
3240            match block.placement() {
3241                Placement::Stable => {
3242                    self.context.push_block_alert(block.block());
3243                }
3244                Placement::Tail => tail.push(block.block().clone()),
3245            }
3246        }
3247        let messages = self.request_messages(&tail);
3248        self.context.restore(checkpoint);
3249        Ok(messages)
3250    }
3251
3252    /// Tells the embedder the agent's state changed, so it can persist it
3253    /// with [`export_checkpoint`](Self::export_checkpoint).
3254    fn emit_checkpoint(&self, cx: &RunCx<'_>, reason: CheckpointReason, turn: usize) {
3255        let window = self.context_window_snapshot(&self.last_tail);
3256        let phase = window.phase;
3257        // Recorded before the event is queued, so a handler that sees the
3258        // event reads this checkpoint or a newer one.
3259        cx.events.checkpoints.record(AgentCheckpoint {
3260            context: self.context.checkpoint(),
3261            tool_surface_hash: self.tool_surface_hash(),
3262            context_window: window,
3263        });
3264        cx.events.emit(AgentEvent::Checkpoint {
3265            run: cx.run.clone(),
3266            reason,
3267            turn,
3268            phase,
3269            message_count: self.context.len_recent(),
3270        });
3271    }
3272}
3273
3274fn format_builtin_tool_result(tool: &str, result: &str) -> String {
3275    format!("[{tool}] {result}\n")
3276}
3277
3278pub fn hex_encode(bytes: &[u8]) -> String {
3279    use std::fmt::Write as _;
3280
3281    let mut output = String::with_capacity(bytes.len() * 2);
3282    for byte in bytes {
3283        write!(output, "{byte:02x}").expect("writing to a String cannot fail");
3284    }
3285    output
3286}
3287
3288#[cfg(test)]
3289mod call_identity_tests;
3290#[cfg(test)]
3291mod idle_compaction_tests;
3292#[cfg(test)]
3293mod keep_warm_tests;
3294#[cfg(test)]
3295mod tests;