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

Pi Agent Command and Shortcut Registration

Pi Agent Command and Shortcut Registration

Register custom commands, keyboard shortcuts, and CLI flags through extensions to better adapt Pi Agent to your workflow.


Registering custom commands

Use pi.registerCommand() to register commands that users can invoke via /.

The extension below demonstrates both a basic command and a command with argument autocompletion:

Example

// File path: ~/.pi/agent/extensions/stats-command.ts

// Basic command

pi.

registerCommand

(

"stats"

,

{

  description

:

"Display statistics for the current session"

,

// Required; shown in the / autocomplete list

  handler

:

async

(

args

,

ctx

)

=>

{

   

const

count

=

ctx.

sessionManager

.

getEntries

(

)

.

length

;

    ctx.

ui

.

notify

(

`Total $

{

count

}

messages`

,

"info"

)

;

 

}

}

)

;

// Command with argument autocompletion

pi.

registerCommand

(

"deploy"

,

{

  description

:

"Deploy to a specified environment"

,

 

// Define argument autocompletion; prefix is the argument prefix the user has entered

  getArgumentCompletions

:

(

prefix

)

=>

{

   

const

envs

=

[

"dev"

,

"staging"

,

"prod"

]

;

   

const

items

=

envs

      .

filter

(

e

=>

e.

startsWith

(

prefix

)

)

      .

map

(

e

=>

(

{

value

:

e

,

label

:

e

}

)

)

;

   

return

items.

length

0

?

items

:

null

;

// Return null when there is no match

 

}

,

  handler

:

async

(

args

,

ctx

)

=>

{

   

if

(

!

args

)

{

      ctx.

ui

.

notify

(

"Usage: /deploy "

,

"warning"

)

;

     

return

;

   

}

    ctx.

ui

.

notify

(

`Deploying to $

{

args

}

environment...`

,

"info"

)

;

 

}

,

}

)

;

After saving, run /reload to load the extension, then enter /stats in the edit area to see the effect:



/stats

共 42 条消息

If multiple extensions register commands with the same name, Pi Agent keeps all registrations and adds a numeric suffix in load order, e.g., /review:1 and /review:2.

This avoids naming conflicts between extensions.


Extensions proactively sending messages

Besides passively responding to commands and events, extensions can also proactively drive the conversation.

pi.sendMessage(message, deliverAs?) is used to inject a custom message, while pi.sendUserMessage(text, deliverAs?) simulates a user input.

deliverAs has three values: steer is the default, inserting the message into the current turn; followUp appends after the current turn ends; nextTurn starts a new turn (only supported by sendMessage).

sendUserMessage always triggers a reply turn because, to the AI, it is a real user utterance.

When calling these two methods during streaming output, deliverAs must be given explicitly, otherwise an error is thrown.

Example

// File path: ~/.pi/agent/extensions/follow-up.ts

// The following snippet is inside the extension factory function body

// Simulate a user adding a request: append after all current tools finish executing

pi.

sendUserMessage

(

"After deployment, please also check the production environment logs"

,

{

  deliverAs

:

"followUp"

,

}

)

;

// Only put reference information into the context, without simulating a user utterance

pi.

sendMessage

(

{

  customType

:

"deploy-context"

,

  content

:

"The current deployment target is production"

,

  display

:

true

,

}

,

{

  deliverAs

:

"steer"

,

// Default value, inserted into the current turn

}

)

;

sendMessage also supports triggerTurn: true, which immediately triggers an LLM response when the agent is idle.

The criterion for choosing between the two is simple: use sendUserMessage when you want the AI to actually respond, and sendMessage when you only want to provide reference information.


Command context (ExtensionCommandContext)

A command's handler receives an ExtensionCommandContext, which inherits from ExtensionContext.

On top of the normal context, it additionally provides the following methods:

