@fractaal/pi-goal-x 0.19.1 → 0.20.1

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 (57) hide show
  1. package/dist/goal-auditor.d.ts +72 -0
  2. package/dist/goal-auditor.js +359 -0
  3. package/dist/goal-auditor.js.map +1 -0
  4. package/dist/goal-compaction.d.ts +10 -0
  5. package/dist/goal-compaction.js +104 -0
  6. package/dist/goal-compaction.js.map +1 -0
  7. package/dist/goal-core.d.ts +19 -0
  8. package/dist/goal-core.js +66 -0
  9. package/dist/goal-core.js.map +1 -0
  10. package/dist/goal-draft.d.ts +71 -0
  11. package/dist/goal-draft.js +201 -0
  12. package/dist/goal-draft.js.map +1 -0
  13. package/dist/goal-ledger.d.ts +139 -0
  14. package/dist/goal-ledger.js +306 -0
  15. package/dist/goal-ledger.js.map +1 -0
  16. package/dist/goal-policy.d.ts +127 -0
  17. package/dist/goal-policy.js +359 -0
  18. package/dist/goal-policy.js.map +1 -0
  19. package/dist/goal-pool.d.ts +17 -0
  20. package/dist/goal-pool.js +85 -0
  21. package/dist/goal-pool.js.map +1 -0
  22. package/dist/goal-questionnaire.d.ts +56 -0
  23. package/dist/goal-questionnaire.js +733 -0
  24. package/dist/goal-questionnaire.js.map +1 -0
  25. package/dist/goal-record.d.ts +94 -0
  26. package/dist/goal-record.js +155 -0
  27. package/dist/goal-record.js.map +1 -0
  28. package/dist/goal-settings.d.ts +56 -0
  29. package/dist/goal-settings.js +184 -0
  30. package/dist/goal-settings.js.map +1 -0
  31. package/dist/goal-tool-names.d.ts +20 -0
  32. package/dist/goal-tool-names.js +69 -0
  33. package/dist/goal-tool-names.js.map +1 -0
  34. package/dist/goal.d.ts +49 -0
  35. package/dist/goal.js +3720 -0
  36. package/dist/goal.js.map +1 -0
  37. package/dist/prompts/goal-prompts.d.ts +17 -0
  38. package/dist/prompts/goal-prompts.js +304 -0
  39. package/dist/prompts/goal-prompts.js.map +1 -0
  40. package/dist/storage/goal-files.d.ts +40 -0
  41. package/dist/storage/goal-files.js +320 -0
  42. package/dist/storage/goal-files.js.map +1 -0
  43. package/dist/widgets/goal-escape-dialog.d.ts +15 -0
  44. package/dist/widgets/goal-escape-dialog.js +118 -0
  45. package/dist/widgets/goal-escape-dialog.js.map +1 -0
  46. package/dist/widgets/goal-notifications.d.ts +5 -0
  47. package/dist/widgets/goal-notifications.js +9 -0
  48. package/dist/widgets/goal-notifications.js.map +1 -0
  49. package/dist/widgets/goal-widget.d.ts +58 -0
  50. package/dist/widgets/goal-widget.js +282 -0
  51. package/dist/widgets/goal-widget.js.map +1 -0
  52. package/dist/widgets/task-list-overlay.d.ts +8 -0
  53. package/dist/widgets/task-list-overlay.js +321 -0
  54. package/dist/widgets/task-list-overlay.js.map +1 -0
  55. package/extensions/goal-questionnaire.ts +37 -30
  56. package/extensions/goal.ts +5 -1
  57. package/package.json +15 -4
