dynamic-tools.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Dynamic Tools Extension
  3. *
  4. * Demonstrates registering tools after session initialization.
  5. *
  6. * - Registers one tool during session_start
  7. * - Registers additional tools at runtime via /add-echo-tool <name>
  8. */
  9. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  10. import { Type } from "typebox";
  11. const ECHO_PARAMS = Type.Object({
  12. message: Type.String({ description: "Message to echo" }),
  13. });
  14. function normalizeToolName(input: string): string | undefined {
  15. const trimmed = input.trim().toLowerCase();
  16. if (!trimmed) return undefined;
  17. if (!/^[a-z0-9_]+$/.test(trimmed)) return undefined;
  18. return trimmed;
  19. }
  20. export default function dynamicToolsExtension(pi: ExtensionAPI) {
  21. const registeredToolNames = new Set<string>();
  22. const registerEchoTool = (name: string, label: string, prefix: string): boolean => {
  23. if (registeredToolNames.has(name)) {
  24. return false;
  25. }
  26. registeredToolNames.add(name);
  27. pi.registerTool({
  28. name,
  29. label,
  30. description: `Echo a message with prefix: ${prefix}`,
  31. promptSnippet: `Echo back user-provided text with ${prefix.trim()} prefix`,
  32. promptGuidelines: ["Use echo_session when the user asks for exact echo output."],
  33. parameters: ECHO_PARAMS,
  34. async execute(_toolCallId, params) {
  35. return {
  36. content: [{ type: "text", text: `${prefix}${params.message}` }],
  37. details: { tool: name, prefix },
  38. };
  39. },
  40. });
  41. return true;
  42. };
  43. pi.on("session_start", (_event, ctx) => {
  44. registerEchoTool("echo_session", "Echo Session", "[session] ");
  45. ctx.ui.notify("Registered dynamic tool: echo_session", "info");
  46. });
  47. pi.registerCommand("add-echo-tool", {
  48. description: "Register a new echo tool dynamically: /add-echo-tool <tool_name>",
  49. handler: async (args, ctx) => {
  50. const toolName = normalizeToolName(args);
  51. if (!toolName) {
  52. ctx.ui.notify("Usage: /add-echo-tool <tool_name> (lowercase, numbers, underscores)", "warning");
  53. return;
  54. }
  55. const created = registerEchoTool(toolName, `Echo ${toolName}`, `[${toolName}] `);
  56. if (!created) {
  57. ctx.ui.notify(`Tool already registered: ${toolName}`, "warning");
  58. return;
  59. }
  60. ctx.ui.notify(`Registered dynamic tool: ${toolName}`, "info");
  61. },
  62. });
  63. }