Skip to main content

blyte_agent/
context.rs

1//! How the next prompt is assembled.
2//!
3//! [`Conversational`] is what mainstream harnesses do: append every turn and re-send the lot.
4//!
5//! [`Folded`] sends `[opening] [digest 1] … [digest k] [verbatim tail]`. Once the verbatim part
6//! passes `budget_tokens`, its older half becomes one harness-written digest. Boundaries are
7//! computed greedily from the start of history, so each depends only on the messages before it:
8//! the next turn reproduces every earlier fold exactly, and between folds the output is pure
9//! append. A cut never separates a tool call from its result.
10
11use blyte_provider::{Message, UserPart};
12
13use crate::state::State;
14
15pub trait ContextStrategy: Send + Sync {
16    /// Build the messages for the next call from the run so far.
17    fn build(&self, state: &State, history: &[Message]) -> Vec<Message>;
18    /// The folds this strategy makes over `history`, as `(a, b)` ranges of `history[1..]`.
19    /// Strategies that never fold return none.
20    fn folds(&self, _history: &[Message]) -> Vec<(usize, usize)> {
21        Vec::new()
22    }
23    /// The fold budget in force after `history`, in approximate tokens, for strategies that fold.
24    fn fold_budget(&self, _history: &[Message]) -> Option<usize> {
25        None
26    }
27}
28
29/// Everything, every time. The baseline to beat.
30#[derive(Debug, Default, Clone)]
31pub struct Conversational;
32
33impl ContextStrategy for Conversational {
34    fn build(&self, _state: &State, history: &[Message]) -> Vec<Message> {
35        history.to_vec()
36    }
37}
38
39/// An append-only conversation, bounded by folding.
40///
41/// `Folded` sends `[opening] [digest 1] … [digest k] [verbatim tail]`. Once the verbatim part
42/// passes `budget_tokens`, its older half becomes one harness-written digest. Boundaries are
43/// computed greedily from the start of history, so each depends only on the messages before it:
44/// the next turn reproduces every earlier fold exactly, and between folds the output is pure
45/// append. A cut never separates a tool call from its result.
46#[derive(Debug, Clone)]
47pub struct Folded {
48    /// Approximate token budget (characters / 4) for the verbatim tail.
49    pub budget_tokens: usize,
50}
51
52impl Default for Folded {
53    fn default() -> Self {
54        Self {
55            budget_tokens: 48_000,
56        }
57    }
58}
59
60/// Fixed token estimate per image, used only for folding and sizing; billing uses the provider's
61/// reported usage.
62pub const IMAGE_TOKEN_ESTIMATE: usize = 1_000;
63
64/// Characters / 4: a budget, not a billing figure.
65pub fn approx_tokens(m: &Message) -> usize {
66    match m {
67        Message::User(t) | Message::Assistant(t) => t.len() / 4,
68        Message::UserParts(parts) => {
69            let mut text_chars = 0usize;
70            let mut images = 0usize;
71            for part in parts {
72                match part {
73                    UserPart::Text(t) => text_chars += t.len(),
74                    UserPart::Image { .. } => images += 1,
75                }
76            }
77            text_chars / 4 + images * IMAGE_TOKEN_ESTIMATE
78        }
79        Message::ToolCall { arguments, .. } => arguments.to_string().len() / 4,
80        Message::ToolResult { content, .. } => content.len() / 4,
81    }
82}
83
84fn clip(text: &str, max: usize) -> String {
85    let one_line = text.lines().next().unwrap_or("").trim();
86    if one_line.chars().count() > max {
87        format!("{}...", one_line.chars().take(max).collect::<String>())
88    } else {
89        one_line.to_string()
90    }
91}
92
93/// One harness-written line per folded item, from the same summarisers as the action ledger.
94/// Calls are paired with results by position within their turn block (calls, then results, in
95/// call order). Not by id: Gemini issues no ids, the adapter numbers calls from `call_0` every
96/// turn, so ids repeat across turns and an id match would pair a call with another turn's result.
97pub fn digest(folded: &[Message], first: usize, last: usize) -> Message {
98    let mut text = format!(
99        "## Earlier turns, folded (messages {first}-{last}; summarised by the harness)\n\
100                 The output of these tool calls is no longer in your context: read a file again \
101                 before quoting or relying on its exact text.\n"
102    );
103    let mut i = 0;
104    while i < folded.len() {
105        match &folded[i] {
106            Message::ToolCall { .. } => {
107                let calls_end = (i..folded.len())
108                    .find(|&j| !matches!(folded[j], Message::ToolCall { .. }))
109                    .unwrap_or(folded.len());
110                let results_end = (calls_end..folded.len())
111                    .find(|&j| !matches!(folded[j], Message::ToolResult { .. }))
112                    .unwrap_or(folded.len());
113                for (k, call) in folded[i..calls_end].iter().enumerate() {
114                    let Message::ToolCall {
115                        name, arguments, ..
116                    } = call
117                    else {
118                        continue;
119                    };
120                    let target = crate::run::extract_action_target(name, arguments);
121                    let summary = match folded.get(calls_end + k) {
122                        Some(Message::ToolResult {
123                            content, is_error, ..
124                        }) if calls_end + k < results_end => {
125                            crate::run::extract_action_summary(name, content, *is_error)
126                        }
127                        _ => "no result".to_string(),
128                    };
129                    text.push_str(&format!("- `{name}` `{target}` -> {summary}\n"));
130                }
131                i = results_end.max(i + 1);
132            }
133            Message::Assistant(t) => {
134                text.push_str(&format!("- you said: {}\n", clip(t, 160)));
135                i += 1;
136            }
137            Message::User(t) => {
138                text.push_str(&format!("- harness: {}\n", clip(t, 160)));
139                i += 1;
140            }
141            Message::UserParts(parts) => {
142                let mut pieces = Vec::new();
143                for part in parts {
144                    match part {
145                        UserPart::Text(t) => {
146                            let c = clip(t, 160);
147                            if !c.is_empty() {
148                                pieces.push(c);
149                            }
150                        }
151                        UserPart::Image { mime_type, .. } => {
152                            pieces.push(format!("[image {mime_type}]"));
153                        }
154                    }
155                }
156                text.push_str(&format!("- harness: {}\n", pieces.join(" ")));
157                i += 1;
158            }
159            Message::ToolResult { .. } => i += 1,
160        }
161    }
162    Message::User(text)
163}
164
165/// Where `Folded` put its boundaries over `history[1..]`: each fold `(a, b)` and the start of the
166/// verbatim tail.
167struct FoldPlan {
168    folds: Vec<(usize, usize)>,
169    seg_start: usize,
170}
171
172/// Greedy fold boundaries over `rest`: each fold depends only on messages before it, so the next
173/// turn reproduces every earlier fold exactly.
174fn greedy_plan(rest: &[Message], budget: usize) -> FoldPlan {
175    let mut folds: Vec<(usize, usize)> = Vec::new();
176    let mut seg_start = 0;
177    let mut size = 0;
178    for i in 0..rest.len() {
179        size += approx_tokens(&rest[i]);
180        if size <= budget {
181            continue;
182        }
183        // Fold roughly the older half, cutting only between turn blocks (never after a call or
184        // before a result), so a call is never separated from its result or from calls in the
185        // same batch. No safe cut yet: keep accumulating.
186        let target = seg_start + (i + 1 - seg_start) / 2;
187        let lo = target.max(seg_start + 1);
188        let Some(cut) = (lo..=i).find(|&j| {
189            !matches!(rest[j], Message::ToolResult { .. })
190                && !matches!(rest[j - 1], Message::ToolCall { .. })
191        }) else {
192            continue;
193        };
194        folds.push((seg_start, cut));
195        size = rest[cut..=i].iter().map(approx_tokens).sum();
196        seg_start = cut;
197    }
198    FoldPlan { folds, seg_start }
199}
200
201/// The prompt for a fold plan: the opening, one digest per fold, then the verbatim tail.
202fn render_folded(opening: &Message, rest: &[Message], plan: &FoldPlan) -> Vec<Message> {
203    let mut out = vec![opening.clone()];
204    for &(a, b) in &plan.folds {
205        // Message numbers are 1-based positions in the full history.
206        out.push(digest(&rest[a..b], a + 2, b + 1));
207    }
208    out.extend_from_slice(&rest[plan.seg_start..]);
209    out
210}
211
212impl Folded {
213    /// Greedy boundaries from the start: each fold depends only on messages before it, so the next
214    /// turn reproduces every earlier fold exactly.
215    fn plan(&self, rest: &[Message]) -> FoldPlan {
216        greedy_plan(rest, self.budget_tokens)
217    }
218}
219
220impl ContextStrategy for Folded {
221    fn build(&self, _state: &State, history: &[Message]) -> Vec<Message> {
222        let Some((opening, rest)) = history.split_first() else {
223            return Vec::new();
224        };
225        render_folded(opening, rest, &self.plan(rest))
226    }
227
228    fn folds(&self, history: &[Message]) -> Vec<(usize, usize)> {
229        history
230            .split_first()
231            .map(|(_, rest)| self.plan(rest).folds)
232            .unwrap_or_default()
233    }
234
235    fn fold_budget(&self, _history: &[Message]) -> Option<usize> {
236        Some(self.budget_tokens)
237    }
238}