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