Use the TypeScript extension to register tools, slash commands, shortcut keys, and lifecycle events.

Difficulty: ★★★★ | Prerequisites:02(agent loop and events),04 |Requires basic knowledge TypeScript

1. What is an extension?

extension is Add the TypeScript module with executable behavior to Pi. Use extensions when your workflow requires tools, commands, event handling, model providers, session state, or terminal UI, not just instructions.

⚠️ The extension runs within the Pi process with the same OS permissions and can inspect prompts, tool calls, files, credentials and session history.Only load extensions you trust.

Typical uses: add agent tools, protect paths, confirm dangerous commands, respond to session events, modify context, expose commands, display persistent status.

2. The first extension: a slash command (official example)

Create ~/.pi/agent/extensions/hello.ts:

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
  pi.registerCommand("hello", {
    description: "Show a greeting",
    handler: async (name, ctx) => {
      ctx.ui.notify(`Hello, ${name || "world"}!`, "info");
    },
  });
}

Start Pi run /hello 张三. Files can also be loaded directly during development:

pi --extension ./hello.ts
  • Pi use jiti, native TS extension No need to compile separately;
  • Export an extension Default factory function, receive ExtensionAPI(usually named pi); the factory can be synchronous or asynchronous, Pi will wait for the asynchronous factory to complete.

2.1 Where to put it

  • User level:~/.pi/agent/extensions/;Project level:.pi/extensions/(requires project trust);
  • You can also set extensions Array or Pi package loading;
  • Pi loading direct .ts/.js File, and including index.ts/index.js of subdirectory;
  • Keep an npm dependency nearby when you need it package.json;
  • After modification /reload。

3. Life cycle (must understand)

3.1 What not to do in factory functions

Do not start processes, sockets, watchers or timers in factories- some calls (e.g. pi --help、pi --list-models) will load the extension but not start the session. Long-term resources please visit session_start Or start it in the command/tool that requires it, in idempotent session_shutdown Medium close.

3.2 The hook sequence of a prompt

input → before_agent_start → agent_start → turn_start → context → context_with_system

→ before_provider_headers → before_provider_request → after_provider_response

→ provider_stream_event / message event

→ [With tool call] tool_execution_start → tool_call → Execution (tool_execution_update) → tool_result → tool_execution_end

  → turn_end → [Need another round? return to turn_start]
  → agent_end → [Try again/restore/queue? return to agent_start]
  → agent_before_settle → [Request to continue? return to agent_start] → agent_settled

3.3 Session life cycle

process start → project_trust (when needed) → session_start → resources_discover

/new or /resume → session_before_switch → session_shutdown → load new runtime → session_start

/fork or /clone → session_before_fork → session_shutdown → …

reload → session_shutdown → …

agent_end No Final idle signal. reload and session replacement will invalidate the old runtime,await ctx.reload() Subsequent code cannot reuse the old runtime state.

3.4 Select events according to intent

  • Examine, transform, or consume raw user input

    event
    input
  • Modify prompt snippets, activate tools, or add context before running

    event
    before_agent_start
  • Observe a low-level operation

    event
    agent_start、agent_end
  • Act after a model reply and its tool invocation

    event
    turn_end
  • Filter messages for a single Provider request

    event
    context
  • Transform a complete conversation containing system messages

    event
    context_with_system
  • Modify the request header or serialized payload

    event
    before_provider_headers、before_provider_request
  • Authorize or modify tool calls

    event
    tool_call
  • Mask, annotate or replace tool results

    event
    tool_result
  • Append final entry or request last continuation

    event
    agent_before_settle
  • Automatically handle notification work after complete stop

    event
    agent_settled
  • Initialize/release session-level resources

    event
    session_start、session_shutdown
targetevent
Examine, transform, or consume raw user inputinput
Modify prompt snippets, activate tools, or add context before runningbefore_agent_start
Observe a low-level operationagent_start、agent_end
Act after a model reply and its tool invocationturn_end
Filter messages for a single Provider requestcontext
Transform a complete conversation containing system messagescontext_with_system
Modify the request header or serialized payloadbefore_provider_headers、before_provider_request
Authorize or modify tool callstool_call
Mask, annotate or replace tool resultstool_result
Append final entry or request last continuationagent_before_settle
Automatically handle notification work after complete stopagent_settled
Initialize/release session-level resourcessession_start、session_shutdown

