@oh-my-pi/pi-coding-agent 3.15.0 → 3.20.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 (193) hide show
  1. package/CHANGELOG.md +61 -1
  2. package/docs/extensions.md +1055 -0
  3. package/docs/rpc.md +69 -13
  4. package/docs/session-tree-plan.md +1 -1
  5. package/examples/extensions/README.md +141 -0
  6. package/examples/extensions/api-demo.ts +87 -0
  7. package/examples/extensions/chalk-logger.ts +26 -0
  8. package/examples/extensions/hello.ts +33 -0
  9. package/examples/extensions/pirate.ts +44 -0
  10. package/examples/extensions/plan-mode.ts +551 -0
  11. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  12. package/examples/extensions/todo.ts +299 -0
  13. package/examples/extensions/tools.ts +145 -0
  14. package/examples/extensions/with-deps/index.ts +36 -0
  15. package/examples/extensions/with-deps/package-lock.json +31 -0
  16. package/examples/extensions/with-deps/package.json +16 -0
  17. package/examples/sdk/02-custom-model.ts +3 -3
  18. package/examples/sdk/05-tools.ts +7 -3
  19. package/examples/sdk/06-extensions.ts +81 -0
  20. package/examples/sdk/06-hooks.ts +14 -13
  21. package/examples/sdk/08-prompt-templates.ts +42 -0
  22. package/examples/sdk/08-slash-commands.ts +17 -12
  23. package/examples/sdk/09-api-keys-and-oauth.ts +2 -2
  24. package/examples/sdk/12-full-control.ts +6 -6
  25. package/package.json +11 -7
  26. package/src/capability/extension-module.ts +34 -0
  27. package/src/cli/args.ts +22 -7
  28. package/src/cli/file-processor.ts +38 -67
  29. package/src/cli/list-models.ts +1 -1
  30. package/src/config.ts +25 -14
  31. package/src/core/agent-session.ts +505 -242
  32. package/src/core/auth-storage.ts +33 -21
  33. package/src/core/compaction/branch-summarization.ts +4 -4
  34. package/src/core/compaction/compaction.ts +3 -3
  35. package/src/core/custom-commands/bundled/wt/index.ts +430 -0
  36. package/src/core/custom-commands/loader.ts +9 -0
  37. package/src/core/custom-tools/wrapper.ts +5 -0
  38. package/src/core/event-bus.ts +59 -0
  39. package/src/core/export-html/vendor/highlight.min.js +1213 -0
  40. package/src/core/export-html/vendor/marked.min.js +6 -0
  41. package/src/core/extensions/index.ts +100 -0
  42. package/src/core/extensions/loader.ts +501 -0
  43. package/src/core/extensions/runner.ts +477 -0
  44. package/src/core/extensions/types.ts +712 -0
  45. package/src/core/extensions/wrapper.ts +147 -0
  46. package/src/core/hooks/types.ts +2 -2
  47. package/src/core/index.ts +10 -21
  48. package/src/core/keybindings.ts +199 -0
  49. package/src/core/messages.ts +26 -7
  50. package/src/core/model-registry.ts +123 -46
  51. package/src/core/model-resolver.ts +7 -5
  52. package/src/core/prompt-templates.ts +242 -0
  53. package/src/core/sdk.ts +378 -295
  54. package/src/core/session-manager.ts +72 -58
  55. package/src/core/settings-manager.ts +118 -22
  56. package/src/core/system-prompt.ts +24 -1
  57. package/src/core/terminal-notify.ts +37 -0
  58. package/src/core/tools/context.ts +4 -4
  59. package/src/core/tools/exa/mcp-client.ts +5 -4
  60. package/src/core/tools/exa/render.ts +176 -131
  61. package/src/core/tools/gemini-image.ts +361 -0
  62. package/src/core/tools/git.ts +216 -0
  63. package/src/core/tools/index.ts +28 -15
  64. package/src/core/tools/lsp/config.ts +5 -4
  65. package/src/core/tools/lsp/index.ts +17 -12
  66. package/src/core/tools/lsp/render.ts +39 -47
  67. package/src/core/tools/read.ts +66 -29
  68. package/src/core/tools/render-utils.ts +268 -0
  69. package/src/core/tools/renderers.ts +243 -225
  70. package/src/core/tools/task/discovery.ts +2 -2
  71. package/src/core/tools/task/executor.ts +66 -58
  72. package/src/core/tools/task/index.ts +29 -10
  73. package/src/core/tools/task/model-resolver.ts +8 -13
  74. package/src/core/tools/task/omp-command.ts +24 -0
  75. package/src/core/tools/task/render.ts +35 -60
  76. package/src/core/tools/task/types.ts +3 -0
  77. package/src/core/tools/web-fetch.ts +29 -28
  78. package/src/core/tools/web-search/index.ts +6 -5
  79. package/src/core/tools/web-search/providers/exa.ts +6 -5
  80. package/src/core/tools/web-search/render.ts +66 -111
  81. package/src/core/voice-controller.ts +135 -0
  82. package/src/core/voice-supervisor.ts +1003 -0
  83. package/src/core/voice.ts +308 -0
  84. package/src/discovery/builtin.ts +75 -1
  85. package/src/discovery/claude.ts +47 -1
  86. package/src/discovery/codex.ts +54 -2
  87. package/src/discovery/gemini.ts +55 -2
  88. package/src/discovery/helpers.ts +100 -1
  89. package/src/discovery/index.ts +2 -0
  90. package/src/index.ts +14 -9
  91. package/src/lib/worktree/collapse.ts +179 -0
  92. package/src/lib/worktree/constants.ts +14 -0
  93. package/src/lib/worktree/errors.ts +23 -0
  94. package/src/lib/worktree/git.ts +110 -0
  95. package/src/lib/worktree/index.ts +23 -0
  96. package/src/lib/worktree/operations.ts +216 -0
  97. package/src/lib/worktree/session.ts +114 -0
  98. package/src/lib/worktree/stats.ts +67 -0
  99. package/src/main.ts +61 -37
  100. package/src/migrations.ts +37 -7
  101. package/src/modes/interactive/components/bash-execution.ts +6 -4
  102. package/src/modes/interactive/components/custom-editor.ts +55 -0
  103. package/src/modes/interactive/components/custom-message.ts +95 -0
  104. package/src/modes/interactive/components/extensions/extension-list.ts +5 -0
  105. package/src/modes/interactive/components/extensions/inspector-panel.ts +18 -12
  106. package/src/modes/interactive/components/extensions/state-manager.ts +12 -0
  107. package/src/modes/interactive/components/extensions/types.ts +1 -0
  108. package/src/modes/interactive/components/footer.ts +324 -0
  109. package/src/modes/interactive/components/hook-editor.ts +1 -0
  110. package/src/modes/interactive/components/hook-selector.ts +3 -3
  111. package/src/modes/interactive/components/model-selector.ts +7 -6
  112. package/src/modes/interactive/components/oauth-selector.ts +3 -3
  113. package/src/modes/interactive/components/settings-defs.ts +55 -6
  114. package/src/modes/interactive/components/status-line/separators.ts +4 -4
  115. package/src/modes/interactive/components/status-line.ts +45 -35
  116. package/src/modes/interactive/components/tool-execution.ts +95 -23
  117. package/src/modes/interactive/interactive-mode.ts +644 -113
  118. package/src/modes/interactive/theme/defaults/alabaster.json +99 -0
  119. package/src/modes/interactive/theme/defaults/amethyst.json +103 -0
  120. package/src/modes/interactive/theme/defaults/anthracite.json +100 -0
  121. package/src/modes/interactive/theme/defaults/basalt.json +90 -0
  122. package/src/modes/interactive/theme/defaults/birch.json +101 -0
  123. package/src/modes/interactive/theme/defaults/dark-abyss.json +97 -0
  124. package/src/modes/interactive/theme/defaults/dark-aurora.json +94 -0
  125. package/src/modes/interactive/theme/defaults/dark-cavern.json +97 -0
  126. package/src/modes/interactive/theme/defaults/dark-copper.json +94 -0
  127. package/src/modes/interactive/theme/defaults/dark-cosmos.json +96 -0
  128. package/src/modes/interactive/theme/defaults/dark-eclipse.json +97 -0
  129. package/src/modes/interactive/theme/defaults/dark-ember.json +94 -0
  130. package/src/modes/interactive/theme/defaults/dark-equinox.json +96 -0
  131. package/src/modes/interactive/theme/defaults/dark-lavender.json +94 -0
  132. package/src/modes/interactive/theme/defaults/dark-lunar.json +95 -0
  133. package/src/modes/interactive/theme/defaults/dark-midnight.json +94 -0
  134. package/src/modes/interactive/theme/defaults/dark-nebula.json +96 -0
  135. package/src/modes/interactive/theme/defaults/dark-rainforest.json +97 -0
  136. package/src/modes/interactive/theme/defaults/dark-reef.json +97 -0
  137. package/src/modes/interactive/theme/defaults/dark-sakura.json +94 -0
  138. package/src/modes/interactive/theme/defaults/dark-slate.json +94 -0
  139. package/src/modes/interactive/theme/defaults/dark-solstice.json +96 -0
  140. package/src/modes/interactive/theme/defaults/dark-starfall.json +97 -0
  141. package/src/modes/interactive/theme/defaults/dark-swamp.json +96 -0
  142. package/src/modes/interactive/theme/defaults/dark-taiga.json +97 -0
  143. package/src/modes/interactive/theme/defaults/dark-terminal.json +94 -0
  144. package/src/modes/interactive/theme/defaults/dark-tundra.json +97 -0
  145. package/src/modes/interactive/theme/defaults/dark-twilight.json +97 -0
  146. package/src/modes/interactive/theme/defaults/dark-volcanic.json +97 -0
  147. package/src/modes/interactive/theme/defaults/graphite.json +99 -0
  148. package/src/modes/interactive/theme/defaults/index.ts +128 -0
  149. package/src/modes/interactive/theme/defaults/light-aurora-day.json +97 -0
  150. package/src/modes/interactive/theme/defaults/light-canyon.json +97 -0
  151. package/src/modes/interactive/theme/defaults/light-cirrus.json +96 -0
  152. package/src/modes/interactive/theme/defaults/light-coral.json +94 -0
  153. package/src/modes/interactive/theme/defaults/light-dawn.json +96 -0
  154. package/src/modes/interactive/theme/defaults/light-dunes.json +97 -0
  155. package/src/modes/interactive/theme/defaults/light-eucalyptus.json +94 -0
  156. package/src/modes/interactive/theme/defaults/light-frost.json +94 -0
  157. package/src/modes/interactive/theme/defaults/light-glacier.json +97 -0
  158. package/src/modes/interactive/theme/defaults/light-haze.json +96 -0
  159. package/src/modes/interactive/theme/defaults/light-honeycomb.json +94 -0
  160. package/src/modes/interactive/theme/defaults/light-lagoon.json +97 -0
  161. package/src/modes/interactive/theme/defaults/light-lavender.json +94 -0
  162. package/src/modes/interactive/theme/defaults/light-meadow.json +97 -0
  163. package/src/modes/interactive/theme/defaults/light-mint.json +94 -0
  164. package/src/modes/interactive/theme/defaults/light-opal.json +97 -0
  165. package/src/modes/interactive/theme/defaults/light-orchard.json +97 -0
  166. package/src/modes/interactive/theme/defaults/light-paper.json +94 -0
  167. package/src/modes/interactive/theme/defaults/light-prism.json +96 -0
  168. package/src/modes/interactive/theme/defaults/light-sand.json +94 -0
  169. package/src/modes/interactive/theme/defaults/light-savanna.json +97 -0
  170. package/src/modes/interactive/theme/defaults/light-soleil.json +96 -0
  171. package/src/modes/interactive/theme/defaults/light-wetland.json +97 -0
  172. package/src/modes/interactive/theme/defaults/light-zenith.json +95 -0
  173. package/src/modes/interactive/theme/defaults/limestone.json +100 -0
  174. package/src/modes/interactive/theme/defaults/mahogany.json +104 -0
  175. package/src/modes/interactive/theme/defaults/marble.json +99 -0
  176. package/src/modes/interactive/theme/defaults/obsidian.json +90 -0
  177. package/src/modes/interactive/theme/defaults/onyx.json +90 -0
  178. package/src/modes/interactive/theme/defaults/pearl.json +99 -0
  179. package/src/modes/interactive/theme/defaults/porcelain.json +90 -0
  180. package/src/modes/interactive/theme/defaults/quartz.json +102 -0
  181. package/src/modes/interactive/theme/defaults/sandstone.json +101 -0
  182. package/src/modes/interactive/theme/defaults/titanium.json +89 -0
  183. package/src/modes/print-mode.ts +14 -72
  184. package/src/modes/rpc/rpc-client.ts +23 -9
  185. package/src/modes/rpc/rpc-mode.ts +137 -125
  186. package/src/modes/rpc/rpc-types.ts +46 -24
  187. package/src/prompts/task.md +1 -0
  188. package/src/prompts/tools/gemini-image.md +4 -0
  189. package/src/prompts/tools/git.md +9 -0
  190. package/src/prompts/voice-summary.md +12 -0
  191. package/src/utils/image-convert.ts +26 -0
  192. package/src/utils/image-resize.ts +215 -0
  193. package/src/utils/shell-snapshot.ts +22 -20
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Todo Extension - Demonstrates state management via session entries
3
+ *
4
+ * This extension:
5
+ * - Registers a `todo` tool for the LLM to manage todos
6
+ * - Registers a `/todos` command for users to view the list
7
+ *
8
+ * State is stored in tool result details (not external files), which allows
9
+ * proper branching - when you branch, the todo state is automatically
10
+ * correct for that point in history.
11
+ */
12
+
13
+ import { StringEnum } from "@oh-my-pi/pi-ai";
14
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@oh-my-pi/pi-coding-agent";
15
+ import { matchesKey, Text, truncateToWidth } from "@oh-my-pi/pi-tui";
16
+ import { Type } from "@sinclair/typebox";
17
+
18
+ interface Todo {
19
+ id: number;
20
+ text: string;
21
+ done: boolean;
22
+ }
23
+
24
+ interface TodoDetails {
25
+ action: "list" | "add" | "toggle" | "clear";
26
+ todos: Todo[];
27
+ nextId: number;
28
+ error?: string;
29
+ }
30
+
31
+ const TodoParams = Type.Object({
32
+ action: StringEnum(["list", "add", "toggle", "clear"] as const),
33
+ text: Type.Optional(Type.String({ description: "Todo text (for add)" })),
34
+ id: Type.Optional(Type.Number({ description: "Todo ID (for toggle)" })),
35
+ });
36
+
37
+ /**
38
+ * UI component for the /todos command
39
+ */
40
+ class TodoListComponent {
41
+ private todos: Todo[];
42
+ private theme: Theme;
43
+ private onClose: () => void;
44
+ private cachedWidth?: number;
45
+ private cachedLines?: string[];
46
+
47
+ constructor(todos: Todo[], theme: Theme, onClose: () => void) {
48
+ this.todos = todos;
49
+ this.theme = theme;
50
+ this.onClose = onClose;
51
+ }
52
+
53
+ handleInput(data: string): void {
54
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
55
+ this.onClose();
56
+ }
57
+ }
58
+
59
+ render(width: number): string[] {
60
+ if (this.cachedLines && this.cachedWidth === width) {
61
+ return this.cachedLines;
62
+ }
63
+
64
+ const lines: string[] = [];
65
+ const th = this.theme;
66
+
67
+ lines.push("");
68
+ const title = th.fg("accent", " Todos ");
69
+ const headerLine =
70
+ th.fg("borderMuted", "─".repeat(3)) + title + th.fg("borderMuted", "─".repeat(Math.max(0, width - 10)));
71
+ lines.push(truncateToWidth(headerLine, width));
72
+ lines.push("");
73
+
74
+ if (this.todos.length === 0) {
75
+ lines.push(truncateToWidth(` ${th.fg("dim", "No todos yet. Ask the agent to add some!")}`, width));
76
+ } else {
77
+ const done = this.todos.filter((t) => t.done).length;
78
+ const total = this.todos.length;
79
+ lines.push(truncateToWidth(` ${th.fg("muted", `${done}/${total} completed`)}`, width));
80
+ lines.push("");
81
+
82
+ for (const todo of this.todos) {
83
+ const check = todo.done ? th.fg("success", "✓") : th.fg("dim", "○");
84
+ const id = th.fg("accent", `#${todo.id}`);
85
+ const text = todo.done ? th.fg("dim", todo.text) : th.fg("text", todo.text);
86
+ lines.push(truncateToWidth(` ${check} ${id} ${text}`, width));
87
+ }
88
+ }
89
+
90
+ lines.push("");
91
+ lines.push(truncateToWidth(` ${th.fg("dim", "Press Escape to close")}`, width));
92
+ lines.push("");
93
+
94
+ this.cachedWidth = width;
95
+ this.cachedLines = lines;
96
+ return lines;
97
+ }
98
+
99
+ invalidate(): void {
100
+ this.cachedWidth = undefined;
101
+ this.cachedLines = undefined;
102
+ }
103
+ }
104
+
105
+ export default function (pi: ExtensionAPI) {
106
+ // In-memory state (reconstructed from session on load)
107
+ let todos: Todo[] = [];
108
+ let nextId = 1;
109
+
110
+ /**
111
+ * Reconstruct state from session entries.
112
+ * Scans tool results for this tool and applies them in order.
113
+ */
114
+ const reconstructState = (ctx: ExtensionContext) => {
115
+ todos = [];
116
+ nextId = 1;
117
+
118
+ for (const entry of ctx.sessionManager.getBranch()) {
119
+ if (entry.type !== "message") continue;
120
+ const msg = (entry as { message?: { role?: string; toolName?: string; details?: unknown } }).message;
121
+ if (!msg || msg.role !== "toolResult" || msg.toolName !== "todo") continue;
122
+
123
+ const details = msg.details as TodoDetails | undefined;
124
+ if (details) {
125
+ todos = details.todos;
126
+ nextId = details.nextId;
127
+ }
128
+ }
129
+ };
130
+
131
+ // Reconstruct state on session events
132
+ pi.on("session_start", async (_event, ctx) => reconstructState(ctx));
133
+ pi.on("session_switch", async (_event, ctx) => reconstructState(ctx));
134
+ pi.on("session_branch", async (_event, ctx) => reconstructState(ctx));
135
+ pi.on("session_tree", async (_event, ctx) => reconstructState(ctx));
136
+
137
+ // Register the todo tool for the LLM
138
+ pi.registerTool({
139
+ name: "todo",
140
+ label: "Todo",
141
+ description: "Manage a todo list. Actions: list, add (text), toggle (id), clear",
142
+ parameters: TodoParams,
143
+
144
+ async execute(_toolCallId, params, _onUpdate, _ctx, _signal) {
145
+ switch (params.action) {
146
+ case "list":
147
+ return {
148
+ content: [
149
+ {
150
+ type: "text",
151
+ text: todos.length
152
+ ? todos.map((t) => `[${t.done ? "x" : " "}] #${t.id}: ${t.text}`).join("\n")
153
+ : "No todos",
154
+ },
155
+ ],
156
+ details: { action: "list", todos: [...todos], nextId } as TodoDetails,
157
+ };
158
+
159
+ case "add": {
160
+ if (!params.text) {
161
+ return {
162
+ content: [{ type: "text", text: "Error: text required for add" }],
163
+ details: { action: "add", todos: [...todos], nextId, error: "text required" } as TodoDetails,
164
+ };
165
+ }
166
+ const newTodo: Todo = { id: nextId++, text: params.text, done: false };
167
+ todos.push(newTodo);
168
+ return {
169
+ content: [{ type: "text", text: `Added todo #${newTodo.id}: ${newTodo.text}` }],
170
+ details: { action: "add", todos: [...todos], nextId } as TodoDetails,
171
+ };
172
+ }
173
+
174
+ case "toggle": {
175
+ if (params.id === undefined) {
176
+ return {
177
+ content: [{ type: "text", text: "Error: id required for toggle" }],
178
+ details: { action: "toggle", todos: [...todos], nextId, error: "id required" } as TodoDetails,
179
+ };
180
+ }
181
+ const todo = todos.find((t) => t.id === params.id);
182
+ if (!todo) {
183
+ return {
184
+ content: [{ type: "text", text: `Todo #${params.id} not found` }],
185
+ details: {
186
+ action: "toggle",
187
+ todos: [...todos],
188
+ nextId,
189
+ error: `#${params.id} not found`,
190
+ } as TodoDetails,
191
+ };
192
+ }
193
+ todo.done = !todo.done;
194
+ return {
195
+ content: [{ type: "text", text: `Todo #${todo.id} ${todo.done ? "completed" : "uncompleted"}` }],
196
+ details: { action: "toggle", todos: [...todos], nextId } as TodoDetails,
197
+ };
198
+ }
199
+
200
+ case "clear": {
201
+ const count = todos.length;
202
+ todos = [];
203
+ nextId = 1;
204
+ return {
205
+ content: [{ type: "text", text: `Cleared ${count} todos` }],
206
+ details: { action: "clear", todos: [], nextId: 1 } as TodoDetails,
207
+ };
208
+ }
209
+
210
+ default:
211
+ return {
212
+ content: [{ type: "text", text: `Unknown action: ${params.action}` }],
213
+ details: {
214
+ action: "list",
215
+ todos: [...todos],
216
+ nextId,
217
+ error: `unknown action: ${params.action}`,
218
+ } as TodoDetails,
219
+ };
220
+ }
221
+ },
222
+
223
+ renderCall(args, theme) {
224
+ let text = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", args.action);
225
+ if (args.text) text += ` ${theme.fg("dim", `"${args.text}"`)}`;
226
+ if (args.id !== undefined) text += ` ${theme.fg("accent", `#${args.id}`)}`;
227
+ return new Text(text, 0, 0);
228
+ },
229
+
230
+ renderResult(result, { expanded }, theme) {
231
+ const details = result.details as TodoDetails | undefined;
232
+ if (!details) {
233
+ const text = result.content[0] as { type: string; text?: string } | undefined;
234
+ return new Text(text?.type === "text" && text.text ? text.text : "", 0, 0);
235
+ }
236
+
237
+ if (details.error) {
238
+ return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
239
+ }
240
+
241
+ const todoList = details.todos;
242
+
243
+ switch (details.action) {
244
+ case "list": {
245
+ if (todoList.length === 0) {
246
+ return new Text(theme.fg("dim", "No todos"), 0, 0);
247
+ }
248
+ let listText = theme.fg("muted", `${todoList.length} todo(s):`);
249
+ const display = expanded ? todoList : todoList.slice(0, 5);
250
+ for (const t of display) {
251
+ const check = t.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
252
+ const itemText = t.done ? theme.fg("dim", t.text) : theme.fg("muted", t.text);
253
+ listText += `\n${check} ${theme.fg("accent", `#${t.id}`)} ${itemText}`;
254
+ }
255
+ if (!expanded && todoList.length > 5) {
256
+ listText += `\n${theme.fg("dim", `... ${todoList.length - 5} more`)}`;
257
+ }
258
+ return new Text(listText, 0, 0);
259
+ }
260
+
261
+ case "add": {
262
+ const added = todoList[todoList.length - 1];
263
+ return new Text(
264
+ theme.fg("success", "✓ Added ") +
265
+ theme.fg("accent", `#${added.id}`) +
266
+ " " +
267
+ theme.fg("muted", added.text),
268
+ 0,
269
+ 0,
270
+ );
271
+ }
272
+
273
+ case "toggle": {
274
+ const text = result.content[0] as { type: string; text?: string } | undefined;
275
+ const msg = text?.type === "text" && text.text ? text.text : "";
276
+ return new Text(theme.fg("success", "✓ ") + theme.fg("muted", msg), 0, 0);
277
+ }
278
+
279
+ case "clear":
280
+ return new Text(theme.fg("success", "✓ ") + theme.fg("muted", "Cleared all todos"), 0, 0);
281
+ }
282
+ },
283
+ });
284
+
285
+ // Register the /todos command for users
286
+ pi.registerCommand("todos", {
287
+ description: "Show all todos on the current branch",
288
+ handler: async (_args, ctx) => {
289
+ if (!ctx.hasUI) {
290
+ ctx.ui.notify("/todos requires interactive mode", "error");
291
+ return;
292
+ }
293
+
294
+ await ctx.ui.custom<void>((_tui, theme, done) => {
295
+ return new TodoListComponent(todos, theme, () => done());
296
+ });
297
+ },
298
+ });
299
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Tools Extension
3
+ *
4
+ * Provides a /tools command to enable/disable tools interactively.
5
+ * Tool selection persists across session reloads and respects branch navigation.
6
+ *
7
+ * Usage:
8
+ * 1. Copy this file to ~/.omp/agent/extensions/ (legacy: ~/.pi/agent/extensions/) or your project's .omp/extensions/
9
+ * 2. Use /tools to open the tool selector
10
+ */
11
+
12
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
13
+ import { getSettingsListTheme } from "@oh-my-pi/pi-coding-agent";
14
+ import { Container, type SettingItem, SettingsList } from "@oh-my-pi/pi-tui";
15
+
16
+ // State persisted to session
17
+ interface ToolsState {
18
+ enabledTools: string[];
19
+ }
20
+
21
+ export default function toolsExtension(pi: ExtensionAPI) {
22
+ // Track enabled tools
23
+ let enabledTools: Set<string> = new Set();
24
+ let allTools: string[] = [];
25
+
26
+ // Persist current state
27
+ function persistState() {
28
+ pi.appendEntry<ToolsState>("tools-config", {
29
+ enabledTools: Array.from(enabledTools),
30
+ });
31
+ }
32
+
33
+ // Apply current tool selection
34
+ function applyTools() {
35
+ pi.setActiveTools(Array.from(enabledTools));
36
+ }
37
+
38
+ // Find the last tools-config entry in the current branch
39
+ function restoreFromBranch(ctx: ExtensionContext) {
40
+ allTools = pi.getAllTools();
41
+
42
+ // Get entries in current branch only
43
+ const branchEntries = ctx.sessionManager.getBranch();
44
+ let savedTools: string[] | undefined;
45
+
46
+ for (const entry of branchEntries) {
47
+ if (entry.type === "custom" && (entry as { customType?: string }).customType === "tools-config") {
48
+ const data = (entry as { data?: ToolsState }).data;
49
+ if (data?.enabledTools) {
50
+ savedTools = data.enabledTools;
51
+ }
52
+ }
53
+ }
54
+
55
+ if (savedTools) {
56
+ // Restore saved tool selection (filter to only tools that still exist)
57
+ enabledTools = new Set(savedTools.filter((t: string) => allTools.includes(t)));
58
+ applyTools();
59
+ } else {
60
+ // No saved state - sync with currently active tools
61
+ enabledTools = new Set(pi.getActiveTools());
62
+ }
63
+ }
64
+
65
+ // Register /tools command
66
+ pi.registerCommand("tools", {
67
+ description: "Enable/disable tools",
68
+ handler: async (_args, ctx) => {
69
+ // Refresh tool list
70
+ allTools = pi.getAllTools();
71
+
72
+ await ctx.ui.custom((tui, theme, done) => {
73
+ // Build settings items for each tool
74
+ const items: SettingItem[] = allTools.map((tool) => ({
75
+ id: tool,
76
+ label: tool,
77
+ currentValue: enabledTools.has(tool) ? "enabled" : "disabled",
78
+ values: ["enabled", "disabled"],
79
+ }));
80
+
81
+ const container = new Container();
82
+ container.addChild(
83
+ new (class {
84
+ render(_width: number) {
85
+ return [theme.fg("accent", theme.bold("Tool Configuration")), ""];
86
+ }
87
+ invalidate() {}
88
+ })(),
89
+ );
90
+
91
+ const settingsList = new SettingsList(
92
+ items,
93
+ Math.min(items.length + 2, 15),
94
+ getSettingsListTheme(),
95
+ (id, newValue) => {
96
+ // Update enabled state and apply immediately
97
+ if (newValue === "enabled") {
98
+ enabledTools.add(id);
99
+ } else {
100
+ enabledTools.delete(id);
101
+ }
102
+ applyTools();
103
+ persistState();
104
+ },
105
+ () => {
106
+ // Close dialog
107
+ done(undefined);
108
+ },
109
+ );
110
+
111
+ container.addChild(settingsList);
112
+
113
+ const component = {
114
+ render(width: number) {
115
+ return container.render(width);
116
+ },
117
+ invalidate() {
118
+ container.invalidate();
119
+ },
120
+ handleInput(data: string) {
121
+ settingsList.handleInput?.(data);
122
+ tui.requestRender();
123
+ },
124
+ };
125
+
126
+ return component;
127
+ });
128
+ },
129
+ });
130
+
131
+ // Restore state on session start
132
+ pi.on("session_start", async (_event, ctx) => {
133
+ restoreFromBranch(ctx);
134
+ });
135
+
136
+ // Restore state when navigating the session tree
137
+ pi.on("session_tree", async (_event, ctx) => {
138
+ restoreFromBranch(ctx);
139
+ });
140
+
141
+ // Restore state after branching
142
+ pi.on("session_branch", async (_event, ctx) => {
143
+ restoreFromBranch(ctx);
144
+ });
145
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Example extension with its own npm dependencies.
3
+ * Tests that jiti resolves modules from the extension's own node_modules.
4
+ *
5
+ * Requires: npm install in this directory
6
+ */
7
+
8
+ import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
9
+ import { Type } from "@sinclair/typebox";
10
+ import ms from "ms";
11
+
12
+ export default function (pi: ExtensionAPI) {
13
+ // Register a tool that uses ms
14
+ pi.registerTool({
15
+ name: "parse_duration",
16
+ label: "Parse Duration",
17
+ description: "Parse a human-readable duration string (e.g., '2 days', '1h', '5m') to milliseconds",
18
+ parameters: Type.Object({
19
+ duration: Type.String({ description: "Duration string like '2 days', '1h', '5m'" }),
20
+ }),
21
+ execute: async (_toolCallId, params) => {
22
+ const result = ms(params.duration as ms.StringValue);
23
+ if (result === undefined) {
24
+ return {
25
+ content: [{ type: "text", text: `Invalid duration: "${params.duration}"` }],
26
+ isError: true,
27
+ details: {},
28
+ };
29
+ }
30
+ return {
31
+ content: [{ type: "text", text: `${params.duration} = ${result} milliseconds` }],
32
+ details: {},
33
+ };
34
+ },
35
+ });
36
+ }
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "pi-extension-with-deps",
3
+ "version": "1.0.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "pi-extension-with-deps",
9
+ "version": "1.0.0",
10
+ "dependencies": {
11
+ "ms": "^2.1.3"
12
+ },
13
+ "devDependencies": {
14
+ "@types/ms": "^2.1.0"
15
+ }
16
+ },
17
+ "node_modules/@types/ms": {
18
+ "version": "2.1.0",
19
+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
20
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
21
+ "dev": true,
22
+ "license": "MIT"
23
+ },
24
+ "node_modules/ms": {
25
+ "version": "2.1.3",
26
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
27
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
28
+ "license": "MIT"
29
+ }
30
+ }
31
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "pi-extension-with-deps",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "pi": {
6
+ "extensions": [
7
+ "./index.ts"
8
+ ]
9
+ },
10
+ "dependencies": {
11
+ "ms": "^2.1.3"
12
+ },
13
+ "devDependencies": {
14
+ "@types/ms": "^2.1.0"
15
+ }
16
+ }
@@ -8,8 +8,8 @@ import { getModel } from "@oh-my-pi/pi-ai";
8
8
  import { createAgentSession, discoverAuthStorage, discoverModels } from "@oh-my-pi/pi-coding-agent";
