Skip to main content

base/
prompt.rs

1//! The prompt block type and the names the kernel's blocks carry. Assembly
2//! itself is `runtime::prompt_assembly`; this file is only the data it produces.
3
4use serde::{Deserialize, Serialize};
5
6/// Protocol-agnostic prompt block.
7///
8/// Each Model implementation translates these into its API-specific format.
9/// `cache_strategy` carries Anthropic cache_control semantics (Ephemeral/Global)
10/// but is ignored by non-Anthropic models.
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12pub struct PromptBlock {
13    pub role: BlockRole,
14    pub content: String,
15    #[serde(default, skip_serializing_if = "Option::is_none")]
16    pub cache_strategy: Option<CacheStrategy>,
17    /// What this block is — see the [`names`] module.
18    ///
19    /// Annotation only: no adapter reads it, so it never reaches the wire and
20    /// two blocks differing only here are byte-identical to the model. It
21    /// exists because block boundaries alone do not say which block is the
22    /// skills inventory and which is the MCP instructions, and the count
23    /// shifts with configuration (rules, MCP and `prompt.append` are each
24    /// optional), so position is not a reliable answer.
25    ///
26    /// This is how an extension addresses a block: "put mine after
27    /// `skills.catalog`", "replace `memory.session`". That only works if the
28    /// names are stable, which is why the kernel's are a published contract
29    /// and not a debugging label.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub name: Option<String>,
32    /// Who put this block here.
33    ///
34    /// Separate from [`name`](Self::name) because they answer different
35    /// questions: the name says which block this is, the origin says whose it
36    /// is. Rearranging the prompt is a privileged act, and how privileged
37    /// depends on where the rearranging came from — a plugin someone
38    /// downloaded is not a script that same person wrote. Nothing enforces
39    /// that yet; recording it truthfully is the precondition for enforcing it
40    /// at all.
41    #[serde(default, skip_serializing_if = "BlockOrigin::is_kernel")]
42    pub origin: BlockOrigin,
43}
44
45/// The kernel's block names. **A published contract**: an extension that
46/// positions itself relative to one of these is relying on the name to keep
47/// meaning what it means, so these change the way any public name changes.
48///
49/// A scene that names its own sections keeps those names, prefixed with
50/// `scene.`; [`SCENE_SKELETON`] is what a scene that names nothing gets.
51pub mod names {
52    /// The scene's system prompt, when the scene does not name its sections.
53    pub const SCENE_SKELETON: &str = "scene.skeleton";
54    /// Prefix for a scene that does name its sections.
55    pub const SCENE_PREFIX: &str = "scene.";
56    /// The inventory of available skills. A `User` block — it opens the
57    /// conversation rather than joining the system prompt.
58    pub const SKILLS_CATALOG: &str = "skills.catalog";
59    /// How to use the file-based memory system.
60    pub const MEMORY_SESSION: &str = "memory.session";
61    /// The discovery index of `.agix/rules/` files.
62    pub const RULES: &str = "rules";
63    /// Instructions contributed by connected MCP servers.
64    pub const MCP_INSTRUCTIONS: &str = "mcp.instructions";
65    /// `settings.prompt.append` given as one text.
66    pub const CONFIG_PROMPT_APPEND: &str = "config.prompt_append";
67    /// Prefix of the configuration's blocks, among them each block of a
68    /// `settings.prompt.append` list a settings file gave.
69    pub const CONFIG_PREFIX: &str = "config.";
70    /// Prefix of each block of a `settings.prompt.append` list the host gave.
71    pub const HOST_PREFIX: &str = "host.";
72    /// `settings.prompt.override`, which replaces everything else.
73    pub const CONFIG_PROMPT_OVERRIDE: &str = "config.prompt_override";
74}
75
76/// Where a prompt block came from.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, schemars::JsonSchema)]
78#[serde(rename_all = "snake_case")]
79#[non_exhaustive]
80pub enum BlockOrigin {
81    /// The engine itself.
82    #[default]
83    Kernel,
84    /// Written by whoever configured this deployment.
85    Config,
86    /// Contributed by an installed plugin, named by its plugin id.
87    Plugin(String),
88    /// Contributed by a script in this project, named by its path.
89    Script(String),
90    /// An entry of a `settings.prompt.append` list the host gave, named as
91    /// the host named it.
92    Host(String),
93    /// An entry of a `settings.prompt.append` list a settings file gave,
94    /// named as the file named it: `{"config": "<name>"}`.
95    #[serde(untagged)]
96    ConfigEntry { config: String },
97}
98
99impl BlockOrigin {
100    /// Used to keep the field out of serialized output in the common case.
101    pub fn is_kernel(&self) -> bool {
102        matches!(self, Self::Kernel)
103    }
104
105    /// Whether this block came from something the user wrote themselves, as
106    /// opposed to something they installed. The distinction trust decisions
107    /// will be made on.
108    pub fn is_local(&self) -> bool {
109        matches!(
110            self,
111            Self::Kernel
112                | Self::Config
113                | Self::ConfigEntry { .. }
114                | Self::Script(_)
115                | Self::Host(_)
116        )
117    }
118}
119
120/// Where a block is delivered. `User` blocks open the conversation, as one
121/// `<system-reminder>` message ahead of everything else, instead of joining
122/// the system prompt: endpoints that cache the prefix in the order system,
123/// tools, messages (DeepSeek) would otherwise re-read the whole tool table
124/// whenever such a block differs, as the skills inventory does between
125/// projects.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
127#[serde(rename_all = "snake_case")]
128pub enum BlockRole {
129    System,
130    User,
131    Assistant,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136pub enum CacheStrategy {
137    Ephemeral,
138    Global,
139}
140
141impl PromptBlock {
142    pub fn system(content: impl Into<String>) -> Self {
143        Self {
144            role: BlockRole::System,
145            content: content.into(),
146            cache_strategy: None,
147            name: None,
148            origin: BlockOrigin::Kernel,
149        }
150    }
151
152    pub fn system_cached(content: impl Into<String>) -> Self {
153        Self {
154            role: BlockRole::System,
155            content: content.into(),
156            cache_strategy: Some(CacheStrategy::Ephemeral),
157            name: None,
158            origin: BlockOrigin::Kernel,
159        }
160    }
161
162    pub fn user(content: impl Into<String>) -> Self {
163        Self {
164            role: BlockRole::User,
165            content: content.into(),
166            cache_strategy: None,
167            name: None,
168            origin: BlockOrigin::Kernel,
169        }
170    }
171
172    pub fn named(mut self, name: impl Into<String>) -> Self {
173        self.name = Some(name.into());
174        self
175    }
176
177    pub fn from_origin(mut self, origin: BlockOrigin) -> Self {
178        self.origin = origin;
179        self
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    /// The names are a contract an extension positions itself against, so a
188    /// rename is a breaking change and has to look like one. This is the test
189    /// that makes it look like one.
190    #[test]
191    fn the_kernel_block_names_are_what_they_are_published_as() {
192        assert_eq!(names::SCENE_SKELETON, "scene.skeleton");
193        assert_eq!(names::SKILLS_CATALOG, "skills.catalog");
194        assert_eq!(names::MEMORY_SESSION, "memory.session");
195        assert_eq!(names::RULES, "rules");
196        assert_eq!(names::MCP_INSTRUCTIONS, "mcp.instructions");
197        assert_eq!(names::CONFIG_PROMPT_APPEND, "config.prompt_append");
198        assert_eq!(names::CONFIG_PROMPT_OVERRIDE, "config.prompt_override");
199        assert_eq!(names::HOST_PREFIX, "host.");
200        assert_eq!(names::CONFIG_PREFIX, "config.");
201    }
202
203    #[test]
204    fn a_settings_file_entry_reads_and_writes_as_config_with_its_name() {
205        let entry = BlockOrigin::ConfigEntry {
206            config: "review".into(),
207        };
208        let json = serde_json::json!({"config": "review"});
209        assert_eq!(serde_json::to_value(&entry).unwrap(), json);
210        assert_eq!(serde_json::from_value::<BlockOrigin>(json).unwrap(), entry);
211        assert_eq!(
212            serde_json::from_value::<BlockOrigin>(serde_json::json!("config")).unwrap(),
213            BlockOrigin::Config
214        );
215        assert_eq!(
216            serde_json::from_value::<BlockOrigin>(serde_json::json!({"host": "a"})).unwrap(),
217            BlockOrigin::Host("a".into())
218        );
219    }
220}