Skip to main content

base/interface/
scene.rs

1//! `SceneSpec` — what a scene is: its identity, tool and module surface,
2//! budgets and per-turn reminders, as data, plus the one behavior a scene
3//! supplies itself, its prompt ([`ScenePrompt`]). Bound at session creation
4//! and immutable thereafter.
5
6use crate::context::config::PathStyle;
7use crate::interface::tool::{Tool, ToolOrigin};
8use crate::interface::tool_selector::{ToolPattern, ToolSelector};
9use crate::prompt::PromptBlock;
10use serde::Deserialize;
11use std::borrow::Cow;
12use std::sync::Arc;
13
14/// Context passed to [`ScenePrompt`].
15#[derive(Debug, Clone, Default)]
16#[non_exhaustive]
17pub struct ScenePromptContext<'a> {
18    pub cwd: Cow<'a, str>,
19    pub os: Cow<'a, str>,
20    pub shell: Cow<'a, str>,
21    pub home_dir: Cow<'a, str>,
22    /// Current date string (e.g. "2026-06-10")
23    pub date: Cow<'a, str>,
24    /// Resolved model name (e.g. "claude-sonnet-4-6")
25    pub model_name: Cow<'a, str>,
26    pub skills_text: Option<Cow<'a, str>>,
27    pub mcp_instructions: Option<Cow<'a, str>>,
28    pub session_memory: Option<Cow<'a, str>>,
29    /// Whether the working directory is a git repository.
30    pub is_git: bool,
31    /// Current git branch name (e.g. "main").
32    pub git_branch: Option<Cow<'a, str>>,
33    /// Whether the cwd is a git worktree.
34    pub is_worktree: bool,
35    /// Raw git status output (truncated).
36    pub git_status: Option<Cow<'a, str>>,
37    /// User's language preference (e.g. "zh-CN"). None = no preference.
38    pub language: Option<Cow<'a, str>>,
39    /// Scratchpad directory path for temporary files.
40    pub scratchpad_dir: Option<Cow<'a, str>>,
41    /// Output style content (loaded from config). None = default style.
42    pub output_style_content: Option<Cow<'a, str>>,
43    /// Comma-separated list of tool names available in this session.
44    /// Used to conditionally include tool-specific guidance.
45    pub available_tools: Option<Cow<'a, str>>,
46    /// Whether any tool result has actually been cleared (time-based/cached
47    /// micro-compact, tool-result budget enforcement, or a `MicroCompact`
48    /// main-compaction pass) at any point in this session. Gates
49    /// the code scene's `function_result_clearing` prompt section — without
50    /// this it was injected unconditionally every turn even when nothing
51    /// had ever been cleared.
52    pub tool_results_ever_cleared: bool,
53    /// Whether someone answers this session's questions — the session's
54    /// own, which defaults to [`SceneSpec::interactive`]. A scene with two
55    /// prompts picks by it.
56    pub attended: bool,
57    /// The instance's names: what the product calls itself to the model.
58    pub layout: crate::paths::Layout,
59}
60
61/// Context for building the `<system-reminder>` block.
62#[derive(Debug, Clone)]
63#[non_exhaustive]
64pub struct ReminderContext<'a> {
65    pub cwd: Cow<'a, str>,
66    pub git_status: Option<Cow<'a, str>>,
67    pub memory_summary: Option<Cow<'a, str>>,
68}
69
70impl<'a> ReminderContext<'a> {
71    pub fn new(cwd: impl Into<Cow<'a, str>>) -> Self {
72        Self {
73            cwd: cwd.into(),
74            git_status: None,
75            memory_summary: None,
76        }
77    }
78    pub fn git_status(mut self, status: impl Into<Cow<'a, str>>) -> Self {
79        self.git_status = Some(status.into());
80        self
81    }
82    pub fn memory_summary(mut self, summary: impl Into<Cow<'a, str>>) -> Self {
83        self.memory_summary = Some(summary.into());
84        self
85    }
86}
87
88/// Tools that only work when someone answers. A session nobody attends (see
89/// [`SceneSpec::interactive`]) does not register them.
90pub const NEEDS_A_USER: &[&str] = &["AskUserQuestion", "EnterPlanMode", "ExitPlanMode"];
91
92/// Token budget configuration for a scene.
93#[derive(Debug, Clone)]
94#[non_exhaustive]
95pub struct TokenBudget {
96    /// Trigger auto-compact when input exceeds this threshold (0 = disabled).
97    pub compact_threshold: usize,
98    /// Number of recent messages to keep during compaction.
99    pub compact_keep_recent: usize,
100}
101
102impl TokenBudget {
103    pub fn new(compact_threshold: usize, compact_keep_recent: usize) -> Self {
104        Self {
105            compact_threshold,
106            compact_keep_recent,
107        }
108    }
109}
110
111/// Execution limits a scene imposes on its own turns.
112///
113/// Tool-call fan-out (`max_parallelism`) and delegation depth
114/// (`max_agent_depth`) are deliberately not here: both are bounded by
115/// `EngineConfig`, which is derived from `Settings`, not from the scene, and a
116/// scene that wants a different bound changes that config.
117///
118/// What is here is honoured — see `runtime::turn`'s `max_calls`.
119#[derive(Debug, Clone)]
120#[non_exhaustive]
121pub struct ExecutionParams {
122    /// Ceiling on LLM round trips within a single turn for this scene.
123    ///
124    /// Combined with `Settings.turn.max_model_calls` by taking
125    /// the **lower** of the two: a scene declaring a tight loop budget is
126    /// making a statement about its own workload that a deployment-wide
127    /// setting should not be able to silently widen, and a deployment that
128    /// wants to be stricter than the scene still gets its way.
129    ///
130    /// Defaults to no ceiling, so a scene that says nothing lets the setting
131    /// decide. Defaulting to the setting's own number would turn the `min`
132    /// into a silent clamp: an operator raising the setting for a
133    /// long-running task would get the scene's number back.
134    pub max_api_calls_per_turn: u32,
135}
136
137impl ExecutionParams {
138    pub fn new(max_api_calls_per_turn: u32) -> Self {
139        Self {
140            max_api_calls_per_turn,
141        }
142    }
143}
144
145impl Default for ExecutionParams {
146    fn default() -> Self {
147        Self {
148            max_api_calls_per_turn: u32::MAX,
149        }
150    }
151}
152
153/// The scene's system prompt and the facts it sends once in the opening
154/// context message.
155pub trait ScenePrompt: Send + Sync {
156    fn system(&self, ctx: &ScenePromptContext) -> Vec<PromptBlock>;
157
158    /// Facts about this session — working directory, platform, scratchpad —
159    /// sent once in the opening context message instead of the system prompt.
160    ///
161    /// Some endpoints (DeepSeek) cache the request prefix in the order system,
162    /// tools, messages: anything per-session in the system prompt makes every
163    /// new session re-read the whole tool table uncached.
164    fn session_context(&self, _ctx: &ScenePromptContext) -> String {
165        String::new()
166    }
167}
168
169/// A prompt that is the same blocks every time and has no session context.
170pub struct FixedPrompt(pub Vec<PromptBlock>);
171
172impl ScenePrompt for FixedPrompt {
173    fn system(&self, _ctx: &ScenePromptContext) -> Vec<PromptBlock> {
174        self.0.clone()
175    }
176}
177
178/// What the per-turn `<system-reminder>` carries, in the order listed.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
180#[serde(rename_all = "snake_case")]
181#[non_exhaustive]
182pub enum Reminder {
183    GitStatus,
184    Memory,
185}
186
187/// Which tools a session in the scene may have, and which of them are
188/// advertised by name only.
189///
190/// `allow` and `deny` are one [`ToolSelector`] layer: a deny always holds, and
191/// `allow: None` allows every tool the deny list leaves. Both only narrow the
192/// registry the host assembled; [`SceneSpec::extra_tools`] is how a scene adds
193/// to it.
194///
195/// `deferred` tools stay allowed and callable, but are advertised to the model
196/// by name and one-line description only, the schema fetched on demand via
197/// `ToolSearch`. Names the session does not have are ignored. The list
198/// becomes the session's `EngineConfig::deferred_tools`, and covers MCP tools
199/// that arrive later in the session too.
200#[derive(Debug, Clone, Default, PartialEq, Eq)]
201#[non_exhaustive]
202pub struct ToolSurface {
203    pub allow: Option<Vec<ToolPattern>>,
204    pub deny: Vec<ToolPattern>,
205    pub deferred: Vec<String>,
206}
207
208impl ToolSurface {
209    /// Lists as configured, an empty `allow` allowing every tool.
210    pub fn from_lists(allow: &[impl AsRef<str>], deny: &[impl AsRef<str>]) -> Self {
211        Self {
212            allow: (!allow.is_empty()).then(|| {
213                allow
214                    .iter()
215                    .map(|p| ToolPattern::parse(p.as_ref()))
216                    .collect()
217            }),
218            deny: deny
219                .iter()
220                .map(|p| ToolPattern::parse(p.as_ref()))
221                .collect(),
222            deferred: Vec::new(),
223        }
224    }
225
226    pub fn allowing(allow: &[impl AsRef<str>]) -> Self {
227        Self::from_lists(allow, &[] as &[&str])
228    }
229
230    pub fn denying(deny: &[impl AsRef<str>]) -> Self {
231        Self::from_lists(&[] as &[&str], deny)
232    }
233
234    pub fn deferring(mut self, deferred: &[impl AsRef<str>]) -> Self {
235        self.deferred = deferred.iter().map(|n| n.as_ref().to_string()).collect();
236        self
237    }
238
239    pub fn selector(&self) -> ToolSelector {
240        if self.allow.is_none() && self.deny.is_empty() {
241            return ToolSelector::all();
242        }
243        ToolSelector::layer(self.allow.clone(), self.deny.clone())
244    }
245
246    pub fn permits(&self, name: &str, origin: &ToolOrigin) -> bool {
247        self.selector().admits(name, origin)
248    }
249}
250
251/// Which modules (`agents`, `mcp`, `skills`, ...) a session in the scene
252/// runs. `allow: None` runs every module the host assembled; naming one the
253/// host did not assemble adds nothing. The delegates a session spawns inherit
254/// the narrowed list.
255#[derive(Debug, Clone, Default, PartialEq, Eq)]
256#[non_exhaustive]
257pub struct ModuleSurface {
258    pub allow: Option<Vec<String>>,
259    pub deny: Vec<String>,
260}
261
262impl ModuleSurface {
263    pub fn new(allow: Option<Vec<String>>, deny: Vec<String>) -> Self {
264        Self { allow, deny }
265    }
266
267    pub fn permits(&self, id: &str) -> bool {
268        self.allow
269            .as_ref()
270            .is_none_or(|allowed| allowed.iter().any(|m| m == id))
271            && !self.deny.iter().any(|m| m == id)
272    }
273}
274
275/// A scene: everything but its prompt is data, so a host that builds on a
276/// built-in scene changes the fields it cares about and keeps the rest,
277/// instead of wrapping a trait object and forwarding every method.
278#[derive(Clone)]
279#[non_exhaustive]
280pub struct SceneSpec {
281    pub id: String,
282    pub name: String,
283    pub description: String,
284    pub prompt: Arc<dyn ScenePrompt>,
285    pub tools: ToolSurface,
286    /// Tools this scene registers into the session's own registry, before
287    /// `tools.deferred` is applied.
288    ///
289    /// A name already registered is **rejected**, not substituted:
290    /// `Builder::build()` fails rather than let a scene shadow `Bash` or
291    /// `Edit`. They are built with no session context, so they suit
292    /// self-contained tools.
293    pub extra_tools: Vec<Arc<dyn Tool>>,
294    pub modules: ModuleSurface,
295    /// Whether a session must be bound to a project root. The daemon refuses
296    /// a session with no `project_root` for a scene that says yes.
297    pub requires_project: bool,
298    /// `false` means the Team tools are never registered for the session.
299    pub supports_team: bool,
300    /// Whether someone is there to answer a question, a plan to approve, a
301    /// permission prompt — for a session that does not say otherwise
302    /// (`Builder::attended`). When nobody is, a call the permission policy
303    /// would ask about is refused instead, the tools in [`NEEDS_A_USER`] are
304    /// left out, [`Self::attended_skills`] are not listed, and the prompt
305    /// must not count on a reply.
306    pub interactive: bool,
307    /// How the file tools word paths when `Settings::path_style` is not set.
308    pub path_style: PathStyle,
309    pub token_budget: TokenBudget,
310    pub execution: ExecutionParams,
311    /// The built-in skills a session lists, by name. A built-in is also left
312    /// out when a tool it needs is not permitted here.
313    pub bundled_skills: Vec<String>,
314    /// Built-in skills listed besides [`Self::bundled_skills`] only when
315    /// someone attends the session: ones that hand something back to the
316    /// user mid-task.
317    pub attended_skills: Vec<String>,
318    pub reminders: Vec<Reminder>,
319    /// When set, the session is named after its first turn by a model call
320    /// with this prompt, `{first_message}` replaced by the user's message.
321    pub session_naming: Option<String>,
322    /// Replaces the intro sentence of post-turn durable-memory extraction,
323    /// whose default is code-flavored. The JSON output instructions that
324    /// follow it are fixed.
325    pub memory_extraction_intro: Option<String>,
326}
327
328impl SceneSpec {
329    pub fn new(
330        id: impl Into<String>,
331        name: impl Into<String>,
332        prompt: Arc<dyn ScenePrompt>,
333    ) -> Self {
334        Self {
335            id: id.into(),
336            name: name.into(),
337            description: String::new(),
338            prompt,
339            tools: ToolSurface::default(),
340            extra_tools: Vec::new(),
341            modules: ModuleSurface::default(),
342            requires_project: false,
343            supports_team: false,
344            interactive: false,
345            path_style: PathStyle::Absolute,
346            token_budget: TokenBudget {
347                compact_threshold: 150_000,
348                compact_keep_recent: 20,
349            },
350            execution: ExecutionParams::default(),
351            bundled_skills: vec!["skillify".into()],
352            attended_skills: Vec::new(),
353            reminders: Vec::new(),
354            session_naming: None,
355            memory_extraction_intro: None,
356        }
357    }
358
359    pub fn system_prompt(&self, ctx: &ScenePromptContext) -> Vec<PromptBlock> {
360        self.prompt.system(ctx)
361    }
362
363    pub fn session_context(&self, ctx: &ScenePromptContext) -> String {
364        self.prompt.session_context(ctx)
365    }
366
367    pub fn permits_tool(&self, name: &str, origin: &ToolOrigin) -> bool {
368        self.tools.permits(name, origin)
369    }
370
371    /// The `<system-reminder>` blocks injected before each turn, one per
372    /// entry in `reminders` that has something to say.
373    pub fn reminder(&self, ctx: &ReminderContext) -> String {
374        let mut out = String::new();
375        for reminder in &self.reminders {
376            let body = match reminder {
377                Reminder::GitStatus => ctx.git_status.as_deref(),
378                Reminder::Memory => ctx.memory_summary.as_deref(),
379            };
380            if let Some(body) = body {
381                out.push_str(&format!("\n<system-reminder>\n{body}\n</system-reminder>"));
382            }
383        }
384        out
385    }
386
387    pub fn session_name_prompt(&self, first_message: &str) -> Option<String> {
388        self.session_naming
389            .as_ref()
390            .map(|template| template.replace("{first_message}", first_message))
391    }
392}
393
394impl std::fmt::Debug for SceneSpec {
395    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396        f.debug_struct("SceneSpec")
397            .field("id", &self.id)
398            .field("name", &self.name)
399            .field("tools", &self.tools)
400            .field("modules", &self.modules)
401            .finish_non_exhaustive()
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    fn spec() -> SceneSpec {
410        SceneSpec::new("t", "T", Arc::new(FixedPrompt(vec![])))
411    }
412
413    fn reminder_ctx<'a>(git: Option<&'a str>, memory: Option<&'a str>) -> ReminderContext<'a> {
414        ReminderContext {
415            cwd: Cow::Borrowed("/w"),
416            git_status: git.map(Cow::Borrowed),
417            memory_summary: memory.map(Cow::Borrowed),
418        }
419    }
420
421    #[test]
422    fn a_deny_holds_under_an_allow_list() {
423        let mut s = spec();
424        s.tools = ToolSurface::from_lists(&["mcp__*", "Read"], &["mcp__shell__*"]);
425        assert!(s.permits_tool("Read", &ToolOrigin::Builtin));
426        assert!(s.permits_tool("mcp__github__diff", &ToolOrigin::mcp("github")));
427        assert!(!s.permits_tool("mcp__shell__run", &ToolOrigin::mcp("shell")));
428        assert!(!s.permits_tool("Bash", &ToolOrigin::Builtin));
429    }
430
431    #[test]
432    fn defaults_admit_every_tool_and_module() {
433        let s = spec();
434        assert_eq!(s.tools.selector(), ToolSelector::all());
435        assert!(s.permits_tool("Bash", &ToolOrigin::Builtin));
436        assert!(s.modules.permits("agents"));
437        assert_eq!(s.bundled_skills, ["skillify"]);
438        assert_eq!(s.reminder(&reminder_ctx(Some("M a.rs"), Some("mem"))), "");
439    }
440
441    #[test]
442    fn modules_are_admitted_and_not_disabled() {
443        let modules = ModuleSurface {
444            allow: Some(vec!["skills".into(), "mcp".into()]),
445            deny: vec!["mcp".into()],
446        };
447        assert!(modules.permits("skills"));
448        assert!(!modules.permits("mcp"));
449        assert!(!modules.permits("team"));
450    }
451
452    #[test]
453    fn reminders_render_in_the_order_listed_and_skip_what_is_absent() {
454        let mut s = spec();
455        s.reminders = vec![Reminder::Memory, Reminder::GitStatus];
456        assert_eq!(
457            s.reminder(&reminder_ctx(Some("M a.rs"), Some("mem"))),
458            "\n<system-reminder>\nmem\n</system-reminder>\n<system-reminder>\nM a.rs\n</system-reminder>"
459        );
460        assert_eq!(
461            s.reminder(&reminder_ctx(Some("M a.rs"), None)),
462            "\n<system-reminder>\nM a.rs\n</system-reminder>"
463        );
464    }
465
466    #[test]
467    fn the_naming_template_takes_the_first_message() {
468        let mut s = spec();
469        assert_eq!(s.session_name_prompt("hi"), None);
470        s.session_naming = Some("title: {first_message}".into());
471        assert_eq!(s.session_name_prompt("hi").as_deref(), Some("title: hi"));
472    }
473}