event-bus.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Inter-extension event bus example.
  3. *
  4. * Shows pi.events for communication between extensions. One extension
  5. * can emit events that other extensions listen to.
  6. *
  7. * Usage: /emit [event-name] [data] - emit an event on the bus
  8. */
  9. import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
  10. export default function (pi: ExtensionAPI) {
  11. // Store ctx for use in event handler
  12. let currentCtx: ExtensionContext | undefined;
  13. pi.on("session_start", async (_event, ctx) => {
  14. currentCtx = ctx;
  15. });
  16. // Listen for events from other extensions
  17. pi.events.on("my:notification", (data) => {
  18. const { message, from } = data as { message: string; from: string };
  19. currentCtx?.ui.notify(`Event from ${from}: ${message}`, "info");
  20. });
  21. // Command to emit events (emits "my:notification" which the listener above receives)
  22. pi.registerCommand("emit", {
  23. description: "Emit my:notification event (usage: /emit message)",
  24. handler: async (args, _ctx) => {
  25. const message = args.trim() || "hello";
  26. pi.events.emit("my:notification", { message, from: "/emit command" });
  27. // Listener above will show the notification
  28. },
  29. });
  30. // Example: emit on session start
  31. pi.on("session_start", async () => {
  32. pi.events.emit("my:notification", {
  33. message: "Session started",
  34. from: "event-bus-example",
  35. });
  36. });
  37. }