Skip to main content

base/interface/
prompt_registry.rs

1//! `PromptRegistry` — contributing to the system prompt instead of replacing
2//! it.
3//!
4//! Assembly was a function that took a scene and returned a list. Every block
5//! in that list was decided in one place, so an extension wanting to add a
6//! paragraph — or change one line of the skills inventory — had exactly one
7//! move available: reimplement the whole scene. Registration is the other
8//! shape. Contributions arrive from anywhere, each named, ordered and
9//! revocable, and assembly becomes the act of merging them.
10//!
11//! # Ordering, and why it is a number
12//!
13//! Blocks sort by [`RegisteredBlock::order`], ascending, ties broken by
14//! registration order. The kernel's stages sit at round hundreds (see
15//! [`orders`]) so that "just before the skills inventory" and "after
16//! everything" are both expressible without renumbering anything. Negative
17//! orders come before the scene; anything past
18//! [`orders::CONFIG_PROMPT_APPEND`] comes last.
19//!
20//! A named anchor would read better than a number and does not survive
21//! contact with two extensions that both want to be immediately after the
22//! same block. Numbers make that conflict visible and resolvable by whoever
23//! is配置ing the system, rather than by whichever extension registered second.
24//!
25//! # Nothing registered is the identical prompt
26//!
27//! An empty registry assembles exactly what the hardcoded function did, byte
28//! for byte, which is what makes this safe to land before anything registers.
29
30use std::sync::{Arc, Mutex};
31
32use crate::interface::prompt_assembly::{AssemblyHook, Authority};
33use crate::interface::scene::ScenePromptContext;
34use crate::prompt::{BlockOrigin, BlockRole, CacheStrategy};
35use crate::tool::{Disposer, RegistrationId};
36
37/// Produces content at assembly time, from the context the prompt is being
38/// assembled for. `None` contributes nothing — the block is dropped, which is
39/// how a contribution stays out of the prompt in the sessions it has nothing
40/// to say about.
41pub type ContextProvider =
42    Arc<dyn for<'a> Fn(&ScenePromptContext<'a>) -> Option<String> + Send + Sync>;
43
44/// Produces the value `{{name}}` expands to. `None` leaves the placeholder
45/// alone rather than blanking it: a variable that could not be resolved is a
46/// bug to see, not a hole to hide.
47pub type VariableProvider =
48    Arc<dyn for<'a> Fn(&ScenePromptContext<'a>) -> Option<String> + Send + Sync>;
49
50/// Where a block's text comes from.
51#[derive(Clone)]
52pub enum PromptContent {
53    /// Fixed at registration.
54    Static(String),
55    /// Computed per assembly.
56    Provider(ContextProvider),
57}
58
59impl std::fmt::Debug for PromptContent {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        match self {
62            Self::Static(s) => f.debug_tuple("Static").field(s).finish(),
63            Self::Provider(_) => f.write_str("Provider(..)"),
64        }
65    }
66}
67
68/// A contribution to the system prompt.
69#[derive(Clone, Debug)]
70pub struct RegisteredBlock {
71    /// How anything else refers to this block. See
72    /// [`crate::prompt::names`] for the kernel's.
73    pub name: String,
74    pub role: BlockRole,
75    /// Ascending. See the module docs.
76    pub order: i32,
77    pub content: PromptContent,
78    pub cache_strategy: Option<CacheStrategy>,
79    pub origin: BlockOrigin,
80}
81
82impl RegisteredBlock {
83    /// A static system block at `order`, from the kernel.
84    pub fn system(name: impl Into<String>, order: i32, content: impl Into<String>) -> Self {
85        Self {
86            name: name.into(),
87            role: BlockRole::System,
88            order,
89            content: PromptContent::Static(content.into()),
90            cache_strategy: None,
91            origin: BlockOrigin::Kernel,
92        }
93    }
94
95    pub fn with_cache(mut self, strategy: CacheStrategy) -> Self {
96        self.cache_strategy = Some(strategy);
97        self
98    }
99
100    pub fn from_origin(mut self, origin: BlockOrigin) -> Self {
101        self.origin = origin;
102        self
103    }
104}
105
106/// Where the kernel's own stages sit, so a contribution can be placed
107/// relative to them.
108///
109/// Round hundreds, in the order assembly has always used. The gaps are the
110/// point: an extension asking to sit between two kernel stages has ninety-nine
111/// places to do it without anything being renumbered.
112pub mod orders {
113    /// The scene's own blocks, in the order the scene emitted them.
114    pub const SCENE: i32 = 0;
115    pub const SKILLS_CATALOG: i32 = 100;
116    pub const MEMORY_SESSION: i32 = 200;
117    pub const RULES: i32 = 300;
118    pub const MCP_INSTRUCTIONS: i32 = 400;
119    pub const CONFIG_PROMPT_APPEND: i32 = 500;
120}
121
122/// What a host, plugin or script contributes to the prompt.
123pub trait PromptRegistry: Send + Sync {
124    /// Add a block. Dispose to remove it.
125    fn register_block(&self, block: RegisteredBlock) -> Disposer;
126
127    /// Add a block whose text is computed at assembly time.
128    ///
129    /// Sugar for [`register_block`](Self::register_block) with
130    /// [`PromptContent::Provider`] — the same thing, named after what it is
131    /// usually for: context that only exists once the session is running.
132    fn register_context(&self, name: &str, order: i32, provider: ContextProvider) -> Disposer {
133        self.register_block(RegisteredBlock {
134            name: name.to_string(),
135            role: BlockRole::System,
136            order,
137            content: PromptContent::Provider(provider),
138            cache_strategy: None,
139            origin: BlockOrigin::Kernel,
140        })
141    }
142
143    /// Make `{{name}}` expand to whatever `provider` returns, in every block.
144    fn register_variable(&self, name: &str, provider: VariableProvider) -> Disposer;
145
146    /// Add a pass over the whole assembled prompt — see
147    /// [`crate::interface::prompt_assembly`]. `authority` is what that pass
148    /// may do beyond adding, and is the registrar's to establish honestly:
149    /// nothing downstream can tell a plugin apart from a script except by
150    /// what it was registered as.
151    fn register_assembly_hook(&self, hook: Arc<dyn AssemblyHook>, authority: Authority)
152        -> Disposer;
153
154    /// Everything registered, in registration order. Assembly sorts.
155    fn blocks(&self) -> Vec<RegisteredBlock>;
156
157    /// Every registered variable, by name.
158    fn variables(&self) -> Vec<(String, VariableProvider)>;
159
160    /// Every registered pass, in the order they run.
161    fn assembly_hooks(&self) -> Vec<(Arc<dyn AssemblyHook>, Authority)> {
162        Vec::new()
163    }
164
165    /// Add a pass that has to await something — a script carrier, most of
166    /// all. Kept separate from [`register_assembly_hook`](Self::register_assembly_hook)
167    /// so a Rust hook that only rearranges strings is not an async function
168    /// for the sake of the one backend that has to be.
169    fn register_async_assembly_hook(
170        &self,
171        _hook: Arc<dyn crate::interface::prompt_assembly::AsyncAssemblyHook>,
172        _authority: Authority,
173    ) -> Disposer {
174        Disposer::inert(RegistrationId::next())
175    }
176
177    /// Every registered async pass, in the order they run.
178    fn async_assembly_hooks(
179        &self,
180    ) -> Vec<(
181        Arc<dyn crate::interface::prompt_assembly::AsyncAssemblyHook>,
182        Authority,
183    )> {
184        Vec::new()
185    }
186}
187
188/// One registered assembly pass and the authority it runs under.
189type HookEntry = (RegistrationId, Arc<dyn AssemblyHook>, Authority);
190
191/// The same, for a pass that has to await something.
192type AsyncHookEntry = (
193    RegistrationId,
194    Arc<dyn crate::interface::prompt_assembly::AsyncAssemblyHook>,
195    Authority,
196);
197
198/// A registry nothing has registered with, and nothing can.
199///
200/// The default: what assembly uses when the host supplied no registry, and
201/// therefore the implementation that has to make "nothing registered assembles
202/// the identical prompt" true by construction rather than by luck.
203pub struct NoRegistrations;
204
205impl PromptRegistry for NoRegistrations {
206    fn register_block(&self, _block: RegisteredBlock) -> Disposer {
207        Disposer::inert(RegistrationId::next())
208    }
209
210    fn register_variable(&self, _name: &str, _provider: VariableProvider) -> Disposer {
211        Disposer::inert(RegistrationId::next())
212    }
213
214    fn register_assembly_hook(
215        &self,
216        _hook: Arc<dyn AssemblyHook>,
217        _authority: Authority,
218    ) -> Disposer {
219        Disposer::inert(RegistrationId::next())
220    }
221
222    fn blocks(&self) -> Vec<RegisteredBlock> {
223        Vec::new()
224    }
225
226    fn variables(&self) -> Vec<(String, VariableProvider)> {
227        Vec::new()
228    }
229}
230
231/// Holds registrations in memory for the life of a session.
232#[derive(Default)]
233pub struct InMemoryPromptRegistry {
234    // `Arc`-shared with every disposer this hands out, so a disposer stays
235    // valid — and inert rather than dangling — after the registry itself is
236    // dropped.
237    blocks: Arc<Mutex<Vec<(RegistrationId, RegisteredBlock)>>>,
238    variables: Arc<Mutex<Vec<(RegistrationId, String, VariableProvider)>>>,
239    hooks: Arc<Mutex<Vec<HookEntry>>>,
240    async_hooks: Arc<Mutex<Vec<AsyncHookEntry>>>,
241}
242
243impl InMemoryPromptRegistry {
244    pub fn new() -> Arc<Self> {
245        Arc::new(Self::default())
246    }
247}
248
249impl PromptRegistry for InMemoryPromptRegistry {
250    fn register_block(&self, block: RegisteredBlock) -> Disposer {
251        let id = RegistrationId::next();
252        self.blocks
253            .lock()
254            .unwrap_or_else(|e| e.into_inner())
255            .push((id, block));
256        let blocks = self.blocks.clone();
257        Disposer::new(id, move |id| {
258            blocks
259                .lock()
260                .unwrap_or_else(|e| e.into_inner())
261                .retain(|(entry, _)| *entry != id);
262        })
263    }
264
265    fn register_variable(&self, name: &str, provider: VariableProvider) -> Disposer {
266        let id = RegistrationId::next();
267        self.variables
268            .lock()
269            .unwrap_or_else(|e| e.into_inner())
270            .push((id, name.to_string(), provider));
271        let variables = self.variables.clone();
272        Disposer::new(id, move |id| {
273            variables
274                .lock()
275                .unwrap_or_else(|e| e.into_inner())
276                .retain(|(entry, _, _)| *entry != id);
277        })
278    }
279
280    fn register_assembly_hook(
281        &self,
282        hook: Arc<dyn AssemblyHook>,
283        authority: Authority,
284    ) -> Disposer {
285        let id = RegistrationId::next();
286        self.hooks
287            .lock()
288            .unwrap_or_else(|e| e.into_inner())
289            .push((id, hook, authority));
290        let hooks = self.hooks.clone();
291        Disposer::new(id, move |id| {
292            hooks
293                .lock()
294                .unwrap_or_else(|e| e.into_inner())
295                .retain(|(entry, _, _)| *entry != id);
296        })
297    }
298
299    fn blocks(&self) -> Vec<RegisteredBlock> {
300        self.blocks
301            .lock()
302            .unwrap_or_else(|e| e.into_inner())
303            .iter()
304            .map(|(_, b)| b.clone())
305            .collect()
306    }
307
308    fn assembly_hooks(&self) -> Vec<(Arc<dyn AssemblyHook>, Authority)> {
309        self.hooks
310            .lock()
311            .unwrap_or_else(|e| e.into_inner())
312            .iter()
313            .map(|(_, h, a)| (h.clone(), a.clone()))
314            .collect()
315    }
316
317    fn register_async_assembly_hook(
318        &self,
319        hook: Arc<dyn crate::interface::prompt_assembly::AsyncAssemblyHook>,
320        authority: Authority,
321    ) -> Disposer {
322        let id = RegistrationId::next();
323        self.async_hooks
324            .lock()
325            .unwrap_or_else(|e| e.into_inner())
326            .push((id, hook, authority));
327        let hooks = self.async_hooks.clone();
328        Disposer::new(id, move |id| {
329            hooks
330                .lock()
331                .unwrap_or_else(|e| e.into_inner())
332                .retain(|(entry, _, _)| *entry != id);
333        })
334    }
335
336    fn async_assembly_hooks(
337        &self,
338    ) -> Vec<(
339        Arc<dyn crate::interface::prompt_assembly::AsyncAssemblyHook>,
340        Authority,
341    )> {
342        self.async_hooks
343            .lock()
344            .unwrap_or_else(|e| e.into_inner())
345            .iter()
346            .map(|(_, h, a)| (h.clone(), a.clone()))
347            .collect()
348    }
349
350    fn variables(&self) -> Vec<(String, VariableProvider)> {
351        self.variables
352            .lock()
353            .unwrap_or_else(|e| e.into_inner())
354            .iter()
355            .map(|(_, n, p)| (n.clone(), p.clone()))
356            .collect()
357    }
358}
359
360/// Expand `{{name}}` for every registered variable.
361///
362/// Deliberately not a template language. An unregistered placeholder is left
363/// exactly as written — a prompt that contains `{{` for its own reasons must
364/// come out unchanged, and a variable that failed to resolve should be visible
365/// rather than silently blank.
366/// What the QuickJS layer contributes to the prompt, fixed when the session
367/// is built.
368#[derive(Default)]
369pub struct ScriptContributions {
370    pub blocks: Vec<RegisteredBlock>,
371    pub variables: Vec<(String, VariableProvider, BlockOrigin)>,
372    pub assembly_hooks: Vec<(Arc<dyn AssemblyHook>, Authority)>,
373    pub async_assembly_hooks: Vec<(
374        Arc<dyn crate::interface::prompt_assembly::AsyncAssemblyHook>,
375        Authority,
376    )>,
377}
378
379/// The Rust registrations with the QuickJS ones above them.
380///
381/// A name both layers claim goes to the script when the script's origin is
382/// local; a packaged script may only add, so its claim on a name a Rust
383/// registration holds is dropped. Assembly passes run Rust first. New
384/// registrations land in the Rust layer.
385pub struct LayeredPromptRegistry {
386    native: Vec<Arc<dyn PromptRegistry>>,
387    top: Arc<dyn PromptRegistry>,
388    script: ScriptContributions,
389}
390
391impl LayeredPromptRegistry {
392    /// The Rust layer is `host`, when there is one, read before `own`, which
393    /// is where registrations made through this registry go.
394    pub fn new(
395        host: Option<Arc<dyn PromptRegistry>>,
396        own: Arc<dyn PromptRegistry>,
397        script: ScriptContributions,
398    ) -> Self {
399        let native = host.into_iter().chain([own.clone()]).collect();
400        Self {
401            native,
402            top: own,
403            script,
404        }
405    }
406
407    fn top(&self) -> &Arc<dyn PromptRegistry> {
408        &self.top
409    }
410}
411
412impl PromptRegistry for LayeredPromptRegistry {
413    fn register_block(&self, block: RegisteredBlock) -> Disposer {
414        self.top().register_block(block)
415    }
416
417    fn register_variable(&self, name: &str, provider: VariableProvider) -> Disposer {
418        self.top().register_variable(name, provider)
419    }
420
421    fn register_assembly_hook(
422        &self,
423        hook: Arc<dyn AssemblyHook>,
424        authority: Authority,
425    ) -> Disposer {
426        self.top().register_assembly_hook(hook, authority)
427    }
428
429    fn register_async_assembly_hook(
430        &self,
431        hook: Arc<dyn crate::interface::prompt_assembly::AsyncAssemblyHook>,
432        authority: Authority,
433    ) -> Disposer {
434        self.top().register_async_assembly_hook(hook, authority)
435    }
436
437    fn blocks(&self) -> Vec<RegisteredBlock> {
438        let native: Vec<RegisteredBlock> = self.native.iter().flat_map(|r| r.blocks()).collect();
439        let taken_by_script: std::collections::HashSet<&str> = self
440            .script
441            .blocks
442            .iter()
443            .filter(|b| b.origin.is_local())
444            .map(|b| b.name.as_str())
445            .collect();
446        let native_names: std::collections::HashSet<String> =
447            native.iter().map(|b| b.name.clone()).collect();
448        let mut out: Vec<RegisteredBlock> = native
449            .into_iter()
450            .filter(|b| !taken_by_script.contains(b.name.as_str()))
451            .collect();
452        for block in &self.script.blocks {
453            if !block.origin.is_local() && native_names.contains(&block.name) {
454                tracing::warn!(
455                    block = %block.name,
456                    origin = ?block.origin,
457                    "a packaged script may only add to the prompt; a Rust plugin already \
458                     registers this block name, so the script's block is dropped"
459                );
460                continue;
461            }
462            out.push(block.clone());
463        }
464        out
465    }
466
467    fn variables(&self) -> Vec<(String, VariableProvider)> {
468        // `interpolate` takes the first provider for a name, so order is precedence.
469        let native: Vec<(String, VariableProvider)> =
470            self.native.iter().flat_map(|r| r.variables()).collect();
471        let mut out: Vec<(String, VariableProvider)> = self
472            .script
473            .variables
474            .iter()
475            .filter(|(_, _, origin)| origin.is_local())
476            .map(|(n, p, _)| (n.clone(), p.clone()))
477            .collect();
478        for (name, provider, origin) in &self.script.variables {
479            if origin.is_local() {
480                continue;
481            }
482            if native.iter().any(|(n, _)| n == name) {
483                tracing::warn!(
484                    variable = %name,
485                    origin = ?origin,
486                    "a packaged script may only add to the prompt; a Rust plugin already \
487                     provides this variable, so the script's is dropped"
488                );
489                continue;
490            }
491            out.push((name.clone(), provider.clone()));
492        }
493        out.extend(native);
494        out
495    }
496
497    fn assembly_hooks(&self) -> Vec<(Arc<dyn AssemblyHook>, Authority)> {
498        let mut out: Vec<_> = self
499            .native
500            .iter()
501            .flat_map(|r| r.assembly_hooks())
502            .collect();
503        out.extend(self.script.assembly_hooks.iter().cloned());
504        out
505    }
506
507    fn async_assembly_hooks(
508        &self,
509    ) -> Vec<(
510        Arc<dyn crate::interface::prompt_assembly::AsyncAssemblyHook>,
511        Authority,
512    )> {
513        let mut out: Vec<_> = self
514            .native
515            .iter()
516            .flat_map(|r| r.async_assembly_hooks())
517            .collect();
518        out.extend(self.script.async_assembly_hooks.iter().cloned());
519        out
520    }
521}
522
523pub fn interpolate(
524    text: &str,
525    variables: &[(String, VariableProvider)],
526    ctx: &ScenePromptContext<'_>,
527) -> String {
528    if variables.is_empty() || !text.contains("{{") {
529        return text.to_string();
530    }
531    let mut out = text.to_string();
532    for (name, provider) in variables {
533        let placeholder = format!("{{{{{name}}}}}");
534        if !out.contains(&placeholder) {
535            continue;
536        }
537        if let Some(value) = provider(ctx) {
538            out = out.replace(&placeholder, &value);
539        }
540    }
541    out
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547
548    fn ctx() -> ScenePromptContext<'static> {
549        use std::borrow::Cow;
550        ScenePromptContext {
551            cwd: Cow::Borrowed("/tmp"),
552            os: Cow::Borrowed("linux"),
553            shell: Cow::Borrowed("bash"),
554            home_dir: Cow::Borrowed("/home/user"),
555            date: Cow::Borrowed("2026-06-10"),
556            model_name: Cow::Borrowed("test-model"),
557            skills_text: None,
558            mcp_instructions: None,
559            session_memory: None,
560            is_git: false,
561            git_branch: None,
562            is_worktree: false,
563            git_status: None,
564            language: None,
565            scratchpad_dir: None,
566            output_style_content: None,
567            available_tools: None,
568            tool_results_ever_cleared: false,
569            attended: false,
570            layout: Default::default(),
571        }
572    }
573
574    #[test]
575    fn disposing_a_registration_takes_it_back_out() {
576        let registry = InMemoryPromptRegistry::new();
577        let disposer = registry.register_block(RegisteredBlock::system("mine", 50, "hello"));
578        assert_eq!(registry.blocks().len(), 1);
579        disposer.dispose();
580        assert!(
581            registry.blocks().is_empty(),
582            "a contribution that cannot be withdrawn is a permanent edit"
583        );
584    }
585
586    #[test]
587    fn a_disposer_outliving_its_registry_is_inert_rather_than_dangling() {
588        let registry = InMemoryPromptRegistry::new();
589        let disposer = registry.register_block(RegisteredBlock::system("mine", 50, "hello"));
590        drop(registry);
591        disposer.dispose();
592    }
593
594    #[test]
595    fn an_unregistered_placeholder_survives_untouched() {
596        let vars: Vec<(String, VariableProvider)> = vec![(
597            "known".into(),
598            Arc::new(|_: &ScenePromptContext<'_>| Some("resolved".to_string())),
599        )];
600        assert_eq!(
601            interpolate("{{known}} and {{unknown}}", &vars, &ctx()),
602            "resolved and {{unknown}}",
603            "a placeholder nobody registered is text, not a hole"
604        );
605    }
606
607    #[test]
608    fn a_variable_that_declines_leaves_its_placeholder_alone() {
609        let vars: Vec<(String, VariableProvider)> =
610            vec![("maybe".into(), Arc::new(|_: &ScenePromptContext<'_>| None))];
611        assert_eq!(interpolate("a {{maybe}} b", &vars, &ctx()), "a {{maybe}} b");
612    }
613
614    #[test]
615    fn nothing_registered_means_nothing_to_interpolate() {
616        assert_eq!(interpolate("{{anything}}", &[], &ctx()), "{{anything}}");
617    }
618
619    fn layered(script: ScriptContributions) -> LayeredPromptRegistry {
620        let native = InMemoryPromptRegistry::new();
621        native.register_block(RegisteredBlock::system("shared", 10, "NATIVE"));
622        native.register_variable(
623            "who",
624            Arc::new(|_: &ScenePromptContext<'_>| Some("native".into())),
625        );
626        LayeredPromptRegistry::new(None, native, script)
627    }
628
629    fn texts(r: &LayeredPromptRegistry) -> Vec<String> {
630        r.blocks()
631            .into_iter()
632            .map(|b| match b.content {
633                PromptContent::Static(s) => s,
634                PromptContent::Provider(_) => String::new(),
635            })
636            .collect()
637    }
638
639    fn who(r: &LayeredPromptRegistry) -> String {
640        interpolate("{{who}}", &r.variables(), &ctx())
641    }
642
643    #[test]
644    fn a_local_script_takes_a_name_the_rust_layer_also_holds() {
645        let r = layered(ScriptContributions {
646            blocks: vec![RegisteredBlock::system("shared", 10, "SCRIPT")
647                .from_origin(BlockOrigin::Script("a.js".into()))],
648            variables: vec![(
649                "who".into(),
650                Arc::new(|_: &ScenePromptContext<'_>| Some("script".into())),
651                BlockOrigin::Script("a.js".into()),
652            )],
653            assembly_hooks: Vec::new(),
654            async_assembly_hooks: Vec::new(),
655        });
656        assert_eq!(texts(&r), ["SCRIPT"]);
657        assert_eq!(who(&r), "script");
658    }
659
660    #[test]
661    fn a_packaged_script_only_adds() {
662        let r = layered(ScriptContributions {
663            blocks: vec![
664                RegisteredBlock::system("shared", 10, "PACKAGED")
665                    .from_origin(BlockOrigin::Plugin("pkg".into())),
666                RegisteredBlock::system("its.own", 20, "ADDED")
667                    .from_origin(BlockOrigin::Plugin("pkg".into())),
668            ],
669            variables: vec![(
670                "who".into(),
671                Arc::new(|_: &ScenePromptContext<'_>| Some("packaged".into())),
672                BlockOrigin::Plugin("pkg".into()),
673            )],
674            assembly_hooks: Vec::new(),
675            async_assembly_hooks: Vec::new(),
676        });
677        assert_eq!(texts(&r), ["NATIVE", "ADDED"]);
678        assert_eq!(who(&r), "native");
679    }
680
681    #[test]
682    fn registering_through_the_layers_lands_in_the_rust_layer() {
683        let r = layered(ScriptContributions::default());
684        r.register_block(RegisteredBlock::system("later", 30, "LATER"));
685        assert_eq!(texts(&r), ["NATIVE", "LATER"]);
686    }
687}