todo.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. import { StringEnum } from "@earendil-works/pi-ai";
  13. import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
  14. import { matchesKey, Text, truncateToWidth } from "@earendil-works/pi-tui";
  15. import { Type } from "typebox";
  16. interface Todo {
  17. id: number;
  18. text: string;
  19. done: boolean;
  20. }
  21. interface TodoDetails {
  22. action: "list" | "add" | "toggle" | "clear";
  23. todos: Todo[];
  24. nextId: number;
  25. error?: string;
  26. }
  27. const TodoParams = Type.Object({
  28. action: StringEnum(["list", "add", "toggle", "clear"] as const),
  29. text: Type.Optional(Type.String({ description: "Todo text (for add)" })),
  30. id: Type.Optional(Type.Number({ description: "Todo ID (for toggle)" })),
  31. });
  32. /**
  33. * UI component for the /todos command
  34. */
  35. class TodoListComponent {
  36. private todos: Todo[];
  37. private theme: Theme;
  38. private onClose: () => void;
  39. private cachedWidth?: number;
  40. private cachedLines?: string[];
  41. constructor(todos: Todo[], theme: Theme, onClose: () => void) {
  42. this.todos = todos;
  43. this.theme = theme;
  44. this.onClose = onClose;
  45. }
  46. handleInput(data: string): void {
  47. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  48. this.onClose();
  49. }
  50. }
  51. render(width: number): string[] {
  52. if (this.cachedLines && this.cachedWidth === width) {
  53. return this.cachedLines;
  54. }
  55. const lines: string[] = [];
  56. const th = this.theme;
  57. lines.push("");
  58. const title = th.fg("accent", " Todos ");
  59. const headerLine =
  60. th.fg("borderMuted", "─".repeat(3)) + title + th.fg("borderMuted", "─".repeat(Math.max(0, width - 10)));
  61. lines.push(truncateToWidth(headerLine, width));
  62. lines.push("");
  63. if (this.todos.length === 0) {
  64. lines.push(truncateToWidth(` ${th.fg("dim", "No todos yet. Ask the agent to add some!")}`, width));
  65. } else {
  66. const done = this.todos.filter((t) => t.done).length;
  67. const total = this.todos.length;
  68. lines.push(truncateToWidth(` ${th.fg("muted", `${done}/${total} completed`)}`, width));
  69. lines.push("");
  70. for (const todo of this.todos) {
  71. const check = todo.done ? th.fg("success", "✓") : th.fg("dim", "○");
  72. const id = th.fg("accent", `#${todo.id}`);
  73. const text = todo.done ? th.fg("dim", todo.text) : th.fg("text", todo.text);
  74. lines.push(truncateToWidth(` ${check} ${id} ${text}`, width));
  75. }
  76. }
  77. lines.push("");
  78. lines.push(truncateToWidth(` ${th.fg("dim", "Press Escape to close")}`, width));
  79. lines.push("");
  80. this.cachedWidth = width;
  81. this.cachedLines = lines;
  82. return lines;
  83. }
  84. invalidate(): void {
  85. this.cachedWidth = undefined;
  86. this.cachedLines = undefined;
  87. }
  88. }
  89. export default function (pi: ExtensionAPI) {
  90. // In-memory state (reconstructed from session on load)
  91. let todos: Todo[] = [];
  92. let nextId = 1;
  93. /**
  94. * Reconstruct state from session entries.
  95. * Scans tool results for this tool and applies them in order.
  96. */
  97. const reconstructState = (ctx: ExtensionContext) => {
  98. todos = [];
  99. nextId = 1;
  100. for (const entry of ctx.sessionManager.getBranch()) {
  101. if (entry.type !== "message") continue;
  102. const msg = entry.message;
  103. if (msg.role !== "toolResult" || msg.toolName !== "todo") continue;
  104. const details = msg.details as TodoDetails | undefined;
  105. if (details) {
  106. todos = details.todos;
  107. nextId = details.nextId;
  108. }
  109. }
  110. };
  111. // Reconstruct state on session events
  112. pi.on("session_start", async (_event, ctx) => reconstructState(ctx));
  113. pi.on("session_tree", async (_event, ctx) => reconstructState(ctx));
  114. // Register the todo tool for the LLM
  115. pi.registerTool({
  116. name: "todo",
  117. label: "Todo",
  118. description: "Manage a todo list. Actions: list, add (text), toggle (id), clear",
  119. parameters: TodoParams,
  120. async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
  121. switch (params.action) {
  122. case "list":
  123. return {
  124. content: [
  125. {
  126. type: "text",
  127. text: todos.length
  128. ? todos.map((t) => `[${t.done ? "x" : " "}] #${t.id}: ${t.text}`).join("\n")
  129. : "No todos",
  130. },
  131. ],
  132. details: { action: "list", todos: [...todos], nextId } as TodoDetails,
  133. };
  134. case "add": {
  135. if (!params.text) {
  136. return {
  137. content: [{ type: "text", text: "Error: text required for add" }],
  138. details: { action: "add", todos: [...todos], nextId, error: "text required" } as TodoDetails,
  139. };
  140. }
  141. const newTodo: Todo = { id: nextId++, text: params.text, done: false };
  142. todos.push(newTodo);
  143. return {
  144. content: [{ type: "text", text: `Added todo #${newTodo.id}: ${newTodo.text}` }],
  145. details: { action: "add", todos: [...todos], nextId } as TodoDetails,
  146. };
  147. }
  148. case "toggle": {
  149. if (params.id === undefined) {
  150. return {
  151. content: [{ type: "text", text: "Error: id required for toggle" }],
  152. details: { action: "toggle", todos: [...todos], nextId, error: "id required" } as TodoDetails,
  153. };
  154. }
  155. const todo = todos.find((t) => t.id === params.id);
  156. if (!todo) {
  157. return {
  158. content: [{ type: "text", text: `Todo #${params.id} not found` }],
  159. details: {
  160. action: "toggle",
  161. todos: [...todos],
  162. nextId,
  163. error: `#${params.id} not found`,
  164. } as TodoDetails,
  165. };
  166. }
  167. todo.done = !todo.done;
  168. return {
  169. content: [{ type: "text", text: `Todo #${todo.id} ${todo.done ? "completed" : "uncompleted"}` }],
  170. details: { action: "toggle", todos: [...todos], nextId } as TodoDetails,
  171. };
  172. }
  173. case "clear": {
  174. const count = todos.length;
  175. todos = [];
  176. nextId = 1;
  177. return {
  178. content: [{ type: "text", text: `Cleared ${count} todos` }],
  179. details: { action: "clear", todos: [], nextId: 1 } as TodoDetails,
  180. };
  181. }
  182. default:
  183. return {
  184. content: [{ type: "text", text: `Unknown action: ${params.action}` }],
  185. details: {
  186. action: "list",
  187. todos: [...todos],
  188. nextId,
  189. error: `unknown action: ${params.action}`,
  190. } as TodoDetails,
  191. };
  192. }
  193. },
  194. renderCall(args, theme, _context) {
  195. let text = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", args.action);
  196. if (args.text) text += ` ${theme.fg("dim", `"${args.text}"`)}`;
  197. if (args.id !== undefined) text += ` ${theme.fg("accent", `#${args.id}`)}`;
  198. return new Text(text, 0, 0);
  199. },
  200. renderResult(result, { expanded }, theme, _context) {
  201. const details = result.details as TodoDetails | undefined;
  202. if (!details) {
  203. const text = result.content[0];
  204. return new Text(text?.type === "text" ? text.text : "", 0, 0);
  205. }
  206. if (details.error) {
  207. return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
  208. }
  209. const todoList = details.todos;
  210. switch (details.action) {
  211. case "list": {
  212. if (todoList.length === 0) {
  213. return new Text(theme.fg("dim", "No todos"), 0, 0);
  214. }
  215. let listText = theme.fg("muted", `${todoList.length} todo(s):`);
  216. const display = expanded ? todoList : todoList.slice(0, 5);
  217. for (const t of display) {
  218. const check = t.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
  219. const itemText = t.done ? theme.fg("dim", t.text) : theme.fg("muted", t.text);
  220. listText += `\n${check} ${theme.fg("accent", `#${t.id}`)} ${itemText}`;
  221. }
  222. if (!expanded && todoList.length > 5) {
  223. listText += `\n${theme.fg("dim", `... ${todoList.length - 5} more`)}`;
  224. }
  225. return new Text(listText, 0, 0);
  226. }
  227. case "add": {
  228. const added = todoList[todoList.length - 1];
  229. return new Text(
  230. theme.fg("success", "✓ Added ") +
  231. theme.fg("accent", `#${added.id}`) +
  232. " " +
  233. theme.fg("muted", added.text),
  234. 0,
  235. 0,
  236. );
  237. }
  238. case "toggle": {
  239. const text = result.content[0];
  240. const msg = text?.type === "text" ? text.text : "";
  241. return new Text(theme.fg("success", "✓ ") + theme.fg("muted", msg), 0, 0);
  242. }
  243. case "clear":
  244. return new Text(theme.fg("success", "✓ ") + theme.fg("muted", "Cleared all todos"), 0, 0);
  245. }
  246. },
  247. });
  248. // Register the /todos command for users
  249. pi.registerCommand("todos", {
  250. description: "Show all todos on the current branch",
  251. handler: async (_args, ctx) => {
  252. if (ctx.mode !== "tui") {
  253. ctx.ui.notify("/todos requires interactive mode", "error");
  254. return;
  255. }
  256. await ctx.ui.custom<void>((_tui, theme, _kb, done) => {
  257. return new TodoListComponent(todos, theme, () => done());
  258. });
  259. },
  260. });
  261. }