Skip to main content

aither_agent/
fork.rs

1//! What a fork subagent inherits from its parent agent.
2//!
3//! A parent agent publishes the request it is about to send to a
4//! [`ForkSource`]; an embedder's fork subagent reads the latest one and starts
5//! from it with [`AgentBuilder::forked_from`](crate::AgentBuilder::forked_from),
6//! so its first request is the parent's request followed by the fork prompt
7//! and reads the parent's warm prompt cache.
8
9use std::sync::{Arc, Mutex};
10
11use aither_core::llm::model::{Parameters, Profile};
12use aither_core::llm::tool::ToolDefinition;
13
14use crate::context::{Context, ContextBudget, ContextPolicy, PromptCache};
15
16/// The parent agent's request, as a fork subagent starts from it.
17///
18/// Everything a request is made of is kept as the parent assembled it: the
19/// window (system blocks, handoff, conversation and live tail, thinking
20/// blocks included), the tool definitions, the request parameters and the
21/// prompt-cache identity.
22#[derive(Debug, Clone)]
23pub struct ForkSnapshot {
24    /// The window the request was built from, with its live tail as the
25    /// last message.
26    pub(crate) context: Context,
27    pub(crate) prompt_cache: PromptCache,
28    pub(crate) budget: ContextBudget,
29    /// The parent's model, whose name identifies it.
30    pub(crate) profile: Profile,
31    pub(crate) request_parameters: Parameters,
32    /// The request-level effort the parent sends, so the fork's first
33    /// request carries the same and reads the parent's cache.
34    pub(crate) effort: crate::effort::EffortAnchor,
35    pub(crate) context_policy: ContextPolicy,
36    pub(crate) definitions: Vec<ToolDefinition>,
37    /// Window usage the request was sent at.
38    pub(crate) usage: f32,
39}
40
41impl ForkSnapshot {
42    /// The name of the model the parent ran the request on.
43    #[must_use]
44    pub fn model(&self) -> &str {
45        &self.profile.name
46    }
47
48    /// The tool definitions the parent's request carried. The fork's own
49    /// tools must present exactly these, or its first request diverges from
50    /// the parent's cached prefix at the tool definitions.
51    #[must_use]
52    pub fn definitions(&self) -> &[ToolDefinition] {
53        &self.definitions
54    }
55
56    /// The fraction of the context window the parent's request used.
57    #[must_use]
58    pub const fn usage(&self) -> f32 {
59        self.usage
60    }
61
62    /// The fraction of the context window the parent pauses at.
63    #[must_use]
64    pub fn compaction_usage(&self) -> f32 {
65        let window = f64::from(self.budget.window());
66        if window == 0.0 {
67            return 0.0;
68        }
69        let point = f64::from(
70            u32::try_from(self.context_policy.pause_point(self.budget.window()))
71                .unwrap_or(u32::MAX),
72        );
73        num_traits::ToPrimitive::to_f32(&(point / window)).unwrap_or(1.0)
74    }
75
76    /// Whether a fork may start from the request the parent sent: it is
77    /// refused within a tenth of the parent's pause point.
78    #[must_use]
79    pub fn allows_fork(&self) -> bool {
80        self.context_policy
81            .allows_fork(self.budget.estimated_tokens(), self.budget.window())
82    }
83
84    /// The parent's context policy.
85    #[must_use]
86    pub const fn policy(&self) -> &ContextPolicy {
87        &self.context_policy
88    }
89}
90
91/// The latest request of a parent agent, shared with whatever forks it.
92///
93/// Create one, hand a clone to the parent's builder with
94/// [`AgentBuilder::fork_source`](crate::AgentBuilder::fork_source) and keep
95/// one: the agent publishes every request it sends, and the holder reads the
96/// newest.
97#[derive(Debug, Clone, Default)]
98pub struct ForkSource {
99    latest: Arc<Mutex<Option<Arc<ForkSnapshot>>>>,
100}
101
102impl ForkSource {
103    /// Replaces the published request.
104    pub(crate) fn publish(&self, snapshot: ForkSnapshot) {
105        *self
106            .latest
107            .lock()
108            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::new(snapshot));
109    }
110
111    /// The request the parent sent last; `None` before its first.
112    #[must_use]
113    pub fn latest(&self) -> Option<Arc<ForkSnapshot>> {
114        self.latest
115            .lock()
116            .unwrap_or_else(std::sync::PoisonError::into_inner)
117            .clone()
118    }
119}