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