co-mono/packages/coding-agent/examples/extensions
Mario Zechner 9ed88646a8 feat(coding-agent): add pluggable operations for remote tool execution
Adds optional operations parameter to create*Tool functions enabling
delegation to remote systems (SSH, containers, etc.):

- ReadOperations: readFile, access, detectImageMimeType
- WriteOperations: writeFile, mkdir
- EditOperations: readFile, writeFile, access
- BashOperations: exec (with streaming, signal, timeout)

Add ssh.ts example demonstrating --ssh flag for remote execution.
Built-in renderers used automatically for overrides without custom renderers.

fixes #564
2026-01-08 19:32:25 +01:00
..
subagent Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
with-deps Release v0.38.0 2026-01-08 04:52:55 +01:00
auto-commit-on-exit.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
chalk-logger.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
claude-rules.ts fix: mark with-deps example as private, update changelog 2026-01-05 17:55:15 +01:00
confirm-destructive.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
custom-compaction.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
custom-footer.ts Add ctx.ui.setFooter() for extensions to replace footer component 2026-01-06 12:39:45 +01:00
custom-header.ts added custom header support and example extension 2026-01-06 21:20:19 +01:00
dirty-repo-guard.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
file-trigger.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
git-checkpoint.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
handoff.ts feat(coding-agent): add ctx.ui.setEditorComponent() extension API 2026-01-07 16:11:49 +01:00
hello.ts Flatten hello/ and question/ extension examples to single files 2026-01-05 01:45:10 +01:00
modal-editor.ts feat(coding-agent): add ctx.ui.setEditorComponent() extension API 2026-01-07 16:11:49 +01:00
permission-gate.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
pirate.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
plan-mode.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
preset.ts feat(coding-agent): add ctx.ui.setEditorComponent() extension API 2026-01-07 16:11:49 +01:00
protected-paths.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
qna.ts feat(coding-agent): add ctx.ui.setEditorComponent() extension API 2026-01-07 16:11:49 +01:00
question.ts Flatten hello/ and question/ extension examples to single files 2026-01-05 01:45:10 +01:00
rainbow-editor.ts feat(coding-agent): add ctx.ui.setEditorComponent() extension API 2026-01-07 16:11:49 +01:00
README.md feat(coding-agent): add pluggable operations for remote tool execution 2026-01-08 19:32:25 +01:00
send-user-message.ts Extensions: add pi.sendUserMessage() for sending user messages 2026-01-06 13:40:24 +01:00
shutdown-command.ts fix(coding-agent): add PR attribution to ctx.shutdown() changelog, fix example comments 2026-01-08 03:31:55 +01:00
snake.ts feat(coding-agent): add ctx.ui.setEditorComponent() extension API 2026-01-07 16:11:49 +01:00
ssh.ts feat(coding-agent): add pluggable operations for remote tool execution 2026-01-08 19:32:25 +01:00
status-line.ts Merge hooks and custom-tools into unified extensions system (#454) 2026-01-05 01:43:35 +01:00
timed-confirm.ts feat(coding-agent): add timeout option to extension dialogs with live countdown 2026-01-06 21:49:27 -08:00
todo.ts feat(coding-agent): add ctx.ui.setEditorComponent() extension API 2026-01-07 16:11:49 +01:00
tool-override.ts docs(coding-agent): simplify tool-override example to use built-in renderer 2026-01-08 18:52:33 +01:00
tools.ts feat(coding-agent): add ctx.ui.setEditorComponent() extension API 2026-01-07 16:11:49 +01:00
truncated-tool.ts Export truncation utilities for custom tools, add truncated-tool example 2026-01-06 22:13:08 +01: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.)
protected-paths.ts Blocks writes to protected paths (.env, .git/, node_modules/)
confirm-destructive.ts Confirms before destructive session actions (clear, switch, branch)
dirty-repo-guard.ts Prevents session changes with uncommitted git changes

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
tool-override.ts Override built-in tools (e.g., add logging/access control to read)
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.ts Claude Code-style plan mode for read-only exploration with /plan command
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
snake.ts Snake game with custom UI, keyboard handling, and session persistence
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
modal-editor.ts Custom vim-like modal editor via ctx.ui.setEditorComponent()

Git Integration

Extension Description
git-checkpoint.ts Creates git stash checkpoints at each turn for code restoration on branch
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
custom-compaction.ts Custom compaction that summarizes entire conversation

External Dependencies

Extension Description
chalk-logger.ts Uses chalk from parent node_modules (demonstrates jiti module resolution)
with-deps/ Extension with its own package.json and dependencies
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 "@mariozechner/pi-coding-agent";
import { Type } from "@sinclair/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, onUpdate, ctx, signal) {
      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 "@mariozechner/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 branching 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
    }
  }
});