@oh-my-pi/pi-coding-agent 1.337.0

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 (224) hide show
  1. package/CHANGELOG.md +1228 -0
  2. package/README.md +1041 -0
  3. package/docs/compaction.md +403 -0
  4. package/docs/custom-tools.md +541 -0
  5. package/docs/extension-loading.md +1004 -0
  6. package/docs/hooks.md +867 -0
  7. package/docs/rpc.md +1040 -0
  8. package/docs/sdk.md +994 -0
  9. package/docs/session-tree-plan.md +441 -0
  10. package/docs/session.md +240 -0
  11. package/docs/skills.md +290 -0
  12. package/docs/theme.md +637 -0
  13. package/docs/tree.md +197 -0
  14. package/docs/tui.md +341 -0
  15. package/examples/README.md +21 -0
  16. package/examples/custom-tools/README.md +124 -0
  17. package/examples/custom-tools/hello/index.ts +20 -0
  18. package/examples/custom-tools/question/index.ts +84 -0
  19. package/examples/custom-tools/subagent/README.md +172 -0
  20. package/examples/custom-tools/subagent/agents/planner.md +37 -0
  21. package/examples/custom-tools/subagent/agents/reviewer.md +35 -0
  22. package/examples/custom-tools/subagent/agents/scout.md +50 -0
  23. package/examples/custom-tools/subagent/agents/worker.md +24 -0
  24. package/examples/custom-tools/subagent/agents.ts +156 -0
  25. package/examples/custom-tools/subagent/commands/implement-and-review.md +10 -0
  26. package/examples/custom-tools/subagent/commands/implement.md +10 -0
  27. package/examples/custom-tools/subagent/commands/scout-and-plan.md +9 -0
  28. package/examples/custom-tools/subagent/index.ts +1002 -0
  29. package/examples/custom-tools/todo/index.ts +212 -0
  30. package/examples/hooks/README.md +56 -0
  31. package/examples/hooks/auto-commit-on-exit.ts +49 -0
  32. package/examples/hooks/confirm-destructive.ts +59 -0
  33. package/examples/hooks/custom-compaction.ts +116 -0
  34. package/examples/hooks/dirty-repo-guard.ts +52 -0
  35. package/examples/hooks/file-trigger.ts +41 -0
  36. package/examples/hooks/git-checkpoint.ts +53 -0
  37. package/examples/hooks/handoff.ts +150 -0
  38. package/examples/hooks/permission-gate.ts +34 -0
  39. package/examples/hooks/protected-paths.ts +30 -0
  40. package/examples/hooks/qna.ts +119 -0
  41. package/examples/hooks/snake.ts +343 -0
  42. package/examples/hooks/status-line.ts +40 -0
  43. package/examples/sdk/01-minimal.ts +22 -0
  44. package/examples/sdk/02-custom-model.ts +49 -0
  45. package/examples/sdk/03-custom-prompt.ts +44 -0
  46. package/examples/sdk/04-skills.ts +44 -0
  47. package/examples/sdk/05-tools.ts +90 -0
  48. package/examples/sdk/06-hooks.ts +61 -0
  49. package/examples/sdk/07-context-files.ts +36 -0
  50. package/examples/sdk/08-slash-commands.ts +42 -0
  51. package/examples/sdk/09-api-keys-and-oauth.ts +55 -0
  52. package/examples/sdk/10-settings.ts +38 -0
  53. package/examples/sdk/11-sessions.ts +48 -0
  54. package/examples/sdk/12-full-control.ts +95 -0
  55. package/examples/sdk/README.md +154 -0
  56. package/package.json +81 -0
  57. package/src/cli/args.ts +246 -0
  58. package/src/cli/file-processor.ts +72 -0
  59. package/src/cli/list-models.ts +104 -0
  60. package/src/cli/plugin-cli.ts +650 -0
  61. package/src/cli/session-picker.ts +41 -0
  62. package/src/cli.ts +10 -0
  63. package/src/commands/init.md +20 -0
  64. package/src/config.ts +159 -0
  65. package/src/core/agent-session.ts +1900 -0
  66. package/src/core/auth-storage.ts +236 -0
  67. package/src/core/bash-executor.ts +196 -0
  68. package/src/core/compaction/branch-summarization.ts +343 -0
  69. package/src/core/compaction/compaction.ts +742 -0
  70. package/src/core/compaction/index.ts +7 -0
  71. package/src/core/compaction/utils.ts +154 -0
  72. package/src/core/custom-tools/index.ts +21 -0
  73. package/src/core/custom-tools/loader.ts +248 -0
  74. package/src/core/custom-tools/types.ts +169 -0
  75. package/src/core/custom-tools/wrapper.ts +28 -0
  76. package/src/core/exec.ts +129 -0
  77. package/src/core/export-html/index.ts +211 -0
  78. package/src/core/export-html/template.css +781 -0
  79. package/src/core/export-html/template.html +54 -0
  80. package/src/core/export-html/template.js +1185 -0
  81. package/src/core/export-html/vendor/highlight.min.js +1213 -0
  82. package/src/core/export-html/vendor/marked.min.js +6 -0
  83. package/src/core/hooks/index.ts +16 -0
  84. package/src/core/hooks/loader.ts +312 -0
  85. package/src/core/hooks/runner.ts +434 -0
  86. package/src/core/hooks/tool-wrapper.ts +99 -0
  87. package/src/core/hooks/types.ts +773 -0
  88. package/src/core/index.ts +52 -0
  89. package/src/core/mcp/client.ts +158 -0
  90. package/src/core/mcp/config.ts +154 -0
  91. package/src/core/mcp/index.ts +45 -0
  92. package/src/core/mcp/loader.ts +68 -0
  93. package/src/core/mcp/manager.ts +181 -0
  94. package/src/core/mcp/tool-bridge.ts +148 -0
  95. package/src/core/mcp/transports/http.ts +316 -0
  96. package/src/core/mcp/transports/index.ts +6 -0
  97. package/src/core/mcp/transports/stdio.ts +252 -0
  98. package/src/core/mcp/types.ts +220 -0
  99. package/src/core/messages.ts +189 -0
  100. package/src/core/model-registry.ts +317 -0
  101. package/src/core/model-resolver.ts +393 -0
  102. package/src/core/plugins/doctor.ts +59 -0
  103. package/src/core/plugins/index.ts +38 -0
  104. package/src/core/plugins/installer.ts +189 -0
  105. package/src/core/plugins/loader.ts +338 -0
  106. package/src/core/plugins/manager.ts +672 -0
  107. package/src/core/plugins/parser.ts +105 -0
  108. package/src/core/plugins/paths.ts +32 -0
  109. package/src/core/plugins/types.ts +190 -0
  110. package/src/core/sdk.ts +760 -0
  111. package/src/core/session-manager.ts +1128 -0
  112. package/src/core/settings-manager.ts +443 -0
  113. package/src/core/skills.ts +437 -0
  114. package/src/core/slash-commands.ts +248 -0
  115. package/src/core/system-prompt.ts +439 -0
  116. package/src/core/timings.ts +25 -0
  117. package/src/core/tools/ask.ts +211 -0
  118. package/src/core/tools/bash-interceptor.ts +120 -0
  119. package/src/core/tools/bash.ts +250 -0
  120. package/src/core/tools/context.ts +32 -0
  121. package/src/core/tools/edit-diff.ts +475 -0
  122. package/src/core/tools/edit.ts +208 -0
  123. package/src/core/tools/exa/company.ts +59 -0
  124. package/src/core/tools/exa/index.ts +64 -0
  125. package/src/core/tools/exa/linkedin.ts +59 -0
  126. package/src/core/tools/exa/logger.ts +56 -0
  127. package/src/core/tools/exa/mcp-client.ts +368 -0
  128. package/src/core/tools/exa/render.ts +196 -0
  129. package/src/core/tools/exa/researcher.ts +90 -0
  130. package/src/core/tools/exa/search.ts +337 -0
  131. package/src/core/tools/exa/types.ts +168 -0
  132. package/src/core/tools/exa/websets.ts +248 -0
  133. package/src/core/tools/find.ts +261 -0
  134. package/src/core/tools/grep.ts +555 -0
  135. package/src/core/tools/index.ts +202 -0
  136. package/src/core/tools/ls.ts +140 -0
  137. package/src/core/tools/lsp/client.ts +605 -0
  138. package/src/core/tools/lsp/config.ts +147 -0
  139. package/src/core/tools/lsp/edits.ts +101 -0
  140. package/src/core/tools/lsp/index.ts +804 -0
  141. package/src/core/tools/lsp/render.ts +447 -0
  142. package/src/core/tools/lsp/rust-analyzer.ts +145 -0
  143. package/src/core/tools/lsp/types.ts +463 -0
  144. package/src/core/tools/lsp/utils.ts +486 -0
  145. package/src/core/tools/notebook.ts +229 -0
  146. package/src/core/tools/path-utils.ts +61 -0
  147. package/src/core/tools/read.ts +240 -0
  148. package/src/core/tools/renderers.ts +540 -0
  149. package/src/core/tools/task/agents.ts +153 -0
  150. package/src/core/tools/task/artifacts.ts +114 -0
  151. package/src/core/tools/task/bundled-agents/browser.md +71 -0
  152. package/src/core/tools/task/bundled-agents/explore.md +82 -0
  153. package/src/core/tools/task/bundled-agents/plan.md +54 -0
  154. package/src/core/tools/task/bundled-agents/reviewer.md +59 -0
  155. package/src/core/tools/task/bundled-agents/task.md +53 -0
  156. package/src/core/tools/task/bundled-commands/architect-plan.md +10 -0
  157. package/src/core/tools/task/bundled-commands/implement-with-critic.md +11 -0
  158. package/src/core/tools/task/bundled-commands/implement.md +11 -0
  159. package/src/core/tools/task/commands.ts +213 -0
  160. package/src/core/tools/task/discovery.ts +208 -0
  161. package/src/core/tools/task/executor.ts +367 -0
  162. package/src/core/tools/task/index.ts +388 -0
  163. package/src/core/tools/task/model-resolver.ts +115 -0
  164. package/src/core/tools/task/parallel.ts +38 -0
  165. package/src/core/tools/task/render.ts +232 -0
  166. package/src/core/tools/task/types.ts +99 -0
  167. package/src/core/tools/truncate.ts +265 -0
  168. package/src/core/tools/web-fetch.ts +2370 -0
  169. package/src/core/tools/web-search/auth.ts +193 -0
  170. package/src/core/tools/web-search/index.ts +537 -0
  171. package/src/core/tools/web-search/providers/anthropic.ts +198 -0
  172. package/src/core/tools/web-search/providers/exa.ts +302 -0
  173. package/src/core/tools/web-search/providers/perplexity.ts +195 -0
  174. package/src/core/tools/web-search/render.ts +182 -0
  175. package/src/core/tools/web-search/types.ts +180 -0
  176. package/src/core/tools/write.ts +99 -0
  177. package/src/index.ts +176 -0
  178. package/src/main.ts +464 -0
  179. package/src/migrations.ts +135 -0
  180. package/src/modes/index.ts +43 -0
  181. package/src/modes/interactive/components/armin.ts +382 -0
  182. package/src/modes/interactive/components/assistant-message.ts +86 -0
  183. package/src/modes/interactive/components/bash-execution.ts +196 -0
  184. package/src/modes/interactive/components/bordered-loader.ts +41 -0
  185. package/src/modes/interactive/components/branch-summary-message.ts +42 -0
  186. package/src/modes/interactive/components/compaction-summary-message.ts +45 -0
  187. package/src/modes/interactive/components/custom-editor.ts +122 -0
  188. package/src/modes/interactive/components/diff.ts +147 -0
  189. package/src/modes/interactive/components/dynamic-border.ts +25 -0
  190. package/src/modes/interactive/components/footer.ts +381 -0
  191. package/src/modes/interactive/components/hook-editor.ts +117 -0
  192. package/src/modes/interactive/components/hook-input.ts +64 -0
  193. package/src/modes/interactive/components/hook-message.ts +96 -0
  194. package/src/modes/interactive/components/hook-selector.ts +91 -0
  195. package/src/modes/interactive/components/model-selector.ts +247 -0
  196. package/src/modes/interactive/components/oauth-selector.ts +120 -0
  197. package/src/modes/interactive/components/plugin-settings.ts +479 -0
  198. package/src/modes/interactive/components/queue-mode-selector.ts +56 -0
  199. package/src/modes/interactive/components/session-selector.ts +204 -0
  200. package/src/modes/interactive/components/settings-selector.ts +453 -0
  201. package/src/modes/interactive/components/show-images-selector.ts +45 -0
  202. package/src/modes/interactive/components/theme-selector.ts +62 -0
  203. package/src/modes/interactive/components/thinking-selector.ts +64 -0
  204. package/src/modes/interactive/components/tool-execution.ts +675 -0
  205. package/src/modes/interactive/components/tree-selector.ts +866 -0
  206. package/src/modes/interactive/components/user-message-selector.ts +159 -0
  207. package/src/modes/interactive/components/user-message.ts +18 -0
  208. package/src/modes/interactive/components/visual-truncate.ts +50 -0
  209. package/src/modes/interactive/components/welcome.ts +183 -0
  210. package/src/modes/interactive/interactive-mode.ts +2516 -0
  211. package/src/modes/interactive/theme/dark.json +101 -0
  212. package/src/modes/interactive/theme/light.json +98 -0
  213. package/src/modes/interactive/theme/theme-schema.json +308 -0
  214. package/src/modes/interactive/theme/theme.ts +998 -0
  215. package/src/modes/print-mode.ts +128 -0
  216. package/src/modes/rpc/rpc-client.ts +527 -0
  217. package/src/modes/rpc/rpc-mode.ts +483 -0
  218. package/src/modes/rpc/rpc-types.ts +203 -0
  219. package/src/utils/changelog.ts +99 -0
  220. package/src/utils/clipboard.ts +265 -0
  221. package/src/utils/fuzzy.ts +108 -0
  222. package/src/utils/mime.ts +30 -0
  223. package/src/utils/shell.ts +276 -0
  224. package/src/utils/tools-manager.ts +274 -0
