@eminent337/aery 0.67.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/CHANGELOG.md +3768 -0
  2. package/README.md +623 -0
  3. package/docs/compaction.md +394 -0
  4. package/docs/custom-provider.md +637 -0
  5. package/docs/development.md +71 -0
  6. package/docs/extensions.md +2368 -0
  7. package/docs/images/doom-extension.png +0 -0
  8. package/docs/images/exy.png +0 -0
  9. package/docs/images/interactive-mode.png +0 -0
  10. package/docs/images/tree-view.png +0 -0
  11. package/docs/json.md +82 -0
  12. package/docs/keybindings.md +197 -0
  13. package/docs/models.md +395 -0
  14. package/docs/packages.md +218 -0
  15. package/docs/prompt-templates.md +88 -0
  16. package/docs/providers.md +195 -0
  17. package/docs/rpc.md +1407 -0
  18. package/docs/sdk.md +1149 -0
  19. package/docs/session.md +412 -0
  20. package/docs/settings.md +247 -0
  21. package/docs/shell-aliases.md +13 -0
  22. package/docs/skills.md +232 -0
  23. package/docs/terminal-setup.md +106 -0
  24. package/docs/termux.md +127 -0
  25. package/docs/themes.md +295 -0
  26. package/docs/tmux.md +61 -0
  27. package/docs/tree.md +233 -0
  28. package/docs/tui.md +918 -0
  29. package/docs/windows.md +17 -0
  30. package/examples/README.md +25 -0
  31. package/examples/extensions/README.md +208 -0
  32. package/examples/extensions/antigravity-image-gen.ts +418 -0
  33. package/examples/extensions/auto-commit-on-exit.ts +49 -0
  34. package/examples/extensions/bash-spawn-hook.ts +30 -0
  35. package/examples/extensions/bookmark.ts +50 -0
  36. package/examples/extensions/built-in-tool-renderer.ts +249 -0
  37. package/examples/extensions/claude-rules.ts +86 -0
  38. package/examples/extensions/commands.ts +72 -0
  39. package/examples/extensions/confirm-destructive.ts +59 -0
  40. package/examples/extensions/custom-compaction.ts +127 -0
  41. package/examples/extensions/custom-footer.ts +64 -0
  42. package/examples/extensions/custom-header.ts +73 -0
  43. package/examples/extensions/custom-provider-anthropic/index.ts +604 -0
  44. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  45. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  46. package/examples/extensions/custom-provider-gitlab-duo/index.ts +349 -0
  47. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  48. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
  49. package/examples/extensions/custom-provider-qwen-cli/index.ts +345 -0
  50. package/examples/extensions/custom-provider-qwen-cli/package.json +16 -0
  51. package/examples/extensions/dirty-repo-guard.ts +56 -0
  52. package/examples/extensions/doom-overlay/README.md +46 -0
  53. package/examples/extensions/doom-overlay/doom/build/doom.js +21 -0
  54. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  55. package/examples/extensions/doom-overlay/doom/build.sh +152 -0
  56. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  57. package/examples/extensions/doom-overlay/doom-component.ts +132 -0
  58. package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
  59. package/examples/extensions/doom-overlay/doom-keys.ts +104 -0
  60. package/examples/extensions/doom-overlay/index.ts +74 -0
  61. package/examples/extensions/doom-overlay/wad-finder.ts +51 -0
  62. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  63. package/examples/extensions/dynamic-resources/dynamic.json +79 -0
  64. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  65. package/examples/extensions/dynamic-resources/index.ts +15 -0
  66. package/examples/extensions/dynamic-tools.ts +74 -0
  67. package/examples/extensions/event-bus.ts +43 -0
  68. package/examples/extensions/file-trigger.ts +41 -0
  69. package/examples/extensions/git-checkpoint.ts +53 -0
  70. package/examples/extensions/handoff.ts +153 -0
  71. package/examples/extensions/hello.ts +26 -0
  72. package/examples/extensions/hidden-thinking-label.ts +53 -0
  73. package/examples/extensions/inline-bash.ts +94 -0
  74. package/examples/extensions/input-transform.ts +43 -0
  75. package/examples/extensions/interactive-shell.ts +196 -0
  76. package/examples/extensions/mac-system-theme.ts +47 -0
  77. package/examples/extensions/message-renderer.ts +59 -0
  78. package/examples/extensions/minimal-mode.ts +426 -0
  79. package/examples/extensions/modal-editor.ts +85 -0
  80. package/examples/extensions/model-status.ts +31 -0
  81. package/examples/extensions/notify.ts +55 -0
  82. package/examples/extensions/overlay-qa-tests.ts +1348 -0
  83. package/examples/extensions/overlay-test.ts +150 -0
  84. package/examples/extensions/permission-gate.ts +34 -0
  85. package/examples/extensions/pirate.ts +47 -0
  86. package/examples/extensions/plan-mode/README.md +65 -0
  87. package/examples/extensions/plan-mode/index.ts +340 -0
  88. package/examples/extensions/plan-mode/utils.ts +168 -0
  89. package/examples/extensions/preset.ts +430 -0
  90. package/examples/extensions/protected-paths.ts +30 -0
  91. package/examples/extensions/provider-payload.ts +18 -0
  92. package/examples/extensions/qna.ts +122 -0
  93. package/examples/extensions/question.ts +264 -0
  94. package/examples/extensions/questionnaire.ts +427 -0
  95. package/examples/extensions/rainbow-editor.ts +88 -0
  96. package/examples/extensions/reload-runtime.ts +37 -0
  97. package/examples/extensions/rpc-demo.ts +118 -0
  98. package/examples/extensions/sandbox/index.ts +321 -0
  99. package/examples/extensions/sandbox/package-lock.json +92 -0
  100. package/examples/extensions/sandbox/package.json +19 -0
  101. package/examples/extensions/send-user-message.ts +97 -0
  102. package/examples/extensions/session-name.ts +27 -0
  103. package/examples/extensions/shutdown-command.ts +63 -0
  104. package/examples/extensions/snake.ts +343 -0
  105. package/examples/extensions/space-invaders.ts +560 -0
  106. package/examples/extensions/ssh.ts +220 -0
  107. package/examples/extensions/status-line.ts +32 -0
  108. package/examples/extensions/subagent/README.md +172 -0
  109. package/examples/extensions/subagent/agents/planner.md +37 -0
  110. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  111. package/examples/extensions/subagent/agents/scout.md +50 -0
  112. package/examples/extensions/subagent/agents/worker.md +24 -0
  113. package/examples/extensions/subagent/agents.ts +126 -0
  114. package/examples/extensions/subagent/index.ts +987 -0
  115. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  116. package/examples/extensions/subagent/prompts/implement.md +10 -0
  117. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  118. package/examples/extensions/summarize.ts +206 -0
  119. package/examples/extensions/system-prompt-header.ts +17 -0
  120. package/examples/extensions/tic-tac-toe.ts +1008 -0
  121. package/examples/extensions/timed-confirm.ts +70 -0
  122. package/examples/extensions/titlebar-spinner.ts +58 -0
  123. package/examples/extensions/todo.ts +297 -0
  124. package/examples/extensions/tool-override.ts +144 -0
  125. package/examples/extensions/tools.ts +141 -0
  126. package/examples/extensions/trigger-compact.ts +50 -0
  127. package/examples/extensions/truncated-tool.ts +195 -0
  128. package/examples/extensions/widget-placement.ts +9 -0
  129. package/examples/extensions/with-deps/index.ts +32 -0
  130. package/examples/extensions/with-deps/package-lock.json +31 -0
  131. package/examples/extensions/with-deps/package.json +22 -0
  132. package/examples/extensions/working-indicator.ts +123 -0
  133. package/examples/rpc-extension-ui.ts +632 -0
  134. package/examples/sdk/01-minimal.ts +22 -0
  135. package/examples/sdk/02-custom-model.ts +49 -0
  136. package/examples/sdk/03-custom-prompt.ts +62 -0
  137. package/examples/sdk/04-skills.ts +55 -0
  138. package/examples/sdk/05-tools.ts +44 -0
  139. package/examples/sdk/06-extensions.ts +90 -0
  140. package/examples/sdk/07-context-files.ts +42 -0
  141. package/examples/sdk/08-prompt-templates.ts +51 -0
  142. package/examples/sdk/09-api-keys-and-oauth.ts +48 -0
  143. package/examples/sdk/10-settings.ts +53 -0
  144. package/examples/sdk/11-sessions.ts +48 -0
  145. package/examples/sdk/12-full-control.ts +73 -0
  146. package/examples/sdk/13-session-runtime.ts +67 -0
  147. package/examples/sdk/README.md +147 -0
  148. package/package.json +102 -0
