Skip to content
Back to search

pi-prompt-template-model

Pi extension: Add model frontmatter to prompt templates for automatic model switching

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/nicobailon--pi-prompt-template-model/badge.svg)](/listings/nicobailon--pi-prompt-template-model)

HTML

<a href="/listings/nicobailon--pi-prompt-template-model"><img src="/api/listings/nicobailon--pi-prompt-template-model/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

pi install npm:pi-prompt-template-model

Restart pi to load the extension.

For delegated subagent execution (`subagent` and `inheritContext` frontmatter), install [pi-subagents](https://github.com/nicobailon/pi-subagents/) separately:

pi install npm:pi-subagents

pi-subagents is optional — everything else works without it. Using `subagent: true` without it installed fails fast with a clear error.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 819 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p>
  2. <img src="banner.png" alt="pi-prompt-template-model" width="1100">
  3. </p>
  4. # Prompt Template Model Extension
  5. Adds `model`, `skill`, and `thinking` frontmatter to pi prompt templates. Define slash commands that switch to the right model, set a thinking level, inject skill context, and auto-restore your session when done.
  6. ```
  7. /debug-python my code crashes
  8. → switches to Sonnet, loads tmux skill, agent responds
  9. → restores your previous model when finished
  10. ```
  11. ## Why?
  12. Each prompt template becomes a self-contained agent mode. `/quick-debug` spins up a cheap model with REPL skills. `/deep-analysis` brings in extended thinking with refactoring expertise. When the command finishes, you're back to your daily driver without touching anything.
  13. No more manually switching models, no hoping the agent picks up on the right skill. You define the configuration once, and the slash command handles the rest.
  14. ## Installation
  15. ```bash
  16. pi install npm:pi-prompt-template-model
  17. ```
  18. Restart pi to load the extension.
  19. For delegated subagent execution (`subagent` and `inheritContext` frontmatter), install [pi-subagents](https://github.com/nicobailon/pi-subagents/) separately:
  20. ```bash
  21. pi install npm:pi-subagents
  22. ```
  23. pi-subagents is optional — everything else works without it. Using `subagent: true` without it installed fails fast with a clear error.
  24. ## Quick Start
  25. Add `model` and optionally `skill` to any prompt template:
  26. ```markdown
  27. ---
  28. description: Debug Python in tmux REPL
  29. model: claude-sonnet-4-20250514
  30. skill: tmux
  31. ---
  32. Start a Python REPL session and help me debug: $@
  33. ```
  34. Run `/debug-python some issue` and the agent switches to Sonnet, receives the tmux skill as context, and starts working. When it finishes, your previous model is restored. If Pi is compacting or finishing a turn, the slash command waits until the session can accept the generated prompt.
  35. ## Prompt Discovery
  36. The extension scans the default prompt directories and the same local prompt paths Pi loads from `settings.json`:
  37. - User defaults: `~/.pi/agent/prompts/`
  38. - Project defaults: `<cwd>/.pi/prompts/`
  39. - User settings: `~/.pi/agent/settings.json` `prompts` entries
  40. - Project settings: `<cwd>/.pi/settings.json` `prompts` entries
  41. Settings entries may point at directories or individual `.md` files. Absolute paths and `~/...` work. Relative user settings paths resolve from `~/.pi/agent`; relative project settings paths resolve from `<cwd>/.pi`. Pattern entries follow Pi's settings behavior: glob-style entries filter configured prompt paths, and `!`, `+`, or `-` entries exclude or force exact matches.
  42. Precedence follows Pi's local-resource order: project settings, project defaults, user settings, then user defaults. If the same file is reachable through both settings and a default directory, it is loaded once by canonical path. Malformed settings files or invalid configured paths produce warnings while the rest of discovery continues.
  43. ## Frontmatter Reference
  44. All fields are optional. Templates that don't use any extension features (no `model`, `skill`, `thinking`, etc.) are left to pi's default prompt loader.
  45. ### Core Fields
  46. | Field | Default | What it does |
  47. |-------|---------|--------------|
  48. | `model` | current session model | Which model to use. Accepts a single model, a `provider/model-id` pair, or a comma-separated fallback list (see [Model Format](#model-format)). Ignored when `chain` is set. |
  49. | `skill` | — | Loads one or more skills. Accepts one name, comma-separated names, or a YAML array; each entry may use the optional `skill:` prefix. Inline runs inject the full content before the agent turn, while delegated runs bind resolved name/path metadata to the outbound request. See [Skill Resolution](#skill-resolution). |
  50. | `thinking` | — | Thinking level for the model: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`. |
  51. | `description` | — | Short text shown next to the command in autocomplete. |
  52. | `chain` | — | Declares a reusable pipeline of templates (`step -> step`). When set, the body is ignored. See [Chain Templates](#chain-templates). |
  53. | `chainContext` | — | Chain templates only. Set to `summary` so delegated steps receive a compact summary of what previous steps did. Steps with `inheritContext: true` are excluded. See [Chain context for delegated steps](#chain-context-for-delegated-steps). |
  54. ### Execution Control
  55. | Field | Default | What it does |
  56. |-------|---------|--------------|
  57. | `restore` | `true` | After the command finishes, switch back to whatever model and thinking level were active before. Set `false` to stay on the new model. |
  58. | `loop` | — | Run this template multiple times by default (1–999, `true`, or `unlimited`). CLI `--loop` overrides this. See [Loop Execution](#loop-execution). |
  59. | `rotate` | `false` | When `true` and looping, cycle through models in the `model` list instead of using fallback semantics. Thinking levels can also be comma-separated to pair with each model. |
  60. | `fresh` | `false` | When looping, collapse the conversation between iterations to a brief summary instead of carrying the full context forward. Saves tokens on long loops. |
  61. | `converge` | `true` | When looping, stop early if an iteration makes no file changes. Set `false` to always run every iteration. |
  62. | `boomerang` | `false` | After a non-chain prompt finishes, collapse its execution context back to the branch point with a brief summary. Works with loops, including `fresh` loop summaries. Useful for review prompts like `/double-check`. |
  63. | `worktree` | `false` | When `true`, parallel delegated work runs in separate git worktrees. Valid on chain templates with `parallel()` steps, on delegated prompts with `parallel: N`, and on compare templates via `bestOfN.worktree`. |
  64. ### Delegation
  65. | Field | Default | What it does |
  66. |-------|---------|--------------|
  67. | `subagent` | — | Delegate execution to a subagent instead of running in the current session. `true` uses the default `delegate` agent; a string value like `reviewer` targets that specific agent. Requires [pi-subagents](https://github.com/nicobailon/pi-subagents/). |
  68. | `inheritContext` | `false` | Only meaningful with `subagent`. When `true`, the subagent receives a fork of the current conversation context instead of starting fresh. |
  69. | `parallel` | — | Delegated prompts only. Repeats the same subagent in parallel `N` times. Each copy gets a slot header like `[Parallel subagent 2/3]` prepended to the task. Must be an integer greater than or equal to 2. |
  70. | `bestOfN` | — | Compare templates only. Nested compare authoring block with `workers`, `reviewers`, optional `finalApplier`, and optional `worktree`. Top-level compare fields are not supported in templates. |
  71. | `bestOfN.workers` | — | Ordered worker lineup used for the worker phase. Each slot object supports optional `agent`/`subagent`, optional `model`, optional `task`, optional `taskSuffix`, optional `cwd`, and optional `count`. If both `agent` and `subagent` are omitted, the default agent is `delegate`. |
  72. | `bestOfN.reviewers` | — | Ordered reviewer lineup used after worker aggregation. Slot shape matches workers. If both `agent` and `subagent` are omitted, the default agent is `reviewer`. |
  73. | `bestOfN.finalApplier` | — | Optional single-slot final apply phase that edits the real branch after reviewers. Supports optional `agent`/`subagent`, optional `model`, optional `task`, and optional `taskSuffix`. If both `agent` and `subagent` are omitted, the default agent is `delegate`. `count` and `cwd` are not supported. Requires `bestOfN.worktree: true` at runtime. |
  74. | `cwd` | — | Working directory for delegated subagent subprocesses. Must be an absolute path (`~/...` is expanded). Valid with `subagent`, on chain templates as the default cwd for delegated steps, and on compare prompts as the default repo cwd. Worker/reviewer slots can also set their own `cwd` inside `bestOfN.workers` / `bestOfN.reviewers`. |
  75. ## Model Format
  76. ```yaml
  77. model: claude-sonnet-4-20250514 # bare model ID — auto-selects provider
  78. model: anthropic/claude-sonnet-4-20250514 # explicit provider/model
  79. ```
  80. Bare model IDs resolve through a provider priority list: `openai-codex` → `anthropic` → `github-copilot` → `openrouter`. The first provider with valid auth wins.
  81. For explicit control:
  82. ```yaml
  83. model: anthropic/claude-opus-4-5 # Direct Anthropic API
  84. model: openai-codex/gpt-5.2 # Via Codex subscription (OAuth)
  85. model: github-copilot/claude-opus-4-5 # Via Copilot subscription
  86. model: openrouter/claude-opus-4-5 # Via OpenRouter
  87. model: openai/gpt-5.2 # Direct OpenAI API
  88. ```
  89. ### Model Fallback
  90. Comma-separated lists try each model in order:
  91. ```yaml
  92. model: claude-haiku-4-5, claude-sonnet-4-20250514
  93. ```
  94. Haiku is tried first. If it can't be found or has no API key, Sonnet is used instead. If the session is already on one of the listed models, that one is kept without switching. When every candidate fails, you get a single error listing what was tried.
  95. You can mix bare IDs and explicit provider specs:
  96. ```yaml
  97. model: anthropic/claude-haiku-4-5, openrouter/claude-haiku-4-5, claude-sonnet-4-20250514
  98. ```
  99. ## Skills
  100. Normally, pi lists available skills in the system prompt, the agent reads your task, decides which skill it needs, and loads it with the read tool. That's an extra round-trip, and the agent might not pick the right one.
  101. The `skill` field bypasses all of that:
  102. ```markdown
  103. ---
  104. description: Browser testing mode
  105. model: claude-sonnet-4-20250514
  106. skill: surf
  107. ---
  108. $@
  109. ```
  110. For inline runs, every skill is resolved first and its full content is injected in a separate `<skill name="...">` block within one context message before the agent processes your task. For single delegated runs, skill bodies are not prepended to the task; the outbound pi-subagents request uses the versioned `skill` field with resolved skill names. Parallel delegated runs also resolve every declared skill before emitting the request and carry name-only `skill` metadata per task for compatible bridges. If any declared skill can't be found or read, the command fails before the inline turn or delegated request starts.
  111. ### Skill Resolution
  112. The `skill` field accepts one name, comma-separated names, or a YAML array. Entries are trimmed, empty entries are dropped, duplicates keep their first position, and each entry may use a `skill:` prefix:
  113. ```yaml
  114. skill: tmux
  115. skill: tmux, skill:browser
  116. skill:
  117. - tmux
  118. - skill:browser
  119. ```
  120. Resolution order:
  121. 1. Registered skill commands from `pi.getCommands()` (source: `"skill"`)
  122. 2. `<cwd>/.pi/skills/<name>/SKILL.md` or `<cwd>/.pi/skills/<name>.md` when project trust is enabled
  123. 3. `.agents/skills` in the current directory and ancestors (up to the git root) when project trust is enabled
  124. 4. `~/.pi/agent/skills/<name>/SKILL.md` or `~/.pi/agent/skills/<name>.md`
  125. 5. `~/.agents/skills/<name>/SKILL.md` or `~/.agents/skills/<name>.md`
  126. ## Inline Model Conditionals
  127. Prompt bodies can include sections that only render for specific models:
  128. ```markdown
  129. ---
  130. description: Cross-model code review
  131. model: claude-haiku-4-5, claude-sonnet-4-20250514
  132. ---
  133. Summarize the change first.
  134. <if-model is="claude-haiku-4-5">
  135. Keep the answer brief and cost-conscious.
  136. <else>
  137. Do a deeper pass and call out subtle risks.
  138. </if-model>
  139. ```
  140. Conditionals evaluate against whichever model actually runs — after fallback resolution for multi-model templates, or against the session model when `model` is omitted.
  141. The `is` attribute supports exact model IDs, `provider/model-id` pairs, provider wildcards like `anthropic/*`, and comma-separated combinations:
  142. ```markdown
  143. <if-model is="anthropic/*">Anthropic-specific instructions</if-model>
  144. <if-model is="openai/gpt-5.2, anthropic/*">Either OpenAI or Anthropic</if-model>
  145. ```
  146. `<else>` is the fallback branch. Nested `<if-model>` blocks work.
  147. ## Argument Substitution
  148. Prompt bodies support placeholders that expand to the arguments passed after the command name:
  149. | Placeholder | Expands to |
  150. |-------------|------------|
  151. | `$1`, `$2`, ... | The Nth argument (1-indexed) |
  152. | `$@` or `@$` or `$ARGUMENTS` | All arguments joined with spaces |
  153. | `${@:N}` | All arguments from position N onward |
  154. | `${@:N:L}` | L arguments starting from position N |
  155. ```markdown
  156. ---
  157. model: claude-sonnet-4-20250514
  158. ---
  159. Analyze $1 focusing on $2. Additional context: ${@:3}
  160. ```
  161. `/analyze src/main.ts performance edge cases error handling` expands `$1` to `src/main.ts`, `$2` to `performance`, and `${@:3}` to `edge cases error handling`.
  162. ## Delegated Subagent Execution
  163. Instead of running a prompt in the current session, you can hand it off to a subagent:
  164. ```markdown
  165. ---
  166. model: anthropic/claude-sonnet-4-20250514
  167. subagent: true
  168. ---
  169. Review and simplify this code: $@
  170. ```
  171. `subagent: true` delegates to the default `delegate` agent. To target a specific agent:
  172. ```markdown
  173. ---
  174. model: anthropic/claude-sonnet-4-20250514
  175. subagent: reviewer
  176. inheritContext: true
  177. ---
  178. Audit this diff for correctness and edge cases: $@
  179. ```
  180. `inheritContext: true` forks the current conversation so the subagent has full context. Without it, the subagent starts fresh. Declared skills are resolved against the delegated `cwd` and sent as skill names on the delegation request; their bodies are never prepended to delegated task text.
  181. To force a subagent into a specific working directory, add `cwd`:
  182. ```markdown
  183. ---
  184. model: claude-sonnet-4-20250514
  185. subagent: browser-screenshoter
  186. cwd: /tmp/screenshots
  187. ---
  188. Use url in the prompt to take screenshot: $@
  189. ```
  190. The subagent process runs with `/tmp/screenshots` as its working directory. Paths must be absolute (`~/...` is expanded). The directory is validated at execution time.
  191. To fan the same delegated prompt out to multiple copies in parallel, add `parallel: N`:
  192. ```markdown
  193. ---
  194. model: anthropic/claude-sonnet-4-20250514
  195. subagent: simplifier
  196. inheritContext: true
  197. parallel: 3
  198. worktree: true
  199. ---
  200. Review changed code and fix any issues found.
  201. ```
  202. This expands to three parallel `pi-subagents` tasks targeting the same agent. Each one receives the same rendered prompt plus an automatic slot header like `[Parallel subagent 1/3]`, `[Parallel subagent 2/3]`, and `[Parallel subagent 3/3]` so the body can assign different roles to each copy. `worktree: true` is optional here and gives each parallel run its own git worktree.
  203. During execution, a live progress widget appears above the editor showing elapsed time, tool count, token usage, and the current tool. When the run finishes, it's replaced by a completion card with the task preview, tool call history, output, and usage stats.
  204. You can override delegation at runtime per invocation with `--subagent`, `--subagent=<name>`, `--subagent:<name>`, or `--cwd=<path>`. `--cwd=<path>` must be absolute after optional `~/...` expansion. Runtime flags take precedence for that invocation only.
  205. Two additional runtime flags work for any prompt (not just delegated ones):
  206. - `--model=provider/model-id` — override the template's `model` for this invocation. Works with single execution, loops, and delegation.
  207. - `--fork` — run with `inheritContext` (forked context). Implies `--subagent` if not already set.
  208. ```
  209. /double-check --model=anthropic/claude-opus-4-6
  210. /double-check --fork --subagent:worker
  211. /deslop --model=openai/gpt-5.4 --loop 3
  212. ```
  213. Compare templates also accept runtime lineup overrides:
  214. Prompt-template frontmatter authoring uses `bestOfN:`. Runtime overrides stay on the low-level flags below.
  215. - `--workers=<json-array>` / `--reviewers=<json-array>` replace the corresponding frontmatter lineup.
  216. - `--workers-append=<json-array>` / `--reviewers-append=<json-array>` append to the corresponding lineup.
  217. - `--final-applier=<json-object-or-one-element-array>` replaces the optional final apply slot.
  218. Each worker/reviewer JSON array entry must be an object with either `subagent` or `agent`, plus optional `model`, `task`, `taskSuffix`, `cwd`, and `count`. In worker slots, `"subagent": true` maps to `delegate`. In reviewer slots, `"subagent": true` maps to `reviewer`. `--final-applier=` accepts one slot object (or a one-element array) with `subagent`/`agent`, optional `model`, optional `task`, and optional `taskSuffix`; for this final slot, `"subagent": true` maps to `delegate`, and both `count` and `cwd` are not supported.
  219. ## Best-of-N Compare Prompt
  220. This repo ships one example compare prompt under `examples/`:
  221. - `examples/best-of-n.md` installs as `/best-of-n`, runs in the current repo, and shows mixed workers, mixed reviewers, and an optional final apply phase.
  222. - Smoke test: `/best-of-n smoke test`.
  223. Install it manually from this repo checkout (or from the installed package directory):
  224. ```bash
  225. PTM_DIR=/path/to/pi-prompt-template-model
  226. mkdir -p ~/.pi/agent/prompts
  227. cp "$PTM_DIR/examples/best-of-n.md" ~/.pi/agent/prompts/best-of-n.md
  228. ```
  229. After copying the file, restart `pi` if it is already running. The prompt then runs an explicit compare flow:
  230. Compare prompt templates are authored under `bestOfN:`. Top-level `workers`, `reviewers`, and `finalApplier` frontmatter fields are rejected with migration diagnostics.
  231. 1. Worker phase: run the worker lineup in parallel (`context: fork`) so workers generate candidate implementations in temporary worktrees.
  232. 2. Continue as long as at least one worker succeeds. Reviewer slots receive successful worker outputs plus worker/worktree summaries and produce findings only.
  233. 3. Optional final apply phase: if `finalApplier` is configured, run one delegated apply step on the real compare repo (`compareCwd`) to pick a winner or synthesize/cherry-pick and apply the final patch.
  234. 4. If all reviewers fail but `finalApplier` exists, the final apply step still runs with fallback context from workers plus reviewer failure summaries.
  235. Worker/reviewer lineups are fully configurable from `bestOfN` frontmatter or runtime overrides, so there is no fixed three-model worker assumption. If a compare prompt omits `bestOfN.workers`, it falls back to one `delegate` worker using the current/main model. If it omits `bestOfN.reviewers`, it falls back to one `reviewer` slot. `bestOfN.finalApplier` is optional, and compare runs reject an effective final applier unless `bestOfN.worktree: true` is set.
  236. For same-model best-of-N, use `count: N` on one worker slot:
  237. ```yaml
  238. bestOfN:
  239. workers:
  240. - model: openai-codex/gpt-5.4:low
  241. count: 4
  242. ```
  243. You can also mix models and give each slot its own count:
  244. ```yaml
  245. bestOfN:
  246. workers:
  247. - model: openai-codex/gpt-5.4:low
  248. count: 3
  249. - model: google/gemini-2.5-pro:medium
  250. count: 2
  251. - model: anthropic/claude-sonnet-4-20250514:high
  252. ```
  253. Reviewer slots support the same lineup shape, and `bestOfN.finalApplier` is one optional single-slot final apply step:
  254. ```yaml
  255. bestOfN:
  256. reviewers:
  257. - model: openai-codex/gpt-5.4:low
  258. count: 2
  259. - model: google/gemini-2.5-pro:medium
  260. taskSuffix: Focus on regression risk.
  261. finalApplier:
  262. model: anthropic/claude-sonnet-4-20250514:high
  263. taskSuffix: Apply the final patch on the current branch and report verification.
  264. ```
  265. Within compare lineups, omitting both `agent` and `subagent` uses phase defaults: `delegate` in workers, `reviewer` in reviewers, and `delegate` in finalApplier. You can still set explicit `agent` or `subagent` when needed.
  266. Explicitly repeating the same slot still works, but `count: N` is the cleaner shorthand when the slot is identical.
  267. Within a compare lineup, use `task` for a full per-slot override and `taskSuffix` for a small per-slot append. `taskSuffix` is added after the shared worker task (or after the slot's `task` if you set one), which makes it the better fit for things like per-model output file names.
  268. When a compare prompt uses `bestOfN.worktree: true`, all worker slots must resolve to the same `cwd`. Mixed worker `cwd` values are only allowed when worktree isolation is off. Worktree isolation is for the worker phase only; `bestOfN.finalApplier` always applies on the real branch (`compareCwd`).
  269. ## Deterministic Steps
  270. Prompt templates can run one deterministic command or script before any optional LLM turn. Use this when the first step should be direct code, not model latency.
  271. The flow is simple:
  272. 1. Run one command or script.
  273. 2. Always render a visible deterministic result card with the command, exit code, duration, and stdout/stderr previews.
  274. 3. Optionally hand the structured result to the model as a `[Deterministic step]` preamble before the prompt body.
  275. 4. If `handoff: never`, stop after the result card and a visible completion marker — no LLM turn happens.
  276. That handoff preamble is intentionally structured and uses stable field names like `status`, `executionKind`, `command`, `cwd`, `exitCode`, `signal`, `durationMs`, `timedOut`, `lineCount`, `charCount`, `truncated`, `omittedChars`, and `preview`.
  277. V1 scope is intentionally narrow: deterministic execution only works on single prompt templates. It does not combine with chain templates, delegated/subagent prompts, `parallel`, or loops. At runtime, deterministic prompts explicitly reject `--loop`, `--subagent`, and `--fork` in v1.
  278. ### Authoring forms
  279. You can write deterministic steps as **top-level shorthand** or **nested under `deterministic:`**. Both are equivalent. Use shorthand for brevity, nested when you want everything grouped under one key.
  280. **Top-level shorthand** — put `run`, `script`, `handoff`, `timeout`, `cwd`, `env`, and `nonInteractive` directly in frontmatter:
  281. ```markdown
  282. ---
  283. run: git push origin HEAD:main
  284. handoff: on-failure
  285. timeout: 30000
  286. ---
  287. If the push failed, explain why and suggest the next step.
  288. ```
  289. You can also use `script:` as shorthand:
  290. ```markdown
  291. ---
  292. script: ./scripts/ship.sh
  293. handoff: always
  294. timeout: 15000
  295. ---
  296. Summarize the script result.
  297. ```
  298. **Nested form** — group everything under `deterministic:`:
  299. ```markdown
  300. ---
  301. model: claude-sonnet-4-20250514
  302. deterministic:
  303. script:
  304. path: ./scripts/ship.sh
  305. args:
  306. - --fast
  307. handoff: always
  308. timeout: 15000
  309. cwd: ~/src/my-repo
  310. ---
  311. Summarize the script result and call out anything risky.
  312. ```
  313. **Structured command form** — when you need explicit args instead of a single shell string, use `deterministic.run.command` with `args`:
  314. ```markdown
  315. ---
  316. model: claude-sonnet-4-20250514
  317. deterministic:
  318. run:
  319. command: git
  320. args: [status, --short]
  321. handoff: always
  322. ---
  323. Interpret the repo state.
  324. ```
  325. Do not mix top-level shorthand with nested `deterministic:` in the same prompt. Pick one style.
  326. ### Model requirement
  327. Deterministic prompts that hand off to the model (`handoff: always`, `on-success`, or `on-failure`) need a model to continue into. You can either:
  328. - Add a `model:` field explicitly
  329. - Omit `model:` and let the prompt inherit whatever model is currently active
  330. `handoff: never` prompts do not need a model field because they never reach the LLM.
  331. ### Handoff values
  332. - `always` — always continue into the LLM after the deterministic card is emitted.
  333. - `never` — stop after the deterministic card and completion marker.
  334. - `on-success` — continue only when the command exits `0`.
  335. - `on-failure` — continue only when the command exits non-zero.
  336. Command descriptions in the slash-command picker show this feature as `deterministic-step:<handoff>`.
  337. ### Timeout
  338. `timeout` is in milliseconds. When a timeout fires, the runner sends `SIGTERM` first. If the process still has not exited after a short grace window, it escalates to `SIGKILL`.
  339. ### Script path resolution
  340. Relative script paths resolve from the prompt file's directory first, then fall back to the command invocation `cwd`. Absolute script paths also work.
  341. ### Environment and non-interactive mode
  342. You can provide explicit environment variables and control the runner's non-interactive guardrails:
  343. ```markdown
  344. ---
  345. deterministic:
  346. run: ./deploy.sh
  347. handoff: never
  348. nonInteractive: false
  349. env:
  350. SPECIAL_TOKEN: abc123
  351. RETRIES: 2
  352. ---
  353. ```
  354. `nonInteractive` defaults to `true`. In that mode the runner keeps stdin ignored and adds a few guardrail environment defaults such as `CI=1`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`, and `GIT_PAGER=cat`. Set `nonInteractive: false` when the command needs a more normal process environment and you explicitly want to opt out of those defaults. Explicit `env` values override the built-in defaults.
  355. ### Output capping
  356. Large stdout/stderr streams are capped before they are stored in the conversation card payload. The card and the LLM handoff block both show the total character and line counts plus explicit truncation metadata when output was capped.
  357. ## Loop Execution
  358. Run a template multiple times with `--loop`:
  359. ```
  360. /deslop --loop 5
  361. /deslop --loop=5
  362. /deslop --loop # unlimited — runs until convergence or cap (999)
  363. ```
  364. You can also set a default in frontmatter. CLI `--loop` always overrides:
  365. ```markdown
  366. ---
  367. loop: 5
  368. ---
  369. ```
  370. Use `loop: unlimited` (or `loop: true`) for open-ended loops that run until convergence, user interrupt, or the safety cap of 999 iterations:
  371. ```markdown
  372. ---
  373. loop: unlimited
  374. converge: false
  375. fresh: true
  376. subagent: true
  377. ---
  378. ```
  379. ### How looping works
  380. Each iteration runs the same prompt. By default, context accumulates — iteration 3 sees the full conversation from iterations 1 and 2 and builds on that work.
  381. **Convergence**: If an iteration makes no file changes (no `write` or `edit` tool calls), the loop stops early. This is on by default. Use `--no-converge` or `converge: false` to always run every iteration.
  382. **Fresh context**: Add `--fresh` (or `fresh: true` in frontmatter) to collapse the conversation between iterations. Each iteration gets a clean slate with only brief summaries of what previous iterations did. Good for long loops where accumulated context would blow up the token count.
  383. **Status**: The TUI status bar shows `loop 2/5` during execution.
  384. Model, thinking level, and skill are maintained throughout. If `restore: true` (the default), everything is restored after the final iteration.
  385. ## Model Rotation
  386. `rotate: true` turns a comma-separated `model` list from a fallback chain into a cycling list. Each loop iteration uses the next model in the list, wrapping around:
  387. ```markdown
  388. ---
  389. model: claude-opus-4-6, gpt-5.4, gpt-5.3-codex
  390. thinking: high, max, off
  391. loop: 9
  392. rotate: true
  393. fresh: true
  394. ---
  395. Review and fix issues in this codebase.
  396. ```
  397. Iteration 1 runs Opus + `high`, iteration 2 runs GPT-5.4 + `max`, iteration 3 runs Codex + `off`, then wraps back to Opus. The status bar shows which model is active: `loop 2/9 · gpt-5.4 max`.
  398. This is especially useful for [ralph-style loops](https://ghuntley.com/ralph/) where different models catch different things. The `subagent` examples below require [pi-subagents](https://github.com/nicobailon/pi-subagents/). A single-model ralph loop that delegates with fresh context each iteration:
  399. ```markdown
  400. ---
  401. model: claude-sonnet-4-20250514
  402. subagent: true
  403. inheritContext: true
  404. loop: 5
  405. fresh: true
  406. ---
  407. Simplify this code: $@
  408. ```
  409. Add `rotate` and multiple models to cycle different perspectives on each pass:
  410. ```markdown
  411. ---
  412. model: claude-opus-4-6, gpt-5.4, gpt-5.3-codex
  413. thinking: max, high, high
  414. loop: 9
  415. rotate: true
  416. fresh: true
  417. subagent: true
  418. ---
  419. Review and fix issues in this codebase.
  420. ```
  421. Each iteration gets fresh context, a different model, and its own thinking level. Convergence stops the loop when an iteration makes no file changes — use `converge: false` to guarantee every model gets at least one shot.
  422. `thinking` pairing with `rotate: true`:
  423. - Single value (`thinking: high`) — applied to every model.
  424. - Comma-separated (`thinking: high, max, off`) — positional, must match the number of models.
  425. - Omitted — each iteration inherits the session default.
  426. Without `loop`, `rotate` has no effect and comma-separated `model` keeps normal fallback behavior.
  427. ## Chaining Templates
  428. `/chain-prompts` runs multiple templates in sequence. Each step uses its own model, skill, and thinking level, while conversation context flows between them:
  429. ```
  430. /chain-prompts analyze-code -> fix-plan -> summarize -- src/main.ts
  431. ```
  432. This runs `analyze-code`, then `fix-plan` (which sees the analysis), then `summarize`. The ` -- ` separator marks shared args — everything after it is passed to each step as `$@`, unless a step has its own inline args:
  433. ```
  434. /chain-prompts analyze-code "error handling" -> fix-plan -> summarize -- src/main.ts
  435. ```
  436. Step 1 gets `"error handling"` as its args. Steps 2 and 3 fall back to the shared `"src/main.ts"`.
  437. The chain captures your model and thinking level before starting and restores them when finished (or if any step fails).
  438. ### Chain Templates
  439. For reusable pipelines, put the chain in frontmatter:
  440. ```markdown
  441. ---
  442. description: Review then clean up
  443. chain: double-check --loop 2 -> deslop --loop 2
  444. ---
  445. ```
  446. This registers the file's name as a command that runs `double-check` twice, then `deslop` twice. Per-step `--loop N` repeats that step before moving to the next, with per-step convergence (stops early if no changes, unless the step's template has `converge: false`).
  447. Chain declarations also support parallel groups with `parallel(...)`:
  448. ```markdown
  449. ---
  450. chain: parallel(scan-frontend, scan-backend) -> consolidate
  451. ---
  452. ```
  453. Each entry inside `parallel(...)` runs as a delegated subagent task concurrently. Parallel entries can include per-step args (for example `parallel(scan-frontend, scan-backend "auth")`), but per-step `--loop` is not supported inside parallel groups. Nested `parallel(...)` is rejected. Parallel entries must be delegated templates (`subagent: ...` or runtime `--subagent` override). All entries in the same parallel group must resolve to the same `inheritContext` mode. Mixed `cwd` values are allowed normally, but when `worktree: true` is enabled they must all resolve to the same `cwd`.
  454. Add `worktree: true` (or `--worktree` at runtime) so each parallel subagent runs in its own git worktree, avoiding file conflicts when agents edit concurrently:
  455. ```markdown
  456. ---
  457. chain: parallel(scan-frontend, scan-backend) -> consolidate
  458. worktree: true
  459. ---
  460. ```
  461. `worktree` requires a chain with at least one `parallel()` step. The flag is passed to pi-subagents, which handles worktree creation and cleanup.
  462. Steps with a `model` field use their own model. Steps without one inherit a snapshot of whatever model was active when the chain started — not the previous step's model. This keeps behavior deterministic regardless of what earlier steps do.
  463. Chain templates support `loop`, `fresh`, `converge`, `restore`, `worktree`, and `cwd` in their frontmatter for controlling the overall execution:
  464. ```markdown
  465. ---
  466. chain: analyze -> fix
  467. loop: 3
  468. fresh: true
  469. converge: false
  470. ---
  471. ```
  472. This runs the full analyze → fix chain 3 times, with fresh context between iterations and no early stopping. Chain nesting is not supported — steps can't reference other chain templates.
  473. When a chain template sets `cwd`, it becomes the default delegated subprocess working directory for all delegated steps in that chain. Runtime `--cwd=<path>` overrides the chain template value.
  474. ### Chain context for delegated steps
  475. Delegated chain steps start fresh — they don't see what earlier steps did. Chain context prepends a compact summary of previous steps to each delegated task so later steps can build on earlier work.
  476. Enable it chain-wide with `chainContext: summary` in frontmatter or `--chain-context` on the CLI:
  477. ```markdown
  478. ---
  479. chain: analyze -> fix
  480. chainContext: summary
  481. ---
  482. ```
  483. ```
  484. /chain-prompts analyze -> fix --chain-context
  485. ```
  486. To enable it for a single step, attach `--with-context` to that step name:
  487. ```
  488. /chain-prompts analyze -> reviewer --with-context -> summarize
  489. ```
  490. Here only `reviewer` receives the summary of `analyze`. The `summarize` step does not.
  491. Steps using `inheritContext: true` already fork the full parent conversation and skip the summary preamble. `--with-context` is not supported inside `parallel(...)` groups. When a chain uses `loop`, summaries reset each iteration.
  492. ### Parallel and looping from the CLI
  493. Parallel groups work in `/chain-prompts` too:
  494. ```
  495. /chain-prompts parallel(scan-fe, scan-be) -> review
  496. /chain-prompts parallel(scan-fe, scan-be) -> review --worktree
  497. ```
  498. Looping applies to the entire chain:
  499. ```
  500. /chain-prompts analyze -> fix --loop 3
  501. /chain-prompts analyze -> fix --loop 3 --fresh
  502. /chain-prompts analyze -> fix --loop 3 --no-converge
  503. /chain-prompts analyze -> fix --loop
  504. ```
  505. Convergence applies across all steps in each iteration — if no step made file changes, the loop stops. Templates are re-read from disk between iterations, so edits take effect live.
  506. ## Prompt Invocation Events
  507. External orchestrators can request prompt execution through the prompt invocation event channel. An accepted request emits one `prompt-template:prompt:started` event and one terminal `prompt-template:prompt:finished` event for the acknowledged `runId`.
  508. The event channel fails closed for prompt types that cannot guarantee bounded completion. Deterministic prompts must set `timeout` to be accepted through events. Delegated prompts, runtime `--subagent` or `--fork` invocations, and compare lineups are refused through events for now with `accepted: false` and `reason: "unsupported-context"`. Interactive slash commands keep the existing behavior.
  509. ## Agent Tool
  510. The agent can invoke prompt templates itself via a `run-prompt` tool. It's off by default:
  511. ```
  512. /prompt-tool on
  513. ```
  514. Once enabled, the agent sees `run-prompt` in its tool list:
  515. ```
  516. run-prompt({ command: "deslop --loop 5 --fresh" })
  517. run-prompt({ command: "chain-prompts analyze -> fix --chain-context" })
  518. run-prompt({ command: "chain-prompts analyze -> fix --loop 3" })
  519. run-prompt({ command: "deslop --subagent" })
  520. ```
  521. The tool queues the command for execution after the agent's current turn ends. All loop, chain, and convergence features work the same as slash commands.
  522. You can add guidance to steer when the agent reaches for it:
  523. ```
  524. /prompt-tool on Use run-prompt for iterative code improvement tasks
  525. /prompt-tool guidance Use sparingly, only for multi-pass refinement
  526. /prompt-tool guidance clear
  527. /prompt-tool off
  528. /prompt-tool # show current status
  529. ```
  530. Config persists across sessions in `~/.pi/agent/prompt-template-model.json`.
  531. ## Autocomplete
  532. Commands show their configuration in the autocomplete description:
  533. ```
  534. /debug-python Debug Python session [sonnet +tmux] (user)
  535. /deep-analysis Deep code analysis [sonnet high] (user)
  536. /save-progress Save progress doc [haiku|sonnet] (user)
  537. /component Create React component [sonnet] (user:frontend)
  538. ```
  539. ## Subdirectories
  540. Organize prompts in subdirectories for namespacing:
  541. ```
  542. ~/.pi/agent/prompts/
  543. ├── quick.md → /quick (user)
  544. ├── debug-python.md → /debug-python (user)
  545. └── frontend/
  546. ├── component.md → /component (user:frontend)
  547. └── hook.md → /hook (user:frontend)
  548. ```
  549. The subdirectory shows as the source label in autocomplete. Command names are based on filename only. Duplicates within the same source layer are skipped with a warning, as are reserved names like `model`, `reload`, and `chain-prompts`.
  550. ## Print Mode
  551. These commands work in `pi -p` too:
  552. ```bash
  553. pi -p "/debug-python my code crashes on line 42"
  554. ```
  555. The model switches, skill is injected, the agent responds, and output goes to stdout. Useful for scripting or piping.
  556. ## Examples
  557. **Thinking levels** — max thinking for thorny analysis:
  558. ```markdown
  559. ---
  560. description: Deep code analysis with extended thinking
  561. model: claude-sonnet-4-20250514
  562. thinking: max
  563. ---
  564. Analyze this code thoroughly, considering edge cases and potential issues: $@
  565. ```
  566. **Sticky mode switch** — switch models for the rest of the session:
  567. ```markdown
  568. ---
  569. description: Switch to Haiku for this session
  570. model: claude-haiku-4-5
  571. restore: false
  572. ---
  573. Switched to Haiku. How can I help?
  574. ```
  575. **Cross-provider fallback** — try the same model on different providers:
  576. ```markdown
  577. ---
  578. description: Quick analysis
  579. model: anthropic/claude-haiku-4-5, openrouter/claude-haiku-4-5
  580. ---
  581. $@
  582. ```
  583. ## Limitations
  584. - Prompt files are reloaded on session start and whenever an extension-owned command runs. If you add a new prompt file mid-session, run any extension command (like `/chain-prompts`), start a new session, or reload pi to pick it up.
  585. - Model restore state is in-memory. Closing pi mid-response loses it.
  586. - In chains, model-less steps inherit the chain-start model snapshot, not the previous step's model. This is intentional for deterministic behavior.
  587. - Delegated `subagent` prompts require [pi-subagents](https://github.com/nicobailon/pi-subagents/).
  588. - `run-prompt` must be explicitly enabled with `/prompt-tool on`.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.