Method Description
ctx.getSystemPromptOptions() Read the base inputs used to build the system prompt (contextFiles, skills, etc.); available only in command context
ctx.waitForIdle() Wait until the AI is completely idle (including retries, compaction, and follow-up messages all finished)
ctx.newSession(options) Create a new session, with optional parent session and initialization logic
ctx.fork(entryId, options) Fork a new session from a specified entry
ctx.navigateTree(targetId, options) Navigate to a specified position in the session tree
ctx.switchSession(sessionPath, options) Switch to another session file
ctx.reload() Execute the same hot-reload process as /reload

The command below lists all sessions of the current project as a selection list and switches directly to the chosen one:

Example

// File path: ~/.pi/agent/extensions/switch-session.ts

import

{

SessionManager

}

from

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

;

pi.

registerCommand

(

"switch"

,

{

  description

:

"Switch to another session"

,

  handler

:

async

(

args

,

ctx

)

=>

{

   

// List all sessions of the current project

   

const

sessions

=

await SessionManager.

list

(

ctx.

cwd

)

;

   

if

(

sessions.

length

===

0

)

{

      ctx.

ui

.

notify

(

"No sessions available"

,

"warning"

)

;

     

return

;

   

}

   

// Pop up a selection list

   

const

choice

=

await ctx.

ui

.

select

(

     

"Select the session to switch to:"

,

      sessions.

map

(

s

=>

s.

file

)

,

   

)

;

   

if

(

choice

)

{

     

// Switch to the selected session

      await ctx.

switchSession

(

choice

,

{

        withSession

:

async

(

ctx

)

=>

{

          ctx.

ui

.

notify

(

"Session switched"

,

"info"

)

;

       

}

,

     

}

)

;

   

}

 

}

,

}

)

;



/switch

Select the session to switch to:

│ > ~/.pi/agent/sessions/my-project/abc123.jsonl

│   ~/.pi/agent/sessions/my-project/def456.jsonl

└

已切换会话

Notes on session replacement: the ctx in the withSession callback is a brand-new context.

Do not use the old pi object or the ctx captured in the command callback, as they become invalid after session replacement.


Registering shortcuts

Use pi.registerShortcut() to register custom keyboard shortcuts.

Below we bind "Toggle Plan Mode" to a key combination not yet occupied by any built-in:

Example

// File path: ~/.pi/agent/extensions/plan-shortcut.ts

pi.

registerShortcut

(

"ctrl+shift+g"

,

{

  description

:

"Toggle Plan Mode"

,

  handler

:

async

(

ctx

)

=>

{

    ctx.

ui

.

notify

(

"Plan Mode toggled!"

,

"info"

)

;

 

}

,

}

)

;

After startup, press the key combination to trigger it:



已切换 Plan 模式!

Before choosing a key combination, check the default shortcut table to avoid overriding built-in bindings.

For example, ctrl+shift+p is already occupied by "Switch model backward"; registering the same combination again would cause the two behaviors to compete for the key.

The shortcut format is modifier+key, e.g., ctrl+shift+g, alt+x, etc.


Registering CLI flags

Use pi.registerFlag() to add a custom CLI argument to the pi command.

The example below registers a --plan boolean flag to make the AI produce a plan before taking action:

Example

// File path: ~/.pi/agent/extensions/plan-flag.ts

pi.

registerFlag

(

"plan"

,

{

  description

:

"Start in Plan Mode"

,

  type

:

"boolean"

,

 

default

:

false

,

}

)

;

// Check the flag value in extension code

// Note: pi.getFlag() only has a value after command-line argument parsing completes,

// so it's recommended to put the check inside an event callback rather than at the top level of the extension module.

// Top-level module evaluation happens during extension loading, when the value read is always the default false.

pi.

on

(

"before_agent_start"

,

async

(

event

,

ctx

)

=>

{

 

if

(

!

pi.

getFlag

(

"plan"

)

)

return

;

// If --plan is not enabled, make no changes

 

return

{

    systemPrompt

:

event.

systemPrompt

     

"\n\nPlan Mode: first propose a plan, then execute after user confirmation."

,

 

}

;

}

)

