@docyrus/docyrus 0.0.20 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/agent-loader.js +32 -1
  2. package/agent-loader.js.map +2 -2
  3. package/main.js +325 -71
  4. package/main.js.map +4 -4
  5. package/package.json +16 -3
  6. package/resources/chrome-tools/browser-content.js +103 -0
  7. package/resources/chrome-tools/browser-cookies.js +35 -0
  8. package/resources/chrome-tools/browser-eval.js +53 -0
  9. package/resources/chrome-tools/browser-hn-scraper.js +108 -0
  10. package/resources/chrome-tools/browser-nav.js +44 -0
  11. package/resources/chrome-tools/browser-pick.js +162 -0
  12. package/resources/chrome-tools/browser-screenshot.js +34 -0
  13. package/resources/chrome-tools/browser-start.js +86 -0
  14. package/resources/pi-agent/extensions/answer.ts +532 -0
  15. package/resources/pi-agent/extensions/context.ts +578 -0
  16. package/resources/pi-agent/extensions/control.ts +1779 -0
  17. package/resources/pi-agent/extensions/diff.ts +218 -0
  18. package/resources/pi-agent/extensions/files.ts +199 -0
  19. package/resources/pi-agent/extensions/loop.ts +446 -0
  20. package/resources/pi-agent/extensions/multi-edit.ts +835 -0
  21. package/resources/pi-agent/extensions/notify.ts +88 -0
  22. package/resources/pi-agent/extensions/pi-bash-live-view/LICENSE +21 -0
  23. package/resources/pi-agent/extensions/pi-bash-live-view/README.md +19 -0
  24. package/resources/pi-agent/extensions/pi-bash-live-view/index.ts +52 -0
  25. package/resources/pi-agent/extensions/pi-bash-live-view/package.json +61 -0
  26. package/resources/pi-agent/extensions/pi-bash-live-view/pty-execute.ts +97 -0
  27. package/resources/pi-agent/extensions/pi-bash-live-view/pty-kill.ts +25 -0
  28. package/resources/pi-agent/extensions/pi-bash-live-view/pty-session.ts +143 -0
  29. package/resources/pi-agent/extensions/pi-bash-live-view/spawn-helper.ts +31 -0
  30. package/resources/pi-agent/extensions/pi-bash-live-view/terminal-emulator.ts +439 -0
  31. package/resources/pi-agent/extensions/pi-bash-live-view/truncate.ts +68 -0
  32. package/resources/pi-agent/extensions/pi-bash-live-view/widget.ts +114 -0
  33. package/resources/pi-agent/extensions/pi-mcp-adapter/CHANGELOG.md +192 -0
  34. package/resources/pi-agent/extensions/pi-mcp-adapter/LICENSE +21 -0
  35. package/resources/pi-agent/extensions/pi-mcp-adapter/README.md +296 -0
  36. package/resources/pi-agent/extensions/pi-mcp-adapter/app-bridge.bundle.js +67 -0
  37. package/resources/pi-agent/extensions/pi-mcp-adapter/cli.js +108 -0
  38. package/resources/pi-agent/extensions/pi-mcp-adapter/commands.ts +211 -0
  39. package/resources/pi-agent/extensions/pi-mcp-adapter/config.ts +227 -0
  40. package/resources/pi-agent/extensions/pi-mcp-adapter/consent-manager.ts +64 -0
  41. package/resources/pi-agent/extensions/pi-mcp-adapter/direct-tools.ts +301 -0
  42. package/resources/pi-agent/extensions/pi-mcp-adapter/errors.ts +219 -0
  43. package/resources/pi-agent/extensions/pi-mcp-adapter/glimpse-ui.ts +80 -0
  44. package/resources/pi-agent/extensions/pi-mcp-adapter/host-html-template.ts +427 -0
  45. package/resources/pi-agent/extensions/pi-mcp-adapter/index.ts +232 -0
  46. package/resources/pi-agent/extensions/pi-mcp-adapter/init.ts +319 -0
  47. package/resources/pi-agent/extensions/pi-mcp-adapter/lifecycle.ts +93 -0
  48. package/resources/pi-agent/extensions/pi-mcp-adapter/logger.ts +169 -0
  49. package/resources/pi-agent/extensions/pi-mcp-adapter/mcp-panel.ts +713 -0
  50. package/resources/pi-agent/extensions/pi-mcp-adapter/metadata-cache.ts +191 -0
  51. package/resources/pi-agent/extensions/pi-mcp-adapter/npx-resolver.ts +419 -0
  52. package/resources/pi-agent/extensions/pi-mcp-adapter/oauth-handler.ts +56 -0
  53. package/resources/pi-agent/extensions/pi-mcp-adapter/package.json +85 -0
  54. package/resources/pi-agent/extensions/pi-mcp-adapter/paths.ts +29 -0
  55. package/resources/pi-agent/extensions/pi-mcp-adapter/proxy-modes.ts +635 -0
  56. package/resources/pi-agent/extensions/pi-mcp-adapter/resource-tools.ts +17 -0
  57. package/resources/pi-agent/extensions/pi-mcp-adapter/server-manager.ts +330 -0
  58. package/resources/pi-agent/extensions/pi-mcp-adapter/state.ts +41 -0
  59. package/resources/pi-agent/extensions/pi-mcp-adapter/tool-metadata.ts +144 -0
  60. package/resources/pi-agent/extensions/pi-mcp-adapter/tool-registrar.ts +46 -0
  61. package/resources/pi-agent/extensions/pi-mcp-adapter/types.ts +367 -0
  62. package/resources/pi-agent/extensions/pi-mcp-adapter/ui-resource-handler.ts +145 -0
  63. package/resources/pi-agent/extensions/pi-mcp-adapter/ui-server.ts +623 -0
  64. package/resources/pi-agent/extensions/pi-mcp-adapter/ui-session.ts +384 -0
  65. package/resources/pi-agent/extensions/pi-mcp-adapter/ui-stream-types.ts +89 -0
  66. package/resources/pi-agent/extensions/pi-mcp-adapter/utils.ts +75 -0
  67. package/resources/pi-agent/extensions/prompt-editor.ts +1315 -0
  68. package/resources/pi-agent/extensions/prompt-url-widget.ts +158 -0
  69. package/resources/pi-agent/extensions/redraws.ts +24 -0
  70. package/resources/pi-agent/extensions/review.ts +2160 -0
  71. package/resources/pi-agent/extensions/todos.ts +2076 -0
  72. package/resources/pi-agent/extensions/tps.ts +47 -0
  73. package/resources/pi-agent/extensions/whimsical.ts +474 -0
  74. package/resources/pi-agent/skills/changelog-generator/SKILL.md +425 -0
  75. package/resources/pi-agent/skills/docyrus-chrome-devtools-cli/SKILL.md +80 -0
  76. package/resources/pi-agent/skills/docyrus-platform/references/docyrus-cli-usage.md +51 -0
