pi-mono/packages/coding-agent/examples/extensions
Petr Houška 282b01c80b
fix(coding-agent): anchor find path patterns at the search path (#12116)
The `find` tool matched path patterns through folders above the search
path. With the project in `/tmp/src/app`:

```
/tmp/src/app/src/a.ts
/tmp/src/app/lib/b.ts
/tmp/src/app/test/c.ts
```

`find { pattern: "src/**/*.ts" }` returned all three files.

**Cause:** fd matches `--full-path` globs against the absolute path, so
`find` put `**/` in front of path patterns. `**/src/**/*.ts` matched
`/tmp/src/app/lib/b.ts` through the parent folder `/tmp/src/`. Windows
had the same bug: its minimatch fallback also matched the absolute path.

**Fix:** path patterns are now relative to the search path, as grep's
`glob` has been since #11895.

- POSIX: the pattern is prefixed with the search path, glob-escaped (`\
* ? [ ] { }`), and passed to fd. fd's smart case would look at the whole
pattern, so a search path such as `/home/User/...` would make `src/b.ts`
case-sensitive. `find` now passes `--ignore-case` when the user's
pattern is all lowercase.
- Windows: minimatch matches the path relative to the search path.
Absolute patterns are still matched against the absolute path.

| Pattern | Before | After |
|---|---|---|
| `src/**/*.ts`, project in `~/src/app` | every `.ts` file | `src/a.ts`
|
| `src/*.ts` with `pkg/src/d.ts` present | `src/a.ts`, `pkg/src/d.ts` |
`src/a.ts` |
| `**/src/*.ts` | both | both |
| `*.ts` | file names at any depth | unchanged |
| absolute, `./src/*.ts`, Windows `src\*.ts` | worked | unchanged |

**Behavior change:** `src/*.ts` no longer finds `pkg/src/d.ts`;
`**/src/*.ts` does. This is the common glob convention (shell, ripgrep,
Node's `glob`) and matches grep's `glob`, so both tools now give the
same results for the same glob. Before, they disagreed. #11895 rejected
the old any-depth behavior for grep because it also matches lookalike
folders (#10418). find's `pattern` and grep's `glob` descriptions now
use the same, shorter wording: relative to the search directory, e.g.
`src/**/*.ts`; without `/`, e.g. `*.ts`, it matches file names at any
depth.

The gondolin example's `matchesToolGlob`, used for both find and grep,
also tried `**/` + pattern. It now anchors too and drops a leading `./`,
like the built-in tools.

**Testing**
- New `test/suite/regressions/12066-find-ancestor-glob.test.ts`: a
parent folder named `src`, anchored patterns vs. a leading `**/`, glob
characters in the search path, case handling with an upper-case search
path, and a symlinked search path (junction on Windows). 4 of its 5
tests fail on main.
- The find suites (3302, 3303, 6104), `test/tools.test.ts` and the other
find-related tests pass. `npm run check` passes.
- Windows: ran the bundled tool with Windows Node 26 and fd 10.5.0 on
`C:`, 32 cases: the cases above, backslash and `.\` patterns, absolute
`C:\` and `C:/` patterns, a lower-case drive letter, a folder named
`w[1]{x,y}`, case handling, a junction, the #3302 cases, and the result
limit. All pass. Against main, 5 of them fail.

fixes #12066

This PR is AI-generated.
2026-11-13 00:58:23 +01:00
..
custom-provider-anthropic Release v1.5.2 2026-11-10 13:01:48 +01:00
custom-provider-gitlab-duo Release v1.5.2 2026-11-10 13:01:48 +01:00
doom-overlay fix(coding-agent): update Doom WAD download source 2026-07-31 10:03:41 +02:00
dynamic-resources feat(coding-agent): use pi.dev configuration schemas (#10751) 2026-10-11 14:48:42 +01:00
gondolin fix(coding-agent): anchor find path patterns at the search path (#12116) 2026-11-13 00:58:23 +01:00
plan-mode fix(plan-mode): make progress tracking robust and tolerant (#7950) 2026-11-04 10:53:52 +01:00
subagent subagent example: ignore the Windows Bun virtual entry path when spawning pi (#11874) 2026-11-06 10:44:05 +01:00
with-deps Release v1.5.2 2026-11-10 13:01:48 +01:00
auto-commit-on-exit.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
bash-spawn-hook.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
bookmark.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
border-status-editor.ts fix(extension-examples): use agent_settled instead of end (#8242) 2026-08-17 13:10:23 +02:00
built-in-tool-renderer.ts fix(coding-agent): preserve renderer example prompt guidance (#10193) 2026-09-30 08:56:08 +01:00
claude-rules.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
commands.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
confirm-destructive.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
custom-compaction.ts fix(coding-agent): preserve extension auth endpoints 2026-08-04 12:37:02 +02:00
custom-footer.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
custom-header.ts Add extension mode context 2026-06-01 18:32:03 +02:00
debug-provider.ts fix(coding-agent): pass host keybinding hints to extension renderers (#11630) 2026-10-30 23:01:20 +01:00
dirty-repo-guard.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
dynamic-tools.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
entry-renderer.ts fix(coding-agent): add entry renderers for session entries 2026-07-01 11:30:26 +02:00
event-bus.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
file-trigger.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
git-checkpoint.ts fix(extension-examples): use agent_settled instead of end (#8242) 2026-08-17 13:10:23 +02:00
git-merge-and-resolve.ts fix(coding-agent): drain follow-ups queued during agent_end 2026-05-28 18:27:39 +10:00
github-issue-autocomplete.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
handoff.ts fix(coding-agent): preserve extension auth endpoints 2026-08-04 12:37:02 +02:00
hello.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
hidden-thinking-label.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
inline-bash.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
input-transform-streaming.ts feat(coding-agent): expose streamingBehavior on InputEvent 2026-05-28 15:52:38 +10:00
input-transform.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
interactive-shell.ts Add extension mode context 2026-06-01 18:32:03 +02:00
jev-router.ts feat(coding-agent): Virtual models (#10035) 2026-09-28 23:30:45 +02:00
mac-system-theme.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
message-renderer.ts feat(coding-agent): expose output padding to custom renderers (#7045) 2026-07-25 08:29:34 +02:00
minimal-mode.ts fix(coding-agent): normalize read line-range labels (#10938) 2026-10-14 15:20:04 +02:00
modal-editor.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
model-status.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
notify.ts fix(extension-examples): use agent_settled instead of end (#8242) 2026-08-17 13:10:23 +02:00
overlay-qa-tests.ts fix(tui): harden overlay focus restoration 2026-05-31 21:20:33 -07:00
overlay-test.ts feat(tui,coding-agent): use only the terminal cursor when showHardwareCursor is enabled 2026-10-08 00:23:06 +02:00
permission-gate.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
pirate.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
preset.ts fix(tui,coding-agent): handle selection page keys in all scrolling lists 2026-10-28 19:05:21 +01:00
project-trust.ts feat(coding-agent): allow project trust extensions to defer 2026-06-08 13:38:29 +02:00
prompt-customizer.ts Mid conversation system messages (#9548) 2026-09-16 15:54:07 +02:00
protected-paths.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
provider-payload.ts feat(coding-agent): export project config dir name 2026-06-18 10:27:11 +02:00
qna.ts fix(coding-agent): preserve extension auth endpoints 2026-08-04 12:37:02 +02:00
question.ts fix(coding-agent): set executionMode: sequential on question example tool 2026-07-02 09:01:15 +02:00
questionnaire.ts feat(examples): Wrap question extension text instead of truncating (#5708) 2026-06-14 15:02:58 +02:00
rainbow-editor.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
README.md fix: remove vulnerable dependency chains 2026-10-31 17:54:29 +01:00
reload-runtime.ts docs(coding-agent): restore the full extensions guide, corrected against current source (#11498) 2026-10-28 00:31:24 +02:00
rpc-demo.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
send-user-message.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
session-name.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
shutdown-command.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
snake.ts Add extension mode context 2026-06-01 18:32:03 +02:00
space-invaders.ts Add extension mode context 2026-06-01 18:32:03 +02:00
ssh.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
status-line.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
structured-output.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
summarize.ts fix(coding-agent): preserve extension auth endpoints 2026-08-04 12:37:02 +02:00
system-prompt-header.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
tic-tac-toe.ts Add extension mode context 2026-06-01 18:32:03 +02:00
timed-confirm.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
titlebar-spinner.ts fix(extension-examples): use agent_settled instead of end (#8242) 2026-08-17 13:10:23 +02:00
todo.ts fix(examples): todo renderResult returns undefined on validation errors 2026-10-23 20:20:02 +02:00
tool-override.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
tools.ts fix(tui,coding-agent): handle selection page keys in all scrolling lists 2026-10-28 19:05:21 +01:00
trigger-compact.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
truncated-tool.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
widget-placement.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
working-indicator.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00
working-message-test.ts chore: migrate pi packages to earendil works scope 2026-05-07 15:59:42 +02:00

Extension Examples

Example extensions for pi-coding-agent.

Usage

# Load an extension with --extension flag
pi --extension examples/extensions/permission-gate.ts

# Or copy to extensions directory for auto-discovery
cp permission-gate.ts ~/.pi/agent/extensions/

Examples

Lifecycle & Safety

Extension Description
permission-gate.ts Prompts for confirmation before dangerous bash commands (rm -rf, sudo, etc.)
project-trust.ts Demonstrates the project_trust event for user/global and CLI extensions
protected-paths.ts Blocks writes to protected paths (.env, .git/, node_modules/)
confirm-destructive.ts Confirms before destructive session actions (clear, switch, fork)
dirty-repo-guard.ts Prevents session changes with uncommitted git changes
gondolin/ Route built-in tools and ! commands into a Gondolin micro-VM

For isolation setup and limitations, see Run Pi in an isolated environment.

Custom Tools

Extension Description
todo.ts Todo list tool + /todos command with custom rendering and state persistence
hello.ts Minimal custom tool example
question.ts Demonstrates ctx.ui.select() for asking the user questions with custom UI
questionnaire.ts Multi-question input with tab bar navigation between questions
tool-override.ts Override built-in tools (e.g., add logging/access control to read)
dynamic-tools.ts Register tools after startup (session_start) and at runtime via command, with prompt snippets and tool-specific prompt guidelines
structured-output.ts Final structured-output tool that returns terminate: true so the agent can end on the tool call
built-in-tool-renderer.ts Custom compact rendering for built-in tools (read, bash, edit, write) while keeping original behavior
minimal-mode.ts Override built-in tool rendering for minimal display (only tool calls, no output in collapsed mode)
truncated-tool.ts Wraps ripgrep with proper output truncation (50KB/2000 lines)
ssh.ts Delegate all tools to a remote machine via SSH using pluggable operations
subagent/ Delegate tasks to specialized subagents with isolated context windows

Commands & UI

Extension Description
preset.ts Named presets for model, thinking level, tools, and instructions via --preset flag and /preset command
plan-mode/ Claude Code-style plan mode for read-only exploration with /plan command and step tracking
tools.ts Interactive /tools command to enable/disable tools with session persistence
handoff.ts Transfer context to a new focused session via /handoff <goal>
qna.ts Extracts questions from last response into editor via ctx.ui.setEditorText()
status-line.ts Shows turn progress in footer via ctx.ui.setStatus() with themed colors
github-issue-autocomplete.ts Adds #1234 issue completions by stacking a custom autocomplete provider that preloads open issues from gh issue list
widget-placement.ts Shows widgets above and below the editor via ctx.ui.setWidget() placement
hidden-thinking-label.ts Customizes the collapsed thinking label via ctx.ui.setHiddenThinkingLabel()
working-indicator.ts Customizes the streaming working indicator via ctx.ui.setWorkingIndicator()
model-status.ts Shows model changes in status bar via model_select hook
snake.ts Snake game with custom UI, keyboard handling, and session persistence
tic-tac-toe.ts Tic-tac-toe vs the agent with executionMode: "sequential" tools to prevent race conditions on shared cursor state
send-user-message.ts Demonstrates pi.sendUserMessage() for sending user messages from extensions
timed-confirm.ts Demonstrates AbortSignal for auto-dismissing ctx.ui.confirm() and ctx.ui.select() dialogs
rpc-demo.ts Exercises all RPC-supported extension UI methods; pair with examples/rpc-extension-ui.ts
modal-editor.ts Custom vim-like modal editor via ctx.ui.setEditorComponent()
rainbow-editor.ts Animated rainbow text effect via custom editor
notify.ts Desktop notifications via OSC 777 when agent finishes (Ghostty, iTerm2, WezTerm)
titlebar-spinner.ts Braille spinner animation in terminal title while the agent is working
summarize.ts Summarize conversation with GPT-5.2 and show in transient UI
custom-footer.ts Custom footer with git branch and token stats via ctx.ui.setFooter()
custom-header.ts Custom header via ctx.ui.setHeader()
overlay-test.ts Test overlay compositing with inline text inputs and edge cases
overlay-qa-tests.ts Comprehensive overlay QA tests: anchors, margins, stacking, overflow, animation
doom-overlay/ DOOM game running as an overlay at 35 FPS (demonstrates real-time game rendering)
shutdown-command.ts Adds /quit command demonstrating ctx.shutdown()
reload-runtime.ts Adds /reload-runtime and reload_runtime tool showing safe reload flow
interactive-shell.ts Run interactive commands (vim, htop) with full terminal via user_bash hook
inline-bash.ts Expands !{command} patterns in prompts via input event transformation
input-transform-streaming.ts Skips expensive input preprocessing for mid-stream steering via streamingBehavior

Git Integration

Extension Description
git-checkpoint.ts Creates git stash checkpoints at each turn for code restoration on fork
auto-commit-on-exit.ts Auto-commits on exit using last assistant message for commit message

System Prompt & Compaction

Extension Description
pirate.ts Demonstrates systemPromptAppend to dynamically modify system prompt
claude-rules.ts Scans .claude/rules/ folder and lists rules in system prompt
custom-compaction.ts Custom compaction that summarizes entire conversation
trigger-compact.ts Triggers compaction when context usage exceeds 100k tokens and adds /trigger-compact command

System Integration

Extension Description
mac-system-theme.ts Syncs pi theme with macOS dark/light mode

Resources

Extension Description
dynamic-resources/ Loads skills, prompts, and themes using resources_discover

Messages & Communication

Extension Description
message-renderer.ts Custom message rendering with colors and expandable details via registerMessageRenderer
entry-renderer.ts TUI-only session entry rendering via appendEntry and registerEntryRenderer
debug-provider.ts Toggle raw provider stream capture with /debug-provider and inspect each assistant message in a TUI-only session entry
event-bus.ts Inter-extension communication via pi.events

Session Metadata

Extension Description
session-name.ts Name sessions for the session selector via setSessionName
bookmark.ts Bookmark entries with labels for /tree navigation via setLabel

Custom Providers

Extension Description
custom-provider-anthropic/ Custom Anthropic provider with OAuth support and custom streaming implementation
custom-provider-gitlab-duo/ GitLab Duo provider using pi-ai's built-in Anthropic/OpenAI streaming via proxy
jev-router.ts Virtual model via registerVirtualModel that plans on Codex Sol or Terra (picked by the Jev classifier) and switches to Luna after the first edit

External Dependencies

Extension Description
with-deps/ Extension with its own package.json and dependencies (demonstrates jiti module resolution)
file-trigger.ts Watches a trigger file and injects contents into conversation

Writing Extensions

See docs/extensions.md for full documentation.

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";

export default function (pi: ExtensionAPI) {
  // Subscribe to lifecycle events
  pi.on("tool_call", async (event, ctx) => {
    if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {
      const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
      if (!ok) return { block: true, reason: "Blocked by user" };
    }
  });

  // Register custom tools
  pi.registerTool({
    name: "greet",
    label: "Greeting",
    description: "Generate a greeting",
    parameters: Type.Object({
      name: Type.String({ description: "Name to greet" }),
    }),
    async execute(toolCallId, params, signal, onUpdate, ctx) {
      return {
        content: [{ type: "text", text: `Hello, ${params.name}!` }],
        details: {},
      };
    },
  });

  // Register commands
  pi.registerCommand("hello", {
    description: "Say hello",
    handler: async (args, ctx) => {
      ctx.ui.notify("Hello!", "info");
    },
  });
}

Key Patterns

Use StringEnum for string parameters (required for Google API compatibility):

import { StringEnum } from "@earendil-works/pi-ai";

// Good
action: StringEnum(["list", "add"] as const)

// Bad - doesn't work with Google
action: Type.Union([Type.Literal("list"), Type.Literal("add")])

State persistence via details:

// Store state in tool result details for proper forking support
return {
  content: [{ type: "text", text: "Done" }],
  details: { todos: [...todos], nextId },  // Persisted in session
};

// Reconstruct on session events
pi.on("session_start", async (_event, ctx) => {
  for (const entry of ctx.sessionManager.getBranch()) {
    if (entry.type === "message" && entry.message.toolName === "my_tool") {
      const details = entry.message.details;
      // Reconstruct state from details
    }
  }
});