@@ -0,0 +1,733 @@
1
+ import { Type } from "@earendil-works/pi-ai";
2
+ import { defineTool } from "@earendil-works/pi-coding-agent";
3
+ import { Editor, Key, matchesKey, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
4
+ import { truncateText } from "./goal-core.js";
5
+ import { QUESTIONNAIRE_TOOL_NAME, QUESTION_TOOL_NAME } from "./goal-tool-names.js";
6
+ const CONFIRM_CONTEXT_SCROLL_STEP = 12;
7
+ export function normalizeQuestionnaireQuestions(rawQuestions) {
8
+ const seenIds = new Set();
9
+ return rawQuestions.map((q, i) => {
10
+ let id = q.id.trim() || `q${i + 1}`;
11
+ if (seenIds.has(id))
12
+ id = `${id}-${i + 1}`;
13
+ seenIds.add(id);
14
+ const options = q.options.filter((option) => option.trim().length > 0);
15
+ const recommended = q.recommended !== undefined && q.recommended >= 0 && q.recommended < options.length
16
+ ? q.recommended
17
+ : undefined;
18
+ return { ...q, id, options, recommended, allowCustom: q.allowCustom ?? true };
19
+ });
20
+ }
21
+ export function formatQuestionnaireAnswers(result) {
22
+ return result.answers.map((answer) => {
23
+ const question = result.questions.find((q) => q.id === answer.id);
24
+ const lines = [`**Q:** ${answer.question}`];
25
+ if (question?.context)
26
+ lines.push(`\n${question.context}`);
27
+ if (question && question.options.length > 0)
28
+ lines.push(`\nOptions: ${question.options.join(" / ")}`);
29
+ lines.push(`\n**A:** ${answer.answer}`);
30
+ return lines.join("");
31
+ }).join("\n\n---\n\n");
32
+ }
33
+ export function hasGoalQuestionnaireUi(ctx) {
34
+ return ctx.hasUI || typeof ctx.ui?.custom === "function";
35
+ }
36
+ export function shouldAutoConfirmProposal(args) {
37
+ if (args.autoConfirmEnv === "0")
38
+ return false; // explicit opt-out (benchmarking)
39
+ return !args.hasUI || args.autoConfirmEnv === "1";
40
+ }
41
+ export function proposalDecisionFromQuestionnaireResult(args) {
42
+ if (args.cancelled)
43
+ return "continue";
44
+ return (args.answer ?? "").startsWith("Confirm") ? "confirm" : "continue";
45
+ }
46
+ export function isHeadlessQuestionSufficientForDraft(args) {
47
+ const topic = args.topic.toLowerCase();
48
+ void args;
49
+ const vagueTopic = topic.trim().length < 20 || /(整理笔记|organize notes|notes|笔记)$/.test(topic.trim());
50
+ return !vagueTopic;
51
+ }
52
+ export function proposalDialogFailureMessage(error) {
53
+ const detail = error instanceof Error ? error.message : String(error);
54
+ return `Goal draft confirmation failed: ${detail}. The goal was NOT created; drafting remains active.`;
55
+ }
56
+ /**
57
+ * Shared question UI used by both the agent-callable goal_questionnaire tool and
58
+ * the internal draft-confirm prompt. This keeps pi-goal self-contained and
59
+ * avoids depending on external question/questionnaire packages.
60
+ */
61
+ export async function runGoalQuestionnaire(ctx, rawQuestions, auditorToggleInit) {
62
+ if (!hasGoalQuestionnaireUi(ctx)) {
63
+ return { questions: [], answers: [], cancelled: true };
64
+ }
65
+ const questions = normalizeQuestionnaireQuestions(rawQuestions);
66
+ const isMulti = questions.length > 1;
67
+ const totalTabs = questions.length + 1;
68
+ return await ctx.ui.custom((tui, theme, _kb, done) => {
69
+ // Suppress hardware cursor during dialog to reduce TUI auto-scroll
70
+ // (the TUI render loop runs at ~60fps and writes ANSI cursor positioning
71
+ // sequences every cycle, which can cause terminal viewport snapping).
72
+ const wasHardwareCursorShown = tui.getShowHardwareCursor();
73
+ tui.setShowHardwareCursor(false);
74
+ let currentTab = 0;
75
+ let optionIndex = 0;
76
+ let inputMode = false;
77
+ let inputQuestionId = null;
78
+ let cachedLines;
79
+ let cachedWidth;
80
+ let cachedTerminalRows;
81
+ let contextScroll = 0;
82
+ let auditorEnabled = auditorToggleInit?.defaultEnabled ?? true;
83
+ const answers = new Map();
84
+ const drafts = new Map();
85
+ const editorTheme = {
86
+ borderColor: (s) => theme.fg("accent", s),
87
+ selectList: {
88
+ selectedPrefix: (t) => theme.fg("accent", t),
89
+ selectedText: (t) => theme.fg("accent", t),
90
+ description: (t) => theme.fg("muted", t),
91
+ scrollInfo: (t) => theme.fg("dim", t),
92
+ noMatch: (t) => theme.fg("warning", t),
93
+ },
94
+ };
95
+ const editor = new Editor(tui, editorTheme);
96
+ function refresh() {
97
+ cachedLines = undefined;
98
+ cachedWidth = undefined;
99
+ cachedTerminalRows = undefined;
100
+ tui.requestRender();
101
+ }
102
+ function submit(cancelled) {
103
+ // Restore hardware cursor now that the dialog is closing
104
+ tui.setShowHardwareCursor(wasHardwareCursorShown);
105
+ const ordered = questions.map((q) => answers.get(q.id)).filter((a) => !!a);
106
+ done({ questions, answers: ordered, cancelled, auditorEnabled: auditorToggleInit ? auditorEnabled : undefined });
107
+ }
108
+ function currentQuestion() {
109
+ return questions[currentTab];
110
+ }
111
+ function displayOptions() {
112
+ const q = currentQuestion();
113
+ if (!q)
114
+ return [];
115
+ const opts = q.options.map((label) => ({ label }));
116
+ if (q.allowCustom !== false)
117
+ opts.push({ label: "Write your own answer...", isCustom: true });
118
+ return opts;
119
+ }
120
+ function allAnswered() {
121
+ return questions.every((q) => answers.has(q.id));
122
+ }
123
+ function enterQuestion(q) {
124
+ contextScroll = 0;
125
+ const existing = answers.get(q.id);
126
+ const draft = drafts.get(q.id);
127
+ if (q.options.length === 0) {
128
+ inputMode = true;
129
+ inputQuestionId = q.id;
130
+ editor.setText(draft ?? (existing?.wasCustom ? existing.answer : ""));
131
+ }
132
+ else if (existing?.wasCustom) {
133
+ optionIndex = q.options.length;
134
+ }
135
+ else if (existing && !existing.wasCustom) {
136
+ const idx = q.options.indexOf(existing.answer);
137
+ optionIndex = idx >= 0 ? idx : 0;
138
+ }
139
+ else {
140
+ optionIndex = q.recommended ?? 0;
141
+ }
142
+ }
143
+ function advanceAfterAnswer() {
144
+ if (!isMulti) {
145
+ submit(false);
146
+ return;
147
+ }
148
+ if (currentTab < questions.length - 1)
149
+ currentTab++;
150
+ else
151
+ currentTab = questions.length;
152
+ const nextQ = currentQuestion();
153
+ if (nextQ)
154
+ enterQuestion(nextQ);
155
+ else
156
+ optionIndex = 0;
157
+ refresh();
158
+ }
159
+ function saveAnswer(qId, value, wasCustom) {
160
+ const q = questions.find((qq) => qq.id === qId);
161
+ answers.set(qId, { id: qId, question: q?.question ?? qId, answer: value, wasCustom });
162
+ }
163
+ editor.onSubmit = (value) => {
164
+ if (!inputQuestionId)
165
+ return;
166
+ const trimmed = value.trim();
167
+ if (!trimmed) {
168
+ refresh();
169
+ return;
170
+ }
171
+ drafts.delete(inputQuestionId);
172
+ saveAnswer(inputQuestionId, trimmed, true);
173
+ inputMode = false;
174
+ inputQuestionId = null;
175
+ editor.setText("");
176
+ advanceAfterAnswer();
177
+ };
178
+ function exitEditor() {
179
+ if (inputQuestionId) {
180
+ const text = editor.getText();
181
+ if (text.trim())
182
+ drafts.set(inputQuestionId, text);
183
+ else
184
+ drafts.delete(inputQuestionId);
185
+ }
186
+ inputMode = false;
187
+ inputQuestionId = null;
188
+ editor.setText("");
189
+ }
190
+ enterQuestion(questions[0]);
191
+ function scrollContextIfRequested(data, q) {
192
+ if (!q?.context)
193
+ return false;
194
+ if (matchesKey(data, Key.pageUp)) {
195
+ contextScroll = Math.max(0, contextScroll - CONFIRM_CONTEXT_SCROLL_STEP);
196
+ refresh();
197
+ return true;
198
+ }
199
+ if (matchesKey(data, Key.pageDown)) {
200
+ contextScroll += CONFIRM_CONTEXT_SCROLL_STEP;
201
+ refresh();
202
+ return true;
203
+ }
204
+ if (matchesKey(data, Key.home)) {
205
+ contextScroll = 0;
206
+ refresh();
207
+ return true;
208
+ }
209
+ if (matchesKey(data, Key.end)) {
210
+ contextScroll = Number.MAX_SAFE_INTEGER;
211
+ refresh();
212
+ return true;
213
+ }
214
+ return false;
215
+ }
216
+ function handleInput(data) {
217
+ const q = currentQuestion();
218
+ if (inputMode) {
219
+ if (scrollContextIfRequested(data, q))
220
+ return;
221
+ if (matchesKey(data, Key.escape)) {
222
+ if (q && q.options.length === 0 && !isMulti)
223
+ submit(true);
224
+ else {
225
+ exitEditor();
226
+ refresh();
227
+ }
228
+ return;
229
+ }
230
+ if (isMulti && (matchesKey(data, Key.tab) || matchesKey(data, Key.shift("tab")))) {
231
+ exitEditor();
232
+ currentTab = matchesKey(data, Key.tab) ? (currentTab + 1) % totalTabs : (currentTab - 1 + totalTabs) % totalTabs;
233
+ const nextQ = currentQuestion();
234
+ if (nextQ)
235
+ enterQuestion(nextQ);
236
+ else
237
+ optionIndex = 0;
238
+ refresh();
239
+ return;
240
+ }
241
+ editor.handleInput(data);
242
+ refresh();
243
+ return;
244
+ }
245
+ const opts = displayOptions();
246
+ if (scrollContextIfRequested(data, q))
247
+ return;
248
+ if (isMulti) {
249
+ if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) {
250
+ currentTab = (currentTab + 1) % totalTabs;
251
+ const nextQ = currentQuestion();
252
+ if (nextQ)
253
+ enterQuestion(nextQ);
254
+ else
255
+ optionIndex = 0;
256
+ refresh();
257
+ return;
258
+ }
259
+ if (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left)) {
260
+ currentTab = (currentTab - 1 + totalTabs) % totalTabs;
261
+ const nextQ = currentQuestion();
262
+ if (nextQ)
263
+ enterQuestion(nextQ);
264
+ else
265
+ optionIndex = 0;
266
+ refresh();
267
+ return;
268
+ }
269
+ }
270
+ if (currentTab === questions.length) {
271
+ if (matchesKey(data, Key.enter) && allAnswered())
272
+ submit(false);
273
+ else if (matchesKey(data, Key.escape))
274
+ submit(true);
275
+ return;
276
+ }
277
+ if (matchesKey(data, Key.up)) {
278
+ optionIndex = Math.max(0, optionIndex - 1);
279
+ refresh();
280
+ return;
281
+ }
282
+ if (matchesKey(data, Key.down)) {
283
+ optionIndex = Math.min(opts.length - 1, optionIndex + 1);
284
+ refresh();
285
+ return;
286
+ }
287
+ // Auditor toggle hotkey
288
+ if (matchesKey(data, "a") && auditorToggleInit) {
289
+ auditorEnabled = !auditorEnabled;
290
+ refresh();
291
+ return;
292
+ }
293
+ if (matchesKey(data, Key.enter) && q) {
294
+ if (q.options.length === 0 || opts[optionIndex]?.isCustom) {
295
+ inputMode = true;
296
+ inputQuestionId = q.id;
297
+ const draft = drafts.get(q.id);
298
+ const existing = answers.get(q.id);
299
+ editor.setText(draft ?? (existing?.wasCustom ? existing.answer : ""));
300
+ refresh();
301
+ return;
302
+ }
303
+ const opt = opts[optionIndex];
304
+ if (opt) {
305
+ saveAnswer(q.id, opt.label, false);
306
+ advanceAfterAnswer();
307
+ }
308
+ return;
309
+ }
310
+ if (matchesKey(data, Key.escape))
311
+ submit(true);
312
+ }
313
+ function render(width) {
314
+ const terminalRows = Number.isFinite(tui.terminal?.rows) ? tui.terminal.rows : 40;
315
+ if (cachedLines && cachedWidth === width && cachedTerminalRows === terminalRows)
316
+ return cachedLines;
317
+ const safeWidth = Math.max(20, width);
318
+ const lines = [];
319
+ const q = currentQuestion();
320
+ const opts = displayOptions();
321
+ const overlayRows = Math.max(1, terminalRows);
322
+ const add = (s) => lines.push(truncateToWidth(s, safeWidth, "…", true));
323
+ const wrappedLineCount = (s) => wrapTextWithAnsi(s, safeWidth).length;
324
+ const optionLineCount = () => opts.reduce((sum, opt, i) => {
325
+ const recTag = !opt.isCustom && q?.recommended === i ? " ★" : "";
326
+ const prefix = i === optionIndex ? "> " : " ";
327
+ return sum + wrappedLineCount(prefix + `${i + 1}. ${opt.label}` + recTag);
328
+ }, 0);
329
+ const contextWindowLimit = (contextLineCount) => {
330
+ const qRows = q ? wrappedLineCount(` ${q.question}`) : 0;
331
+ let reservedRowsWithoutContextHints;
332
+ if (inputMode && q) {
333
+ const optionsRows = q.options.length > 0 ? optionLineCount() + 1 : 0;
334
+ const editorRows = editor.render(Math.max(1, safeWidth - 2)).length;
335
+ reservedRowsWithoutContextHints = 1 + qRows + optionsRows + 1 + 1 + editorRows + 1 + 1 + 2;
336
+ }
337
+ else {
338
+ const auditorRows = auditorToggleInit ? 2 : 0;
339
+ const existingRows = answers.get(q?.id ?? "") ? 1 : 0;
340
+ reservedRowsWithoutContextHints = 1 + qRows + auditorRows + existingRows + 1 + optionLineCount() + 3 + (isMulti ? 2 : 0);
341
+ }
342
+ const availableRowsWithoutContextHints = overlayRows - reservedRowsWithoutContextHints;
343
+ const contextHintRows = contextLineCount > availableRowsWithoutContextHints ? 2 : 0;
344
+ return Math.max(0, overlayRows - reservedRowsWithoutContextHints - contextHintRows);
345
+ };
346
+ const addWrapped = (s) => lines.push(...wrapTextWithAnsi(s, safeWidth));
347
+ /**
348
+ * Wraps a pipe-prefixed line and prepends "│ " to continuation lines
349
+ * so wrapped content stays within the ASCII box.
350
+ */
351
+ const PIPE_PREFIX = "│ ";
352
+ const PIPE_WIDTH = visibleWidth(PIPE_PREFIX);
353
+ const addWrappedPipe = (styledLine) => {
354
+ const wrapWidth = Math.max(1, safeWidth - PIPE_WIDTH);
355
+ const wrapped = wrapTextWithAnsi(styledLine, wrapWidth);
356
+ for (let i = 0; i < wrapped.length; i++) {
357
+ lines.push(i === 0 ? wrapped[i] : PIPE_PREFIX + wrapped[i]);
358
+ }
359
+ };
360
+ /** Render context lines with per-line styling, then window long confirmations so options stay reachable. */
361
+ const renderContextLines = (context) => {
362
+ const contextStart = lines.length;
363
+ const rawLines = context.split("\n");
364
+ for (const rawLine of rawLines) {
365
+ const trimmed = rawLine.trim();
366
+ // Empty line — preserve as spacing
367
+ if (!trimmed) {
368
+ lines.push("");
369
+ continue;
370
+ }
371
+ // 1. Announcement header — "● Goal draft/tweak ready for confirmation."
372
+ if (/^● Goal (draft|tweak) ready for confirmation\.$/.test(trimmed)) {
373
+ addWrapped(theme.fg("accent", rawLine));
374
+ continue;
375
+ }
376
+ // 2. Section marker — "─── Name ───" → full-width box-drawing header
377
+ const sectionMatch = trimmed.match(/^───\s+(.+?)\s+───$/);
378
+ if (sectionMatch) {
379
+ const sectionName = sectionMatch[1];
380
+ const namePart = ` ${sectionName} `;
381
+ const left = "┌─";
382
+ const right = "─┐";
383
+ const fill = Math.max(0, safeWidth - 2 - visibleWidth(left + namePart + right));
384
+ add(theme.fg("accent", left + namePart + "─".repeat(fill) + right));
385
+ continue;
386
+ }
387
+ // 3. Lines with │ prefix come from buildDraftConfirmationText / buildTweakConfirmationText.
388
+ if (trimmed.startsWith("│")) {
389
+ const afterPipe = trimmed.slice(1).trim();
390
+ // 3a. Task checkbox under │ prefix — detect before key-value to avoid
391
+ // "[x] t1: ..." being misinterpreted as a key-value pair.
392
+ const pipeTaskMatch = afterPipe.match(/^(\[.\])(\s+)(.+)$/);
393
+ if (pipeTaskMatch) {
394
+ const bracket = pipeTaskMatch[1];
395
+ const sep = pipeTaskMatch[2];
396
+ const rest = pipeTaskMatch[3];
397
+ // Preserve inner whitespace between │ and the task marker (e.g. " " in "│ [x]...")
398
+ const pipeContent = trimmed.slice(1);
399
+ const innerWs = pipeContent.slice(0, pipeContent.length - pipeContent.trimStart().length);
400
+ const linePrefix = "│" + innerWs;
401
+ const color = bracket === "[x]" ? "success" : "warning";
402
+ addWrappedPipe(linePrefix + theme.fg(color, bracket) + sep + theme.fg("muted", rest));
403
+ continue;
404
+ }
405
+ // 3b. Key-value content (e.g. "│ Mode: Normal goal", "│ Auto-continue: yes")
406
+ if (afterPipe.includes(": ")) {
407
+ const colonIdx = afterPipe.indexOf(": ");
408
+ const val = afterPipe.slice(colonIdx + 2).trim();
409
+ const keyPart = rawLine.slice(0, rawLine.indexOf(afterPipe) + colonIdx + 2);
410
+ if (val === "yes" || val === "no") {
411
+ addWrappedPipe(theme.fg("muted", keyPart) + theme.fg(val === "yes" ? "success" : "warning", val));
412
+ continue;
413
+ }
414
+ addWrappedPipe(theme.fg("muted", rawLine));
415
+ continue;
416
+ }
417
+ // 3c. Generic content under │ prefix (topic, goal text, etc.)
418
+ addWrappedPipe(theme.fg("muted", rawLine));
419
+ continue;
420
+ }
421
+ // 4. Goal objective structure lines — detected before task checkboxes
422
+ // because === Goal could overlap with ─── markers but we already checked those.
423
+ const GOAL_SECTION_RE = /^(=== (Goal|Sisyphus Goal) ===|Objective:|Success criteria:|Boundaries:|Constraints:|Verification contract:|If blocked:)/;
424
+ if (GOAL_SECTION_RE.test(trimmed)) {
425
+ addWrapped(theme.fg("accent", rawLine));
426
+ continue;
427
+ }
428
+ // 5. Actual box-drawing borders (┌ └ ├ └ ┐ ┤ ┘ ─) — NOT │ which is handled above
429
+ if (/^[┌├└┐┤┘─]/.test(trimmed)) {
430
+ addWrapped(theme.fg("dim", rawLine));
431
+ continue;
432
+ }
433
+ // 6. Task checkbox item — "[ ] ...", "[x] ...", or "[~] ..." (with optional indent)
434
+ const checkMatch = trimmed.match(/^(\[.\])(\s+)(.+)$/);
435
+ if (checkMatch) {
436
+ const bracket = checkMatch[1];
437
+ const sep = checkMatch[2];
438
+ const rest = checkMatch[3];
439
+ const indent = rawLine.slice(0, rawLine.length - trimmed.length);
440
+ const color = bracket === "[x]" ? "success" : "warning";
441
+ addWrapped(indent + theme.fg(color, bracket) + sep + theme.fg("muted", rest));
442
+ continue;
443
+ }
444
+ // 7. Default: any remaining content (fallback)
445
+ addWrapped(theme.fg("muted", rawLine));
446
+ }
447
+ const contextLines = lines.splice(contextStart);
448
+ const contextWindowLines = contextWindowLimit(contextLines.length);
449
+ if (contextLines.length <= contextWindowLines) {
450
+ lines.push(...contextLines);
451
+ return;
452
+ }
453
+ if (contextWindowLines <= 0) {
454
+ contextScroll = 0;
455
+ add(theme.fg("dim", ` Preview hidden (${contextLines.length} lines) — resize terminal or use PgUp/PgDn`));
456
+ add(theme.fg("dim", " Context hidden to keep controls visible in this tiny pane"));
457
+ return;
458
+ }
459
+ const maxStart = Math.max(0, contextLines.length - contextWindowLines);
460
+ contextScroll = Math.max(0, Math.min(contextScroll, maxStart));
461
+ const end = Math.min(contextLines.length, contextScroll + contextWindowLines);
462
+ add(theme.fg("dim", ` Preview lines ${contextScroll + 1}-${end} of ${contextLines.length} — PgUp/PgDn scroll context`));
463
+ lines.push(...contextLines.slice(contextScroll, end));
464
+ if (end < contextLines.length) {
465
+ add(theme.fg("dim", ` ${contextLines.length - end} more lines below — PgDn/End scroll context; Enter confirms selected option`));
466
+ }
467
+ else {
468
+ add(theme.fg("dim", " End of context preview — PgUp/Home scroll up; Enter confirms selected option"));
469
+ }
470
+ };
471
+ add(theme.fg("accent", "─".repeat(safeWidth)));
472
+ if (isMulti) {
473
+ const tabs = ["← "];
474
+ for (let i = 0; i < questions.length; i++) {
475
+ const isActive = i === currentTab;
476
+ const isAnswered = answers.has(questions[i].id);
477
+ const label = ` ${isAnswered ? "■" : "□"} ${questions[i].id} `;
478
+ tabs.push(isActive ? theme.bg("selectedBg", theme.fg("text", label)) : theme.fg(isAnswered ? "success" : "muted", label));
479
+ tabs.push(" ");
480
+ }
481
+ const submitText = " ✓ Submit ";
482
+ tabs.push(currentTab === questions.length ? theme.bg("selectedBg", theme.fg("text", submitText)) : theme.fg(allAnswered() ? "success" : "dim", submitText));
483
+ tabs.push(" →");
484
+ add(` ${tabs.join("")}`);
485
+ lines.push("");
486
+ }
487
+ function renderOptions() {
488
+ for (let i = 0; i < opts.length; i++) {
489
+ const opt = opts[i];
490
+ const selected = i === optionIndex;
491
+ const prefix = selected ? theme.fg("accent", "> ") : " ";
492
+ const recTag = !opt.isCustom && q?.recommended === i ? theme.fg("success", " ★") : "";
493
+ addWrapped(prefix + theme.fg(selected ? "accent" : "text", `${i + 1}. ${opt.label}`) + recTag);
494
+ }
495
+ }
496
+ if (inputMode && q) {
497
+ addWrapped(theme.fg("text", ` ${q.question}`));
498
+ if (q.context)
499
+ renderContextLines(q.context);
500
+ lines.push("");
501
+ if (q.options.length > 0) {
502
+ renderOptions();
503
+ lines.push("");
504
+ }
505
+ add(theme.fg("muted", " Your answer:"));
506
+ for (const line of editor.render(safeWidth - 2))
507
+ add(` ${line}`);
508
+ lines.push("");
509
+ add(theme.fg("dim", " Enter to submit • Esc to cancel"));
510
+ }
511
+ else if (currentTab === questions.length) {
512
+ add(theme.fg("accent", theme.bold(" Ready to submit")));
513
+ lines.push("");
514
+ for (const question of questions) {
515
+ const answer = answers.get(question.id);
516
+ add(`${theme.fg("muted", ` ${question.id}: `)}${answer ? theme.fg("text", `${answer.wasCustom ? "(wrote) " : ""}${answer.answer}`) : theme.fg("warning", "(unanswered)")}`);
517
+ }
518
+ lines.push("");
519
+ add(allAnswered() ? theme.fg("success", " Press Enter to submit") : theme.fg("warning", ` Unanswered: ${questions.filter((qq) => !answers.has(qq.id)).map((qq) => qq.id).join(", ")}`));
520
+ }
521
+ else if (q) {
522
+ addWrapped(theme.fg("text", ` ${q.question}`));
523
+ if (q.context)
524
+ renderContextLines(q.context);
525
+ // Auditor toggle line between context and options
526
+ if (auditorToggleInit) {
527
+ const circle = auditorEnabled ? "●" : "○";
528
+ const label = auditorEnabled ? "Auditor enabled" : "Auditor disabled";
529
+ const color = auditorEnabled ? "success" : "warning";
530
+ add(theme.fg(color, ` ${circle} ${label}`) + theme.fg("dim", " (press 'a' to toggle)"));
531
+ lines.push("");
532
+ }
533
+ const existing = answers.get(q.id);
534
+ if (existing)
535
+ add(theme.fg("dim", ` Current: ${existing.wasCustom ? "(wrote) " : ""}${existing.answer}`));
536
+ lines.push("");
537
+ if (opts.length > 0)
538
+ renderOptions();
539
+ else
540
+ add(theme.fg("muted", " Press Enter to write your answer"));
541
+ }
542
+ lines.push("");
543
+ if (!inputMode) {
544
+ const auditorHint = auditorToggleInit ? " • a toggle auditor" : "";
545
+ const scrollHint = q?.context ? " • PgUp/PgDn scroll context" : "";
546
+ add(theme.fg("dim", isMulti ? " Tab/←→ navigate • ↑↓ select • Enter confirm • Esc cancel" + scrollHint + auditorHint : " ↑↓ navigate • Enter select • Esc cancel" + scrollHint + auditorHint));
547
+ }
548
+ add(theme.fg("accent", "─".repeat(safeWidth)));
549
+ // Full-screen overlay rows must be opaque. Otherwise Pi's overlay compositor
550
+ // leaves the chat/status underneath visible in the uncovered rows/columns,
551
+ // which turns goal proposal dialogs into high-speed garbled redraw soup while
552
+ // the underlying session keeps updating.
553
+ while (lines.length < overlayRows)
554
+ lines.push("");
555
+ // Safety net: ensure no returned line exceeds the terminal width
556
+ for (let i = 0; i < lines.length; i++) {
557
+ if (lines[i] && visibleWidth(lines[i]) > safeWidth) {
558
+ lines[i] = truncateToWidth(lines[i], safeWidth);
559
+ }
560
+ }
561
+ cachedLines = lines;
562
+ cachedWidth = width;
563
+ cachedTerminalRows = terminalRows;
564
+ return lines;
565
+ }
566
+ return { render, invalidate: () => { cachedLines = undefined; cachedWidth = undefined; cachedTerminalRows = undefined; }, handleInput };
567
+ }, {
568
+ overlay: true,
569
+ overlayOptions: {
570
+ width: "100%",
571
+ maxHeight: "100%",
572
+ anchor: "top-left",
573
+ margin: 0,
574
+ },
575
+ });
576
+ }
577
+ /**
578
+ * Confirm a proposed draft through the shared questionnaire UI. Escape / cancel
579
+ * maps to "continue" so the user is never trapped.
580
+ */
581
+ export async function showProposalDialog(ctx, confirmationText, focus, defaultAuditorEnabled) {
582
+ const headerTitle = focus === "sisyphus" ? "Confirm Sisyphus Goal Draft" : "Confirm Goal Draft";
583
+ const result = await runGoalQuestionnaire(ctx, [{
584
+ id: "confirm",
585
+ question: headerTitle,
586
+ context: confirmationText,
587
+ options: ["Confirm — create this goal now", "Continue chatting — keep refining"],
588
+ recommended: 0,
589
+ allowCustom: false,
590
+ }], defaultAuditorEnabled !== undefined ? { defaultEnabled: defaultAuditorEnabled } : undefined);
591
+ const decision = proposalDecisionFromQuestionnaireResult({
592
+ cancelled: result.cancelled,
593
+ answer: result.answers[0]?.answer,
594
+ });
595
+ return { decision, auditorEnabled: result.auditorEnabled ?? true };
596
+ }
597
+ export function registerQuestionnaireTools(pi) {
598
+ pi.registerTool(defineTool({
599
+ name: QUESTION_TOOL_NAME,
600
+ label: "goal_question",
601
+ description: "Ask the user a focused single question through pi-goal's built-in goal_question UI. " +
602
+ "This is the single-question alias for goal_questionnaire and is allowed during drafting.",
603
+ promptSnippet: "Ask the user a focused question with optional choices.",
604
+ promptGuidelines: [
605
+ "Use goal_question when exactly one user decision is required before proceeding.",
606
+ "During drafting this is allowed; it returns user Q&A into the conversation and is not task execution.",
607
+ "Prefer concise options. Use allowFreeText=false only when the user must pick from fixed choices.",
608
+ ],
609
+ parameters: Type.Object({
610
+ question: Type.String({ description: "Question to ask the user." }),
611
+ context: Type.Optional(Type.String({ description: "Short context explaining why the answer is needed." })),
612
+ options: Type.Optional(Type.Array(Type.String({ description: "Suggested answer option." }))),
613
+ recommended: Type.Optional(Type.Integer({ minimum: 0, description: "0-based index of the recommended option." })),
614
+ allowFreeText: Type.Optional(Type.Boolean({ description: "Allow the user to write a custom answer. Defaults to true." })),
615
+ }),
616
+ executionMode: "sequential",
617
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
618
+ if (!hasGoalQuestionnaireUi(ctx)) {
619
+ return {
620
+ content: [{ type: "text", text: "Headless mode: the question was recorded, but no interactive UI answer was collected. If the original request is already fully specified, proceed with the documented/default assumption; otherwise ask the user in final text and stop." }],
621
+ details: { questions: [], answers: [], cancelled: true, answer: undefined },
622
+ };
623
+ }
624
+ const result = await runGoalQuestionnaire(ctx, [{
625
+ id: "answer",
626
+ question: params.question,
627
+ context: params.context,
628
+ options: params.options ?? [],
629
+ recommended: params.recommended,
630
+ allowCustom: params.allowFreeText ?? true,
631
+ }]);
632
+ if (result.cancelled) {
633
+ return {
634
+ content: [{ type: "text", text: "User cancelled the question." }],
635
+ details: { ...result, answer: undefined },
636
+ };
637
+ }
638
+ const answer = result.answers[0]?.answer ?? "";
639
+ return {
640
+ content: [{ type: "text", text: `User answered: ${answer}` }],
641
+ details: { ...result, answer },
642
+ };
643
+ },
644
+ renderCall(args, theme) {
645
+ return new Text(theme.fg("toolTitle", theme.bold("goal_question ")) + theme.fg("muted", truncateText(args?.question ?? "", 80)), 0, 0);
646
+ },
647
+ renderResult(result, _options, theme) {
648
+ const details = result.details;
649
+ if (details?.cancelled)
650
+ return new Text(theme.fg("warning", "(cancelled)"), 0, 0);
651
+ if (details?.answer !== undefined)
652
+ return new Text(theme.fg("success", "✓ ") + theme.fg("muted", details.answer), 0, 0);
653
+ const text = result.content[0];
654
+ return new Text(text?.type === "text" ? text.text : "", 0, 0);
655
+ },
656
+ }));
657
+ pi.registerTool(defineTool({
658
+ name: QUESTIONNAIRE_TOOL_NAME,
659
+ label: "goal_questionnaire",
660
+ description: "Ask the user one or more questions via pi-goal's built-in goal_questionnaire UI. " +
661
+ "Use this during drafting when you need structured grill/Q&A before propose_goal_draft; " +
662
+ "batch related questions into one call. Returns Q&A records in the conversation history.",
663
+ promptSnippet: "Ask the user one or more structured questions with choices and optional free-text answers.",
664
+ promptGuidelines: [
665
+ "Use goal_questionnaire when a user decision or missing requirement blocks a concrete draft.",
666
+ "During /goals or /sisyphus intent discussion, goal_questionnaire is allowed when structured Q&A helps produce a concrete draft.",
667
+ "Prefer 1-3 focused questions. Batch related choices in one questionnaire call instead of repeatedly interrupting the user.",
668
+ "Use recommended to mark the best default choice when there is one. Set allowCustom=false only for strict binary/choice prompts such as confirmation.",
669
+ ],
670
+ parameters: Type.Object({
671
+ questions: Type.Array(Type.Object({
672
+ id: Type.String({ description: "Short stable identifier, e.g. 'scope', 'success', 'constraints'." }),
673
+ question: Type.String({ description: "The question to ask the user." }),
674
+ context: Type.Optional(Type.String({ description: "Optional background, trade-offs, or why the answer matters." })),
675
+ options: Type.Optional(Type.Array(Type.String({ description: "Suggested answer option." }), { description: "Suggested answers. Free-text is still available unless allowCustom=false." })),
676
+ recommended: Type.Optional(Type.Integer({ minimum: 0, description: "0-based index of the recommended option. Shown with a star and selected by default." })),
677
+ allowCustom: Type.Optional(Type.Boolean({ description: "Allow the user to write a custom answer. Defaults to true." })),
678
+ }), { minItems: 1 }),
679
+ }),
680
+ executionMode: "sequential",
681
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
682
+ if (!hasGoalQuestionnaireUi(ctx)) {
683
+ return {
684
+ content: [{ type: "text", text: "Headless mode: the questions were recorded, but no interactive UI answers were collected. If the original request is already fully specified, proceed with documented/default assumptions; otherwise ask the user in final text and stop." }],
685
+ details: { questions: [], answers: [], cancelled: true },
686
+ };
687
+ }
688
+ const rawQuestions = params.questions.map((q) => ({
689
+ id: q.id,
690
+ question: q.question,
691
+ context: q.context,
692
+ options: q.options ?? [],
693
+ recommended: q.recommended,
694
+ allowCustom: q.allowCustom ?? true,
695
+ }));
696
+ const result = await runGoalQuestionnaire(ctx, rawQuestions);
697
+ if (result.cancelled) {
698
+ return {
699
+ content: [{ type: "text", text: "(goal_questionnaire dismissed)" }],
700
+ details: result,
701
+ };
702
+ }
703
+ return {
704
+ content: [{ type: "text", text: formatQuestionnaireAnswers(result) }],
705
+ details: result,
706
+ };
707
+ },
708
+ renderCall(args, theme) {
709
+ const qs = args.questions || [];
710
+ const labels = qs.map((q) => q.id).join(", ");
711
+ let text = theme.fg("toolTitle", theme.bold("goal_questionnaire "));
712
+ text += theme.fg("muted", `${qs.length} question${qs.length !== 1 ? "s" : ""}`);
713
+ if (labels)
714
+ text += theme.fg("dim", ` (${truncateToWidth(labels, 40)})`);
715
+ return new Text(text, 0, 0);
716
+ },
717
+ renderResult(result, _options, theme) {
718
+ const details = result.details;
719
+ if (!details) {
720
+ const text = result.content[0];
721
+ return new Text(text?.type === "text" ? text.text : "", 0, 0);
722
+ }
723
+ if (details.cancelled)
724
+ return new Text(theme.fg("warning", "(dismissed)"), 0, 0);
725
+ const lines = details.answers.map((answer) => {
726
+ const prefix = answer.wasCustom ? "(wrote) " : "";
727
+ return `${theme.fg("success", "✓ ")}${theme.fg("accent", answer.id)}: ${theme.fg("muted", prefix)}${answer.answer}`;
728
+ });
729
+ return new Text(lines.join("\n"), 0, 0);
730
+ },
731
+ }));
732
+ }
733
+ //# sourceMappingURL=goal-questionnaire.js.map