1use std::sync::Arc;
33
34use crate::interface::scene::ScenePromptContext;
35use crate::prompt::{BlockOrigin, PromptBlock};
36
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub struct AssemblyCapabilities {
44 pub modify: bool,
46 pub remove: bool,
48 pub reorder: bool,
50}
51
52impl AssemblyCapabilities {
53 pub fn all() -> Self {
55 Self {
56 modify: true,
57 remove: true,
58 reorder: true,
59 }
60 }
61}
62
63#[derive(Debug, Clone)]
65pub struct Authority {
66 pub origin: BlockOrigin,
67 pub capabilities: AssemblyCapabilities,
68}
69
70impl Authority {
71 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Denied {
138 pub capability: &'static str,
140 pub block: String,
142 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
156pub 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 pub fn refusals(&self) -> &[Denied] {
178 &self.refusals
179 }
180
181 pub fn into_blocks(self) -> Vec<PromptBlock> {
182 self.blocks
183 }
184
185 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 pub fn push(&mut self, block: PromptBlock) {
195 self.blocks.push(block);
196 }
197
198 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 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 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 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 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
264pub trait AssemblyHook: Send + Sync {
271 fn on_assemble(
272 &self,
273 assembly: &mut PromptAssembly,
274 ctx: &ScenePromptContext<'_>,
275 ) -> Result<(), String>;
276}
277
278#[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
294pub 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
320pub 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 #[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 #[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}