Skip to main content

base/interface/
prompt_assembly.rs

1//! The assembly hook point: a last pass over the whole prompt, with authority
2//! that depends on where the pass came from.
3//!
4//! Registration ([`crate::interface::prompt_registry`]) covers contributing.
5//! It does not cover *editing* — reading what everything else produced and
6//! changing it. Some of what an extension legitimately wants is only
7//! expressible that way: strip a section that does not apply to this
8//! deployment, rewrite a paragraph the model keeps misreading, move a block
9//! the cache would rather see earlier.
10//!
11//! # Editing a prompt is not the same act as adding to one
12//!
13//! Adding is bounded: whatever a contribution says, everything else still
14//! says what it said. Removal and rewriting are not — a block that silently
15//! deletes `rules` turns off a safety mechanism its author never agreed to
16//! turn off, and the result looks exactly like a system that has no rules
17//! configured.
18//!
19//! So authority follows provenance. Something the operator wrote themselves —
20//! a script in their project, their own configuration — may do anything they
21//! could have done by editing the prompt by hand, because it *is* them. A
22//! plugin they downloaded may add, and may do more only if it declared the
23//! capability, which is what an install-time disclosure has to show them.
24//!
25//! # A refusal is visible, not silent
26//!
27//! A denied edit returns [`Denied`] and is counted on the assembly. A hook
28//! that ignores the error still cannot make the change, and the count is what
29//! lets a host tell "this plugin does nothing" apart from "this plugin is
30//! being stopped from doing something".
31
32use std::sync::Arc;
33
34use crate::interface::scene::ScenePromptContext;
35use crate::prompt::{BlockOrigin, PromptBlock};
36
37/// What a hook is allowed to do beyond adding.
38///
39/// Every field defaults to off. A plugin that declares nothing gets the
40/// smallest authority that is still useful, which is the only default that is
41/// safe to apply to code the operator did not read.
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub struct AssemblyCapabilities {
44    /// Rewrite an existing block's content.
45    pub modify: bool,
46    /// Take an existing block out.
47    pub remove: bool,
48    /// Move blocks relative to one another.
49    pub reorder: bool,
50}
51
52impl AssemblyCapabilities {
53    /// Everything. What an operator's own script gets.
54    pub fn all() -> Self {
55        Self {
56            modify: true,
57            remove: true,
58            reorder: true,
59        }
60    }
61}
62
63/// Who a hook is, and what it may therefore do.
64#[derive(Debug, Clone)]
65pub struct Authority {
66    pub origin: BlockOrigin,
67    pub capabilities: AssemblyCapabilities,
68}
69
70impl Authority {
71    /// A hook from something the operator wrote or configured. Unrestricted:
72    /// it can do what they could have done by hand, because it is them.
73    pub fn local(origin: BlockOrigin) -> Self {
74        debug_assert!(
75            origin.is_local(),
76            "local authority is for kernel, config and project scripts"
77        );
78        Self {
79            origin,
80            capabilities: AssemblyCapabilities::all(),
81        }
82    }
83
84    /// A hook from an installed plugin, with whatever it declared at install
85    /// time and nothing more.
86    pub fn plugin(name: impl Into<String>, capabilities: AssemblyCapabilities) -> Self {
87        Self {
88            origin: BlockOrigin::Plugin(name.into()),
89            capabilities,
90        }
91    }
92
93    fn may(&self, want: Capability) -> bool {
94        // Provenance first: something the operator wrote needs to declare
95        // nothing, because there is nobody for it to declare to.
96        if self.origin.is_local() {
97            return true;
98        }
99        match want {
100            Capability::Modify => self.capabilities.modify,
101            Capability::Remove => self.capabilities.remove,
102            Capability::Reorder => self.capabilities.reorder,
103        }
104    }
105
106    pub(crate) fn describe(&self) -> String {
107        match &self.origin {
108            BlockOrigin::Plugin(name) => format!("plugin '{name}'"),
109            BlockOrigin::Script(path) => format!("script '{path}'"),
110            BlockOrigin::Host(name) => format!("host block '{name}'"),
111            BlockOrigin::ConfigEntry { config } => format!("configuration block '{config}'"),
112            BlockOrigin::Config => "configuration".to_string(),
113            BlockOrigin::Kernel => "the engine".to_string(),
114        }
115    }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119enum Capability {
120    Modify,
121    Remove,
122    Reorder,
123}
124
125impl Capability {
126    fn name(self) -> &'static str {
127        match self {
128            Self::Modify => "modify",
129            Self::Remove => "remove",
130            Self::Reorder => "reorder",
131        }
132    }
133}
134
135/// An edit that was not permitted.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Denied {
138    /// What was attempted, in the words a disclosure would use.
139    pub capability: &'static str,
140    /// The block it was attempted on.
141    pub block: String,
142    /// Who attempted it.
143    pub by: String,
144}
145
146impl std::fmt::Display for Denied {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        write!(
149            f,
150            "{} may not {} the prompt block '{}': it did not declare that capability at install",
151            self.by, self.capability, self.block
152        )
153    }
154}
155
156/// The prompt, mid-assembly, as one hook is allowed to see and change it.
157pub struct PromptAssembly {
158    blocks: Vec<PromptBlock>,
159    authority: Authority,
160    refusals: Vec<Denied>,
161}
162
163impl PromptAssembly {
164    pub fn new(blocks: Vec<PromptBlock>, authority: Authority) -> Self {
165        Self {
166            blocks,
167            authority,
168            refusals: Vec::new(),
169        }
170    }
171
172    pub fn blocks(&self) -> &[PromptBlock] {
173        &self.blocks
174    }
175
176    /// Every edit this hook was not allowed to make.
177    pub fn refusals(&self) -> &[Denied] {
178        &self.refusals
179    }
180
181    pub fn into_blocks(self) -> Vec<PromptBlock> {
182        self.blocks
183    }
184
185    /// Position of the block named `name`, if it is present.
186    pub fn position(&self, name: &str) -> Option<usize> {
187        self.blocks
188            .iter()
189            .position(|b| b.name.as_deref() == Some(name))
190    }
191
192    /// Add a block at the end. Always permitted — adding cannot unsay
193    /// anything that was already said.
194    pub fn push(&mut self, block: PromptBlock) {
195        self.blocks.push(block);
196    }
197
198    /// Add a block directly after `name`, or at the end if there is no such
199    /// block. Always permitted, for the same reason as [`push`](Self::push):
200    /// nothing that was there stops being there.
201    pub fn insert_after(&mut self, name: &str, block: PromptBlock) {
202        match self.position(name) {
203            Some(i) => self.blocks.insert(i + 1, block),
204            None => self.blocks.push(block),
205        }
206    }
207
208    /// Rewrite a block's content. Requires `modify`.
209    ///
210    /// `Ok(false)` means there was no such block — a hook targeting something
211    /// optional should not have to care whether this session has it.
212    pub fn modify(&mut self, name: &str, content: String) -> Result<bool, Denied> {
213        self.guard(Capability::Modify, name)?;
214        match self.position(name) {
215            Some(i) => {
216                self.blocks[i].content = content;
217                Ok(true)
218            }
219            None => Ok(false),
220        }
221    }
222
223    /// Take a block out. Requires `remove`.
224    pub fn remove(&mut self, name: &str) -> Result<bool, Denied> {
225        self.guard(Capability::Remove, name)?;
226        match self.position(name) {
227            Some(i) => {
228                self.blocks.remove(i);
229                Ok(true)
230            }
231            None => Ok(false),
232        }
233    }
234
235    /// Move a block so it sits directly before `before`. Requires `reorder`.
236    pub fn move_before(&mut self, name: &str, before: &str) -> Result<bool, Denied> {
237        self.guard(Capability::Reorder, name)?;
238        let (Some(from), Some(_)) = (self.position(name), self.position(before)) else {
239            return Ok(false);
240        };
241        let block = self.blocks.remove(from);
242        // Recomputed after the removal: taking the block out shifts anything
243        // that was behind it, so the index read before would be off by one.
244        let to = self.position(before).unwrap_or(self.blocks.len());
245        self.blocks.insert(to, block);
246        Ok(true)
247    }
248
249    fn guard(&mut self, want: Capability, block: &str) -> Result<(), Denied> {
250        if self.authority.may(want) {
251            return Ok(());
252        }
253        let denied = Denied {
254            capability: want.name(),
255            block: block.to_string(),
256            by: self.authority.describe(),
257        };
258        tracing::warn!(%denied, "a prompt assembly edit was refused");
259        self.refusals.push(denied.clone());
260        Err(denied)
261    }
262}
263
264/// A pass over the assembled prompt.
265///
266/// Waterfall: hooks run in registration order and each sees what the previous
267/// one left. An error stops that hook, not the assembly — a broken extension
268/// must not be able to take a session down with it, and the prompt without its
269/// edits is still a prompt.
270pub trait AssemblyHook: Send + Sync {
271    fn on_assemble(
272        &self,
273        assembly: &mut PromptAssembly,
274        ctx: &ScenePromptContext<'_>,
275    ) -> Result<(), String>;
276}
277
278/// A pass over the assembled prompt that has to await something.
279///
280/// The synchronous [`AssemblyHook`] is the common case and stays
281/// synchronous — a Rust hook that only rearranges strings should not be an
282/// async function for the sake of the one backend that needs to be. This is
283/// the variant a script carrier implements, since running the operator's code
284/// means awaiting an engine.
285#[async_trait::async_trait]
286pub trait AsyncAssemblyHook: Send + Sync {
287    async fn on_assemble_async(
288        &self,
289        assembly: &mut PromptAssembly,
290        ctx: &ScenePromptContext<'_>,
291    ) -> Result<(), String>;
292}
293
294/// Run every async hook over `blocks`, each under its own authority.
295///
296/// Separate from [`run_assembly_hooks`] rather than replacing it: prompt
297/// assembly is a synchronous function called from the turn, and making the
298/// whole of it async to accommodate a backend nobody has configured would put
299/// an await point in every session's hot path to serve none of them.
300pub async fn run_async_assembly_hooks(
301    blocks: Vec<PromptBlock>,
302    hooks: &[(Arc<dyn AsyncAssemblyHook>, Authority)],
303    ctx: &ScenePromptContext<'_>,
304) -> Vec<PromptBlock> {
305    let mut blocks = blocks;
306    for (hook, authority) in hooks {
307        let mut assembly = PromptAssembly::new(blocks, authority.clone());
308        if let Err(e) = hook.on_assemble_async(&mut assembly, ctx).await {
309            tracing::warn!(
310                by = %authority.describe(),
311                error = %e,
312                "an async prompt assembly hook failed; its edits up to that point stand"
313            );
314        }
315        blocks = assembly.into_blocks();
316    }
317    blocks
318}
319
320/// Run every hook over `blocks`, each under its own authority.
321pub fn run_assembly_hooks(
322    blocks: Vec<PromptBlock>,
323    hooks: &[(Arc<dyn AssemblyHook>, Authority)],
324    ctx: &ScenePromptContext<'_>,
325) -> Vec<PromptBlock> {
326    let mut blocks = blocks;
327    for (hook, authority) in hooks {
328        let mut assembly = PromptAssembly::new(blocks, authority.clone());
329        if let Err(e) = hook.on_assemble(&mut assembly, ctx) {
330            tracing::warn!(
331                by = %authority.describe(),
332                error = %e,
333                "a prompt assembly hook failed; its edits up to that point stand"
334            );
335        }
336        blocks = assembly.into_blocks();
337    }
338    blocks
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344    use crate::prompt::names;
345
346    fn prompt() -> Vec<PromptBlock> {
347        vec![
348            PromptBlock::system("you are an agent").named(names::SCENE_SKELETON),
349            PromptBlock::system("skills: a, b").named(names::SKILLS_CATALOG),
350            PromptBlock::system("rules: no rm -rf").named(names::RULES),
351        ]
352    }
353
354    fn tests_ctx() -> ScenePromptContext<'static> {
355        use std::borrow::Cow;
356        ScenePromptContext {
357            cwd: Cow::Borrowed("/tmp"),
358            os: Cow::Borrowed("linux"),
359            shell: Cow::Borrowed("bash"),
360            home_dir: Cow::Borrowed("/home/user"),
361            date: Cow::Borrowed("2026-06-10"),
362            model_name: Cow::Borrowed("test-model"),
363            skills_text: None,
364            mcp_instructions: None,
365            session_memory: None,
366            is_git: false,
367            git_branch: None,
368            is_worktree: false,
369            git_status: None,
370            language: None,
371            scratchpad_dir: None,
372            output_style_content: None,
373            available_tools: None,
374            tool_results_ever_cleared: false,
375            attended: false,
376            layout: Default::default(),
377        }
378    }
379
380    fn downloaded(caps: AssemblyCapabilities) -> Authority {
381        Authority::plugin("example", caps)
382    }
383
384    fn own_script() -> Authority {
385        Authority::local(BlockOrigin::Script("./.agix/scripts/prompt.js".into()))
386    }
387
388    /// The acceptance property: something downloaded, declaring nothing,
389    /// cannot delete a kernel block.
390    #[test]
391    fn a_downloaded_extension_that_declared_nothing_cannot_remove_a_kernel_block() {
392        let mut asm = PromptAssembly::new(prompt(), downloaded(AssemblyCapabilities::default()));
393
394        let refused = asm.remove(names::RULES).unwrap_err();
395        assert_eq!(refused.capability, "remove");
396        assert_eq!(refused.block, names::RULES);
397        assert!(refused.by.contains("example"), "{refused}");
398
399        assert!(
400            asm.position(names::RULES).is_some(),
401            "the block must still be there — a refused edit that half-applies is worse than none"
402        );
403        assert_eq!(asm.refusals().len(), 1, "a refusal must be visible");
404    }
405
406    #[test]
407    fn a_downloaded_extension_may_always_add() {
408        let mut asm = PromptAssembly::new(prompt(), downloaded(AssemblyCapabilities::default()));
409        asm.insert_after(
410            names::SCENE_SKELETON,
411            PromptBlock::system("also this").named("example.note"),
412        );
413        assert_eq!(asm.position("example.note"), Some(1));
414        assert!(
415            asm.refusals().is_empty(),
416            "adding needs no capability: it cannot unsay anything"
417        );
418    }
419
420    #[test]
421    fn a_declared_capability_is_the_one_that_is_granted_and_no_other() {
422        let caps = AssemblyCapabilities {
423            modify: true,
424            ..Default::default()
425        };
426        let mut asm = PromptAssembly::new(prompt(), downloaded(caps));
427
428        assert_eq!(
429            asm.modify(names::SKILLS_CATALOG, "skills: a".into()),
430            Ok(true)
431        );
432        assert!(asm.remove(names::RULES).is_err(), "remove was not declared");
433        assert!(
434            asm.move_before(names::RULES, names::SCENE_SKELETON)
435                .is_err(),
436            "reorder was not declared"
437        );
438    }
439
440    #[test]
441    fn a_script_the_operator_wrote_may_rewrite_anything() {
442        let mut asm = PromptAssembly::new(prompt(), own_script());
443        assert_eq!(
444            asm.modify(names::RULES, "rules: rewritten".into()),
445            Ok(true)
446        );
447        assert_eq!(asm.remove(names::SKILLS_CATALOG), Ok(true));
448        assert_eq!(
449            asm.move_before(names::RULES, names::SCENE_SKELETON),
450            Ok(true)
451        );
452        let names: Vec<&str> = asm
453            .blocks()
454            .iter()
455            .filter_map(|b| b.name.as_deref())
456            .collect();
457        assert_eq!(names, [names::RULES, names::SCENE_SKELETON]);
458        assert!(asm.refusals().is_empty());
459    }
460
461    #[test]
462    fn editing_a_block_that_is_not_there_is_not_an_error() {
463        let mut asm = PromptAssembly::new(prompt(), own_script());
464        assert_eq!(asm.modify("mcp.instructions", "x".into()), Ok(false));
465        assert_eq!(asm.remove("mcp.instructions"), Ok(false));
466    }
467
468    /// Waterfall, and containment: the second hook sees the first hook's
469    /// result, and a hook that fails does not take the assembly with it.
470    #[test]
471    fn hooks_see_each_others_work_and_a_failure_is_contained() {
472        struct Appends(&'static str);
473        impl AssemblyHook for Appends {
474            fn on_assemble(
475                &self,
476                asm: &mut PromptAssembly,
477                _ctx: &ScenePromptContext<'_>,
478            ) -> Result<(), String> {
479                asm.push(PromptBlock::system("x").named(self.0));
480                Ok(())
481            }
482        }
483        struct AppendsThenFails;
484        impl AssemblyHook for AppendsThenFails {
485            fn on_assemble(
486                &self,
487                asm: &mut PromptAssembly,
488                _ctx: &ScenePromptContext<'_>,
489            ) -> Result<(), String> {
490                asm.push(PromptBlock::system("y").named("second.partial"));
491                Err("gave up halfway".into())
492            }
493        }
494
495        let hooks: Vec<(Arc<dyn AssemblyHook>, Authority)> = vec![
496            (Arc::new(Appends("first")), own_script()),
497            (Arc::new(AppendsThenFails), own_script()),
498            (Arc::new(Appends("third")), own_script()),
499        ];
500        let out = run_assembly_hooks(prompt(), &hooks, &tests_ctx());
501        let names: Vec<&str> = out.iter().filter_map(|b| b.name.as_deref()).collect();
502        assert_eq!(
503            &names[3..],
504            ["first", "second.partial", "third"],
505            "each hook builds on the last, and the one that failed still ran"
506        );
507    }
508}