Skip to main content

aither_agent/context/
system.rs

1//! The system prompt's layout: which blocks it holds, in what order, and how
2//! external content is kept from posing as instructions.
3//!
4//! The system prompt has two regions, rendered in this order:
5//!
6//! 1. **instructions** — the agent's own prompt: the base system prompt, the
7//!    persona, the built-in rules and whatever the host adds;
8//! 2. **external content** — text the host did not write as instructions
9//!    (memory, a repository's `AGENTS.md`, fetched pages, files), each block
10//!    inside a provenance-labelled boundary its content cannot close, behind
11//!    one notice that such content is data.
12//!
13//! The host chooses the order of each region with a [`SystemLayout`]; a block
14//! renders at its slot's position whenever it was inserted, so the prefix is
15//! a function of the layout and the contents alone. The region a block
16//! belongs to is part of its slot's type, which is what keeps external
17//! content after every instruction.
18
19use std::borrow::Cow;
20use std::collections::BTreeMap;
21use std::fmt::Debug;
22use std::marker::PhantomData;
23
24use askama::Template;
25use serde::de::DeserializeOwned;
26use serde::{Deserialize, Serialize};
27use sha2::{Digest, Sha256};
28
29/// A block of text wrapped in the one delimiting tag the model sees.
30#[derive(Template)]
31#[template(path = "tagged_block.txt", escape = "none")]
32pub(crate) struct TaggedBlockTemplate<'a> {
33    pub(crate) tag: &'a str,
34    pub(crate) content: &'a str,
35}
36
37impl TaggedBlockTemplate<'_> {
38    pub(crate) fn into_text(self) -> String {
39        self.render().expect("tagged block template must render")
40    }
41}
42
43mod sealed {
44    pub trait Sealed {}
45}
46
47/// The kind of a system block, which fixes the region it renders in and the
48/// content it holds.
49pub trait BlockKind: sealed::Sealed + Debug + Clone + PartialEq + Eq + Ord {
50    /// What a block of this kind holds.
51    type Content: Debug + Clone + PartialEq + Serialize + DeserializeOwned;
52
53    /// The region's name, for diagnostics.
54    const REGION: &'static str;
55
56    /// The text of `content` the model reads, which a change is diffed on.
57    fn text(content: &Self::Content) -> &str;
58}
59
60/// Instruction blocks: the agent's own prompt, rendered first.
61#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub struct Instruction;
63
64impl sealed::Sealed for Instruction {}
65
66impl BlockKind for Instruction {
67    type Content = String;
68    const REGION: &'static str = "instruction";
69
70    fn text(content: &Self::Content) -> &str {
71        content
72    }
73}
74
75/// External-content blocks: bounded data, rendered after every instruction.
76#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub struct External;
78
79impl sealed::Sealed for External {}
80
81impl BlockKind for External {
82    type Content = ExternalContent;
83    const REGION: &'static str = "external";
84
85    fn text(content: &Self::Content) -> &str {
86        &content.content
87    }
88}
89
90/// Blocks live sources render: placed after the system prompt and before the
91/// handoff, in the cacheable prefix (see [`LiveSource`](crate::LiveSource)).
92#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
93pub struct Sourced;
94
95impl sealed::Sealed for Sourced {}
96
97impl BlockKind for Sourced {
98    type Content = String;
99    const REGION: &'static str = "live source";
100
101    fn text(content: &Self::Content) -> &str {
102        content
103    }
104}
105
106/// The identity of a system block within its region.
107///
108/// The slot's type names its region, so a block can only be inserted where
109/// the layout places blocks of its kind.
110#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
111#[serde(transparent)]
112pub struct Slot<K> {
113    name: Cow<'static, str>,
114    #[serde(skip)]
115    kind: PhantomData<fn() -> K>,
116}
117
118/// The slot of an instruction block.
119pub type InstructionSlot = Slot<Instruction>;
120
121/// The slot of an external-content block.
122pub type ExternalSlot = Slot<External>;
123
124/// The slot of a live source's block, named by its
125/// [`TAG`](crate::LiveSource::TAG).
126pub type SourcedSlot = Slot<Sourced>;
127
128impl<K> Slot<K> {
129    /// A slot named `name`. The name is also the tag a tagged block renders
130    /// with.
131    #[must_use]
132    pub const fn new(name: &'static str) -> Self {
133        Self {
134            name: Cow::Borrowed(name),
135            kind: PhantomData,
136        }
137    }
138
139    /// A slot named `name`, for a name known only at run time.
140    pub(crate) fn owned(name: String) -> Self {
141        Self {
142            name: Cow::Owned(name),
143            kind: PhantomData,
144        }
145    }
146
147    /// The slot's name.
148    #[must_use]
149    pub fn name(&self) -> &str {
150        &self.name
151    }
152}
153
154#[cfg(test)]
155impl InstructionSlot {
156    pub(crate) const BASE_SYSTEM: Self = Self::new("base_system");
157    pub(crate) const PERSONA: Self = Self::new("persona");
158    pub(crate) const PERMISSIONS: Self = Self::new("permissions");
159}
160
161/// The order the host gives the system prompt's blocks.
162///
163/// Every block the prompt holds has a slot here; inserting a block whose slot
164/// is not laid out is a mistake in the host and panics. aither supplies no
165/// block of its own: the prompt holds what the embedder fills. Instructions
166/// render first in their listed order, then the external-content notice and
167/// the external blocks in theirs.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct SystemLayout {
170    instructions: Vec<InstructionSlot>,
171    external: Vec<ExternalSlot>,
172}
173
174impl SystemLayout {
175    /// A layout rendering `instructions`, then `external`, each in the order
176    /// given.
177    ///
178    /// # Panics
179    ///
180    /// Panics if a slot is listed twice in its region.
181    #[must_use]
182    pub fn new(
183        instructions: impl IntoIterator<Item = InstructionSlot>,
184        external: impl IntoIterator<Item = ExternalSlot>,
185    ) -> Self {
186        Self {
187            instructions: unique_slots(instructions),
188            external: unique_slots(external),
189        }
190    }
191
192    /// The instruction slots in render order.
193    #[must_use]
194    pub fn instructions(&self) -> &[InstructionSlot] {
195        &self.instructions
196    }
197
198    /// The external-content slots in render order.
199    #[must_use]
200    pub fn external(&self) -> &[ExternalSlot] {
201        &self.external
202    }
203
204    /// The instruction and external-content orders.
205    pub(crate) fn into_regions(self) -> (Vec<InstructionSlot>, Vec<ExternalSlot>) {
206        (self.instructions, self.external)
207    }
208}
209
210impl Default for SystemLayout {
211    /// No slots: the system prompt holds only the blocks the embedder places
212    /// and fills, in the order it places them.
213    fn default() -> Self {
214        Self::new([], [])
215    }
216}
217
218fn unique_slots<K: BlockKind>(slots: impl IntoIterator<Item = Slot<K>>) -> Vec<Slot<K>> {
219    let slots: Vec<Slot<K>> = slots.into_iter().collect();
220    for (index, slot) in slots.iter().enumerate() {
221        assert!(
222            !slots[..index].contains(slot),
223            "{} slot `{}` is laid out twice",
224            K::REGION,
225            slot.name()
226        );
227    }
228    slots
229}
230
231/// One region of the system prompt: the blocks of one kind, in the order the
232/// layout gives them.
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234#[serde(bound(
235    serialize = "K::Content: Serialize",
236    deserialize = "K::Content: DeserializeOwned"
237))]
238pub struct SystemRegion<K: BlockKind> {
239    order: Vec<Slot<K>>,
240    blocks: BTreeMap<Slot<K>, K::Content>,
241    /// Live-content changes applied on the next reassembly: the new content,
242    /// or `None` for a block that goes away.
243    ///
244    /// Rewriting a block while the prefix is cached invalidates it, so a
245    /// change is parked here (and announced to the model as an appended diff
246    /// alert instead) until reassembly, which rewrites the prefix anyway.
247    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
248    staged: BTreeMap<Slot<K>, Option<K::Content>>,
249}
250
251/// One live block's change, as the model is told it: the text it knew and
252/// the text it is to know.
253#[derive(Debug)]
254pub(crate) struct TextChange {
255    pub(crate) before: String,
256    pub(crate) after: String,
257}
258
259impl<K: BlockKind> SystemRegion<K> {
260    pub(crate) const fn with_order(order: Vec<Slot<K>>) -> Self {
261        Self {
262            order,
263            blocks: BTreeMap::new(),
264            staged: BTreeMap::new(),
265        }
266    }
267
268    /// Replaces the region's order.
269    ///
270    /// # Panics
271    ///
272    /// Panics if a block already present, or staged, has no slot in `order`.
273    pub(crate) fn set_order(&mut self, order: Vec<Slot<K>>) {
274        self.order = order;
275        for slot in self.blocks.keys().chain(self.staged.keys()) {
276            self.assert_placed(slot);
277        }
278    }
279
280    /// Appends `slot` to the region's order unless it is already placed.
281    pub(crate) fn place(&mut self, slot: Slot<K>) {
282        if !self.order.contains(&slot) {
283            self.order.push(slot);
284        }
285    }
286
287    fn assert_placed(&self, slot: &Slot<K>) {
288        assert!(
289            self.order.contains(slot),
290            "{} block `{}` has no slot in the system layout",
291            K::REGION,
292            slot.name()
293        );
294    }
295
296    /// The region's slots in render order.
297    #[must_use]
298    pub fn order(&self) -> &[Slot<K>] {
299        &self.order
300    }
301
302    /// Inserts or replaces the block in `slot`.
303    ///
304    /// # Panics
305    ///
306    /// Panics if the layout has no such slot.
307    pub fn insert(&mut self, slot: &Slot<K>, content: impl Into<K::Content>) {
308        self.assert_placed(slot);
309        self.blocks.insert(slot.clone(), content.into());
310    }
311
312    /// Removes the block in `slot`, together with any staged replacement.
313    pub fn remove(&mut self, slot: &Slot<K>) -> Option<K::Content> {
314        self.staged.remove(slot);
315        self.blocks.remove(slot)
316    }
317
318    /// The block in `slot`.
319    #[must_use]
320    pub fn get(&self, slot: &Slot<K>) -> Option<&K::Content> {
321        self.blocks.get(slot)
322    }
323
324    /// Whether `slot` holds a block.
325    #[must_use]
326    pub fn contains(&self, slot: &Slot<K>) -> bool {
327        self.blocks.contains_key(slot)
328    }
329
330    /// The number of blocks held.
331    #[must_use]
332    pub fn len(&self) -> usize {
333        self.blocks.len()
334    }
335
336    /// Whether the region holds no block.
337    #[must_use]
338    pub fn is_empty(&self) -> bool {
339        self.blocks.is_empty()
340    }
341
342    /// The blocks in render order.
343    pub fn iter(&self) -> impl Iterator<Item = (&Slot<K>, &K::Content)> {
344        self.order
345            .iter()
346            .filter_map(|slot| self.blocks.get(slot).map(|content| (slot, content)))
347    }
348
349    /// The content the model knows `slot` to hold: the prefix's block with
350    /// every announced change applied.
351    fn known(&self, slot: &Slot<K>) -> Option<&K::Content> {
352        self.staged
353            .get(slot)
354            .map_or_else(|| self.blocks.get(slot), Option::as_ref)
355    }
356
357    /// Brings the live block in `slot` to `desired` (`None` removes it).
358    ///
359    /// While the prefix is `warm` the block is left as the cache holds it and
360    /// the change is staged for the next reassembly; the change is returned
361    /// when the text the model reads differs from what it knows, so the
362    /// caller announces it. A cold prefix is rewritten at once and nothing
363    /// is returned: no request has carried the old version.
364    ///
365    /// # Panics
366    ///
367    /// Panics if the layout has no such slot.
368    pub(crate) fn change(
369        &mut self,
370        slot: &Slot<K>,
371        desired: Option<K::Content>,
372        warm: bool,
373    ) -> Option<TextChange> {
374        self.assert_placed(slot);
375        let known = self.known(slot);
376        if known == desired.as_ref() {
377            return None;
378        }
379        if warm {
380            let change = TextChange {
381                before: known.map_or("", K::text).to_owned(),
382                after: desired.as_ref().map_or("", K::text).to_owned(),
383            };
384            if self.blocks.get(slot) == desired.as_ref() {
385                self.staged.remove(slot);
386            } else {
387                self.staged.insert(slot.clone(), desired);
388            }
389            return (change.before != change.after).then_some(change);
390        }
391        self.staged.remove(slot);
392        match desired {
393            Some(content) => self.blocks.insert(slot.clone(), content),
394            None => self.blocks.remove(slot),
395        };
396        None
397    }
398
399    /// Whether any change is waiting for reassembly.
400    #[must_use]
401    pub fn has_staged(&self) -> bool {
402        !self.staged.is_empty()
403    }
404
405    /// Folds the staged changes in, returning how many were applied and how
406    /// many bytes they freed.
407    pub(crate) fn apply_staged(&mut self) -> (usize, usize) {
408        let mut applied = 0;
409        let mut freed = 0;
410        for (slot, content) in std::mem::take(&mut self.staged) {
411            let before = self
412                .blocks
413                .get(&slot)
414                .map_or(0, |block| K::text(block).len());
415            let after = content.as_ref().map_or(0, |block| K::text(block).len());
416            freed += before.saturating_sub(after);
417            match content {
418                Some(content) => self.blocks.insert(slot, content),
419                None => self.blocks.remove(&slot),
420            };
421            applied += 1;
422        }
423        (applied, freed)
424    }
425
426    /// Drops every block and staged replacement, keeping the order.
427    pub(crate) fn clear(&mut self) {
428        self.blocks.clear();
429        self.staged.clear();
430    }
431}
432
433impl SystemRegion<Instruction> {
434    /// Inserts or replaces the block in `slot`, wrapped in a tag named after
435    /// the slot.
436    ///
437    /// # Panics
438    ///
439    /// Panics if the layout has no such slot.
440    pub fn insert_tagged(&mut self, slot: &InstructionSlot, content: &str) {
441        let wrapped = TaggedBlockTemplate {
442            tag: slot.name(),
443            content,
444        }
445        .into_text();
446        self.insert(slot, wrapped);
447    }
448}
449
450/// How the model is to treat a block of external content.
451#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
452#[serde(rename_all = "snake_case")]
453enum ExternalKind {
454    /// Data the model may read and use, never follow.
455    Data,
456    /// A repository's own rules (`AGENTS.md` and the like): followed as
457    /// project rules, subordinate to the system prompt and the user.
458    RepositoryInstructions,
459}
460
461impl ExternalKind {
462    const fn label(self) -> &'static str {
463        match self {
464            Self::Data => "data",
465            Self::RepositoryInstructions => "repository-instructions",
466        }
467    }
468}
469
470/// Text the host places in the system prompt without writing it as
471/// instructions: memory, a repository's instructions, a fetched page, a file.
472///
473/// It renders inside a boundary derived from its own bytes, which therefore
474/// never occurs in it: nothing it contains can close the block or pose as a
475/// block of its own.
476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477pub struct ExternalContent {
478    kind: ExternalKind,
479    source: String,
480    content: String,
481}
482
483impl ExternalContent {
484    /// Data from `source` (a path, a URL, or a name such as `memory`).
485    #[must_use]
486    pub fn data(source: impl Into<String>, content: impl Into<String>) -> Self {
487        Self {
488            kind: ExternalKind::Data,
489            source: source.into(),
490            content: content.into(),
491        }
492    }
493
494    /// A repository's instructions, read from `source`: followed as project
495    /// rules, subordinate to the system prompt and the user.
496    #[must_use]
497    pub fn repository_instructions(source: impl Into<String>, content: impl Into<String>) -> Self {
498        Self {
499            kind: ExternalKind::RepositoryInstructions,
500            source: source.into(),
501            content: content.into(),
502        }
503    }
504
505    /// Where the content came from.
506    #[must_use]
507    pub fn source(&self) -> &str {
508        &self.source
509    }
510
511    /// The content itself.
512    #[must_use]
513    pub fn content(&self) -> &str {
514        &self.content
515    }
516
517    /// Whether the content is a repository's instructions.
518    #[must_use]
519    pub const fn is_repository_instructions(&self) -> bool {
520        matches!(self.kind, ExternalKind::RepositoryInstructions)
521    }
522
523    /// The boundary this block renders inside.
524    ///
525    /// A hash of the block, so the same block always renders the same bytes
526    /// and the prompt-cache prefix survives a rebuild; a candidate that
527    /// occurs in the label or the content is skipped, so the boundary never
528    /// does.
529    fn boundary(&self) -> String {
530        boundary(&[self.kind.label(), &self.source, &self.content])
531    }
532}
533
534/// A boundary that occurs in none of `parts`: hex of a hash of them, rehashed
535/// until it is absent, so the same parts always get the same boundary.
536pub(crate) fn boundary(parts: &[&str]) -> String {
537    let mut attempt: u64 = 0;
538    loop {
539        let mut hasher = Sha256::new();
540        for (index, part) in parts.iter().enumerate() {
541            if index > 0 {
542                hasher.update([0]);
543            }
544            hasher.update(part);
545        }
546        hasher.update(attempt.to_le_bytes());
547        let candidate = crate::agent::hex_encode(&hasher.finalize()[..8]);
548        if parts.iter().all(|part| !part.contains(&candidate)) {
549            return candidate;
550        }
551        attempt += 1;
552    }
553}
554
555impl ExternalContent {
556    /// The block as the templates read it.
557    fn view(&self) -> ExternalBlockView<'_> {
558        ExternalBlockView {
559            boundary: self.boundary(),
560            kind: self.kind.label(),
561            source: &self.source,
562            content: &self.content,
563        }
564    }
565
566    /// The content inside its provenance-labelled boundary, for a host that
567    /// places it in text of its own — an alert's template, say.
568    ///
569    /// The closing tag carries a boundary derived from the block's own
570    /// bytes, which therefore never occurs in it, exactly as in the system
571    /// prompt. The same block always renders the same text. The text does
572    /// not repeat the notice that external content is data; see
573    /// [`Block::external`](super::Block::external) for a block that does.
574    ///
575    /// # Panics
576    ///
577    /// Panics if the template fails to render.
578    #[must_use]
579    pub fn render(&self) -> String {
580        ExternalBlockTemplate { block: self.view() }
581            .render()
582            .expect("external block template must render")
583    }
584
585    /// The block with the notice that external content is data before it,
586    /// for an alert that arrives where the system prompt has no such notice.
587    pub(crate) fn render_with_notice(&self) -> String {
588        ExternalAlertTemplate { block: self.view() }
589            .render()
590            .expect("external alert template must render")
591    }
592}
593
594/// One external block as the templates read it.
595struct ExternalBlockView<'a> {
596    boundary: String,
597    kind: &'static str,
598    source: &'a str,
599    content: &'a str,
600}
601
602/// One external block, bounded.
603#[derive(Template)]
604#[template(path = "external_block.txt", escape = "none")]
605struct ExternalBlockTemplate<'a> {
606    block: ExternalBlockView<'a>,
607}
608
609/// One external block, bounded and preceded by the notice that it is data.
610#[derive(Template)]
611#[template(path = "external_alert.txt", escape = "none")]
612struct ExternalAlertTemplate<'a> {
613    block: ExternalBlockView<'a>,
614}
615
616/// The whole cacheable system prefix.
617#[derive(Template)]
618#[template(path = "system_prefix.txt", escape = "none")]
619struct SystemPrefixTemplate<'a> {
620    instructions: Vec<&'a str>,
621    external: Vec<ExternalBlockView<'a>>,
622}
623
624/// Renders the system prefix: the instructions, then the external notice and
625/// blocks. `None` when both regions are empty.
626pub(crate) fn render_prefix(
627    instructions: &SystemRegion<Instruction>,
628    external: &SystemRegion<External>,
629) -> Option<String> {
630    if instructions.is_empty() && external.is_empty() {
631        return None;
632    }
633    let template = SystemPrefixTemplate {
634        instructions: instructions.iter().map(|(_, text)| text.as_str()).collect(),
635        external: external.iter().map(|(_, block)| block.view()).collect(),
636    };
637    Some(
638        template
639            .render()
640            .expect("system prefix template must render"),
641    )
642}