tools.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 ~/.pi/agent/extensions/ or your project's .pi/extensions/
  9. * 2. Use /tools to open the tool selector
  10. */
  11. import type { ExtensionAPI, ExtensionContext, ToolInfo } from "@earendil-works/pi-coding-agent";
  12. import { getSettingsListTheme } from "@earendil-works/pi-coding-agent";
  13. import { Container, type SettingItem, SettingsList } from "@earendil-works/pi-tui";
  14. // State persisted to session
  15. interface ToolsState {
  16. enabledTools: string[];
  17. }
  18. export default function toolsExtension(pi: ExtensionAPI) {
  19. // Track enabled tools
  20. let enabledTools: Set<string> = new Set();
  21. let allTools: ToolInfo[] = [];
  22. // Persist current state
  23. function persistState() {
  24. pi.appendEntry<ToolsState>("tools-config", {
  25. enabledTools: Array.from(enabledTools),
  26. });
  27. }
  28. // Apply current tool selection
  29. function applyTools() {
  30. pi.setActiveTools(Array.from(enabledTools));
  31. }
  32. // Find the last tools-config entry in the current branch
  33. function restoreFromBranch(ctx: ExtensionContext) {
  34. allTools = pi.getAllTools();
  35. // Get entries in current branch only
  36. const branchEntries = ctx.sessionManager.getBranch();
  37. let savedTools: string[] | undefined;
  38. for (const entry of branchEntries) {
  39. if (entry.type === "custom" && entry.customType === "tools-config") {
  40. const data = entry.data as ToolsState | undefined;
  41. if (data?.enabledTools) {
  42. savedTools = data.enabledTools;
  43. }
  44. }
  45. }
  46. if (savedTools) {
  47. // Restore saved tool selection (filter to only tools that still exist)
  48. const allToolNames = allTools.map((t) => t.name);
  49. enabledTools = new Set(savedTools.filter((t: string) => allToolNames.includes(t)));
  50. applyTools();
  51. } else {
  52. // No saved state - sync with currently active tools
  53. enabledTools = new Set(pi.getActiveTools());
  54. }
  55. }
  56. // Register /tools command
  57. pi.registerCommand("tools", {
  58. description: "Enable/disable tools",
  59. handler: async (_args, ctx) => {
  60. if (ctx.mode !== "tui") {
  61. ctx.ui.notify("/tools requires TUI mode", "error");
  62. return;
  63. }
  64. // Refresh tool list
  65. allTools = pi.getAllTools();
  66. await ctx.ui.custom((tui, theme, _kb, done) => {
  67. // Build settings items for each tool
  68. const items: SettingItem[] = allTools.map((tool) => ({
  69. id: tool.name,
  70. label: tool.name,
  71. currentValue: enabledTools.has(tool.name) ? "enabled" : "disabled",
  72. values: ["enabled", "disabled"],
  73. }));
  74. const container = new Container();
  75. container.addChild(
  76. new (class {
  77. render(_width: number) {
  78. return [theme.fg("accent", theme.bold("Tool Configuration")), ""];
  79. }
  80. invalidate() {}
  81. })(),
  82. );
  83. const settingsList = new SettingsList(
  84. items,
  85. Math.min(items.length + 2, 15),
  86. getSettingsListTheme(),
  87. (id, newValue) => {
  88. // Update enabled state and apply immediately
  89. if (newValue === "enabled") {
  90. enabledTools.add(id);
  91. } else {
  92. enabledTools.delete(id);
  93. }
  94. applyTools();
  95. persistState();
  96. },
  97. () => {
  98. // Close dialog
  99. done(undefined);
  100. },
  101. );
  102. container.addChild(settingsList);
  103. const component = {
  104. render(width: number) {
  105. return container.render(width);
  106. },
  107. invalidate() {
  108. container.invalidate();
  109. },
  110. handleInput(data: string) {
  111. settingsList.handleInput?.(data);
  112. tui.requestRender();
  113. },
  114. };
  115. return component;
  116. });
  117. },
  118. });
  119. // Restore state on session start
  120. pi.on("session_start", async (_event, ctx) => {
  121. restoreFromBranch(ctx);
  122. });
  123. // Restore state when navigating the session tree
  124. pi.on("session_tree", async (_event, ctx) => {
  125. restoreFromBranch(ctx);
  126. });
  127. }