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

Pi Agent Event System

Pi Agent Event System

The event system is the core mechanism of extensions.

By listening to lifecycle events, you can insert custom logic at various stages of the AI's work.


Lifecycle overview

The following are all events triggered during Pi Agent's lifecycle from startup to exit:

Pi Agent extended event lifecycle: startup, project trust, session start, turn loop, and session close

Within each turn, the three categories of events—context, provider, and tool—fire in order, looping through multiple rounds when there are tool calls.

Dashed parts indicate that the stage can be triggered multiple times by multiple events.

The trigger timing of input, before_agent_start, resources_discover, agent_settled, and other events is shown in the full event quick-reference table below.


Core events in detail

This section selects the 5 most frequently used events and explains their trigger timing and return value conventions.

input — input interception

Triggered before user input is processed; can transform, intercept, or handle the input directly:

Example

// File path: ~/.pi/agent/extensions/quick-input.ts

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

pi.

on

(

"input"

,

async

(

event

,

ctx

)

=>

{

 

// event.text - raw input text

 

// event.images - attached images

 

// event.source - "interactive" | "rpc" | "extension"

 

// Transform input: add an instruction before the input

 

if

(

event.

text

.

startsWith

(

"?quick "

)

)

{

   

return

{

      action

:

"transform"

,

      text

:

`Brief reply: $

{

event.

text

.

slice

(

7

)

}

`

   

}

;

 

}

 

// Handle directly: respond without going through the LLM

 

if

(

event.

text

===

"ping"

)

{

    ctx.

ui

.

notify

(

"pong"

,

"info"

)

;

   

return

{

action

:

"handled"

}

;

 

}

 

// Skip messages injected by extensions

 

if

(

event.

source

===

"extension"

)

{

   

return

{

action

:

"continue"

}

;

 

}

 

return

{

action

:

"continue"

}

;

 

// Default: process normally

}

)

;

action value effect
"continue" Leave the input unchanged and continue the normal processing flow
"transform" Continue processing after modifying the input; transformations from multiple handlers chain together
"handled" Take over completely, skipping the LLM call (the first handler returning this value takes effect)

The actual effects of the two typical writing styles are as follows.

When entering ?quick hello world, the text actually sent to the LLM has been rewritten:



简短回复:hello world

Entering ping does not call the LLM; only a notification pops up in the terminal:



pong

The input event fires before Skill and template expansion,, so what you see is the raw input.

/skill:foo and /template have not been expanded at this point.


tool_call — tool call interception

Triggered before a tool executes; can modify parameters or block execution:

Example

// File path: ~/.pi/agent/extensions/guard-bash.ts

// The import is at the top level of the module; the pi.on snippet below is inside the extension factory function

// isToolCallEventType is a type guard and must be imported from the official package

import

{

isToolCallEventType

}

from

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

;

pi.

on

(

"tool_call"

,

async

(

event

,

ctx

)

=>

{

 

// Block dangerous bash commands

 

if

(

isToolCallEventType

(

"bash"

,

event

)

)

{

   

// event.input is { command: string; timeout?: number }

   

const

dangerous

=

[

"rm -rf /"

,

"mkfs."

,

"dd if="

,

"> /dev/sda"

]

;

   

// First determine whether it's dangerous, then decide whether to allow it

   

if

(

dangerous.

some

(

cmd

=>

        event.

input

.

command

.

includes

(

cmd

)

)

)

{

     

return

{

block

:

true

,

reason

:

"Dangerous command blocked"

}

;

   

}

   

// Only append environment variable loading after the check passes

    event.

input

.

command

=

`source ~

/

.

profile

\n$

{

event.

input

.

command

}

`

;

 

}

 

// Log all file read operations

 

if

(

isToolCallEventType

(

"read"

,

event

)

)

{

   

// event.input is { path: string; offset?: number; limit?: number }

    ctx.

ui

.

notify

(

`Reading file

:

$

{

event.

input

.

path

}

`

,

"info"

)

;

 

}

}

)

;

If the AI tries to execute rm -rf /, the tool won't run and the terminal shows the block reason:



危险命令已被阻止

event.input is mutable—modifying it directly affects tool execution.


tool_result — modify tool result

Triggered after a tool finishes executing; can modify the result returned to the LLM:

Example

// File path: ~/.pi/agent/extensions/read-linenum.ts

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

pi.

on

(

"tool_result"

,

async

(

event

,

ctx

)

=>

{

 

// event.toolName - tool name

 

// event.content - content returned to the LLM

 

// event.details - detail data

 

// event.isError - whether it's an error

 

// For example: add line numbers to the read result

 

if

(

event.

toolName

===

"read"

&&

!

event.

isError

)

{

   

const

lines

=

event.

content

      .

filter

(

c

=>

c.

type

===

"text"

)

      .

map

(

c

=>

c.

text

)

      .

join

(

"\n"

)

      .

split

(

"\n"

)

      .

map

(

(

line

,

i

)

=>

`$

{

i

1

}

:

$

{

line

}

`

)

      .

join

(

"\n"

)

;

   

return

{

      content

:

[

{

type

:

"text"

,

text

:

lines

}

]

,

   

}

;

 

}

}

)

