@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
247 lines (243 loc) • 12.3 kB
JavaScript
/**
* System prompt construction and project context loading
*/
import { getDocsPath, getExamplesPath, getReadmePath } from "../config.js";
import { formatSkillsForPrompt } from "./skills.js";
/** Contributions include eval-only tools even when the selected model-facing list does not. */
export function getEvalOnlyGrepGuideline(selectedTools, toolSnippets, sharedSections = "diet") {
if (!toolSnippets?.grep || selectedTools.includes("grep"))
return undefined;
return sharedSections === "full"
? "Search file contents with tool.grep({ pattern, path }) inside eval; prefer it over rg/grep in shell"
: "Content search: tool.grep({ pattern, path }) in eval, not rg/grep in shell; page full -> skip, narrow with glob/path.";
}
const SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;
function assertSystemPromptSectionNames(sections) {
for (const name of Object.keys(sections)) {
if (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === "preamble") {
throw new Error(`Invalid system prompt section name: ${name}`);
}
}
}
/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */
export function normalizeBuildSystemPromptOptions(input) {
return {
customPrompt: input.customPrompt,
forceSystemPrompt: input.forceSystemPrompt,
selectedTools: [...(input.selectedTools ?? ["read", "bash", "edit", "write"])],
toolSnippets: { ...(input.toolSnippets ?? {}) },
toolGuidelines: Object.fromEntries(Object.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]])),
promptGuidelines: [...(input.promptGuidelines ?? [])],
appendSystemPrompt: input.appendSystemPrompt ?? "",
sections: { ...(input.sections ?? {}) },
cwd: input.cwd,
contextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),
skills: (input.skills ?? []).map((skill) => ({ ...skill })),
surface: input.surface,
};
}
function renderProjectContext(contextFiles) {
return [
"Project-specific instructions and guidelines:",
...contextFiles.map(({ path, content }) => `<project_instructions path="${path}">\n${content}\n</project_instructions>`),
].join("\n\n");
}
function buildRules(selectedTools, toolSnippets, toolGuidelines, promptGuidelines) {
const rules = [];
const seen = new Set();
const addRule = (rule) => {
const normalized = rule.trim();
if (!normalized || seen.has(normalized))
return;
seen.add(normalized);
rules.push(normalized);
};
const hasBash = selectedTools.includes("bash");
const hasPowerShell = selectedTools.includes("powershell");
const hasGrep = selectedTools.includes("grep");
const hasFind = selectedTools.includes("find");
const hasLs = selectedTools.includes("ls");
const evalOnlyGrepGuideline = getEvalOnlyGrepGuideline(selectedTools, toolSnippets);
if (evalOnlyGrepGuideline) {
addRule(evalOnlyGrepGuideline);
}
else if ((hasBash || hasPowerShell) && !hasGrep && !hasFind && !hasLs) {
if (hasBash && hasPowerShell) {
addRule("Use bash or PowerShell for file operations like listing, searching, and finding files");
}
else if (hasPowerShell) {
addRule("Use PowerShell for file operations like listing, searching, and finding files");
}
else {
addRule("Use bash for file operations like ls, rg, find");
}
}
for (const name of selectedTools) {
for (const rule of toolGuidelines[name] ?? [])
addRule(rule);
}
for (const rule of promptGuidelines)
addRule(rule);
addRule("Be concise in your responses");
addRule("Show file paths clearly when working with files");
return rules.map((rule) => `- ${rule}`).join("\n");
}
const PI_DOCS_GUIDANCE = `- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
- 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), MCP servers (docs/mcp.md)
- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing
- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;
function renderPiDocs() {
return `Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):
- Main documentation: ${getReadmePath()}
- Additional docs: ${getDocsPath()}
- Examples: ${getExamplesPath()} (extensions, custom tools, SDK)
${PI_DOCS_GUIDANCE}`;
}
/** Build the ordered, independently replaceable sections of the structured system prompt. */
export function buildSystemPromptSections(input) {
const options = normalizeBuildSystemPromptOptions(input);
const { customPrompt, selectedTools, toolSnippets, toolGuidelines, promptGuidelines, appendSystemPrompt, sections: customSections, cwd, contextFiles, skills, } = options;
assertSystemPromptSectionNames(customSections);
const promptSections = {};
if (customPrompt) {
promptSections.preamble = customPrompt;
}
else {
promptSections.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.";
const visibleTools = selectedTools.filter((name) => !!toolSnippets[name]);
const tools = visibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join("\n") : "(none)";
promptSections.tools = `${tools}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;
promptSections.rules = buildRules(selectedTools, toolSnippets, toolGuidelines, promptGuidelines);
promptSections.docs = renderPiDocs();
}
if (appendSystemPrompt)
promptSections.addendum = appendSystemPrompt;
if (contextFiles.length > 0)
promptSections.project_context = renderProjectContext(contextFiles);
const skillFileReadTool = ["read", "bash"].find((tool) => selectedTools.includes(tool));
if (skillFileReadTool && skills.length > 0) {
const skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();
if (skillsPrompt)
promptSections.skills = skillsPrompt;
}
promptSections.cwd = cwd.replace(/\\/g, "/");
for (const [name, content] of Object.entries(customSections)) {
if (content)
promptSections[name] = content;
}
const sections = { preamble: promptSections.preamble };
for (const [name, content] of Object.entries(promptSections)) {
if (name !== "preamble")
sections[name] = `<${name}>\n${content}\n</${name}>`;
}
return sections;
}
/**
* The complete prompt state for `input`. A forced prompt is opaque and lives in `content`
* with no sections; otherwise `content` is empty and the structured sections carry the prompt.
*/
export function buildSystemPromptState(input) {
if (input.forceSystemPrompt !== undefined)
return { content: input.forceSystemPrompt };
return { content: "", sections: buildSystemPromptSections(input) };
}
function renderCustomSections(sections) {
if (!sections)
return "";
assertSystemPromptSectionNames(sections);
let rendered = "";
for (const [name, content] of Object.entries(sections)) {
if (content)
rendered += `\n\n<${name}>\n${content}\n</${name}>`;
}
return rendered;
}
/**
* Build the system prompt string (fork layout: "Available tools:" / "Guidelines:" blocks and a trailing
* "Current working directory:" line). The structured section form for transcript system messages is
* `buildSystemPromptSections`/`buildSystemPromptState`.
*/
export function buildSystemPrompt(options) {
const { customPrompt, forceSystemPrompt, selectedTools, toolSnippets, toolGuidelines, promptGuidelines, appendSystemPrompt, sections: customSections, cwd, contextFiles: providedContextFiles, skills: providedSkills, } = options;
if (forceSystemPrompt !== undefined)
return forceSystemPrompt;
const promptCwd = cwd.replace(/\\/g, "/");
const appendSection = appendSystemPrompt ? `\n\n${appendSystemPrompt}` : "";
const customSectionText = renderCustomSections(customSections);
const contextFiles = providedContextFiles ?? [];
const skills = providedSkills ?? [];
const tools = selectedTools || ["read", "bash", "edit", "write"];
const skillFileReadTool = ["read", "bash"].find((tool) => tools.includes(tool));
if (customPrompt) {
let prompt = customPrompt;
if (appendSection) {
prompt += appendSection;
}
// Append project context files
if (contextFiles.length > 0) {
prompt += "\n\n<project_context>\n\n";
prompt += "Project-specific instructions and guidelines:\n\n";
for (const { path: filePath, content } of contextFiles) {
prompt += `<project_instructions path="${filePath}">\n${content}\n</project_instructions>\n\n`;
}
prompt += "</project_context>\n";
}
// Append skills when a tool capable of reading their files is available.
if (skillFileReadTool && skills.length > 0) {
prompt += formatSkillsForPrompt(skills, skillFileReadTool);
}
prompt += customSectionText;
prompt += `\nCurrent working directory: ${promptCwd}\n`;
return prompt;
}
// Build tools list based on selected tools.
// A tool appears in Available tools only when the caller provides a one-line snippet.
const visibleTools = tools.filter((name) => !!toolSnippets?.[name]);
const toolsList = visibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join("\n") : "(none)";
const guidelines = buildRules(tools, toolSnippets ?? {}, toolGuidelines ?? {}, promptGuidelines ?? []);
let prompt = `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.
Available tools:
${toolsList}
In addition to the tools above, you may have access to other custom tools depending on the project.
Guidelines:
${guidelines}
${renderPiDocs()}`;
if (appendSection) {
prompt += appendSection;
}
// Append project context files
if (contextFiles.length > 0) {
prompt += "\n\n<project_context>\n\n";
prompt += "Project-specific instructions and guidelines:\n\n";
for (const { path: filePath, content } of contextFiles) {
prompt += `<project_instructions path="${filePath}">\n${content}\n</project_instructions>\n\n`;
}
prompt += "</project_context>\n";
}
// Append skills when a tool capable of reading their files is available.
if (skillFileReadTool && skills.length > 0) {
prompt += formatSkillsForPrompt(skills, skillFileReadTool);
}
prompt += customSectionText;
prompt += `\nCurrent working directory: ${promptCwd}`;
return prompt;
}
/**
* Diff the sections the model currently has (replayed from the transcript, so never null)
* against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when
* nothing changed.
*/
export function diffSystemPromptSections(previous, current) {
const patch = {};
for (const [name, text] of Object.entries(current)) {
if (previous[name] !== text)
patch[name] = text;
}
for (const name of Object.keys(previous)) {
if (current[name] === undefined)
patch[name] = null;
}
return Object.keys(patch).length > 0 ? patch : undefined;
}
//# sourceMappingURL=system-prompt.js.map