pi-querit 1.0.3 → 1.1.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.
package/src/setup.ts CHANGED
@@ -1,514 +1,330 @@
1
- import { getSupportedThinkingLevels } from "@earendil-works/pi-ai/compat";
2
- import { DynamicBorder, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
- import {
4
- Container,
5
- Input,
6
- SelectList,
7
- Spacer,
8
- Text,
9
- fuzzyFilter,
10
- getKeybindings,
11
- type Component,
12
- type Focusable,
13
- type SelectItem,
14
- type SelectListTheme,
15
- type TUI,
16
- } from "@earendil-works/pi-tui";
17
- import {
18
- COUNTRY_VALUES,
19
- LANGUAGE_VALUES,
20
- type QueritConfig,
21
- type QueritCountry,
22
- type QueritLanguage,
23
- type QueritSearchDefaults,
24
- type QueritThinkingLevel,
25
- type SearchWorkflow,
26
- } from "./config.js";
27
-
28
- /**
29
- * Masks the API key during rendering by temporarily swapping the Input value
30
- * with asterisks. Safe because pi-tui's Input.setValue is a pure field
31
- * assignment (no callbacks) and Input.render is a pure computation.
32
- */
33
- class MaskedInput extends Input {
34
- override render(width: number): string[] {
35
- const secret = this.getValue();
36
- this.setValue("*".repeat(secret.length));
37
- try {
38
- return super.render(width);
39
- } finally {
40
- this.setValue(secret);
41
- }
42
- }
43
- }
44
-
45
- export async function promptForApiKey(ctx: ExtensionCommandContext): Promise<string | undefined> {
46
- if (ctx.mode !== "tui") {
47
- ctx.ui.notify("/querit-setup requires Pi's interactive TUI.", "error");
48
- return undefined;
49
- }
50
-
51
- return ctx.ui.custom<string | undefined>((tui, theme, _keybindings, done) => {
52
- const container = new Container();
53
- const input = new MaskedInput();
54
- input.onSubmit = (value) => done(value.trim() || undefined);
55
- input.onEscape = () => done(undefined);
56
-
57
- container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
58
- container.addChild(new Spacer(1));
59
- container.addChild(new Text(theme.fg("accent", theme.bold("Configure Querit")), 1, 0));
60
- container.addChild(new Text("Enter your Querit API key. Input is masked and is not added to chat history.", 1, 0));
61
- container.addChild(new Spacer(1));
62
- container.addChild(input);
63
- container.addChild(new Spacer(1));
64
- container.addChild(new Text(theme.fg("dim", "Enter to validate and continue • Esc to cancel"), 1, 0));
65
- container.addChild(new Spacer(1));
66
- container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
67
-
68
- return new FocusableContainer(container, input, tui);
69
- });
70
- }
71
-
72
- export interface SummarySetupSelection {
73
- defaultWorkflow: SearchWorkflow;
74
- summaryModel?: string;
75
- summaryThinkingLevel?: QueritThinkingLevel;
76
- }
77
-
78
- export async function promptForSummarySettings(
79
- ctx: ExtensionCommandContext,
80
- ): Promise<SummarySetupSelection | undefined> {
81
- if (ctx.mode !== "tui") return { defaultWorkflow: "raw" };
82
-
83
- const workflowChoice = await ctx.ui.select("Default Querit search workflow", [
84
- "Raw results (recommended)",
85
- "Auto-summary before returning results",
86
- ]);
87
- if (!workflowChoice) return undefined;
88
- const defaultWorkflow: SearchWorkflow = workflowChoice.startsWith("Auto-summary") ? "summary" : "raw";
89
-
90
- if (defaultWorkflow === "raw") return { defaultWorkflow: "raw" };
91
-
92
- const availableModels = ctx.scopedModels.length > 0
93
- ? ctx.scopedModels.map((entry) => entry.model)
94
- : ctx.modelRegistry.getAvailable();
95
- const modelReferences = new Set<string>();
96
- if (ctx.model) modelReferences.add(`${ctx.model.provider}/${ctx.model.id}`);
97
- for (const model of availableModels) modelReferences.add(`${model.provider}/${model.id}`);
98
-
99
- if (modelReferences.size === 0) {
100
- ctx.ui.notify("No Pi model is currently available for Querit summaries. Raw mode will still work.", "warning");
101
- return { defaultWorkflow: "raw" };
102
- }
103
-
104
- const summaryModel = await promptForModelPicker(
105
- ctx,
106
- "Fixed model for optional Querit summaries",
107
- [...modelReferences],
108
- );
109
- if (!summaryModel) return undefined;
110
-
111
- const thinkingLevel = await promptForSummaryThinkingLevel(ctx, summaryModel);
112
- if (thinkingLevel.cancelled) return undefined;
113
- return {
114
- defaultWorkflow,
115
- summaryModel,
116
- ...(thinkingLevel.level === undefined ? {} : { summaryThinkingLevel: thinkingLevel.level }),
117
- };
118
- }
119
-
120
- interface ThinkingLevelPromptResult {
121
- cancelled: boolean;
122
- level?: QueritThinkingLevel;
123
- }
124
-
125
- async function promptForSummaryThinkingLevel(
126
- ctx: ExtensionCommandContext,
127
- modelReference: string,
128
- ): Promise<ThinkingLevelPromptResult> {
129
- const slash = modelReference.indexOf("/");
130
- const model = ctx.modelRegistry.find(modelReference.slice(0, slash), modelReference.slice(slash + 1));
131
- if (!model || !model.reasoning) return { cancelled: false };
132
-
133
- const levels = getSupportedThinkingLevels(model);
134
- if (levels.length === 0) return { cancelled: false };
135
- const recommended = levels.includes("medium") ? "medium" : levels.find((level) => level !== "off") ?? "off";
136
- const options = levels.map((level) => (level === recommended ? `${level} (recommended)` : level));
137
-
138
- const choice = await ctx.ui.select(`Thinking intensity for ${modelReference} summaries`, options);
139
- if (choice === undefined) return { cancelled: true };
140
- const level = levels.find(
141
- (candidate) => (candidate === recommended ? `${candidate} (recommended)` : candidate) === choice,
142
- );
143
- return level === undefined ? { cancelled: false } : { cancelled: false, level: level as QueritThinkingLevel };
144
- }
145
-
146
- const MODEL_PICKER_VISIBLE_ROWS = 5;
147
-
148
- function promptForModelPicker(
149
- ctx: ExtensionCommandContext,
150
- title: string,
151
- models: string[],
152
- ): Promise<string | undefined> {
153
- const items: SelectItem[] = models.map((value) => ({ value, label: value }));
154
- return ctx.ui.custom<string | undefined>((tui, theme, _keybindings, done) => {
155
- const listTheme: SelectListTheme = {
156
- selectedPrefix: (text) => theme.fg("accent", text),
157
- selectedText: (text) => theme.fg("accent", theme.bold(text)),
158
- description: (text) => theme.fg("dim", text),
159
- scrollInfo: (text) => theme.fg("dim", text),
160
- noMatch: (text) => theme.fg("dim", text),
161
- };
162
- const header: Component[] = [
163
- new DynamicBorder((text: string) => theme.fg("accent", text)),
164
- new Spacer(1),
165
- new Text(theme.fg("accent", theme.bold(title)), 1, 0),
166
- new Text(theme.fg("dim", "Type to filter • Up/Down to move • Enter to select • Esc to cancel"), 1, 0),
167
- new Spacer(1),
168
- ];
169
- const footer: Component[] = [
170
- new Spacer(1),
171
- new DynamicBorder((text: string) => theme.fg("accent", text)),
172
- ];
173
- return new ModelPicker(items, listTheme, header, footer, tui, (value) => done(value), () => done(undefined));
174
- });
175
- }
176
-
177
- class ModelPicker implements Focusable {
178
- private _focused = false;
179
- private list: SelectList;
180
- private readonly input = new Input();
181
-
182
- constructor(
183
- private readonly items: SelectItem[],
184
- private readonly listTheme: SelectListTheme,
185
- private readonly header: Component[],
186
- private readonly footer: Component[],
187
- private readonly tui: TUI,
188
- private readonly onSelect: (value: string) => void,
189
- private readonly onCancel: () => void,
190
- ) {
191
- this.list = this.buildList("");
192
- }
193
-
194
- private buildList(filter: string): SelectList {
195
- const query = filter.trim();
196
- const filtered = query ? fuzzyFilter(this.items, query, (item) => item.value) : this.items;
197
- const list = new SelectList(filtered, MODEL_PICKER_VISIBLE_ROWS, this.listTheme);
198
- list.onSelect = (item) => this.onSelect(item.value);
199
- list.onCancel = () => this.onCancel();
200
- return list;
201
- }
202
-
203
- get focused(): boolean {
204
- return this._focused;
205
- }
206
-
207
- set focused(value: boolean) {
208
- this._focused = value;
209
- this.input.focused = value;
210
- }
211
-
212
- render(width: number): string[] {
213
- const lines: string[] = [];
214
- for (const component of this.header) lines.push(...component.render(width));
215
- lines.push(...this.input.render(width));
216
- lines.push(...this.list.render(width));
217
- for (const component of this.footer) lines.push(...component.render(width));
218
- return lines;
219
- }
220
-
221
- handleInput(data: string): void {
222
- const keybindings = getKeybindings();
223
- if (
224
- keybindings.matches(data, "tui.select.up") ||
225
- keybindings.matches(data, "tui.select.down") ||
226
- keybindings.matches(data, "tui.select.confirm") ||
227
- keybindings.matches(data, "tui.select.cancel")
228
- ) {
229
- this.list.handleInput(data);
230
- } else {
231
- this.input.handleInput(data);
232
- this.list = this.buildList(this.input.getValue());
233
- }
234
- this.tui.requestRender();
235
- }
236
-
237
- invalidate(): void {
238
- this.input.invalidate();
239
- this.list.invalidate();
240
- for (const component of [...this.header, ...this.footer]) component.invalidate();
241
- }
242
- }
243
-
244
- export type SetupMode = "replace-key" | "search-defaults" | "summary-settings";
245
-
246
- export function maskApiKeyHint(apiKey: string): string {
247
- const trimmed = apiKey.trim();
248
- return trimmed.length <= 4 ? "****" : `…${trimmed.slice(-4)}`;
249
- }
250
-
251
- export async function promptForSetupMode(
252
- ctx: ExtensionCommandContext,
253
- config: QueritConfig,
254
- ): Promise<SetupMode | undefined> {
255
- if (ctx.mode !== "tui") {
256
- ctx.ui.notify("/querit-setup requires Pi's interactive TUI.", "error");
257
- return undefined;
258
- }
259
-
260
- const choice = await ctx.ui.select(
261
- `Querit is already configured (API key ${maskApiKeyHint(config.apiKey)}). What would you like to change?`,
262
- [
263
- "Replace API key (full re-setup)",
264
- "Change search defaults",
265
- "Change summary settings",
266
- ],
267
- );
268
- if (!choice) return undefined;
269
- if (choice.startsWith("Replace")) return "replace-key";
270
- if (choice.startsWith("Change search")) return "search-defaults";
271
- return "summary-settings";
272
- }
273
-
274
- export async function promptForSearchDefaults(
275
- ctx: ExtensionCommandContext,
276
- current: QueritSearchDefaults = {},
277
- ): Promise<QueritSearchDefaults | undefined> {
278
- if (ctx.mode !== "tui") return {};
279
-
280
- const next: QueritSearchDefaults = { ...current };
281
-
282
- const countChoice = await ctx.ui.select(
283
- "Default result count per search",
284
- scalarOptions(current.count === undefined ? undefined : String(current.count), ["3", "5", "10", "20"]),
285
- );
286
- if (countChoice === undefined) return undefined;
287
- if (isResetChoice(countChoice)) delete next.count;
288
- else if (!isKeepChoice(countChoice)) {
289
- const parsed = Number.parseInt(countChoice, 10);
290
- if (Number.isInteger(parsed) && parsed >= 1 && parsed <= 20) next.count = parsed;
291
- }
292
-
293
- const timeChoice = await ctx.ui.select(
294
- "Default time range filter",
295
- scalarOptions(current.timeRange, [
296
- "d7 (past 7 days)",
297
- "w2 (past 2 weeks)",
298
- "m3 (past 3 months)",
299
- "y1 (past year)",
300
- ]),
301
- );
302
- if (timeChoice === undefined) return undefined;
303
- if (isResetChoice(timeChoice)) delete next.timeRange;
304
- else if (!isKeepChoice(timeChoice)) next.timeRange = timeChoice.split(" ", 1)[0];
305
-
306
- const contentChoice = await ctx.ui.select(
307
- "Include sentence-level content excerpts by default?",
308
- scalarOptions(
309
- current.includeContent === undefined ? undefined : current.includeContent ? "yes" : "no",
310
- ["Yes, include excerpts", "No, snippets only"],
311
- ),
312
- );
313
- if (contentChoice === undefined) return undefined;
314
- if (isResetChoice(contentChoice)) delete next.includeContent;
315
- else if (!isKeepChoice(contentChoice)) next.includeContent = contentChoice.startsWith("Yes");
316
-
317
- const countries = await promptForEnumList(ctx, {
318
- title: `Default countries filter${formatCurrentList(current.countries)}`,
319
- hint: `Comma-separated country names. Valid values: ${COUNTRY_VALUES.join(", ")}.`,
320
- allowed: COUNTRY_VALUES,
321
- });
322
- if (countries === undefined) return undefined;
323
- if (countries.cleared) delete next.countries;
324
- else if (countries.values !== undefined) next.countries = countries.values as QueritCountry[];
325
-
326
- const languages = await promptForEnumList(ctx, {
327
- title: `Default languages filter${formatCurrentList(current.languages)}`,
328
- hint: `Comma-separated language names. Valid values: ${LANGUAGE_VALUES.join(", ")}.`,
329
- allowed: LANGUAGE_VALUES,
330
- });
331
- if (languages === undefined) return undefined;
332
- if (languages.cleared) delete next.languages;
333
- else if (languages.values !== undefined) next.languages = languages.values as QueritLanguage[];
334
-
335
- const includeDomains = await promptForDomainChoice(ctx, {
336
- message: "Restrict results to specific domains? (include whitelist)",
337
- current: current.includeDomains,
338
- customTitle: "Include only these domains (whitelist)",
339
- customHint: "Only these domains will return results. Example: github.com, stackoverflow.com, developer.mozilla.org. Comma-separated; 'none' clears.",
340
- });
341
- if (includeDomains === undefined) return undefined;
342
- if (includeDomains.cleared) delete next.includeDomains;
343
- else if (includeDomains.values !== undefined) next.includeDomains = includeDomains.values;
344
- const excludeDomains = await promptForDomainChoice(ctx, {
345
- message: "Exclude specific domains from results? (blacklist)",
346
- current: current.excludeDomains,
347
- preset: EXCLUDE_DOMAIN_PRESET,
348
- customTitle: "Exclude these domains (blacklist)",
349
- customHint: "These domains will never return results. Comma-separated; 'none' clears.",
350
- });
351
- if (excludeDomains === undefined) return undefined;
352
- if (excludeDomains.cleared) delete next.excludeDomains;
353
- else if (excludeDomains.values !== undefined) next.excludeDomains = excludeDomains.values;
354
-
355
- return next;
356
- }
357
-
358
- const EXCLUDE_DOMAIN_PRESET = {
359
- label: "Noise blockers (pinterest.com, facebook.com, instagram.com, tiktok.com)",
360
- values: ["pinterest.com", "facebook.com", "instagram.com", "tiktok.com"],
361
- };
362
-
363
- interface ListPromptResult {
364
- cleared: boolean;
365
- values?: string[];
366
- }
367
-
368
- async function promptForEnumList(
369
- ctx: ExtensionCommandContext,
370
- options: { title: string; hint: string; allowed: readonly string[] },
371
- ): Promise<ListPromptResult | undefined> {
372
- for (;;) {
373
- const raw = await promptForPlainText(ctx, options.title, options.hint);
374
- if (raw === undefined) return undefined;
375
- const trimmed = raw.trim();
376
- if (trimmed === "") return { cleared: false };
377
- if (trimmed.toLowerCase() === "none") return { cleared: true };
378
- const values = splitList(trimmed);
379
- const invalid = values.filter((value) => !options.allowed.includes(value));
380
- if (invalid.length > 0) {
381
- ctx.ui.notify(`Unknown values: ${invalid.join(", ")}. ${options.hint}`, "error");
382
- continue;
383
- }
384
- return { cleared: false, values: [...new Set(values)] };
385
- }
386
- }
387
-
388
- async function promptForDomainList(
389
- ctx: ExtensionCommandContext,
390
- options: { title: string; hint: string },
391
- ): Promise<ListPromptResult | undefined> {
392
- for (;;) {
393
- const raw = await promptForPlainText(ctx, options.title, options.hint);
394
- if (raw === undefined) return undefined;
395
- const trimmed = raw.trim();
396
- if (trimmed === "") return { cleared: false };
397
- if (trimmed.toLowerCase() === "none") return { cleared: true };
398
- const values = splitList(trimmed);
399
- const invalid = values.filter((value) => value.length > 253 || /\s/u.test(value) || !value.includes("."));
400
- if (invalid.length > 0) {
401
- ctx.ui.notify(`Invalid domains: ${invalid.join(", ")}. ${options.hint}`, "error");
402
- continue;
403
- }
404
- return { cleared: false, values: [...new Set(values)] };
405
- }
406
- }
407
-
408
- async function promptForDomainChoice(
409
- ctx: ExtensionCommandContext,
410
- options: {
411
- message: string;
412
- current: string[] | undefined;
413
- preset?: { label: string; values: string[] };
414
- customTitle: string;
415
- customHint: string;
416
- },
417
- ): Promise<ListPromptResult | undefined> {
418
- const hasCurrent = options.current !== undefined && options.current.length > 0;
419
- const selectOptions: string[] = [];
420
- if (hasCurrent) {
421
- selectOptions.push(`Keep current (${options.current?.join(", ")})`);
422
- selectOptions.push("Reset (no domain filter)");
423
- } else {
424
- selectOptions.push("Skip (no domain filter)");
425
- }
426
- if (options.preset) selectOptions.push(options.preset.label);
427
- selectOptions.push("Enter a custom list…");
428
-
429
- const choice = await ctx.ui.select(options.message, selectOptions);
430
- if (choice === undefined) return undefined;
431
- if (isKeepChoice(choice)) return { cleared: false };
432
- if (isResetChoice(choice)) return { cleared: true };
433
- if (options.preset && choice === options.preset.label) {
434
- return { cleared: false, values: [...options.preset.values] };
435
- }
436
- return promptForDomainList(ctx, { title: options.customTitle, hint: options.customHint });
437
- }
438
- async function promptForPlainText(
439
- ctx: ExtensionCommandContext,
440
- title: string,
441
- hint: string,
442
- ): Promise<string | undefined> {
443
- return ctx.ui.custom<string | undefined>((tui, theme, _keybindings, done) => {
444
- const container = new Container();
445
- const input = new Input();
446
- input.onSubmit = (value) => done(value);
447
- input.onEscape = () => done(undefined);
448
-
449
- container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
450
- container.addChild(new Spacer(1));
451
- container.addChild(new Text(theme.fg("accent", theme.bold(title)), 1, 0));
452
- container.addChild(new Text(hint, 1, 0));
453
- container.addChild(new Spacer(1));
454
- container.addChild(input);
455
- container.addChild(new Spacer(1));
456
- container.addChild(new Text(theme.fg("dim", "Enter = keep • 'none' = clear • Esc = cancel setup"), 1, 0));
457
- container.addChild(new Spacer(1));
458
- container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
459
-
460
- return new FocusableContainer(container, input, tui);
461
- });
462
- }
463
-
464
- function scalarOptions(currentLabel: string | undefined, values: string[]): string[] {
465
- if (currentLabel === undefined) return ["Skip (use API default)", ...values];
466
- return [`Keep current (${currentLabel})`, "Reset to API default", ...values];
467
- }
468
-
469
- function isKeepChoice(choice: string): boolean {
470
- return choice.startsWith("Keep current");
471
- }
472
-
473
- function isResetChoice(choice: string): boolean {
474
- return choice.startsWith("Reset") || choice.startsWith("Skip");
475
- }
476
-
477
- function formatCurrentList(values: string[] | undefined): string {
478
- return values === undefined || values.length === 0 ? "" : ` (current: ${values.join(", ")})`;
479
- }
480
-
481
- function splitList(value: string): string[] {
482
- return value.split(",").map((entry) => entry.trim().toLowerCase()).filter((entry) => entry.length > 0);
483
- }
484
- class FocusableContainer implements Focusable {
485
- private _focused = false;
486
-
487
- constructor(
488
- private readonly container: Container,
489
- private readonly input: Input,
490
- private readonly tui: TUI,
491
- ) {}
492
-
493
- get focused(): boolean {
494
- return this._focused;
495
- }
496
-
497
- set focused(value: boolean) {
498
- this._focused = value;
499
- this.input.focused = value;
500
- }
501
-
502
- render(width: number): string[] {
503
- return this.container.render(width);
504
- }
505
-
506
- handleInput(data: string): void {
507
- this.input.handleInput(data);
508
- this.tui.requestRender();
509
- }
510
-
511
- invalidate(): void {
512
- this.container.invalidate();
513
- }
514
- }
1
+ import { DynamicBorder, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Container,
4
+ Input,
5
+ Spacer,
6
+ Text,
7
+ type Focusable,
8
+ type TUI,
9
+ } from "@earendil-works/pi-tui";
10
+ import {
11
+ COUNTRY_VALUES,
12
+ LANGUAGE_VALUES,
13
+ type QueritConfig,
14
+ type QueritCountry,
15
+ type QueritLanguage,
16
+ type QueritSearchDefaults,
17
+ } from "./config.js";
18
+
19
+ /**
20
+ * Masks the API key during rendering by temporarily swapping the Input value
21
+ * with asterisks. Safe because pi-tui's Input.setValue is a pure field
22
+ * assignment (no callbacks) and Input.render is a pure computation.
23
+ */
24
+ class MaskedInput extends Input {
25
+ override render(width: number): string[] {
26
+ const secret = this.getValue();
27
+ this.setValue("*".repeat(secret.length));
28
+ try {
29
+ return super.render(width);
30
+ } finally {
31
+ this.setValue(secret);
32
+ }
33
+ }
34
+ }
35
+
36
+ export async function promptForApiKey(ctx: ExtensionCommandContext): Promise<string | undefined> {
37
+ if (ctx.mode !== "tui") {
38
+ ctx.ui.notify("/querit-setup requires Pi's interactive TUI.", "error");
39
+ return undefined;
40
+ }
41
+
42
+ return ctx.ui.custom<string | undefined>((tui, theme, _keybindings, done) => {
43
+ const container = new Container();
44
+ const input = new MaskedInput();
45
+ input.onSubmit = (value) => done(value.trim() || undefined);
46
+ input.onEscape = () => done(undefined);
47
+
48
+ container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
49
+ container.addChild(new Spacer(1));
50
+ container.addChild(new Text(theme.fg("accent", theme.bold("Configure Querit")), 1, 0));
51
+ container.addChild(new Text("Enter your Querit API key. Input is masked and is not added to chat history.", 1, 0));
52
+ container.addChild(new Spacer(1));
53
+ container.addChild(input);
54
+ container.addChild(new Spacer(1));
55
+ container.addChild(new Text(theme.fg("dim", "Enter to validate and continue • Esc to cancel"), 1, 0));
56
+ container.addChild(new Spacer(1));
57
+ container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
58
+
59
+ return new FocusableContainer(container, input, tui);
60
+ });
61
+ }
62
+
63
+ export type SetupMode = "replace-key" | "search-defaults";
64
+
65
+ export function maskApiKeyHint(apiKey: string): string {
66
+ const trimmed = apiKey.trim();
67
+ return trimmed.length <= 4 ? "****" : `…${trimmed.slice(-4)}`;
68
+ }
69
+
70
+ export async function promptForSetupMode(
71
+ ctx: ExtensionCommandContext,
72
+ config: QueritConfig,
73
+ ): Promise<SetupMode | undefined> {
74
+ if (ctx.mode !== "tui") {
75
+ ctx.ui.notify("/querit-setup requires Pi's interactive TUI.", "error");
76
+ return undefined;
77
+ }
78
+
79
+ const choice = await ctx.ui.select(
80
+ `Querit is already configured (API key ${maskApiKeyHint(config.apiKey)}). What would you like to change?`,
81
+ [
82
+ "Replace API key (full re-setup)",
83
+ "Change search defaults",
84
+ ],
85
+ );
86
+ if (!choice) return undefined;
87
+ return choice.startsWith("Replace") ? "replace-key" : "search-defaults";
88
+ }
89
+
90
+ export async function promptForSearchDefaults(
91
+ ctx: ExtensionCommandContext,
92
+ current: QueritSearchDefaults = {},
93
+ ): Promise<QueritSearchDefaults | undefined> {
94
+ if (ctx.mode !== "tui") return {};
95
+
96
+ const next: QueritSearchDefaults = { ...current };
97
+
98
+ const countChoice = await ctx.ui.select(
99
+ "Default result count per search",
100
+ scalarOptions(current.count === undefined ? undefined : String(current.count), ["3", "5", "10", "20"]),
101
+ );
102
+ if (countChoice === undefined) return undefined;
103
+ if (isResetChoice(countChoice)) delete next.count;
104
+ else if (!isKeepChoice(countChoice)) {
105
+ const parsed = Number.parseInt(countChoice, 10);
106
+ if (Number.isInteger(parsed) && parsed >= 1 && parsed <= 20) next.count = parsed;
107
+ }
108
+
109
+ const timeChoice = await ctx.ui.select(
110
+ "Default time range filter",
111
+ scalarOptions(current.timeRange, [
112
+ "d7 (past 7 days)",
113
+ "w2 (past 2 weeks)",
114
+ "m3 (past 3 months)",
115
+ "y1 (past year)",
116
+ ]),
117
+ );
118
+ if (timeChoice === undefined) return undefined;
119
+ if (isResetChoice(timeChoice)) delete next.timeRange;
120
+ else if (!isKeepChoice(timeChoice)) next.timeRange = timeChoice.split(" ", 1)[0];
121
+
122
+ const contentChoice = await ctx.ui.select(
123
+ "Include sentence-level content excerpts by default?",
124
+ scalarOptions(
125
+ current.includeContent === undefined ? undefined : current.includeContent ? "yes" : "no",
126
+ ["Yes, include excerpts", "No, snippets only"],
127
+ ),
128
+ );
129
+ if (contentChoice === undefined) return undefined;
130
+ if (isResetChoice(contentChoice)) delete next.includeContent;
131
+ else if (!isKeepChoice(contentChoice)) next.includeContent = contentChoice.startsWith("Yes");
132
+
133
+ const countries = await promptForEnumList(ctx, {
134
+ title: `Default countries filter${formatCurrentList(current.countries)}`,
135
+ hint: `Comma-separated country names. Valid values: ${COUNTRY_VALUES.join(", ")}.`,
136
+ allowed: COUNTRY_VALUES,
137
+ });
138
+ if (countries === undefined) return undefined;
139
+ if (countries.cleared) delete next.countries;
140
+ else if (countries.values !== undefined) next.countries = countries.values as QueritCountry[];
141
+
142
+ const languages = await promptForEnumList(ctx, {
143
+ title: `Default languages filter${formatCurrentList(current.languages)}`,
144
+ hint: `Comma-separated language names. Valid values: ${LANGUAGE_VALUES.join(", ")}.`,
145
+ allowed: LANGUAGE_VALUES,
146
+ });
147
+ if (languages === undefined) return undefined;
148
+ if (languages.cleared) delete next.languages;
149
+ else if (languages.values !== undefined) next.languages = languages.values as QueritLanguage[];
150
+
151
+ const includeDomains = await promptForDomainChoice(ctx, {
152
+ message: "Restrict results to specific domains? (include whitelist)",
153
+ current: current.includeDomains,
154
+ customTitle: "Include only these domains (whitelist)",
155
+ customHint: "Only these domains will return results. Example: github.com, stackoverflow.com, developer.mozilla.org. Comma-separated; 'none' clears.",
156
+ });
157
+ if (includeDomains === undefined) return undefined;
158
+ if (includeDomains.cleared) delete next.includeDomains;
159
+ else if (includeDomains.values !== undefined) next.includeDomains = includeDomains.values;
160
+ const excludeDomains = await promptForDomainChoice(ctx, {
161
+ message: "Exclude specific domains from results? (blacklist)",
162
+ current: current.excludeDomains,
163
+ preset: EXCLUDE_DOMAIN_PRESET,
164
+ customTitle: "Exclude these domains (blacklist)",
165
+ customHint: "These domains will never return results. Comma-separated; 'none' clears.",
166
+ });
167
+ if (excludeDomains === undefined) return undefined;
168
+ if (excludeDomains.cleared) delete next.excludeDomains;
169
+ else if (excludeDomains.values !== undefined) next.excludeDomains = excludeDomains.values;
170
+
171
+ return next;
172
+ }
173
+
174
+ const EXCLUDE_DOMAIN_PRESET = {
175
+ label: "Noise blockers (pinterest.com, facebook.com, instagram.com, tiktok.com)",
176
+ values: ["pinterest.com", "facebook.com", "instagram.com", "tiktok.com"],
177
+ };
178
+
179
+ interface ListPromptResult {
180
+ cleared: boolean;
181
+ values?: string[];
182
+ }
183
+
184
+ async function promptForEnumList(
185
+ ctx: ExtensionCommandContext,
186
+ options: { title: string; hint: string; allowed: readonly string[] },
187
+ ): Promise<ListPromptResult | undefined> {
188
+ for (;;) {
189
+ const raw = await promptForPlainText(ctx, options.title, options.hint);
190
+ if (raw === undefined) return undefined;
191
+ const trimmed = raw.trim();
192
+ if (trimmed === "") return { cleared: false };
193
+ if (trimmed.toLowerCase() === "none") return { cleared: true };
194
+ const values = splitList(trimmed);
195
+ const invalid = values.filter((value) => !options.allowed.includes(value));
196
+ if (invalid.length > 0) {
197
+ ctx.ui.notify(`Unknown values: ${invalid.join(", ")}. ${options.hint}`, "error");
198
+ continue;
199
+ }
200
+ return { cleared: false, values: [...new Set(values)] };
201
+ }
202
+ }
203
+
204
+ async function promptForDomainList(
205
+ ctx: ExtensionCommandContext,
206
+ options: { title: string; hint: string },
207
+ ): Promise<ListPromptResult | undefined> {
208
+ for (;;) {
209
+ const raw = await promptForPlainText(ctx, options.title, options.hint);
210
+ if (raw === undefined) return undefined;
211
+ const trimmed = raw.trim();
212
+ if (trimmed === "") return { cleared: false };
213
+ if (trimmed.toLowerCase() === "none") return { cleared: true };
214
+ const values = splitList(trimmed);
215
+ const invalid = values.filter((value) => value.length > 253 || /\s/u.test(value) || !value.includes("."));
216
+ if (invalid.length > 0) {
217
+ ctx.ui.notify(`Invalid domains: ${invalid.join(", ")}. ${options.hint}`, "error");
218
+ continue;
219
+ }
220
+ return { cleared: false, values: [...new Set(values)] };
221
+ }
222
+ }
223
+
224
+ async function promptForDomainChoice(
225
+ ctx: ExtensionCommandContext,
226
+ options: {
227
+ message: string;
228
+ current: string[] | undefined;
229
+ preset?: { label: string; values: string[] };
230
+ customTitle: string;
231
+ customHint: string;
232
+ },
233
+ ): Promise<ListPromptResult | undefined> {
234
+ const hasCurrent = options.current !== undefined && options.current.length > 0;
235
+ const selectOptions: string[] = [];
236
+ if (hasCurrent) {
237
+ selectOptions.push(`Keep current (${options.current?.join(", ")})`);
238
+ selectOptions.push("Reset (no domain filter)");
239
+ } else {
240
+ selectOptions.push("Skip (no domain filter)");
241
+ }
242
+ if (options.preset) selectOptions.push(options.preset.label);
243
+ selectOptions.push("Enter a custom list…");
244
+
245
+ const choice = await ctx.ui.select(options.message, selectOptions);
246
+ if (choice === undefined) return undefined;
247
+ if (isKeepChoice(choice)) return { cleared: false };
248
+ if (isResetChoice(choice)) return { cleared: true };
249
+ if (options.preset && choice === options.preset.label) {
250
+ return { cleared: false, values: [...options.preset.values] };
251
+ }
252
+ return promptForDomainList(ctx, { title: options.customTitle, hint: options.customHint });
253
+ }
254
+ async function promptForPlainText(
255
+ ctx: ExtensionCommandContext,
256
+ title: string,
257
+ hint: string,
258
+ ): Promise<string | undefined> {
259
+ return ctx.ui.custom<string | undefined>((tui, theme, _keybindings, done) => {
260
+ const container = new Container();
261
+ const input = new Input();
262
+ input.onSubmit = (value) => done(value);
263
+ input.onEscape = () => done(undefined);
264
+
265
+ container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
266
+ container.addChild(new Spacer(1));
267
+ container.addChild(new Text(theme.fg("accent", theme.bold(title)), 1, 0));
268
+ container.addChild(new Text(hint, 1, 0));
269
+ container.addChild(new Spacer(1));
270
+ container.addChild(input);
271
+ container.addChild(new Spacer(1));
272
+ container.addChild(new Text(theme.fg("dim", "Enter = keep • 'none' = clear • Esc = cancel setup"), 1, 0));
273
+ container.addChild(new Spacer(1));
274
+ container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
275
+
276
+ return new FocusableContainer(container, input, tui);
277
+ });
278
+ }
279
+
280
+ function scalarOptions(currentLabel: string | undefined, values: string[]): string[] {
281
+ if (currentLabel === undefined) return ["Skip (use API default)", ...values];
282
+ return [`Keep current (${currentLabel})`, "Reset to API default", ...values];
283
+ }
284
+
285
+ function isKeepChoice(choice: string): boolean {
286
+ return choice.startsWith("Keep current");
287
+ }
288
+
289
+ function isResetChoice(choice: string): boolean {
290
+ return choice.startsWith("Reset") || choice.startsWith("Skip");
291
+ }
292
+
293
+ function formatCurrentList(values: string[] | undefined): string {
294
+ return values === undefined || values.length === 0 ? "" : ` (current: ${values.join(", ")})`;
295
+ }
296
+
297
+ function splitList(value: string): string[] {
298
+ return value.split(",").map((entry) => entry.trim().toLowerCase()).filter((entry) => entry.length > 0);
299
+ }
300
+ class FocusableContainer implements Focusable {
301
+ private _focused = false;
302
+
303
+ constructor(
304
+ private readonly container: Container,
305
+ private readonly input: Input,
306
+ private readonly tui: TUI,
307
+ ) {}
308
+
309
+ get focused(): boolean {
310
+ return this._focused;
311
+ }
312
+
313
+ set focused(value: boolean) {
314
+ this._focused = value;
315
+ this.input.focused = value;
316
+ }
317
+
318
+ render(width: number): string[] {
319
+ return this.container.render(width);
320
+ }
321
+
322
+ handleInput(data: string): void {
323
+ this.input.handleInput(data);
324
+ this.tui.requestRender();
325
+ }
326
+
327
+ invalidate(): void {
328
+ this.container.invalidate();
329
+ }
330
+ }