@bismawy/pi-arnative 0.18.3 → 0.19.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/extensions/index.ts +2 -0
- package/lib/ask-user.ts +596 -0
- package/lib/features/arnative.ts +246 -4
- package/lib/features/ask-user.ts +1036 -0
- package/lib/preset-store.ts +7 -1
- package/package.json +3 -2
|
@@ -0,0 +1,1036 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured `ask_user_question` tool for @bismawy/pi-arnative.
|
|
3
|
+
*
|
|
4
|
+
* - Supports custom-model delegation (Hybrid: Refine drafted questions OR Author from
|
|
5
|
+
* goal/ambiguities using a stronger model configured in `/arnative` → `Ask`).
|
|
6
|
+
* - Renders an Arnative-styled interactive TUI dialog (single/multi-select, tabs,
|
|
7
|
+
* automatic `Type something.` custom input, side-by-side or stacked `preview`,
|
|
8
|
+
* submit review tab) with RPC native-dialog fallback and non-interactive reconciler.
|
|
9
|
+
*/
|
|
10
|
+
import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import {
|
|
12
|
+
Input,
|
|
13
|
+
matchesKey,
|
|
14
|
+
truncateToWidth,
|
|
15
|
+
visibleWidth,
|
|
16
|
+
wrapTextWithAnsi,
|
|
17
|
+
type Component,
|
|
18
|
+
type Focusable,
|
|
19
|
+
type TUI,
|
|
20
|
+
} from "@earendil-works/pi-tui";
|
|
21
|
+
import {
|
|
22
|
+
ASK_PROMPT_GUIDELINES,
|
|
23
|
+
ASK_PROMPT_SNIPPET,
|
|
24
|
+
ASK_TOOL_DESCRIPTION,
|
|
25
|
+
ASK_TOOL_NAME,
|
|
26
|
+
AskUserParamsSchema,
|
|
27
|
+
CUSTOM_ROW_LABEL,
|
|
28
|
+
SMART_QUESTION_SYSTEM_PROMPT,
|
|
29
|
+
activeAskMode,
|
|
30
|
+
activeAskModel,
|
|
31
|
+
activeAskThinking,
|
|
32
|
+
buildDelegationUserPrompt,
|
|
33
|
+
buildQuestionnaireResponse,
|
|
34
|
+
extractSessionSnippet,
|
|
35
|
+
formatAnswerValue,
|
|
36
|
+
normalizeQuestions,
|
|
37
|
+
parseDelegatedResponse,
|
|
38
|
+
parseModelSpec,
|
|
39
|
+
prepareAskArguments,
|
|
40
|
+
validateQuestions,
|
|
41
|
+
type AskMode,
|
|
42
|
+
type AskUserParams,
|
|
43
|
+
type QuestionAnswer,
|
|
44
|
+
type QuestionData,
|
|
45
|
+
type QuestionnaireResult,
|
|
46
|
+
} from "../ask-user.ts";
|
|
47
|
+
import { softOf, softSecondaryOf, thinkingColorOf } from "../ansi.ts";
|
|
48
|
+
import { boxRow, paintKeycapLegend, renderBoxLines, screenTitle, type BoxTheme } from "../box.ts";
|
|
49
|
+
import { INPUT_LEGEND, InputPicker } from "../list-picker.ts";
|
|
50
|
+
|
|
51
|
+
/** Hard timeout so a slow custom model never wedges an interactive turn. */
|
|
52
|
+
export const DELEGATION_TIMEOUT_MS = 25_000;
|
|
53
|
+
const DELEGATE_WIDGET_KEY = "arnative-ask-delegate";
|
|
54
|
+
const BEL = "\x07";
|
|
55
|
+
const SIDE_BY_SIDE_MIN_WIDTH = 92;
|
|
56
|
+
|
|
57
|
+
export interface DelegationOutcome {
|
|
58
|
+
questions: QuestionData[];
|
|
59
|
+
delegatedModel?: string;
|
|
60
|
+
delegatedAction?: "refined" | "authored" | "fallback";
|
|
61
|
+
fallbackReason?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function sameModel(
|
|
65
|
+
active: { provider?: string; id?: string } | undefined,
|
|
66
|
+
target: { provider: string; modelId: string },
|
|
67
|
+
): boolean {
|
|
68
|
+
if (!active?.provider || !active?.id) return false;
|
|
69
|
+
return active.provider === target.provider && active.id === target.modelId;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function extractAssistantText(msg: { content?: unknown } | null | undefined): string {
|
|
73
|
+
const content = msg?.content;
|
|
74
|
+
if (typeof content === "string") return content;
|
|
75
|
+
if (!Array.isArray(content)) return "";
|
|
76
|
+
const parts: string[] = [];
|
|
77
|
+
for (const block of content) {
|
|
78
|
+
if (!block || typeof block !== "object") continue;
|
|
79
|
+
const rec = block as { type?: unknown; text?: unknown };
|
|
80
|
+
if (rec.type === "text" && typeof rec.text === "string") parts.push(rec.text);
|
|
81
|
+
}
|
|
82
|
+
return parts.join("\n");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function emitTerminalBell(): void {
|
|
86
|
+
try {
|
|
87
|
+
if (process.stdout.isTTY) process.stdout.write(BEL);
|
|
88
|
+
} catch {
|
|
89
|
+
// Best-effort attention cue.
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Resolve final questions: either directly from `params.questions`, or via the configured
|
|
95
|
+
* custom question model (Refine / Hybrid). Always falls back cleanly to valid draft
|
|
96
|
+
* questions on timeout, abort, missing model, or invalid JSON output.
|
|
97
|
+
*/
|
|
98
|
+
export async function resolveQuestions(
|
|
99
|
+
params: AskUserParams,
|
|
100
|
+
ctx: ExtensionContext,
|
|
101
|
+
signal?: AbortSignal,
|
|
102
|
+
opts: {
|
|
103
|
+
mode?: AskMode;
|
|
104
|
+
modelSpec?: string;
|
|
105
|
+
thinking?: string;
|
|
106
|
+
timeoutMs?: number;
|
|
107
|
+
} = {},
|
|
108
|
+
): Promise<DelegationOutcome | { error: string; message: string }> {
|
|
109
|
+
const draft = Array.isArray(params.questions) && params.questions.length > 0
|
|
110
|
+
? normalizeQuestions(params.questions)
|
|
111
|
+
: null;
|
|
112
|
+
const mode = opts.mode ?? activeAskMode();
|
|
113
|
+
const modelSpec = (opts.modelSpec ?? activeAskModel()).trim();
|
|
114
|
+
const thinking = opts.thinking ?? activeAskThinking();
|
|
115
|
+
const parsedSpec = parseModelSpec(modelSpec);
|
|
116
|
+
|
|
117
|
+
const hasAuthorInputs = Boolean(
|
|
118
|
+
params.goal?.trim() ||
|
|
119
|
+
params.context?.trim() ||
|
|
120
|
+
(Array.isArray(params.ambiguities) && params.ambiguities.some((a) => a.trim().length > 0)),
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
// Decide whether to delegate to the configured custom model.
|
|
124
|
+
const canDelegate = mode !== "Off" && parsedSpec !== null;
|
|
125
|
+
const action: "refine" | "author" | null = !canDelegate
|
|
126
|
+
? null
|
|
127
|
+
: draft
|
|
128
|
+
? "refine"
|
|
129
|
+
: mode === "Hybrid" && hasAuthorInputs
|
|
130
|
+
? "author"
|
|
131
|
+
: null;
|
|
132
|
+
|
|
133
|
+
// If no delegation applies, validate and return draft directly.
|
|
134
|
+
if (!action || !parsedSpec) {
|
|
135
|
+
if (!draft) {
|
|
136
|
+
return {
|
|
137
|
+
error: "no_questions",
|
|
138
|
+
message:
|
|
139
|
+
"Error: `questions` is required unless a custom question model is configured in /arnative → Ask (Hybrid mode) and goal/ambiguities are supplied.",
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
const valid = validateQuestions(draft);
|
|
143
|
+
if (!valid.ok) return valid;
|
|
144
|
+
return { questions: draft };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Skip redundant self-delegation on refine when the configured model is already active.
|
|
148
|
+
if (action === "refine" && sameModel(ctx.model, parsedSpec)) {
|
|
149
|
+
const valid = validateQuestions(draft!);
|
|
150
|
+
if (!valid.ok) return valid;
|
|
151
|
+
return { questions: draft! };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const model = ctx.modelRegistry?.find?.(parsedSpec.provider, parsedSpec.modelId);
|
|
155
|
+
if (!model) {
|
|
156
|
+
if (draft) {
|
|
157
|
+
const valid = validateQuestions(draft);
|
|
158
|
+
if (!valid.ok) return valid;
|
|
159
|
+
return {
|
|
160
|
+
questions: draft,
|
|
161
|
+
delegatedModel: modelSpec,
|
|
162
|
+
delegatedAction: "fallback",
|
|
163
|
+
fallbackReason: `Configured question model "${modelSpec}" not found in registry`,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
error: "model_not_found",
|
|
168
|
+
message: `Error: Configured question model "${modelSpec}" was not found. Pass explicit \`questions\` or update /arnative → Ask.`,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const timeoutMs = opts.timeoutMs ?? DELEGATION_TIMEOUT_MS;
|
|
173
|
+
const controller = new AbortController();
|
|
174
|
+
const onOuterAbort = () => controller.abort(signal?.reason);
|
|
175
|
+
if (signal) {
|
|
176
|
+
if (signal.aborted) controller.abort(signal.reason);
|
|
177
|
+
else signal.addEventListener("abort", onOuterAbort, { once: true });
|
|
178
|
+
}
|
|
179
|
+
const timer = setTimeout(() => controller.abort(new Error("timeout")), timeoutMs);
|
|
180
|
+
timer.unref?.();
|
|
181
|
+
|
|
182
|
+
const widgetLabel = action === "refine"
|
|
183
|
+
? `Refining questions with ${modelSpec}…`
|
|
184
|
+
: `Authoring questions with ${modelSpec}…`;
|
|
185
|
+
ctx.ui?.setWidget?.(DELEGATE_WIDGET_KEY, [widgetLabel], { placement: "aboveEditor" });
|
|
186
|
+
|
|
187
|
+
try {
|
|
188
|
+
const entries = ctx.sessionManager?.buildContextEntries?.() ?? ctx.sessionManager?.getBranch?.() ?? [];
|
|
189
|
+
const snippet = extractSessionSnippet(entries);
|
|
190
|
+
const userPrompt = buildDelegationUserPrompt(action, params, snippet);
|
|
191
|
+
const context = {
|
|
192
|
+
systemPrompt: SMART_QUESTION_SYSTEM_PROMPT,
|
|
193
|
+
messages: [
|
|
194
|
+
{
|
|
195
|
+
role: "user" as const,
|
|
196
|
+
content: [{ type: "text" as const, text: userPrompt }],
|
|
197
|
+
timestamp: Date.now(),
|
|
198
|
+
},
|
|
199
|
+
],
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const streamOptions: Record<string, unknown> = { signal: controller.signal };
|
|
203
|
+
if (thinking && thinking !== "off") streamOptions.reasoning = thinking;
|
|
204
|
+
|
|
205
|
+
let finalMessage: { content?: unknown; stopReason?: string; errorMessage?: string } | undefined;
|
|
206
|
+
if (typeof ctx.modelRegistry.streamSimple === "function") {
|
|
207
|
+
const stream = ctx.modelRegistry.streamSimple(model as never, context as never, streamOptions as never);
|
|
208
|
+
finalMessage = await stream.result();
|
|
209
|
+
} else if (typeof ctx.modelRegistry.complete === "function") {
|
|
210
|
+
finalMessage = await ctx.modelRegistry.complete(model as never, context as never, streamOptions as never);
|
|
211
|
+
} else {
|
|
212
|
+
throw new Error("ModelRegistry has neither streamSimple nor complete");
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (finalMessage?.stopReason === "error") {
|
|
216
|
+
throw new Error(finalMessage.errorMessage || "delegated model returned error");
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const parsed = parseDelegatedResponse(extractAssistantText(finalMessage));
|
|
220
|
+
if (parsed) {
|
|
221
|
+
const valid = validateQuestions(parsed);
|
|
222
|
+
if (valid.ok) {
|
|
223
|
+
return {
|
|
224
|
+
questions: parsed,
|
|
225
|
+
delegatedModel: modelSpec,
|
|
226
|
+
delegatedAction: action === "refine" ? "refined" : "authored",
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (draft) {
|
|
232
|
+
const valid = validateQuestions(draft);
|
|
233
|
+
if (!valid.ok) return valid;
|
|
234
|
+
return {
|
|
235
|
+
questions: draft,
|
|
236
|
+
delegatedModel: modelSpec,
|
|
237
|
+
delegatedAction: "fallback",
|
|
238
|
+
fallbackReason: "Delegated response did not contain valid questions",
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
return {
|
|
242
|
+
error: "delegation_invalid",
|
|
243
|
+
message: `Error: Question model "${modelSpec}" did not return valid structured questions. Call ask_user_question again with explicit \`questions\`.`,
|
|
244
|
+
};
|
|
245
|
+
} catch (err) {
|
|
246
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
247
|
+
if (draft) {
|
|
248
|
+
const valid = validateQuestions(draft);
|
|
249
|
+
if (!valid.ok) return valid;
|
|
250
|
+
return {
|
|
251
|
+
questions: draft,
|
|
252
|
+
delegatedModel: modelSpec,
|
|
253
|
+
delegatedAction: "fallback",
|
|
254
|
+
fallbackReason: reason,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
error: "delegation_failed",
|
|
259
|
+
message: `Error: Question model "${modelSpec}" failed (${reason}). Call ask_user_question again with explicit \`questions\`.`,
|
|
260
|
+
};
|
|
261
|
+
} finally {
|
|
262
|
+
clearTimeout(timer);
|
|
263
|
+
signal?.removeEventListener("abort", onOuterAbort);
|
|
264
|
+
ctx.ui?.setWidget?.(DELEGATE_WIDGET_KEY, undefined);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// ---------------------------------------------------------------------------
|
|
269
|
+
// Arnative TUI Questionnaire Component
|
|
270
|
+
// ---------------------------------------------------------------------------
|
|
271
|
+
|
|
272
|
+
interface TabDraft {
|
|
273
|
+
/** Cursor row index within `0 .. question.options.length` (last row = Type something.). */
|
|
274
|
+
cursor: number;
|
|
275
|
+
/** Checked option indices for multiSelect. */
|
|
276
|
+
checked: Set<number>;
|
|
277
|
+
/** Committed single-select option index (null if unanswered or custom). */
|
|
278
|
+
selectedOption: number | null;
|
|
279
|
+
/** Custom text typed on the `Type something.` row. */
|
|
280
|
+
customText: string;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export class AskUserDialog implements Component, Focusable {
|
|
284
|
+
focused = false;
|
|
285
|
+
private readonly theme: Theme;
|
|
286
|
+
private readonly questions: readonly QuestionData[];
|
|
287
|
+
private readonly delegatedLabel: string | undefined;
|
|
288
|
+
private readonly onDone: (result: QuestionnaireResult) => void;
|
|
289
|
+
private readonly requestRender: () => void;
|
|
290
|
+
private readonly edge: (s: string) => string;
|
|
291
|
+
|
|
292
|
+
private tabIndex = 0;
|
|
293
|
+
private readonly drafts: TabDraft[];
|
|
294
|
+
private editingCustom = false;
|
|
295
|
+
private readonly customInput: Input;
|
|
296
|
+
private submitCursor = 0; // 0 = Submit answers, 1 = Cancel
|
|
297
|
+
|
|
298
|
+
constructor(
|
|
299
|
+
theme: Theme,
|
|
300
|
+
questions: readonly QuestionData[],
|
|
301
|
+
opts: {
|
|
302
|
+
delegatedLabel?: string;
|
|
303
|
+
thinkingLevel?: string;
|
|
304
|
+
onDone: (result: QuestionnaireResult) => void;
|
|
305
|
+
requestRender: () => void;
|
|
306
|
+
},
|
|
307
|
+
) {
|
|
308
|
+
this.theme = theme;
|
|
309
|
+
this.questions = questions;
|
|
310
|
+
this.delegatedLabel = opts.delegatedLabel;
|
|
311
|
+
this.onDone = opts.onDone;
|
|
312
|
+
this.requestRender = opts.requestRender;
|
|
313
|
+
this.edge = thinkingColorOf(theme, opts.thinkingLevel);
|
|
314
|
+
this.drafts = questions.map(() => ({
|
|
315
|
+
cursor: 0,
|
|
316
|
+
checked: new Set<number>(),
|
|
317
|
+
selectedOption: null,
|
|
318
|
+
customText: "",
|
|
319
|
+
}));
|
|
320
|
+
this.customInput = new Input({
|
|
321
|
+
prompt: theme.fg("accent", "> "),
|
|
322
|
+
placeholder: "Type your answer...",
|
|
323
|
+
placeholderStyle: (t: string) => theme.fg("muted", t),
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
invalidate(): void {
|
|
328
|
+
/* stateless render */
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
private get isMultiQuestion(): boolean {
|
|
332
|
+
return this.questions.length > 1;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private get submitTabIndex(): number {
|
|
336
|
+
return this.questions.length;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private get onSubmitTab(): boolean {
|
|
340
|
+
return this.isMultiQuestion && this.tabIndex === this.submitTabIndex;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private currentQuestion(): QuestionData {
|
|
344
|
+
return this.questions[this.tabIndex]!;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private currentDraft(): TabDraft {
|
|
348
|
+
return this.drafts[this.tabIndex]!;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private isAnswered(index: number): boolean {
|
|
352
|
+
const q = this.questions[index]!;
|
|
353
|
+
const d = this.drafts[index]!;
|
|
354
|
+
if (q.multiSelect) return d.checked.size > 0 || d.customText.trim().length > 0;
|
|
355
|
+
return d.selectedOption !== null || d.customText.trim().length > 0;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private buildAnswers(): QuestionAnswer[] {
|
|
359
|
+
const answers: QuestionAnswer[] = [];
|
|
360
|
+
for (let i = 0; i < this.questions.length; i++) {
|
|
361
|
+
const q = this.questions[i]!;
|
|
362
|
+
const d = this.drafts[i]!;
|
|
363
|
+
const custom = d.customText.trim();
|
|
364
|
+
if (q.multiSelect) {
|
|
365
|
+
const selected = [...d.checked]
|
|
366
|
+
.sort((a, b) => a - b)
|
|
367
|
+
.map((idx) => q.options[idx]!.label);
|
|
368
|
+
if (selected.length === 0 && !custom) continue;
|
|
369
|
+
answers.push({
|
|
370
|
+
questionIndex: i,
|
|
371
|
+
question: q.question,
|
|
372
|
+
kind: "multi",
|
|
373
|
+
selected,
|
|
374
|
+
answer: custom || null,
|
|
375
|
+
});
|
|
376
|
+
} else if (d.selectedOption !== null) {
|
|
377
|
+
const opt = q.options[d.selectedOption]!;
|
|
378
|
+
answers.push({
|
|
379
|
+
questionIndex: i,
|
|
380
|
+
question: q.question,
|
|
381
|
+
kind: "option",
|
|
382
|
+
answer: opt.label,
|
|
383
|
+
...(opt.preview ? { preview: opt.preview } : {}),
|
|
384
|
+
});
|
|
385
|
+
} else if (custom) {
|
|
386
|
+
answers.push({
|
|
387
|
+
questionIndex: i,
|
|
388
|
+
question: q.question,
|
|
389
|
+
kind: "custom",
|
|
390
|
+
answer: custom,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return answers;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
private finish(cancelled: boolean): void {
|
|
398
|
+
this.onDone({
|
|
399
|
+
answers: this.buildAnswers(),
|
|
400
|
+
cancelled,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private openCustomEditor(): void {
|
|
405
|
+
const draft = this.currentDraft();
|
|
406
|
+
this.customInput.setValue(draft.customText);
|
|
407
|
+
this.editingCustom = true;
|
|
408
|
+
this.requestRender();
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
private commitCustomEditor(advance: boolean): void {
|
|
412
|
+
const q = this.currentQuestion();
|
|
413
|
+
const draft = this.currentDraft();
|
|
414
|
+
const val = this.customInput.getValue().trim();
|
|
415
|
+
draft.customText = val;
|
|
416
|
+
if (!q.multiSelect && val) draft.selectedOption = null;
|
|
417
|
+
this.editingCustom = false;
|
|
418
|
+
if (advance && val) {
|
|
419
|
+
if (!this.isMultiQuestion) {
|
|
420
|
+
this.finish(false);
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
this.tabIndex = Math.min(this.submitTabIndex, this.tabIndex + 1);
|
|
424
|
+
}
|
|
425
|
+
this.requestRender();
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
handleInput(data: string): void {
|
|
429
|
+
if (this.editingCustom) {
|
|
430
|
+
if (matchesKey(data, "escape")) {
|
|
431
|
+
this.editingCustom = false;
|
|
432
|
+
this.requestRender();
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
if (matchesKey(data, "enter") || matchesKey(data, "return")) {
|
|
436
|
+
this.commitCustomEditor(!this.currentQuestion().multiSelect);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
this.customInput.handleInput(data);
|
|
440
|
+
this.requestRender();
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Cancel everywhere on Esc
|
|
445
|
+
if (matchesKey(data, "escape")) {
|
|
446
|
+
this.finish(true);
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// Tab / Shift+Tab switches questions when multi-question
|
|
451
|
+
if (this.isMultiQuestion && matchesKey(data, "tab")) {
|
|
452
|
+
this.tabIndex = (this.tabIndex + 1) % (this.questions.length + 1);
|
|
453
|
+
this.requestRender();
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
if (this.isMultiQuestion && matchesKey(data, "shift+tab")) {
|
|
457
|
+
this.tabIndex = (this.tabIndex + this.questions.length) % (this.questions.length + 1);
|
|
458
|
+
this.requestRender();
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
if (this.onSubmitTab) {
|
|
463
|
+
if (matchesKey(data, "up") || matchesKey(data, "down") || matchesKey(data, "k") || matchesKey(data, "j")) {
|
|
464
|
+
this.submitCursor = this.submitCursor === 0 ? 1 : 0;
|
|
465
|
+
this.requestRender();
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (matchesKey(data, "left")) {
|
|
469
|
+
this.tabIndex = this.questions.length - 1;
|
|
470
|
+
this.requestRender();
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
if (matchesKey(data, "enter") || matchesKey(data, "return")) {
|
|
474
|
+
this.finish(this.submitCursor === 1);
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const q = this.currentQuestion();
|
|
481
|
+
const draft = this.currentDraft();
|
|
482
|
+
const rowCount = q.options.length + 1; // +1 for "Type something."
|
|
483
|
+
const customRowIdx = q.options.length;
|
|
484
|
+
|
|
485
|
+
if (matchesKey(data, "up") || matchesKey(data, "k")) {
|
|
486
|
+
draft.cursor = (draft.cursor - 1 + rowCount) % rowCount;
|
|
487
|
+
this.requestRender();
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (matchesKey(data, "down") || matchesKey(data, "j")) {
|
|
491
|
+
draft.cursor = (draft.cursor + 1) % rowCount;
|
|
492
|
+
this.requestRender();
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (this.isMultiQuestion && matchesKey(data, "left")) {
|
|
496
|
+
this.tabIndex = (this.tabIndex + this.questions.length) % (this.questions.length + 1);
|
|
497
|
+
this.requestRender();
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (this.isMultiQuestion && matchesKey(data, "right")) {
|
|
501
|
+
this.tabIndex = (this.tabIndex + 1) % (this.questions.length + 1);
|
|
502
|
+
this.requestRender();
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// Quick digit selection (1..4) for options
|
|
507
|
+
if (data.length === 1 && data >= "1" && data <= String(q.options.length)) {
|
|
508
|
+
const idx = Number(data) - 1;
|
|
509
|
+
draft.cursor = idx;
|
|
510
|
+
if (q.multiSelect) {
|
|
511
|
+
if (draft.checked.has(idx)) draft.checked.delete(idx);
|
|
512
|
+
else draft.checked.add(idx);
|
|
513
|
+
} else {
|
|
514
|
+
draft.selectedOption = idx;
|
|
515
|
+
draft.customText = "";
|
|
516
|
+
if (!this.isMultiQuestion) {
|
|
517
|
+
this.finish(false);
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
this.tabIndex = Math.min(this.submitTabIndex, this.tabIndex + 1);
|
|
521
|
+
}
|
|
522
|
+
this.requestRender();
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Space toggles in multiSelect (or opens custom input on the last row)
|
|
527
|
+
if (matchesKey(data, "space") && q.multiSelect) {
|
|
528
|
+
if (draft.cursor === customRowIdx) {
|
|
529
|
+
this.openCustomEditor();
|
|
530
|
+
} else {
|
|
531
|
+
if (draft.checked.has(draft.cursor)) draft.checked.delete(draft.cursor);
|
|
532
|
+
else draft.checked.add(draft.cursor);
|
|
533
|
+
this.requestRender();
|
|
534
|
+
}
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
if (matchesKey(data, "enter") || matchesKey(data, "return")) {
|
|
539
|
+
if (draft.cursor === customRowIdx) {
|
|
540
|
+
this.openCustomEditor();
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
if (q.multiSelect) {
|
|
544
|
+
// If nothing selected yet on this question, toggle focused option before advancing.
|
|
545
|
+
if (draft.checked.size === 0 && !draft.customText.trim()) {
|
|
546
|
+
draft.checked.add(draft.cursor);
|
|
547
|
+
}
|
|
548
|
+
if (!this.isMultiQuestion) {
|
|
549
|
+
this.finish(false);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
this.tabIndex = Math.min(this.submitTabIndex, this.tabIndex + 1);
|
|
553
|
+
this.requestRender();
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
draft.selectedOption = draft.cursor;
|
|
557
|
+
draft.customText = "";
|
|
558
|
+
if (!this.isMultiQuestion) {
|
|
559
|
+
this.finish(false);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
this.tabIndex = Math.min(this.submitTabIndex, this.tabIndex + 1);
|
|
563
|
+
this.requestRender();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
private renderTabs(innerWidth: number): string {
|
|
568
|
+
const fg = this.theme.fg.bind(this.theme);
|
|
569
|
+
const bold = this.theme.bold?.bind(this.theme) ?? ((s: string) => s);
|
|
570
|
+
const parts: string[] = [];
|
|
571
|
+
for (let i = 0; i < this.questions.length; i++) {
|
|
572
|
+
const q = this.questions[i]!;
|
|
573
|
+
const active = i === this.tabIndex;
|
|
574
|
+
const mark = this.isAnswered(i) ? fg("success", "✓") : fg("dim", "○");
|
|
575
|
+
const label = active ? fg("accent", bold(q.header)) : fg("muted", q.header);
|
|
576
|
+
parts.push(active ? `${fg("accent", "[")}${mark} ${label}${fg("accent", "]")}` : ` ${mark} ${label} `);
|
|
577
|
+
}
|
|
578
|
+
const submitActive = this.onSubmitTab;
|
|
579
|
+
const submitLabel = submitActive ? fg("accent", bold("Submit")) : fg("muted", "Submit");
|
|
580
|
+
parts.push(submitActive ? `${fg("accent", "[")}${submitLabel}${fg("accent", "]")}` : ` ${submitLabel} `);
|
|
581
|
+
return truncateToWidth(parts.join(fg("dim", " · ")), innerWidth, "…");
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
private renderOptionLines(q: QuestionData, draft: TabDraft, colWidth: number): string[] {
|
|
585
|
+
const fg = this.theme.fg.bind(this.theme);
|
|
586
|
+
const bold = this.theme.bold?.bind(this.theme) ?? ((s: string) => s);
|
|
587
|
+
const soft = softOf(this.theme);
|
|
588
|
+
const lines: string[] = [];
|
|
589
|
+
|
|
590
|
+
for (let i = 0; i < q.options.length; i++) {
|
|
591
|
+
const opt = q.options[i]!;
|
|
592
|
+
const focused = draft.cursor === i;
|
|
593
|
+
const pointer = focused ? fg("accent", "❯") : " ";
|
|
594
|
+
const num = fg("dim", `${i + 1}.`);
|
|
595
|
+
const box = q.multiSelect
|
|
596
|
+
? draft.checked.has(i)
|
|
597
|
+
? fg("success", "[x]")
|
|
598
|
+
: fg("dim", "[ ]")
|
|
599
|
+
: draft.selectedOption === i
|
|
600
|
+
? fg("success", "●")
|
|
601
|
+
: "";
|
|
602
|
+
const labelText = focused ? fg("accent", bold(opt.label)) : soft(opt.label);
|
|
603
|
+
const prefix = box ? `${pointer} ${num} ${box} ` : `${pointer} ${num} `;
|
|
604
|
+
const headWrapped = wrapTextWithAnsi(`${prefix}${labelText}`, colWidth);
|
|
605
|
+
lines.push(...headWrapped);
|
|
606
|
+
|
|
607
|
+
if (opt.description) {
|
|
608
|
+
const indent = " ";
|
|
609
|
+
const descLines = wrapTextWithAnsi(opt.description, Math.max(10, colWidth - indent.length));
|
|
610
|
+
for (const d of descLines) {
|
|
611
|
+
lines.push(`${indent}${fg("muted", d)}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// Automatically appended "Type something." custom row (2-cell glyph column aligns with "1."/"2.")
|
|
617
|
+
const customIdx = q.options.length;
|
|
618
|
+
const focused = draft.cursor === customIdx;
|
|
619
|
+
const pointer = focused ? fg("accent", "❯") : " ";
|
|
620
|
+
const customTag = focused ? fg("accent", bold(CUSTOM_ROW_LABEL)) : fg("muted", CUSTOM_ROW_LABEL);
|
|
621
|
+
const customBox = q.multiSelect
|
|
622
|
+
? draft.customText.trim()
|
|
623
|
+
? `${fg("success", "[x]")} `
|
|
624
|
+
: `${fg("dim", "[ ]")} `
|
|
625
|
+
: "";
|
|
626
|
+
const previewVal = draft.customText.trim()
|
|
627
|
+
? ` ${fg("dim", "·")} ${fg("success", truncateToWidth(draft.customText.trim(), Math.max(8, colWidth - 24), "…"))}`
|
|
628
|
+
: "";
|
|
629
|
+
lines.push(`${pointer} ${fg("dim", "\uf01f ")} ${customBox}${customTag}${previewVal}`);
|
|
630
|
+
|
|
631
|
+
if (this.editingCustom) {
|
|
632
|
+
lines.push("");
|
|
633
|
+
lines.push(...this.customInput.render(colWidth));
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
return lines;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
private renderPreviewBox(preview: string, boxWidth: number): string[] {
|
|
640
|
+
const fg = this.theme.fg.bind(this.theme);
|
|
641
|
+
const inner = Math.max(8, boxWidth - 4);
|
|
642
|
+
const rawLines = preview.split("\n");
|
|
643
|
+
const content: string[] = [fg("dim", "Preview")];
|
|
644
|
+
for (const raw of rawLines.slice(0, 14)) {
|
|
645
|
+
content.push(...wrapTextWithAnsi(raw, inner));
|
|
646
|
+
}
|
|
647
|
+
if (rawLines.length > 14) content.push(fg("dim", `… +${rawLines.length - 14} lines`));
|
|
648
|
+
return renderBoxLines(this.theme as unknown as BoxTheme, boxWidth, content, undefined, "dim");
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
private renderQuestionBody(innerWidth: number): string[] {
|
|
652
|
+
const fg = this.theme.fg.bind(this.theme);
|
|
653
|
+
const bold = this.theme.bold?.bind(this.theme) ?? ((s: string) => s);
|
|
654
|
+
const q = this.currentQuestion();
|
|
655
|
+
const draft = this.currentDraft();
|
|
656
|
+
const lines: string[] = [];
|
|
657
|
+
|
|
658
|
+
if (this.isMultiQuestion) {
|
|
659
|
+
lines.push(this.renderTabs(innerWidth));
|
|
660
|
+
lines.push("");
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
const modeBadge = q.multiSelect ? ` ${fg("dim", "(multi-select)")}` : "";
|
|
664
|
+
for (const qLine of wrapTextWithAnsi(`${bold(q.question)}${modeBadge}`, innerWidth)) {
|
|
665
|
+
lines.push(qLine);
|
|
666
|
+
}
|
|
667
|
+
lines.push("");
|
|
668
|
+
|
|
669
|
+
const focusedOption = draft.cursor < q.options.length ? q.options[draft.cursor] : undefined;
|
|
670
|
+
const hasAnyPreview = !q.multiSelect && q.options.some((o) => Boolean(o.preview));
|
|
671
|
+
const activePreview = !this.editingCustom ? focusedOption?.preview : undefined;
|
|
672
|
+
|
|
673
|
+
if (hasAnyPreview && activePreview && innerWidth >= SIDE_BY_SIDE_MIN_WIDTH) {
|
|
674
|
+
const gap = 2;
|
|
675
|
+
const leftW = Math.floor((innerWidth - gap) * 0.48);
|
|
676
|
+
const rightW = innerWidth - gap - leftW;
|
|
677
|
+
const leftLines = this.renderOptionLines(q, draft, leftW);
|
|
678
|
+
const rightLines = this.renderPreviewBox(activePreview, rightW);
|
|
679
|
+
const total = Math.max(leftLines.length, rightLines.length);
|
|
680
|
+
for (let i = 0; i < total; i++) {
|
|
681
|
+
const l = leftLines[i] ?? "";
|
|
682
|
+
const r = rightLines[i] ?? "";
|
|
683
|
+
const pad = Math.max(0, leftW - visibleWidth(l));
|
|
684
|
+
lines.push(`${truncateToWidth(l, leftW, "")}${" ".repeat(pad)}${" ".repeat(gap)}${r}`);
|
|
685
|
+
}
|
|
686
|
+
} else {
|
|
687
|
+
lines.push(...this.renderOptionLines(q, draft, innerWidth));
|
|
688
|
+
if (activePreview) {
|
|
689
|
+
lines.push("");
|
|
690
|
+
lines.push(...this.renderPreviewBox(activePreview, innerWidth));
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
return lines;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
private renderSubmitBody(innerWidth: number): string[] {
|
|
698
|
+
const fg = this.theme.fg.bind(this.theme);
|
|
699
|
+
const bold = this.theme.bold?.bind(this.theme) ?? ((s: string) => s);
|
|
700
|
+
const lines: string[] = [this.renderTabs(innerWidth), "", bold("Review your answers"), ""];
|
|
701
|
+
|
|
702
|
+
let unansweredCount = 0;
|
|
703
|
+
for (let i = 0; i < this.questions.length; i++) {
|
|
704
|
+
const q = this.questions[i]!;
|
|
705
|
+
const d = this.drafts[i]!;
|
|
706
|
+
let answerText = "";
|
|
707
|
+
if (q.multiSelect) {
|
|
708
|
+
const picked = [...d.checked].sort((a, b) => a - b).map((idx) => q.options[idx]!.label);
|
|
709
|
+
if (d.customText.trim()) picked.push(d.customText.trim());
|
|
710
|
+
answerText = picked.join(", ");
|
|
711
|
+
} else if (d.selectedOption !== null) {
|
|
712
|
+
answerText = q.options[d.selectedOption]!.label;
|
|
713
|
+
} else if (d.customText.trim()) {
|
|
714
|
+
answerText = d.customText.trim();
|
|
715
|
+
}
|
|
716
|
+
if (!answerText) {
|
|
717
|
+
unansweredCount++;
|
|
718
|
+
lines.push(`${fg("warning", "○")} ${fg("muted", q.header)}: ${fg("dim", "unanswered")}`);
|
|
719
|
+
} else {
|
|
720
|
+
const row = `${fg("success", "✓")} ${fg("muted", q.header)}: ${answerText}`;
|
|
721
|
+
lines.push(...wrapTextWithAnsi(row, innerWidth));
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
if (unansweredCount > 0) {
|
|
726
|
+
lines.push("");
|
|
727
|
+
lines.push(fg("warning", `${unansweredCount} question${unansweredCount > 1 ? "s" : ""} still unanswered — you can still submit or Tab back.`));
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
lines.push("");
|
|
731
|
+
const submitRow = this.submitCursor === 0
|
|
732
|
+
? `${fg("accent", "❯")} ${fg("accent", bold("Submit answers"))}`
|
|
733
|
+
: ` ${fg("muted", "Submit answers")}`;
|
|
734
|
+
const cancelRow = this.submitCursor === 1
|
|
735
|
+
? `${fg("accent", "❯")} ${fg("accent", bold("Cancel"))}`
|
|
736
|
+
: ` ${fg("muted", "Cancel")}`;
|
|
737
|
+
lines.push(submitRow, cancelRow);
|
|
738
|
+
|
|
739
|
+
return lines;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
render(width: number): string[] {
|
|
743
|
+
if (width < 12) return [];
|
|
744
|
+
const fg = this.theme.fg.bind(this.theme);
|
|
745
|
+
const bold = this.theme.bold?.bind(this.theme) ?? ((s: string) => s);
|
|
746
|
+
const inner = Math.max(8, width - 4);
|
|
747
|
+
const border = this.edge;
|
|
748
|
+
const row = (content: string) => boxRow(content, width, border);
|
|
749
|
+
|
|
750
|
+
const title = screenTitle("Question");
|
|
751
|
+
const subtitle = this.delegatedLabel
|
|
752
|
+
? `via ${this.delegatedLabel}`
|
|
753
|
+
: this.isMultiQuestion
|
|
754
|
+
? `${this.questions.length} questions`
|
|
755
|
+
: "Select an option or type your own";
|
|
756
|
+
|
|
757
|
+
const body = this.onSubmitTab ? this.renderSubmitBody(inner) : this.renderQuestionBody(inner);
|
|
758
|
+
|
|
759
|
+
let legend: string;
|
|
760
|
+
if (this.editingCustom) {
|
|
761
|
+
legend = "[Enter] Save [Esc] Cancel edit";
|
|
762
|
+
} else if (this.onSubmitTab) {
|
|
763
|
+
legend = "[↑↓] Move [Tab] Questions [Enter] Confirm [Esc] Cancel";
|
|
764
|
+
} else if (this.currentQuestion().multiSelect) {
|
|
765
|
+
legend = this.isMultiQuestion
|
|
766
|
+
? "[↑↓] Move [Space] Toggle [Tab] Next [Enter] Continue [Esc] Cancel"
|
|
767
|
+
: "[↑↓] Move [Space] Toggle [Enter] Submit [Esc] Cancel";
|
|
768
|
+
} else {
|
|
769
|
+
const optCount = this.currentQuestion().options.length;
|
|
770
|
+
const pickHint = optCount > 1 ? `[1-${optCount}] Pick` : "[1] Pick";
|
|
771
|
+
legend = this.isMultiQuestion
|
|
772
|
+
? `[↑↓] Move ${pickHint} [Tab] Next [Enter] Select [Esc] Cancel`
|
|
773
|
+
: `[↑↓] Move ${pickHint} [Enter] Select [Esc] Cancel`;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const top = border(`╭${"─".repeat(Math.max(0, width - 2))}╮`);
|
|
777
|
+
const bottom = border(`╰${"─".repeat(Math.max(0, width - 2))}╯`);
|
|
778
|
+
|
|
779
|
+
return [
|
|
780
|
+
top,
|
|
781
|
+
row(`${fg("accent", bold(title))} ${fg("dim", subtitle)}`),
|
|
782
|
+
row(""),
|
|
783
|
+
...body.map(row),
|
|
784
|
+
row(""),
|
|
785
|
+
row(paintKeycapLegend(legend, this.theme as unknown as BoxTheme, softSecondaryOf(this.theme))),
|
|
786
|
+
bottom,
|
|
787
|
+
].map((l) => truncateToWidth(l, width, ""));
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// ---------------------------------------------------------------------------
|
|
792
|
+
// RPC / native dialog fallback (Zed, VS Code pendant, etc.)
|
|
793
|
+
// ---------------------------------------------------------------------------
|
|
794
|
+
|
|
795
|
+
async function runRpcFallback(
|
|
796
|
+
ctx: ExtensionContext,
|
|
797
|
+
questions: readonly QuestionData[],
|
|
798
|
+
): Promise<QuestionnaireResult> {
|
|
799
|
+
const answers: QuestionAnswer[] = [];
|
|
800
|
+
for (let i = 0; i < questions.length; i++) {
|
|
801
|
+
const q = questions[i]!;
|
|
802
|
+
const labels = [...q.options.map((o) => `${o.label} — ${o.description}`), CUSTOM_ROW_LABEL];
|
|
803
|
+
const picked = await ctx.ui.select(`${q.header}: ${q.question}`, labels);
|
|
804
|
+
if (picked === undefined) {
|
|
805
|
+
return { answers, cancelled: true };
|
|
806
|
+
}
|
|
807
|
+
const idx = labels.indexOf(picked);
|
|
808
|
+
if (idx === q.options.length || idx < 0) {
|
|
809
|
+
const typed = await ctx.ui.input(q.question, "");
|
|
810
|
+
if (typed === undefined || !typed.trim()) {
|
|
811
|
+
return { answers, cancelled: true };
|
|
812
|
+
}
|
|
813
|
+
answers.push({
|
|
814
|
+
questionIndex: i,
|
|
815
|
+
question: q.question,
|
|
816
|
+
kind: q.multiSelect ? "multi" : "custom",
|
|
817
|
+
...(q.multiSelect ? { selected: [] } : {}),
|
|
818
|
+
answer: typed.trim(),
|
|
819
|
+
});
|
|
820
|
+
} else {
|
|
821
|
+
const opt = q.options[idx]!;
|
|
822
|
+
answers.push({
|
|
823
|
+
questionIndex: i,
|
|
824
|
+
question: q.question,
|
|
825
|
+
kind: q.multiSelect ? "multi" : "option",
|
|
826
|
+
...(q.multiSelect ? { selected: [opt.label], answer: null } : { answer: opt.label }),
|
|
827
|
+
...(!q.multiSelect && opt.preview ? { preview: opt.preview } : {}),
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
return { answers, cancelled: false };
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** Run the interactive or RPC questionnaire for the given questions and return the enriched result. */
|
|
835
|
+
export async function openAskQuestionsDialog(
|
|
836
|
+
ctx: ExtensionContext,
|
|
837
|
+
questions: readonly QuestionData[],
|
|
838
|
+
opts: { delegatedLabel?: string } = {},
|
|
839
|
+
): Promise<QuestionnaireResult | undefined> {
|
|
840
|
+
const mode = (ctx as { mode?: string }).mode;
|
|
841
|
+
if (mode === "rpc" && typeof ctx.ui.select === "function") {
|
|
842
|
+
return runRpcFallback(ctx, questions);
|
|
843
|
+
}
|
|
844
|
+
if (typeof ctx.ui.custom === "function") {
|
|
845
|
+
let result = await ctx.ui.custom<QuestionnaireResult>(
|
|
846
|
+
(tui: TUI, theme: Theme, _kb, done) =>
|
|
847
|
+
new AskUserDialog(theme, questions, {
|
|
848
|
+
delegatedLabel: opts.delegatedLabel,
|
|
849
|
+
thinkingLevel: ctx.thinkingLevel,
|
|
850
|
+
onDone: done,
|
|
851
|
+
requestRender: () => tui.requestRender(),
|
|
852
|
+
}),
|
|
853
|
+
);
|
|
854
|
+
if (result === undefined && typeof ctx.ui.select === "function") {
|
|
855
|
+
result = await runRpcFallback(ctx, questions);
|
|
856
|
+
}
|
|
857
|
+
return result;
|
|
858
|
+
}
|
|
859
|
+
if (typeof ctx.ui.select === "function") {
|
|
860
|
+
return runRpcFallback(ctx, questions);
|
|
861
|
+
}
|
|
862
|
+
return undefined;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** Format manual `/ask` interview answers into a concise user message for the active agent. */
|
|
866
|
+
export function formatInterviewPrompt(topic: string, result: QuestionnaireResult): string {
|
|
867
|
+
const lines = result.answers
|
|
868
|
+
.map((a) => {
|
|
869
|
+
const value = formatAnswerValue(a);
|
|
870
|
+
if (!value) return null;
|
|
871
|
+
const preview = a.preview ? `\n Selected preview:\n${a.preview.split("\n").map((l) => ` ${l}`).join("\n")}` : "";
|
|
872
|
+
return `- **${a.question}** ${value}${preview}`;
|
|
873
|
+
})
|
|
874
|
+
.filter((line): line is string => line !== null);
|
|
875
|
+
return `Clarified requirements for "${topic}":\n${lines.join("\n")}\n\nProceed using these decisions.`;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
/** Manual `/ask [topic]` command handler: authors structured questions via the configured
|
|
879
|
+
* question model (or active session model as fallback) and feeds answers into the chat. */
|
|
880
|
+
export async function runAskCommand(
|
|
881
|
+
pi: Pick<ExtensionAPI, "sendUserMessage">,
|
|
882
|
+
args: string,
|
|
883
|
+
ctx: ExtensionCommandContext,
|
|
884
|
+
): Promise<void> {
|
|
885
|
+
if (!ctx.hasUI) {
|
|
886
|
+
ctx.ui.notify?.("[arnative] /ask requires an interactive UI.", "error");
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
const configured = activeAskModel();
|
|
891
|
+
const activeSpec = ctx.model?.provider && ctx.model?.id ? `${ctx.model.provider}/${ctx.model.id}` : "";
|
|
892
|
+
const targetModel = configured || activeSpec;
|
|
893
|
+
if (!targetModel) {
|
|
894
|
+
ctx.ui.notify?.("[arnative] No active or configured Ask model available.", "error");
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
let topic = args.trim();
|
|
899
|
+
if (!topic) {
|
|
900
|
+
const entered = ctx.mode !== "tui" && typeof ctx.ui.input === "function"
|
|
901
|
+
? await ctx.ui.input(`Ask (${targetModel})`, "")
|
|
902
|
+
: typeof ctx.ui.custom === "function"
|
|
903
|
+
? await ctx.ui.custom<string | null>((tui, theme, _kb, done) =>
|
|
904
|
+
new InputPicker(
|
|
905
|
+
theme,
|
|
906
|
+
{
|
|
907
|
+
title: screenTitle("Ask"),
|
|
908
|
+
description: `Topic or requirements to clarify via ${targetModel}.`,
|
|
909
|
+
legend: INPUT_LEGEND,
|
|
910
|
+
},
|
|
911
|
+
"",
|
|
912
|
+
{
|
|
913
|
+
done: (v) => done(v),
|
|
914
|
+
cancel: () => done(null),
|
|
915
|
+
requestRender: () => tui.requestRender(),
|
|
916
|
+
},
|
|
917
|
+
"e.g. Add caching to the API client",
|
|
918
|
+
ctx.thinkingLevel,
|
|
919
|
+
),
|
|
920
|
+
)
|
|
921
|
+
: null;
|
|
922
|
+
if (!entered || !entered.trim()) return;
|
|
923
|
+
topic = entered.trim();
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
const resolved = await resolveQuestions(
|
|
927
|
+
{ goal: topic, ambiguities: [topic] },
|
|
928
|
+
ctx,
|
|
929
|
+
undefined,
|
|
930
|
+
{ mode: "Hybrid", modelSpec: targetModel },
|
|
931
|
+
);
|
|
932
|
+
if ("error" in resolved) {
|
|
933
|
+
ctx.ui.notify?.(`[arnative] ${resolved.message}`, "error");
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
const { questions, delegatedModel, delegatedAction } = resolved;
|
|
938
|
+
const delegatedLabel = delegatedModel && delegatedAction && delegatedAction !== "fallback"
|
|
939
|
+
? `${delegatedModel} (${delegatedAction})`
|
|
940
|
+
: undefined;
|
|
941
|
+
|
|
942
|
+
emitTerminalBell();
|
|
943
|
+
const result = await openAskQuestionsDialog(ctx, questions, { delegatedLabel });
|
|
944
|
+
if (!result) {
|
|
945
|
+
ctx.ui.notify?.("[arnative] This host cannot render the Ask dialog.", "error");
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
if (result.cancelled || result.answers.length === 0) {
|
|
949
|
+
ctx.ui.notify?.("[arnative] Ask interview cancelled.", "info");
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
pi.sendUserMessage(formatInterviewPrompt(topic, result));
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// ---------------------------------------------------------------------------
|
|
957
|
+
// Reconciler & tool registration
|
|
958
|
+
// ---------------------------------------------------------------------------
|
|
959
|
+
|
|
960
|
+
export function reconcileAskTool(pi: ExtensionAPI, ctx: ExtensionContext): void {
|
|
961
|
+
if (typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") return;
|
|
962
|
+
const active = pi.getActiveTools();
|
|
963
|
+
const hasTool = active.includes(ASK_TOOL_NAME);
|
|
964
|
+
if (!ctx.hasUI && hasTool) {
|
|
965
|
+
pi.setActiveTools(active.filter((n) => n !== ASK_TOOL_NAME));
|
|
966
|
+
} else if (ctx.hasUI && !hasTool) {
|
|
967
|
+
pi.setActiveTools([...active, ASK_TOOL_NAME]);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
export default function registerAskUser(pi: ExtensionAPI): void {
|
|
972
|
+
pi.registerTool({
|
|
973
|
+
name: ASK_TOOL_NAME,
|
|
974
|
+
label: "Ask User Question",
|
|
975
|
+
description: ASK_TOOL_DESCRIPTION,
|
|
976
|
+
promptSnippet: ASK_PROMPT_SNIPPET,
|
|
977
|
+
promptGuidelines: ASK_PROMPT_GUIDELINES,
|
|
978
|
+
parameters: AskUserParamsSchema,
|
|
979
|
+
prepareArguments: prepareAskArguments,
|
|
980
|
+
|
|
981
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
982
|
+
if (!ctx.hasUI) {
|
|
983
|
+
return {
|
|
984
|
+
content: [{ type: "text" as const, text: "Error: UI not available (non-interactive mode)." }],
|
|
985
|
+
details: { answers: [], cancelled: true, error: "no_ui" } satisfies QuestionnaireResult,
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
const resolved = await resolveQuestions(params as unknown as AskUserParams, ctx, signal);
|
|
990
|
+
if ("error" in resolved) {
|
|
991
|
+
return {
|
|
992
|
+
content: [{ type: "text" as const, text: resolved.message }],
|
|
993
|
+
details: { answers: [], cancelled: true, error: resolved.error } satisfies QuestionnaireResult,
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const { questions, delegatedModel, delegatedAction, fallbackReason } = resolved;
|
|
998
|
+
if (fallbackReason) {
|
|
999
|
+
ctx.ui.notify?.(`[arnative] Ask model fallback (${fallbackReason}) — using drafted questions.`, "warning");
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
const delegatedLabel = delegatedModel && delegatedAction && delegatedAction !== "fallback"
|
|
1003
|
+
? `${delegatedModel} (${delegatedAction})`
|
|
1004
|
+
: undefined;
|
|
1005
|
+
|
|
1006
|
+
emitTerminalBell();
|
|
1007
|
+
const result = await openAskQuestionsDialog(ctx, questions, { delegatedLabel });
|
|
1008
|
+
|
|
1009
|
+
if (!result) {
|
|
1010
|
+
return {
|
|
1011
|
+
content: [
|
|
1012
|
+
{
|
|
1013
|
+
type: "text" as const,
|
|
1014
|
+
text: "Error: This host cannot render the questionnaire dialog. Ask the questions as plain chat text instead.",
|
|
1015
|
+
},
|
|
1016
|
+
],
|
|
1017
|
+
details: { answers: [], cancelled: true, error: "no_custom_ui" } satisfies QuestionnaireResult,
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
const enriched: QuestionnaireResult = {
|
|
1022
|
+
...result,
|
|
1023
|
+
...(delegatedModel ? { delegatedModel } : {}),
|
|
1024
|
+
...(delegatedAction ? { delegatedAction } : {}),
|
|
1025
|
+
};
|
|
1026
|
+
return buildQuestionnaireResponse(enriched, questions);
|
|
1027
|
+
},
|
|
1028
|
+
});
|
|
1029
|
+
|
|
1030
|
+
pi.registerCommand("ask", {
|
|
1031
|
+
description: "Clarify requirements with the configured question model (/ask [topic])",
|
|
1032
|
+
handler: (args, ctx) => runAskCommand(pi, args, ctx),
|
|
1033
|
+
});
|
|
1034
|
+
|
|
1035
|
+
pi.on("before_agent_start", (_event, ctx) => reconcileAskTool(pi, ctx));
|
|
1036
|
+
}
|