aither_agent/context/live.rs
1//! Prefix content that changes while a session runs.
2//!
3//! Some system blocks describe things that change mid-session: a repository's
4//! `AGENTS.md`, memory, a table of the embedder's commands. Rewriting such
5//! a block at once would invalidate the provider's cached prefix, and leaving
6//! it would leave the model believing the old version. Live content takes the
7//! third way, the same for every such block:
8//!
9//! - a change made before any request has carried the prefix is written into
10//! it directly, since nothing cached the old version;
11//! - a change made after is staged, the prefix stays byte-identical, and the
12//! change is announced once, as a diff alert appended to the conversation;
13//! - the next reassembly (a compaction, or a cache that went cold) folds the
14//! clean current version into the prefix and drops the diff alerts, so the
15//! model reads the content once, with no diff.
16//!
17//! A host brings its blocks to their current version with
18//! [`Context::update_live`](crate::Context::update_live) whenever it reads
19//! them; an update that changes nothing announces nothing, so calling it on
20//! every turn is cheap and never repeats an alert.
21
22use askama::Template;
23
24use super::system::{
25 External, ExternalContent, ExternalSlot, Instruction, InstructionSlot, SystemRegion,
26 TextChange, boundary,
27};
28
29/// Names a piece of live content in the alert announcing its change.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct LiveContent {
32 subject: &'static str,
33 tag: &'static str,
34}
35
36impl LiveContent {
37 /// Live content the alert calls `subject`, which opens its first
38 /// sentence ("The launch directory's AGENTS.md files"), and whose diff it
39 /// wraps in the tag `tag` (`agents_md_diff`).
40 #[must_use]
41 pub const fn new(subject: &'static str, tag: &'static str) -> Self {
42 Self { subject, tag }
43 }
44}
45
46/// The blocks one [`Context::update_live`](crate::Context::update_live) call
47/// brings to their current version; every block that changed goes into the
48/// one alert the call appends.
49pub struct LiveUpdate<'a> {
50 instructions: &'a mut SystemRegion<Instruction>,
51 external: &'a mut SystemRegion<External>,
52 warm: bool,
53 changes: Vec<TextChange>,
54}
55
56impl std::fmt::Debug for LiveUpdate<'_> {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 f.debug_struct("LiveUpdate")
59 .field("warm", &self.warm)
60 .field("changes", &self.changes.len())
61 .finish_non_exhaustive()
62 }
63}
64
65impl<'a> LiveUpdate<'a> {
66 pub(crate) const fn new(
67 instructions: &'a mut SystemRegion<Instruction>,
68 external: &'a mut SystemRegion<External>,
69 warm: bool,
70 ) -> Self {
71 Self {
72 instructions,
73 external,
74 warm,
75 changes: Vec::new(),
76 }
77 }
78
79 /// Brings the instruction block in `slot` to `desired`, stored verbatim;
80 /// `None` removes the block.
81 ///
82 /// # Panics
83 ///
84 /// Panics if the layout has no such slot.
85 pub fn instruction(&mut self, slot: &InstructionSlot, desired: Option<String>) -> &mut Self {
86 let change = self.instructions.change(slot, desired, self.warm);
87 self.changes.extend(change);
88 self
89 }
90
91 /// Brings the external-content block in `slot` to `desired`; `None`
92 /// removes the block.
93 ///
94 /// # Panics
95 ///
96 /// Panics if the layout has no such slot.
97 pub fn external(&mut self, slot: &ExternalSlot, desired: Option<ExternalContent>) -> &mut Self {
98 let change = self.external.change(slot, desired, self.warm);
99 self.changes.extend(change);
100 self
101 }
102
103 /// The alert announcing every change this update made, `None` when the
104 /// model's view did not change.
105 pub(crate) fn into_alert(self, content: &LiveContent) -> Option<String> {
106 if self.changes.is_empty() {
107 return None;
108 }
109 let diff: String = self
110 .changes
111 .iter()
112 .map(|change| unified_diff(&change.before, &change.after))
113 .collect();
114 Some(
115 LiveContentChangedTemplate {
116 subject: content.subject,
117 tag: content.tag,
118 boundary: boundary(&[&diff]),
119 diff: &diff,
120 }
121 .render()
122 .expect("live content alert template must render"),
123 )
124 }
125}
126
127/// The unified diff from `before` to `after`.
128pub(crate) fn unified_diff(before: &str, after: &str) -> String {
129 similar::TextDiff::from_lines(before, after)
130 .unified_diff()
131 .context_radius(2)
132 .to_string()
133}
134
135/// The one alert announcing a change to live content.
136#[derive(Template)]
137#[template(path = "live_content_changed.txt", escape = "none")]
138struct LiveContentChangedTemplate<'a> {
139 subject: &'a str,
140 tag: &'a str,
141 boundary: String,
142 diff: &'a str,
143}