1use 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#[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 pub date: Cow<'a, str>,
24 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 pub is_git: bool,
31 pub git_branch: Option<Cow<'a, str>>,
33 pub is_worktree: bool,
35 pub git_status: Option<Cow<'a, str>>,
37 pub language: Option<Cow<'a, str>>,
39 pub scratchpad_dir: Option<Cow<'a, str>>,
41 pub output_style_content: Option<Cow<'a, str>>,
43 pub available_tools: Option<Cow<'a, str>>,
46 pub tool_results_ever_cleared: bool,
53 pub attended: bool,
57 pub layout: crate::paths::Layout,
59}
60
61#[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
88pub const NEEDS_A_USER: &[&str] = &["AskUserQuestion", "EnterPlanMode", "ExitPlanMode"];
91
92#[derive(Debug, Clone)]
94#[non_exhaustive]
95pub struct TokenBudget {
96 pub compact_threshold: usize,
98 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#[derive(Debug, Clone)]
120#[non_exhaustive]
121pub struct ExecutionParams {
122 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
153pub trait ScenePrompt: Send + Sync {
156 fn system(&self, ctx: &ScenePromptContext) -> Vec<PromptBlock>;
157
158 fn session_context(&self, _ctx: &ScenePromptContext) -> String {
165 String::new()
166 }
167}
168
169pub 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#[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#[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 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#[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#[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 pub extra_tools: Vec<Arc<dyn Tool>>,
294 pub modules: ModuleSurface,
295 pub requires_project: bool,
298 pub supports_team: bool,
300 pub interactive: bool,
307 pub path_style: PathStyle,
309 pub token_budget: TokenBudget,
310 pub execution: ExecutionParams,
311 pub bundled_skills: Vec<String>,
314 pub attended_skills: Vec<String>,
318 pub reminders: Vec<Reminder>,
319 pub session_naming: Option<String>,
322 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 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}