;

A two-line file content becomes line-numbered when given to the LLM:



1: import { readFile } from "node:fs/promises";

2: export async function load() {


context — modify LLM context

Triggered before each LLM call; can filter or modify messages:

Example

// File path: ~/.pi/agent/extensions/context-filter.ts

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

pi.

on

(

"context"

,

async

(

event

,

ctx

)

=>

{

 

// event.messages - a deep copy of current context messages, safe to modify

 

// Filter out messages of a specific type

 

const

filtered

=

event.

messages

.

filter

(

m

=>

{

   

// Remove messages with custom type "debug"

   

if

(

m.

type

===

"custom"

&&

m.

customType

===

"debug"

)

{

     

return

false

;

   

}

   

return

true

;

 

}

)

;

 

return

{

messages

:

filtered

}

;

}

)

;


before_agent_start — inject messages

Triggered before the AI starts processing user input; can inject extra messages or modify the system prompt:

Example

// File path: ~/.pi/agent/extensions/context-inject.ts

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

pi.

on

(

"before_agent_start"

,

async

(

event

,

ctx

)

=>

{

 

// event.prompt - the user's prompt text

 

// event.systemPrompt - currently configured system prompt

 

return

{

   

// Inject a persistent message (stored in the session, sent to the LLM)

    message

:

{

      customType

:

"my-context"

,

      content

:

`Current time is $

{

new

Date

(

)

.

toISOString

(

)

}

`

,

      display

:

true

,

   

}

,

   

// Append to the system prompt

    systemPrompt

:

event.

systemPrompt

     

"\n\nPlease use Chinese in all replies."

,

 

}

;

}

)

;


Full event quick-reference table

The ASCII diagram in the previous section also showed many events; they're listed here in trigger order for easy reference.

Events Trigger Timing Modifiable Blockable
project_trust Before loading project resources, confirm whether the current project is trusted No Yes (if rejected, project extensions are not loaded)
session_start When a session starts or resumes No No
resources_discover Triggered after session_start (during startup/reload) Yes (can only append Skills, prompt templates, theme paths; cannot add or remove extensions) No
input Before user input is processed Yes (can transform input) Yes (handled takeover)
before_agent_start Before the AI starts processing user input Yes (can inject messages, modify system prompt) No
agent_start When the agent loop starts No No
message_start / message_update During message generation (message_update is the assistant's streaming increment) No No
message_end When user, assistant, and toolResult messages are finalized Yes (can return { message } to replace the final message; role must match) No
turn_start At the start of each turn No No
context Before each LLM call Yes (can filter messages) No
before_provider_headers Before sending HTTP request headers Yes (can add or modify request headers) No
before_provider_request Before the request body is sent to the model Yes (returning a non-undefined value replaces the entire request payload rather than aborting the request) No
after_provider_response After receiving the HTTP response, before the streaming body is consumed No (can only read status/headers for observation) No
tool_execution_start When a tool starts executing No No
tool_call Before tool execution Yes (event.input is mutable) Yes (block: true)
tool_execution_update When progress occurs during tool execution No No
tool_result After tool execution completes Yes (can modify returned content) No
tool_execution_end When tool execution ends No No
turn_end At the end of each turn No No
agent_end When the agent loop ends No No
agent_settled After one interaction round fully settles No No
session_before_switch Before /new or /resume executes No Yes (return { cancel: true })
session_before_fork Before /fork or /clone executes No Yes (return { cancel: true })
session_before_compact Before compaction executes (manual /compact, threshold, context overflow) Yes (can customize the compaction summary) Yes (return { cancel: true })
session_shutdown Triggered before session destruction; exit, /new, /resume, /fork, /reload all trigger it (reason is quit/reload/new/resume/fork) No No

Event handling key points

When writing an event handler, the following points determine whether the code is robust.

Method Purpose
Multiple extensions listening to the same event Execute in extension loading order; the previous return value affects subsequent handlers
Return { block: true, reason: "..." } Block the operation; reason is shown to the user and AI
Return { cancel: true } Cancel operations such as session switching
Use ctx.signal Respond to the cancellation signal in async operations; abort when the user presses Escape
Use the ctx.ui family of methods Interact with the user, such as notify, confirm, select, etc.
Guard dialog calls with ctx.hasUI In Print/JSON/RPC modes, dialog-type methods are unavailable or no-ops; check before calling
Guard TUI-specific APIs with ctx.mode === "tui" custom(), component factories, terminal input, etc. are only valid in interactive mode

Do not start background resources (processes, sockets, timers, etc.) in the extension factory function.

Defer resource startup to the session_start event, and clean up in the session_shutdown event.