message-renderer.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * Custom message rendering example.
  3. *
  4. * Shows how to use registerMessageRenderer to control how custom messages
  5. * appear in the TUI, with colors, formatting, and expandable details.
  6. *
  7. * Usage: /status [message] - sends a status message with custom rendering
  8. */
  9. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  10. import { Box, Text } from "@earendil-works/pi-tui";
  11. export default function (pi: ExtensionAPI) {
  12. // Register custom renderer for "status-update" messages
  13. pi.registerMessageRenderer("status-update", (message, { expanded }, theme) => {
  14. const details = message.details as { level: string; timestamp: number } | undefined;
  15. const level = details?.level ?? "info";
  16. // Color based on level
  17. const color = level === "error" ? "error" : level === "warn" ? "warning" : "success";
  18. const prefix = theme.fg(color, `[${level.toUpperCase()}]`);
  19. let text = `${prefix} ${message.content}`;
  20. // Show timestamp when expanded
  21. if (expanded && details?.timestamp) {
  22. const time = new Date(details.timestamp).toLocaleTimeString();
  23. text += `\n${theme.fg("dim", ` at ${time}`)}`;
  24. }
  25. // Use Box with customMessageBg for consistent styling
  26. const box = new Box(1, 1, (t) => theme.bg("customMessageBg", t));
  27. box.addChild(new Text(text, 0, 0));
  28. return box;
  29. });
  30. // Command to send status messages
  31. pi.registerCommand("status", {
  32. description: "Send a status message (usage: /status [warn|error] message)",
  33. handler: async (args, _ctx) => {
  34. const parts = args.trim().split(/\s+/);
  35. let level = "info";
  36. let content = args.trim();
  37. // Check for level prefix
  38. if (parts[0] === "warn" || parts[0] === "error") {
  39. level = parts[0];
  40. content = parts.slice(1).join(" ") || "Status update";
  41. }
  42. pi.sendMessage({
  43. customType: "status-update",
  44. content,
  45. display: true,
  46. details: { level, timestamp: Date.now() },
  47. });
  48. },
  49. });
  50. }