pi-extension-authoring
Build, debug, and maintain Pi extensions safely. Use when editing ~/.pi/agent/extensions, joelclaw/pi/extensions, pi-tools extensions, or any code that uses the Pi ExtensionAPI, hooks, tools, commands, widgets, session replacement, reload, custom messages, or extension package updates.
What this skill does
# Pi Extension Authoring
Use this before changing Pi extension code or debugging Pi startup warnings.
## Canonical surfaces
- Repo-local joelclaw extensions: `~/Code/joelhooks/joelclaw/pi/extensions/<name>`
- Active symlinks: `~/.pi/agent/extensions/<name>` → repo-local source
- Package extensions: `~/.pi/agent/git/github.com/<owner>/<repo>`
- Package config: `~/.pi/agent/settings.json`
- Pi SDK/docs: global package under `~/.local/share/fnm/node-versions/*/installation/lib/node_modules/@earendil-works/pi-coding-agent/` (older installs used `@mariozechner/pi-coding-agent`)
## Rules
1. **Do not keep using captured session-bound objects after session replacement.**
- `ctx.newSession()`, `ctx.fork()`, `ctx.switchSession()`, and `ctx.reload()` invalidate old `pi` and `ctx` objects.
- For replacement commands, move post-switch work into the method's `withSession` callback and use only the callback `ctx`.
- For reload commands, treat `await ctx.reload(); return;` as terminal.
2. **Do not call `pi.sendMessage()` from delayed `session_start` callbacks.**
- A timer, promise, or subprocess can finish after reload/session replacement and throw stale-context errors.
- Start async work without storing `pi`/ctx, cache the plain result, then inject through `before_agent_start` by returning `{ message }`.
- Keep any first-turn wait tiny; use a short `Promise.race` budget if the result may not be ready.
3. **Use `pi.registerTool()`, not old APIs.**
- `pi.addTool()` is gone.
- Tool results need cloneable `details`. No timers, functions, sockets, or class instances.
4. **Optional dependencies must be lazy.**
- No top-level imports for optional packages.
- Use dynamic import or `createRequire()` inside guarded functions.
- Missing optional dependencies should disable that feature, not crash Pi startup.
5. **One active copy per extension.**
- Duplicate extension paths cause double hooks, duplicate messages, and weird cost/trace behavior.
- If a package checkout still contains an old extension directory, make sure its `package.json` no longer lists it in `pi.extensions` before ignoring it.
## Session-safe hidden message pattern
```ts
let cachedMessage: HiddenCustomMessage | null | undefined;
let messagePromise: Promise<HiddenCustomMessage | null> | null = null;
let delivered = false;
pi.on("session_start", (_event, ctx) => {
delivered = false;
cachedMessage = undefined;
const sessionId = ctx.sessionManager?.getSessionId?.() ?? null;
messagePromise = buildMessageWithoutCapturedPi(sessionId).then((message) => {
cachedMessage = message;
return message;
});
});
pi.on("before_agent_start", async (event) => {
const message = await Promise.race([
messagePromise,
new Promise<null>((resolve) => setTimeout(() => resolve(null), 250)),
]);
if (message && !delivered) {
delivered = true;
return {
systemPrompt: event.systemPrompt,
message,
};
}
return { systemPrompt: event.systemPrompt };
});
```
## Validation
Run the cheap gates first:
```bash
bun --check path/to/extension/index.ts
PI_OFFLINE=1 pi --help >/tmp/pi-help.out 2>/tmp/pi-help.err
rg -n "Skill conflicts|cannot load optional dependency|stale after session|<extension-name>" /tmp/pi-help.err /tmp/pi-help.out
```
For package updates:
```bash
# Update Pi plus settings-managed packages. Current Pi self-update migrates
# @mariozechner/pi-coding-agent installs to @earendil-works/pi-coding-agent.
pi update
# Keep npm-global tools current. Do not install the unrelated `pi` npm package.
npm install -g @earendil-works/pi-coding-agent@latest pi-mcp-adapter@latest pi-gitnexus@latest pi-subagents@latest pi-interactive-shell@latest
# If Bun's shadow global is present, either point ~/.bun/bin/pi at ~/.local/bin/pi
# or force the exact current version. Bun may block fresh releases via minimum-release-age.
bun add -g --minimum-release-age=0 @earendil-works/pi-coding-agent@$(pi --version)
which -a pi
pi --version
pi list
npm list -g --depth=0 | rg '@earendil-works/pi-coding-agent|@mariozechner/pi-coding-agent|pi-gitnexus|pi-mcp-adapter|pi-subagents|pi-interactive-shell'
```
Smoke-test both base Pi and full extension/tool startup with an approved model:
```bash
pi -p --no-session --no-tools --no-extensions --no-context-files --model openai-codex/gpt-5.5 "Reply with exactly OK."
pi -p --no-session --no-context-files --model openai-codex/gpt-5.5 "Reply with exactly OK."
```
Clean untracked npm lockfiles generated inside git package checkouts when the package does not track them.
If multiple `pi` binaries exist, verify they resolve to the same version. On Panda, `~/.bun/bin/pi` should be a symlink to `~/.local/bin/pi`; Bun's global installer can lag behind npm because of `minimum-release-age`.
## Common fixes
| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `This extension ctx is stale after session replacement or reload` | Delayed callback used old `pi`/ctx | Cache plain data; inject via `before_agent_start` return or use `withSession` |
| `cannot load optional dependency` | Package not installed from extension realpath | Install deps from the source repo realpath or make the dependency lazy/fail-open |
| Duplicate startup messages/traces | Extension loaded twice via package + symlink | Remove one active path from settings/package `pi.extensions` |
| Skill conflict warning | Skill directory name differs from frontmatter `name` | Rename directory or frontmatter so they match |
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.