@@ -0,0 +1,2368 @@
1
+ > pi can create extensions. Ask it to build one for your use case.
2
+
3
+ # Extensions
4
+
5
+ Extensions are TypeScript modules that extend pi's behavior. They can subscribe to lifecycle events, register custom tools callable by the LLM, add commands, and more.
6
+
7
+ > **Placement for /reload:** Put extensions in `~/.pi/agent/extensions/` (global) or `.pi/extensions/` (project-local) for auto-discovery. Use `pi -e ./path.ts` only for quick tests. Extensions in auto-discovered locations can be hot-reloaded with `/reload`.
8
+
9
+ **Key capabilities:**
10
+ - **Custom tools** - Register tools the LLM can call via `pi.registerTool()`
11
+ - **Event interception** - Block or modify tool calls, inject context, customize compaction
12
+ - **User interaction** - Prompt users via `ctx.ui` (select, confirm, input, notify)
13
+ - **Custom UI components** - Full TUI components with keyboard input via `ctx.ui.custom()` for complex interactions
14
+ - **Custom commands** - Register commands like `/mycommand` via `pi.registerCommand()`
15
+ - **Session persistence** - Store state that survives restarts via `pi.appendEntry()`
16
+ - **Custom rendering** - Control how tool calls/results and messages appear in TUI
17
+
18
+ **Example use cases:**
19
+ - Permission gates (confirm before `rm -rf`, `sudo`, etc.)
20
+ - Git checkpointing (stash at each turn, restore on branch)
21
+ - Path protection (block writes to `.env`, `node_modules/`)
22
+ - Custom compaction (summarize conversation your way)
23
+ - Conversation summaries (see `summarize.ts` example)
24
+ - Interactive tools (questions, wizards, custom dialogs)
25
+ - Stateful tools (todo lists, connection pools)
26
+ - External integrations (file watchers, webhooks, CI triggers)
27
+ - Games while you wait (see `snake.ts` example)
28
+
29
+ See [examples/extensions/](../examples/extensions/) for working implementations.
30
+
31
+ ## Table of Contents
32
+
33
+ - [Quick Start](#quick-start)
34
+ - [Extension Locations](#extension-locations)
35
+ - [Available Imports](#available-imports)
36
+ - [Writing an Extension](#writing-an-extension)
37
+ - [Extension Styles](#extension-styles)
38
+ - [Events](#events)
39
+ - [Lifecycle Overview](#lifecycle-overview)
40
+ - [Resource Events](#resource-events)
41
+ - [Session Events](#session-events)
42
+ - [Agent Events](#agent-events)
43
+ - [Tool Events](#tool-events)
44
+ - [ExtensionContext](#extensioncontext)
45
+ - [ExtensionCommandContext](#extensioncommandcontext)
46
+ - [ExtensionAPI Methods](#extensionapi-methods)
47
+ - [State Management](#state-management)
48
+ - [Custom Tools](#custom-tools)
49
+ - [Custom UI](#custom-ui)
50
+ - [Error Handling](#error-handling)
51
+ - [Mode Behavior](#mode-behavior)
52
+ - [Examples Reference](#examples-reference)
53
+
54
+ ## Quick Start
55
+
56
+ Create `~/.pi/agent/extensions/my-extension.ts`:
57
+
58
+ ```typescript
59
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
60
+ import { Type } from "@sinclair/typebox";
61
+
62
+ export default function (pi: ExtensionAPI) {
63
+ // React to events
64
+ pi.on("session_start", async (_event, ctx) => {
65
+ ctx.ui.notify("Extension loaded!", "info");
66
+ });
67
+
68
+ pi.on("tool_call", async (event, ctx) => {
69
+ if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {
70
+ const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
71
+ if (!ok) return { block: true, reason: "Blocked by user" };
72
+ }
73
+ });
74
+
75
+ // Register a custom tool
76
+ pi.registerTool({
77
+ name: "greet",
78
+ label: "Greet",
79
+ description: "Greet someone by name",
80
+ parameters: Type.Object({
81
+ name: Type.String({ description: "Name to greet" }),
82
+ }),
83
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
84
+ return {
85
+ content: [{ type: "text", text: `Hello, ${params.name}!` }],
86
+ details: {},
87
+ };
88
+ },
89
+ });
90
+
91
+ // Register a command
92
+ pi.registerCommand("hello", {
93
+ description: "Say hello",
94
+ handler: async (args, ctx) => {
95
+ ctx.ui.notify(`Hello ${args || "world"}!`, "info");
96
+ },
97
+ });
98
+ }
99
+ ```
100
+
101
+ Test with `--extension` (or `-e`) flag:
102
+
103
+ ```bash
104
+ pi -e ./my-extension.ts
105
+ ```
106
+
107
+ ## Extension Locations
108
+
109
+ > **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust.
110
+
111
+ Extensions are auto-discovered from:
112
+
113
+ | Location | Scope |
114
+ |----------|-------|
115
+ | `~/.pi/agent/extensions/*.ts` | Global (all projects) |
116
+ | `~/.pi/agent/extensions/*/index.ts` | Global (subdirectory) |
117
+ | `.pi/extensions/*.ts` | Project-local |
118
+ | `.pi/extensions/*/index.ts` | Project-local (subdirectory) |
119
+
120
+ Additional paths via `settings.json`:
121
+
122
+ ```json
123
+ {
124
+ "packages": [
125
+ "npm:@foo/bar@1.0.0",
126
+ "git:github.com/user/repo@v1"
127
+ ],
128
+ "extensions": [
129
+ "/path/to/local/extension.ts",
130
+ "/path/to/local/extension/dir"
131
+ ]
132
+ }
133
+ ```
134
+
135
+ To share extensions via npm or git as pi packages, see [packages.md](packages.md).
136
+
137
+ ## Available Imports
138
+
139
+ | Package | Purpose |
140
+ |---------|---------|
141
+ | `@mariozechner/pi-coding-agent` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) |
142
+ | `@sinclair/typebox` | Schema definitions for tool parameters |
143
+ | `@mariozechner/pi-ai` | AI utilities (`StringEnum` for Google-compatible enums) |
144
+ | `@mariozechner/pi-tui` | TUI components for custom rendering |
145
+
146
+ npm dependencies work too. Add a `package.json` next to your extension (or in a parent directory), run `npm install`, and imports from `node_modules/` are resolved automatically.
147
+
148
+ For distributed pi packages installed with `pi install` (npm or git), runtime deps must be in `dependencies`. Package installation uses production installs (`npm install --omit=dev`), so `devDependencies` are not available at runtime.
149
+
150
+ Node.js built-ins (`node:fs`, `node:path`, etc.) are also available.
151
+
152
+ ## Writing an Extension
153
+
154
+ An extension exports a default factory function that receives `ExtensionAPI`. The factory can be synchronous or asynchronous:
155
+
156
+ ```typescript
157
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
158
+
159
+ export default function (pi: ExtensionAPI) {
160
+ // Subscribe to events
161
+ pi.on("event_name", async (event, ctx) => {
162
+ // ctx.ui for user interaction
163
+ const ok = await ctx.ui.confirm("Title", "Are you sure?");
164
+ ctx.ui.notify("Done!", "success");
165
+ ctx.ui.setStatus("my-ext", "Processing..."); // Footer status
166
+ ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
167
+ });
168
+
169
+ // Register tools, commands, shortcuts, flags
170
+ pi.registerTool({ ... });
171
+ pi.registerCommand("name", { ... });
172
+ pi.registerShortcut("ctrl+x", { ... });
173
+ pi.registerFlag("my-flag", { ... });
174
+ }
175
+ ```
176
+
177
+ Extensions are loaded via [jiti](https://github.com/unjs/jiti), so TypeScript works without compilation.
178
+
179
+ If the factory returns a `Promise`, pi awaits it before continuing startup. That means async initialization completes before `session_start`, before `resources_discover`, and before provider registrations queued via `pi.registerProvider()` are flushed.
180
+
181
+ ### Async factory functions
182
+
183
+ Use an async factory for one-time startup work such as fetching remote configuration or dynamically discovering available models.
184
+
185
+ ```typescript
186
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
187
+
188
+ export default async function (pi: ExtensionAPI) {
189
+ const response = await fetch("http://localhost:1234/v1/models");
190
+ const payload = (await response.json()) as {
191
+ data: Array<{
192
+ id: string;
193
+ name?: string;
194
+ context_window?: number;
195
+ max_tokens?: number;
196
+ }>;
197
+ };
198
+
199
+ pi.registerProvider("local-openai", {
200
+ baseUrl: "http://localhost:1234/v1",
201
+ apiKey: "LOCAL_OPENAI_API_KEY",
202
+ api: "openai-completions",
203
+ models: payload.data.map((model) => ({
204
+ id: model.id,
205
+ name: model.name ?? model.id,
206
+ reasoning: false,
207
+ input: ["text"],
208
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
209
+ contextWindow: model.context_window ?? 128000,
210
+ maxTokens: model.max_tokens ?? 4096,
211
+ })),
212
+ });
213
+ }
214
+ ```
215
+
216
+ This pattern makes the fetched models available during normal startup and to `pi --list-models`.
217
+
218
+ ### Extension Styles
219
+
220
+ **Single file** - simplest, for small extensions:
221
+
222
+ ```
223
+ ~/.pi/agent/extensions/
224
+ └── my-extension.ts
225
+ ```
226
+
227
+ **Directory with index.ts** - for multi-file extensions:
228
+
229
+ ```
230
+ ~/.pi/agent/extensions/
231
+ └── my-extension/
232
+ ├── index.ts # Entry point (exports default function)
233
+ ├── tools.ts # Helper module
234
+ └── utils.ts # Helper module
235
+ ```
236
+
237
+ **Package with dependencies** - for extensions that need npm packages:
238
+
239
+ ```
240
+ ~/.pi/agent/extensions/
241
+ └── my-extension/
242
+ ├── package.json # Declares dependencies and entry points
243
+ ├── package-lock.json
244
+ ├── node_modules/ # After npm install
245
+ └── src/
246
+ └── index.ts
247
+ ```
248
+
249
+ ```json
250
+ // package.json
251
+ {
252
+ "name": "my-extension",
253
+ "dependencies": {
254
+ "zod": "^3.0.0",
255
+ "chalk": "^5.0.0"
256
+ },
257
+ "pi": {
258
+ "extensions": ["./src/index.ts"]
259
+ }
260
+ }
261
+ ```
262
+
263
+ Run `npm install` in the extension directory, then imports from `node_modules/` work automatically.
264
+
265
+ ## Events
266
+
267
+ ### Lifecycle Overview
268
+
269
+ ```
270
+ pi starts
271
+
272
+ ├─► session_start { reason: "startup" }
273
+ └─► resources_discover { reason: "startup" }
274
+
275
+
276
+ user sends prompt ─────────────────────────────────────────┐
277
+ │ │
278
+ ├─► (extension commands checked first, bypass if found) │
279
+ ├─► input (can intercept, transform, or handle) │
280
+ ├─► (skill/template expansion if not handled) │
281
+ ├─► before_agent_start (can inject message, modify system prompt)
282
+ ├─► agent_start │
283
+ ├─► message_start / message_update / message_end │
284
+ │ │
285
+ │ ┌─── turn (repeats while LLM calls tools) ───┐ │
286
+ │ │ │ │
287
+ │ ├─► turn_start │ │
288
+ │ ├─► context (can modify messages) │ │
289
+ │ ├─► before_provider_request (can inspect or replace payload)
290
+ │ ├─► after_provider_response (status + headers, before stream consume)
291
+ │ │ │ │
292
+ │ │ LLM responds, may call tools: │ │
293
+ │ │ ├─► tool_execution_start │ │
294
+ │ │ ├─► tool_call (can block) │ │
295
+ │ │ ├─► tool_execution_update │ │
296
+ │ │ ├─► tool_result (can modify) │ │
297
+ │ │ └─► tool_execution_end │ │
298
+ │ │ │ │
299
+ │ └─► turn_end │ │
300
+ │ │
301
+ └─► agent_end │
302
+
303
+ user sends another prompt ◄────────────────────────────────┘
304
+
305
+ /new (new session) or /resume (switch session)
306
+ ├─► session_before_switch (can cancel)
307
+ ├─► session_shutdown
308
+ ├─► session_start { reason: "new" | "resume", previousSessionFile? }
309
+ └─► resources_discover { reason: "startup" }
310
+
311
+ /fork or /clone
312
+ ├─► session_before_fork (can cancel)
313
+ ├─► session_shutdown
314
+ ├─► session_start { reason: "fork", previousSessionFile }
315
+ └─► resources_discover { reason: "startup" }
316
+
317
+ /compact or auto-compaction
318
+ ├─► session_before_compact (can cancel or customize)
319
+ └─► session_compact
320
+
321
+ /tree navigation
322
+ ├─► session_before_tree (can cancel or customize)
323
+ └─► session_tree
324
+
325
+ /model or Ctrl+P (model selection/cycling)
326
+ └─► model_select
327
+
328
+ exit (Ctrl+C, Ctrl+D, SIGHUP, SIGTERM)
329
+ └─► session_shutdown
330
+ ```
331
+
332
+ ### Resource Events
333
+
334
+ #### resources_discover
335
+
336
+ Fired after `session_start` so extensions can contribute additional skill, prompt, and theme paths.
337
+ The startup path uses `reason: "startup"`. Reload uses `reason: "reload"`.
338
+
339
+ ```typescript
340
+ pi.on("resources_discover", async (event, _ctx) => {
341
+ // event.cwd - current working directory
342
+ // event.reason - "startup" | "reload"
343
+ return {
344
+ skillPaths: ["/path/to/skills"],
345
+ promptPaths: ["/path/to/prompts"],
346
+ themePaths: ["/path/to/themes"],
347
+ };
348
+ });
349
+ ```
350
+
351
+ ### Session Events
352
+
353
+ See [session.md](session.md) for session storage internals and the SessionManager API.
354
+
355
+ #### session_start
356
+
357
+ Fired when a session is started, loaded, or reloaded.
358
+
359
+ ```typescript
360
+ pi.on("session_start", async (event, ctx) => {
361
+ // event.reason - "startup" | "reload" | "new" | "resume" | "fork"
362
+ // event.previousSessionFile - present for "new", "resume", and "fork"
363
+ ctx.ui.notify(`Session: ${ctx.sessionManager.getSessionFile() ?? "ephemeral"}`, "info");
364
+ });
365
+ ```
366
+
367
+ #### session_before_switch
368
+
369
+ Fired before starting a new session (`/new`) or switching sessions (`/resume`).
370
+
371
+ ```typescript
372
+ pi.on("session_before_switch", async (event, ctx) => {
373
+ // event.reason - "new" or "resume"
374
+ // event.targetSessionFile - session we're switching to (only for "resume")
375
+
376
+ if (event.reason === "new") {
377
+ const ok = await ctx.ui.confirm("Clear?", "Delete all messages?");
378
+ if (!ok) return { cancel: true };
379
+ }
380
+ });
381
+ ```
382
+
383
+ After a successful switch or new-session action, pi emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "new" | "resume"` and `previousSessionFile`.
384
+ Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
385
+
386
+ #### session_before_fork
387
+
388
+ Fired when forking via `/fork` or cloning via `/clone`.
389
+
390
+ ```typescript
391
+ pi.on("session_before_fork", async (event, ctx) => {
392
+ // event.entryId - ID of the selected entry
393
+ // event.position - "before" for /fork, "at" for /clone
394
+ return { cancel: true }; // Cancel fork/clone
395
+ // OR
396
+ return { skipConversationRestore: true }; // Reserved for future conversation restore control
397
+ });
398
+ ```
399
+
400
+ After a successful fork or clone, pi emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "fork"` and `previousSessionFile`.
401
+ Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
402
+
403
+ #### session_before_compact / session_compact
404
+
405
+ Fired on compaction. See [compaction.md](compaction.md) for details.
406
+
407
+ ```typescript
408
+ pi.on("session_before_compact", async (event, ctx) => {
409
+ const { preparation, branchEntries, customInstructions, signal } = event;
410
+
411
+ // Cancel:
412
+ return { cancel: true };
413
+
414
+ // Custom summary:
415
+ return {
416
+ compaction: {
417
+ summary: "...",
418
+ firstKeptEntryId: preparation.firstKeptEntryId,
419
+ tokensBefore: preparation.tokensBefore,
420
+ }
421
+ };
422
+ });
423
+
424
+ pi.on("session_compact", async (event, ctx) => {
425
+ // event.compactionEntry - the saved compaction
426
+ // event.fromExtension - whether extension provided it
427
+ });
428
+ ```
429
+
430
+ #### session_before_tree / session_tree
431
+
432
+ Fired on `/tree` navigation. See [tree.md](tree.md) for tree navigation concepts.
433
+
434
+ ```typescript
435
+ pi.on("session_before_tree", async (event, ctx) => {
436
+ const { preparation, signal } = event;
437
+ return { cancel: true };
438
+ // OR provide custom summary:
439
+ return { summary: { summary: "...", details: {} } };
440
+ });
441
+
442
+ pi.on("session_tree", async (event, ctx) => {
443
+ // event.newLeafId, oldLeafId, summaryEntry, fromExtension
444
+ });
445
+ ```
446
+
447
+ #### session_shutdown
448
+
449
+ Fired on exit (Ctrl+C, Ctrl+D, SIGHUP, SIGTERM).
450
+
451
+ ```typescript
452
+ pi.on("session_shutdown", async (_event, ctx) => {
453
+ // Cleanup, save state, etc.
454
+ });
455
+ ```
456
+
457
+ ### Agent Events
458
+
459
+ #### before_agent_start
460
+
461
+ Fired after user submits prompt, before agent loop. Can inject a message and/or modify the system prompt.
462
+
463
+ ```typescript
464
+ pi.on("before_agent_start", async (event, ctx) => {
465
+ // event.prompt - user's prompt text
466
+ // event.images - attached images (if any)
467
+ // event.systemPrompt - current system prompt
468
+
469
+ return {
470
+ // Inject a persistent message (stored in session, sent to LLM)
471
+ message: {
472
+ customType: "my-extension",
473
+ content: "Additional context for the LLM",
474
+ display: true,
475
+ },
476
+ // Replace the system prompt for this turn (chained across extensions)
477
+ systemPrompt: event.systemPrompt + "\n\nExtra instructions for this turn...",
478
+ };
479
+ });
480
+ ```
481
+
482
+ #### agent_start / agent_end
483
+
484
+ Fired once per user prompt.
485
+
486
+ ```typescript
487
+ pi.on("agent_start", async (_event, ctx) => {});
488
+
489
+ pi.on("agent_end", async (event, ctx) => {
490
+ // event.messages - messages from this prompt
491
+ });
492
+ ```
493
+
494
+ #### turn_start / turn_end
495
+
496
+ Fired for each turn (one LLM response + tool calls).
497
+
498
+ ```typescript
499
+ pi.on("turn_start", async (event, ctx) => {
500
+ // event.turnIndex, event.timestamp
501
+ });
502
+
503
+ pi.on("turn_end", async (event, ctx) => {
504
+ // event.turnIndex, event.message, event.toolResults
505
+ });
506
+ ```
507
+
508
+ #### message_start / message_update / message_end
509
+
510
+ Fired for message lifecycle updates.
511
+
512
+ - `message_start` and `message_end` fire for user, assistant, and toolResult messages.
513
+ - `message_update` fires for assistant streaming updates.
514
+
515
+ ```typescript
516
+ pi.on("message_start", async (event, ctx) => {
517
+ // event.message
518
+ });
519
+
520
+ pi.on("message_update", async (event, ctx) => {
521
+ // event.message
522
+ // event.assistantMessageEvent (token-by-token stream event)
523
+ });
524
+
525
+ pi.on("message_end", async (event, ctx) => {
526
+ // event.message
527
+ });
528
+ ```
529
+
530
+ #### tool_execution_start / tool_execution_update / tool_execution_end
531
+
532
+ Fired for tool execution lifecycle updates.
533
+
534
+ In parallel tool mode:
535
+ - `tool_execution_start` is emitted in assistant source order during the preflight phase
536
+ - `tool_execution_update` events may interleave across tools
537
+ - `tool_execution_end` is emitted in assistant source order, matching final tool result message order
538
+
539
+ ```typescript
540
+ pi.on("tool_execution_start", async (event, ctx) => {
541
+ // event.toolCallId, event.toolName, event.args
542
+ });
543
+
544
+ pi.on("tool_execution_update", async (event, ctx) => {
545
+ // event.toolCallId, event.toolName, event.args, event.partialResult
546
+ });
547
+
548
+ pi.on("tool_execution_end", async (event, ctx) => {
549
+ // event.toolCallId, event.toolName, event.result, event.isError
550
+ });
551
+ ```
552
+
553
+ #### context
554
+
555
+ Fired before each LLM call. Modify messages non-destructively. See [session.md](session.md) for message types.
556
+
557
+ ```typescript
558
+ pi.on("context", async (event, ctx) => {
559
+ // event.messages - deep copy, safe to modify
560
+ const filtered = event.messages.filter(m => !shouldPrune(m));
561
+ return { messages: filtered };
562
+ });
563
+ ```
564
+
565
+ #### before_provider_request
566
+
567
+ Fired after the provider-specific payload is built, right before the request is sent. Handlers run in extension load order. Returning `undefined` keeps the payload unchanged. Returning any other value replaces the payload for later handlers and for the actual request.
568
+
569
+ ```typescript
570
+ pi.on("before_provider_request", (event, ctx) => {
571
+ console.log(JSON.stringify(event.payload, null, 2));
572
+
573
+ // Optional: replace payload
574
+ // return { ...event.payload, temperature: 0 };
575
+ });
576
+ ```
577
+
578
+ This is mainly useful for debugging provider serialization and cache behavior.
579
+
580
+ #### after_provider_response
581
+
582
+ Fired after an HTTP response is received and before its stream body is consumed. Handlers run in extension load order.
583
+
584
+ ```typescript
585
+ pi.on("after_provider_response", (event, ctx) => {
586
+ // event.status - HTTP status code
587
+ // event.headers - normalized response headers
588
+ if (event.status === 429) {
589
+ console.log("rate limited", event.headers["retry-after"]);
590
+ }
591
+ });
592
+ ```
593
+
594
+ Header availability depends on provider and transport. Providers that abstract HTTP responses may not expose headers.
595
+
596
+ ### Model Events
597
+
598
+ #### model_select
599
+
600
+ Fired when the model changes via `/model` command, model cycling (`Ctrl+P`), or session restore.
601
+
602
+ ```typescript
603
+ pi.on("model_select", async (event, ctx) => {
604
+ // event.model - newly selected model
605
+ // event.previousModel - previous model (undefined if first selection)
606
+ // event.source - "set" | "cycle" | "restore"
607
+
608
+ const prev = event.previousModel
609
+ ? `${event.previousModel.provider}/${event.previousModel.id}`
610
+ : "none";
611
+ const next = `${event.model.provider}/${event.model.id}`;
612
+
613
+ ctx.ui.notify(`Model changed (${event.source}): ${prev} -> ${next}`, "info");
614
+ });
615
+ ```
616
+
617
+ Use this to update UI elements (status bars, footers) or perform model-specific initialization when the active model changes.
618
+
619
+ ### Tool Events
620
+
621
+ #### tool_call
622
+
623
+ Fired after `tool_execution_start`, before the tool executes. **Can block.** Use `isToolCallEventType` to narrow and get typed inputs.
624
+
625
+ Before `tool_call` runs, pi waits for previously emitted Agent events to finish draining through `AgentSession`. This means `ctx.sessionManager` is up to date through the current assistant tool-calling message.
626
+
627
+ In the default parallel tool execution mode, sibling tool calls from the same assistant message are preflighted sequentially, then executed concurrently. `tool_call` is not guaranteed to see sibling tool results from that same assistant message in `ctx.sessionManager`.
628
+
629
+ `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
630
+
631
+ Behavior guarantees:
632
+ - Mutations to `event.input` affect the actual tool execution
633
+ - Later `tool_call` handlers see mutations made by earlier handlers
634
+ - No re-validation is performed after your mutation
635
+ - Return values from `tool_call` only control blocking via `{ block: true, reason?: string }`
636
+
637
+ ```typescript
638
+ import { isToolCallEventType } from "@mariozechner/pi-coding-agent";
639
+
640
+ pi.on("tool_call", async (event, ctx) => {
641
+ // event.toolName - "bash", "read", "write", "edit", etc.
642
+ // event.toolCallId
643
+ // event.input - tool parameters (mutable)
644
+
645
+ // Built-in tools: no type params needed
646
+ if (isToolCallEventType("bash", event)) {
647
+ // event.input is { command: string; timeout?: number }
648
+ event.input.command = `source ~/.profile\n${event.input.command}`;
649
+
650
+ if (event.input.command.includes("rm -rf")) {
651
+ return { block: true, reason: "Dangerous command" };
652
+ }
653
+ }
654
+
655
+ if (isToolCallEventType("read", event)) {
656
+ // event.input is { path: string; offset?: number; limit?: number }
657
+ console.log(`Reading: ${event.input.path}`);
658
+ }
659
+ });
660
+ ```
661
+
662
+ #### Typing custom tool input
663
+
664
+ Custom tools should export their input type:
665
+
666
+ ```typescript
667
+ // my-extension.ts
668
+ export type MyToolInput = Static<typeof myToolSchema>;
669
+ ```
670
+
671
+ Use `isToolCallEventType` with explicit type parameters:
672
+
673
+ ```typescript
674
+ import { isToolCallEventType } from "@mariozechner/pi-coding-agent";
675
+ import type { MyToolInput } from "my-extension";
676
+
677
+ pi.on("tool_call", (event) => {
678
+ if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
679
+ event.input.action; // typed
680
+ }
681
+ });
682
+ ```
683
+
684
+ #### tool_result
685
+
686
+ Fired after tool execution finishes and before `tool_execution_end` plus the final tool result message events are emitted. **Can modify result.**
687
+
688
+ `tool_result` handlers chain like middleware:
689
+ - Handlers run in extension load order
690
+ - Each handler sees the latest result after previous handler changes
691
+ - Handlers can return partial patches (`content`, `details`, or `isError`); omitted fields keep their current values
692
+
693
+ Use `ctx.signal` for nested async work inside the handler. This lets Esc cancel model calls, `fetch()`, and other abort-aware operations started by the extension.
694
+
695
+ ```typescript
696
+ import { isBashToolResult } from "@mariozechner/pi-coding-agent";
697
+
698
+ pi.on("tool_result", async (event, ctx) => {
699
+ // event.toolName, event.toolCallId, event.input
700
+ // event.content, event.details, event.isError
701
+
702
+ if (isBashToolResult(event)) {
703
+ // event.details is typed as BashToolDetails
704
+ }
705
+
706
+ const response = await fetch("https://example.com/summarize", {
707
+ method: "POST",
708
+ body: JSON.stringify({ content: event.content }),
709
+ signal: ctx.signal,
710
+ });
711
+
712
+ // Modify result:
713
+ return { content: [...], details: {...}, isError: false };
714
+ });
715
+ ```
716
+
717
+ ### User Bash Events
718
+
719
+ #### user_bash
720
+
721
+ Fired when user executes `!` or `!!` commands. **Can intercept.**
722
+
723
+ ```typescript
724
+ import { createLocalBashOperations } from "@mariozechner/pi-coding-agent";
725
+
726
+ pi.on("user_bash", (event, ctx) => {
727
+ // event.command - the bash command
728
+ // event.excludeFromContext - true if !! prefix
729
+ // event.cwd - working directory
730
+
731
+ // Option 1: Provide custom operations (e.g., SSH)
732
+ return { operations: remoteBashOps };
733
+
734
+ // Option 2: Wrap pi's built-in local bash backend
735
+ const local = createLocalBashOperations();
736
+ return {
737
+ operations: {
738
+ exec(command, cwd, options) {
739
+ return local.exec(`source ~/.profile\n${command}`, cwd, options);
740
+ }
741
+ }
742
+ };
743
+
744
+ // Option 3: Full replacement - return result directly
745
+ return { result: { output: "...", exitCode: 0, cancelled: false, truncated: false } };
746
+ });
747
+ ```
748
+
749
+ ### Input Events
750
+
751
+ #### input
752
+
753
+ Fired when user input is received, after extension commands are checked but before skill and template expansion. The event sees the raw input text, so `/skill:foo` and `/template` are not yet expanded.
754
+
755
+ **Processing order:**
756
+ 1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped
757
+ 2. `input` event fires - can intercept, transform, or handle
758
+ 3. If not handled: skill commands (`/skill:name`) expanded to skill content
759
+ 4. If not handled: prompt templates (`/template`) expanded to template content
760
+ 5. Agent processing begins (`before_agent_start`, etc.)
761
+
762
+ ```typescript
763
+ pi.on("input", async (event, ctx) => {
764
+ // event.text - raw input (before skill/template expansion)
765
+ // event.images - attached images, if any
766
+ // event.source - "interactive" (typed), "rpc" (API), or "extension" (via sendUserMessage)
767
+
768
+ // Transform: rewrite input before expansion
769
+ if (event.text.startsWith("?quick "))
770
+ return { action: "transform", text: `Respond briefly: ${event.text.slice(7)}` };
771
+
772
+ // Handle: respond without LLM (extension shows its own feedback)
773
+ if (event.text === "ping") {
774
+ ctx.ui.notify("pong", "info");
775
+ return { action: "handled" };
776
+ }
777
+
778
+ // Route by source: skip processing for extension-injected messages
779
+ if (event.source === "extension") return { action: "continue" };
780
+
781
+ // Intercept skill commands before expansion
782
+ if (event.text.startsWith("/skill:")) {
783
+ // Could transform, block, or let pass through
784
+ }
785
+
786
+ return { action: "continue" }; // Default: pass through to expansion
787
+ });
788
+ ```
789
+
790
+ **Results:**
791
+ - `continue` - pass through unchanged (default if handler returns nothing)
792
+ - `transform` - modify text/images, then continue to expansion
793
+ - `handled` - skip agent entirely (first handler to return this wins)
794
+
795
+ Transforms chain across handlers. See [input-transform.ts](../examples/extensions/input-transform.ts).
796
+
797
+ ## ExtensionContext
798
+
799
+ All handlers receive `ctx: ExtensionContext`.
800
+
801
+ ### ctx.ui
802
+
803
+ UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
804
+
805
+ ### ctx.hasUI
806
+
807
+ `false` in print mode (`-p`) and JSON mode. `true` in interactive and RPC mode. In RPC mode, dialog methods (`select`, `confirm`, `input`, `editor`) work via the extension UI sub-protocol, and fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText`) emit requests to the client. Some TUI-specific methods are no-ops or return defaults (see [rpc.md](rpc.md#extension-ui-protocol)).
808
+
809
+ ### ctx.cwd
810
+
811
+ Current working directory.
812
+
813
+ ### ctx.sessionManager
814
+
815
+ Read-only access to session state. See [session.md](session.md) for the full SessionManager API and entry types.
816
+
817
+ For `tool_call`, this state is synchronized through the current assistant message before handlers run. In parallel tool execution mode it is still not guaranteed to include sibling tool results from the same assistant message.
818
+
819
+ ```typescript
820
+ ctx.sessionManager.getEntries() // All entries
821
+ ctx.sessionManager.getBranch() // Current branch
822
+ ctx.sessionManager.getLeafId() // Current leaf entry ID
823
+ ```
824
+
825
+ ### ctx.modelRegistry / ctx.model
826
+
827
+ Access to models and API keys.
828
+
829
+ ### ctx.signal
830
+
831
+ The current agent abort signal, or `undefined` when no agent turn is active.
832
+
833
+ Use this for abort-aware nested work started by extension handlers, for example:
834
+ - `fetch(..., { signal: ctx.signal })`
835
+ - model calls that accept `signal`
836
+ - file or process helpers that accept `AbortSignal`
837
+
838
+ `ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`.
839
+ It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while pi is idle.
840
+
841
+ ```typescript
842
+ pi.on("tool_result", async (event, ctx) => {
843
+ const response = await fetch("https://example.com/api", {
844
+ method: "POST",
845
+ body: JSON.stringify(event),
846
+ signal: ctx.signal,
847
+ });
848
+
849
+ const data = await response.json();
850
+ return { details: data };
851
+ });
852
+ ```
853
+
854
+ ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
855
+
856
+ Control flow helpers.
857
+
858
+ ### ctx.shutdown()
859
+
860
+ Request a graceful shutdown of pi.
861
+
862
+ - **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages).
863
+ - **RPC mode:** Deferred until the next idle state (after completing the current command response, when waiting for the next command).
864
+ - **Print mode:** No-op. The process exits automatically when all prompts are processed.
865
+
866
+ Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts).
867
+
868
+ ```typescript
869
+ pi.on("tool_call", (event, ctx) => {
870
+ if (isFatal(event.input)) {
871
+ ctx.shutdown();
872
+ }
873
+ });
874
+ ```
875
+
876
+ ### ctx.getContextUsage()
877
+
878
+ Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages.
879
+
880
+ ```typescript
881
+ const usage = ctx.getContextUsage();
882
+ if (usage && usage.tokens > 100_000) {
883
+ // ...
884
+ }
885
+ ```
886
+
887
+ ### ctx.compact()
888
+
889
+ Trigger compaction without awaiting completion. Use `onComplete` and `onError` for follow-up actions.
890
+
891
+ ```typescript
892
+ ctx.compact({
893
+ customInstructions: "Focus on recent changes",
894
+ onComplete: (result) => {
895
+ ctx.ui.notify("Compaction completed", "info");
896
+ },
897
+ onError: (error) => {
898
+ ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
899
+ },
900
+ });
901
+ ```
902
+
903
+ ### ctx.getSystemPrompt()
904
+
905
+ Returns the current effective system prompt. This includes any modifications made by `before_agent_start` handlers for the current turn.
906
+
907
+ ```typescript
908
+ pi.on("before_agent_start", (event, ctx) => {
909
+ const prompt = ctx.getSystemPrompt();
910
+ console.log(`System prompt length: ${prompt.length}`);
911
+ });
912
+ ```
913
+
914
+ ## ExtensionCommandContext
915
+
916
+ Command handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers.
917
+
918
+ ### ctx.waitForIdle()
919
+
920
+ Wait for the agent to finish streaming:
921
+
922
+ ```typescript
923
+ pi.registerCommand("my-cmd", {
924
+ handler: async (args, ctx) => {
925
+ await ctx.waitForIdle();
926
+ // Agent is now idle, safe to modify session
927
+ },
928
+ });
929
+ ```
930
+
931
+ ### ctx.newSession(options?)
932
+
933
+ Create a new session:
934
+
935
+ ```typescript
936
+ const result = await ctx.newSession({
937
+ parentSession: ctx.sessionManager.getSessionFile(),
938
+ setup: async (sm) => {
939
+ sm.appendMessage({
940
+ role: "user",
941
+ content: [{ type: "text", text: "Context from previous session..." }],
942
+ timestamp: Date.now(),
943
+ });
944
+ },
945
+ });
946
+
947
+ if (result.cancelled) {
948
+ // An extension cancelled the new session
949
+ }
950
+ ```
951
+
952
+ ### ctx.fork(entryId, options?)
953
+
954
+ Fork from a specific entry, creating a new session file:
955
+
956
+ ```typescript
957
+ const result = await ctx.fork("entry-id-123");
958
+ if (!result.cancelled) {
959
+ // Now in the forked session
960
+ }
961
+
962
+ const cloneResult = await ctx.fork("entry-id-456", { position: "at" });
963
+ if (!cloneResult.cancelled) {
964
+ // New session contains the active path through entry-id-456
965
+ }
966
+ ```
967
+
968
+ Options:
969
+ - `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor
970
+ - `position`: `"at"` duplicates the active path through the selected entry without restoring editor text
971
+
972
+ ### ctx.navigateTree(targetId, options?)
973
+
974
+ Navigate to a different point in the session tree:
975
+
976
+ ```typescript
977
+ const result = await ctx.navigateTree("entry-id-456", {
978
+ summarize: true,
979
+ customInstructions: "Focus on error handling changes",
980
+ replaceInstructions: false, // true = replace default prompt entirely
981
+ label: "review-checkpoint",
982
+ });
983
+ ```
984
+
985
+ Options:
986
+ - `summarize`: Whether to generate a summary of the abandoned branch
987
+ - `customInstructions`: Custom instructions for the summarizer
988
+ - `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended
989
+ - `label`: Label to attach to the branch summary entry (or target entry if not summarizing)
990
+
991
+ ### ctx.switchSession(sessionPath)
992
+
993
+ Switch to a different session file:
994
+
995
+ ```typescript
996
+ const result = await ctx.switchSession("/path/to/session.jsonl");
997
+ if (result.cancelled) {
998
+ // An extension cancelled the switch via session_before_switch
999
+ }
1000
+ ```
1001
+
1002
+ To discover available sessions, use the static `SessionManager.list()` or `SessionManager.listAll()` methods:
1003
+
1004
+ ```typescript
1005
+ import { SessionManager } from "@mariozechner/pi-coding-agent";
1006
+
1007
+ pi.registerCommand("switch", {
1008
+ description: "Switch to another session",
1009
+ handler: async (args, ctx) => {
1010
+ const sessions = await SessionManager.list(ctx.cwd);
1011
+ if (sessions.length === 0) return;
1012
+ const choice = await ctx.ui.select(
1013
+ "Pick session:",
1014
+ sessions.map(s => s.file),
1015
+ );
1016
+ if (choice) {
1017
+ await ctx.switchSession(choice);
1018
+ }
1019
+ },
1020
+ });
1021
+ ```
1022
+
1023
+ ### ctx.reload()
1024
+
1025
+ Run the same reload flow as `/reload`.
1026
+
1027
+ ```typescript
1028
+ pi.registerCommand("reload-runtime", {
1029
+ description: "Reload extensions, skills, prompts, and themes",
1030
+ handler: async (_args, ctx) => {
1031
+ await ctx.reload();
1032
+ return;
1033
+ },
1034
+ });
1035
+ ```
1036
+
1037
+ Important behavior:
1038
+ - `await ctx.reload()` emits `session_shutdown` for the current extension runtime
1039
+ - It then reloads resources and emits `session_start` with `reason: "reload"` and `resources_discover` with reason `"reload"`
1040
+ - The currently running command handler still continues in the old call frame
1041
+ - Code after `await ctx.reload()` still runs from the pre-reload version
1042
+ - Code after `await ctx.reload()` must not assume old in-memory extension state is still valid
1043
+ - After the handler returns, future commands/events/tool calls use the new extension version
1044
+
1045
+ For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
1046
+
1047
+ Tools run with `ExtensionContext`, so they cannot call `ctx.reload()` directly. Use a command as the reload entrypoint, then expose a tool that queues that command as a follow-up user message.
1048
+
1049
+ Example tool the LLM can call to trigger reload:
1050
+
1051
+ ```typescript
1052
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
1053
+ import { Type } from "@sinclair/typebox";
1054
+
1055
+ export default function (pi: ExtensionAPI) {
1056
+ pi.registerCommand("reload-runtime", {
1057
+ description: "Reload extensions, skills, prompts, and themes",
1058
+ handler: async (_args, ctx) => {
1059
+ await ctx.reload();
1060
+ return;
1061
+ },
1062
+ });
1063
+
1064
+ pi.registerTool({
1065
+ name: "reload_runtime",
1066
+ label: "Reload Runtime",
1067
+ description: "Reload extensions, skills, prompts, and themes",
1068
+ parameters: Type.Object({}),
1069
+ async execute() {
1070
+ pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
1071
+ return {
1072
+ content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
1073
+ };
1074
+ },
1075
+ });
1076
+ }
1077
+ ```
1078
+
1079
+ ## ExtensionAPI Methods
1080
+
1081
+ ### pi.on(event, handler)
1082
+
1083
+ Subscribe to events. See [Events](#events) for event types and return values.
1084
+
1085
+ ### pi.registerTool(definition)
1086
+
1087
+ Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
1088
+
1089
+ `pi.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools are refreshed immediately in the same session, so they appear in `pi.getAllTools()` and are callable by the LLM without `/reload`.
1090
+
1091
+ Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime.
1092
+
1093
+ Use `promptSnippet` to opt a custom tool into a one-line entry in `Available tools`, and `promptGuidelines` to append tool-specific bullets to the default `Guidelines` section when the tool is active.
1094
+
1095
+ See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example.
1096
+
1097
+ ```typescript
1098
+ import { Type } from "@sinclair/typebox";
1099
+ import { StringEnum } from "@mariozechner/pi-ai";
1100
+
1101
+ pi.registerTool({
1102
+ name: "my_tool",
1103
+ label: "My Tool",
1104
+ description: "What this tool does",
1105
+ promptSnippet: "Summarize or transform text according to action",
1106
+ promptGuidelines: ["Use this tool when the user asks to summarize previously generated text."],
1107
+ parameters: Type.Object({
1108
+ action: StringEnum(["list", "add"] as const),
1109
+ text: Type.Optional(Type.String()),
1110
+ }),
1111
+ prepareArguments(args) {
1112
+ // Optional compatibility shim. Runs before schema validation.
1113
+ // Return the current schema shape, for example to fold legacy fields
1114
+ // into the modern parameter object.
1115
+ return args;
1116
+ },
1117
+
1118
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1119
+ // Stream progress
1120
+ onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
1121
+
1122
+ return {
1123
+ content: [{ type: "text", text: "Done" }],
1124
+ details: { result: "..." },
1125
+ };
1126
+ },
1127
+
1128
+ // Optional: Custom rendering
1129
+ renderCall(args, theme, context) { ... },
1130
+ renderResult(result, options, theme, context) { ... },
1131
+ });
1132
+ ```
1133
+
1134
+ ### pi.sendMessage(message, options?)
1135
+
1136
+ Inject a custom message into the session.
1137
+
1138
+ ```typescript
1139
+ pi.sendMessage({
1140
+ customType: "my-extension",
1141
+ content: "Message text",
1142
+ display: true,
1143
+ details: { ... },
1144
+ }, {
1145
+ triggerTurn: true,
1146
+ deliverAs: "steer",
1147
+ });
1148
+ ```
1149
+
1150
+ **Options:**
1151
+ - `deliverAs` - Delivery mode:
1152
+ - `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
1153
+ - `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
1154
+ - `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
1155
+ - `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`).
1156
+
1157
+ ### pi.sendUserMessage(content, options?)
1158
+
1159
+ Send a user message to the agent. Unlike `sendMessage()` which sends custom messages, this sends an actual user message that appears as if typed by the user. Always triggers a turn.
1160
+
1161
+ ```typescript
1162
+ // Simple text message
1163
+ pi.sendUserMessage("What is 2+2?");
1164
+
1165
+ // With content array (text + images)
1166
+ pi.sendUserMessage([
1167
+ { type: "text", text: "Describe this image:" },
1168
+ { type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } },
1169
+ ]);
1170
+
1171
+ // During streaming - must specify delivery mode
1172
+ pi.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
1173
+ pi.sendUserMessage("And then summarize", { deliverAs: "followUp" });
1174
+ ```
1175
+
1176
+ **Options:**
1177
+ - `deliverAs` - Required when agent is streaming:
1178
+ - `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls
1179
+ - `"followUp"` - Waits for agent to finish all tools
1180
+
1181
+ When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error.
1182
+
1183
+ See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example.
1184
+
1185
+ ### pi.appendEntry(customType, data?)
1186
+
1187
+ Persist extension state (does NOT participate in LLM context).
1188
+
1189
+ ```typescript
1190
+ pi.appendEntry("my-state", { count: 42 });
1191
+
1192
+ // Restore on reload
1193
+ pi.on("session_start", async (_event, ctx) => {
1194
+ for (const entry of ctx.sessionManager.getEntries()) {
1195
+ if (entry.type === "custom" && entry.customType === "my-state") {
1196
+ // Reconstruct from entry.data
1197
+ }
1198
+ }
1199
+ });
1200
+ ```
1201
+
1202
+ ### pi.setSessionName(name)
1203
+
1204
+ Set the session display name (shown in session selector instead of first message).
1205
+
1206
+ ```typescript
1207
+ pi.setSessionName("Refactor auth module");
1208
+ ```
1209
+
1210
+ ### pi.getSessionName()
1211
+
1212
+ Get the current session name, if set.
1213
+
1214
+ ```typescript
1215
+ const name = pi.getSessionName();
1216
+ if (name) {
1217
+ console.log(`Session: ${name}`);
1218
+ }
1219
+ ```
1220
+
1221
+ ### pi.setLabel(entryId, label)
1222
+
1223
+ Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector).
1224
+
1225
+ ```typescript
1226
+ // Set a label
1227
+ pi.setLabel(entryId, "checkpoint-before-refactor");
1228
+
1229
+ // Clear a label
1230
+ pi.setLabel(entryId, undefined);
1231
+
1232
+ // Read labels via sessionManager
1233
+ const label = ctx.sessionManager.getLabel(entryId);
1234
+ ```
1235
+
1236
+ Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree.
1237
+
1238
+ ### pi.registerCommand(name, options)
1239
+
1240
+ Register a command.
1241
+
1242
+ If multiple extensions register the same command name, pi keeps them all and assigns numeric invocation suffixes in load order, for example `/review:1` and `/review:2`.
1243
+
1244
+ ```typescript
1245
+ pi.registerCommand("stats", {
1246
+ description: "Show session statistics",
1247
+ handler: async (args, ctx) => {
1248
+ const count = ctx.sessionManager.getEntries().length;
1249
+ ctx.ui.notify(`${count} entries`, "info");
1250
+ }
1251
+ });
1252
+ ```
1253
+
1254
+ Optional: add argument auto-completion for `/command ...`:
1255
+
1256
+ ```typescript
1257
+ import type { AutocompleteItem } from "@mariozechner/pi-tui";
1258
+
1259
+ pi.registerCommand("deploy", {
1260
+ description: "Deploy to an environment",
1261
+ getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
1262
+ const envs = ["dev", "staging", "prod"];
1263
+ const items = envs.map((e) => ({ value: e, label: e }));
1264
+ const filtered = items.filter((i) => i.value.startsWith(prefix));
1265
+ return filtered.length > 0 ? filtered : null;
1266
+ },
1267
+ handler: async (args, ctx) => {
1268
+ ctx.ui.notify(`Deploying: ${args}`, "info");
1269
+ },
1270
+ });
1271
+ ```
1272
+
1273
+ ### pi.getCommands()
1274
+
1275
+ Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
1276
+ The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
1277
+
1278
+ ```typescript
1279
+ const commands = pi.getCommands();
1280
+ const bySource = commands.filter((command) => command.source === "extension");
1281
+ const userScoped = commands.filter((command) => command.sourceInfo.scope === "user");
1282
+ ```
1283
+
1284
+ Each entry has this shape:
1285
+
1286
+ ```typescript
1287
+ {
1288
+ name: string; // Invokable command name without the leading slash. May be suffixed like "review:1"
1289
+ description?: string;
1290
+ source: "extension" | "prompt" | "skill";
1291
+ sourceInfo: {
1292
+ path: string;
1293
+ source: string;
1294
+ scope: "user" | "project" | "temporary";
1295
+ origin: "package" | "top-level";
1296
+ baseDir?: string;
1297
+ };
1298
+ }
1299
+ ```
1300
+
1301
+ Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
1302
+
1303
+ Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
1304
+ mode and would not execute if sent via `prompt`.
1305
+
1306
+ ### pi.registerMessageRenderer(customType, renderer)
1307
+
1308
+ Register a custom TUI renderer for messages with your `customType`. See [Custom UI](#custom-ui).
1309
+
1310
+ ### pi.registerShortcut(shortcut, options)
1311
+
1312
+ Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings.
1313
+
1314
+ ```typescript
1315
+ pi.registerShortcut("ctrl+shift+p", {
1316
+ description: "Toggle plan mode",
1317
+ handler: async (ctx) => {
1318
+ ctx.ui.notify("Toggled!");
1319
+ },
1320
+ });
1321
+ ```
1322
+
1323
+ ### pi.registerFlag(name, options)
1324
+
1325
+ Register a CLI flag.
1326
+
1327
+ ```typescript
1328
+ pi.registerFlag("plan", {
1329
+ description: "Start in plan mode",
1330
+ type: "boolean",
1331
+ default: false,
1332
+ });
1333
+
1334
+ // Check value
1335
+ if (pi.getFlag("--plan")) {
1336
+ // Plan mode enabled
1337
+ }
1338
+ ```
1339
+
1340
+ ### pi.exec(command, args, options?)
1341
+
1342
+ Execute a shell command.
1343
+
1344
+ ```typescript
1345
+ const result = await pi.exec("git", ["status"], { signal, timeout: 5000 });
1346
+ // result.stdout, result.stderr, result.code, result.killed
1347
+ ```
1348
+
1349
+ ### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
1350
+
1351
+ Manage active tools. This works for both built-in tools and dynamically registered tools.
1352
+
1353
+ ```typescript
1354
+ const active = pi.getActiveTools();
1355
+ const all = pi.getAllTools();
1356
+ // [{
1357
+ // name: "read",
1358
+ // description: "Read file contents...",
1359
+ // parameters: ...,
1360
+ // sourceInfo: { path: "<builtin:read>", source: "builtin", scope: "temporary", origin: "top-level" }
1361
+ // }, ...]
1362
+ const names = all.map(t => t.name);
1363
+ const builtinTools = all.filter((t) => t.sourceInfo.source === "builtin");
1364
+ const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
1365
+ pi.setActiveTools(["read", "bash"]); // Switch to read-only
1366
+ ```
1367
+
1368
+ `pi.getAllTools()` returns `name`, `description`, `parameters`, and `sourceInfo`.
1369
+
1370
+ Typical `sourceInfo.source` values:
1371
+ - `builtin` for built-in tools
1372
+ - `sdk` for tools passed via `createAgentSession({ customTools })`
1373
+ - extension source metadata for tools registered by extensions
1374
+
1375
+ ### pi.setModel(model)
1376
+
1377
+ Set the current model. Returns `false` if no API key is available for the model. See [models.md](models.md) for configuring custom models.
1378
+
1379
+ ```typescript
1380
+ const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5");
1381
+ if (model) {
1382
+ const success = await pi.setModel(model);
1383
+ if (!success) {
1384
+ ctx.ui.notify("No API key for this model", "error");
1385
+ }
1386
+ }
1387
+ ```
1388
+
1389
+ ### pi.getThinkingLevel() / pi.setThinkingLevel(level)
1390
+
1391
+ Get or set the thinking level. Level is clamped to model capabilities (non-reasoning models always use "off").
1392
+
1393
+ ```typescript
1394
+ const current = pi.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh"
1395
+ pi.setThinkingLevel("high");
1396
+ ```
1397
+
1398
+ ### pi.events
1399
+
1400
+ Shared event bus for communication between extensions:
1401
+
1402
+ ```typescript
1403
+ pi.events.on("my:event", (data) => { ... });
1404
+ pi.events.emit("my:event", { ... });
1405
+ ```
1406
+
1407
+ ### pi.registerProvider(name, config)
1408
+
1409
+ Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
1410
+
1411
+ Calls made during the extension factory function are queued and applied once the runner initialises. Calls made after that — for example from a command handler following a user setup flow — take effect immediately without requiring a `/reload`.
1412
+
1413
+ If you need to discover models from a remote endpoint, prefer an async extension factory over deferring the fetch to `session_start`. pi waits for the factory before startup continues, so the registered models are available immediately, including to `pi --list-models`.
1414
+
1415
+ ```typescript
1416
+ // Register a new provider with custom models
1417
+ pi.registerProvider("my-proxy", {
1418
+ baseUrl: "https://proxy.example.com",
1419
+ apiKey: "PROXY_API_KEY", // env var name or literal
1420
+ api: "anthropic-messages",
1421
+ models: [
1422
+ {
1423
+ id: "claude-sonnet-4-20250514",
1424
+ name: "Claude 4 Sonnet (proxy)",
1425
+ reasoning: false,
1426
+ input: ["text", "image"],
1427
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1428
+ contextWindow: 200000,
1429
+ maxTokens: 16384
1430
+ }
1431
+ ]
1432
+ });
1433
+
1434
+ // Override baseUrl for an existing provider (keeps all models)
1435
+ pi.registerProvider("anthropic", {
1436
+ baseUrl: "https://proxy.example.com"
1437
+ });
1438
+
1439
+ // Register provider with OAuth support for /login
1440
+ pi.registerProvider("corporate-ai", {
1441
+ baseUrl: "https://ai.corp.com",
1442
+ api: "openai-responses",
1443
+ models: [...],
1444
+ oauth: {
1445
+ name: "Corporate AI (SSO)",
1446
+ async login(callbacks) {
1447
+ // Custom OAuth flow
1448
+ callbacks.onAuth({ url: "https://sso.corp.com/..." });
1449
+ const code = await callbacks.onPrompt({ message: "Enter code:" });
1450
+ return { refresh: code, access: code, expires: Date.now() + 3600000 };
1451
+ },
1452
+ async refreshToken(credentials) {
1453
+ // Refresh logic
1454
+ return credentials;
1455
+ },
1456
+ getApiKey(credentials) {
1457
+ return credentials.access;
1458
+ }
1459
+ }
1460
+ });
1461
+ ```
1462
+
1463
+ **Config options:**
1464
+ - `baseUrl` - API endpoint URL. Required when defining models.
1465
+ - `apiKey` - API key or environment variable name. Required when defining models (unless `oauth` provided).
1466
+ - `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
1467
+ - `headers` - Custom headers to include in requests.
1468
+ - `authHeader` - If true, adds `Authorization: Bearer` header automatically.
1469
+ - `models` - Array of model definitions. If provided, replaces all existing models for this provider.
1470
+ - `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu.
1471
+ - `streamSimple` - Custom streaming implementation for non-standard APIs.
1472
+
1473
+ See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
1474
+
1475
+ ### pi.unregisterProvider(name)
1476
+
1477
+ Remove a previously registered provider and its models. Built-in models that were overridden by the provider are restored. Has no effect if the provider was not registered.
1478
+
1479
+ Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required.
1480
+
1481
+ ```typescript
1482
+ pi.registerCommand("my-setup-teardown", {
1483
+ description: "Remove the custom proxy provider",
1484
+ handler: async (_args, _ctx) => {
1485
+ pi.unregisterProvider("my-proxy");
1486
+ },
1487
+ });
1488
+ ```
1489
+
1490
+ ## State Management
1491
+
1492
+ Extensions with state should store it in tool result `details` for proper branching support:
1493
+
1494
+ ```typescript
1495
+ export default function (pi: ExtensionAPI) {
1496
+ let items: string[] = [];
1497
+
1498
+ // Reconstruct state from session
1499
+ pi.on("session_start", async (_event, ctx) => {
1500
+ items = [];
1501
+ for (const entry of ctx.sessionManager.getBranch()) {
1502
+ if (entry.type === "message" && entry.message.role === "toolResult") {
1503
+ if (entry.message.toolName === "my_tool") {
1504
+ items = entry.message.details?.items ?? [];
1505
+ }
1506
+ }
1507
+ }
1508
+ });
1509
+
1510
+ pi.registerTool({
1511
+ name: "my_tool",
1512
+ // ...
1513
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1514
+ items.push("new item");
1515
+ return {
1516
+ content: [{ type: "text", text: "Added" }],
1517
+ details: { items: [...items] }, // Store for reconstruction
1518
+ };
1519
+ },
1520
+ });
1521
+ }
1522
+ ```
1523
+
1524
+ ## Custom Tools
1525
+
1526
+ Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt and can have custom rendering.
1527
+
1528
+ Use `promptSnippet` for a short one-line entry in the `Available tools` section in the default system prompt. If omitted, custom tools are left out of that section.
1529
+
1530
+ Use `promptGuidelines` to add tool-specific bullets to the default system prompt `Guidelines` section. These bullets are included only while the tool is active (for example, after `pi.setActiveTools([...])`).
1531
+
1532
+ Note: Some models are idiots and include the @ prefix in tool path arguments. Built-in tools strip a leading @ before resolving paths. If your custom tool accepts a path, normalize a leading @ as well.
1533
+
1534
+ If your custom tool mutates files, use `withFileMutationQueue()` so it participates in the same per-file queue as built-in `edit` and `write`. This matters because tool calls run in parallel by default. Without the queue, two tools can read the same old file contents, compute different updates, and then whichever write lands last overwrites the other.
1535
+
1536
+ Example failure case: your custom tool edits `foo.ts` while built-in `edit` also changes `foo.ts` in the same assistant turn. If your tool does not participate in the queue, both can read the original `foo.ts`, apply separate changes, and one of those changes is lost.
1537
+
1538
+ Pass the real target file path to `withFileMutationQueue()`, not the raw user argument. Resolve it to an absolute path first, relative to `ctx.cwd` or your tool's working directory. For existing files, the helper canonicalizes through `realpath()`, so symlink aliases for the same file share one queue. For new files, it falls back to the resolved absolute path because there is nothing to `realpath()` yet.
1539
+
1540
+ Queue the entire mutation window on that target path. That includes read-modify-write logic, not just the final write.
1541
+
1542
+ ```typescript
1543
+ import { withFileMutationQueue } from "@mariozechner/pi-coding-agent";
1544
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
1545
+ import { dirname, resolve } from "node:path";
1546
+
1547
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1548
+ const absolutePath = resolve(ctx.cwd, params.path);
1549
+
1550
+ return withFileMutationQueue(absolutePath, async () => {
1551
+ await mkdir(dirname(absolutePath), { recursive: true });
1552
+ const current = await readFile(absolutePath, "utf8");
1553
+ const next = current.replace(params.oldText, params.newText);
1554
+ await writeFile(absolutePath, next, "utf8");
1555
+
1556
+ return {
1557
+ content: [{ type: "text", text: `Updated ${params.path}` }],
1558
+ details: {},
1559
+ };
1560
+ });
1561
+ }
1562
+ ```
1563
+
1564
+ ### Tool Definition
1565
+
1566
+ ```typescript
1567
+ import { Type } from "@sinclair/typebox";
1568
+ import { StringEnum } from "@mariozechner/pi-ai";
1569
+ import { Text } from "@mariozechner/pi-tui";
1570
+
1571
+ pi.registerTool({
1572
+ name: "my_tool",
1573
+ label: "My Tool",
1574
+ description: "What this tool does (shown to LLM)",
1575
+ promptSnippet: "List or add items in the project todo list",
1576
+ promptGuidelines: [
1577
+ "Use this tool for todo planning instead of direct file edits when the user asks for a task list."
1578
+ ],
1579
+ parameters: Type.Object({
1580
+ action: StringEnum(["list", "add"] as const), // Use StringEnum for Google compatibility
1581
+ text: Type.Optional(Type.String()),
1582
+ }),
1583
+ prepareArguments(args) {
1584
+ if (!args || typeof args !== "object") return args;
1585
+ const input = args as { action?: string; oldAction?: string };
1586
+ if (typeof input.oldAction === "string" && input.action === undefined) {
1587
+ return { ...input, action: input.oldAction };
1588
+ }
1589
+ return args;
1590
+ },
1591
+
1592
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1593
+ // Check for cancellation
1594
+ if (signal?.aborted) {
1595
+ return { content: [{ type: "text", text: "Cancelled" }] };
1596
+ }
1597
+
1598
+ // Stream progress updates
1599
+ onUpdate?.({
1600
+ content: [{ type: "text", text: "Working..." }],
1601
+ details: { progress: 50 },
1602
+ });
1603
+
1604
+ // Run commands via pi.exec (captured from extension closure)
1605
+ const result = await pi.exec("some-command", [], { signal });
1606
+
1607
+ // Return result
1608
+ return {
1609
+ content: [{ type: "text", text: "Done" }], // Sent to LLM
1610
+ details: { data: result }, // For rendering & state
1611
+ };
1612
+ },
1613
+
1614
+ // Optional: Custom rendering
1615
+ renderCall(args, theme, context) { ... },
1616
+ renderResult(result, options, theme, context) { ... },
1617
+ });
1618
+ ```
1619
+
1620
+ **Signaling errors:** To mark a tool execution as failed (sets `isError: true` on the result and reports it to the LLM), throw an error from `execute`. Returning a value never sets the error flag regardless of what properties you include in the return object.
1621
+
1622
+ ```typescript
1623
+ // Correct: throw to signal an error
1624
+ async execute(toolCallId, params) {
1625
+ if (!isValid(params.input)) {
1626
+ throw new Error(`Invalid input: ${params.input}`);
1627
+ }
1628
+ return { content: [{ type: "text", text: "OK" }], details: {} };
1629
+ }
1630
+ ```
1631
+
1632
+ **Important:** Use `StringEnum` from `@mariozechner/pi-ai` for string enums. `Type.Union`/`Type.Literal` doesn't work with Google's API.
1633
+
1634
+ **Argument preparation:** `prepareArguments(args)` is optional. If defined, it runs before schema validation and before `execute()`. Use it to mimic an older accepted input shape when pi resumes an older session whose stored tool call arguments no longer match the current schema. Return the object you want validated against `parameters`. Keep the public schema strict. Do not add deprecated compatibility fields to `parameters` just to keep old resumed sessions working.
1635
+
1636
+ Example: an older session may contain an `edit` tool call with top-level `oldText` and `newText`, while the current schema only accepts `edits: [{ oldText, newText }]`.
1637
+
1638
+ ```typescript
1639
+ pi.registerTool({
1640
+ name: "edit",
1641
+ label: "Edit",
1642
+ description: "Edit a single file using exact text replacement",
1643
+ parameters: Type.Object({
1644
+ path: Type.String(),
1645
+ edits: Type.Array(
1646
+ Type.Object({
1647
+ oldText: Type.String(),
1648
+ newText: Type.String(),
1649
+ }),
1650
+ ),
1651
+ }),
1652
+ prepareArguments(args) {
1653
+ if (!args || typeof args !== "object") return args;
1654
+
1655
+ const input = args as {
1656
+ path?: string;
1657
+ edits?: Array<{ oldText: string; newText: string }>;
1658
+ oldText?: unknown;
1659
+ newText?: unknown;
1660
+ };
1661
+
1662
+ if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
1663
+ return args;
1664
+ }
1665
+
1666
+ return {
1667
+ ...input,
1668
+ edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }],
1669
+ };
1670
+ },
1671
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1672
+ // params now matches the current schema
1673
+ return {
1674
+ content: [{ type: "text", text: `Applying ${params.edits.length} edit block(s)` }],
1675
+ details: {},
1676
+ };
1677
+ },
1678
+ });
1679
+ ```
1680
+
1681
+ ### Overriding Built-in Tools
1682
+
1683
+ Extensions can override built-in tools (`read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. Interactive mode displays a warning when this happens.
1684
+
1685
+ ```bash
1686
+ # Extension's read tool replaces built-in read
1687
+ pi -e ./tool-override.ts
1688
+ ```
1689
+
1690
+ Alternatively, use `--no-tools` to start without any built-in tools:
1691
+ ```bash
1692
+ # No built-in tools, only extension tools
1693
+ pi --no-tools -e ./my-extension.ts
1694
+ ```
1695
+
1696
+ See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
1697
+
1698
+ **Rendering:** Built-in renderer inheritance is resolved per slot. Execution override and rendering override are independent. If your override omits `renderCall`, the built-in `renderCall` is used. If your override omits `renderResult`, the built-in `renderResult` is used. If your override omits both, the built-in renderer is used automatically (syntax highlighting, diffs, etc.). This lets you wrap built-in tools for logging or access control without reimplementing the UI.
1699
+
1700
+ **Prompt metadata:** `promptSnippet` and `promptGuidelines` are not inherited from the built-in tool. If your override should keep those prompt instructions, define them on the override explicitly.
1701
+
1702
+ **Your implementation must match the exact result shape**, including the `details` type. The UI and session logic depend on these shapes for rendering and state tracking.
1703
+
1704
+ Built-in tool implementations:
1705
+ - [read.ts](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails`
1706
+ - [bash.ts](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails`
1707
+ - [edit.ts](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/core/tools/edit.ts)
1708
+ - [write.ts](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/core/tools/write.ts)
1709
+ - [grep.ts](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails`
1710
+ - [find.ts](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/core/tools/find.ts) - `FindToolDetails`
1711
+ - [ls.ts](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/core/tools/ls.ts) - `LsToolDetails`
1712
+
1713
+ ### Remote Execution
1714
+
1715
+ Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
1716
+
1717
+ ```typescript
1718
+ import { createReadTool, createBashTool, type ReadOperations } from "@mariozechner/pi-coding-agent";
1719
+
1720
+ // Create tool with custom operations
1721
+ const remoteRead = createReadTool(cwd, {
1722
+ operations: {
1723
+ readFile: (path) => sshExec(remote, `cat ${path}`),
1724
+ access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}),
1725
+ }
1726
+ });
1727
+
1728
+ // Register, checking flag at execution time
1729
+ pi.registerTool({
1730
+ ...remoteRead,
1731
+ async execute(id, params, signal, onUpdate, _ctx) {
1732
+ const ssh = getSshConfig();
1733
+ if (ssh) {
1734
+ const tool = createReadTool(cwd, { operations: createRemoteOps(ssh) });
1735
+ return tool.execute(id, params, signal, onUpdate);
1736
+ }
1737
+ return localRead.execute(id, params, signal, onUpdate);
1738
+ },
1739
+ });
1740
+ ```
1741
+
1742
+ **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
1743
+
1744
+ For `user_bash`, extensions can reuse pi's local shell backend via `createLocalBashOperations()` instead of reimplementing local process spawning, shell resolution, and process-tree termination.
1745
+
1746
+ The bash tool also supports a spawn hook to adjust the command, cwd, or env before execution:
1747
+
1748
+ ```typescript
1749
+ import { createBashTool } from "@mariozechner/pi-coding-agent";
1750
+
1751
+ const bashTool = createBashTool(cwd, {
1752
+ spawnHook: ({ command, cwd, env }) => ({
1753
+ command: `source ~/.profile\n${command}`,
1754
+ cwd: `/mnt/sandbox${cwd}`,
1755
+ env: { ...env, CI: "1" },
1756
+ }),
1757
+ });
1758
+ ```
1759
+
1760
+ See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
1761
+
1762
+ ### Output Truncation
1763
+
1764
+ **Tools MUST truncate their output** to avoid overwhelming the LLM context. Large outputs can cause:
1765
+ - Context overflow errors (prompt too long)
1766
+ - Compaction failures
1767
+ - Degraded model performance
1768
+
1769
+ The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hit first. Use the exported truncation utilities:
1770
+
1771
+ ```typescript
1772
+ import {
1773
+ truncateHead, // Keep first N lines/bytes (good for file reads, search results)
1774
+ truncateTail, // Keep last N lines/bytes (good for logs, command output)
1775
+ truncateLine, // Truncate a single line to maxBytes with ellipsis
1776
+ formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
1777
+ DEFAULT_MAX_BYTES, // 50KB
1778
+ DEFAULT_MAX_LINES, // 2000
1779
+ } from "@mariozechner/pi-coding-agent";
1780
+
1781
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1782
+ const output = await runCommand();
1783
+
1784
+ // Apply truncation
1785
+ const truncation = truncateHead(output, {
1786
+ maxLines: DEFAULT_MAX_LINES,
1787
+ maxBytes: DEFAULT_MAX_BYTES,
1788
+ });
1789
+
1790
+ let result = truncation.content;
1791
+
1792
+ if (truncation.truncated) {
1793
+ // Write full output to temp file
1794
+ const tempFile = writeTempFile(output);
1795
+
1796
+ // Inform the LLM where to find complete output
1797
+ result += `\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines`;
1798
+ result += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
1799
+ result += ` Full output saved to: ${tempFile}]`;
1800
+ }
1801
+
1802
+ return { content: [{ type: "text", text: result }] };
1803
+ }
1804
+ ```
1805
+
1806
+ **Key points:**
1807
+ - Use `truncateHead` for content where the beginning matters (search results, file reads)
1808
+ - Use `truncateTail` for content where the end matters (logs, command output)
1809
+ - Always inform the LLM when output is truncated and where to find the full version
1810
+ - Document the truncation limits in your tool's description
1811
+
1812
+ See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
1813
+
1814
+ ### Multiple Tools
1815
+
1816
+ One extension can register multiple tools with shared state:
1817
+
1818
+ ```typescript
1819
+ export default function (pi: ExtensionAPI) {
1820
+ let connection = null;
1821
+
1822
+ pi.registerTool({ name: "db_connect", ... });
1823
+ pi.registerTool({ name: "db_query", ... });
1824
+ pi.registerTool({ name: "db_close", ... });
1825
+
1826
+ pi.on("session_shutdown", async () => {
1827
+ connection?.close();
1828
+ });
1829
+ }
1830
+ ```
1831
+
1832
+ ### Custom Rendering
1833
+
1834
+ Tools can provide `renderCall` and `renderResult` for custom TUI display. See [tui.md](tui.md) for the full component API and [tool-execution.ts](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/modes/interactive/components/tool-execution.ts) for how tool rows are composed.
1835
+
1836
+ By default, tool output is wrapped in a `Box` that handles padding and background. A defined `renderCall` or `renderResult` must return a `Component`. If a slot renderer is not defined, `tool-execution.ts` uses fallback rendering for that slot.
1837
+
1838
+ Set `renderShell: "self"` when the tool should render its own shell instead of using the default `Box`. This is useful for tools that need complete control over framing or background behavior, for example large previews that must stay visually stable after the tool settles.
1839
+
1840
+ ```typescript
1841
+ pi.registerTool({
1842
+ name: "my_tool",
1843
+ label: "My Tool",
1844
+ description: "Custom shell example",
1845
+ parameters: Type.Object({}),
1846
+ renderShell: "self",
1847
+ async execute() {
1848
+ return { content: [{ type: "text", text: "ok" }], details: undefined };
1849
+ },
1850
+ renderCall(args, theme, context) {
1851
+ return new Text(theme.fg("accent", "my custom shell"), 0, 0);
1852
+ },
1853
+ });
1854
+ ```
1855
+
1856
+ `renderCall` and `renderResult` each receive a `context` object with:
1857
+ - `args` - the current tool call arguments
1858
+ - `state` - shared row-local state across `renderCall` and `renderResult`
1859
+ - `lastComponent` - the previously returned component for that slot, if any
1860
+ - `invalidate()` - request a rerender of this tool row
1861
+ - `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError`
1862
+
1863
+ Use `context.state` for cross-slot shared state. Keep slot-local caches on the returned component instance when you want to reuse and mutate the same component across renders.
1864
+
1865
+ #### renderCall
1866
+
1867
+ Renders the tool call or header:
1868
+
1869
+ ```typescript
1870
+ import { Text } from "@mariozechner/pi-tui";
1871
+
1872
+ renderCall(args, theme, context) {
1873
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
1874
+ let content = theme.fg("toolTitle", theme.bold("my_tool "));
1875
+ content += theme.fg("muted", args.action);
1876
+ if (args.text) {
1877
+ content += " " + theme.fg("dim", `"${args.text}"`);
1878
+ }
1879
+ text.setText(content);
1880
+ return text;
1881
+ }
1882
+ ```
1883
+
1884
+ #### renderResult
1885
+
1886
+ Renders the tool result or output:
1887
+
1888
+ ```typescript
1889
+ renderResult(result, { expanded, isPartial }, theme, context) {
1890
+ if (isPartial) {
1891
+ return new Text(theme.fg("warning", "Processing..."), 0, 0);
1892
+ }
1893
+
1894
+ if (result.details?.error) {
1895
+ return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
1896
+ }
1897
+
1898
+ let text = theme.fg("success", "✓ Done");
1899
+ if (expanded && result.details?.items) {
1900
+ for (const item of result.details.items) {
1901
+ text += "\n " + theme.fg("dim", item);
1902
+ }
1903
+ }
1904
+ return new Text(text, 0, 0);
1905
+ }
1906
+ ```
1907
+
1908
+ If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`.
1909
+
1910
+ #### Keybinding Hints
1911
+
1912
+ Use `keyHint()` to display keybinding hints that respect the active keybinding configuration:
1913
+
1914
+ ```typescript
1915
+ import { keyHint } from "@mariozechner/pi-coding-agent";
1916
+
1917
+ renderResult(result, { expanded }, theme, context) {
1918
+ let text = theme.fg("success", "✓ Done");
1919
+ if (!expanded) {
1920
+ text += ` (${keyHint("app.tools.expand", "to expand")})`;
1921
+ }
1922
+ return new Text(text, 0, 0);
1923
+ }
1924
+ ```
1925
+
1926
+ Available functions:
1927
+ - `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`
1928
+ - `keyText(keybinding)` - Returns the raw configured key text for a keybinding id
1929
+ - `rawKeyHint(key, description)` - Format a raw key string
1930
+
1931
+ Use namespaced keybinding ids:
1932
+ - Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
1933
+ - Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
1934
+
1935
+ For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
1936
+
1937
+ Custom editors and `ctx.ui.custom()` components receive `keybindings: KeybindingsManager` as an injected argument. They should use that injected manager directly instead of calling `getKeybindings()` or `setKeybindings()`.
1938
+
1939
+ #### Best Practices
1940
+
1941
+ - Use `Text` with padding `(0, 0)`. The default Box handles padding.
1942
+ - Use `\n` for multi-line content.
1943
+ - Handle `isPartial` for streaming progress.
1944
+ - Support `expanded` for detail on demand.
1945
+ - Keep default view compact.
1946
+ - Read `context.args` in `renderResult` instead of copying args into `context.state`.
1947
+ - Use `context.state` only for data that must be shared across call and result slots.
1948
+ - Reuse `context.lastComponent` when the same component instance can be updated in place.
1949
+ - Use `renderShell: "self"` only when the default boxed shell gets in the way. In self-shell mode the tool is responsible for its own framing, padding, and background.
1950
+
1951
+ #### Fallback
1952
+
1953
+ If a slot renderer is not defined or throws:
1954
+ - `renderCall`: Shows the tool name
1955
+ - `renderResult`: Shows raw text from `content`
1956
+
1957
+ ## Custom UI
1958
+
1959
+ Extensions can interact with users via `ctx.ui` methods and customize how messages/tools render.
1960
+
1961
+ **For custom components, see [tui.md](tui.md)** which has copy-paste patterns for:
1962
+ - Selection dialogs (SelectList)
1963
+ - Async operations with cancel (BorderedLoader)
1964
+ - Settings toggles (SettingsList)
1965
+ - Status indicators (setStatus)
1966
+ - Working message and indicator during streaming (`setWorkingMessage`, `setWorkingIndicator`)
1967
+ - Widgets above/below editor (setWidget)
1968
+ - Custom footers (setFooter)
1969
+
1970
+ ### Dialogs
1971
+
1972
+ ```typescript
1973
+ // Select from options
1974
+ const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
1975
+
1976
+ // Confirm dialog
1977
+ const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
1978
+
1979
+ // Text input
1980
+ const name = await ctx.ui.input("Name:", "placeholder");
1981
+
1982
+ // Multi-line editor
1983
+ const text = await ctx.ui.editor("Edit:", "prefilled text");
1984
+
1985
+ // Notification (non-blocking)
1986
+ ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
1987
+ ```
1988
+
1989
+ #### Timed Dialogs with Countdown
1990
+
1991
+ Dialogs support a `timeout` option that auto-dismisses with a live countdown display:
1992
+
1993
+ ```typescript
1994
+ // Dialog shows "Title (5s)" → "Title (4s)" → ... → auto-dismisses at 0
1995
+ const confirmed = await ctx.ui.confirm(
1996
+ "Timed Confirmation",
1997
+ "This dialog will auto-cancel in 5 seconds. Confirm?",
1998
+ { timeout: 5000 }
1999
+ );
2000
+
2001
+ if (confirmed) {
2002
+ // User confirmed
2003
+ } else {
2004
+ // User cancelled or timed out
2005
+ }
2006
+ ```
2007
+
2008
+ **Return values on timeout:**
2009
+ - `select()` returns `undefined`
2010
+ - `confirm()` returns `false`
2011
+ - `input()` returns `undefined`
2012
+
2013
+ #### Manual Dismissal with AbortSignal
2014
+
2015
+ For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
2016
+
2017
+ ```typescript
2018
+ const controller = new AbortController();
2019
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
2020
+
2021
+ const confirmed = await ctx.ui.confirm(
2022
+ "Timed Confirmation",
2023
+ "This dialog will auto-cancel in 5 seconds. Confirm?",
2024
+ { signal: controller.signal }
2025
+ );
2026
+
2027
+ clearTimeout(timeoutId);
2028
+
2029
+ if (confirmed) {
2030
+ // User confirmed
2031
+ } else if (controller.signal.aborted) {
2032
+ // Dialog timed out
2033
+ } else {
2034
+ // User cancelled (pressed Escape or selected "No")
2035
+ }
2036
+ ```
2037
+
2038
+ See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples.
2039
+
2040
+ ### Widgets, Status, and Footer
2041
+
2042
+ ```typescript
2043
+ // Status in footer (persistent until cleared)
2044
+ ctx.ui.setStatus("my-ext", "Processing...");
2045
+ ctx.ui.setStatus("my-ext", undefined); // Clear
2046
+
2047
+ // Working message (shown during streaming)
2048
+ ctx.ui.setWorkingMessage("Thinking deeply...");
2049
+ ctx.ui.setWorkingMessage(); // Restore default
2050
+
2051
+ // Working indicator (shown during streaming)
2052
+ ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); // Static dot
2053
+ ctx.ui.setWorkingIndicator({
2054
+ frames: [
2055
+ ctx.ui.theme.fg("dim", "·"),
2056
+ ctx.ui.theme.fg("muted", "•"),
2057
+ ctx.ui.theme.fg("accent", "●"),
2058
+ ctx.ui.theme.fg("muted", "•"),
2059
+ ],
2060
+ intervalMs: 120,
2061
+ });
2062
+ ctx.ui.setWorkingIndicator({ frames: [] }); // Hide indicator
2063
+ ctx.ui.setWorkingIndicator(); // Restore default spinner
2064
+
2065
+ // Widget above editor (default)
2066
+ ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
2067
+ // Widget below editor
2068
+ ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
2069
+ ctx.ui.setWidget("my-widget", (tui, theme) => new Text(theme.fg("accent", "Custom"), 0, 0));
2070
+ ctx.ui.setWidget("my-widget", undefined); // Clear
2071
+
2072
+ // Custom footer (replaces built-in footer entirely)
2073
+ ctx.ui.setFooter((tui, theme) => ({
2074
+ render(width) { return [theme.fg("dim", "Custom footer")]; },
2075
+ invalidate() {},
2076
+ }));
2077
+ ctx.ui.setFooter(undefined); // Restore built-in footer
2078
+
2079
+ // Terminal title
2080
+ ctx.ui.setTitle("pi - my-project");
2081
+
2082
+ // Editor text
2083
+ ctx.ui.setEditorText("Prefill text");
2084
+ const current = ctx.ui.getEditorText();
2085
+
2086
+ // Paste into editor (triggers paste handling, including collapse for large content)
2087
+ ctx.ui.pasteToEditor("pasted content");
2088
+
2089
+ // Tool output expansion
2090
+ const wasExpanded = ctx.ui.getToolsExpanded();
2091
+ ctx.ui.setToolsExpanded(true);
2092
+ ctx.ui.setToolsExpanded(wasExpanded);
2093
+
2094
+ // Custom editor (vim mode, emacs mode, etc.)
2095
+ ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings));
2096
+ ctx.ui.setEditorComponent(undefined); // Restore default editor
2097
+
2098
+ // Theme management (see themes.md for creating themes)
2099
+ const themes = ctx.ui.getAllThemes(); // [{ name: "dark", path: "/..." | undefined }, ...]
2100
+ const lightTheme = ctx.ui.getTheme("light"); // Load without switching
2101
+ const result = ctx.ui.setTheme("light"); // Switch by name
2102
+ if (!result.success) {
2103
+ ctx.ui.notify(`Failed: ${result.error}`, "error");
2104
+ }
2105
+ ctx.ui.setTheme(lightTheme!); // Or switch by Theme object
2106
+ ctx.ui.theme.fg("accent", "styled text"); // Access current theme
2107
+ ```
2108
+
2109
+ Custom working-indicator frames are rendered verbatim. If you want colors, add them to the frame strings yourself, for example with `ctx.ui.theme.fg(...)`.
2110
+
2111
+ ### Custom Components
2112
+
2113
+ For complex UI, use `ctx.ui.custom()`. This temporarily replaces the editor with your component until `done()` is called:
2114
+
2115
+ ```typescript
2116
+ import { Text, Component } from "@mariozechner/pi-tui";
2117
+
2118
+ const result = await ctx.ui.custom<boolean>((tui, theme, keybindings, done) => {
2119
+ const text = new Text("Press Enter to confirm, Escape to cancel", 1, 1);
2120
+
2121
+ text.onKey = (key) => {
2122
+ if (key === "return") done(true);
2123
+ if (key === "escape") done(false);
2124
+ return true;
2125
+ };
2126
+
2127
+ return text;
2128
+ });
2129
+
2130
+ if (result) {
2131
+ // User pressed Enter
2132
+ }
2133
+ ```
2134
+
2135
+ The callback receives:
2136
+ - `tui` - TUI instance (for screen dimensions, focus management)
2137
+ - `theme` - Current theme for styling
2138
+ - `keybindings` - App keybinding manager (for checking shortcuts)
2139
+ - `done(value)` - Call to close component and return value
2140
+
2141
+ See [tui.md](tui.md) for the full component API.
2142
+
2143
+ #### Overlay Mode (Experimental)
2144
+
2145
+ Pass `{ overlay: true }` to render the component as a floating modal on top of existing content, without clearing the screen:
2146
+
2147
+ ```typescript
2148
+ const result = await ctx.ui.custom<string | null>(
2149
+ (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
2150
+ { overlay: true }
2151
+ );
2152
+ ```
2153
+
2154
+ For advanced positioning (anchors, margins, percentages, responsive visibility), pass `overlayOptions`. Use `onHandle` to control visibility programmatically:
2155
+
2156
+ ```typescript
2157
+ const result = await ctx.ui.custom<string | null>(
2158
+ (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
2159
+ {
2160
+ overlay: true,
2161
+ overlayOptions: { anchor: "top-right", width: "50%", margin: 2 },
2162
+ onHandle: (handle) => { /* handle.setHidden(true/false) */ }
2163
+ }
2164
+ );
2165
+ ```
2166
+
2167
+ See [tui.md](tui.md) for the full `OverlayOptions` API and [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for examples.
2168
+
2169
+ ### Custom Editor
2170
+
2171
+ Replace the main input editor with a custom implementation (vim mode, emacs mode, etc.):
2172
+
2173
+ ```typescript
2174
+ import { CustomEditor, type ExtensionAPI } from "@mariozechner/pi-coding-agent";
2175
+ import { matchesKey } from "@mariozechner/pi-tui";
2176
+
2177
+ class VimEditor extends CustomEditor {
2178
+ private mode: "normal" | "insert" = "insert";
2179
+
2180
+ handleInput(data: string): void {
2181
+ if (matchesKey(data, "escape") && this.mode === "insert") {
2182
+ this.mode = "normal";
2183
+ return;
2184
+ }
2185
+ if (this.mode === "normal" && data === "i") {
2186
+ this.mode = "insert";
2187
+ return;
2188
+ }
2189
+ super.handleInput(data); // App keybindings + text editing
2190
+ }
2191
+ }
2192
+
2193
+ export default function (pi: ExtensionAPI) {
2194
+ pi.on("session_start", (_event, ctx) => {
2195
+ ctx.ui.setEditorComponent((_tui, theme, keybindings) =>
2196
+ new VimEditor(theme, keybindings)
2197
+ );
2198
+ });
2199
+ }
2200
+ ```
2201
+
2202
+ **Key points:**
2203
+ - Extend `CustomEditor` (not base `Editor`) to get app keybindings (escape to abort, ctrl+d, model switching)
2204
+ - Call `super.handleInput(data)` for keys you don't handle
2205
+ - Factory receives `theme` and `keybindings` from the app
2206
+ - Pass `undefined` to restore default: `ctx.ui.setEditorComponent(undefined)`
2207
+
2208
+ See [tui.md](tui.md) Pattern 7 for a complete example with mode indicator.
2209
+
2210
+ ### Message Rendering
2211
+
2212
+ Register a custom renderer for messages with your `customType`:
2213
+
2214
+ ```typescript
2215
+ import { Text } from "@mariozechner/pi-tui";
2216
+
2217
+ pi.registerMessageRenderer("my-extension", (message, options, theme) => {
2218
+ const { expanded } = options;
2219
+ let text = theme.fg("accent", `[${message.customType}] `);
2220
+ text += message.content;
2221
+
2222
+ if (expanded && message.details) {
2223
+ text += "\n" + theme.fg("dim", JSON.stringify(message.details, null, 2));
2224
+ }
2225
+
2226
+ return new Text(text, 0, 0);
2227
+ });
2228
+ ```
2229
+
2230
+ Messages are sent via `pi.sendMessage()`:
2231
+
2232
+ ```typescript
2233
+ pi.sendMessage({
2234
+ customType: "my-extension", // Matches registerMessageRenderer
2235
+ content: "Status update",
2236
+ display: true, // Show in TUI
2237
+ details: { ... }, // Available in renderer
2238
+ });
2239
+ ```
2240
+
2241
+ ### Theme Colors
2242
+
2243
+ All render functions receive a `theme` object. See [themes.md](themes.md) for creating custom themes and the full color palette.
2244
+
2245
+ ```typescript
2246
+ // Foreground colors
2247
+ theme.fg("toolTitle", text) // Tool names
2248
+ theme.fg("accent", text) // Highlights
2249
+ theme.fg("success", text) // Success (green)
2250
+ theme.fg("error", text) // Errors (red)
2251
+ theme.fg("warning", text) // Warnings (yellow)
2252
+ theme.fg("muted", text) // Secondary text
2253
+ theme.fg("dim", text) // Tertiary text
2254
+
2255
+ // Text styles
2256
+ theme.bold(text)
2257
+ theme.italic(text)
2258
+ theme.strikethrough(text)
2259
+ ```
2260
+
2261
+ For syntax highlighting in custom tool renderers:
2262
+
2263
+ ```typescript
2264
+ import { highlightCode, getLanguageFromPath } from "@mariozechner/pi-coding-agent";
2265
+
2266
+ // Highlight code with explicit language
2267
+ const highlighted = highlightCode("const x = 1;", "typescript", theme);
2268
+
2269
+ // Auto-detect language from file path
2270
+ const lang = getLanguageFromPath("/path/to/file.rs"); // "rust"
2271
+ const highlighted = highlightCode(code, lang, theme);
2272
+ ```
2273
+
2274
+ ## Error Handling
2275
+
2276
+ - Extension errors are logged, agent continues
2277
+ - `tool_call` errors block the tool (fail-safe)
2278
+ - Tool `execute` errors must be signaled by throwing; the thrown error is caught, reported to the LLM with `isError: true`, and execution continues
2279
+
2280
+ ## Mode Behavior
2281
+
2282
+ | Mode | UI Methods | Notes |
2283
+ |------|-----------|-------|
2284
+ | Interactive | Full TUI | Normal operation |
2285
+ | RPC (`--mode rpc`) | JSON protocol | Host handles UI, see [rpc.md](rpc.md) |
2286
+ | JSON (`--mode json`) | No-op | Event stream to stdout, see [json.md](json.md) |
2287
+ | Print (`-p`) | No-op | Extensions run but can't prompt |
2288
+
2289
+ In non-interactive modes, check `ctx.hasUI` before using UI methods.
2290
+
2291
+ ## Examples Reference
2292
+
2293
+ All examples in [examples/extensions/](../examples/extensions/).
2294
+
2295
+ | Example | Description | Key APIs |
2296
+ |---------|-------------|----------|
2297
+ | **Tools** |||
2298
+ | `hello.ts` | Minimal tool registration | `registerTool` |
2299
+ | `question.ts` | Tool with user interaction | `registerTool`, `ui.select` |
2300
+ | `questionnaire.ts` | Multi-step wizard tool | `registerTool`, `ui.custom` |
2301
+ | `todo.ts` | Stateful tool with persistence | `registerTool`, `appendEntry`, `renderResult`, session events |
2302
+ | `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
2303
+ | `truncated-tool.ts` | Output truncation example | `registerTool`, `truncateHead` |
2304
+ | `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
2305
+ | **Commands** |||
2306
+ | `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
2307
+ | `summarize.ts` | Conversation summary command | `registerCommand`, `ui.custom` |
2308
+ | `handoff.ts` | Cross-provider model handoff | `registerCommand`, `ui.editor`, `ui.custom` |
2309
+ | `qna.ts` | Q&A with custom UI | `registerCommand`, `ui.custom`, `setEditorText` |
2310
+ | `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
2311
+ | `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `sendUserMessage` |
2312
+ | `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
2313
+ | **Events & Gates** |||
2314
+ | `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.confirm` |
2315
+ | `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
2316
+ | `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
2317
+ | `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
2318
+ | `input-transform.ts` | Transform user input | `on("input")` |
2319
+ | `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
2320
+ | `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` |
2321
+ | `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
2322
+ | `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
2323
+ | `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
2324
+ | **Compaction & Sessions** |||
2325
+ | `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` |
2326
+ | `trigger-compact.ts` | Trigger compaction manually | `compact()` |
2327
+ | `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("session_before_fork")`, `exec` |
2328
+ | `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
2329
+ | **UI Components** |||
2330
+ | `status-line.ts` | Footer status indicator | `setStatus`, session events |
2331
+ | `working-indicator.ts` | Customize the streaming working indicator | `setWorkingIndicator`, `registerCommand` |
2332
+ | `custom-footer.ts` | Replace footer entirely | `registerCommand`, `setFooter` |
2333
+ | `custom-header.ts` | Replace startup header | `on("session_start")`, `setHeader` |
2334
+ | `modal-editor.ts` | Vim-style modal editor | `setEditorComponent`, `CustomEditor` |
2335
+ | `rainbow-editor.ts` | Custom editor styling | `setEditorComponent` |
2336
+ | `widget-placement.ts` | Widget above/below editor | `setWidget` |
2337
+ | `overlay-test.ts` | Overlay components | `ui.custom` with overlay options |
2338
+ | `overlay-qa-tests.ts` | Comprehensive overlay tests | `ui.custom`, all overlay options |
2339
+ | `notify.ts` | Simple notifications | `ui.notify` |
2340
+ | `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
2341
+ | `mac-system-theme.ts` | Auto-switch theme | `setTheme`, `exec` |
2342
+ | **Complex Extensions** |||
2343
+ | `plan-mode/` | Full plan mode implementation | All event types, `registerCommand`, `registerShortcut`, `registerFlag`, `setStatus`, `setWidget`, `sendMessage`, `setActiveTools` |
2344
+ | `preset.ts` | Saveable presets (model, tools, thinking) | `registerCommand`, `registerShortcut`, `registerFlag`, `setModel`, `setActiveTools`, `setThinkingLevel`, `appendEntry` |
2345
+ | `tools.ts` | Toggle tools on/off UI | `registerCommand`, `setActiveTools`, `SettingsList`, session events |
2346
+ | **Remote & Sandbox** |||
2347
+ | `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
2348
+ | `interactive-shell.ts` | Persistent shell session | `on("user_bash")` |
2349
+ | `sandbox/` | Sandboxed tool execution | Tool operations |
2350
+ | `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
2351
+ | **Games** |||
2352
+ | `snake.ts` | Snake game | `registerCommand`, `ui.custom`, keyboard handling |
2353
+ | `space-invaders.ts` | Space Invaders game | `registerCommand`, `ui.custom` |
2354
+ | `doom-overlay/` | Doom in overlay | `ui.custom` with overlay |
2355
+ | **Providers** |||
2356
+ | `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
2357
+ | `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
2358
+ | **Messages & Communication** |||
2359
+ | `message-renderer.ts` | Custom message rendering | `registerMessageRenderer`, `sendMessage` |
2360
+ | `event-bus.ts` | Inter-extension events | `pi.events` |
2361
+ | **Session Metadata** |||
2362
+ | `session-name.ts` | Name sessions for selector | `setSessionName`, `getSessionName` |
2363
+ | `bookmark.ts` | Bookmark entries for /tree | `setLabel` |
2364
+ | **Misc** |||
2365
+ | `antigravity-image-gen.ts` | Image generation tool | `registerTool`, Google Antigravity |
2366
+ | `inline-bash.ts` | Inline bash in tool calls | `on("tool_call")` |
2367
+ | `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
2368
+ | `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |