use crate::context::config::PathStyle;
use crate::interface::tool::{Tool, ToolOrigin};
use crate::interface::tool_selector::{ToolPattern, ToolSelector};
use crate::prompt::PromptBlock;
use serde::Deserialize;
use std::borrow::Cow;
use std::sync::Arc;
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ScenePromptContext<'a> {
pub cwd: Cow<'a, str>,
pub os: Cow<'a, str>,
pub shell: Cow<'a, str>,
pub home_dir: Cow<'a, str>,
pub date: Cow<'a, str>,
pub model_name: Cow<'a, str>,
pub skills_text: Option<Cow<'a, str>>,
pub mcp_instructions: Option<Cow<'a, str>>,
pub session_memory: Option<Cow<'a, str>>,
pub is_git: bool,
pub git_branch: Option<Cow<'a, str>>,
pub is_worktree: bool,
pub git_status: Option<Cow<'a, str>>,
pub language: Option<Cow<'a, str>>,
pub scratchpad_dir: Option<Cow<'a, str>>,
pub output_style_content: Option<Cow<'a, str>>,
pub available_tools: Option<Cow<'a, str>>,
pub tool_results_ever_cleared: bool,
pub attended: bool,
pub layout: crate::paths::Layout,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ReminderContext<'a> {
pub cwd: Cow<'a, str>,
pub git_status: Option<Cow<'a, str>>,
pub memory_summary: Option<Cow<'a, str>>,
}
impl<'a> ReminderContext<'a> {
pub fn new(cwd: impl Into<Cow<'a, str>>) -> Self {
Self {
cwd: cwd.into(),
git_status: None,
memory_summary: None,
}
}
pub fn git_status(mut self, status: impl Into<Cow<'a, str>>) -> Self {
self.git_status = Some(status.into());
self
}
pub fn memory_summary(mut self, summary: impl Into<Cow<'a, str>>) -> Self {
self.memory_summary = Some(summary.into());
self
}
}
pub const NEEDS_A_USER: &[&str] = &["AskUserQuestion", "EnterPlanMode", "ExitPlanMode"];
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TokenBudget {
pub compact_threshold: usize,
pub compact_keep_recent: usize,
}
impl TokenBudget {
pub fn new(compact_threshold: usize, compact_keep_recent: usize) -> Self {
Self {
compact_threshold,
compact_keep_recent,
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ExecutionParams {
pub max_api_calls_per_turn: u32,
}
impl ExecutionParams {
pub fn new(max_api_calls_per_turn: u32) -> Self {
Self {
max_api_calls_per_turn,
}
}
}
impl Default for ExecutionParams {
fn default() -> Self {
Self {
max_api_calls_per_turn: u32::MAX,
}
}
}
pub trait ScenePrompt: Send + Sync {
fn system(&self, ctx: &ScenePromptContext) -> Vec<PromptBlock>;
fn session_context(&self, _ctx: &ScenePromptContext) -> String {
String::new()
}
}
pub struct FixedPrompt(pub Vec<PromptBlock>);
impl ScenePrompt for FixedPrompt {
fn system(&self, _ctx: &ScenePromptContext) -> Vec<PromptBlock> {
self.0.clone()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Reminder {
GitStatus,
Memory,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ToolSurface {
pub allow: Option<Vec<ToolPattern>>,
pub deny: Vec<ToolPattern>,
pub deferred: Vec<String>,
}
impl ToolSurface {
pub fn from_lists(allow: &[impl AsRef<str>], deny: &[impl AsRef<str>]) -> Self {
Self {
allow: (!allow.is_empty()).then(|| {
allow
.iter()
.map(|p| ToolPattern::parse(p.as_ref()))
.collect()
}),
deny: deny
.iter()
.map(|p| ToolPattern::parse(p.as_ref()))
.collect(),
deferred: Vec::new(),
}
}
pub fn allowing(allow: &[impl AsRef<str>]) -> Self {
Self::from_lists(allow, &[] as &[&str])
}
pub fn denying(deny: &[impl AsRef<str>]) -> Self {
Self::from_lists(&[] as &[&str], deny)
}
pub fn deferring(mut self, deferred: &[impl AsRef<str>]) -> Self {
self.deferred = deferred.iter().map(|n| n.as_ref().to_string()).collect();
self
}
pub fn selector(&self) -> ToolSelector {
if self.allow.is_none() && self.deny.is_empty() {
return ToolSelector::all();
}
ToolSelector::layer(self.allow.clone(), self.deny.clone())
}
pub fn permits(&self, name: &str, origin: &ToolOrigin) -> bool {
self.selector().admits(name, origin)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ModuleSurface {
pub allow: Option<Vec<String>>,
pub deny: Vec<String>,
}
impl ModuleSurface {
pub fn new(allow: Option<Vec<String>>, deny: Vec<String>) -> Self {
Self { allow, deny }
}
pub fn permits(&self, id: &str) -> bool {
self.allow
.as_ref()
.is_none_or(|allowed| allowed.iter().any(|m| m == id))
&& !self.deny.iter().any(|m| m == id)
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct SceneSpec {
pub id: String,
pub name: String,
pub description: String,
pub prompt: Arc<dyn ScenePrompt>,
pub tools: ToolSurface,
pub extra_tools: Vec<Arc<dyn Tool>>,
pub modules: ModuleSurface,
pub requires_project: bool,
pub supports_team: bool,
pub interactive: bool,
pub path_style: PathStyle,
pub token_budget: TokenBudget,
pub execution: ExecutionParams,
pub bundled_skills: Vec<String>,
pub attended_skills: Vec<String>,
pub reminders: Vec<Reminder>,
pub session_naming: Option<String>,
pub memory_extraction_intro: Option<String>,
}
impl SceneSpec {
pub fn new(
id: impl Into<String>,
name: impl Into<String>,
prompt: Arc<dyn ScenePrompt>,
) -> Self {
Self {
id: id.into(),
name: name.into(),
description: String::new(),
prompt,
tools: ToolSurface::default(),
extra_tools: Vec::new(),
modules: ModuleSurface::default(),
requires_project: false,
supports_team: false,
interactive: false,
path_style: PathStyle::Absolute,
token_budget: TokenBudget {
compact_threshold: 150_000,
compact_keep_recent: 20,
},
execution: ExecutionParams::default(),
bundled_skills: vec!["skillify".into()],
attended_skills: Vec::new(),
reminders: Vec::new(),
session_naming: None,
memory_extraction_intro: None,
}
}
pub fn system_prompt(&self, ctx: &ScenePromptContext) -> Vec<PromptBlock> {
self.prompt.system(ctx)
}
pub fn session_context(&self, ctx: &ScenePromptContext) -> String {
self.prompt.session_context(ctx)
}
pub fn permits_tool(&self, name: &str, origin: &ToolOrigin) -> bool {
self.tools.permits(name, origin)
}
pub fn reminder(&self, ctx: &ReminderContext) -> String {
let mut out = String::new();
for reminder in &self.reminders {
let body = match reminder {
Reminder::GitStatus => ctx.git_status.as_deref(),
Reminder::Memory => ctx.memory_summary.as_deref(),
};
if let Some(body) = body {
out.push_str(&format!("\n<system-reminder>\n{body}\n</system-reminder>"));
}
}
out
}
pub fn session_name_prompt(&self, first_message: &str) -> Option<String> {
self.session_naming
.as_ref()
.map(|template| template.replace("{first_message}", first_message))
}
}
impl std::fmt::Debug for SceneSpec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SceneSpec")
.field("id", &self.id)
.field("name", &self.name)
.field("tools", &self.tools)
.field("modules", &self.modules)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn spec() -> SceneSpec {
SceneSpec::new("t", "T", Arc::new(FixedPrompt(vec![])))
}
fn reminder_ctx<'a>(git: Option<&'a str>, memory: Option<&'a str>) -> ReminderContext<'a> {
ReminderContext {
cwd: Cow::Borrowed("/w"),
git_status: git.map(Cow::Borrowed),
memory_summary: memory.map(Cow::Borrowed),
}
}
#[test]
fn a_deny_holds_under_an_allow_list() {
let mut s = spec();
s.tools = ToolSurface::from_lists(&["mcp__*", "Read"], &["mcp__shell__*"]);
assert!(s.permits_tool("Read", &ToolOrigin::Builtin));
assert!(s.permits_tool("mcp__github__diff", &ToolOrigin::mcp("github")));
assert!(!s.permits_tool("mcp__shell__run", &ToolOrigin::mcp("shell")));
assert!(!s.permits_tool("Bash", &ToolOrigin::Builtin));
}
#[test]
fn defaults_admit_every_tool_and_module() {
let s = spec();
assert_eq!(s.tools.selector(), ToolSelector::all());
assert!(s.permits_tool("Bash", &ToolOrigin::Builtin));
assert!(s.modules.permits("agents"));
assert_eq!(s.bundled_skills, ["skillify"]);
assert_eq!(s.reminder(&reminder_ctx(Some("M a.rs"), Some("mem"))), "");
}
#[test]
fn modules_are_admitted_and_not_disabled() {
let modules = ModuleSurface {
allow: Some(vec!["skills".into(), "mcp".into()]),
deny: vec!["mcp".into()],
};
assert!(modules.permits("skills"));
assert!(!modules.permits("mcp"));
assert!(!modules.permits("team"));
}
#[test]
fn reminders_render_in_the_order_listed_and_skip_what_is_absent() {
let mut s = spec();
s.reminders = vec![Reminder::Memory, Reminder::GitStatus];
assert_eq!(
s.reminder(&reminder_ctx(Some("M a.rs"), Some("mem"))),
"\n<system-reminder>\nmem\n</system-reminder>\n<system-reminder>\nM a.rs\n</system-reminder>"
);
assert_eq!(
s.reminder(&reminder_ctx(Some("M a.rs"), None)),
"\n<system-reminder>\nM a.rs\n</system-reminder>"
);
}
#[test]
fn the_naming_template_takes_the_first_message() {
let mut s = spec();
assert_eq!(s.session_name_prompt("hi"), None);
s.session_naming = Some("title: {first_message}".into());
assert_eq!(s.session_name_prompt("hi").as_deref(), Some("title: hi"));
}
}