9
9
 
10
10
  // Set up auth storage and model registry
11
- const authStorage = discoverAuthStorage();
12
- const modelRegistry = discoverModels(authStorage);
11
+ const authStorage = await discoverAuthStorage();
12
+ const modelRegistry = await discoverModels(authStorage);
13
13
 
14
14
  // Option 1: Find a specific built-in model by provider/id
15
15
  const opus = getModel("anthropic", "claude-opus-4-5");
@@ -24,7 +24,7 @@ if (customModel) {
24
24
  }
25
25
 
26
26
  // Option 3: Pick from available models (have valid API keys)
27
- const available = await modelRegistry.getAvailable();
27
+ const available = modelRegistry.getAvailable();
28
28
  console.log(
29
29
  "Available models:",
30
30
  available.map((m) => `${m.provider}/${m.id}`),
@@ -39,17 +39,21 @@ console.log("Custom tools session created");
39
39
 
40
40
  // With custom cwd - MUST use factory functions!
41
41
  const customCwd = "/path/to/project";
42
+ const customTools = await createCodingTools(customCwd);
42
43
  await createAgentSession({
43
44
  cwd: customCwd,
44
- tools: createCodingTools(customCwd), // Tools resolve paths relative to customCwd
45
+ tools: customTools, // Tools resolve paths relative to customCwd
45
46
  sessionManager: SessionManager.inMemory(),
46
47
  });
47
48
  console.log("Custom cwd session created");
48
49
 
49
50
  // Or pick specific tools for custom cwd
51
+ const customReadTool = await createReadTool(customCwd);
52
+ const customBashTool = await createBashTool(customCwd);
53
+ const customGrepTool = await createGrepTool(customCwd);
50
54
  await createAgentSession({
51
55
  cwd: customCwd,
52
- tools: [createReadTool(customCwd), createBashTool(customCwd), createGrepTool(customCwd)],
56
+ tools: [customReadTool, customBashTool, customGrepTool],
53
57
  sessionManager: SessionManager.inMemory(),
54
58
  });
55
59
  console.log("Specific tools with custom cwd session created");
@@ -69,7 +73,7 @@ const weatherTool: CustomTool = {
69
73
  };
70
74
 
71
75
  const { session } = await createAgentSession({
72
- customTools: [{ tool: weatherTool }],
76
+ customTools: [weatherTool],
73
77
  sessionManager: SessionManager.inMemory(),
74
78
  });
75
79
 
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Extensions Configuration
3
+ *
4
+ * Extensions intercept agent events and can register custom tools.
5
+ * They provide a unified system for extensions, custom tools, commands, and more.
6
+ *
7
+ * Extension files are discovered from:
8
+ * - ~/.omp/agent/extensions/ (legacy: ~/.pi/agent/extensions/)
9
+ * - <cwd>/.omp/extensions/ (legacy: <cwd>/.pi/extensions/)
10
+ * - Paths specified in settings.json "extensions" array
11
+ * - Paths passed via --extension CLI flag
12
+ *
13
+ * An extension is a TypeScript file that exports a default function:
14
+ * export default function (pi: ExtensionAPI) { ... }
15
+ */
16
+
17
+ import { createAgentSession, SessionManager } from "@oh-my-pi/pi-coding-agent";
18
+
19
+ // Extensions are loaded from disk, not passed inline to createAgentSession.
20
+ // Use the discovery mechanism:
21
+ // 1. Place extension files in ~/.omp/agent/extensions/ or .omp/extensions/
22
+ // 2. Add paths to settings.json: { "extensions": ["./my-extension.ts"] }
23
+ // 3. Use --extension flag: pi --extension ./my-extension.ts
24
+
25
+ // To add additional extension paths beyond discovery:
26
+ const { session } = await createAgentSession({
27
+ additionalExtensionPaths: ["./my-logging-extension.ts", "./my-safety-extension.ts"],
28
+ sessionManager: SessionManager.inMemory(),
29
+ });
30
+
31
+ session.subscribe((event) => {
32
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
33
+ process.stdout.write(event.assistantMessageEvent.delta);
34
+ }
35
+ });
36
+
37
+ await session.prompt("List files in the current directory.");
38
+ console.log();
39
+
40
+ // Example extension file (./my-logging-extension.ts):
41
+ /*
42
+ import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
43
+
44
+ export default function (pi: ExtensionAPI) {
45
+ pi.on("agent_start", async () => {
46
+ console.log("[Extension] Agent starting");
47
+ });
48
+
49
+ pi.on("tool_call", async (event) => {
50
+ console.log(\`[Extension] Tool: \${event.toolName}\`);
51
+ // Return { block: true, reason: "..." } to block execution
52
+ return undefined;
53
+ });
54
+
55
+ pi.on("agent_end", async (event) => {
56
+ console.log(\`[Extension] Done, \${event.messages.length} messages\`);
57
+ });
58
+
59
+ // Register a custom tool
60
+ pi.registerTool({
61
+ name: "my_tool",
62
+ label: "My Tool",
63
+ description: "Does something useful",
64
+ parameters: Type.Object({
65
+ input: Type.String(),
66
+ }),
67
+ execute: async (_toolCallId, params, _onUpdate, _ctx, _signal) => ({
68
+ content: [{ type: "text", text: \`Processed: \${params.input}\` }],
69
+ details: {},
70
+ }),
71
+ });
72
+
73
+ // Register a command
74
+ pi.registerCommand("mycommand", {
75
+ description: "Do something",
76
+ handler: async (args, ctx) => {
77
+ ctx.ui.notify(\`Command executed with: \${args}\`);
78
+ },
79
+ });
80
+ }
81
+ */