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 conversation memory, applies context compression, and
5//! handles tool execution in an agent-controlled loop.
6
7use num_traits::ToPrimitive as _;
8use std::path::PathBuf;
9use std::time::{Duration, Instant};
10
11use aither_core::{
12    LanguageModel,
13    llm::{
14        Attachment, Event, LLMRequest, Message, ReasoningState, ToolCall,
15        model::Profile as ModelProfile,
16    },
17};
18#[cfg(feature = "skills")]
19use aither_skills::Skill;
20use askama::Template;
21use futures_core::Stream;
22use futures_lite::StreamExt;
23use sha2::{Digest, Sha256};
24#[cfg(feature = "skills")]
25use std::collections::HashSet;
26
27use crate::{
28    checkpoint::AgentCheckpoint,
29    compression::{ContextStrategy, estimate_context_usage},
30    config::{AgentConfig, AgentKind},
31    context::{Context, serialize_xml},
32    context_window::{ContextWindowMetrics, ContextWindowPhase, ContextWindowSnapshot},
33    error::AgentError,
34    event::{AgentEvent, RunPauseReason},
35    handoff::HandoffDocument,
36    hook::{
37        CheckpointContext, CheckpointReason, Hook, PostToolAction, PreToolAction, StopContext,
38        StopReason, ToolResultContext, ToolUseContext, TurnBoundaryAction, TurnBoundaryContext,
39    },
40    model_group::ModelTier,
41    tools::AgentTools,
42    transcript::Transcript,
43    working_docs,
44};
45
46use aither_sandbox::{
47    BackgroundReason, BackgroundTaskReceiver, JobRegistry, PermissionEvent,
48    PermissionEventReceiver, PermissionEventStage, TERMINAL_STDIN_BLOCKED_NOTICE, TerminalArgs,
49    TerminalExecutionMode, TerminalMode,
50};
51use std::collections::{HashMap, VecDeque};
52#[cfg(feature = "skills")]
53use std::sync::Arc;
54
55const BACKGROUND_TASK_MAX_WAIT: Duration = Duration::from_secs(300);
56const BACKGROUND_TASK_POLL_INTERVAL: Duration = Duration::from_millis(100);
57const FOCUS_INSTRUCTION_PLACEHOLDER: &str = "{focus_instruction}";
58
59enum ExecutionSignal<T> {
60    Tool(T),
61    Permission(PermissionEvent),
62}
63
64struct ModelTurn {
65    response_text: String,
66    tool_calls: Vec<ToolCall>,
67    /// Opaque provider reasoning produced this turn, in the order it arrived.
68    ///
69    /// Replayed on the next request: providers that verify their own reasoning
70    /// reject a turn whose blocks were reordered or partially dropped.
71    reasoning: Vec<ReasoningState>,
72    malformed_function_call: bool,
73}
74
75/// Streams agent events to the consumer as they happen.
76///
77/// Wraps an unbounded channel: emitting never blocks, and events emitted
78/// after the consumer dropped the stream are discarded.
79#[derive(Clone)]
80struct EventSink {
81    sender: async_channel::Sender<AgentEvent>,
82}
83
84impl EventSink {
85    fn emit(&self, event: AgentEvent) {
86        let _ = self.sender.try_send(event);
87    }
88}
89
90/// One step of the merged run/event stream in [`Agent::run`].
91enum RunStep {
92    Event(Option<AgentEvent>),
93    Finished(Result<(), AgentError>),
94}
95
96struct RunLoopOutcome {
97    final_text: String,
98    stop_reason: StopReason,
99    iteration: usize,
100}
101
102enum TurnControl {
103    Continue,
104    Break {
105        final_text: String,
106        stop_reason: StopReason,
107    },
108}
109
110enum ModelEventAction {
111    Emit(AgentEvent),
112    Continue,
113    RetryMalformed,
114}
115
116type ToolExecutionResult = Result<(String, String, aither_core::llm::ToolResult), AgentError>;
117type ToolExecutionSignal = ExecutionSignal<ToolExecutionResult>;
118
119macro_rules! drain_model_stream {
120    ($stream:expr, $hooks:expr, $cache_stats:expr, $events:expr, $text_chunks:expr, $tool_calls:expr, $reasoning:expr, $malformed:expr) => {{
121        let stream = $stream;
122        futures_lite::pin!(stream);
123        while let Some(event) = stream.next().await {
124            match handle_model_event(
125                $hooks,
126                $cache_stats,
127                event.map_err(|error| error.to_string()),
128                $text_chunks,
129                $tool_calls,
130                $reasoning,
131            )
132            .await?
133            {
134                ModelEventAction::Emit(event) => $events.emit(event),
135                ModelEventAction::Continue => {}
136                ModelEventAction::RetryMalformed => {
137                    $malformed = true;
138                    break;
139                }
140            }
141        }
142    }};
143}
144
145async fn handle_model_event<H: Hook>(
146    hooks: &H,
147    cache_stats: &mut crate::CacheStats,
148    event: Result<Event, String>,
149    text_chunks: &mut Vec<String>,
150    tool_calls: &mut Vec<ToolCall>,
151    reasoning: &mut Vec<ReasoningState>,
152) -> Result<ModelEventAction, AgentError> {
153    match event {
154        Ok(Event::Text(text)) => {
155            hooks.on_text(&text).await;
156            text_chunks.push(text.clone());
157            Ok(ModelEventAction::Emit(AgentEvent::Text(text)))
158        }
159        Ok(Event::Reasoning(reasoning)) => {
160            Ok(ModelEventAction::Emit(AgentEvent::Reasoning(reasoning)))
161        }
162        Ok(Event::ToolCallDelta {
163            id,
164            name,
165            arguments_fragment,
166        }) => Ok(ModelEventAction::Emit(AgentEvent::ToolCallDelta {
167            id,
168            name,
169            arguments_fragment,
170        })),
171        Ok(Event::ToolCall(call)) => {
172            tool_calls.push(call);
173            Ok(ModelEventAction::Continue)
174        }
175        // State, unlike Reasoning, is not for the reader: it is collected so
176        // the next request can hand it back to the provider.
177        Ok(Event::ReasoningState(state)) => {
178            reasoning.push(state);
179            Ok(ModelEventAction::Continue)
180        }
181        Ok(Event::BuiltInToolResult { tool, result }) => {
182            let formatted = format_builtin_tool_result(&tool, &result);
183            text_chunks.push(formatted.clone());
184            Ok(ModelEventAction::Emit(AgentEvent::Text(formatted)))
185        }
186        Ok(Event::Usage(usage)) => {
187            cache_stats.record(&usage);
188            Ok(ModelEventAction::Emit(AgentEvent::Usage(usage)))
189        }
190        Err(error) if error.contains("malformed function call") => {
191            tracing::warn!("Model generated malformed function call, retrying...");
192            Ok(ModelEventAction::RetryMalformed)
193        }
194        Err(error) => Err(AgentError::Llm(error)),
195    }
196}
197
198fn ensure_non_empty_tool_call_ids(
199    tool_calls: &[ToolCall],
200    response_text: &str,
201) -> Result<(), AgentError> {
202    if tool_calls.iter().all(|call| !call.id.trim().is_empty()) {
203        return Ok(());
204    }
205    let tool_calls_json = serde_json::to_string(tool_calls)
206        .unwrap_or_else(|error| format!("failed to serialize tool calls: {error}"));
207    Err(AgentError::Llm(format!(
208        "provider emitted tool call with empty id; response_text={response_text:?}; tool_calls={tool_calls_json}"
209    )))
210}
211
212/// Result of a compaction operation.
213#[derive(Debug, Clone)]
214pub struct CompactResult {
215    /// Number of messages that were compacted.
216    pub messages_compacted: usize,
217    /// Number of messages remaining (preserved).
218    pub messages_remaining: usize,
219    /// The generated summary.
220    pub summary: String,
221}
222
223#[derive(serde::Serialize)]
224struct SystemReminder {
225    #[serde(rename = "$text")]
226    content: String,
227}
228
229#[derive(serde::Serialize)]
230struct Tasks {
231    #[serde(rename = "$text")]
232    content: String,
233}
234
235#[derive(serde::Serialize)]
236struct TasksDiffReminder {
237    #[serde(rename = "$text")]
238    diff: String,
239}
240
241#[derive(serde::Serialize)]
242struct TasksStale {
243    #[serde(rename = "$text")]
244    content: String,
245}
246
247/// Tracks tasks.md maintenance across tool turns.
248///
249/// A turn counts as stale when the model executed tool calls without the
250/// file's content changing. The counter resets on any content change, and
251/// also while the document has no unchecked items (a complete checklist is
252/// not stale). The alert fires once per stale episode.
253#[derive(Debug, Default)]
254pub struct TasksDocStaleness {
255    /// Whether a baseline observation exists yet.
256    seen: bool,
257    /// tasks.md content at the previous tool turn (None = file absent).
258    last_content: Option<String>,
259    /// Consecutive tool turns without a content change.
260    stale_turns: usize,
261    /// Whether the current episode already alerted.
262    alerted: bool,
263}
264
265#[derive(Debug, Clone, Copy)]
266struct EmittedCheckpoint {
267    phase: ContextWindowPhase,
268    message_count: usize,
269}
270
271#[derive(Template)]
272#[template(path = "background_started_reminder.txt", escape = "none")]
273struct BackgroundStartedReminderTemplate<'a> {
274    task_id: &'a str,
275    output_preview: &'a str,
276    output_file: &'a str,
277}
278
279/// `knowledge_and_time` system block. `websearch_command` selects whether the
280/// verification hint names the `websearch` CLI command or a provider-native
281/// web search capability.
282#[derive(Template)]
283#[template(path = "knowledge_and_time.txt", escape = "none")]
284pub struct KnowledgeAndTimeTemplate {
285    pub websearch_command: bool,
286}
287
288#[derive(serde::Serialize)]
289struct BackgroundTerminalResultXml {
290    #[serde(rename = "@task_id")]
291    task_id: String,
292    script: String,
293    #[serde(skip_serializing_if = "Option::is_none")]
294    exit_code: Option<i32>,
295    #[serde(skip_serializing_if = "Option::is_none")]
296    output: Option<String>,
297    #[serde(skip_serializing_if = "Option::is_none")]
298    stderr: Option<String>,
299    #[serde(skip_serializing_if = "Option::is_none")]
300    error: Option<String>,
301}
302
303struct BackgroundTaskStartedEvent {
304    task_id: String,
305    output_preview: String,
306    output_file: String,
307    reminder: String,
308    reason: BackgroundReason,
309}
310
311struct TerminalInputNeededEvent {
312    task_id: Option<String>,
313    notice: String,
314}
315
316#[derive(Debug, Clone, PartialEq, Eq, Hash)]
317struct PermissionEventKey {
318    mode: TerminalMode,
319    script: String,
320}
321
322#[derive(Debug, Default)]
323struct PermissionPauseTracker {
324    pending: HashMap<PermissionEventKey, VecDeque<String>>,
325    active: HashMap<PermissionEventKey, VecDeque<String>>,
326}
327
328impl PermissionPauseTracker {
329    fn from_tool_calls(tool_calls: &[aither_core::llm::ToolCall]) -> Self {
330        let mut tracker = Self::default();
331        for call in tool_calls {
332            let Some(key) = permission_event_key_for_call(call.name.as_str(), &call.arguments)
333            else {
334                continue;
335            };
336            tracker
337                .pending
338                .entry(key)
339                .or_default()
340                .push_back(call.id.clone());
341        }
342        tracker
343    }
344
345    fn event_for(&mut self, event: PermissionEvent) -> Option<(RunPauseReason, String)> {
346        let key = PermissionEventKey {
347            mode: event.mode,
348            script: event.script,
349        };
350        match event.stage {
351            PermissionEventStage::Waiting => {
352                let tool_call_id = self.pending.get_mut(&key)?.pop_front()?;
353                self.active
354                    .entry(key)
355                    .or_default()
356                    .push_back(tool_call_id.clone());
357                Some((RunPauseReason::PermissionRequest, tool_call_id))
358            }
359            PermissionEventStage::Resolved => {
360                let tool_call_id = self.active.get_mut(&key)?.pop_front()?;
361                Some((RunPauseReason::PermissionRequest, tool_call_id))
362            }
363        }
364    }
365}
366
367#[cfg(feature = "skills")]
368#[derive(serde::Serialize)]
369struct SkillInstructionXml {
370    name: String,
371    description: String,
372    instructions: String,
373    #[serde(skip_serializing_if = "Option::is_none")]
374    allowed_tools: Option<Vec<String>>,
375    #[serde(skip_serializing_if = "Option::is_none")]
376    resource_paths: Option<Vec<String>>,
377}
378
379/// An autonomous agent that processes tasks using tiered language models.
380///
381/// The agent manages conversation context, handles tool execution in a loop,
382/// and applies context compression when needed. Unlike the raw `LanguageModel`
383/// trait which only emits events, the agent handles the full tool execution
384/// cycle.
385///
386/// # Type Parameters
387///
388/// - `Advanced`: The primary LLM for main reasoning (most capable)
389/// - `Balanced`: LLM for moderate tasks like subagents (defaults to Advanced)
390/// - `Fast`: LLM for quick tasks like compaction (defaults to Balanced)
391/// - `H`: Composed hooks for customizing behavior (defaults to `()`)
392///
393/// # Model Tier Selection
394///
395/// Each agent uses one tier for its main reasoning loop (set via `tier()`):
396/// - Main agent: typically `ModelTier::Advanced`
397/// - Explore subagent: `ModelTier::Balanced` (cheaper but capable)
398/// - Quick tasks: `ModelTier::Fast`
399///
400/// The `Fast` tier is always used for compaction, regardless of main tier.
401///
402/// # Example
403///
404/// ```rust,ignore
405/// // Simple usage (all tiers use same model)
406/// let agent = Agent::new(claude);
407/// let response = agent.query("What is 2+2?").await?;
408///
409/// // With tiered models
410/// let agent = Agent::builder(opus)
411///     .balanced_model(sonnet)
412///     .fast_model(haiku)
413///     .build();
414///
415/// // Subagent using balanced tier
416/// let explore_agent = Agent::builder(opus)
417///     .balanced_model(sonnet)
418///     .fast_model(haiku)
419///     .tier(ModelTier::Balanced)  // Use sonnet for reasoning
420///     .build();
421/// ```
422#[derive(Debug)]
423pub struct Agent<Advanced, Balanced = Advanced, Fast = Balanced, H = ()> {
424    /// Primary LLM for main reasoning (most capable).
425    pub(crate) advanced: Advanced,
426
427    /// Balanced LLM for moderate tasks (subagents).
428    pub(crate) balanced: Balanced,
429
430    /// Fast LLM for quick tasks (compaction, ask command).
431    pub(crate) fast: Fast,
432
433    /// Which model tier to use for main reasoning.
434    pub(crate) tier: ModelTier,
435
436    /// Registered tools.
437    pub(crate) tools: AgentTools,
438
439    /// Composed hooks.
440    pub(crate) hooks: H,
441
442    /// Agent configuration.
443    pub(crate) config: AgentConfig,
444
445    /// Unified context manager.
446    pub(crate) context: Context,
447
448    /// Cached model profile (for the selected tier).
449    pub(crate) profile: Option<ModelProfile>,
450
451    /// Cached fast model profile (for compression decisions).
452    pub(crate) fast_profile: Option<ModelProfile>,
453
454    /// Whether tools have been bootstrapped.
455    pub(crate) initialized: bool,
456
457    /// Receiver for completed background terminal tasks.
458    pub(crate) background_receiver: Option<BackgroundTaskReceiver>,
459    /// Receiver for permission wait/resume events emitted by terminal execution.
460    pub(crate) permission_receiver: Option<PermissionEventReceiver>,
461    /// Registry for running background terminal tasks.
462    pub(crate) job_registry: Option<JobRegistry>,
463
464    /// Optional readable transcript for long-context recovery.
465    pub(crate) transcript: Option<Transcript>,
466
467    /// Optional sandbox directory for working-doc supervision (`tasks.md`).
468    pub(crate) sandbox_dir: Option<PathBuf>,
469
470    /// Last observed working-doc snapshot for diff reminders.
471    pub(crate) last_working_docs: Option<working_docs::WorkingDocsSnapshot>,
472
473    /// tasks.md maintenance tracking across tool turns.
474    pub(crate) tasks_staleness: TasksDocStaleness,
475
476    /// Start time of the most recent LLM request issued by this agent.
477    pub(crate) last_request_started_at: Option<Instant>,
478
479    /// Transient per-turn system messages injected by the host application.
480    ///
481    /// These participate in prompt assembly for the current turn but are not
482    /// stored in the persistent context or checkpoints.
483
484    /// Rolling KV-cache statistics accumulated from emitted `Usage` events.
485    ///
486    /// Hosts can read [`Agent::cache_stats`] at any time to observe the
487    /// cumulative prompt-caching hit rate for this agent session.
488    pub(crate) cache_stats: crate::CacheStats,
489
490    /// Runtime skill registry loaded by host integrations.
491    /// Automatic prompt-triggered activation is intentionally disabled.
492    #[cfg(feature = "skills")]
493    pub(crate) skill_registry: Option<Arc<aither_skills::SkillRegistry>>,
494
495    /// Skills activated for the current run.
496    #[cfg(feature = "skills")]
497    pub(crate) active_skills: Vec<Skill>,
498
499    /// Exact tool-name allowlist derived from activated skills.
500    #[cfg(feature = "skills")]
501    pub(crate) active_allowed_tools: Option<HashSet<String>>,
502}
503
504impl<LLM: LanguageModel + Clone> Agent<LLM, LLM, LLM, ()> {
505    /// Creates a new agent with default configuration.
506    ///
507    /// All model tiers (advanced/balanced/fast) use the same model.
508    #[must_use]
509    pub fn new(llm: LLM) -> Self {
510        Self::with_config(llm, AgentConfig::default())
511    }
512
513    /// Creates a new agent with the specified configuration.
514    ///
515    /// All model tiers (advanced/balanced/fast) use the same model.
516    #[must_use]
517    pub fn with_config(llm: LLM, config: AgentConfig) -> Self {
518        Self {
519            advanced: llm.clone(),
520            balanced: llm.clone(),
521            fast: llm,
522            tier: ModelTier::default(),
523            tools: AgentTools::new(),
524            hooks: (),
525            config,
526            context: Context::default(),
527            profile: None,
528            fast_profile: None,
529            initialized: false,
530            background_receiver: None,
531            permission_receiver: None,
532            job_registry: None,
533            transcript: None,
534            sandbox_dir: None,
535            last_working_docs: None,
536            tasks_staleness: TasksDocStaleness::default(),
537            last_request_started_at: None,
538            cache_stats: crate::CacheStats::new(),
539            #[cfg(feature = "skills")]
540            skill_registry: None,
541            #[cfg(feature = "skills")]
542            active_skills: Vec::new(),
543            #[cfg(feature = "skills")]
544            active_allowed_tools: None,
545        }
546    }
547}
548
549impl<LLM: LanguageModel + Clone> Agent<LLM, LLM, LLM, ()> {
550    /// Returns a builder for more complex agent construction.
551    pub fn builder(llm: LLM) -> crate::builder::AgentBuilder<LLM, LLM, LLM, ()> {
552        crate::builder::AgentBuilder::new(llm)
553    }
554}
555
556impl<Advanced, Balanced, Fast, H> Agent<Advanced, Balanced, Fast, H>
557where
558    Advanced: LanguageModel,
559    Balanced: LanguageModel,
560    Fast: LanguageModel,
561    H: Hook,
562{
563    async fn collect_model_turn(
564        &mut self,
565        request: LLMRequest,
566        events: &EventSink,
567    ) -> Result<ModelTurn, AgentError> {
568        let mut text_chunks = Vec::new();
569        let mut tool_calls = Vec::new();
570        let mut reasoning = Vec::new();
571        let mut malformed_function_call = false;
572
573        match self.tier {
574            ModelTier::Advanced => {
575                drain_model_stream!(
576                    self.advanced.respond(request),
577                    &self.hooks,
578                    &mut self.cache_stats,
579                    events,
580                    &mut text_chunks,
581                    &mut tool_calls,
582                    &mut reasoning,
583                    malformed_function_call
584                );
585            }
586            ModelTier::Balanced => {
587                drain_model_stream!(
588                    self.balanced.respond(request),
589                    &self.hooks,
590                    &mut self.cache_stats,
591                    events,
592                    &mut text_chunks,
593                    &mut tool_calls,
594                    &mut reasoning,
595                    malformed_function_call
596                );
597            }
598            ModelTier::Fast => {
599                drain_model_stream!(
600                    self.fast.respond(request),
601                    &self.hooks,
602                    &mut self.cache_stats,
603                    events,
604                    &mut text_chunks,
605                    &mut tool_calls,
606                    &mut reasoning,
607                    malformed_function_call
608                );
609            }
610        }
611
612        Ok(ModelTurn {
613            response_text: text_chunks.join(""),
614            tool_calls,
615            reasoning,
616            malformed_function_call,
617        })
618    }
619
620    async fn run_streaming(
621        &mut self,
622        prompt: String,
623        attachments: Vec<Attachment>,
624        events: &EventSink,
625    ) -> Result<(), AgentError> {
626        let run_id = uuid::Uuid::new_v4().to_string();
627        events.emit(AgentEvent::run_start(
628            run_id.clone(),
629            self.config.max_iterations,
630        ));
631        self.ensure_initialized().await;
632        #[cfg(feature = "skills")]
633        for event in self.activate_skills_for_prompt(&prompt) {
634            events.emit(event);
635        }
636        self.maybe_compress().await?;
637
638        self.context
639            .push(Message::user(&prompt).with_attachments(attachments));
640        if let Some(transcript) = &self.transcript {
641            transcript.write_user_message(&prompt).await;
642        }
643
644        let outcome = self.run_agent_loop(run_id.as_str(), 0, events).await?;
645        if outcome.stop_reason != StopReason::EndTurn
646            && self
647                .collect_final_background_events(run_id.as_str(), outcome.iteration, events)
648                .await?
649        {
650            return Ok(());
651        }
652        self.push_stop_events(run_id.as_str(), outcome, events)
653            .await?;
654        Ok(())
655    }
656
657    async fn run_agent_loop(
658        &mut self,
659        run_id: &str,
660        turn_offset: usize,
661        events: &EventSink,
662    ) -> Result<RunLoopOutcome, AgentError> {
663        let mut iteration = 0;
664        loop {
665            iteration += 1;
666            let turn = turn_offset + iteration;
667            if turn > self.config.max_iterations {
668                return Err(AgentError::MaxIterations {
669                    limit: self.config.max_iterations,
670                });
671            }
672            match self.run_agent_turn(run_id, turn, events).await? {
673                TurnControl::Continue => {}
674                TurnControl::Break {
675                    final_text,
676                    stop_reason,
677                } => {
678                    return Ok(RunLoopOutcome {
679                        final_text,
680                        stop_reason,
681                        iteration: turn,
682                    });
683                }
684            }
685        }
686    }
687
688    async fn run_agent_turn(
689        &mut self,
690        run_id: &str,
691        turn: usize,
692        events: &EventSink,
693    ) -> Result<TurnControl, AgentError> {
694        let messages = self.build_live_request_messages().await;
695        let request =
696            LLMRequest::new(messages).with_tool_definitions(self.tools.active_definitions());
697        let model_turn = self.collect_model_turn(request, events).await?;
698
699        if model_turn.malformed_function_call {
700            return Ok(TurnControl::Continue);
701        }
702        let response_text = model_turn.response_text;
703        let tool_calls = model_turn.tool_calls;
704        ensure_non_empty_tool_call_ids(&tool_calls, &response_text)?;
705
706        if tool_calls.is_empty() {
707            return self.finish_no_tool_turn(response_text, turn, events).await;
708        }
709
710        // The reasoning has to travel with the turn that produced these calls,
711        // or the model receives their results without the thinking behind them.
712        self.context.push(Message::assistant_with_reasoning(
713            &response_text,
714            tool_calls.clone(),
715            model_turn.reasoning,
716        ));
717        self.push_tool_start_events(&tool_calls, events).await;
718        let results = self.execute_tool_calls(&tool_calls, turn, events).await;
719        self.apply_tool_results(results, events).await?;
720        self.check_tasks_doc_staleness().await;
721        self.push_turn_boundary_events(run_id, turn, &response_text, events)
722            .await
723    }
724
725    async fn finish_no_tool_turn(
726        &mut self,
727        response_text: String,
728        turn: usize,
729        events: &EventSink,
730    ) -> Result<TurnControl, AgentError> {
731        if !response_text.is_empty() {
732            self.context.push(Message::assistant(&response_text));
733            if let Some(transcript) = &self.transcript {
734                transcript.write_assistant_text(&response_text).await;
735            }
736        }
737        events.emit(AgentEvent::turn_complete(turn, false));
738        if self.inject_working_doc_continue_reminder().await {
739            return Ok(TurnControl::Continue);
740        }
741        Ok(TurnControl::Break {
742            final_text: response_text,
743            stop_reason: StopReason::NoToolCalls,
744        })
745    }
746
747    async fn push_tool_start_events(&self, tool_calls: &[ToolCall], events: &EventSink) {
748        for call in tool_calls {
749            let args = call.arguments.to_string();
750            if let Some(transcript) = &self.transcript {
751                transcript.write_tool_call(&call.name, &args).await;
752            }
753            events.emit(AgentEvent::ToolCallStart {
754                id: call.id.clone(),
755                name: call.name.clone(),
756                arguments: args,
757            });
758            if let Some(reason) = pause_reason_for_tool(call.name.as_str()) {
759                events.emit(AgentEvent::run_paused(reason, call.id.clone()));
760            }
761        }
762    }
763
764    async fn execute_tool_calls(
765        &self,
766        tool_calls: &[ToolCall],
767        turn: usize,
768        events: &EventSink,
769    ) -> Vec<Result<(String, String, aither_core::llm::ToolResult), AgentError>> {
770        let permission_receiver = self.permission_receiver.clone();
771        let mut permission_pause_tracker = PermissionPauseTracker::from_tool_calls(tool_calls);
772        let tool_futures = tool_calls.iter().map(|call| {
773            let args_json = call.arguments.to_string();
774            let message_count = self.context.len_recent();
775            async move {
776                let tool_ctx = ToolUseContext {
777                    tool_name: &call.name,
778                    arguments: &args_json,
779                    turn,
780                    message_count,
781                };
782                let (result, duration) = self
783                    .call_tool_with_hooks(call, &args_json, &tool_ctx)
784                    .await?;
785                let result_ctx = ToolResultContext {
786                    tool_name: &call.name,
787                    arguments: &args_json,
788                    result: &result,
789                    duration,
790                };
791                let tool_result = match self.hooks.post_tool_use(&result_ctx).await {
792                    PostToolAction::Abort(reason) => {
793                        return Err(AgentError::HookRejected {
794                            hook: "post_tool_use",
795                            reason,
796                        });
797                    }
798                    PostToolAction::Replace(replacement) => replacement,
799                    PostToolAction::Keep => result,
800                };
801                Ok((call.id.clone(), call.name.clone(), tool_result))
802            }
803        });
804
805        let mut pending = tool_futures.collect::<futures::stream::FuturesUnordered<_>>();
806        let mut results = Vec::new();
807        while !pending.is_empty() {
808            let next = match &permission_receiver {
809                Some(receiver) => {
810                    futures_lite::future::or(
811                        async { pending.next().await.map(ExecutionSignal::Tool) },
812                        async { receiver.recv().await.map(ExecutionSignal::Permission) },
813                    )
814                    .await
815                }
816                None => pending.next().await.map(ExecutionSignal::Tool),
817            };
818            Self::handle_execution_signal(
819                next,
820                &mut permission_pause_tracker,
821                &mut results,
822                events,
823            );
824        }
825        if let Some(receiver) = &permission_receiver {
826            for event in receiver.take_pending() {
827                emit_permission_event(&mut permission_pause_tracker, &event, events);
828            }
829        }
830        results
831    }
832
833    async fn call_tool_with_hooks(
834        &self,
835        call: &ToolCall,
836        args_json: &str,
837        tool_ctx: &ToolUseContext<'_>,
838    ) -> Result<(aither_core::llm::ToolResult, Duration), AgentError> {
839        match self.hooks.pre_tool_use(tool_ctx).await {
840            PreToolAction::Abort(reason) => Err(AgentError::HookRejected {
841                hook: "pre_tool_use",
842                reason,
843            }),
844            PreToolAction::Deny(reason) => {
845                Ok((aither_core::llm::ToolResult::error(reason), Duration::ZERO))
846            }
847            PreToolAction::Allow => {
848                let start = Instant::now();
849                // The agent loop has nowhere to show a tool's progress.
850                let result = self
851                    .tools
852                    .call(&call.name, args_json, aither_core::llm::ToolContext::new())
853                    .await
854                    .unwrap_or_else(|error| {
855                        let mut message = String::from("Error: ");
856                        message.push_str(error.to_string().as_str());
857                        aither_core::llm::ToolResult::error(message)
858                    });
859                Ok((result, start.elapsed()))
860            }
861        }
862    }
863
864    fn handle_execution_signal(
865        signal: Option<ToolExecutionSignal>,
866        tracker: &mut PermissionPauseTracker,
867        results: &mut Vec<ToolExecutionResult>,
868        events: &EventSink,
869    ) {
870        match signal {
871            Some(ExecutionSignal::Tool(result)) => results.push(result),
872            Some(ExecutionSignal::Permission(event)) => {
873                emit_permission_event(tracker, &event, events);
874            }
875            None => {}
876        }
877    }
878
879    async fn apply_tool_results(
880        &mut self,
881        results: Vec<Result<(String, String, aither_core::llm::ToolResult), AgentError>>,
882        events: &EventSink,
883    ) -> Result<(), AgentError> {
884        let mut has_tool_error = false;
885        let mut unknown_tools: Vec<String> = Vec::new();
886        let known_tools: Vec<String> = self
887            .tools
888            .active_definitions()
889            .into_iter()
890            .map(|definition| definition.name().to_string())
891            .collect();
892        for result in results {
893            let (call_id, call_name, tool_result) = result?;
894            let is_terminal_call = call_name == "terminal";
895            if !known_tools.contains(&call_name) && !unknown_tools.contains(&call_name) {
896                unknown_tools.push(call_name.clone());
897            }
898            if let Some(transcript) = &self.transcript {
899                transcript.write_tool_result(&call_name, &tool_result).await;
900            }
901            events.emit(AgentEvent::ToolCallEnd {
902                id: call_id.clone(),
903                name: call_name.clone(),
904                result: tool_result.clone(),
905            });
906            if let Some(reason) = pause_reason_for_tool(call_name.as_str()) {
907                events.emit(AgentEvent::run_resumed(reason, call_id.clone()));
908            }
909            let content = tool_result.render_for_model()?;
910            has_tool_error |= tool_result_is_error(&tool_result, &content);
911            self.push_terminal_followup_events(is_terminal_call, &tool_result, &content, events);
912            self.context.push(Message::tool(&call_id, content));
913        }
914        let has_terminal_tool = known_tools.iter().any(|name| name == "terminal");
915        if has_terminal_tool && !unknown_tools.is_empty() {
916            // Terminal-first architecture: non-native capabilities are CLI
917            // commands, and models trained on native tool calling routinely
918            // reach for them as tools. Redirect immediately instead of letting
919            // the model retry the same wrong call.
920            for name in &unknown_tools {
921                self.push_system_alert(format!(
922                    "There is no native tool named '{name}'. This runtime is terminal-first: the only native tools are terminal, terminal_kill, terminal_input, and terminal_read; every other capability is a CLI command executed through the `terminal` tool. If '{name}' is a capability, run it as a command (check with `{name} --help`)."
923                ));
924            }
925        } else if has_tool_error {
926            self.push_system_alert(
927                "A tool call failed. Re-assess the current state, inspect the latest tool result carefully, and choose the next action deliberately. Native tools remain terminal, terminal_kill, terminal_input, and terminal_read.",
928            );
929        }
930        self.push_completed_background_events(events);
931        Ok(())
932    }
933
934    fn push_terminal_followup_events(
935        &mut self,
936        is_terminal_call: bool,
937        tool_result: &aither_core::llm::ToolResult,
938        content: &str,
939        events: &EventSink,
940    ) {
941        if !is_terminal_call || tool_result.is_error() {
942            return;
943        }
944        if let Some(started) = Self::format_background_started_event(content) {
945            self.context.push(Message::system(&started.reminder));
946            events.emit(AgentEvent::background_task_started(
947                started.task_id,
948                started.output_preview,
949                started.output_file,
950                started.reason,
951            ));
952        }
953        if let Some(waiting) = Self::detect_terminal_input_needed(content) {
954            events.emit(AgentEvent::terminal_input_needed(
955                waiting.task_id,
956                waiting.notice,
957            ));
958        }
959    }
960
961    fn push_completed_background_events(&mut self, events: &EventSink) {
962        if let Some(ref receiver) = self.background_receiver {
963            for task in receiver.take_completed() {
964                tracing::info!(task_id = %task.task_id, "background task completed");
965                let result_msg = Self::format_background_task_result(&task);
966                self.context.push(Message::system(&result_msg));
967                events.emit(AgentEvent::background_task_completed(
968                    task.task_id.clone(),
969                    result_msg,
970                ));
971            }
972        }
973    }
974
975    async fn push_turn_boundary_events(
976        &self,
977        run_id: &str,
978        turn: usize,
979        response_text: &str,
980        events: &EventSink,
981    ) -> Result<TurnControl, AgentError> {
982        let boundary_ctx = TurnBoundaryContext {
983            assistant_text: response_text,
984            turn,
985            message_count: self.context.len_recent(),
986        };
987        let checkpoint = self
988            .emit_checkpoint(CheckpointReason::TurnBoundary, response_text, turn)
989            .await?;
990        events.emit(AgentEvent::checkpoint(
991            run_id.to_string(),
992            CheckpointReason::TurnBoundary,
993            turn,
994            checkpoint.phase,
995            checkpoint.message_count,
996        ));
997        events.emit(AgentEvent::turn_complete(turn, true));
998        if self.hooks.on_turn_boundary(&boundary_ctx).await == TurnBoundaryAction::EndTurn {
999            Ok(TurnControl::Break {
1000                final_text: response_text.to_string(),
1001                stop_reason: StopReason::EndTurn,
1002            })
1003        } else {
1004            Ok(TurnControl::Continue)
1005        }
1006    }
1007
1008    async fn collect_final_background_events(
1009        &mut self,
1010        run_id: &str,
1011        iteration: usize,
1012        events: &EventSink,
1013    ) -> Result<bool, AgentError> {
1014        let Some(receiver) = self.background_receiver.clone() else {
1015            return Ok(false);
1016        };
1017        let mut had_completed = self.drain_background_receiver(&receiver, events);
1018        let start = Instant::now();
1019        while start.elapsed() < BACKGROUND_TASK_MAX_WAIT {
1020            if let Some(task) = receiver.recv_timeout(BACKGROUND_TASK_POLL_INTERVAL).await {
1021                tracing::info!(task_id = %task.task_id, "background task completed (waiting)");
1022                self.push_completed_task_event(task, events);
1023                had_completed = true;
1024            } else if !self
1025                .background_receiver
1026                .as_ref()
1027                .is_some_and(aither_sandbox::BackgroundTaskReceiver::has_running)
1028            {
1029                break;
1030            }
1031        }
1032        if !had_completed {
1033            return Ok(false);
1034        }
1035        let outcome = self.run_agent_loop(run_id, iteration, events).await?;
1036        self.push_stop_events(run_id, outcome, events).await?;
1037        Ok(true)
1038    }
1039
1040    fn drain_background_receiver(
1041        &mut self,
1042        receiver: &BackgroundTaskReceiver,
1043        events: &EventSink,
1044    ) -> bool {
1045        let completed_tasks = receiver.take_completed();
1046        let had_completed = !completed_tasks.is_empty();
1047        for task in completed_tasks {
1048            tracing::info!(task_id = %task.task_id, "background task completed (final check)");
1049            self.push_completed_task_event(task, events);
1050        }
1051        had_completed
1052    }
1053
1054    fn push_completed_task_event(
1055        &mut self,
1056        task: aither_sandbox::CompletedTask,
1057        events: &EventSink,
1058    ) {
1059        let result_msg = Self::format_background_task_result(&task);
1060        self.context.push(Message::system(&result_msg));
1061        events.emit(AgentEvent::background_task_completed(
1062            task.task_id,
1063            result_msg,
1064        ));
1065    }
1066
1067    async fn push_stop_events(
1068        &self,
1069        run_id: &str,
1070        outcome: RunLoopOutcome,
1071        events: &EventSink,
1072    ) -> Result<(), AgentError> {
1073        let checkpoint = self
1074            .emit_checkpoint(
1075                CheckpointReason::Stop,
1076                &outcome.final_text,
1077                outcome.iteration,
1078            )
1079            .await?;
1080        events.emit(AgentEvent::checkpoint(
1081            run_id.to_string(),
1082            CheckpointReason::Stop,
1083            outcome.iteration,
1084            checkpoint.phase,
1085            checkpoint.message_count,
1086        ));
1087        let stop_ctx = StopContext {
1088            final_text: &outcome.final_text,
1089            turns: outcome.iteration,
1090            reason: outcome.stop_reason,
1091        };
1092        if let Some(reason) = self.hooks.on_stop(&stop_ctx).await {
1093            return Err(AgentError::HookRejected {
1094                hook: "on_stop",
1095                reason,
1096            });
1097        }
1098        events.emit(AgentEvent::Complete {
1099            final_text: outcome.final_text,
1100            turns: outcome.iteration,
1101        });
1102        Ok(())
1103    }
1104
1105    /// Performs a one-shot query and returns the final response.
1106    ///
1107    /// This is the simplest way to use the agent. The agent handles tool
1108    /// execution internally and returns the final text response.
1109    ///
1110    /// # Errors
1111    ///
1112    /// Returns an error if:
1113    /// - The LLM returns an error
1114    /// - A hook aborts the operation
1115    /// - Tool execution fails
1116    pub async fn query(&mut self, prompt: &str) -> Result<String, AgentError> {
1117        use futures_lite::StreamExt;
1118
1119        let stream = self.run(prompt, std::iter::empty());
1120        futures_lite::pin!(stream);
1121
1122        let mut final_text = String::new();
1123        while let Some(event) = stream.next().await {
1124            match event? {
1125                AgentEvent::Text(chunk) => final_text.push_str(&chunk),
1126                AgentEvent::Complete {
1127                    final_text: text, ..
1128                } => {
1129                    return Ok(text);
1130                }
1131                _ => {}
1132            }
1133        }
1134        Ok(final_text)
1135    }
1136
1137    /// Runs the agent with streaming events.
1138    ///
1139    /// Returns a stream of `AgentEvent`s that can be consumed to observe
1140    /// the agent's progress in real-time. Text chunks are yielded as they
1141    /// arrive from the LLM for true streaming display.
1142    ///
1143    /// # Example
1144    ///
1145    /// ```rust,ignore
1146    /// use futures::StreamExt;
1147    ///
1148    /// let mut stream = agent.run("Implement the feature", std::iter::empty());
1149    /// while let Some(event) = stream.next().await {
1150    ///     match event? {
1151    ///         AgentEvent::Text(t) => print!("{}", t),
1152    ///         AgentEvent::Complete { .. } => break,
1153    ///         _ => {}
1154    ///     }
1155    /// }
1156    /// ```
1157    pub fn run(
1158        &mut self,
1159        prompt: &str,
1160        attachments: impl IntoIterator<Item = Attachment>,
1161    ) -> impl Stream<Item = Result<AgentEvent, AgentError>> + '_ {
1162        let prompt = prompt.to_string();
1163        let attachments: Vec<Attachment> = attachments.into_iter().collect();
1164
1165        async_stream::stream! {
1166            let (sender, receiver) = async_channel::unbounded();
1167            let sink = EventSink { sender };
1168            let run = async {
1169                let result = self.run_streaming(prompt, attachments, &sink).await;
1170                drop(sink);
1171                result
1172            };
1173            futures_lite::pin!(run);
1174
1175            let mut outcome = None;
1176            while outcome.is_none() {
1177                let step = futures_lite::future::or(
1178                    async { RunStep::Event(receiver.recv().await.ok()) },
1179                    async { RunStep::Finished((&mut run).await) },
1180                )
1181                .await;
1182                match step {
1183                    RunStep::Event(Some(event)) => yield Ok(event),
1184                    // Sink dropped: the run is wrapping up — await its outcome.
1185                    RunStep::Event(None) => outcome = Some((&mut run).await),
1186                    RunStep::Finished(result) => outcome = Some(result),
1187                }
1188            }
1189            // Deliver events that raced with run completion.
1190            while let Ok(event) = receiver.try_recv() {
1191                yield Ok(event);
1192            }
1193            if let Some(Err(error)) = outcome {
1194                yield Err(error);
1195            }
1196        }
1197    }
1198
1199    /// Registers a tool for the agent to use.
1200    ///
1201    /// # Errors
1202    ///
1203    /// Returns [`RegisterError`](aither_core::llm::tool::RegisterError) if the
1204    /// name collides with a registered tool, or the tool has no description.
1205    pub fn register_tool<T: aither_core::llm::Tool + 'static>(
1206        &mut self,
1207        tool: T,
1208    ) -> Result<(), aither_core::llm::tool::RegisterError> {
1209        self.tools.register(tool)
1210    }
1211
1212    /// Returns a reference to the unified context manager.
1213    #[must_use]
1214    pub const fn context(&self) -> &Context {
1215        &self.context
1216    }
1217
1218    /// Returns a mutable reference to the unified context manager.
1219    ///
1220    /// Use this to insert/update system blocks, push messages, etc.
1221    pub const fn context_mut(&mut self) -> &mut Context {
1222        &mut self.context
1223    }
1224
1225    /// Adds a message to the conversation history.
1226    pub fn push_message(&mut self, message: Message) {
1227        self.context.push(message);
1228    }
1229
1230    /// Returns the rolling KV-cache statistics for this agent session.
1231    ///
1232    /// The stats are updated every time the underlying provider emits a
1233    /// `Usage` event (which, for providers like Claude with prompt
1234    /// caching, includes `cache_read_tokens` and `cache_write_tokens`).
1235    /// Hosts can read the hit rate, reset the accumulator, or snapshot
1236    /// it for per-turn diffs.
1237    #[must_use]
1238    pub const fn cache_stats(&self) -> &crate::CacheStats {
1239        &self.cache_stats
1240    }
1241
1242    /// Returns a mutable reference to the KV-cache statistics accumulator.
1243    ///
1244    /// Hosts typically only use this to [`CacheStats::reset`] between
1245    /// distinct sessions, since the agent itself records new observations.
1246    ///
1247    /// [`CacheStats::reset`]: crate::CacheStats::reset
1248    pub const fn cache_stats_mut(&mut self) -> &mut crate::CacheStats {
1249        &mut self.cache_stats
1250    }
1251
1252    /// Stops every terminal task that is still running for this agent.
1253    ///
1254    /// Returns the number of tasks that received a stop request.
1255    pub async fn kill_running_terminal_jobs(&self) -> usize {
1256        match &self.job_registry {
1257            Some(job_registry) => job_registry.kill_running().await,
1258            None => 0,
1259        }
1260    }
1261
1262    /// Clears the conversation history.
1263    pub fn clear_history(&mut self) {
1264        self.context.clear_history();
1265    }
1266
1267    /// Compacts the conversation by generating a structured handoff and starting fresh.
1268    ///
1269    /// # Errors
1270    ///
1271    /// Returns an error if handoff generation fails.
1272    pub async fn compact(
1273        &mut self,
1274        focus: Option<&str>,
1275    ) -> Result<Option<CompactResult>, AgentError> {
1276        self.ensure_initialized().await;
1277
1278        let messages = self.context.conversation_messages();
1279        if messages.is_empty() {
1280            return Ok(None);
1281        }
1282
1283        let messages_compacted = messages.len();
1284        let mut handoff = self.generate_handoff_document(focus).await?;
1285        // The file index is built mechanically from the conversation: prompting
1286        // the model for it is unreliable, and missing entries directly cause
1287        // post-compaction re-reads.
1288        handoff.file_index = crate::handoff::build_file_index(&messages);
1289        let summary = handoff.render_markdown();
1290
1291        if let Some(transcript) = &self.transcript {
1292            transcript.write_compact_marker().await;
1293        }
1294
1295        self.context.clear_recent();
1296        self.context.clear_reminders();
1297        self.context.set_handoff_document(&handoff);
1298
1299        Ok(Some(CompactResult {
1300            messages_compacted,
1301            messages_remaining: 0,
1302            summary,
1303        }))
1304    }
1305
1306    /// Generates a structured handoff document using the current tier model.
1307    async fn generate_handoff_document(
1308        &self,
1309        focus: Option<&str>,
1310    ) -> Result<HandoffDocument, AgentError> {
1311        let focus_instruction = focus.map(str::trim).filter(|s| !s.is_empty()).map_or_else(
1312            || "No additional focus hint was provided.".to_string(),
1313            |f| {
1314                let mut instruction = String::with_capacity(f.len() + 22);
1315                instruction.push_str("Focus the handoff on: ");
1316                instruction.push_str(f);
1317                instruction
1318            },
1319        );
1320        let handoff_prompt = include_str!("prompts/compact_handoff.txt")
1321            .replace(FOCUS_INSTRUCTION_PLACEHOLDER, &focus_instruction);
1322
1323        let mut messages = self.context.conversation_messages();
1324        messages.push(Message::user(handoff_prompt));
1325
1326        let mut chunks = Vec::new();
1327        match self.tier {
1328            ModelTier::Advanced => {
1329                let stream = self.advanced.respond(LLMRequest::new(messages.clone()));
1330                futures_lite::pin!(stream);
1331                while let Some(event) = stream.next().await {
1332                    match event {
1333                        Ok(Event::Text(text)) => chunks.push(text),
1334                        Ok(Event::BuiltInToolResult { tool, result }) => {
1335                            chunks.push(format_builtin_tool_result(&tool, &result));
1336                        }
1337                        Ok(_) => {}
1338                        Err(e) => return Err(AgentError::Llm(e.to_string())),
1339                    }
1340                }
1341            }
1342            ModelTier::Balanced => {
1343                let stream = self.balanced.respond(LLMRequest::new(messages.clone()));
1344                futures_lite::pin!(stream);
1345                while let Some(event) = stream.next().await {
1346                    match event {
1347                        Ok(Event::Text(text)) => chunks.push(text),
1348                        Ok(Event::BuiltInToolResult { tool, result }) => {
1349                            chunks.push(format_builtin_tool_result(&tool, &result));
1350                        }
1351                        Ok(_) => {}
1352                        Err(e) => return Err(AgentError::Llm(e.to_string())),
1353                    }
1354                }
1355            }
1356            ModelTier::Fast => {
1357                let stream = self.fast.respond(LLMRequest::new(messages));
1358                futures_lite::pin!(stream);
1359                while let Some(event) = stream.next().await {
1360                    match event {
1361                        Ok(Event::Text(text)) => chunks.push(text),
1362                        Ok(Event::BuiltInToolResult { tool, result }) => {
1363                            chunks.push(format_builtin_tool_result(&tool, &result));
1364                        }
1365                        Ok(_) => {}
1366                        Err(e) => return Err(AgentError::Llm(e.to_string())),
1367                    }
1368                }
1369            }
1370        }
1371
1372        let response = chunks.join("").trim().to_string();
1373        if response.is_empty() {
1374            return Err(AgentError::Llm(
1375                "Compaction failed to generate handoff summary".to_string(),
1376            ));
1377        }
1378        serde_json::from_str::<HandoffDocument>(&response)
1379            .map_err(|error| AgentError::Llm(error.to_string()))?
1380            .validate()
1381            .map_err(AgentError::Llm)
1382    }
1383
1384    /// Injects a continuation reminder when working documents still have pending tasks.
1385    async fn inject_working_doc_continue_reminder(&mut self) -> bool {
1386        let Some(sandbox_dir) = self.sandbox_dir.as_deref() else {
1387            return false;
1388        };
1389
1390        let docs = working_docs::read_snapshot(sandbox_dir).await;
1391        if !docs.has_unchecked_items() {
1392            return false;
1393        }
1394
1395        self.push_system_alert(
1396            "tasks.md still has unchecked items. Continue working through the checklist. If user input is required, call ask_user and then proceed.",
1397        );
1398        true
1399    }
1400
1401    /// Pushes a one-shot system alert into the conversation stream.
1402    ///
1403    /// Unlike [`Context::insert_reminder`], which is reserved for content
1404    /// regenerated by `populate_dynamic_reminders` on every request build, an
1405    /// alert pushed here stays in `runtime_items` until reassembly or
1406    /// compaction prunes it — this is the only channel that survives to the
1407    /// next request.
1408    fn push_system_alert(&mut self, content: impl Into<String>) {
1409        self.context.push_alert(&SystemReminder {
1410            content: content.into(),
1411        });
1412    }
1413
1414    /// Nags the model when tool turns keep passing without tasks.md updates.
1415    ///
1416    /// Runs after a tool turn: the turn itself is the tool-activity signal,
1417    /// so no separate bookkeeping of tool calls is needed. The alert goes in
1418    /// as a durable system message — `insert_reminder` would be cleared by
1419    /// the next request's reminder repopulation before ever being sent.
1420    async fn check_tasks_doc_staleness(&mut self) {
1421        let Some(sandbox_dir) = self.sandbox_dir.as_deref() else {
1422            return;
1423        };
1424        let docs = working_docs::read_snapshot(sandbox_dir).await;
1425        let threshold = self.config.tasks_stale_after_turns;
1426
1427        let state = &mut self.tasks_staleness;
1428        if !state.seen {
1429            state.seen = true;
1430            state.last_content = docs.tasks_md;
1431            return;
1432        }
1433        if state.last_content != docs.tasks_md {
1434            state.last_content = docs.tasks_md;
1435            state.stale_turns = 0;
1436            state.alerted = false;
1437            return;
1438        }
1439
1440        let stale_kind = match &docs.tasks_md {
1441            Some(content) if working_docs::has_unchecked_markdown_tasks(content) => {
1442                Some("unchecked")
1443            }
1444            Some(_) => {
1445                state.stale_turns = 0;
1446                state.alerted = false;
1447                None
1448            }
1449            None => Some("missing"),
1450        };
1451        let Some(stale_kind) = stale_kind else {
1452            return;
1453        };
1454
1455        state.stale_turns += 1;
1456        if state.stale_turns < threshold || state.alerted {
1457            return;
1458        }
1459        state.alerted = true;
1460        let content = if stale_kind == "missing" {
1461            format!(
1462                "{threshold} tool turns have run without a tasks.md. For multi-step work, create tasks.md in the sandbox root with a checklist of the plan — it is the canonical task document and survives context compaction."
1463            )
1464        } else {
1465            format!(
1466                "tasks.md has unchecked items but has not been updated for {threshold} tool turns. Mark finished items and keep the checklist in sync with actual progress."
1467            )
1468        };
1469        self.context.push_alert(&TasksStale { content });
1470    }
1471
1472    /// Returns the current conversation history.
1473    #[must_use]
1474    pub fn history(&self) -> Vec<Message> {
1475        self.context.conversation_messages()
1476    }
1477
1478    fn tool_surface_hash(&self) -> String {
1479        let mut names = self
1480            .tools
1481            .active_definitions()
1482            .into_iter()
1483            .map(|definition| definition.name().to_string())
1484            .collect::<Vec<_>>();
1485        names.sort();
1486        let mut hasher = Sha256::new();
1487        for name in names {
1488            hasher.update(name.as_bytes());
1489            hasher.update(b"\n");
1490        }
1491        hex_encode(hasher.finalize().as_slice())
1492    }
1493
1494    /// Export a checkpoint bundle for restart-safe persistence.
1495    ///
1496    /// # Errors
1497    ///
1498    /// Returns an error when checkpoint construction or checkpoint hooks fail.
1499    pub async fn export_checkpoint(&mut self) -> Result<AgentCheckpoint, AgentError> {
1500        self.ensure_initialized().await;
1501        let context_window = self.snapshot_context_window().await;
1502        Ok(AgentCheckpoint {
1503            context: self.context.checkpoint(),
1504            tool_surface_hash: self.tool_surface_hash(),
1505            context_window,
1506            has_background_tasks: self
1507                .background_receiver
1508                .as_ref()
1509                .is_some_and(aither_sandbox::BackgroundTaskReceiver::has_running),
1510        })
1511    }
1512
1513    /// Restore a previously exported checkpoint bundle.
1514    ///
1515    /// # Errors
1516    ///
1517    /// Returns an error when the checkpoint cannot be restored into this agent.
1518    pub fn restore_checkpoint(&mut self, checkpoint: AgentCheckpoint) -> Result<(), AgentError> {
1519        self.context.restore(checkpoint.context);
1520        #[cfg(feature = "skills")]
1521        {
1522            self.active_skills.clear();
1523            self.active_allowed_tools = None;
1524        }
1525        Ok(())
1526    }
1527
1528    /// Returns a structured snapshot of the current context window.
1529    ///
1530    /// This is a pure measurement: it does not repopulate reminders or
1531    /// otherwise mutate the context.
1532    pub async fn snapshot_context_window(&mut self) -> ContextWindowSnapshot {
1533        self.ensure_initialized().await;
1534        self.context_window_snapshot()
1535    }
1536
1537    /// Returns the model profile if available.
1538    #[must_use]
1539    pub const fn profile(&self) -> Option<&ModelProfile> {
1540        self.profile.as_ref()
1541    }
1542
1543    /// Ensures the agent is initialized (profiles fetched, static blocks set up).
1544    async fn ensure_initialized(&mut self) {
1545        if self.initialized {
1546            return;
1547        }
1548
1549        // Fetch profile for the selected tier (for context window decisions)
1550        self.profile = Some(match self.tier {
1551            ModelTier::Advanced => self.advanced.profile().await,
1552            ModelTier::Balanced => self.balanced.profile().await,
1553            ModelTier::Fast => self.fast.profile().await,
1554        });
1555
1556        // Fetch fast model profile (for compression decisions)
1557        // We always need this because compression uses the fast model
1558        self.fast_profile = Some(self.fast.profile().await);
1559
1560        // Populate static system blocks in Context from AgentConfig.
1561        // These form the stable, cacheable prefix.
1562        self.populate_system_blocks();
1563
1564        self.initialized = true;
1565    }
1566
1567    /// Populates the Context's system blocks from `AgentConfig`.
1568    ///
1569    /// Called once during initialization. These blocks form the stable
1570    /// cacheable prefix of the system message.
1571    fn populate_system_blocks(&mut self) {
1572        if let Some(ref system_prompt) = self.config.system_prompt {
1573            self.context
1574                .insert_system_named("base_system", system_prompt);
1575        }
1576
1577        if let Some(ref persona_prompt) = self.config.persona_prompt {
1578            self.context.insert_system_named("persona", persona_prompt);
1579        }
1580
1581        if self.config.agent_kind == AgentKind::Coding {
1582            self.context.insert_system_named(
1583                "workspace_facts",
1584                "When discovering workspace guidance, load AGENT.md first. If AGENT.md is missing, load CLAUDE.md. Treat these files as repository policy for coding tasks; this behavior is not required for chatbot-style sessions.",
1585            );
1586        }
1587
1588        // TerminalAgentBuilder pre-seeds this block rendered against the
1589        // command registry; keep that version when present.
1590        if !self.context.has_system_block("knowledge_and_time") {
1591            self.context.insert_system_named(
1592                "knowledge_and_time",
1593                KnowledgeAndTimeTemplate {
1594                    websearch_command: true,
1595                }
1596                .render()
1597                .expect("failed to render knowledge_and_time template"),
1598            );
1599        }
1600
1601        self.context
1602            .insert_system_named("permissions", include_str!("prompts/permissions.txt"));
1603
1604        let tool_hints = self.format_tool_hints_block();
1605        if !tool_hints.is_empty() {
1606            self.context.insert_system_named("tool_hints", &tool_hints);
1607        }
1608    }
1609
1610    async fn populate_dynamic_reminders(&mut self) {
1611        self.context.clear_reminders();
1612
1613        #[cfg(feature = "skills")]
1614        self.populate_skill_reminders();
1615
1616        if let Some(sandbox_dir) = self.sandbox_dir.as_deref() {
1617            let docs = working_docs::read_snapshot(sandbox_dir).await;
1618            if let Some(previous) = self.last_working_docs.as_ref()
1619                && let Some(diff) = working_docs::tasks_md_diff(previous, &docs)
1620            {
1621                self.context.insert_reminder(&TasksDiffReminder { diff });
1622            }
1623            self.last_working_docs = Some(docs.clone());
1624            if let Some(tasks_md) = docs.tasks_md {
1625                self.context.insert_reminder(&Tasks { content: tasks_md });
1626            }
1627        }
1628
1629        if let Some(job_registry) = &self.job_registry {
1630            let running = job_registry.format_running_jobs().await;
1631            if !running.is_empty() {
1632                self.context.insert_reminder(&SystemReminder {
1633                    content: format!(
1634                        "Running background terminals:\n{running}Use terminal_read for incremental output, read redirected output files via terminal commands like head/tail/grep/cat when needed, terminal_input for stdin, and terminal_kill to stop tasks."
1635                    ),
1636                });
1637            }
1638        }
1639    }
1640
1641    /// Builds the message list for an LLM request.
1642    ///
1643    /// Uses `context.build_messages()` for the stable system prefix + conversation,
1644    /// then prepends per-turn ephemeral context (working docs, background
1645    /// jobs, context usage) as system messages inserted before conversation messages.
1646    async fn build_request_messages(&mut self) -> Vec<Message> {
1647        self.assemble_context_window().await.messages
1648    }
1649
1650    async fn build_live_request_messages(&mut self) -> Vec<Message> {
1651        let _ = self.maybe_reassemble_after_idle_gap();
1652        let messages = self.build_request_messages().await;
1653        self.last_request_started_at = Some(Instant::now());
1654        messages
1655    }
1656
1657    #[cfg(feature = "skills")]
1658    pub(crate) fn activate_skills_for_prompt(&mut self, _prompt: &str) -> Vec<AgentEvent> {
1659        let _ = self.skill_registry.as_ref();
1660        self.active_skills.clear();
1661        self.active_allowed_tools = None;
1662        Vec::new()
1663    }
1664
1665    #[cfg(feature = "skills")]
1666    fn populate_skill_reminders(&mut self) {
1667        for skill in &self.active_skills {
1668            let mut resource_paths = skill.resources.keys().cloned().collect::<Vec<_>>();
1669            resource_paths.sort();
1670            let payload = serialize_xml(
1671                "skill_instruction",
1672                &SkillInstructionXml {
1673                    name: skill.name.clone(),
1674                    description: skill.description.clone(),
1675                    instructions: skill.instructions.clone(),
1676                    allowed_tools: skill.allowed_tools.clone(),
1677                    resource_paths: (!resource_paths.is_empty()).then_some(resource_paths),
1678                },
1679            );
1680            self.context
1681                .insert_reminder(&SystemReminder { content: payload });
1682        }
1683    }
1684
1685    /// Measures the context window exactly as it stands: no reminder
1686    /// repopulation, no alert insertion, no working-doc baseline updates.
1687    ///
1688    /// Metrics-only callers (checkpoints, compression gating, status
1689    /// snapshots) must use this — running the full assemble path there would
1690    /// wipe ad-hoc alerts queued for the next request and consume the
1691    /// tasks.md diff baseline before the model ever sees it.
1692    fn context_window_snapshot(&self) -> ContextWindowSnapshot {
1693        let messages = self.context.build_messages();
1694        let metrics = self.estimate_context_window_metrics(&messages);
1695        ContextWindowSnapshot {
1696            phase: self.classify_context_window_phase(&metrics),
1697            metrics,
1698            messages,
1699        }
1700    }
1701
1702    async fn assemble_context_window(&mut self) -> ContextWindowSnapshot {
1703        self.populate_dynamic_reminders().await;
1704
1705        let mut messages = self.context.build_messages();
1706        let mut metrics = self.estimate_context_window_metrics(&messages);
1707
1708        if !metrics.has_handoff
1709            && metrics.usage_fraction >= self.config.context_assembler.handoff_threshold
1710            && let Some(handoff_ctx) = self.format_handoff_context(metrics.usage_fraction)
1711        {
1712            self.context.insert_reminder(&SystemReminder {
1713                content: handoff_ctx,
1714            });
1715            messages = self.context.build_messages();
1716            metrics = self.estimate_context_window_metrics(&messages);
1717        }
1718
1719        ContextWindowSnapshot {
1720            phase: self.classify_context_window_phase(&metrics),
1721            metrics,
1722            messages,
1723        }
1724    }
1725
1726    fn maybe_reassemble_after_idle_gap(&mut self) -> crate::context::ReassemblyReport {
1727        let unchanged = crate::context::ReassemblyReport::default();
1728        if self.context.handoff().is_some() {
1729            return unchanged;
1730        }
1731        let Some(last_request_started_at) = self.last_request_started_at else {
1732            return unchanged;
1733        };
1734        if last_request_started_at.elapsed() < self.config.context_assembler.idle_reassemble_after {
1735            return unchanged;
1736        }
1737        self.reassemble_context()
1738    }
1739
1740    fn estimate_context_window_metrics(&self, messages: &[Message]) -> ContextWindowMetrics {
1741        ContextWindowMetrics {
1742            usage_fraction: estimate_context_usage(messages, self.effective_context_window()),
1743            selected_model_context_window: self
1744                .profile
1745                .as_ref()
1746                .map(|profile| profile.context_length),
1747            fast_model_context_window: self
1748                .fast_profile
1749                .as_ref()
1750                .map(|profile| profile.context_length),
1751            effective_context_window: self.effective_context_window(),
1752            system_block_count: self.context.system_block_count(),
1753            reminder_count: self.context.reminders().len(),
1754            recent_message_count: self.context.len_recent(),
1755            recent_system_message_count: self.context.count_recent_system_messages(),
1756            has_handoff: self.context.handoff().is_some(),
1757        }
1758    }
1759
1760    fn classify_context_window_phase(&self, metrics: &ContextWindowMetrics) -> ContextWindowPhase {
1761        if metrics.has_handoff {
1762            return ContextWindowPhase::HandoffActive;
1763        }
1764
1765        if metrics.usage_fraction >= self.config.context_assembler.handoff_threshold {
1766            return ContextWindowPhase::HandoffDue;
1767        }
1768
1769        match &self.config.context {
1770            ContextStrategy::Smart(config)
1771                if metrics.usage_fraction >= config.effective_trigger()
1772                    && metrics.recent_system_message_count > 0 =>
1773            {
1774                ContextWindowPhase::ReassemblyDue
1775            }
1776            ContextStrategy::Smart(config)
1777                if metrics.usage_fraction >= config.effective_trigger() =>
1778            {
1779                ContextWindowPhase::CompressionDue
1780            }
1781            ContextStrategy::Unlimited | ContextStrategy::Smart(_) => ContextWindowPhase::Stable,
1782        }
1783    }
1784
1785    fn effective_context_window(&self) -> usize {
1786        let tier_context = self
1787            .profile
1788            .as_ref()
1789            .map_or(100_000, |profile| profile.context_length as usize);
1790        let fast_context = self
1791            .fast_profile
1792            .as_ref()
1793            .map_or(100_000, |profile| profile.context_length as usize);
1794        tier_context.min(fast_context)
1795    }
1796
1797    /// Returns the exact request message sequence that would be sent for the next turn.
1798    ///
1799    /// This is intended for observability/debug UIs and does not mutate agent memory.
1800    /// Temporarily adds the prompt to a forked context, builds the messages, then discards.
1801    pub async fn preview_request_messages(
1802        &mut self,
1803        prompt: &str,
1804        attachments: impl IntoIterator<Item = Attachment>,
1805    ) -> Vec<Message> {
1806        self.ensure_initialized().await;
1807        // Fork context, add the user message, build messages
1808        let checkpoint = self.context.checkpoint();
1809        // `populate_dynamic_reminders` also advances the working-docs diff
1810        // baseline, which lives outside the context checkpoint — preserve it
1811        // so a preview cannot consume a diff the real request should surface.
1812        let working_docs_baseline = self.last_working_docs.clone();
1813        self.context
1814            .push(Message::user(prompt).with_attachments(attachments));
1815        let messages = self.build_request_messages().await;
1816        self.context.restore(checkpoint);
1817        self.last_working_docs = working_docs_baseline;
1818        messages
1819    }
1820
1821    /// Injects a handoff instruction when context usage approaches the threshold.
1822    fn format_handoff_context(&self, usage: f32) -> Option<String> {
1823        if usage < self.config.context_assembler.handoff_threshold {
1824            return None;
1825        }
1826
1827        let mut note = String::new();
1828        note.push_str(&self.config.context_assembler.handoff_instruction);
1829        if let Some(path) = &self.config.transcript_path {
1830            note.push_str(" Transcript source: ");
1831            note.push_str(path);
1832            note.push('.');
1833        }
1834        Some(note)
1835    }
1836
1837    fn format_tool_hints_block(&self) -> String {
1838        let defs = self.tools.active_definitions();
1839        let mut lines = Vec::new();
1840
1841        for def in defs {
1842            let desc = first_paragraph(def.description());
1843            if desc.is_empty() {
1844                continue;
1845            }
1846            let mut line = def.name().to_string();
1847            line.push_str(": ");
1848            line.push_str(desc.as_str());
1849            lines.push(line);
1850        }
1851
1852        lines.join("\n")
1853    }
1854
1855    /// Compresses context if needed.
1856    ///
1857    /// Considers BOTH the selected tier's context window AND the fast model's
1858    /// context window. Compression is triggered based on the most constrained
1859    /// of the two windows, ensuring the fast LLM can actually see the content
1860    /// during compaction.
1861    ///
1862    /// Uses `effective_trigger()` which accounts for a 20% context reservation
1863    /// to ensure there's room for the fast LLM during compaction.
1864    ///
1865    async fn maybe_compress(&mut self) -> Result<(), AgentError> {
1866        self.ensure_initialized().await;
1867        let snapshot = self.context_window_snapshot();
1868        let context_strategy = self.config.context.clone();
1869
1870        match context_strategy {
1871            ContextStrategy::Unlimited => Ok(()),
1872            ContextStrategy::Smart(config) => {
1873                if !matches!(
1874                    snapshot.phase,
1875                    ContextWindowPhase::ReassemblyDue | ContextWindowPhase::CompressionDue
1876                ) {
1877                    return Ok(());
1878                }
1879
1880                // Reassembly alone is preferred only when it frees enough of
1881                // the window to leave the danger zone; a marginal saving is
1882                // not worth the cache invalidation on top of a compaction
1883                // that would follow anyway.
1884                let window = self.effective_context_window();
1885                let savings_tokens = self.context.estimate_reassembly_savings() / 4;
1886                let savings_fraction =
1887                    savings_tokens.to_f32().unwrap_or(0.0) / window.to_f32().unwrap_or(f32::MAX);
1888                let usage_after_reassembly = snapshot.metrics.usage_fraction - savings_fraction;
1889
1890                if usage_after_reassembly < config.effective_trigger() {
1891                    let report = self.reassemble_context();
1892                    tracing::debug!(
1893                        reminders = report.reminders_cleared,
1894                        system_messages = report.system_messages_pruned,
1895                        deduped = report.tool_results_deduped,
1896                        bytes_freed = report.bytes_freed,
1897                        "context reassembly freed enough window; compaction skipped"
1898                    );
1899                    return Ok(());
1900                }
1901
1902                if self.context.len_recent() > config.preserve_recent {
1903                    // Compress directly; if compaction itself fails (for
1904                    // example the compaction request overflows the window),
1905                    // fall back to reassembly and retry once.
1906                    if let Err(error) = self.compact(None).await {
1907                        let report = self.reassemble_context();
1908                        if !report.changed() {
1909                            return Err(error);
1910                        }
1911                        tracing::warn!(
1912                            %error,
1913                            bytes_freed = report.bytes_freed,
1914                            "compaction failed; retrying after context reassembly"
1915                        );
1916                        self.compact(None).await?;
1917                    }
1918                } else {
1919                    let _ = self.reassemble_context();
1920                }
1921                Ok(())
1922            }
1923        }
1924    }
1925
1926    fn reassemble_context(&mut self) -> crate::context::ReassemblyReport {
1927        self.context.reassemble()
1928    }
1929
1930    async fn emit_checkpoint(
1931        &self,
1932        reason: CheckpointReason,
1933        assistant_text: &str,
1934        turn: usize,
1935    ) -> Result<EmittedCheckpoint, AgentError> {
1936        let context = self.context.checkpoint();
1937        let tool_surface_hash = self.tool_surface_hash();
1938        let window = self.context_window_snapshot();
1939        let checkpoint_ctx = CheckpointContext {
1940            reason,
1941            assistant_text,
1942            turn,
1943            message_count: self.context.len_recent(),
1944            context: &context,
1945            tool_surface_hash: &tool_surface_hash,
1946            has_background_tasks: self
1947                .background_receiver
1948                .as_ref()
1949                .is_some_and(aither_sandbox::BackgroundTaskReceiver::has_running),
1950            window: &window,
1951        };
1952        if let Some(reason) = self.hooks.on_checkpoint(&checkpoint_ctx).await {
1953            return Err(AgentError::HookRejected {
1954                hook: "on_checkpoint",
1955                reason,
1956            });
1957        }
1958        Ok(EmittedCheckpoint {
1959            phase: window.phase,
1960            message_count: self.context.len_recent(),
1961        })
1962    }
1963
1964    /// Formats a reminder and event payload when `terminal` has been auto-promoted to background.
1965    fn format_background_started_event(tool_content: &str) -> Option<BackgroundTaskStartedEvent> {
1966        let payload: serde_json::Value = serde_json::from_str(tool_content).ok()?;
1967        let status = payload.get("status")?.as_str()?;
1968        if status != "running" {
1969            return None;
1970        }
1971
1972        let task_id = payload.get("task_id")?.as_str()?.trim();
1973        if task_id.is_empty() {
1974            return None;
1975        }
1976
1977        let output_preview = payload
1978            .get("stdout")
1979            .and_then(|stdout| stdout.get("content"))
1980            .and_then(|content| content.get("text"))
1981            .and_then(serde_json::Value::as_str)
1982            .map(str::trim)
1983            .filter(|text| !text.is_empty())
1984            .unwrap_or("(no output yet)");
1985
1986        let output_file = payload
1987            .get("stdout")
1988            .and_then(|stdout| stdout.get("url"))
1989            .and_then(serde_json::Value::as_str)
1990            .unwrap_or("(missing output file)");
1991
1992        let reason = payload
1993            .get("background_reason")
1994            .cloned()
1995            .and_then(|raw| serde_json::from_value::<BackgroundReason>(raw).ok())
1996            .unwrap_or(BackgroundReason::Explicit);
1997
1998        let reminder = BackgroundStartedReminderTemplate {
1999            task_id,
2000            output_preview,
2001            output_file,
2002        }
2003        .render()
2004        .ok()?;
2005
2006        Some(BackgroundTaskStartedEvent {
2007            task_id: task_id.to_string(),
2008            output_preview: output_preview.to_string(),
2009            output_file: output_file.to_string(),
2010            reminder,
2011            reason,
2012        })
2013    }
2014
2015    fn detect_terminal_input_needed(tool_content: &str) -> Option<TerminalInputNeededEvent> {
2016        let payload: aither_sandbox::TerminalResult = serde_json::from_str(tool_content).ok()?;
2017        if payload.status.as_deref() != Some("running") {
2018            return None;
2019        }
2020        let notice = match &payload.stdout {
2021            aither_sandbox::OutputEntry::Inline { content }
2022            | aither_sandbox::OutputEntry::Loaded { content, .. } => match content {
2023                aither_sandbox::Content::Text { text, .. } => text.as_str(),
2024                aither_sandbox::Content::Image { .. } => return None,
2025            },
2026            aither_sandbox::OutputEntry::Stored { content, .. } => match content {
2027                Some(aither_sandbox::Content::Text { text, .. }) => text.as_str(),
2028                Some(aither_sandbox::Content::Image { .. }) | None => return None,
2029            },
2030            aither_sandbox::OutputEntry::Empty => return None,
2031        };
2032        if !notice.starts_with(TERMINAL_STDIN_BLOCKED_NOTICE) {
2033            return None;
2034        }
2035        Some(TerminalInputNeededEvent {
2036            task_id: payload.task_id,
2037            notice: notice.to_string(),
2038        })
2039    }
2040
2041    /// Formats a completed background task result as a system message.
2042    fn format_background_task_result(task: &aither_sandbox::CompletedTask) -> String {
2043        let mut xml = BackgroundTerminalResultXml {
2044            task_id: task.task_id.clone(),
2045            script: truncate_script(&task.script, 100).to_string(),
2046            exit_code: None,
2047            output: None,
2048            stderr: None,
2049            error: None,
2050        };
2051
2052        match &task.result {
2053            Ok(result) => {
2054                xml.exit_code = Some(result.exit_code);
2055                let stdout = result.stdout.to_string();
2056                if !stdout.is_empty() {
2057                    xml.output = Some(stdout);
2058                }
2059                if let Some(stderr) = &result.stderr {
2060                    let stderr = stderr.to_string();
2061                    if !stderr.is_empty() {
2062                        xml.stderr = Some(stderr);
2063                    }
2064                }
2065            }
2066            Err(error) => {
2067                xml.error = Some(error.to_string());
2068            }
2069        }
2070
2071        serialize_xml("background-terminal-result", &xml)
2072    }
2073}
2074fn format_builtin_tool_result(tool: &str, result: &str) -> String {
2075    let mut text = String::from("[");
2076    text.push_str(tool);
2077    text.push_str("] ");
2078    text.push_str(result);
2079    text
2080}
2081
2082fn permission_event_key_for_call(
2083    tool_name: &str,
2084    arguments: &serde_json::Value,
2085) -> Option<PermissionEventKey> {
2086    if tool_name != "terminal" {
2087        return None;
2088    }
2089    let args: TerminalArgs = serde_json::from_value(arguments.clone()).ok()?;
2090    let mode = match args.mode {
2091        TerminalExecutionMode::Sandboxed
2092        | TerminalExecutionMode::Default
2093        | TerminalExecutionMode::Ssh => return None,
2094        TerminalExecutionMode::Unsafe => TerminalMode::Unsafe,
2095    };
2096    Some(PermissionEventKey {
2097        mode,
2098        script: args.script,
2099    })
2100}
2101
2102fn pause_reason_for_tool(tool_name: &str) -> Option<RunPauseReason> {
2103    match tool_name {
2104        "ask_user" => Some(RunPauseReason::AskUser),
2105        "request_workspace" => Some(RunPauseReason::WorkspaceRequest),
2106        _ => None,
2107    }
2108}
2109
2110fn emit_permission_event(
2111    tracker: &mut PermissionPauseTracker,
2112    event: &PermissionEvent,
2113    events: &EventSink,
2114) {
2115    if let Some((reason, tool_call_id)) = tracker.event_for(event.clone()) {
2116        match event.stage {
2117            PermissionEventStage::Waiting => {
2118                events.emit(AgentEvent::run_paused(reason, tool_call_id));
2119            }
2120            PermissionEventStage::Resolved => {
2121                events.emit(AgentEvent::run_resumed(reason, tool_call_id));
2122            }
2123        }
2124    }
2125}
2126
2127fn tool_result_is_error(tool_result: &aither_core::llm::ToolResult, content: &str) -> bool {
2128    tool_result.is_error()
2129        || content.contains("ssh_server_id is required")
2130        || content.contains("unknown ssh_server_id")
2131        || content.contains("not found")
2132        || content.contains("Invalid arguments")
2133}
2134
2135fn hex_encode(bytes: &[u8]) -> String {
2136    const HEX: &[u8; 16] = b"0123456789abcdef";
2137    let mut output = String::with_capacity(bytes.len() * 2);
2138    for byte in bytes {
2139        output.push(HEX[(byte >> 4) as usize] as char);
2140        output.push(HEX[(byte & 0x0f) as usize] as char);
2141    }
2142    output
2143}
2144
2145fn first_paragraph(text: &str) -> String {
2146    let trimmed = text.trim();
2147    if trimmed.is_empty() {
2148        return String::new();
2149    }
2150
2151    if let Some((first, _)) = trimmed.split_once("\n\n") {
2152        return first.split_whitespace().collect::<Vec<_>>().join(" ");
2153    }
2154
2155    trimmed.split_whitespace().collect::<Vec<_>>().join(" ")
2156}
2157
2158/// Truncates a script for display in messages.
2159fn truncate_script(script: &str, max_chars: usize) -> &str {
2160    let script = script.trim();
2161    // Find byte index at max_chars boundary
2162    match script.char_indices().nth(max_chars) {
2163        Some((byte_idx, _)) => &script[..byte_idx],
2164        None => script, // String is shorter than max_chars
2165    }
2166}
2167
2168#[cfg(test)]
2169mod tests {
2170    use super::*;
2171
2172    use futures_core::Stream;
2173
2174    use crate::compression::{CompressionLevel, PreserveConfig, SmartCompressionConfig};
2175    use crate::config::ContextAssemblerConfig;
2176    #[cfg(feature = "skills")]
2177    use crate::{AgentCheckpoint, ContextWindowMetrics, ContextWindowPhase, ContextWindowSnapshot};
2178    #[cfg(feature = "skills")]
2179    use aither_skills::{Skill, SkillRegistry};
2180    #[cfg(feature = "skills")]
2181    use std::collections::HashMap;
2182    #[cfg(feature = "skills")]
2183    use std::sync::Arc;
2184
2185    #[derive(Debug)]
2186    struct MockError;
2187
2188    impl std::fmt::Display for MockError {
2189        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2190            f.write_str("mock error")
2191        }
2192    }
2193
2194    impl std::error::Error for MockError {}
2195
2196    #[derive(Clone)]
2197    struct MockLlm {
2198        context_length: u32,
2199    }
2200
2201    impl LanguageModel for MockLlm {
2202        type Error = MockError;
2203
2204        fn respond(
2205            &self,
2206            _request: LLMRequest,
2207        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
2208            futures_lite::stream::empty()
2209        }
2210
2211        fn profile(&self) -> impl std::future::Future<Output = ModelProfile> + Send {
2212            std::future::ready(ModelProfile::new(
2213                "mock",
2214                "test",
2215                "mock-model",
2216                "mock model",
2217                self.context_length,
2218            ))
2219        }
2220    }
2221
2222    #[tokio::test]
2223    async fn snapshot_phase_accounts_for_system_blocks() {
2224        let config = AgentConfig {
2225            system_prompt: Some("x".repeat(120)),
2226            context: ContextStrategy::Smart(SmartCompressionConfig {
2227                trigger_threshold: 0.4,
2228                emergency_threshold: 0.9,
2229                preserve_recent: 0,
2230                preserve: PreserveConfig::default(),
2231                level: CompressionLevel::Standard,
2232            }),
2233            context_assembler: ContextAssemblerConfig {
2234                handoff_threshold: 10.0,
2235                ..ContextAssemblerConfig::default()
2236            },
2237            ..AgentConfig::default()
2238        };
2239
2240        let mut agent = Agent::with_config(
2241            MockLlm {
2242                context_length: 100,
2243            },
2244            config,
2245        );
2246        agent.push_message(Message::user("hello"));
2247
2248        let snapshot = agent.snapshot_context_window().await;
2249
2250        assert_eq!(snapshot.phase, ContextWindowPhase::CompressionDue);
2251        assert!(snapshot.metrics.system_block_count > 0);
2252        assert!(snapshot.metrics.usage_fraction >= 0.4);
2253        assert_eq!(snapshot.metrics.recent_message_count, 1);
2254    }
2255
2256    #[tokio::test]
2257    async fn snapshot_phase_reports_handoff_active() {
2258        let mut agent = Agent::new(MockLlm {
2259            context_length: 1_000,
2260        });
2261        agent.context_mut().set_handoff("resume here");
2262
2263        let snapshot = agent.snapshot_context_window().await;
2264
2265        assert_eq!(snapshot.phase, ContextWindowPhase::HandoffActive);
2266        assert!(snapshot.metrics.has_handoff);
2267    }
2268
2269    #[tokio::test]
2270    async fn handoff_due_does_not_trigger_automatic_compaction() {
2271        let config = AgentConfig {
2272            system_prompt: Some("x".repeat(120)),
2273            context: ContextStrategy::Smart(SmartCompressionConfig {
2274                trigger_threshold: 0.2,
2275                emergency_threshold: 0.9,
2276                preserve_recent: 0,
2277                preserve: PreserveConfig::default(),
2278                level: CompressionLevel::Standard,
2279            }),
2280            context_assembler: ContextAssemblerConfig {
2281                handoff_threshold: 0.1,
2282                ..ContextAssemblerConfig::default()
2283            },
2284            ..AgentConfig::default()
2285        };
2286
2287        let mut agent = Agent::with_config(
2288            MockLlm {
2289                context_length: 100,
2290            },
2291            config,
2292        );
2293        agent.push_message(Message::user("hello"));
2294
2295        let before_recent = agent.context().len_recent();
2296        agent
2297            .maybe_compress()
2298            .await
2299            .unwrap_or_else(|error| panic!("handoff_due must not compact automatically: {error}"));
2300
2301        assert_eq!(agent.context().len_recent(), before_recent);
2302        assert!(agent.context().handoff().is_none());
2303    }
2304
2305    #[tokio::test]
2306    async fn reassembly_due_prunes_recent_system_messages_before_compaction() {
2307        let config = AgentConfig {
2308            context: ContextStrategy::Smart(SmartCompressionConfig {
2309                trigger_threshold: 0.05,
2310                emergency_threshold: 0.9,
2311                preserve_recent: 100,
2312                preserve: PreserveConfig::default(),
2313                level: CompressionLevel::Standard,
2314            }),
2315            context_assembler: ContextAssemblerConfig {
2316                handoff_threshold: 10.0,
2317                ..ContextAssemblerConfig::default()
2318            },
2319            ..AgentConfig::default()
2320        };
2321
2322        let mut agent = Agent::with_config(
2323            MockLlm {
2324                context_length: 100,
2325            },
2326            config,
2327        );
2328        agent.push_message(Message::user("hello"));
2329        agent.push_message(Message::system(
2330            "<system-reminder>ephemeral</system-reminder>",
2331        ));
2332
2333        let snapshot = agent.snapshot_context_window().await;
2334        assert_eq!(snapshot.phase, ContextWindowPhase::ReassemblyDue);
2335
2336        agent
2337            .maybe_compress()
2338            .await
2339            .unwrap_or_else(|error| panic!("reassembly_due must not fail: {error}"));
2340
2341        assert_eq!(agent.context().count_recent_system_messages(), 0);
2342        assert_eq!(agent.context().len_recent(), 1);
2343        assert_eq!(agent.context().recent()[0].content(), "hello");
2344    }
2345
2346    #[tokio::test]
2347    async fn idle_gap_reassembles_before_next_live_request() {
2348        let mut config = AgentConfig::default();
2349        config.context_assembler.idle_reassemble_after = Duration::from_secs(1);
2350
2351        let mut agent = Agent::with_config(
2352            MockLlm {
2353                context_length: 1_000,
2354            },
2355            config,
2356        );
2357        agent.push_message(Message::user("hello"));
2358        agent.push_message(Message::system(
2359            "<system-reminder>ephemeral</system-reminder>",
2360        ));
2361        agent.last_request_started_at = Instant::now().checked_sub(Duration::from_secs(5));
2362
2363        let _ = agent.build_live_request_messages().await;
2364
2365        assert_eq!(agent.context().count_recent_system_messages(), 0);
2366        assert_eq!(agent.context().len_recent(), 1);
2367        assert_eq!(agent.context().recent()[0].content(), "hello");
2368        assert!(agent.last_request_started_at.is_some());
2369    }
2370
2371    #[test]
2372    fn permission_event_key_parses_terminal_modes() {
2373        let default_args = serde_json::to_value(TerminalArgs {
2374            description: "list the working directory".to_string(),
2375            script: "ls".to_string(),
2376            mode: TerminalExecutionMode::Default,
2377            ssh_server_id: None,
2378            expect: aither_sandbox::OutputFormat::Text,
2379            resolution: aither_sandbox::MediaResolution::Auto,
2380            timeout: 30,
2381            max_lines: 200,
2382            raw: false,
2383        })
2384        .expect("default args should serialize");
2385        let unsafe_args = serde_json::to_value(TerminalArgs {
2386            description: "remove the demo directory".to_string(),
2387            script: "rm -rf /tmp/demo".to_string(),
2388            mode: TerminalExecutionMode::Unsafe,
2389            ssh_server_id: None,
2390            expect: aither_sandbox::OutputFormat::Text,
2391            resolution: aither_sandbox::MediaResolution::Auto,
2392            timeout: 30,
2393            max_lines: 200,
2394            raw: false,
2395        })
2396        .expect("unsafe args should serialize");
2397        let sandboxed_args = serde_json::to_value(TerminalArgs {
2398            description: "print the current working directory".to_string(),
2399            script: "pwd".to_string(),
2400            mode: TerminalExecutionMode::Sandboxed,
2401            ssh_server_id: None,
2402            expect: aither_sandbox::OutputFormat::Text,
2403            resolution: aither_sandbox::MediaResolution::Auto,
2404            timeout: 30,
2405            max_lines: 200,
2406            raw: false,
2407        })
2408        .expect("sandboxed args should serialize");
2409
2410        let unsafe_key = permission_event_key_for_call("terminal", &unsafe_args)
2411            .expect("unsafe terminal mode should require permission routing");
2412
2413        // Default and sandboxed no longer require approval: network is
2414        // available by default and only unsafe escalation is gated.
2415        assert!(permission_event_key_for_call("terminal", &default_args).is_none());
2416        assert_eq!(unsafe_key.mode, TerminalMode::Unsafe);
2417        assert_eq!(unsafe_key.script, "rm -rf /tmp/demo");
2418        assert!(permission_event_key_for_call("terminal", &sandboxed_args).is_none());
2419    }
2420
2421    #[test]
2422    fn permission_pause_tracker_routes_waiting_and_resolved_events() {
2423        let tool_calls = vec![aither_core::llm::ToolCall::new(
2424            "tool-1",
2425            "terminal",
2426            serde_json::to_value(TerminalArgs {
2427                description: "remove the demo directory".to_string(),
2428                script: "rm -rf /tmp/demo".to_string(),
2429                mode: TerminalExecutionMode::Unsafe,
2430                ssh_server_id: None,
2431                expect: aither_sandbox::OutputFormat::Text,
2432                resolution: aither_sandbox::MediaResolution::Auto,
2433                timeout: 30,
2434                max_lines: 200,
2435                raw: false,
2436            })
2437            .expect("tool args should serialize"),
2438        )];
2439
2440        let mut tracker = PermissionPauseTracker::from_tool_calls(&tool_calls);
2441        let waiting = tracker
2442            .event_for(PermissionEvent {
2443                mode: TerminalMode::Unsafe,
2444                script: "rm -rf /tmp/demo".to_string(),
2445                stage: PermissionEventStage::Waiting,
2446            })
2447            .expect("waiting event should map to tool call");
2448        let resolved = tracker
2449            .event_for(PermissionEvent {
2450                mode: TerminalMode::Unsafe,
2451                script: "rm -rf /tmp/demo".to_string(),
2452                stage: PermissionEventStage::Resolved,
2453            })
2454            .expect("resolved event should map to tool call");
2455
2456        assert_eq!(
2457            waiting,
2458            (RunPauseReason::PermissionRequest, "tool-1".to_string())
2459        );
2460        assert_eq!(
2461            resolved,
2462            (RunPauseReason::PermissionRequest, "tool-1".to_string())
2463        );
2464    }
2465
2466    #[cfg(feature = "skills")]
2467    fn empty_checkpoint() -> AgentCheckpoint {
2468        AgentCheckpoint {
2469            context: crate::Context::default().checkpoint(),
2470            tool_surface_hash: "tool-surface".to_string(),
2471            context_window: ContextWindowSnapshot {
2472                phase: ContextWindowPhase::Stable,
2473                metrics: ContextWindowMetrics {
2474                    usage_fraction: 0.0,
2475                    selected_model_context_window: None,
2476                    fast_model_context_window: None,
2477                    effective_context_window: 0,
2478                    system_block_count: 0,
2479                    reminder_count: 0,
2480                    recent_message_count: 0,
2481                    recent_system_message_count: 0,
2482                    has_handoff: false,
2483                },
2484                messages: Vec::new(),
2485            },
2486            has_background_tasks: false,
2487        }
2488    }
2489
2490    #[cfg(feature = "skills")]
2491    fn review_skill_registry() -> Arc<SkillRegistry> {
2492        let mut registry = SkillRegistry::new();
2493        registry.register(Skill {
2494            name: "code-review".to_string(),
2495            description: "Review code carefully".to_string(),
2496            instructions: "Use a review checklist.".to_string(),
2497            allowed_tools: Some(vec!["mock_tool".to_string()]),
2498            resources: HashMap::new(),
2499        });
2500        Arc::new(registry)
2501    }
2502
2503    #[cfg(feature = "skills")]
2504    #[test]
2505    fn restore_checkpoint_succeeds_without_legacy_skill_state() {
2506        let mut agent = Agent::with_config(
2507            MockLlm {
2508                context_length: 1000,
2509            },
2510            AgentConfig::default(),
2511        );
2512        agent.skill_registry = Some(review_skill_registry());
2513
2514        agent
2515            .restore_checkpoint(empty_checkpoint())
2516            .expect("restore checkpoint must succeed");
2517    }
2518
2519    #[cfg(feature = "skills")]
2520    #[tokio::test]
2521    async fn activate_skills_for_prompt_is_disabled() {
2522        let mut registry = SkillRegistry::new();
2523        registry.register(Skill {
2524            name: "code-review".to_string(),
2525            description: "Review code carefully".to_string(),
2526            instructions: "Use a review checklist.".to_string(),
2527            allowed_tools: Some(vec!["mock_tool".to_string()]),
2528            resources: HashMap::new(),
2529        });
2530
2531        let mut agent = Agent::with_config(
2532            MockLlm {
2533                context_length: 1000,
2534            },
2535            AgentConfig::default(),
2536        );
2537        agent.skill_registry = Some(Arc::new(registry));
2538        let events = agent.activate_skills_for_prompt("please review this patch");
2539        assert!(events.is_empty());
2540        assert!(agent.active_skills.is_empty());
2541        assert!(agent.active_allowed_tools.is_none());
2542    }
2543
2544    #[cfg(feature = "skills")]
2545    #[tokio::test]
2546    async fn build_live_request_messages_omit_skill_resource_catalog() {
2547        let mut registry = SkillRegistry::new();
2548        registry.register(Skill {
2549            name: "code-review".to_string(),
2550            description: "Review code carefully".to_string(),
2551            instructions: "Use a review checklist.".to_string(),
2552            allowed_tools: Some(vec!["mock_tool".to_string()]),
2553            resources: HashMap::from([(
2554                "templates/review.md".to_string(),
2555                "# Review template".to_string(),
2556            )]),
2557        });
2558
2559        let mut agent = Agent::with_config(
2560            MockLlm {
2561                context_length: 1000,
2562            },
2563            AgentConfig::default(),
2564        );
2565        agent.skill_registry = Some(Arc::new(registry));
2566        let _ = agent.activate_skills_for_prompt("please review this patch");
2567
2568        let messages = agent.build_live_request_messages().await;
2569        assert!(
2570            messages
2571                .iter()
2572                .all(|message| !message.content().contains("templates/review.md")),
2573            "skill resource catalog must not be injected automatically"
2574        );
2575    }
2576
2577    fn tasks_stale_agent(dir: &std::path::Path) -> Agent<MockLlm, MockLlm, MockLlm, ()> {
2578        Agent::builder(MockLlm {
2579            context_length: 1_000,
2580        })
2581        .sandbox_dir(dir)
2582        .config(AgentConfig {
2583            tasks_stale_after_turns: 2,
2584            ..AgentConfig::default()
2585        })
2586        .build()
2587    }
2588
2589    fn stale_alert_count(agent: &Agent<MockLlm, MockLlm, MockLlm, ()>) -> usize {
2590        agent
2591            .context()
2592            .conversation_messages()
2593            .iter()
2594            .filter(|message| message.content().contains("<tasks_stale>"))
2595            .count()
2596    }
2597
2598    #[tokio::test]
2599    async fn tasks_stale_fires_once_after_threshold_with_unchecked_items() {
2600        use tempfile::tempdir;
2601
2602        let dir = tempdir().expect("tempdir should exist");
2603        std::fs::write(dir.path().join("tasks.md"), "- [ ] pending\n").expect("write tasks.md");
2604        let mut agent = tasks_stale_agent(dir.path());
2605
2606        agent.check_tasks_doc_staleness().await; // baseline
2607        agent.check_tasks_doc_staleness().await; // stale turn 1
2608        assert_eq!(stale_alert_count(&agent), 0);
2609        agent.check_tasks_doc_staleness().await; // stale turn 2 -> alert
2610        assert_eq!(stale_alert_count(&agent), 1);
2611        agent.check_tasks_doc_staleness().await; // still stale, no re-alert
2612        assert_eq!(stale_alert_count(&agent), 1);
2613    }
2614
2615    #[tokio::test]
2616    async fn tasks_stale_suggests_creating_missing_doc() {
2617        use tempfile::tempdir;
2618
2619        let dir = tempdir().expect("tempdir should exist");
2620        let mut agent = tasks_stale_agent(dir.path());
2621
2622        for _ in 0..3 {
2623            agent.check_tasks_doc_staleness().await;
2624        }
2625
2626        let messages = agent.context().conversation_messages();
2627        assert!(
2628            messages
2629                .iter()
2630                .any(|m| m.content().contains("without a tasks.md")),
2631            "missing tasks.md should earn a create-the-doc alert"
2632        );
2633    }
2634
2635    #[tokio::test]
2636    async fn metrics_snapshot_preserves_reminders_and_working_docs_baseline() {
2637        let mut agent = Agent::new(MockLlm {
2638            context_length: 1_000,
2639        });
2640        agent.context_mut().insert_reminder(&SystemReminder {
2641            content: "queued".to_string(),
2642        });
2643        agent.last_working_docs = Some(working_docs::WorkingDocsSnapshot {
2644            tasks_md: Some("- [ ] pending".to_string()),
2645        });
2646
2647        let _ = agent.snapshot_context_window().await;
2648        agent
2649            .maybe_compress()
2650            .await
2651            .expect("maybe_compress should succeed");
2652
2653        assert_eq!(agent.context().reminders().len(), 1);
2654        assert!(
2655            agent.last_working_docs.is_some(),
2656            "metrics-only reads must not consume the diff baseline"
2657        );
2658    }
2659
2660    #[tokio::test]
2661    async fn tasks_stale_resets_when_doc_is_updated_or_complete() {
2662        use tempfile::tempdir;
2663
2664        let dir = tempdir().expect("tempdir should exist");
2665        let tasks_path = dir.path().join("tasks.md");
2666        std::fs::write(&tasks_path, "- [ ] pending\n").expect("write tasks.md");
2667        let mut agent = tasks_stale_agent(dir.path());
2668
2669        agent.check_tasks_doc_staleness().await; // baseline
2670        agent.check_tasks_doc_staleness().await; // stale turn 1
2671
2672        // Model updates the doc: counter resets.
2673        std::fs::write(&tasks_path, "- [x] done\n- [ ] next\n").expect("update tasks.md");
2674        agent.check_tasks_doc_staleness().await;
2675        assert_eq!(agent.tasks_staleness.stale_turns, 0);
2676
2677        // All-checked doc is not stale: counter stays reset.
2678        std::fs::write(&tasks_path, "- [x] done\n- [x] next\n").expect("complete tasks.md");
2679        for _ in 0..4 {
2680            agent.check_tasks_doc_staleness().await;
2681        }
2682        assert_eq!(agent.tasks_staleness.stale_turns, 0);
2683        assert_eq!(stale_alert_count(&agent), 0);
2684    }
2685
2686    #[tokio::test]
2687    async fn system_alerts_survive_reminder_repopulation() {
2688        use aither_core::llm::Role;
2689
2690        let mut agent = Agent::new(MockLlm {
2691            context_length: 1_000,
2692        });
2693        agent.context_mut().insert_reminder(&SystemReminder {
2694            content: "stale reminder".to_string(),
2695        });
2696        agent.push_system_alert("no native tool named foo");
2697
2698        let snapshot = agent.assemble_context_window().await;
2699
2700        assert!(
2701            snapshot.messages.iter().any(|message| {
2702                message.role() == Role::System
2703                    && message.content().contains("no native tool named foo")
2704            }),
2705            "ad-hoc alerts must reach the next request"
2706        );
2707        assert!(
2708            snapshot
2709                .messages
2710                .iter()
2711                .all(|message| !message.content().contains("stale reminder")),
2712            "populate still clears managed reminders"
2713        );
2714    }
2715
2716    #[tokio::test]
2717    async fn preview_does_not_consume_working_docs_baseline() {
2718        use tempfile::tempdir;
2719
2720        let dir = tempdir().expect("tempdir should exist");
2721        std::fs::write(dir.path().join("tasks.md"), "- [ ] pending\n").expect("write tasks.md");
2722        let mut agent = Agent::builder(MockLlm {
2723            context_length: 1_000,
2724        })
2725        .sandbox_dir(dir.path())
2726        .build();
2727
2728        let _ = agent
2729            .preview_request_messages("hi", std::iter::empty())
2730            .await;
2731
2732        assert!(
2733            agent.last_working_docs.is_none(),
2734            "preview must restore the working-docs baseline"
2735        );
2736    }
2737}