Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/coding-agent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
- Exposed `copyToClipboard` utility for extensions ([#926](https://github.com/badlogic/pi-mono/issues/926) by [@mitsuhiko](https://github.com/mitsuhiko))
- Skill invocation messages are now collapsible in chat output, showing collapsed by default with skill name and expand hint ([#894](https://github.com/badlogic/pi-mono/issues/894))
- Header values in `models.json` now support environment variables and shell commands, matching `apiKey` resolution ([#909](https://github.com/badlogic/pi-mono/issues/909))
- Template variables (`{{tools}}`, `{{context}}`, `{{skills}}`) for custom system prompts in SYSTEM.md, allowing precise control over where dynamic content is injected
- `markdown.codeBlockIndent` setting to customize code block indentation in rendered output
- Extension package management with `pi install`, `pi remove`, `pi update`, and `pi list` commands ([#645](https://github.com/badlogic/pi-mono/issues/645))
- Package filtering: selectively load resources from packages using object form in `packages` array ([#645](https://github.com/badlogic/pi-mono/issues/645))
Expand Down
1 change: 1 addition & 0 deletions packages/coding-agent/examples/sdk/12-full-control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const resourceLoader: ResourceLoader = {
getAgentsFiles: () => ({ agentsFiles: [] }),
getSystemPrompt: () => `You are a minimal assistant.
Available: read, bash. Be concise.`,
getSystemPromptTemplates: () => undefined,
getAppendSystemPrompt: () => [],
getPathMetadata: () => new Map(),
reload: async () => {},
Expand Down
4 changes: 3 additions & 1 deletion packages/coding-agent/src/core/agent-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,14 +610,16 @@ export class AgentSession {
const loadedSkills = this._resourceLoader.getSkills().skills;
const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;

return buildSystemPrompt({
const result = buildSystemPrompt({
cwd: this._cwd,
skills: loadedSkills,
contextFiles: loadedContextFiles,
customPrompt: loaderSystemPrompt,
appendSystemPrompt,
selectedTools: validToolNames,
});

return result.prompt;
}

// =========================================================================
Expand Down
18 changes: 18 additions & 0 deletions packages/coding-agent/src/core/resource-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,22 @@ import { SettingsManager } from "./settings-manager.js";
import type { Skill } from "./skills.js";
import { loadSkills } from "./skills.js";

/** Template variable usage in custom SYSTEM.md */
export interface SystemPromptTemplates {
tools: boolean;
context: boolean;
skills: boolean;
}

export interface ResourceLoader {
getExtensions(): LoadExtensionsResult;
getSkills(): { skills: Skill[]; diagnostics: ResourceDiagnostic[] };
getPrompts(): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] };
getThemes(): { themes: Theme[]; diagnostics: ResourceDiagnostic[] };
getAgentsFiles(): { agentsFiles: Array<{ path: string; content: string }> };
getSystemPrompt(): string | undefined;
/** Returns template variable usage if custom SYSTEM.md exists, undefined otherwise */
getSystemPromptTemplates(): SystemPromptTemplates | undefined;
getAppendSystemPrompt(): string[];
getPathMetadata(): Map<string, PathMetadata>;
reload(): Promise<void>;
Expand Down Expand Up @@ -258,6 +267,15 @@ export class DefaultResourceLoader implements ResourceLoader {
return this.systemPrompt;
}

getSystemPromptTemplates(): SystemPromptTemplates | undefined {
if (!this.systemPrompt) return undefined;
return {
tools: this.systemPrompt.includes("{{tools}}"),
context: this.systemPrompt.includes("{{context}}"),
skills: this.systemPrompt.includes("{{skills}}"),
};
}

getAppendSystemPrompt(): string[] {
return this.appendSystemPrompt;
}
Expand Down
63 changes: 46 additions & 17 deletions packages/coding-agent/src/core/system-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,17 @@ export interface BuildSystemPromptOptions {
skills?: Skill[];
}

export interface BuildSystemPromptResult {
/** The built system prompt */
prompt: string;
/** Whether context files were injected (always true for default prompt, depends on {{context}} for custom) */
contextInjected: boolean;
/** Whether skills were injected (always true for default prompt, depends on {{skills}} for custom) */
skillsInjected: boolean;
}

/** Build the system prompt with tools, guidelines, and context */
export function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {
export function buildSystemPrompt(options: BuildSystemPromptOptions = {}): BuildSystemPromptResult {
const {
customPrompt,
selectedTools,
Expand Down Expand Up @@ -63,30 +72,48 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions = {}): strin
if (customPrompt) {
let prompt = customPrompt;

if (appendSection) {
prompt += appendSection;
// Template variable replacement (opt-in injection)
// No template variables = full replacement mode (no automatic appending)
const contextInjected = prompt.includes("{{context}}");
const skillsInjected = prompt.includes("{{skills}}");

if (prompt.includes("{{tools}}")) {
const tools = selectedTools || ["read", "bash", "edit", "write"];
const toolsList =
tools.length > 0
? tools.map((t) => `- ${t}: ${toolDescriptions[t] ?? "Custom tool"}`).join("\n")
: "(none)";
prompt = prompt.replace("{{tools}}", toolsList);
}

// 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 += `## ${filePath}\n\n${content}\n\n`;
if (contextInjected) {
let contextStr = "";
if (contextFiles.length > 0) {
contextStr = "# Project Context\n\n";
contextStr += "Project-specific instructions and guidelines:\n\n";
for (const { path: filePath, content } of contextFiles) {
contextStr += `## ${filePath}\n\n${content}\n\n`;
}
}
prompt = prompt.replace("{{context}}", contextStr);
}

// Append skills section (only if read tool is available)
const customPromptHasRead = !selectedTools || selectedTools.includes("read");
if (customPromptHasRead && skills.length > 0) {
prompt += formatSkillsForPrompt(skills);
if (skillsInjected) {
const customPromptHasRead = !selectedTools || selectedTools.includes("read");
const skillsStr = customPromptHasRead && skills.length > 0 ? formatSkillsForPrompt(skills) : "";
prompt = prompt.replace("{{skills}}", skillsStr);
}

// Append section always applies (for --append-system-prompt)
if (appendSection) {
prompt += appendSection;
}

// Add date/time and working directory last
// Add date/time and working directory last (always)
prompt += `\nCurrent date and time: ${dateTime}`;
prompt += `\nCurrent working directory: ${resolvedCwd}`;

return prompt;
return { prompt, contextInjected, skillsInjected };
}

// Get absolute paths to documentation and examples
Expand Down Expand Up @@ -175,13 +202,15 @@ Pi documentation (read only when the user asks about pi itself, its SDK, extensi
}

// Append skills section (only if read tool is available)
if (hasRead && skills.length > 0) {
const skillsInjected = hasRead;
if (skillsInjected && skills.length > 0) {
prompt += formatSkillsForPrompt(skills);
}

// Add date/time and working directory last
prompt += `\nCurrent date and time: ${dateTime}`;
prompt += `\nCurrent working directory: ${resolvedCwd}`;

return prompt;
// Default prompt always injects context, skills depend on read tool
return { prompt, contextInjected: true, skillsInjected };
}
7 changes: 6 additions & 1 deletion packages/coding-agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,12 @@ export type {
ResolvedPaths,
} from "./core/package-manager.js";
export { DefaultPackageManager } from "./core/package-manager.js";
export type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from "./core/resource-loader.js";
export type {
ResourceCollision,
ResourceDiagnostic,
ResourceLoader,
SystemPromptTemplates,
} from "./core/resource-loader.js";
export { DefaultResourceLoader } from "./core/resource-loader.js";
// SDK for programmatic usage
export {
Expand Down
44 changes: 29 additions & 15 deletions packages/coding-agent/src/modes/interactive/interactive-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -866,26 +866,40 @@ export class InteractiveMode {
}

const metadata = this.session.resourceLoader.getPathMetadata();
// Check if custom SYSTEM.md uses template variables
// undefined = no custom prompt (default behavior, show all)
// defined = custom prompt, only show if template is used
const promptTemplates = this.session.resourceLoader.getSystemPromptTemplates();

const sectionHeader = (name: string, color: ThemeColor = "mdHeading") => theme.fg(color, `[${name}]`);

const contextFiles = this.session.resourceLoader.getAgentsFiles().agentsFiles;
if (contextFiles.length > 0) {
const contextList = contextFiles.map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`)).join("\n");
this.chatContainer.addChild(new Text(`${sectionHeader("Context")}\n${contextList}`, 0, 0));
this.chatContainer.addChild(new Spacer(1));
// Show context only if: no custom prompt OR custom prompt uses {{context}}
const showContext = !promptTemplates || promptTemplates.context;
if (showContext) {
const contextFiles = this.session.resourceLoader.getAgentsFiles().agentsFiles;
if (contextFiles.length > 0) {
const contextList = contextFiles
.map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`))
.join("\n");
this.chatContainer.addChild(new Text(`${sectionHeader("Context")}\n${contextList}`, 0, 0));
this.chatContainer.addChild(new Spacer(1));
}
}

const skills = this.session.resourceLoader.getSkills().skills;
if (skills.length > 0) {
const skillPaths = skills.map((s) => s.filePath);
const groups = this.buildScopeGroups(skillPaths, metadata);
const skillList = this.formatScopeGroups(groups, {
formatPath: (p) => this.formatDisplayPath(p),
formatPackagePath: (p, source) => this.getShortPath(p, source),
});
this.chatContainer.addChild(new Text(`${sectionHeader("Skills")}\n${skillList}`, 0, 0));
this.chatContainer.addChild(new Spacer(1));
// Show skills only if: no custom prompt OR custom prompt uses {{skills}}
const showSkills = !promptTemplates || promptTemplates.skills;
if (showSkills) {
const skills = this.session.resourceLoader.getSkills().skills;
if (skills.length > 0) {
const skillPaths = skills.map((s) => s.filePath);
const groups = this.buildScopeGroups(skillPaths, metadata);
const skillList = this.formatScopeGroups(groups, {
formatPath: (p) => this.formatDisplayPath(p),
formatPackagePath: (p, source) => this.getShortPath(p, source),
});
this.chatContainer.addChild(new Text(`${sectionHeader("Skills")}\n${skillList}`, 0, 0));
this.chatContainer.addChild(new Spacer(1));
}
}

const skillDiagnostics = this.session.resourceLoader.getSkills().diagnostics;
Expand Down
2 changes: 2 additions & 0 deletions packages/coding-agent/test/sdk-skills.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ This is a test skill.
getThemes: () => ({ themes: [], diagnostics: [] }),
getAgentsFiles: () => ({ agentsFiles: [] }),
getSystemPrompt: () => undefined,
getSystemPromptTemplates: () => undefined,
getAppendSystemPrompt: () => [],
getPathMetadata: () => new Map(),
reload: async () => {},
Expand Down Expand Up @@ -90,6 +91,7 @@ This is a test skill.
getThemes: () => ({ themes: [], diagnostics: [] }),
getAgentsFiles: () => ({ agentsFiles: [] }),
getSystemPrompt: () => undefined,
getSystemPromptTemplates: () => undefined,
getAppendSystemPrompt: () => [],
getPathMetadata: () => new Map(),
reload: async () => {},
Expand Down
Loading