3.5 Processor Combination Mode

  • Notification

    behavior
    Return value is ignored
  • Modify in place

    behavior
    The processor behind can see the correct tool_call.input、before_agent_start.systemPromptOptions etc. Modifications
  • chain transformation

    behavior
    input、context、message_end、tool_result、before_provider_request Wait, the latter receives the return value of the former
  • Gate

    behavior
    Processed input, blocked tool calls, canceled session operations stop the default path
  • last override

    behavior
    cache_warming_decision The last returned actor takes effect
modebehavior
NotificationReturn value is ignored
Modify in placeThe processor behind can see the correct tool_call.input、before_agent_start.systemPromptOptions etc. Modifications
chain transformationinput、context、message_end、tool_result、before_provider_request Wait, the latter receives the return value of the former
GateProcessed input, blocked tool calls, canceled session operations stop the default path
last overridecache_warming_decision The last returned actor takes effect

Access control processors should fail closed。tool_call When the processor throws an error, Pi will serve as insurance block the tool.

4. List of extended API capabilities

  • Observe/modify life cycle

    Main API
    pi.on()(Return to unsubscribe function)
  • Add tools callable by the model

    Main API
    pi.registerTool() / defineTool()
  • add / command

    Main API
    pi.registerCommand()
  • Shortcut keys/CLI parameters

    Main API
    pi.registerShortcut() / pi.registerFlag() + pi.getFlag()
  • Send user or custom message

    Main API
    pi.sendUserMessage() / pi.sendMessage()
  • Persist data without context

    Main API
    pi.appendEntry()
  • Modify activation tools, models, and thinking levels

    Main API
    pi.setActiveTools()、pi.setModel()、pi.setThinkingLevel() Wait
  • Add model provider

    Main API
    pi.registerProvider()
  • Add MCP server

    Main API
    pi.registerMcpServer()
  • Each request is routed to a different model

    Main API
    pi.registerVirtualModel()
  • terminal rendering

    Main API
    Renderer registration with ctx.ui
  • Communication between extensions

    Main API
    pi.events
  • Execute external command

    Main API
    pi.exec(cmd, args)
AbilityMain API
Observe/modify life cyclepi.on()(Return to unsubscribe function)
Add tools callable by the modelpi.registerTool() / defineTool()
add / commandpi.registerCommand()
Shortcut keys/CLI parameterspi.registerShortcut() / pi.registerFlag() + pi.getFlag()
Send user or custom messagepi.sendUserMessage() / pi.sendMessage()
Persist data without contextpi.appendEntry()
Modify activation tools, models, and thinking levelspi.setActiveTools()、pi.setModel()、pi.setThinkingLevel() Wait
Add model providerpi.registerProvider()
Add MCP serverpi.registerMcpServer()
Each request is routed to a different modelpi.registerVirtualModel()
terminal renderingRenderer registration with ctx.ui
Communication between extensionspi.events
Execute external commandpi.exec(cmd, args)

5. Registration tool

5.1 Minimal tools (official hello.ts)

import { Type } from "@earendil-works/pi-ai";
import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
const helloTool = defineTool({
  name: "hello",
  label: "Hello",
  description: "A simple greeting tool",
  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: { greeted: params.name },
    };
  },
});
export default function (pi: ExtensionAPI) {
  pi.registerTool(helloTool);
}

Key points of the tool contract:

  • definition name, model-oriented description、TypeBox Parameters schema and execute();
  • The results must be model-oriented content, and for rendering/state reconstruction details(without exception details: undefined);
  • execute(toolCallId, params, signal, onUpdate, ctx):signal for cancellation,onUpdate Push partial results;
  • Throw exception will produce a failed tool result; return object No Marked as an error;
  • Return terminate: true: When all tools in this batch agree to terminate, skip the automatic subsequent LLM round (see example below);
  • Tools that share mutable memory state should execute sequentially; tools that modify files use withFileMutationQueue() Package complete read-modify-write;
  • Truncate results when they are too large and tell the model where to read the full output (see truncated-tool.ts, 50KB/2000 lines);
  • Declare when there is structured data outputSchema and return structuredContent(The codemode script will get the structured value);
  • Tools available ctx.executeTool(name, args, { signal, onUpdate }) call other tools;
  • If the model is called internally by the tool, put usage Enter the results to ensure accurate session cost statistics.

5.2 Terminated structured output tool (official structured-output.ts excerpt)