@@ -0,0 +1,532 @@
1
+ /**
2
+ * Q&A extraction hook - extracts questions from assistant responses
3
+ *
4
+ * Custom interactive TUI for answering questions.
5
+ *
6
+ * Demonstrates the "prompt generator" pattern with custom TUI:
7
+ * 1. /answer command gets the last assistant message
8
+ * 2. Shows a spinner while extracting questions as structured JSON
9
+ * 3. Presents an interactive TUI to navigate and answer questions
10
+ * 4. Submits the compiled answers when done
11
+ */
12
+
13
+ import { complete, type Model, type Api, type UserMessage } from "@mariozechner/pi-ai";
14
+ import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
15
+ import { BorderedLoader } from "@mariozechner/pi-coding-agent";
16
+ import {
17
+ type Component,
18
+ Editor,
19
+ type EditorTheme,
20
+ Key,
21
+ matchesKey,
22
+ truncateToWidth,
23
+ type TUI,
24
+ visibleWidth,
25
+ wrapTextWithAnsi,
26
+ } from "@mariozechner/pi-tui";
27
+
28
+ // Structured output format for question extraction
29
+ interface ExtractedQuestion {
30
+ question: string;
31
+ context?: string;
32
+ }
33
+
34
+ interface ExtractionResult {
35
+ questions: ExtractedQuestion[];
36
+ }
37
+
38
+ const SYSTEM_PROMPT = `You are a question extractor. Given text from a conversation, extract any questions that need answering.
39
+
40
+ Output a JSON object with this structure:
41
+ {
42
+ "questions": [
43
+ {
44
+ "question": "The question text",
45
+ "context": "Optional context that helps answer the question"
46
+ }
47
+ ]
48
+ }
49
+
50
+ Rules:
51
+ - Extract all questions that require user input
52
+ - Keep questions in the order they appeared
53
+ - Be concise with question text
54
+ - Include context only when it provides essential information for answering
55
+ - If no questions are found, return {"questions": []}
56
+
57
+ Example output:
58
+ {
59
+ "questions": [
60
+ {
61
+ "question": "What is your preferred database?",
62
+ "context": "We can only configure MySQL and PostgreSQL because of what is implemented."
63
+ },
64
+ {
65
+ "question": "Should we use TypeScript or JavaScript?"
66
+ }
67
+ ]
68
+ }`;
69
+
70
+ const CODEX_MODEL_ID = "gpt-5.1-codex-mini";
71
+ const HAIKU_MODEL_ID = "claude-haiku-4-5";
72
+
73
+ /**
74
+ * Prefer Codex mini for extraction when available, otherwise fallback to haiku or the current model.
75
+ */
76
+ async function selectExtractionModel(
77
+ currentModel: Model<Api>,
78
+ modelRegistry: {
79
+ find: (provider: string, modelId: string) => Model<Api> | undefined;
80
+ getApiKey: (model: Model<Api>) => Promise<string | undefined>;
81
+ },
82
+ ): Promise<Model<Api>> {
83
+ const codexModel = modelRegistry.find("openai-codex", CODEX_MODEL_ID);
84
+ if (codexModel) {
85
+ const apiKey = await modelRegistry.getApiKey(codexModel);
86
+ if (apiKey) {
87
+ return codexModel;
88
+ }
89
+ }
90
+
91
+ const haikuModel = modelRegistry.find("anthropic", HAIKU_MODEL_ID);
92
+ if (!haikuModel) {
93
+ return currentModel;
94
+ }
95
+
96
+ const apiKey = await modelRegistry.getApiKey(haikuModel);
97
+ if (!apiKey) {
98
+ return currentModel;
99
+ }
100
+
101
+ return haikuModel;
102
+ }
103
+
104
+ /**
105
+ * Parse the JSON response from the LLM
106
+ */
107
+ function parseExtractionResult(text: string): ExtractionResult | null {
108
+ try {
109
+ // Try to find JSON in the response (it might be wrapped in markdown code blocks)
110
+ let jsonStr = text;
111
+
112
+ // Remove markdown code block if present
113
+ const jsonMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/);
114
+ if (jsonMatch) {
115
+ jsonStr = jsonMatch[1].trim();
116
+ }
117
+
118
+ const parsed = JSON.parse(jsonStr);
119
+ if (parsed && Array.isArray(parsed.questions)) {
120
+ return parsed as ExtractionResult;
121
+ }
122
+ return null;
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Interactive Q&A component for answering extracted questions
130
+ */
131
+ class QnAComponent implements Component {
132
+ private questions: ExtractedQuestion[];
133
+ private answers: string[];
134
+ private currentIndex: number = 0;
135
+ private editor: Editor;
136
+ private tui: TUI;
137
+ private onDone: (result: string | null) => void;
138
+ private showingConfirmation: boolean = false;
139
+
140
+ // Cache
141
+ private cachedWidth?: number;
142
+ private cachedLines?: string[];
143
+
144
+ // Colors - using proper reset sequences
145
+ private dim = (s: string) => `\x1b[2m${s}\x1b[0m`;
146
+ private bold = (s: string) => `\x1b[1m${s}\x1b[0m`;
147
+ private cyan = (s: string) => `\x1b[36m${s}\x1b[0m`;
148
+ private green = (s: string) => `\x1b[32m${s}\x1b[0m`;
149
+ private yellow = (s: string) => `\x1b[33m${s}\x1b[0m`;
150
+ private gray = (s: string) => `\x1b[90m${s}\x1b[0m`;
151
+
152
+ constructor(
153
+ questions: ExtractedQuestion[],
154
+ tui: TUI,
155
+ onDone: (result: string | null) => void,
156
+ ) {
157
+ this.questions = questions;
158
+ this.answers = questions.map(() => "");
159
+ this.tui = tui;
160
+ this.onDone = onDone;
161
+
162
+ // Create a minimal theme for the editor
163
+ const editorTheme: EditorTheme = {
164
+ borderColor: this.dim,
165
+ selectList: {
166
+ selectedBg: (s: string) => `\x1b[44m${s}\x1b[0m`,
167
+ matchHighlight: this.cyan,
168
+ itemSecondary: this.gray,
169
+ },
170
+ };
171
+
172
+ this.editor = new Editor(tui, editorTheme);
173
+ // Disable the editor's built-in submit (which clears the editor)
174
+ // We'll handle Enter ourselves to preserve the text
175
+ this.editor.disableSubmit = true;
176
+ this.editor.onChange = () => {
177
+ this.invalidate();
178
+ this.tui.requestRender();
179
+ };
180
+ }
181
+
182
+ private allQuestionsAnswered(): boolean {
183
+ this.saveCurrentAnswer();
184
+ return this.answers.every((a) => (a?.trim() || "").length > 0);
185
+ }
186
+
187
+ private saveCurrentAnswer(): void {
188
+ this.answers[this.currentIndex] = this.editor.getText();
189
+ }
190
+
191
+ private navigateTo(index: number): void {
192
+ if (index < 0 || index >= this.questions.length) return;
193
+ this.saveCurrentAnswer();
194
+ this.currentIndex = index;
195
+ this.editor.setText(this.answers[index] || "");
196
+ this.invalidate();
197
+ }
198
+
199
+ private submit(): void {
200
+ this.saveCurrentAnswer();
201
+
202
+ // Build the response text
203
+ const parts: string[] = [];
204
+ for (let i = 0; i < this.questions.length; i++) {
205
+ const q = this.questions[i];
206
+ const a = this.answers[i]?.trim() || "(no answer)";
207
+ parts.push(`Q: ${q.question}`);
208
+ if (q.context) {
209
+ parts.push(`> ${q.context}`);
210
+ }
211
+ parts.push(`A: ${a}`);
212
+ parts.push("");
213
+ }
214
+
215
+ this.onDone(parts.join("\n").trim());
216
+ }
217
+
218
+ private cancel(): void {
219
+ this.onDone(null);
220
+ }
221
+
222
+ invalidate(): void {
223
+ this.cachedWidth = undefined;
224
+ this.cachedLines = undefined;
225
+ }
226
+
227
+ handleInput(data: string): void {
228
+ // Handle confirmation dialog
229
+ if (this.showingConfirmation) {
230
+ if (matchesKey(data, Key.enter) || data.toLowerCase() === "y") {
231
+ this.submit();
232
+ return;
233
+ }
234
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c")) || data.toLowerCase() === "n") {
235
+ this.showingConfirmation = false;
236
+ this.invalidate();
237
+ this.tui.requestRender();
238
+ return;
239
+ }
240
+ return;
241
+ }
242
+
243
+ // Global navigation and commands
244
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
245
+ this.cancel();
246
+ return;
247
+ }
248
+
249
+ // Tab / Shift+Tab for navigation
250
+ if (matchesKey(data, Key.tab)) {
251
+ if (this.currentIndex < this.questions.length - 1) {
252
+ this.navigateTo(this.currentIndex + 1);
253
+ this.tui.requestRender();
254
+ }
255
+ return;
256
+ }
257
+ if (matchesKey(data, Key.shift("tab"))) {
258
+ if (this.currentIndex > 0) {
259
+ this.navigateTo(this.currentIndex - 1);
260
+ this.tui.requestRender();
261
+ }
262
+ return;
263
+ }
264
+
265
+ // Arrow up/down for question navigation when editor is empty
266
+ // (Editor handles its own cursor navigation when there's content)
267
+ if (matchesKey(data, Key.up) && this.editor.getText() === "") {
268
+ if (this.currentIndex > 0) {
269
+ this.navigateTo(this.currentIndex - 1);
270
+ this.tui.requestRender();
271
+ return;
272
+ }
273
+ }
274
+ if (matchesKey(data, Key.down) && this.editor.getText() === "") {
275
+ if (this.currentIndex < this.questions.length - 1) {
276
+ this.navigateTo(this.currentIndex + 1);
277
+ this.tui.requestRender();
278
+ return;
279
+ }
280
+ }
281
+
282
+ // Handle Enter ourselves (editor's submit is disabled)
283
+ // Plain Enter moves to next question or shows confirmation on last question
284
+ // Shift+Enter adds a newline (handled by editor)
285
+ if (matchesKey(data, Key.enter) && !matchesKey(data, Key.shift("enter"))) {
286
+ this.saveCurrentAnswer();
287
+ if (this.currentIndex < this.questions.length - 1) {
288
+ this.navigateTo(this.currentIndex + 1);
289
+ } else {
290
+ // On last question - show confirmation
291
+ this.showingConfirmation = true;
292
+ }
293
+ this.invalidate();
294
+ this.tui.requestRender();
295
+ return;
296
+ }
297
+
298
+ // Pass to editor
299
+ this.editor.handleInput(data);
300
+ this.invalidate();
301
+ this.tui.requestRender();
302
+ }
303
+
304
+ render(width: number): string[] {
305
+ if (this.cachedLines && this.cachedWidth === width) {
306
+ return this.cachedLines;
307
+ }
308
+
309
+ const lines: string[] = [];
310
+ const boxWidth = Math.min(width - 4, 120); // Allow wider box
311
+ const contentWidth = boxWidth - 4; // 2 chars padding on each side
312
+
313
+ // Helper to create horizontal lines (dim the whole thing at once)
314
+ const horizontalLine = (count: number) => "─".repeat(count);
315
+
316
+ // Helper to create a box line
317
+ const boxLine = (content: string, leftPad: number = 2): string => {
318
+ const paddedContent = " ".repeat(leftPad) + content;
319
+ const contentLen = visibleWidth(paddedContent);
320
+ const rightPad = Math.max(0, boxWidth - contentLen - 2);
321
+ return this.dim("│") + paddedContent + " ".repeat(rightPad) + this.dim("│");
322
+ };
323
+
324
+ const emptyBoxLine = (): string => {
325
+ return this.dim("│") + " ".repeat(boxWidth - 2) + this.dim("│");
326
+ };
327
+
328
+ const padToWidth = (line: string): string => {
329
+ const len = visibleWidth(line);
330
+ return line + " ".repeat(Math.max(0, width - len));
331
+ };
332
+
333
+ // Title
334
+ lines.push(padToWidth(this.dim("╭" + horizontalLine(boxWidth - 2) + "╮")));
335
+ const title = `${this.bold(this.cyan("Questions"))} ${this.dim(`(${this.currentIndex + 1}/${this.questions.length})`)}`;
336
+ lines.push(padToWidth(boxLine(title)));
337
+ lines.push(padToWidth(this.dim("├" + horizontalLine(boxWidth - 2) + "┤")));
338
+
339
+ // Progress indicator
340
+ const progressParts: string[] = [];
341
+ for (let i = 0; i < this.questions.length; i++) {
342
+ const answered = (this.answers[i]?.trim() || "").length > 0;
343
+ const current = i === this.currentIndex;
344
+ if (current) {
345
+ progressParts.push(this.cyan("●"));
346
+ } else if (answered) {
347
+ progressParts.push(this.green("●"));
348
+ } else {
349
+ progressParts.push(this.dim("○"));
350
+ }
351
+ }
352
+ lines.push(padToWidth(boxLine(progressParts.join(" "))));
353
+ lines.push(padToWidth(emptyBoxLine()));
354
+
355
+ // Current question
356
+ const q = this.questions[this.currentIndex];
357
+ const questionText = `${this.bold("Q:")} ${q.question}`;
358
+ const wrappedQuestion = wrapTextWithAnsi(questionText, contentWidth);
359
+ for (const line of wrappedQuestion) {
360
+ lines.push(padToWidth(boxLine(line)));
361
+ }
362
+
363
+ // Context if present
364
+ if (q.context) {
365
+ lines.push(padToWidth(emptyBoxLine()));
366
+ const contextText = this.gray(`> ${q.context}`);
367
+ const wrappedContext = wrapTextWithAnsi(contextText, contentWidth - 2);
368
+ for (const line of wrappedContext) {
369
+ lines.push(padToWidth(boxLine(line)));
370
+ }
371
+ }
372
+
373
+ lines.push(padToWidth(emptyBoxLine()));
374
+
375
+ // Render the editor component (multi-line input) with padding
376
+ // Skip the first and last lines (editor's own border lines)
377
+ const answerPrefix = this.bold("A: ");
378
+ const editorWidth = contentWidth - 4 - 3; // Extra padding + space for "A: "
379
+ const editorLines = this.editor.render(editorWidth);
380
+ for (let i = 1; i < editorLines.length - 1; i++) {
381
+ if (i === 1) {
382
+ // First content line gets the "A: " prefix
383
+ lines.push(padToWidth(boxLine(answerPrefix + editorLines[i])));
384
+ } else {
385
+ // Subsequent lines get padding to align with the first line
386
+ lines.push(padToWidth(boxLine(" " + editorLines[i])));
387
+ }
388
+ }
389
+
390
+ lines.push(padToWidth(emptyBoxLine()));
391
+
392
+ // Confirmation dialog or footer with controls
393
+ if (this.showingConfirmation) {
394
+ lines.push(padToWidth(this.dim("├" + horizontalLine(boxWidth - 2) + "┤")));
395
+ const confirmMsg = `${this.yellow("Submit all answers?")} ${this.dim("(Enter/y to confirm, Esc/n to cancel)")}`;
396
+ lines.push(padToWidth(boxLine(truncateToWidth(confirmMsg, contentWidth))));
397
+ } else {
398
+ lines.push(padToWidth(this.dim("├" + horizontalLine(boxWidth - 2) + "┤")));
399
+ const controls = `${this.dim("Tab/Enter")} next · ${this.dim("Shift+Tab")} prev · ${this.dim("Shift+Enter")} newline · ${this.dim("Esc")} cancel`;
400
+ lines.push(padToWidth(boxLine(truncateToWidth(controls, contentWidth))));
401
+ }
402
+ lines.push(padToWidth(this.dim("╰" + horizontalLine(boxWidth - 2) + "╯")));
403
+
404
+ this.cachedWidth = width;
405
+ this.cachedLines = lines;
406
+ return lines;
407
+ }
408
+ }
409
+
410
+ export default function (pi: ExtensionAPI) {
411
+ const answerHandler = async (ctx: ExtensionContext) => {
412
+ if (!ctx.hasUI) {
413
+ ctx.ui.notify("answer requires interactive mode", "error");
414
+ return;
415
+ }
416
+
417
+ if (!ctx.model) {
418
+ ctx.ui.notify("No model selected", "error");
419
+ return;
420
+ }
421
+
422
+ // Find the last assistant message on the current branch
423
+ const branch = ctx.sessionManager.getBranch();
424
+ let lastAssistantText: string | undefined;
425
+
426
+ for (let i = branch.length - 1; i >= 0; i--) {
427
+ const entry = branch[i];
428
+ if (entry.type === "message") {
429
+ const msg = entry.message;
430
+ if ("role" in msg && msg.role === "assistant") {
431
+ if (msg.stopReason !== "stop") {
432
+ ctx.ui.notify(`Last assistant message incomplete (${msg.stopReason})`, "error");
433
+ return;
434
+ }
435
+ const textParts = msg.content
436
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
437
+ .map((c) => c.text);
438
+ if (textParts.length > 0) {
439
+ lastAssistantText = textParts.join("\n");
440
+ break;
441
+ }
442
+ }
443
+ }
444
+ }
445
+
446
+ if (!lastAssistantText) {
447
+ ctx.ui.notify("No assistant messages found", "error");
448
+ return;
449
+ }
450
+
451
+ // Select the best model for extraction (prefer Codex mini, then haiku)
452
+ const extractionModel = await selectExtractionModel(ctx.model, ctx.modelRegistry);
453
+
454
+ // Run extraction with loader UI
455
+ const extractionResult = await ctx.ui.custom<ExtractionResult | null>((tui, theme, _kb, done) => {
456
+ const loader = new BorderedLoader(tui, theme, `Extracting questions using ${extractionModel.id}...`);
457
+ loader.onAbort = () => done(null);
458
+
459
+ const doExtract = async () => {
460
+ const apiKey = await ctx.modelRegistry.getApiKey(extractionModel);
461
+ const userMessage: UserMessage = {
462
+ role: "user",
463
+ content: [{ type: "text", text: lastAssistantText! }],
464
+ timestamp: Date.now(),
465
+ };
466
+
467
+ const response = await complete(
468
+ extractionModel,
469
+ { systemPrompt: SYSTEM_PROMPT, messages: [userMessage] },
470
+ { apiKey, signal: loader.signal },
471
+ );
472
+
473
+ if (response.stopReason === "aborted") {
474
+ return null;
475
+ }
476
+
477
+ const responseText = response.content
478
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
479
+ .map((c) => c.text)
480
+ .join("\n");
481
+
482
+ return parseExtractionResult(responseText);
483
+ };
484
+
485
+ doExtract()
486
+ .then(done)
487
+ .catch(() => done(null));
488
+
489
+ return loader;
490
+ });
491
+
492
+ if (extractionResult === null) {
493
+ ctx.ui.notify("Cancelled", "info");
494
+ return;
495
+ }
496
+
497
+ if (extractionResult.questions.length === 0) {
498
+ ctx.ui.notify("No questions found in the last message", "info");
499
+ return;
500
+ }
501
+
502
+ // Show the Q&A component
503
+ const answersResult = await ctx.ui.custom<string | null>((tui, _theme, _kb, done) => {
504
+ return new QnAComponent(extractionResult.questions, tui, done);
505
+ });
506
+
507
+ if (answersResult === null) {
508
+ ctx.ui.notify("Cancelled", "info");
509
+ return;
510
+ }
511
+
512
+ // Send the answers directly as a message and trigger a turn
513
+ pi.sendMessage(
514
+ {
515
+ customType: "answers",
516
+ content: "I answered your questions in the following way:\n\n" + answersResult,
517
+ display: true,
518
+ },
519
+ { triggerTurn: true },
520
+ );
521
+ };
522
+
523
+ pi.registerCommand("answer", {
524
+ description: "Extract questions from last assistant message into interactive Q&A",
525
+ handler: (_args, ctx) => answerHandler(ctx),
526
+ });
527
+
528
+ pi.registerShortcut("ctrl+.", {
529
+ description: "Extract and answer questions",
530
+ handler: answerHandler,
531
+ });
532
+ }