pi-mono/packages/coding-agent/examples/extensions
Petr Houška da7e26cc8b
fix(mcp,ai,agent,coding-agent,tui): read large streamed lines and events in linear time (#12451)
Closes #12224.

## Problem

Stream readers kept an incomplete line or SSE event in one growing
string and searched all of it again on every chunk. Searching only from
a saved offset is not enough: searching a string built by `+=` makes V8
flatten (copy) the whole string first, so every chunk still costs the
full pending length.

Example: a 16 MiB MCP tool result arriving as one SSE `data:` line in 64
KiB chunks is about 256 chunks, each rescanning up to 16 MiB.
`consumeSseStream` took 9.8 s, blocking the event loop.

## Fix

Search only the new text, append the leftover to the pending string
without reading it, and read the pending string once when its line or
event ends. This is the approach #11791 used for the stdio line reader.

- **mcp**: `consumeSseStream`. The size limit now uses a running byte
count instead of measuring the buffer on every chunk. 16 MiB: 9.8 s ->
89 ms.
- **ai**: Anthropic, OpenAI Codex, Mistral and pi-messages each had
their own SSE parser with this bug. Anthropic's spec-conformant parser
moves to `src/utils/sse.ts` as `SseDecoder` (now linear) and all four
use it. Each keeps its own abort and error handling.
- **agent**: `streamProxy` line splitting.
- **coding-agent**: RPC JSONL reader, session file loading, llama.cpp
model events (now `SseDecoder`), and the `subagent` and
`rpc-extension-ui` examples.
- **env, durable**: text line readers searched the whole pending line
after every 64 KiB read. 16 MiB line: 1.35 s -> 72 ms.
- **chord**: sync batch lines and `importStore` JSONL.
- **tui**: `StdinBuffer` searched the whole bracketed paste for its end
marker on every chunk. It now searches the new text plus the last 5
characters, in case the marker is split across chunks.
- **p2**: terminal frames copied the whole incomplete frame on every
chunk (backlog replays reach 8 MiB). They now keep the chunks and join
them once per frame. Discord attachment downloads copied the growing 1
MiB upload chunk on every network read (about 800 MiB copied for a 25
MiB file); they now collect the parts and join them once per upload
chunk.

## Behavior changes in the shared SSE parser

- Codex also accepts CRLF line endings (it only split on LF before);
Codex and pi-messages also accept lone CR.
- llama.cpp model events also accept lone CR and CRLF split across
chunks.
- Anthropic no longer ends an event at a CRLF split across chunks.
- pi-messages joins multiple `data:` lines instead of taking the first.
- Mistral strips only the one space after `data:`. The payload is still
trimmed, so JSON is unaffected.
- Anthropic's `raw` diagnostic lines no longer carry comment lines from
earlier blocks that had no event or data.

## Not changed

- `readBodyText` in MCP: append-only, never rescanned. 16 MiB takes 100
ms.
- `p2-sandbox.mjs` exec frames: each frame is at most one chunk of child
output.
- Bounded buffers (1 MiB or less) that are re-measured or rescanned per
chunk: `apps/p2/src/runtime/logs.ts`, the `env/connection.ts` startup
marker scan, the `p2-sandbox.mjs` request header, terminal-reply parsing
in `StdinBuffer`.
- Editor and input paste buffers: they receive the whole paste in one
call from `StdinBuffer`.

## Tests

- mcp: a 1 MiB event in 4 KiB chunks measures at most 2x its size (the
old code measured 135M characters).
- ai: `test/sse.test.ts`, same events for every chunk size and line
ending, CRLF split across chunks.
- tui: paste end marker split at every position.
- p2: terminal frames at every chunk size; a 1 MiB frame calls
`Buffer.concat` once (the old code called it 256 times); a frame whose
handler threw is not delivered again.
- mcp: a line that never ends is rejected at the limit.
- ai: pi-messages skips `data: null`; an empty `event:` does not carry
into the next event.
- coding-agent: a throwing RPC line handler does not get its line joined
with the next.
- Existing tests pass for the Anthropic, Mistral, Codex and pi-messages
providers, proxy, RPC JSONL, session manager, llama, durable env-node,
env differential, and chord sync/store. `npm run check` and `apps/p2`
check pass.
2026-11-25 00:45:10 +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 fix(mcp,ai,agent,coding-agent,tui): read large streamed lines and events in linear time (#12451) 2026-11-25 00:45:10 +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
    }
  }
});