Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pi Agent Extension Getting Started

Pi Agent Extension Getting Started

Extensions are Pi Agent's most powerful customization method—you can write custom tools, commands, and event listeners in TypeScript.


What is an Extension

An Extension is a TypeScript module that can do the following things.

Capability Description Typical use
Register custom tools Add new callable capabilities to the AI Query internal systems, read/write databases, wrap third-party APIs
Registering custom commands Users invoke via /command-name Wrap common prompts, one-click execution of fixed workflows
Listen to lifecycle events Insert logic at various stages of the AI's work Intercept dangerous commands, inject context, log audit trails
Register keyboard shortcuts Bind keys in the terminal interface Quickly switch panels, trigger frequent operations
Display custom UI Render interactive interfaces in the terminal Components such as progress bars, lists, confirmation dialogs

First Extension: Hello World

The following extension demonstrates event listening, tool registration, and command registration all at once.

Example

// File path: ~/.pi/agent/extensions/my-extension.ts

import

type

{

ExtensionAPI

}

from

"@earendil-works/pi-coding-agent"

;

import

{

Type

}

from

"typebox"

;

export

default

function

(

pi

:

ExtensionAPI

)

{

 

// Triggered when the session starts

  pi.

on

(

"session_start"

,

async

(

_event

,

ctx

)

=>

{

    ctx.

ui

.

notify

(

"My extension has loaded!"

,

"info"

)

;

 

}

)

;

 

// Intercept dangerous commands

  pi.

on

(

"tool_call"

,

async

(

event

,

ctx

)

=>

{

   

if

(

event.

toolName

===

"bash"

       

&&

event.

input

.

command

?

.

includes

(

"rm -rf"

)

)

{

     

const

ok

=

await ctx.

ui

.

confirm

(

"Dangerous operation!"

,

"Confirm execution of rm -rf?"

)

;

     

if

(

!

ok

)

return

{

block

:

true

,

reason

:

"User blocked"

}

;

   

}

 

}

)

;

 

// Register a custom tool

  pi.

registerTool

(

{

    name

:

"greet"

,

    label

:

"Say hello"

,

    description

:

"Greet a specified person"

,

    parameters

:

Type.

Object

(

{

      name

:

Type.

String

(

{

description

:

"Name of the person to greet"

}

)

,

   

}

)

,

    async execute

(

toolCallId

,

params

)

{

     

return

{

        content

:

[

{

type

:

"text"

,

text

:

`Hello, $

{

params.

name

}

!`

}

]

,

        details

:

{

}

,

     

}

;

   

}

,

 

}

)

;

 

// Register a custom command

  pi.

registerCommand

(

"hello"

,

{

    description

:

"Say hello to the world"

,

    handler

:

async

(

args

,

ctx

)

=>

{

      ctx.

ui

.

notify

(

`Hello $

{

args

||

"World"

}

!`

,

"info"

)

;

   

}

,

 

}

)

;

}

Line 13's event check uses the simplest event.toolName form; you can also use a type guard to narrow event to a specific event type, see the "Event System" chapter.

Start Pi Agent with the pi -e argument to load this extension for testing:



$ pi -e ~/.pi/agent/extensions/my-extension.ts

Loading extension: /Users/runoob/.pi/agent/extensions/my-extension.ts

my-extension 加载成功(1 个工具、1 个命令)

我的扩展已加载!

The last line is the notification popped up by ctx.ui.notify in the session_start event, indicating the extension is working.


Extension loading locations

Pi Agent automatically discovers extensions in several fixed directories, and you can also explicitly specify paths.

Position Scope Description
~/.pi/agent/extensions/*.ts Global Applies to all projects, auto-discovered
~/.pi/agent/extensions/*/index.ts Global Extensions with index.ts in subdirectories
.pi/extensions/*.ts Projects Current project only, requires project trust
.pi/extensions/*/index.ts Projects Project subdirectory extensions

Besides command-line arguments, you can also write an array of paths in the extensions field of settings.json; directory paths are expanded according to extension directory rules.

Example

{

  "extensions": [

    "/Users/runoob/.pi/agent/extensions/quick-notify.ts",

    "/Users/runoob/.pi/agent/extensions/team-tools"

  ]

}

The first element is a single-file extension, the second is a directory extension; just replace them with your own extension locations when actually using.


Extension file structure

An Extension can be a single .ts file or a directory with an entry file.

Single-file extension

The simplest form, suitable for small extensions:



~/.pi/agent/extensions/

└── my-extension.ts

Directory extension (with index.ts)

Suitable for multi-file extensions:



~/.pi/agent/extensions/

└── my-extension/

    ├── index.ts        # 入口文件(导出默认函数)

    ├── tools.ts        # 辅助模块

    └── utils.ts        # 工具函数

Extension with dependencies

Suitable for large extensions that need npm packages:



~/.pi/agent/extensions/

└── my-extension/

    ├── package.json    # 声明依赖和入口

    ├── node_modules/   # npm install 后生成

    └── src/

        └── index.ts

Extensions run with your system privileges and can execute arbitrary code.

Only install extensions from trusted sources。


Extension loading mechanism

Extensions are loaded via jiti , and TypeScript code runs directly without compilation.

If your factory function returns a Promise, Pi Agent waits for it to complete before continuing the startup process.

This means you can perform async operations during extension initialization, such as fetching remote configuration.


Available Import packages

These packages are provided built-in by Pi Agent and can be imported directly in extensions.

Package name Purpose
@earendil-works/pi-coding-agent Extension types (ExtensionAPI, ExtensionContext, and various event types)
typebox Schema definitions for tool parameters
@earendil-works/pi-ai AI tools (such as StringEnum for Google-compatible enums)
@earendil-works/pi-tui TUI components for custom rendering

These built-in core packages are provided by Pi itself; list them as peerDependencies and do not bundle them into your extension.

Your own runtime dependencies must be written in the dependencies field of package.json.

When Pi installs an extension package, it performs a production install by default (npm install --omit=dev), and devDependencies are unavailable at runtime.

Other npm packages can also be used—just add package.json in the extension directory and run npm install.


Development tips

These tips can help you avoid detours, especially the choice of loading method.

Approach Reason
Put extensions in the ~/.pi/agent/extensions/ directory Supports /reload hot reload; no session restart needed after changes
pi -e ./path.ts is only for temporary testing For long-term use, put extensions in the ~/.pi/agent/extensions/ directory for auto-discovery by Pi Agent
Do not start background resources in the extension factory function Processes, sockets, file watchers, timers, etc. should be started in the session_start event
Clean up session-level resources in the session_shutdown event Avoid leftover handles and listeners after switching sessions

Further integration

Besides writing extensions, there are two officially provided programmatic integration routes.

Node or TypeScript projects can directly use the SDK exported by @earendil-works/pi-coding-agent: use createAgentSession to create a session, subscribe to subscribe to events, and prompt to send messages.

This approach runs in the same process as Pi, with complete type definitions.

For cross-language calls or when process isolation is needed, use pi --mode rpc instead, communicating with the Pi process via the JSONL protocol.

Both routes share the same event model as extensions; which to choose mainly depends on whether you need a separate process.