1use crate::context_files::ContextFile;
4use crate::skills::{Skill, bundled_skills_note, format_always_skills_for_prompt, format_skills_for_prompt};
5
6#[derive(Clone, Debug, Default)]
8pub struct DocPaths {
9 pub readme: String,
10 pub docs: String,
11 pub examples: String,
12}
13
14#[derive(Clone, Debug, Default)]
16pub struct BuildOptions {
17 pub custom_prompt: Option<String>,
18 pub selected_tools: Vec<String>,
19 pub tool_snippets: Vec<(String, String)>,
20 pub tool_guidelines: Vec<(String, Vec<String>)>,
21 pub prompt_guidelines: Vec<String>,
22 pub append_system_prompt: String,
23 pub sections: Vec<(String, String)>,
24 pub cwd: String,
25 pub context_files: Vec<ContextFile>,
26 pub skills: Vec<Skill>,
27 pub engineering: bool,
28 pub include_harness_docs: bool,
29 pub doc_paths: DocPaths,
30 pub bundled_skills_dir: Option<String>,
32 pub persona: Option<String>,
34 pub proactive_skills: bool,
37}
38
39impl BuildOptions {
40 pub fn new(cwd: &str) -> Self {
42 Self {
43 selected_tools: ["read", "bash", "edit", "write"].map(String::from).to_vec(),
44 include_harness_docs: true,
45 cwd: cwd.to_string(),
46 ..Self::default()
47 }
48 }
49}
50
51pub type Sections = Vec<(String, String)>;
53
54fn lookup<'a, T>(pairs: &'a [(String, T)], name: &str) -> Option<&'a T> {
55 pairs.iter().find(|(key, _)| key == name).map(|(_, value)| value)
56}
57
58fn valid_section_name(name: &str) -> bool {
59 let mut bytes = name.bytes();
60 bytes.next().is_some_and(|b| b.is_ascii_lowercase())
61 && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-')
62}
63
64fn build_rules(options: &BuildOptions) -> String {
65 let mut rules: Vec<String> = Vec::new();
66 let mut add = |rule: &str| {
67 let rule = rule.trim();
68 if !rule.is_empty() && !rules.iter().any(|r| r == rule) {
69 rules.push(rule.to_string());
70 }
71 };
72 let has = |name: &str| options.selected_tools.iter().any(|t| t == name);
73 let (bash, pwsh) = (has("bash"), has("powershell"));
74 if (bash || pwsh) && !has("grep") && !has("find") && !has("ls") {
75 add(if bash && pwsh {
76 "Use bash or PowerShell for file operations like listing, searching, and finding files"
77 } else if pwsh {
78 "Use PowerShell for file operations like listing, searching, and finding files"
79 } else {
80 "Use bash for file operations like ls, rg, find"
81 });
82 }
83 for name in &options.selected_tools {
84 for rule in lookup(&options.tool_guidelines, name).into_iter().flatten() {
85 add(rule);
86 }
87 }
88 for rule in &options.prompt_guidelines {
89 add(rule);
90 }
91 add("Be concise in your responses");
92 add("Show file paths clearly when working with files");
93 rules
94 .iter()
95 .map(|rule| format!("- {rule}"))
96 .collect::<Vec<_>>()
97 .join("\n")
98}
99
100fn set(sections: &mut Sections, name: &str, text: String) {
102 match sections.iter_mut().find(|(key, _)| key == name) {
103 Some(entry) => entry.1 = text,
104 None => sections.push((name.to_string(), text)),
105 }
106}
107
108pub fn build_system_prompt_sections(options: &BuildOptions) -> Result<Sections, String> {
110 for (name, _) in &options.sections {
111 if !valid_section_name(name) || name == "preamble" {
112 return Err(format!("Invalid system prompt section name: {name}"));
113 }
114 }
115 let skills: Vec<Skill> = if options.engineering {
116 options.skills.clone()
117 } else {
118 options
119 .skills
120 .iter()
121 .map(|s| Skill {
122 always_on_content: None,
123 ..s.clone()
124 })
125 .collect()
126 };
127 let mut out: Sections = Vec::new();
128 match options.custom_prompt.as_deref().filter(|p| !p.is_empty()) {
129 Some(custom) => set(&mut out, "preamble", custom.to_string()),
130 None => {
131 set(&mut out, "preamble", "You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.".to_string());
132 let visible: Vec<String> = options
133 .selected_tools
134 .iter()
135 .filter_map(|name| {
136 let snippet = lookup(&options.tool_snippets, name).filter(|s| !s.is_empty())?;
137 Some(format!("- {name}: {snippet}"))
138 })
139 .collect();
140 let tools = if visible.is_empty() {
141 "(none)".to_string()
142 } else {
143 visible.join("\n")
144 };
145 set(
146 &mut out,
147 "tools",
148 if options.include_harness_docs {
149 format!(
150 "{tools}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project."
151 )
152 } else {
153 tools
154 },
155 );
156 set(&mut out, "rules", build_rules(options));
157 if options.include_harness_docs {
158 let DocPaths { readme, docs, examples } = &options.doc_paths;
159 set(&mut out, "docs", format!("Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):
160- Main documentation: {readme}
161- Additional docs: {docs}
162- Examples: {examples} (extensions, custom tools, SDK)
163- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
164- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md)
165- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing
166- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)"));
167 }
168 }
169 }
170 if !options.append_system_prompt.is_empty() {
171 set(&mut out, "addendum", options.append_system_prompt.clone());
172 }
173 if !options.context_files.is_empty() {
174 let mut parts = vec!["Project-specific instructions and guidelines:".to_string()];
175 parts.extend(options.context_files.iter().map(|ContextFile { path, content }| {
176 format!("<project_instructions path=\"{path}\">\n{content}\n</project_instructions>")
177 }));
178 set(&mut out, "project_context", parts.join("\n\n"));
179 }
180 if let Some(persona) = options.persona.as_deref().filter(|p| !p.is_empty()) {
181 set(&mut out, "persona", crate::persona::section_text(persona));
182 }
183 let read_tool = ["read", "bash", "rlm"]
184 .into_iter()
185 .find(|tool| options.selected_tools.iter().any(|t| t == tool));
186 if let Some(tool) = read_tool.filter(|_| !skills.is_empty()) {
187 let parts = [
188 format_always_skills_for_prompt(&skills),
189 format_skills_for_prompt(&skills, tool).trim().to_string(),
190 bundled_skills_note(&skills, options.bundled_skills_dir.as_deref(), options.proactive_skills),
191 ];
192 let text = parts
193 .into_iter()
194 .filter(|p| !p.is_empty())
195 .collect::<Vec<_>>()
196 .join("\n\n");
197 if !text.is_empty() {
198 set(&mut out, "skills", text);
199 }
200 }
201 set(&mut out, "cwd", options.cwd.replace('\\', "/"));
202 for (name, content) in &options.sections {
203 if !content.is_empty() {
204 set(&mut out, name, content.clone());
205 }
206 }
207 Ok(out
208 .into_iter()
209 .map(|(name, text)| {
210 if name == "preamble" {
211 (name, text)
212 } else {
213 let wrapped = format!("<{name}>\n{text}\n</{name}>");
214 (name, wrapped)
215 }
216 })
217 .collect())
218}
219
220pub fn build_system_prompt(options: &BuildOptions, force: Option<&str>) -> Result<String, String> {
222 if let Some(force) = force {
223 return Ok(force.to_string());
224 }
225 let sections = build_system_prompt_sections(options)?;
226 Ok(sections
227 .into_iter()
228 .map(|(_, text)| text)
229 .filter(|t| !t.is_empty())
230 .collect::<Vec<_>>()
231 .join("\n\n"))
232}