summarize.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import { complete, getModel } from "@earendil-works/pi-ai";
  2. import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
  3. import { DynamicBorder, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
  4. import { Container, Markdown, matchesKey, Text } from "@earendil-works/pi-tui";
  5. type ContentBlock = {
  6. type?: string;
  7. text?: string;
  8. name?: string;
  9. arguments?: Record<string, unknown>;
  10. };
  11. type SessionEntry = {
  12. type: string;
  13. message?: {
  14. role?: string;
  15. content?: unknown;
  16. };
  17. };
  18. const extractTextParts = (content: unknown): string[] => {
  19. if (typeof content === "string") {
  20. return [content];
  21. }
  22. if (!Array.isArray(content)) {
  23. return [];
  24. }
  25. const textParts: string[] = [];
  26. for (const part of content) {
  27. if (!part || typeof part !== "object") {
  28. continue;
  29. }
  30. const block = part as ContentBlock;
  31. if (block.type === "text" && typeof block.text === "string") {
  32. textParts.push(block.text);
  33. }
  34. }
  35. return textParts;
  36. };
  37. const extractToolCallLines = (content: unknown): string[] => {
  38. if (!Array.isArray(content)) {
  39. return [];
  40. }
  41. const toolCalls: string[] = [];
  42. for (const part of content) {
  43. if (!part || typeof part !== "object") {
  44. continue;
  45. }
  46. const block = part as ContentBlock;
  47. if (block.type !== "toolCall" || typeof block.name !== "string") {
  48. continue;
  49. }
  50. const args = block.arguments ?? {};
  51. toolCalls.push(`Tool ${block.name} was called with args ${JSON.stringify(args)}`);
  52. }
  53. return toolCalls;
  54. };
  55. const buildConversationText = (entries: SessionEntry[]): string => {
  56. const sections: string[] = [];
  57. for (const entry of entries) {
  58. if (entry.type !== "message" || !entry.message?.role) {
  59. continue;
  60. }
  61. const role = entry.message.role;
  62. const isUser = role === "user";
  63. const isAssistant = role === "assistant";
  64. if (!isUser && !isAssistant) {
  65. continue;
  66. }
  67. const entryLines: string[] = [];
  68. const textParts = extractTextParts(entry.message.content);
  69. if (textParts.length > 0) {
  70. const roleLabel = isUser ? "User" : "Assistant";
  71. const messageText = textParts.join("\n").trim();
  72. if (messageText.length > 0) {
  73. entryLines.push(`${roleLabel}: ${messageText}`);
  74. }
  75. }
  76. if (isAssistant) {
  77. entryLines.push(...extractToolCallLines(entry.message.content));
  78. }
  79. if (entryLines.length > 0) {
  80. sections.push(entryLines.join("\n"));
  81. }
  82. }
  83. return sections.join("\n\n");
  84. };
  85. const buildSummaryPrompt = (conversationText: string): string =>
  86. [
  87. "Summarize this conversation so I can resume it later.",
  88. "Include goals, key decisions, progress, open questions, and next steps.",
  89. "Keep it concise and structured with headings.",
  90. "",
  91. "<conversation>",
  92. conversationText,
  93. "</conversation>",
  94. ].join("\n");
  95. const showSummaryUi = async (summary: string, ctx: ExtensionCommandContext) => {
  96. if (ctx.mode !== "tui") {
  97. return;
  98. }
  99. await ctx.ui.custom((_tui, theme, _kb, done) => {
  100. const container = new Container();
  101. const border = new DynamicBorder((s: string) => theme.fg("accent", s));
  102. const mdTheme = getMarkdownTheme();
  103. container.addChild(border);
  104. container.addChild(new Text(theme.fg("accent", theme.bold("Conversation Summary")), 1, 0));
  105. container.addChild(new Markdown(summary, 1, 1, mdTheme));
  106. container.addChild(new Text(theme.fg("dim", "Press Enter or Esc to close"), 1, 0));
  107. container.addChild(border);
  108. return {
  109. render: (width: number) => container.render(width),
  110. invalidate: () => container.invalidate(),
  111. handleInput: (data: string) => {
  112. if (matchesKey(data, "enter") || matchesKey(data, "escape")) {
  113. done(undefined);
  114. }
  115. },
  116. };
  117. });
  118. };
  119. export default function (pi: ExtensionAPI) {
  120. pi.registerCommand("summarize", {
  121. description: "Summarize the current conversation in a custom UI",
  122. handler: async (_args, ctx) => {
  123. const branch = ctx.sessionManager.getBranch();
  124. const conversationText = buildConversationText(branch);
  125. if (!conversationText.trim()) {
  126. if (ctx.hasUI) {
  127. ctx.ui.notify("No conversation text found", "warning");
  128. }
  129. return;
  130. }
  131. if (ctx.hasUI) {
  132. ctx.ui.notify("Preparing summary...", "info");
  133. }
  134. const model = getModel("openai", "gpt-5.2");
  135. if (!model && ctx.hasUI) {
  136. ctx.ui.notify("Model openai/gpt-5.2 not found", "warning");
  137. }
  138. const auth = model ? await ctx.modelRegistry.getApiKeyAndHeaders(model) : undefined;
  139. if (auth && !auth.ok && ctx.hasUI) {
  140. ctx.ui.notify(auth.error, "warning");
  141. }
  142. if (auth?.ok && !auth.apiKey && ctx.hasUI) {
  143. ctx.ui.notify("No API key for openai/gpt-5.2", "warning");
  144. }
  145. if (!model || !auth?.ok || !auth.apiKey) {
  146. return;
  147. }
  148. const summaryMessages = [
  149. {
  150. role: "user" as const,
  151. content: [{ type: "text" as const, text: buildSummaryPrompt(conversationText) }],
  152. timestamp: Date.now(),
  153. },
  154. ];
  155. const response = await complete(
  156. model,
  157. { messages: summaryMessages },
  158. {
  159. apiKey: auth.apiKey,
  160. headers: auth.headers,
  161. reasoningEffort: "high",
  162. },
  163. );
  164. const summary = response.content
  165. .filter((c): c is { type: "text"; text: string } => c.type === "text")
  166. .map((c) => c.text)
  167. .join("\n");
  168. await showSummaryUi(summary, ctx);
  169. },
  170. });
  171. }