;

Usage:



$ pi --plan "帮我实现用户认证功能"


Communication between extensions

Use pi.events to share events between extensions.

The sender doesn't need to know who is listening, and the listener doesn't need to know where the event came from:

Example

// File path: ~/.pi/agent/extensions/deploy-events.ts

// Extension A: send an event

pi.

events

.

emit

(

"deploy:completed"

,

{

  env

:

"production"

,

  timestamp

:

Date

.

now

(

)

,

}

)

;

// Extension B: listen for the event (usually written in another extension file)

pi.

events

.

on

(

"deploy:completed"

,

(

data

)

=>

{

  console.

log

(

`Deployment complete: $

{

data.

env

}

`

)

;

}

)

;


Getting registered commands

Use pi.getCommands() to get all commands available in the current session.

The example below registers a /my-commands command to list all commands registered by extensions:

Example

// File path: ~/.pi/agent/extensions/list-commands.ts

pi.

registerCommand

(

"my-commands"

,

{

  description

:

"List all commands registered by extensions"

,

  handler

:

async

(

args

,

ctx

)

=>

{

   

const

commands

=

pi.

getCommands

(

)

;

   

// Group by source

   

const

extCommands

=

commands.

filter

(

      c

=>

c.

source

===

"extension"

   

)

;

   

const

templates

=

commands.

filter

(

      c

=>

c.

source

===

"prompt"

   

)

;

   

const

skills

=

commands.

filter

(

      c

=>

c.

source

===

"skill"

   

)

;

   

// Display the results, avoiding computing without output

    ctx.

ui

.

notify

(

      `Extension commands $

{

extCommands.

length

}

:`

       

extCommands.

map

(

c

=>

"/"

c.

name

)

.

join

(

"、"

)

,

     

"info"

   

)

;

    console.

table

(

commands

)

;

 

}

,

}

)

;



/my-commands

扩展命令 2 个:/stats、/deploy

Each command entry contains the following fields:

Field Type Description
name string Command name, invoked as /name in the edit area
description string Command description, shown in the autocomplete list
source string Source type: extension, prompt, skill, etc.
sourceInfo object Detailed source metadata, such as the extension path that registered it

Dynamic tool management

Enable and disable tools at runtime.

A typical use is to temporarily turn off write tools so the AI can only read but not modify during a task:

Example

// File path: ~/.pi/agent/extensions/manage-tools.ts

// Get the list of currently enabled tools

const

active

=

pi.

getActiveTools

(

)

;

// For example: ["read", "bash", "edit", "write"]

// Get metadata of all registered tools

const

all

=

pi.

getAllTools

(

)

;

// Filter built-in tools

const

builtinTools

=

all.

filter

(

  t

=>

t.

sourceInfo

.

source

===

"builtin"

)

;

// Filter tools registered by extensions

const

extTools

=

all.

filter

(

  t

=>

t.

sourceInfo

.

source

!==

"builtin"

   

&&

t.

sourceInfo

.

source

!==

"sdk"

)

;

// Dynamically enable custom tools (keep existing tools)

pi.

setActiveTools

(

[

...

new

Set

(

[

...

active

,

"my_tool"

]

)

]

)

;

// Switch to read-only mode: keep only read-type tools,

// excluding bash / edit / write; the AI cannot execute commands or modify files in this state

pi.

setActiveTools

(

[

"read"

,

"grep"

,

"find"

,

"ls"

]

)

;

The setActiveTools here and the command-line --tools / --exclude-tools option act on the same set of tools.

CLI options determine the initial set at startup, while setActiveTools adjusts it dynamically at runtime; the two can be used together.

Changes passed to setActiveTools must be additive; removing currently active tools in the same call loses the lazy-loading optimization.

In addition, activating a tool with promptSnippet or promptGuidelines rebuilds the system prompt, which can invalidate the cached prompt prefix even if the model supports lazy loading.