tau-coding-agent 0.1.0

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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -0
  3. package/extensions/answer.ts +601 -0
  4. package/extensions/branch-term.ts +405 -0
  5. package/extensions/btw.ts +444 -0
  6. package/extensions/ghostty.ts +301 -0
  7. package/extensions/git-diff-stats.ts +277 -0
  8. package/extensions/git-pr-status.ts +286 -0
  9. package/extensions/insights.ts +2367 -0
  10. package/extensions/interlude.ts +144 -0
  11. package/extensions/loop.ts +529 -0
  12. package/extensions/memory.ts +1889 -0
  13. package/extensions/notify.ts +161 -0
  14. package/extensions/openai-fast.ts +227 -0
  15. package/extensions/openai-verbosity.ts +223 -0
  16. package/extensions/review.ts +4347 -0
  17. package/extensions/sandbox/index.ts +2578 -0
  18. package/extensions/usage/anthropic.ts +198 -0
  19. package/extensions/usage/github-copilot.ts +204 -0
  20. package/extensions/usage/google-gemini-cli.ts +232 -0
  21. package/extensions/usage/index.ts +2310 -0
  22. package/extensions/usage/minimax.ts +208 -0
  23. package/extensions/usage/openai-codex.ts +180 -0
  24. package/extensions/usage/openrouter.ts +168 -0
  25. package/extensions/usage/providers.ts +26 -0
  26. package/extensions/usage/shared.ts +156 -0
  27. package/extensions/usage/types.ts +53 -0
  28. package/extensions/usage/zai.ts +186 -0
  29. package/extensions/websearch/README.md +68 -0
  30. package/extensions/websearch/browser/chromium.ts +330 -0
  31. package/extensions/websearch/browser/discovery.ts +75 -0
  32. package/extensions/websearch/browser/firefox.ts +150 -0
  33. package/extensions/websearch/browser/sqlite.ts +38 -0
  34. package/extensions/websearch/config.ts +76 -0
  35. package/extensions/websearch/index.ts +312 -0
  36. package/extensions/websearch/normalize.ts +155 -0
  37. package/extensions/websearch/providers/anthropic.pi.ts +139 -0
  38. package/extensions/websearch/providers/gemini.browser.ts +185 -0
  39. package/extensions/websearch/providers/gemini.pi.ts +108 -0
  40. package/extensions/websearch/providers/openai-codex.browser.ts +77 -0
  41. package/extensions/websearch/providers/openai-codex.pi.ts +49 -0
  42. package/extensions/websearch/providers/openai-codex.shared.ts +123 -0
  43. package/extensions/websearch/providers/pi-model.shared.ts +86 -0
  44. package/extensions/websearch/providers/search-prompt.shared.ts +17 -0
  45. package/extensions/websearch/providers/shared.ts +76 -0
  46. package/extensions/websearch/types.ts +52 -0
  47. package/extensions/worktree.ts +2223 -0
  48. package/package.json +72 -0
  49. package/skills/browser-tools/SKILL.md +253 -0
  50. package/skills/browser-tools/scripts/browser-content.js +100 -0
  51. package/skills/browser-tools/scripts/browser-cookies.js +33 -0
  52. package/skills/browser-tools/scripts/browser-dismiss-cookies.js +455 -0
  53. package/skills/browser-tools/scripts/browser-eval.js +75 -0
  54. package/skills/browser-tools/scripts/browser-logs-tail.js +89 -0
  55. package/skills/browser-tools/scripts/browser-nav.js +28 -0
  56. package/skills/browser-tools/scripts/browser-net-summary.js +115 -0
  57. package/skills/browser-tools/scripts/browser-pick.js +133 -0
  58. package/skills/browser-tools/scripts/browser-screenshot.js +18 -0
  59. package/skills/browser-tools/scripts/browser-start.js +281 -0
  60. package/skills/browser-tools/scripts/browser-watch.js +321 -0
  61. package/skills/browser-tools/scripts/utils.js +60 -0
  62. package/skills/git-clean-history/SKILL.md +45 -0
  63. package/skills/git-commit/SKILL.md +55 -0
  64. package/skills/oracle/SKILL.md +64 -0
  65. package/skills/oracle/scripts/oracle +249 -0
  66. package/skills/oracle/scripts/oracle-bundle +227 -0
  67. package/skills/sentry/SKILL.md +198 -0
  68. package/skills/sentry/lib/auth.js +99 -0
  69. package/skills/sentry/scripts/fetch-event.js +325 -0
  70. package/skills/sentry/scripts/fetch-issue.js +368 -0
  71. package/skills/sentry/scripts/list-issues.js +245 -0
  72. package/skills/sentry/scripts/search-events.js +291 -0
  73. package/skills/sentry/scripts/search-logs.js +234 -0
  74. package/skills/update-changelog/SKILL.md +135 -0
  75. package/skills/web-design/SKILL.md +117 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gonçalo Silva
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # tau-coding-agent
2
+
3
+ Coding-focused Tau package for [Pi](https://pi.dev).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pi install npm:tau-coding-agent
9
+ ```
10
+
11
+ ## Includes
12
+
13
+ Extensions:
14
+
15
+ - `answer`
16
+ - `branch-term`
17
+ - `btw`
18
+ - `ghostty`
19
+ - `git-diff-stats`
20
+ - `git-pr-status`
21
+ - `insights`
22
+ - `interlude`
23
+ - `loop`
24
+ - `memory`
25
+ - `notify`
26
+ - `openai-fast`
27
+ - `openai-verbosity`
28
+ - `review`
29
+ - `sandbox`
30
+ - `usage`
31
+ - `websearch`
32
+ - `worktree`
33
+
34
+ Skills:
35
+
36
+ - `browser-tools`
37
+ - `git-clean-history`
38
+ - `git-commit`
39
+ - `oracle`
40
+ - `sentry`
41
+ - `update-changelog`
42
+ - `web-design`
@@ -0,0 +1,601 @@
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
+ const SYSTEM_PROMPT = `You extract items that need user input from assistant text:
29
+
30
+ - Direct questions
31
+ - Choices between alternatives (even if not phrased as a question)
32
+ - Other pending decisions that still require user input
33
+
34
+ When a decision is implicit, rewrite it as a clear question.
35
+
36
+ Output a JSON object with this structure:
37
+ {
38
+ "questions": [
39
+ {
40
+ "question": "Clear question requiring user input",
41
+ "context": "Optional concise context (options, tradeoffs, constraints)"
42
+ }
43
+ ]
44
+ }
45
+
46
+ Rules:
47
+ - Extract all pending decisions (questions, choices, etc)
48
+ - Keep them in the order they appear
49
+ - Be concise and specific in question text
50
+ - Add context only when it is essential for the user to answer
51
+ - If nothing requires input, return {"questions": []}
52
+
53
+ Example input: "We can use PostgreSQL (stronger relational features) or SQLite (simpler local setup). Both are viable."
54
+ Example output:
55
+ {
56
+ "questions": [
57
+ {
58
+ "question": "PostgreSQL or SQLite?",
59
+ "context": "PostgreSQL has stronger relational features; SQLite offers a simpler local setup."
60
+ }
61
+ ]
62
+ }
63
+
64
+ Example input: "I can split this into two commits or keep it in one commit. Either is fine."
65
+ Example output:
66
+ {
67
+ "questions": [
68
+ {
69
+ "question": "Split into two commits or keep as one?"
70
+ }
71
+ ]
72
+ }
73
+
74
+ Example input: "I already started implementing Option A."
75
+ Example output:
76
+ {
77
+ "questions": []
78
+ }`;
79
+
80
+ const OPENAI_FAST_MODEL_ID = "gpt-5.3-codex-spark";
81
+ const ANTHROPIC_FAST_MODEL_ID = "claude-haiku-4-5";
82
+
83
+ // Structured output format for question extraction
84
+ interface ExtractedQuestion {
85
+ question: string;
86
+ context?: string;
87
+ }
88
+
89
+ interface ExtractionResult {
90
+ questions: ExtractedQuestion[];
91
+ }
92
+
93
+ interface ModelRequestAuth {
94
+ model: Model<Api>;
95
+ apiKey?: string;
96
+ headers?: Record<string, string>;
97
+ }
98
+
99
+ type ModelAuthLookup = {
100
+ find: (provider: string, modelId: string) => Model<Api> | undefined;
101
+ getApiKeyAndHeaders: (
102
+ model: Model<Api>,
103
+ ) => Promise<
104
+ { ok: true; apiKey?: string; headers?: Record<string, string> } | { ok: false; error: string }
105
+ >;
106
+ };
107
+
108
+ type ModelFamily = "openai" | "anthropic";
109
+
110
+ function detectModelFamily(provider: string): ModelFamily | null {
111
+ const normalizedProvider = provider.toLowerCase();
112
+ if (normalizedProvider.includes("openai")) return "openai";
113
+ if (normalizedProvider.includes("anthropic")) return "anthropic";
114
+ return null;
115
+ }
116
+
117
+ /**
118
+ * Prefer a fast model from the current model family when available.
119
+ */
120
+ async function selectExtractionModel(
121
+ currentModel: Model<Api>,
122
+ modelRegistry: ModelAuthLookup,
123
+ ): Promise<ModelRequestAuth | null> {
124
+ const family = detectModelFamily(currentModel.provider);
125
+ if (!family) return resolveModelRequestAuth(modelRegistry, currentModel);
126
+
127
+ const modelId = family === "openai" ? OPENAI_FAST_MODEL_ID : ANTHROPIC_FAST_MODEL_ID;
128
+ const providerCandidates =
129
+ family === "openai"
130
+ ? [currentModel.provider, "openai-codex", "openai"]
131
+ : [currentModel.provider, "anthropic"];
132
+
133
+ for (const provider of new Set(providerCandidates)) {
134
+ const model = modelRegistry.find(provider, modelId);
135
+ if (!model) continue;
136
+
137
+ const auth = await resolveModelRequestAuth(modelRegistry, model);
138
+ if (auth) {
139
+ return auth;
140
+ }
141
+ }
142
+
143
+ return resolveModelRequestAuth(modelRegistry, currentModel);
144
+ }
145
+
146
+ async function resolveModelRequestAuth(
147
+ modelRegistry: ModelAuthLookup,
148
+ model: Model<Api>,
149
+ ): Promise<ModelRequestAuth | null> {
150
+ const auth = await modelRegistry.getApiKeyAndHeaders(model);
151
+ return auth.ok ? { model, apiKey: auth.apiKey, headers: auth.headers } : null;
152
+ }
153
+
154
+ /**
155
+ * Parse the JSON response from the LLM
156
+ */
157
+ function parseExtractionResult(text: string): ExtractionResult | null {
158
+ try {
159
+ // Try to find JSON in the response (it might be wrapped in markdown code blocks)
160
+ let jsonStr = text;
161
+
162
+ // Remove markdown code block if present
163
+ const jsonMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/);
164
+ if (jsonMatch) {
165
+ jsonStr = jsonMatch[1].trim();
166
+ }
167
+
168
+ const parsed = JSON.parse(jsonStr);
169
+ if (parsed && Array.isArray(parsed.questions)) {
170
+ return parsed as ExtractionResult;
171
+ }
172
+ return null;
173
+ } catch {
174
+ return null;
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Interactive Q&A component for answering extracted questions
180
+ */
181
+ class QnAComponent implements Component {
182
+ private questions: ExtractedQuestion[];
183
+ private answers: string[];
184
+ private currentIndex: number = 0;
185
+ private editor: Editor;
186
+ private tui: TUI;
187
+ private onDone: (result: string | null) => void;
188
+ private showingConfirmation: boolean = false;
189
+
190
+ // Cache
191
+ private cachedWidth?: number;
192
+ private cachedLines?: string[];
193
+
194
+ // Colors - using proper reset sequences
195
+ private dim = (s: string) => `\x1b[2m${s}\x1b[0m`;
196
+ private bold = (s: string) => `\x1b[1m${s}\x1b[0m`;
197
+ private cyan = (s: string) => `\x1b[36m${s}\x1b[0m`;
198
+ private green = (s: string) => `\x1b[32m${s}\x1b[0m`;
199
+ private yellow = (s: string) => `\x1b[33m${s}\x1b[0m`;
200
+ private gray = (s: string) => `\x1b[90m${s}\x1b[0m`;
201
+
202
+ constructor(questions: ExtractedQuestion[], tui: TUI, onDone: (result: string | null) => void) {
203
+ this.questions = questions;
204
+ this.answers = questions.map(() => "");
205
+ this.tui = tui;
206
+ this.onDone = onDone;
207
+
208
+ // Create a minimal theme for the editor
209
+ const selectedLine = (s: string) => `\x1b[44m${s}\x1b[0m`;
210
+ const editorTheme: EditorTheme = {
211
+ borderColor: this.dim,
212
+ selectList: {
213
+ selectedPrefix: selectedLine,
214
+ selectedText: selectedLine,
215
+ description: this.gray,
216
+ scrollInfo: this.gray,
217
+ noMatch: this.gray,
218
+ },
219
+ };
220
+
221
+ this.editor = new Editor(tui, editorTheme);
222
+ // Disable the editor's built-in submit (which clears the editor)
223
+ // We'll handle Enter ourselves to preserve the text
224
+ this.editor.disableSubmit = true;
225
+ this.editor.onChange = () => {
226
+ this.invalidate();
227
+ this.tui.requestRender();
228
+ };
229
+ }
230
+
231
+ private allQuestionsAnswered(): boolean {
232
+ this.saveCurrentAnswer();
233
+ return this.answers.every((a) => (a?.trim() || "").length > 0);
234
+ }
235
+
236
+ private saveCurrentAnswer(): void {
237
+ this.answers[this.currentIndex] = this.editor.getText();
238
+ }
239
+
240
+ private navigateTo(index: number): void {
241
+ if (index < 0 || index >= this.questions.length) return;
242
+ this.saveCurrentAnswer();
243
+ this.currentIndex = index;
244
+ this.editor.setText(this.answers[index] || "");
245
+ this.invalidate();
246
+ }
247
+
248
+ private submit(): void {
249
+ this.saveCurrentAnswer();
250
+
251
+ // Build the response text
252
+ const parts: string[] = [];
253
+ for (let i = 0; i < this.questions.length; i++) {
254
+ const q = this.questions[i];
255
+ const a = this.answers[i]?.trim() || "(no answer)";
256
+ parts.push(`Q: ${q.question}`);
257
+ if (q.context) {
258
+ for (const line of q.context.split("\n")) {
259
+ parts.push(`> ${line}`);
260
+ }
261
+ parts.push("");
262
+ }
263
+ parts.push(`A: ${a}`);
264
+ parts.push("");
265
+ }
266
+
267
+ this.onDone(parts.join("\n").trim());
268
+ }
269
+
270
+ private cancel(): void {
271
+ this.onDone(null);
272
+ }
273
+
274
+ invalidate(): void {
275
+ this.cachedWidth = undefined;
276
+ this.cachedLines = undefined;
277
+ }
278
+
279
+ handleInput(data: string): void {
280
+ // Handle confirmation dialog
281
+ if (this.showingConfirmation) {
282
+ if (matchesKey(data, Key.enter) || data.toLowerCase() === "y") {
283
+ this.submit();
284
+ return;
285
+ }
286
+ if (
287
+ matchesKey(data, Key.escape) ||
288
+ matchesKey(data, Key.ctrl("c")) ||
289
+ data.toLowerCase() === "n"
290
+ ) {
291
+ this.showingConfirmation = false;
292
+ this.invalidate();
293
+ this.tui.requestRender();
294
+ return;
295
+ }
296
+ return;
297
+ }
298
+
299
+ // Global navigation and commands
300
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
301
+ this.cancel();
302
+ return;
303
+ }
304
+
305
+ // Tab / Shift+Tab for navigation
306
+ if (matchesKey(data, Key.tab)) {
307
+ if (this.currentIndex < this.questions.length - 1) {
308
+ this.navigateTo(this.currentIndex + 1);
309
+ this.tui.requestRender();
310
+ }
311
+ return;
312
+ }
313
+ if (matchesKey(data, Key.shift("tab"))) {
314
+ if (this.currentIndex > 0) {
315
+ this.navigateTo(this.currentIndex - 1);
316
+ this.tui.requestRender();
317
+ }
318
+ return;
319
+ }
320
+
321
+ // Arrow up/down for question navigation when editor is empty
322
+ // (Editor handles its own cursor navigation when there's content)
323
+ if (matchesKey(data, Key.up) && this.editor.getText() === "") {
324
+ if (this.currentIndex > 0) {
325
+ this.navigateTo(this.currentIndex - 1);
326
+ this.tui.requestRender();
327
+ return;
328
+ }
329
+ }
330
+ if (matchesKey(data, Key.down) && this.editor.getText() === "") {
331
+ if (this.currentIndex < this.questions.length - 1) {
332
+ this.navigateTo(this.currentIndex + 1);
333
+ this.tui.requestRender();
334
+ return;
335
+ }
336
+ }
337
+
338
+ // Handle Enter ourselves (editor's submit is disabled)
339
+ // Plain Enter moves to next question or shows confirmation on last question
340
+ // Shift+Enter adds a newline (handled by editor)
341
+ if (matchesKey(data, Key.enter) && !matchesKey(data, Key.shift("enter"))) {
342
+ this.saveCurrentAnswer();
343
+ if (this.currentIndex < this.questions.length - 1) {
344
+ this.navigateTo(this.currentIndex + 1);
345
+ } else {
346
+ // On last question - show confirmation
347
+ this.showingConfirmation = true;
348
+ }
349
+ this.invalidate();
350
+ this.tui.requestRender();
351
+ return;
352
+ }
353
+
354
+ // Pass to editor
355
+ this.editor.handleInput(data);
356
+ this.invalidate();
357
+ this.tui.requestRender();
358
+ }
359
+
360
+ render(width: number): string[] {
361
+ if (this.cachedLines && this.cachedWidth === width) {
362
+ return this.cachedLines;
363
+ }
364
+
365
+ const lines: string[] = [];
366
+ const boxWidth = Math.min(width - 4, 120); // Allow wider box
367
+ const contentWidth = boxWidth - 4; // 2 chars padding on each side
368
+
369
+ // Helper to create horizontal lines (dim the whole thing at once)
370
+ const horizontalLine = (count: number) => "─".repeat(count);
371
+
372
+ // Helper to create a box line
373
+ const boxLine = (content: string, leftPad: number = 2): string => {
374
+ const paddedContent = " ".repeat(leftPad) + content;
375
+ const contentLen = visibleWidth(paddedContent);
376
+ const rightPad = Math.max(0, boxWidth - contentLen - 2);
377
+ return this.dim("│") + paddedContent + " ".repeat(rightPad) + this.dim("│");
378
+ };
379
+
380
+ const emptyBoxLine = (): string => {
381
+ return this.dim("│") + " ".repeat(boxWidth - 2) + this.dim("│");
382
+ };
383
+
384
+ const padToWidth = (line: string): string => {
385
+ const len = visibleWidth(line);
386
+ return line + " ".repeat(Math.max(0, width - len));
387
+ };
388
+
389
+ // Title
390
+ lines.push(padToWidth(this.dim("╭" + horizontalLine(boxWidth - 2) + "╮")));
391
+ const title = `${this.bold(this.cyan("Questions"))} ${this.dim(`(${this.currentIndex + 1}/${this.questions.length})`)}`;
392
+ lines.push(padToWidth(boxLine(title)));
393
+ lines.push(padToWidth(this.dim("├" + horizontalLine(boxWidth - 2) + "┤")));
394
+
395
+ // Progress indicator
396
+ const progressParts: string[] = [];
397
+ for (let i = 0; i < this.questions.length; i++) {
398
+ const answered = (this.answers[i]?.trim() || "").length > 0;
399
+ const current = i === this.currentIndex;
400
+ if (current) {
401
+ progressParts.push(this.cyan("●"));
402
+ } else if (answered) {
403
+ progressParts.push(this.green("●"));
404
+ } else {
405
+ progressParts.push(this.dim("○"));
406
+ }
407
+ }
408
+ lines.push(padToWidth(boxLine(progressParts.join(" "))));
409
+ lines.push(padToWidth(emptyBoxLine()));
410
+
411
+ // Current question
412
+ const q = this.questions[this.currentIndex];
413
+ const questionText = `> ${q.question}`;
414
+ const wrappedQuestion = wrapTextWithAnsi(questionText, contentWidth);
415
+ for (const line of wrappedQuestion) {
416
+ lines.push(padToWidth(boxLine(line)));
417
+ }
418
+
419
+ // Context if present
420
+ if (q.context) {
421
+ lines.push(padToWidth(emptyBoxLine()));
422
+ const contextText = this.gray(`${q.context}`);
423
+ const wrappedContext = wrapTextWithAnsi(contextText, contentWidth - 2);
424
+ for (const line of wrappedContext) {
425
+ lines.push(padToWidth(boxLine(line)));
426
+ }
427
+ }
428
+
429
+ lines.push(padToWidth(emptyBoxLine()));
430
+
431
+ // Render the editor component (multi-line input) with padding
432
+ // Skip the first and last lines (editor's own border lines)
433
+ const answerPrefix = this.bold("A: ");
434
+ const editorWidth = contentWidth - 4 - 3; // Extra padding + space for "A: "
435
+ const editorLines = this.editor.render(editorWidth);
436
+ for (let i = 1; i < editorLines.length - 1; i++) {
437
+ if (i === 1) {
438
+ // First content line gets the "A: " prefix
439
+ lines.push(padToWidth(boxLine(answerPrefix + editorLines[i])));
440
+ } else {
441
+ // Subsequent lines get padding to align with the first line
442
+ lines.push(padToWidth(boxLine(" " + editorLines[i])));
443
+ }
444
+ }
445
+
446
+ lines.push(padToWidth(emptyBoxLine()));
447
+
448
+ // Confirmation dialog or footer with controls
449
+ if (this.showingConfirmation) {
450
+ lines.push(padToWidth(this.dim("├" + horizontalLine(boxWidth - 2) + "┤")));
451
+ const confirmMsg = `${this.yellow("Submit all answers?")} ${this.dim("(Enter/y to confirm, Esc/n to cancel)")}`;
452
+ lines.push(padToWidth(boxLine(truncateToWidth(confirmMsg, contentWidth))));
453
+ } else {
454
+ lines.push(padToWidth(this.dim("├" + horizontalLine(boxWidth - 2) + "┤")));
455
+ const controls = `${this.dim("Tab/Enter")} next · ${this.dim("Shift+Tab")} prev · ${this.dim("Shift+Enter")} newline · ${this.dim("Esc")} cancel`;
456
+ lines.push(padToWidth(boxLine(truncateToWidth(controls, contentWidth))));
457
+ }
458
+ lines.push(padToWidth(this.dim("╰" + horizontalLine(boxWidth - 2) + "╯")));
459
+
460
+ this.cachedWidth = width;
461
+ this.cachedLines = lines;
462
+ return lines;
463
+ }
464
+ }
465
+
466
+ export default function (pi: ExtensionAPI) {
467
+ const answerHandler = async (ctx: ExtensionContext) => {
468
+ if (!ctx.hasUI) {
469
+ ctx.ui.notify("answer requires interactive mode", "error");
470
+ return;
471
+ }
472
+
473
+ if (!ctx.model) {
474
+ ctx.ui.notify("No model selected", "error");
475
+ return;
476
+ }
477
+
478
+ // Find the last assistant message on the current branch
479
+ const branch = ctx.sessionManager.getBranch();
480
+ let lastAssistantText: string | undefined;
481
+
482
+ for (let i = branch.length - 1; i >= 0; i--) {
483
+ const entry = branch[i];
484
+ if (entry.type === "message") {
485
+ const msg = entry.message;
486
+ if ("role" in msg && msg.role === "assistant") {
487
+ if (msg.stopReason !== "stop") {
488
+ ctx.ui.notify(`Last assistant message incomplete (${msg.stopReason})`, "error");
489
+ return;
490
+ }
491
+ const textParts = msg.content
492
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
493
+ .map((c) => c.text);
494
+ if (textParts.length > 0) {
495
+ lastAssistantText = textParts.join("\n");
496
+ break;
497
+ }
498
+ }
499
+ }
500
+ }
501
+
502
+ if (!lastAssistantText) {
503
+ ctx.ui.notify("No assistant messages found", "error");
504
+ return;
505
+ }
506
+
507
+ // Select the best model for extraction (prefer a fast model in the current family).
508
+ const extractionSelection = await selectExtractionModel(ctx.model, ctx.modelRegistry);
509
+ if (!extractionSelection) {
510
+ ctx.ui.notify("No configured Pi model is available for question extraction", "error");
511
+ return;
512
+ }
513
+
514
+ // Run extraction with loader UI
515
+ const extractionResult = await ctx.ui.custom<ExtractionResult | null>(
516
+ (tui, theme, _kb, done) => {
517
+ const loader = new BorderedLoader(
518
+ tui,
519
+ theme,
520
+ `Extracting questions using ${extractionSelection.model.id}...`,
521
+ );
522
+ loader.onAbort = () => done(null);
523
+
524
+ const doExtract = async () => {
525
+ const userMessage: UserMessage = {
526
+ role: "user",
527
+ content: [{ type: "text", text: lastAssistantText! }],
528
+ timestamp: Date.now(),
529
+ };
530
+
531
+ const response = await complete(
532
+ extractionSelection.model,
533
+ { systemPrompt: SYSTEM_PROMPT, messages: [userMessage] },
534
+ {
535
+ apiKey: extractionSelection.apiKey,
536
+ headers: extractionSelection.headers,
537
+ signal: loader.signal,
538
+ },
539
+ );
540
+
541
+ if (response.stopReason === "aborted") {
542
+ return null;
543
+ }
544
+
545
+ const responseText = response.content
546
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
547
+ .map((c) => c.text)
548
+ .join("\n");
549
+
550
+ return parseExtractionResult(responseText);
551
+ };
552
+
553
+ doExtract()
554
+ .then(done)
555
+ .catch(() => done(null));
556
+
557
+ return loader;
558
+ },
559
+ );
560
+
561
+ if (extractionResult === null) {
562
+ ctx.ui.notify("Cancelled", "info");
563
+ return;
564
+ }
565
+
566
+ if (extractionResult.questions.length === 0) {
567
+ ctx.ui.notify("No questions found in the last message", "info");
568
+ return;
569
+ }
570
+
571
+ // Show the Q&A component
572
+ const answersResult = await ctx.ui.custom<string | null>((tui, _theme, _kb, done) => {
573
+ return new QnAComponent(extractionResult.questions, tui, done);
574
+ });
575
+
576
+ if (answersResult === null) {
577
+ ctx.ui.notify("Cancelled", "info");
578
+ return;
579
+ }
580
+
581
+ // Send the answers directly as a message and trigger a turn
582
+ pi.sendMessage(
583
+ {
584
+ customType: "answers",
585
+ content: "Here are my answers to your questions:\n\n" + answersResult,
586
+ display: true,
587
+ },
588
+ { triggerTurn: true },
589
+ );
590
+ };
591
+
592
+ pi.registerCommand("answer", {
593
+ description: "Extract questions from last assistant message into interactive Q&A",
594
+ handler: (_args, ctx) => answerHandler(ctx),
595
+ });
596
+
597
+ pi.registerShortcut("ctrl+.", {
598
+ description: "Extract and answer questions",
599
+ handler: answerHandler,
600
+ });
601
+ }