prompt: Pi's <available_skills> and its context files count as skills and memory, not system prompt

Reported on X by @JinJieBeWater: Pi's skills showed up as system prompt
in the context breakdown. Pi (pi-coding-agent 0.73.1, read from the npm
tarball: formatSkillsForPrompt in dist/core/skills.js, buildSystemPrompt
in dist/core/system-prompt.js) builds one system prompt: its own text,
then "# Project Context" with each AGENTS.md/CLAUDE.md under
"## <path>", then a paragraph on loading skills ("The following skills
provide specialized instructions for specific tasks. ...") and an
<available_skills> block of <skill> entries (the Agent Skills standard's
format), then "Current date:" and "Current working directory:" lines.
splitSkills knew only Claude Code's "The following skills are available
for use with the Skill tool:" list, systemText only a leading
<skills_instructions> (Codex), and splitMemory only Claude Code's,
OpenCode's and Codex's headings, so all of Pi's prompt was one System
prompt item.

- splitSkills also takes an <available_skills> block out, with Pi's
  lead paragraph before it, on every protocol and in a reminder too.
  The tag must open a line and the block must close, so prose naming
  the tag stays put. Any agent listing skills in the standard's block
  is read the same way.
- splitMemory reads Pi's "## /path/AGENTS.md" files as memory, only
  under Pi's "# Project Context" header, and ends the last one at Pi's
  skills or its closing lines. A file under ~/.pi/ is the user's.

Prompts recorded before keep only token counts per item, so they stay
as they were; new requests are split.

testdata/context/pi-0.73.1-system.txt is Pi's default system prompt
assembled by hand from 0.73.1's source (not run): its tool snippets and
guidelines, two context files and two skills, one description with
Pi's &amp; escaping.

Run on mote at this tree (rebased on e4e9eb092):
- go test ./internal/gateway -count=1 -timeout 45m: every test ok except
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes, red 3 of 3 on
  e4e9eb092 without this change too (#7117, open)
- go vet ./internal/gateway, also GOOS=linux and GOOS=windows: ok
- gofmt -l: clean
Then rebased onto d7796bf40 (three commits in netproxy, usage, usageapi
and gui, none in internal/gateway); at that pushed tree go vet
./internal/gateway and -run 'Prompt|SplitSkills|SkillsApart': ok.
Broken by hand: with e4e9eb092's prompt.go, TestPromptOfPiSkills is red
("the system prompt keeps the skills"); with the splitMemory branch
turned off, TestPromptOfPiMemory is red (no memory item).
Not tried: a real Pi run through magpie; only Pi's source was read.
No GUI change (the Context view shows the parts it is given), so no GUI
suite.
This commit is contained in:
yetone
2026-11-19 18:40:18 +08:00
parent d7796bf409
commit 71718b277a
3 changed files with 268 additions and 3 deletions
+92 -3
View File
@@ -383,7 +383,9 @@ var (
instructionsFrom = lazyre.New(`(?m)^Instructions from: (\S.*?)[ \t]*$`)
// Codex: "# AGENTS.md instructions for /path"
agentsFor = lazyre.New(`^# (\S+\.md) instructions for (\S.*?)[ \t]*\n`)
leadTag = lazyre.New(`^\s*<([a-zA-Z_][\w -]{0,40})>`)
// Pi: "## /path/AGENTS.md" under its "# Project Context" header
piFile = lazyre.New(`(?m)^## (\S.*?[/\\](?:AGENTS|CLAUDE)\.(?:md|MD))[ \t]*$`)
leadTag = lazyre.New(`^\s*<([a-zA-Z_][\w -]{0,40})>`)
)
// memoryTag says whose an instruction file is from how the agent
@@ -400,7 +402,8 @@ func memoryTag(path, desc string) string {
case d != "":
return "project"
}
if strings.Contains(path, "/.claude/") || strings.Contains(path, "/.codex/") || strings.Contains(path, "/.config/") {
if strings.Contains(path, "/.claude/") || strings.Contains(path, "/.codex/") || strings.Contains(path, "/.config/") ||
strings.Contains(path, "/.pi/") {
return "user"
}
return "project"
@@ -413,6 +416,7 @@ func (b *promptBuilder) splitMemory(text string) string {
at, body int
path, desc string
openCodeish bool
pi bool
}
var ss []section
for _, m := range contentsOf.FindAllStringSubmatchIndex(text, -1) {
@@ -421,6 +425,11 @@ func (b *promptBuilder) splitMemory(text string) string {
for _, m := range instructionsFrom.FindAllStringSubmatchIndex(text, -1) {
ss = append(ss, section{at: m[0], body: m[1], path: text[m[2]:m[3]], openCodeish: true})
}
if strings.Contains(text, piContext) {
for _, m := range piFile.FindAllStringSubmatchIndex(text, -1) {
ss = append(ss, section{at: m[0], body: m[1], path: text[m[2]:m[3]], pi: true})
}
}
if len(ss) == 0 {
return text
}
@@ -438,18 +447,98 @@ func (b *promptBuilder) splitMemory(text string) string {
rest.WriteString(chunk[j:])
chunk = chunk[:j]
}
// Pi's skills and closing lines after its last file aren't the file's
if s.pi {
if j := piFileEnd(chunk); j < len(chunk) {
rest.WriteString("\n" + strings.TrimLeft(chunk[j:], "\n"))
chunk = chunk[:j]
}
}
b.add(PartMemory, s.path, memoryTag(s.path, s.desc), tokensOf(chunk), txt("", chunk))
}
return rest.String()
}
// piContext heads the instruction files Pi puts in its system prompt,
// each under "## <path>", before its skills and its closing date and
// working directory lines.
const piContext = "# Project Context\n\nProject-specific instructions and guidelines:\n\n"
// piFileEnd is where a Pi instruction file's text ends: at Pi's skills,
// or its closing lines.
func piFileEnd(chunk string) int {
end := len(chunk)
if j := strings.Index(chunk, skillsBlockLead); j >= 0 {
end = j
}
if m := skillsBlock.FindStringIndex(chunk); m != nil && m[0] < end {
end = m[0]
}
if j := strings.Index(chunk, "\nCurrent date: "); j >= 0 && j < end {
end = j
}
return end
}
// skillsList heads the skills Claude Code lists, in its own prompt or a
// reminder; the list runs to the next blank line.
const skillsList = "The following skills are available for use with the Skill tool:"
// splitSkills takes the list of skills out of a text, as skills, and
// skillsBlock holds the skills of Pi and other agents on the Agent Skills
// standard (agentskills.io): <skill> entries in an <available_skills>
// block, after a paragraph on how to load them.
const (
skillsBlockEnd = "</available_skills>"
// Pi's paragraph before the block
skillsBlockLead = "The following skills provide specialized instructions"
)
// skillsBlock opens the block, on a line of its own, so prose naming the
// tag isn't taken for one.
var skillsBlock = lazyre.New(`(?m)^[ \t]*<available_skills>[ \t]*$`)
// splitSkills takes the lists of skills out of a text, as skills, and
// returns what is left.
func (b *promptBuilder) splitSkills(text, role string) string {
return b.splitSkillsBlock(b.splitSkillsList(text, role), role)
}
// splitSkillsBlock takes an <available_skills> block, and the paragraph
// leading it, out of a text.
func (b *promptBuilder) splitSkillsBlock(text, role string) string {
m := skillsBlock.FindStringIndex(text)
if m == nil {
return text
}
at := m[0]
n := strings.Index(text[at:], skillsBlockEnd)
if n < 0 {
return text
}
end := at + n + len(skillsBlockEnd)
// the paragraph before the block, when it is about the skills
before := strings.TrimRight(text[:at], "\n")
lead := 0
if p := strings.LastIndex(before, "\n\n"); p >= 0 {
lead = p + 2
}
if strings.HasPrefix(before[lead:], skillsBlockLead) {
at = lead
}
b.add(PartSkills, "skills", "skills", tokensOf(text[at:end]), txt(role, text[at:end]))
head := strings.TrimRight(text[:at], "\n")
tail := strings.TrimLeft(text[end:], "\n")
switch {
case head == "":
return b.splitSkillsBlock(tail, role)
case tail == "":
return head
}
return head + "\n\n" + b.splitSkillsBlock(tail, role)
}
// splitSkillsList takes Claude Code's list of skills out of a text.
func (b *promptBuilder) splitSkillsList(text, role string) string {
at := strings.Index(text, skillsList)
if at < 0 {
return text
+107
View File
@@ -357,3 +357,110 @@ func TestRouteTellsItsPrompt(t *testing.T) {
t.Fatalf("conversation %q", rs[0].Conv)
}
}
// Pi lists its skills in an <available_skills> block after a paragraph
// on loading them (pi-coding-agent 0.73.1's formatSkillsForPrompt, its
// bytes in testdata/context): the block and the paragraph are skills, on
// every protocol, and the system prompt keeps what is around them.
func TestPromptOfPiSkills(t *testing.T) {
raw, err := os.ReadFile("testdata/context/pi-0.73.1-system.txt")
if err != nil {
t.Fatal(err)
}
sys := string(raw)
at := strings.Index(sys, "The following skills provide specialized")
end := strings.Index(sys, "</available_skills>") + len("</available_skills>")
if at < 0 || end < at {
t.Fatal("fixture has no skills block")
}
block := sys[at:end]
b := newPromptBuilder()
rest := b.splitSkills(sys, "system")
if strings.Contains(rest, "<skill>") || strings.Contains(rest, "The following skills") {
t.Fatalf("the system prompt keeps the skills: %q", rest[max(0, len(rest)-400):])
}
if !strings.HasSuffix(rest, "Run `go test ./...` before you commit.\n\nCurrent date: 2026-11-19\nCurrent working directory: /home/u/proj") ||
!strings.HasPrefix(rest, "You are an expert coding assistant operating inside pi") {
t.Fatalf("what is around the block moved: %q", rest[max(0, len(rest)-200):])
}
if it, ok := itemOf(b.prompt(), PartSkills, "skills"); !ok || it.Tokens != tokensOf(block) {
t.Fatalf("skills %+v, want %d tokens", it, tokensOf(block))
}
str, _ := json.Marshal(sys)
for _, c := range []struct {
from provider.Protocol
body string
}{
{provider.Chat, `{"model":"m","messages":[{"role":"system","content":` + string(str) + `},{"role":"user","content":"hi"}]}`},
{provider.Anthropic, `{"model":"m","system":[{"type":"text","text":` + string(str) + `}],"messages":[{"role":"user","content":"hi"}]}`},
} {
p := promptOf(c.from, []byte(c.body))
if p == nil {
t.Fatalf("%s: no prompt", c.from)
}
sk, ok := itemOf(p, PartSkills, "skills")
if !ok || sk.Tokens != tokensOf(block) {
t.Fatalf("%s: skills %+v", c.from, partOf(p, PartSkills))
}
if s := partOf(p, PartSystem); s.Tokens <= 0 || s.Tokens > tokensOf(sys)-tokensOf(block)+2 {
t.Fatalf("%s: system %d tokens, the whole prompt is %d and its skills %d", c.from, s.Tokens, tokensOf(sys), tokensOf(block))
}
}
}
// An <available_skills> named in prose, or a block left open, isn't
// taken for skills.
func TestSplitSkillsBlockOnlyWhole(t *testing.T) {
for _, s := range []string{
"Agents on the standard list skills in an <available_skills> block.",
"Skills:\n\n<available_skills>\n <skill>\n <name>a</name>",
} {
b := newPromptBuilder()
if rest := b.splitSkills(s, "system"); rest != s {
t.Fatalf("%q became %q", s, rest)
}
if _, ok := itemOf(b.prompt(), PartSkills, "skills"); ok {
t.Fatalf("%q: skills", s)
}
}
}
// Pi's instruction files, each under "## <path>" in its "# Project
// Context" (pi-coding-agent 0.73.1's buildSystemPrompt), are memory, and
// its skills and closing lines after the last file aren't part of it.
func TestPromptOfPiMemory(t *testing.T) {
raw, err := os.ReadFile("testdata/context/pi-0.73.1-system.txt")
if err != nil {
t.Fatal(err)
}
str, _ := json.Marshal(string(raw))
p := promptOf(provider.Chat, []byte(`{"model":"m","messages":[{"role":"system","content":`+string(str)+`},{"role":"user","content":"hi"}]}`))
if p == nil {
t.Fatal("no prompt")
}
for path, tag := range map[string]string{"/home/u/.pi/agent/AGENTS.md": "user", "/home/u/proj/AGENTS.md": "project"} {
it, ok := itemOf(p, PartMemory, path)
if !ok || it.Tag != tag {
t.Fatalf("%s: %+v in %+v", path, it, partOf(p, PartMemory))
}
}
file := "## /home/u/proj/AGENTS.md\n\n# Project notes\n\nRun `go test ./...` before you commit.\n\n\n\n"
if it, _ := itemOf(p, PartMemory, "/home/u/proj/AGENTS.md"); it.Tokens != tokensOf(file) {
t.Fatalf("the last file holds %d tokens, its text is %d", it.Tokens, tokensOf(file))
}
if _, ok := itemOf(p, PartSkills, "skills"); !ok {
t.Fatalf("skills %+v", partOf(p, PartSkills))
}
b := newPromptBuilder()
if rest := b.splitSkills(b.splitMemory(string(raw)), "system"); strings.Contains(rest, "AGENTS.md") || strings.Contains(rest, "Run `go test") ||
!strings.HasSuffix(rest, "\nCurrent date: 2026-11-19\nCurrent working directory: /home/u/proj") || !strings.Contains(rest, piContext) {
t.Fatalf("system prompt %q", rest[max(0, len(rest)-300):])
}
// without Pi's header, a "## /path/AGENTS.md" line is the prompt's own
b = newPromptBuilder()
if s := "Notes.\n\n## /p/AGENTS.md\n\nkeep this"; b.splitMemory(s) != s {
t.Fatal("a heading outside Pi's context was taken")
}
}
+69
View File
@@ -0,0 +1,69 @@
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:
- read: Read file contents
- bash: Execute bash commands (ls, grep, find, etc.)
- edit: Make precise file edits with exact text replacement, including multiple disjoint edits in one call
- write: Create or overwrite files
In addition to the tools above, you may have access to other custom tools depending on the project.
Guidelines:
- Use bash for file operations like ls, rg, find
- Use read to examine files instead of cat or sed.
- Use edit for precise changes (edits[].oldText must match exactly)
- When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls
- Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.
- Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.
- Use write only for new files or complete rewrites.
- Be concise in your responses
- Show file paths clearly when working with files
Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):
- Main documentation: /home/u/.npm-global/lib/node_modules/@mariozechner/pi-coding-agent/README.md
- Additional docs: /home/u/.npm-global/lib/node_modules/@mariozechner/pi-coding-agent/docs
- Examples: /home/u/.npm-global/lib/node_modules/@mariozechner/pi-coding-agent/examples (extensions, custom tools, SDK)
- 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)
- 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)
# Project Context
Project-specific instructions and guidelines:
## /home/u/.pi/agent/AGENTS.md
# Global
## Style
- Reply in English.
## /home/u/proj/AGENTS.md
# Project notes
Run `go test ./...` before you commit.
The following skills provide specialized instructions for specific tasks.
Use the read tool to load a skill's file when the task matches its description.
When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.
<available_skills>
<skill>
<name>pdf</name>
<description>Fill, merge &amp; split PDF files. Use when the task names a .pdf.</description>
<location>/home/u/.pi/agent/skills/pdf/SKILL.md</location>
</skill>
<skill>
<name>release-notes</name>
<description>Write release notes from the git log since the last tag.</description>
<location>/home/u/proj/.pi/skills/release-notes/SKILL.md</location>
</skill>
</available_skills>
Current date: 2026-11-19
Current working directory: /home/u/proj