@@ -0,0 +1,773 @@
1
+ /**
2
+ * Hook system types.
3
+ *
4
+ * Hooks are TypeScript modules that can subscribe to agent lifecycle events
5
+ * and interact with the user via UI primitives.
6
+ */
7
+
8
+ import type { AgentMessage } from "@oh-my-pi/pi-agent-core";
9
+ import type { ImageContent, Message, Model, TextContent, ToolResultMessage } from "@oh-my-pi/pi-ai";
10
+ import type { Component, TUI } from "@oh-my-pi/pi-tui";
11
+ import type { Theme } from "../../modes/interactive/theme/theme.js";
12
+ import type { CompactionPreparation, CompactionResult } from "../compaction/index.js";
13
+ import type { ExecOptions, ExecResult } from "../exec.js";
14
+ import type { HookMessage } from "../messages.js";
15
+ import type { ModelRegistry } from "../model-registry.js";
16
+ import type {
17
+ BranchSummaryEntry,
18
+ CompactionEntry,
19
+ ReadonlySessionManager,
20
+ SessionEntry,
21
+ SessionManager,
22
+ } from "../session-manager.js";
23
+
24
+ import type { EditToolDetails } from "../tools/edit.js";
25
+ import type {
26
+ BashToolDetails,
27
+ FindToolDetails,
28
+ GrepToolDetails,
29
+ LsToolDetails,
30
+ ReadToolDetails,
31
+ } from "../tools/index.js";
32
+
33
+ // Re-export for backward compatibility
34
+ export type { ExecOptions, ExecResult } from "../exec.js";
35
+
36
+ /**
37
+ * UI context for hooks to request interactive UI from the harness.
38
+ * Each mode (interactive, RPC, print) provides its own implementation.
39
+ */
40
+ export interface HookUIContext {
41
+ /**
42
+ * Show a selector and return the user's choice.
43
+ * @param title - Title to display
44
+ * @param options - Array of string options
45
+ * @returns Selected option string, or null if cancelled
46
+ */
47
+ select(title: string, options: string[]): Promise<string | undefined>;
48
+
49
+ /**
50
+ * Show a confirmation dialog.
51
+ * @returns true if confirmed, false if cancelled
52
+ */
53
+ confirm(title: string, message: string): Promise<boolean>;
54
+
55
+ /**
56
+ * Show a text input dialog.
57
+ * @returns User input, or undefined if cancelled
58
+ */
59
+ input(title: string, placeholder?: string): Promise<string | undefined>;
60
+
61
+ /**
62
+ * Show a notification to the user.
63
+ */
64
+ notify(message: string, type?: "info" | "warning" | "error"): void;
65
+
66
+ /**
67
+ * Set status text in the footer/status bar.
68
+ * Pass undefined as text to clear the status for this key.
69
+ * Text can include ANSI escape codes for styling.
70
+ * Note: Newlines, tabs, and carriage returns are replaced with spaces.
71
+ * The combined status line is truncated to terminal width.
72
+ * @param key - Unique key to identify this status (e.g., hook name)
73
+ * @param text - Status text to display, or undefined to clear
74
+ */
75
+ setStatus(key: string, text: string | undefined): void;
76
+
77
+ /**
78
+ * Show a custom component with keyboard focus.
79
+ * The factory receives TUI, theme, and a done() callback to close the component.
80
+ * Can be async for fire-and-forget work (don't await the work, just start it).
81
+ *
82
+ * @param factory - Function that creates the component. Call done() when finished.
83
+ * @returns Promise that resolves with the value passed to done()
84
+ *
85
+ * @example
86
+ * // Sync factory
87
+ * const result = await ctx.ui.custom((tui, theme, done) => {
88
+ * const component = new MyComponent(tui, theme);
89
+ * component.onFinish = (value) => done(value);
90
+ * return component;
91
+ * });
92
+ *
93
+ * // Async factory with fire-and-forget work
94
+ * const result = await ctx.ui.custom(async (tui, theme, done) => {
95
+ * const loader = new CancellableLoader(tui, theme.fg("accent"), theme.fg("muted"), "Working...");
96
+ * loader.onAbort = () => done(null);
97
+ * doWork(loader.signal).then(done); // Don't await - fire and forget
98
+ * return loader;
99
+ * });
100
+ */
101
+ custom<T>(
102
+ factory: (
103
+ tui: TUI,
104
+ theme: Theme,
105
+ done: (result: T) => void,
106
+ ) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,
107
+ ): Promise<T>;
108
+
109
+ /**
110
+ * Set the text in the core input editor.
111
+ * Use this to pre-fill the input box with generated content (e.g., prompt templates, extracted questions).
112
+ * @param text - Text to set in the editor
113
+ */
114
+ setEditorText(text: string): void;
115
+
116
+ /**
117
+ * Get the current text from the core input editor.
118
+ * @returns Current editor text
119
+ */
120
+ getEditorText(): string;
121
+
122
+ /**
123
+ * Show a multi-line editor for text editing.
124
+ * Supports Ctrl+G to open external editor ($VISUAL or $EDITOR).
125
+ * @param title - Title describing what is being edited
126
+ * @param prefill - Optional initial text
127
+ * @returns Edited text, or undefined if cancelled (Escape)
128
+ */
129
+ editor(title: string, prefill?: string): Promise<string | undefined>;
130
+
131
+ /**
132
+ * Get the current theme for styling text with ANSI codes.
133
+ * Use theme.fg() and theme.bg() to style status text.
134
+ *
135
+ * @example
136
+ * const theme = ctx.ui.theme;
137
+ * ctx.ui.setStatus("my-hook", theme.fg("success", "✓") + " Ready");
138
+ */
139
+ readonly theme: Theme;
140
+ }
141
+
142
+ /**
143
+ * Context passed to hook event handlers.
144
+ * For command handlers, see HookCommandContext which extends this with session control methods.
145
+ */
146
+ export interface HookContext {
147
+ /** UI methods for user interaction */
148
+ ui: HookUIContext;
149
+ /** Whether UI is available (false in print mode) */
150
+ hasUI: boolean;
151
+ /** Current working directory */
152
+ cwd: string;
153
+ /** Session manager (read-only) - use pi.sendMessage()/pi.appendEntry() for writes */
154
+ sessionManager: ReadonlySessionManager;
155
+ /** Model registry - use for API key resolution and model retrieval */
156
+ modelRegistry: ModelRegistry;
157
+ /** Current model (may be undefined if no model is selected yet) */
158
+ model: Model<any> | undefined;
159
+ /** Whether the agent is idle (not streaming) */
160
+ isIdle(): boolean;
161
+ /** Abort the current agent operation (fire-and-forget, does not wait) */
162
+ abort(): void;
163
+ /** Whether there are queued messages waiting to be processed */
164
+ hasQueuedMessages(): boolean;
165
+ }
166
+
167
+ /**
168
+ * Extended context for slash command handlers.
169
+ * Includes session control methods that are only safe in user-initiated commands.
170
+ *
171
+ * These methods are not available in event handlers because they can cause
172
+ * deadlocks when called from within the agent loop (e.g., tool_call, context events).
173
+ */
174
+ export interface HookCommandContext extends HookContext {
175
+ /** Wait for the agent to finish streaming */
176
+ waitForIdle(): Promise<void>;
177
+
178
+ /**
179
+ * Start a new session, optionally with a setup callback to initialize it.
180
+ * The setup callback receives a writable SessionManager for the new session.
181
+ *
182
+ * @param options.parentSession - Path to parent session for lineage tracking
183
+ * @param options.setup - Async callback to initialize the new session (e.g., append messages)
184
+ * @returns Object with `cancelled: true` if a hook cancelled the new session
185
+ *
186
+ * @example
187
+ * // Handoff: summarize current session and start fresh with context
188
+ * await ctx.newSession({
189
+ * parentSession: ctx.sessionManager.getSessionFile(),
190
+ * setup: async (sm) => {
191
+ * sm.appendMessage({ role: "user", content: [{ type: "text", text: summary }] });
192
+ * }
193
+ * });
194
+ */
195
+ newSession(options?: {
196
+ parentSession?: string;
197
+ setup?: (sessionManager: SessionManager) => Promise<void>;
198
+ }): Promise<{ cancelled: boolean }>;
199
+
200
+ /**
201
+ * Branch from a specific entry, creating a new session file.
202
+ *
203
+ * @param entryId - ID of the entry to branch from
204
+ * @returns Object with `cancelled: true` if a hook cancelled the branch
205
+ */
206
+ branch(entryId: string): Promise<{ cancelled: boolean }>;
207
+
208
+ /**
209
+ * Navigate to a different point in the session tree (in-place).
210
+ *
211
+ * @param targetId - ID of the entry to navigate to
212
+ * @param options.summarize - Whether to summarize the abandoned branch
213
+ * @returns Object with `cancelled: true` if a hook cancelled the navigation
214
+ */
215
+ navigateTree(targetId: string, options?: { summarize?: boolean }): Promise<{ cancelled: boolean }>;
216
+ }
217
+
218
+ // ============================================================================
219
+ // Session Events
220
+ // ============================================================================
221
+
222
+ /** Fired on initial session load */
223
+ export interface SessionStartEvent {
224
+ type: "session_start";
225
+ }
226
+
227
+ /** Fired before switching to another session (can be cancelled) */
228
+ export interface SessionBeforeSwitchEvent {
229
+ type: "session_before_switch";
230
+ /** Reason for the switch */
231
+ reason: "new" | "resume";
232
+ /** Session file we're switching to (only for "resume") */
233
+ targetSessionFile?: string;
234
+ }
235
+
236
+ /** Fired after switching to another session */
237
+ export interface SessionSwitchEvent {
238
+ type: "session_switch";
239
+ /** Reason for the switch */
240
+ reason: "new" | "resume";
241
+ /** Session file we came from */
242
+ previousSessionFile: string | undefined;
243
+ }
244
+
245
+ /** Fired before branching a session (can be cancelled) */
246
+ export interface SessionBeforeBranchEvent {
247
+ type: "session_before_branch";
248
+ /** ID of the entry to branch from */
249
+ entryId: string;
250
+ }
251
+
252
+ /** Fired after branching a session */
253
+ export interface SessionBranchEvent {
254
+ type: "session_branch";
255
+ previousSessionFile: string | undefined;
256
+ }
257
+
258
+ /** Fired before context compaction (can be cancelled or customized) */
259
+ export interface SessionBeforeCompactEvent {
260
+ type: "session_before_compact";
261
+ /** Compaction preparation with messages to summarize, file ops, previous summary, etc. */
262
+ preparation: CompactionPreparation;
263
+ /** Branch entries (root to current leaf). Use to inspect custom state or previous compactions. */
264
+ branchEntries: SessionEntry[];
265
+ /** Optional user-provided instructions for the summary */
266
+ customInstructions?: string;
267
+ /** Abort signal - hooks should pass this to LLM calls and check it periodically */
268
+ signal: AbortSignal;
269
+ }
270
+
271
+ /** Fired after context compaction */
272
+ export interface SessionCompactEvent {
273
+ type: "session_compact";
274
+ compactionEntry: CompactionEntry;
275
+ /** Whether the compaction entry was provided by a hook */
276
+ fromHook: boolean;
277
+ }
278
+
279
+ /** Fired on process exit (SIGINT/SIGTERM) */
280
+ export interface SessionShutdownEvent {
281
+ type: "session_shutdown";
282
+ }
283
+
284
+ /** Preparation data for tree navigation (used by session_before_tree event) */
285
+ export interface TreePreparation {
286
+ /** Node being switched to */
287
+ targetId: string;
288
+ /** Current active leaf (being abandoned), null if no current position */
289
+ oldLeafId: string | null;
290
+ /** Common ancestor of target and old leaf, null if no common ancestor */
291
+ commonAncestorId: string | null;
292
+ /** Entries to summarize (old leaf back to common ancestor or compaction) */
293
+ entriesToSummarize: SessionEntry[];
294
+ /** Whether user chose to summarize */
295
+ userWantsSummary: boolean;
296
+ }
297
+
298
+ /** Fired before navigating to a different node in the session tree (can be cancelled) */
299
+ export interface SessionBeforeTreeEvent {
300
+ type: "session_before_tree";
301
+ /** Preparation data for the navigation */
302
+ preparation: TreePreparation;
303
+ /** Abort signal - honors Escape during summarization (model available via ctx.model) */
304
+ signal: AbortSignal;
305
+ }
306
+
307
+ /** Fired after navigating to a different node in the session tree */
308
+ export interface SessionTreeEvent {
309
+ type: "session_tree";
310
+ /** The new active leaf, null if navigated to before first entry */
311
+ newLeafId: string | null;
312
+ /** Previous active leaf, null if there was no position */
313
+ oldLeafId: string | null;
314
+ /** Branch summary entry if one was created */
315
+ summaryEntry?: BranchSummaryEntry;
316
+ /** Whether summary came from hook */
317
+ fromHook?: boolean;
318
+ }
319
+
320
+ /** Union of all session event types */
321
+ export type SessionEvent =
322
+ | SessionStartEvent
323
+ | SessionBeforeSwitchEvent
324
+ | SessionSwitchEvent
325
+ | SessionBeforeBranchEvent
326
+ | SessionBranchEvent
327
+ | SessionBeforeCompactEvent
328
+ | SessionCompactEvent
329
+ | SessionShutdownEvent
330
+ | SessionBeforeTreeEvent
331
+ | SessionTreeEvent;
332
+
333
+ /**
334
+ * Event data for context event.
335
+ * Fired before each LLM call, allowing hooks to modify context non-destructively.
336
+ * Original session messages are NOT modified - only the messages sent to the LLM are affected.
337
+ */
338
+ export interface ContextEvent {
339
+ type: "context";
340
+ /** Messages about to be sent to the LLM (deep copy, safe to modify) */
341
+ messages: AgentMessage[];
342
+ }
343
+
344
+ /**
345
+ * Event data for before_agent_start event.
346
+ * Fired after user submits a prompt but before the agent loop starts.
347
+ * Allows hooks to inject context that will be persisted and visible in TUI.
348
+ */
349
+ export interface BeforeAgentStartEvent {
350
+ type: "before_agent_start";
351
+ /** The user's prompt text */
352
+ prompt: string;
353
+ /** Any images attached to the prompt */
354
+ images?: ImageContent[];
355
+ }
356
+
357
+ /**
358
+ * Event data for agent_start event.
359
+ * Fired when an agent loop starts (once per user prompt).
360
+ */
361
+ export interface AgentStartEvent {
362
+ type: "agent_start";
363
+ }
364
+
365
+ /**
366
+ * Event data for agent_end event.
367
+ */
368
+ export interface AgentEndEvent {
369
+ type: "agent_end";
370
+ messages: AgentMessage[];
371
+ }
372
+
373
+ /**
374
+ * Event data for turn_start event.
375
+ */
376
+ export interface TurnStartEvent {
377
+ type: "turn_start";
378
+ turnIndex: number;
379
+ timestamp: number;
380
+ }
381
+
382
+ /**
383
+ * Event data for turn_end event.
384
+ */
385
+ export interface TurnEndEvent {
386
+ type: "turn_end";
387
+ turnIndex: number;
388
+ message: AgentMessage;
389
+ toolResults: ToolResultMessage[];
390
+ }
391
+
392
+ /**
393
+ * Event data for tool_call event.
394
+ * Fired before a tool is executed. Hooks can block execution.
395
+ */
396
+ export interface ToolCallEvent {
397
+ type: "tool_call";
398
+ /** Tool name (e.g., "bash", "edit", "write") */
399
+ toolName: string;
400
+ /** Tool call ID */
401
+ toolCallId: string;
402
+ /** Tool input parameters */
403
+ input: Record<string, unknown>;
404
+ }
405
+
406
+ /**
407
+ * Base interface for tool_result events.
408
+ */
409
+ interface ToolResultEventBase {
410
+ type: "tool_result";
411
+ /** Tool call ID */
412
+ toolCallId: string;
413
+ /** Tool input parameters */
414
+ input: Record<string, unknown>;
415
+ /** Full content array (text and images) */
416
+ content: (TextContent | ImageContent)[];
417
+ /** Whether the tool execution was an error */
418
+ isError: boolean;
419
+ }
420
+
421
+ /** Tool result event for bash tool */
422
+ export interface BashToolResultEvent extends ToolResultEventBase {
423
+ toolName: "bash";
424
+ details: BashToolDetails | undefined;
425
+ }
426
+
427
+ /** Tool result event for read tool */
428
+ export interface ReadToolResultEvent extends ToolResultEventBase {
429
+ toolName: "read";
430
+ details: ReadToolDetails | undefined;
431
+ }
432
+
433
+ /** Tool result event for edit tool */
434
+ export interface EditToolResultEvent extends ToolResultEventBase {
435
+ toolName: "edit";
436
+ details: EditToolDetails | undefined;
437
+ }
438
+
439
+ /** Tool result event for write tool */
440
+ export interface WriteToolResultEvent extends ToolResultEventBase {
441
+ toolName: "write";
442
+ details: undefined;
443
+ }
444
+
445
+ /** Tool result event for grep tool */
446
+ export interface GrepToolResultEvent extends ToolResultEventBase {
447
+ toolName: "grep";
448
+ details: GrepToolDetails | undefined;
449
+ }
450
+
451
+ /** Tool result event for find tool */
452
+ export interface FindToolResultEvent extends ToolResultEventBase {
453
+ toolName: "find";
454
+ details: FindToolDetails | undefined;
455
+ }
456
+
457
+ /** Tool result event for ls tool */
458
+ export interface LsToolResultEvent extends ToolResultEventBase {
459
+ toolName: "ls";
460
+ details: LsToolDetails | undefined;
461
+ }
462
+
463
+ /** Tool result event for custom/unknown tools */
464
+ export interface CustomToolResultEvent extends ToolResultEventBase {
465
+ toolName: string;
466
+ details: unknown;
467
+ }
468
+
469
+ /**
470
+ * Event data for tool_result event.
471
+ * Fired after a tool is executed. Hooks can modify the result.
472
+ * Use toolName to discriminate and get typed details.
473
+ */
474
+ export type ToolResultEvent =
475
+ | BashToolResultEvent
476
+ | ReadToolResultEvent
477
+ | EditToolResultEvent
478
+ | WriteToolResultEvent
479
+ | GrepToolResultEvent
480
+ | FindToolResultEvent
481
+ | LsToolResultEvent
482
+ | CustomToolResultEvent;
483
+
484
+ // Type guards for narrowing ToolResultEvent to specific tool types
485
+ export function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {
486
+ return e.toolName === "bash";
487
+ }
488
+ export function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {
489
+ return e.toolName === "read";
490
+ }
491
+ export function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {
492
+ return e.toolName === "edit";
493
+ }
494
+ export function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {
495
+ return e.toolName === "write";
496
+ }
497
+ export function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {
498
+ return e.toolName === "grep";
499
+ }
500
+ export function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {
501
+ return e.toolName === "find";
502
+ }
503
+ export function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {
504
+ return e.toolName === "ls";
505
+ }
506
+
507
+ /**
508
+ * Union of all hook event types.
509
+ */
510
+ export type HookEvent =
511
+ | SessionEvent
512
+ | ContextEvent
513
+ | BeforeAgentStartEvent
514
+ | AgentStartEvent
515
+ | AgentEndEvent
516
+ | TurnStartEvent
517
+ | TurnEndEvent
518
+ | ToolCallEvent
519
+ | ToolResultEvent;
520
+
521
+ // ============================================================================
522
+ // Event Results
523
+ // ============================================================================
524
+
525
+ /**
526
+ * Return type for context event handlers.
527
+ * Allows hooks to modify messages before they're sent to the LLM.
528
+ */
529
+ export interface ContextEventResult {
530
+ /** Modified messages to send instead of the original */
531
+ messages?: Message[];
532
+ }
533
+
534
+ /**
535
+ * Return type for tool_call event handlers.
536
+ * Allows hooks to block tool execution.
537
+ */
538
+ export interface ToolCallEventResult {
539
+ /** If true, block the tool from executing */
540
+ block?: boolean;
541
+ /** Reason for blocking (returned to LLM as error) */
542
+ reason?: string;
543
+ }
544
+
545
+ /**
546
+ * Return type for tool_result event handlers.
547
+ * Allows hooks to modify tool results.
548
+ */
549
+ export interface ToolResultEventResult {
550
+ /** Replacement content array (text and images) */
551
+ content?: (TextContent | ImageContent)[];
552
+ /** Replacement details */
553
+ details?: unknown;
554
+ /** Override isError flag */
555
+ isError?: boolean;
556
+ }
557
+
558
+ /**
559
+ * Return type for before_agent_start event handlers.
560
+ * Allows hooks to inject context before the agent runs.
561
+ */
562
+ export interface BeforeAgentStartEventResult {
563
+ /** Message to inject into context (persisted to session, visible in TUI) */
564
+ message?: Pick<HookMessage, "customType" | "content" | "display" | "details">;
565
+ }
566
+
567
+ /** Return type for session_before_switch handlers */
568
+ export interface SessionBeforeSwitchResult {
569
+ /** If true, cancel the switch */
570
+ cancel?: boolean;
571
+ }
572
+
573
+ /** Return type for session_before_branch handlers */
574
+ export interface SessionBeforeBranchResult {
575
+ /**
576
+ * If true, abort the branch entirely. No new session file is created,
577
+ * conversation stays unchanged.
578
+ */
579
+ cancel?: boolean;
580
+ /**
581
+ * If true, the branch proceeds (new session file created, session state updated)
582
+ * but the in-memory conversation is NOT rewound to the branch point.
583
+ *
584
+ * Use case: git-checkpoint hook that restores code state separately.
585
+ * The hook handles state restoration itself, so it doesn't want the
586
+ * agent's conversation to be rewound (which would lose recent context).
587
+ *
588
+ * - `cancel: true` → nothing happens, user stays in current session
589
+ * - `skipConversationRestore: true` → branch happens, but messages stay as-is
590
+ * - neither → branch happens AND messages rewind to branch point (default)
591
+ */
592
+ skipConversationRestore?: boolean;
593
+ }
594
+
595
+ /** Return type for session_before_compact handlers */
596
+ export interface SessionBeforeCompactResult {
597
+ /** If true, cancel the compaction */
598
+ cancel?: boolean;
599
+ /** Custom compaction result - SessionManager adds id/parentId */
600
+ compaction?: CompactionResult;
601
+ }
602
+
603
+ /** Return type for session_before_tree handlers */
604
+ export interface SessionBeforeTreeResult {
605
+ /** If true, cancel the navigation entirely */
606
+ cancel?: boolean;
607
+ /**
608
+ * Custom summary (skips default summarizer).
609
+ * Only used if preparation.userWantsSummary is true.
610
+ */
611
+ summary?: {
612
+ summary: string;
613
+ details?: unknown;
614
+ };
615
+ }
616
+
617
+ // ============================================================================
618
+ // Hook API
619
+ // ============================================================================
620
+
621
+ /**
622
+ * Handler function type for each event.
623
+ * Handlers can return R, undefined, or void (bare return statements).
624
+ */
625
+ // biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements in handlers
626
+ export type HookHandler<E, R = undefined> = (event: E, ctx: HookContext) => Promise<R | void> | R | void;
627
+
628
+ export interface HookMessageRenderOptions {
629
+ /** Whether the view is expanded */
630
+ expanded: boolean;
631
+ }
632
+
633
+ /**
634
+ * Renderer for hook messages.
635
+ * Hooks register these to provide custom TUI rendering for their message types.
636
+ */
637
+ export type HookMessageRenderer<T = unknown> = (
638
+ message: HookMessage<T>,
639
+ options: HookMessageRenderOptions,
640
+ theme: Theme,
641
+ ) => Component | undefined;
642
+
643
+ /**
644
+ * Command registration options.
645
+ */
646
+ export interface RegisteredCommand {
647
+ name: string;
648
+ description?: string;
649
+
650
+ handler: (args: string, ctx: HookCommandContext) => Promise<void>;
651
+ }
652
+
653
+ /**
654
+ * HookAPI passed to hook factory functions.
655
+ * Hooks use pi.on() to subscribe to events and pi.sendMessage() to inject messages.
656
+ */
657
+ export interface HookAPI {
658
+ // Session events
659
+ on(event: "session_start", handler: HookHandler<SessionStartEvent>): void;
660
+ on(event: "session_before_switch", handler: HookHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>): void;
661
+ on(event: "session_switch", handler: HookHandler<SessionSwitchEvent>): void;
662
+ on(event: "session_before_branch", handler: HookHandler<SessionBeforeBranchEvent, SessionBeforeBranchResult>): void;
663
+ on(event: "session_branch", handler: HookHandler<SessionBranchEvent>): void;
664
+ on(
665
+ event: "session_before_compact",
666
+ handler: HookHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,
667
+ ): void;
668
+ on(event: "session_compact", handler: HookHandler<SessionCompactEvent>): void;
669
+ on(event: "session_shutdown", handler: HookHandler<SessionShutdownEvent>): void;
670
+ on(event: "session_before_tree", handler: HookHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;
671
+ on(event: "session_tree", handler: HookHandler<SessionTreeEvent>): void;
672
+
673
+ // Context and agent events
674
+ on(event: "context", handler: HookHandler<ContextEvent, ContextEventResult>): void;
675
+ on(event: "before_agent_start", handler: HookHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;
676
+ on(event: "agent_start", handler: HookHandler<AgentStartEvent>): void;
677
+ on(event: "agent_end", handler: HookHandler<AgentEndEvent>): void;
678
+ on(event: "turn_start", handler: HookHandler<TurnStartEvent>): void;
679
+ on(event: "turn_end", handler: HookHandler<TurnEndEvent>): void;
680
+ on(event: "tool_call", handler: HookHandler<ToolCallEvent, ToolCallEventResult>): void;
681
+ on(event: "tool_result", handler: HookHandler<ToolResultEvent, ToolResultEventResult>): void;
682
+
683
+ /**
684
+ * Send a custom message to the session. Creates a CustomMessageEntry that
685
+ * participates in LLM context and can be displayed in the TUI.
686
+ *
687
+ * Use this when you want the LLM to see the message content.
688
+ * For hook state that should NOT be sent to the LLM, use appendEntry() instead.
689
+ *
690
+ * @param message - The message to send
691
+ * @param message.customType - Identifier for your hook (used for filtering on reload)
692
+ * @param message.content - Message content (string or TextContent/ImageContent array)
693
+ * @param message.display - Whether to show in TUI (true = styled display, false = hidden)
694
+ * @param message.details - Optional hook-specific metadata (not sent to LLM)
695
+ * @param triggerTurn - If true and agent is idle, triggers a new LLM turn. Default: false.
696
+ * If agent is streaming, message is queued and triggerTurn is ignored.
697
+ */
698
+ sendMessage<T = unknown>(
699
+ message: Pick<HookMessage<T>, "customType" | "content" | "display" | "details">,
700
+ triggerTurn?: boolean,
701
+ ): void;
702
+
703
+ /**
704
+ * Append a custom entry to the session for hook state persistence.
705
+ * Creates a CustomEntry that does NOT participate in LLM context.
706
+ *
707
+ * Use this to store hook-specific data that should persist across session reloads
708
+ * but should NOT be sent to the LLM. On reload, scan session entries for your
709
+ * customType to reconstruct hook state.
710
+ *
711
+ * For messages that SHOULD be sent to the LLM, use sendMessage() instead.
712
+ *
713
+ * @param customType - Identifier for your hook (used for filtering on reload)
714
+ * @param data - Hook-specific data to persist (must be JSON-serializable)
715
+ *
716
+ * @example
717
+ * // Store permission state
718
+ * pi.appendEntry("permissions", { level: "full", grantedAt: Date.now() });
719
+ *
720
+ * // On reload, reconstruct state from entries
721
+ * pi.on("session", async (event, ctx) => {
722
+ * if (event.reason === "start") {
723
+ * const entries = event.sessionManager.getEntries();
724
+ * const myEntries = entries.filter(e => e.type === "custom" && e.customType === "permissions");
725
+ * // Reconstruct state from myEntries...
726
+ * }
727
+ * });
728
+ */
729
+ appendEntry<T = unknown>(customType: string, data?: T): void;
730
+
731
+ /**
732
+ * Register a custom renderer for CustomMessageEntry with a specific customType.
733
+ * The renderer is called when rendering the entry in the TUI.
734
+ * Return nothing to use the default renderer.
735
+ */
736
+ registerMessageRenderer<T = unknown>(customType: string, renderer: HookMessageRenderer<T>): void;
737
+
738
+ /**
739
+ * Register a custom slash command.
740
+ * Handler receives HookCommandContext with session control methods.
741
+ */
742
+ registerCommand(name: string, options: { description?: string; handler: RegisteredCommand["handler"] }): void;
743
+
744
+ /**
745
+ * Execute a shell command and return stdout/stderr/code.
746
+ * Supports timeout and abort signal.
747
+ */
748
+ exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
749
+
750
+ /** Injected @sinclair/typebox module */
751
+ typebox: typeof import("@sinclair/typebox");
752
+ /** Injected pi-coding-agent exports */
753
+ pi: typeof import("../../index.js");
754
+ }
755
+
756
+ /**
757
+ * Hook factory function type.
758
+ * Hooks export a default function that receives the HookAPI.
759
+ */
760
+ export type HookFactory = (pi: HookAPI) => void;
761
+
762
+ // ============================================================================
763
+ // Errors
764
+ // ============================================================================
765
+
766
+ /**
767
+ * Error emitted when a hook fails.
768
+ */
769
+ export interface HookError {
770
+ hookPath: string;
771
+ event: string;
772
+ error: string;
773
+ }