import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
const structuredOutputTool = defineTool({
  name: "structured_output",
  label: "Structured Output",
  description:
    "Return a final structured answer. Use this as your last action when the user asks for structured output or a machine-readable summary.",
  promptSnippet: "Emit a final structured answer as a terminating tool result",
  promptGuidelines: [
    "Use structured_output as your final action when the user asks for structured output, JSON-like output, or a machine-readable summary.",
    "After calling structured_output, do not emit another assistant response in the same turn.",
  ],
  parameters: Type.Object({
    headline: Type.String({ description: "Short title for the result" }),
    summary: Type.String({ description: "One-paragraph summary" }),
    actionItems: Type.Array(Type.String(), { description: "Concrete next steps or key bullets" }),
  }),
  async execute(_toolCallId, params) {
    return {
      content: [{ type: "text", text: `Saved structured output: ${params.headline}` }],
      details: { headline: params.headline, summary: params.summary, actionItems: params.actionItems },
      terminate: true,
    };
  },
});
export default function (pi: ExtensionAPI) {
  pi.registerTool(structuredOutputTool);
}

promptSnippet / promptGuidelines You will enter the tool-related part of the system prompt. The official complete example also implements renderResult Custom TUI rendering.

5.3 Tool exposure (exposure)

  • direct(default)

    meaning
    Declared to the model when activated and can be called by other tools
  • model-only

    meaning
    Declared to the model, but cannot be called by other tools (suitable for orchestration tools or tools that ask users)
  • codemode

    meaning
    It can be called after registration and listed in the codemode tool; it is not declared to the model by default.
  • deferred

    meaning
    Like codemode, but not listed in codemode; can be tool_search Find and activate
  • hidden

    meaning
    Registered but unreachable (the tool cannot be logged out, use it to "revoke")
exposuremeaning
direct(default)Declared to the model when activated and can be called by other tools
model-onlyDeclared to the model, but cannot be called by other tools (suitable for orchestration tools or tools that ask users)
codemodeIt can be called after registration and listed in the codemode tool; it is not declared to the model by default.
deferredLike codemode, but not listed in codemode; can be tool_search Find and activate
hiddenRegistered but unreachable (the tool cannot be logged out, use it to "revoke")

You can also set namespace(grouped, as is the case with MCP servers) and annotations(readOnlyHint、destructiveHint、idempotentHint、openWorldHint), the permission class extension can decide whether confirmation is required based on this.

5.4 Dynamic activation tools

Register all tools first and leave optional tools inactive before using them pi.setActiveTools() Select. The name must be registered, unknown names are ignored. Reference dynamic-tools.ts。

6. Register commands, shortcut keys and parameters

6.1 Commands with parameter completion (official commands.ts excerpt)

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function commandsExtension(pi: ExtensionAPI) {
  pi.registerCommand("commands", {
    description: "List available slash commands",
    getArgumentCompletions: (prefix) => {
      const sources = ["extension", "prompt", "skill"];
      const filtered = sources.filter((s) => s.startsWith(prefix));
      return filtered.length > 0 ? filtered.map((s) => ({ value: s, label: s })) : null;
    },
    handler: async (args, ctx) => {
      const commands = pi.getCommands();
      // ... Filter and use ctx.ui.select() show
    },
  });
}

6.2 CLI parameters and shortcut keys (official preset.ts excerpt)

pi.registerFlag("preset", {
  description: "Preset configuration to use",
  type: "string",
});
pi.registerShortcut(Key.ctrlShift("u"), {
  description: "Cycle presets",
  handler: async (ctx) => {
    await cyclePreset(ctx);
  },
});
// Then read:const presetFlag = pi.getFlag("preset");

The command processor receives ExtensionCommandContext, additionally provides operations such as waiting for idle, reload, tree navigation, session replacement - these Can only be called in the command, calling in the life cycle handler may deadlock.

7. Event handling practice

7.1 Dangerous order confirmation (official permission-gate.ts)

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
  const dangerousPatterns = [/\brm\\s+(-rf?|--recursive)/i, /\bsudo\b/i, /\b(chmod|chown)\b.*777/i];
  pi.on("tool_call", async (event, ctx) => {
    if (event.toolName !== "bash") return undefined;
    const command = event.input.command as string;
    const isDangerous = dangerousPatterns.some((p) => p.test(command));
    if (isDangerous) {
      if (!ctx.hasUI) {
        // In non-interactive mode, block by default
        return { block: true, reason: "Dangerous command blocked (no UI for confirmation)" };
      }
      const choice = await ctx.ui.select(`⚠️ Dangerous command:\n\n  ${command}\n\nAllow?`, ["Yes", "No"]);
      if (choice !== "Yes") {
        return { block: true, reason: "Blocked by user" };
      }
    }
    return undefined;
  });
}

Pay attention to the three principles it embodies:Filter by tool name、Close on failure if there is no UI、Return { block: true, reason } Block calls。

7.2 Protection path (official protected-paths.ts)

pi.on("tool_call", async (event, ctx) => {
  if (event.toolName !== "write" && event.toolName !== "edit") return undefined;
  const path = event.input.path as string;
  const isProtected = [".env", ".git/", "node_modules/"].some((p) => path.includes(p));
  if (isProtected) {
    if (ctx.hasUI) ctx.ui.notify(`Blocked write to protected path: ${path}`, "warning");
    return { block: true, reason: `Path "${path}" is protected` };
  }
  return undefined;
});

7.3 Transform user input (official input-transform.ts excerpt)

pi.on("input", async (event, ctx) => {
  if (event.source === "extension") return { action: "continue" };
  if (event.text.startsWith("?quick ")) {
    const query = event.text.slice(7).trim();
    return { action: "transform", text: `Respond briefly in 1-2 sentences: ${query}` };
  }
  if (event.text.toLowerCase() === "ping") {
    ctx.ui.notify("pong", "info");
    return { action: "handled" };   // Not called LLM
  }
  return { action: "continue" };
});

7.4 Modify the system prompt fragment (official prompt-customizer.ts ideas)

pi.on("before_agent_start", (event) => {
  event.systemPromptOptions.sections.tool_guidance = "- Prefer `edit` over `write` for existing files.";
});

The official recommendation is to prioritize modifying structured prompt sections, selected tools, or guides rather than returning the entire section. systemPrompt Replace (that will force the entire prompt to be replaced for this run).

1.2.0 Behavioral changes:before_agent_start Will be there now pi.sendMessage(..., { triggerTurn: true }) Triggered on-the-fly. event becomes based on event.messageType union type ("user" bring prompt/images;"custom" bring message). Processors that only want to handle user prompts need to check messageType。

7.5 Status bar (official status-line.ts)

pi.on("turn_start", async (_event, ctx) => {
  turnCount++;
  const theme = ctx.ui.theme;
  ctx.ui.setStatus("status-demo", theme.fg("accent", "●") + theme.fg("dim", ` Turn ${turnCount}...`));
});

7.6 Automatically submit when exiting (official auto-commit-on-exit.ts ideas)

pi.on("session_shutdown", async (_event, ctx) => {
  const { stdout: status, code } = await pi.exec("git", ["status", "--porcelain"]);
  if (code !== 0 || status.trim().length === 0) return;
  await pi.exec("git", ["add", "-A"]);
  await pi.exec("git", ["commit", "-m", "[pi] work in progress"]);
});

7.7 Customizing compression summaries (Compaction documentation)

pi.on("session_before_compact", async (event, ctx) => {
  const { preparation } = event;
  // return { cancel: true };  // Cancel
  return {
    compaction: {
      summary: "Your summary...",
      firstKeptEntryId: preparation.firstKeptEntryId,
      tokensBefore: preparation.tokensBefore,
    },
  };
});

Available serializeConversation(convertToLlm(preparation.messagesToSummarize)) Leave the message to text to your own model. Complete example:custom-compaction.ts。

8. Status management

  • Follow the tool status of the active branch

    Storage method
    tool result details
  • Persistent data that does not enter the model context

    Storage method
    pi.appendEntry()
  • Custom content stored and sent to the model

    Storage method
    pi.sendMessage()
  • Cross-session data

    Storage method
    external storage
status typeStorage method
Follow the tool status of the active branchtool result details
Persistent data that does not enter the model contextpi.appendEntry()
Custom content stored and sent to the modelpi.sendMessage()
Cross-session dataexternal storage

Key Tips: in session_start(and /tree After navigation session_tree), from ctx.sessionManager.getBranch() rebuild State associated with branches; do not rebuild from all entries in the file, since abandoned branches represent alternative history. official todo.ts Core logic:

const reconstructState = (ctx: ExtensionContext) => {
  todos = [];
  nextId = 1;
  for (const entry of ctx.sessionManager.getBranch()) {
    if (entry.type !== "message") continue;
    const msg = entry.message;
    if (msg.role !== "toolResult" || msg.toolName !== "todo") continue;
    const details = msg.details as TodoDetails | undefined;
    if (details) {
      todos = details.todos;
      nextId = details.nextId;
    }
  }
};
pi.on("session_start", async (_event, ctx) => reconstructState(ctx));
pi.on("session_tree", async (_event, ctx) => reconstructState(ctx));

In this way, when the branch is switched, the todo status automatically corresponds to that historical time point.

8.1 Send messages

// Send message as user (always trigger round); must be specified when busy deliverAs
pi.sendUserMessage("Please run the test", { deliverAs: "followUp" });
// Send a custom message
pi.sendMessage(
  { customType: "my-note", content: "Build completed", display: true },
  { triggerTurn: false },
);
`sendMessage` of `deliverAs` can be `"steer"`、`"followUp"`、`"nextTurn"`。

9. UI and mode adaptation

  • ctx.ui Provides a dialog box (select、confirm、input、editor)、notify、setStatus、setWidget, title, editor access,custom() Custom components;
  • extended in Interaction, RPC, JSON, print Will be loaded in four modes: interactive mode has a complete TUI; RPC can forward dialog boxes and notifications through the RPC Extension UI protocol (custom terminal components are not supported); JSON and print No UI;
  • use ctx.mode === "tui" Protect terminal-only behavior; use ctx.hasUI Determine whether the interactive/RPC client supports interaction;
  • Make tool and event logic independent of rendering, ensuring that non-interactive mode is available.

10. Errors and Cleanup

  • Report Pi on processor error and try to continue;tool_call Processor failure will block the tool (insurance); tool execution failure will result in erroneous results for the model;
  • in session_shutdown resources are released in Keep idempotent(Cancellation, reload, session replacement, and process exit may take the same path);
  • ctx.shutdown() Requests an orderly shutdown of a process.

11. Official sample navigation

  • Confirm or block tool calls

    Start with this example
    permission-gate.ts
  • Modify prompt snippet for a run

    Start with this example
    prompt-customizer.ts
  • Branch-aware tool status

    Start with this example
    todo.ts
  • Register tool after startup

    Start with this example
    dynamic-tools.ts
  • Run cancelable model calls in command

    Start with this example
    qna.ts
  • Replace main editor

    Start with this example
    modal-editor.ts
  • Finishing touches at closing

    Start with this example
    auto-commit-on-exit.ts
  • Route built-in tools to remote machines

    Start with this example
    ssh.ts
  • OAuth + Custom Streaming Provider

    Start with this example
    custom-provider-gitlab-duo/
  • Subagent/Schedule Mode

    Start with this example
    subagent/、plan-mode/
  • Communication between extensions

    Start with this example
    event-bus.ts
targetStart with this example
Confirm or block tool callspermission-gate.ts
Modify prompt snippet for a runprompt-customizer.ts
Branch-aware tool statustodo.ts
Register tool after startupdynamic-tools.ts
Run cancelable model calls in commandqna.ts
Replace main editormodal-editor.ts
Finishing touches at closingauto-commit-on-exit.ts
Route built-in tools to remote machinesssh.ts
OAuth + Custom Streaming Providercustom-provider-gitlab-duo/
Subagent/Schedule Modesubagent/、plan-mode/
Communication between extensionsevent-bus.ts

12. Small exercises

  1. Hello tool: put hello.ts put in ~/.pi/agent/extensions/, let Pi "greet Mario with the hello tool", with Ctrl+O View tool results.
  2. Permission access control: Transformation permission-gate.ts, additional interception git push --force and curl ... | sh; use pi -p Tests whether it is blocked when there is no UI.
  3. word count tool:Write a word_count Tool, the parameters are path, returns the number of words and lines,details Store numbers in; and add /wc After the command directly calls the same logic ctx.ui.notify。
  4. branch aware counter: imitate todo.ts, implement a counter Tools (inc/get), in /tree Verify that the counter value changes with the branch after switching branches.
  5. Enter shortcut: use input event realization ?zh <文本> → "Translate the following into Chinese:…".
  6. Conversation wrap-up: in session_shutdown Write the token usage of this session in ~/pi-usage.log(Tip: check ctx type declaration on the session/usage API).
  7. Advanced:Read examples/extensions/subagent/, showing how it provides an isolated context window for subtasks.

13. Official sources