@diegopetrucci/pi-todo 0.1.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 (3) hide show
  1. package/README.md +43 -0
  2. package/index.ts +301 -0
  3. package/package.json +30 -0
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # todo
2
+
3
+ A pi extension that adds a branch-aware todo list managed by the agent.
4
+
5
+ This started from the original `todo.ts` example in [`earendil-works/pi-mono`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/examples/extensions/todo.ts), with small packaging and snapshot-safety tweaks.
6
+
7
+ ## What it adds
8
+
9
+ - a `todo` tool for the agent to list, add, toggle, and clear todos
10
+ - a `/todos` command for users to view todos on the current branch
11
+ - todo state stored as snapshots in tool result details, so session branches reconstruct the right todo list for that point in history
12
+
13
+ ## Install
14
+
15
+ ### Standalone npm package
16
+
17
+ ```bash
18
+ pi install npm:@diegopetrucci/pi-todo
19
+ ```
20
+
21
+ ### Collection package
22
+
23
+ ```bash
24
+ pi install npm:@diegopetrucci/pi-extensions
25
+ ```
26
+
27
+ ### GitHub package
28
+
29
+ ```bash
30
+ pi install git:github.com/diegopetrucci/pi-extensions
31
+ ```
32
+
33
+ Then reload pi:
34
+
35
+ ```text
36
+ /reload
37
+ ```
38
+
39
+ ## Notes
40
+
41
+ - Hooks `session_start` and `session_tree` to reconstruct branch-local todo state.
42
+ - The `todo` tool supports `list`, `add`, `toggle`, and `clear` actions.
43
+ - The `/todos` command opens an interactive viewer and requires UI mode.
package/index.ts ADDED
@@ -0,0 +1,301 @@
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 "@earendil-works/pi-ai";
14
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
15
+ import { matchesKey, Text, truncateToWidth } from "@earendil-works/pi-tui";
16
+ import { Type } from "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 cloneTodos = (items: Todo[]): Todo[] => items.map((todo) => ({ ...todo }));
32
+
33
+ const TodoParams = Type.Object({
34
+ action: StringEnum(["list", "add", "toggle", "clear"] as const),
35
+ text: Type.Optional(Type.String({ description: "Todo text (for add)" })),
36
+ id: Type.Optional(Type.Number({ description: "Todo ID (for toggle)" })),
37
+ });
38
+
39
+ /**
40
+ * UI component for the /todos command
41
+ */
42
+ class TodoListComponent {
43
+ private todos: Todo[];
44
+ private theme: Theme;
45
+ private onClose: () => void;
46
+ private cachedWidth?: number;
47
+ private cachedLines?: string[];
48
+
49
+ constructor(todos: Todo[], theme: Theme, onClose: () => void) {
50
+ this.todos = todos;
51
+ this.theme = theme;
52
+ this.onClose = onClose;
53
+ }
54
+
55
+ handleInput(data: string): void {
56
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
57
+ this.onClose();
58
+ }
59
+ }
60
+
61
+ render(width: number): string[] {
62
+ if (this.cachedLines && this.cachedWidth === width) {
63
+ return this.cachedLines;
64
+ }
65
+
66
+ const lines: string[] = [];
67
+ const th = this.theme;
68
+
69
+ lines.push("");
70
+ const title = th.fg("accent", " Todos ");
71
+ const headerLine =
72
+ th.fg("borderMuted", "─".repeat(3)) + title + th.fg("borderMuted", "─".repeat(Math.max(0, width - 10)));
73
+ lines.push(truncateToWidth(headerLine, width));
74
+ lines.push("");
75
+
76
+ if (this.todos.length === 0) {
77
+ lines.push(truncateToWidth(` ${th.fg("dim", "No todos yet. Ask the agent to add some!")}`, width));
78
+ } else {
79
+ const done = this.todos.filter((t) => t.done).length;
80
+ const total = this.todos.length;
81
+ lines.push(truncateToWidth(` ${th.fg("muted", `${done}/${total} completed`)}`, width));
82
+ lines.push("");
83
+
84
+ for (const todo of this.todos) {
85
+ const check = todo.done ? th.fg("success", "✓") : th.fg("dim", "○");
86
+ const id = th.fg("accent", `#${todo.id}`);
87
+ const text = todo.done ? th.fg("dim", todo.text) : th.fg("text", todo.text);
88
+ lines.push(truncateToWidth(` ${check} ${id} ${text}`, width));
89
+ }
90
+ }
91
+
92
+ lines.push("");
93
+ lines.push(truncateToWidth(` ${th.fg("dim", "Press Escape to close")}`, width));
94
+ lines.push("");
95
+
96
+ this.cachedWidth = width;
97
+ this.cachedLines = lines;
98
+ return lines;
99
+ }
100
+
101
+ invalidate(): void {
102
+ this.cachedWidth = undefined;
103
+ this.cachedLines = undefined;
104
+ }
105
+ }
106
+
107
+ export default function (pi: ExtensionAPI) {
108
+ // In-memory state (reconstructed from session on load)
109
+ let todos: Todo[] = [];
110
+ let nextId = 1;
111
+
112
+ /**
113
+ * Reconstruct state from session entries.
114
+ * Scans tool results for this tool and applies them in order.
115
+ */
116
+ const reconstructState = (ctx: ExtensionContext) => {
117
+ todos = [];
118
+ nextId = 1;
119
+
120
+ for (const entry of ctx.sessionManager.getBranch()) {
121
+ if (entry.type !== "message") continue;
122
+ const msg = entry.message;
123
+ if (msg.role !== "toolResult" || msg.toolName !== "todo") continue;
124
+
125
+ const details = msg.details as TodoDetails | undefined;
126
+ if (details) {
127
+ todos = cloneTodos(details.todos);
128
+ nextId = details.nextId;
129
+ }
130
+ }
131
+ };
132
+
133
+ // Reconstruct state on session events
134
+ pi.on("session_start", 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, _signal, _onUpdate, _ctx) {
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: cloneTodos(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: cloneTodos(todos), nextId, error: "text required" } as TodoDetails,
164
+ };
165
+ }
166
+ const newTodo: Todo = { id: nextId++, text: params.text, done: false };
167
+ todos = [...todos, newTodo];
168
+ return {
169
+ content: [{ type: "text", text: `Added todo #${newTodo.id}: ${newTodo.text}` }],
170
+ details: { action: "add", todos: cloneTodos(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: cloneTodos(todos), nextId, error: "id required" } as TodoDetails,
179
+ };
180
+ }
181
+ const targetId = params.id;
182
+ const todo = todos.find((t) => t.id === targetId);
183
+ if (!todo) {
184
+ return {
185
+ content: [{ type: "text", text: `Todo #${targetId} not found` }],
186
+ details: {
187
+ action: "toggle",
188
+ todos: cloneTodos(todos),
189
+ nextId,
190
+ error: `#${targetId} not found`,
191
+ } as TodoDetails,
192
+ };
193
+ }
194
+ todos = todos.map((t) => (t.id === targetId ? { ...t, done: !t.done } : t));
195
+ const updated = todos.find((t) => t.id === targetId)!;
196
+ return {
197
+ content: [{ type: "text", text: `Todo #${updated.id} ${updated.done ? "completed" : "uncompleted"}` }],
198
+ details: { action: "toggle", todos: cloneTodos(todos), nextId } as TodoDetails,
199
+ };
200
+ }
201
+
202
+ case "clear": {
203
+ const count = todos.length;
204
+ todos = [];
205
+ nextId = 1;
206
+ return {
207
+ content: [{ type: "text", text: `Cleared ${count} todos` }],
208
+ details: { action: "clear", todos: [], nextId: 1 } as TodoDetails,
209
+ };
210
+ }
211
+
212
+ default:
213
+ return {
214
+ content: [{ type: "text", text: `Unknown action: ${params.action}` }],
215
+ details: {
216
+ action: "list",
217
+ todos: cloneTodos(todos),
218
+ nextId,
219
+ error: `unknown action: ${params.action}`,
220
+ } as TodoDetails,
221
+ };
222
+ }
223
+ },
224
+
225
+ renderCall(args, theme, _context) {
226
+ let text = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", args.action);
227
+ if (args.text) text += ` ${theme.fg("dim", `"${args.text}"`)}`;
228
+ if (args.id !== undefined) text += ` ${theme.fg("accent", `#${args.id}`)}`;
229
+ return new Text(text, 0, 0);
230
+ },
231
+
232
+ renderResult(result, { expanded }, theme, _context) {
233
+ const details = result.details as TodoDetails | undefined;
234
+ if (!details) {
235
+ const text = result.content[0];
236
+ return new Text(text?.type === "text" ? text.text : "", 0, 0);
237
+ }
238
+
239
+ if (details.error) {
240
+ return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
241
+ }
242
+
243
+ const todoList = details.todos;
244
+
245
+ switch (details.action) {
246
+ case "list": {
247
+ if (todoList.length === 0) {
248
+ return new Text(theme.fg("dim", "No todos"), 0, 0);
249
+ }
250
+ let listText = theme.fg("muted", `${todoList.length} todo(s):`);
251
+ const display = expanded ? todoList : todoList.slice(0, 5);
252
+ for (const t of display) {
253
+ const check = t.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
254
+ const itemText = t.done ? theme.fg("dim", t.text) : theme.fg("muted", t.text);
255
+ listText += `\n${check} ${theme.fg("accent", `#${t.id}`)} ${itemText}`;
256
+ }
257
+ if (!expanded && todoList.length > 5) {
258
+ listText += `\n${theme.fg("dim", `... ${todoList.length - 5} more`)}`;
259
+ }
260
+ return new Text(listText, 0, 0);
261
+ }
262
+
263
+ case "add": {
264
+ const added = todoList[todoList.length - 1];
265
+ return new Text(
266
+ theme.fg("success", "✓ Added ") +
267
+ theme.fg("accent", `#${added.id}`) +
268
+ " " +
269
+ theme.fg("muted", added.text),
270
+ 0,
271
+ 0,
272
+ );
273
+ }
274
+
275
+ case "toggle": {
276
+ const text = result.content[0];
277
+ const msg = text?.type === "text" ? text.text : "";
278
+ return new Text(theme.fg("success", "✓ ") + theme.fg("muted", msg), 0, 0);
279
+ }
280
+
281
+ case "clear":
282
+ return new Text(theme.fg("success", "✓ ") + theme.fg("muted", "Cleared all todos"), 0, 0);
283
+ }
284
+ },
285
+ });
286
+
287
+ // Register the /todos command for users
288
+ pi.registerCommand("todos", {
289
+ description: "Show all todos on the current branch",
290
+ handler: async (_args, ctx) => {
291
+ if (!ctx.hasUI) {
292
+ ctx.ui.notify("/todos requires interactive mode", "error");
293
+ return;
294
+ }
295
+
296
+ await ctx.ui.custom<void>((_tui, theme, _kb, done) => {
297
+ return new TodoListComponent(todos, theme, () => done());
298
+ });
299
+ },
300
+ });
301
+ }
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@diegopetrucci/pi-todo",
3
+ "version": "0.1.0",
4
+ "description": "A pi extension that adds a branch-aware todo tool and /todos viewer.",
5
+ "keywords": ["pi-package", "pi", "todo", "tool", "session"],
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/diegopetrucci/pi-extensions.git",
10
+ "directory": "extensions/todo"
11
+ },
12
+ "files": [
13
+ "index.ts",
14
+ "README.md"
15
+ ],
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "pi": {
20
+ "extensions": [
21
+ "index.ts"
22
+ ]
23
+ },
24
+ "peerDependencies": {
25
+ "@earendil-works/pi-ai": "*",
26
+ "@earendil-works/pi-coding-agent": "*",
27
+ "@earendil-works/pi-tui": "*",
28
+ "typebox": "*"
29
+ }
30
+ }