@f5xc-salesdemos/pi-tui 14.0.3

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.
@@ -0,0 +1,787 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import type { SearchDb } from "@f5xc-salesdemos/pi-natives";
5
+ import { fuzzyFind } from "@f5xc-salesdemos/pi-natives";
6
+ import { getProjectDir } from "@f5xc-salesdemos/pi-utils";
7
+
8
+ const PATH_DELIMITERS = new Set([" ", "\t", '"', "'", "="]);
9
+
10
+ function buildAutocompleteFuzzyDiscoveryProfile(
11
+ query: string,
12
+ basePath: string,
13
+ ): {
14
+ query: string;
15
+ path: string;
16
+ maxResults: number;
17
+ hidden: boolean;
18
+ gitignore: boolean;
19
+ cache: boolean;
20
+ } {
21
+ return {
22
+ query,
23
+ path: basePath,
24
+ maxResults: 100,
25
+ hidden: true,
26
+ gitignore: true,
27
+ cache: true,
28
+ };
29
+ }
30
+
31
+ function findLastDelimiter(text: string): number {
32
+ for (let i = text.length - 1; i >= 0; i -= 1) {
33
+ if (PATH_DELIMITERS.has(text[i] ?? "")) {
34
+ return i;
35
+ }
36
+ }
37
+ return -1;
38
+ }
39
+
40
+ function findUnclosedQuoteStart(text: string): number | null {
41
+ let inQuotes = false;
42
+ let quoteStart = -1;
43
+
44
+ for (let i = 0; i < text.length; i += 1) {
45
+ if (text[i] === '"') {
46
+ inQuotes = !inQuotes;
47
+ if (inQuotes) {
48
+ quoteStart = i;
49
+ }
50
+ }
51
+ }
52
+
53
+ return inQuotes ? quoteStart : null;
54
+ }
55
+
56
+ function isTokenStart(text: string, index: number): boolean {
57
+ return index === 0 || PATH_DELIMITERS.has(text[index - 1] ?? "");
58
+ }
59
+
60
+ function extractQuotedPrefix(text: string): string | null {
61
+ const quoteStart = findUnclosedQuoteStart(text);
62
+ if (quoteStart === null) {
63
+ return null;
64
+ }
65
+
66
+ if (quoteStart > 0 && text[quoteStart - 1] === "@") {
67
+ if (!isTokenStart(text, quoteStart - 1)) {
68
+ return null;
69
+ }
70
+ return text.slice(quoteStart - 1);
71
+ }
72
+
73
+ if (!isTokenStart(text, quoteStart)) {
74
+ return null;
75
+ }
76
+
77
+ return text.slice(quoteStart);
78
+ }
79
+
80
+ function parsePathPrefix(prefix: string): { rawPrefix: string; isAtPrefix: boolean; isQuotedPrefix: boolean } {
81
+ if (prefix.startsWith('@"')) {
82
+ return { rawPrefix: prefix.slice(2), isAtPrefix: true, isQuotedPrefix: true };
83
+ }
84
+ if (prefix.startsWith('"')) {
85
+ return { rawPrefix: prefix.slice(1), isAtPrefix: false, isQuotedPrefix: true };
86
+ }
87
+ if (prefix.startsWith("@")) {
88
+ return { rawPrefix: prefix.slice(1), isAtPrefix: true, isQuotedPrefix: false };
89
+ }
90
+ return { rawPrefix: prefix, isAtPrefix: false, isQuotedPrefix: false };
91
+ }
92
+
93
+ function buildCompletionValue(
94
+ path: string,
95
+ options: { isDirectory: boolean; isAtPrefix: boolean; isQuotedPrefix: boolean },
96
+ ): string {
97
+ const needsQuotes = options.isQuotedPrefix || path.includes(" ");
98
+ const prefix = options.isAtPrefix ? "@" : "";
99
+
100
+ if (!needsQuotes) {
101
+ return `${prefix}${path}`;
102
+ }
103
+
104
+ const openQuote = `${prefix}"`;
105
+ const closeQuote = options.isDirectory ? "" : '"';
106
+ return `${openQuote}${path}${closeQuote}`;
107
+ }
108
+
109
+ /**
110
+ * Check if query is a subsequence of target (fuzzy match).
111
+ * "wig" matches "skill:wig" because w-i-g appear in order.
112
+ */
113
+ function fuzzyMatch(query: string, target: string): boolean {
114
+ if (query.length === 0) return true;
115
+ if (query.length > target.length) return false;
116
+
117
+ let qi = 0;
118
+ for (let ti = 0; ti < target.length && qi < query.length; ti++) {
119
+ if (query[qi] === target[ti]) qi++;
120
+ }
121
+ return qi === query.length;
122
+ }
123
+
124
+ /**
125
+ * Score a fuzzy match. Higher = better match.
126
+ * Prioritizes: exact match > starts-with > contains > subsequence
127
+ */
128
+ function fuzzyScore(query: string, target: string): number {
129
+ if (query.length === 0) return 1;
130
+ if (target === query) return 100;
131
+ if (target.startsWith(query)) return 80;
132
+ if (target.includes(query)) return 60;
133
+
134
+ // Subsequence match - score by how "tight" the match is
135
+ // (fewer gaps between matched characters = higher score)
136
+ let qi = 0;
137
+ let gaps = 0;
138
+ let lastMatchIdx = -1;
139
+ for (let ti = 0; ti < target.length && qi < query.length; ti++) {
140
+ if (query[qi] === target[ti]) {
141
+ if (lastMatchIdx >= 0 && ti - lastMatchIdx > 1) gaps++;
142
+ lastMatchIdx = ti;
143
+ qi++;
144
+ }
145
+ }
146
+ if (qi !== query.length) return 0;
147
+
148
+ // Base score 40 for subsequence, minus penalty for gaps
149
+ return Math.max(1, 40 - gaps * 5);
150
+ }
151
+
152
+ export interface AutocompleteItem {
153
+ value: string;
154
+ label: string;
155
+ description?: string;
156
+ /** Dim hint text shown inline after cursor when this item is selected */
157
+ hint?: string;
158
+ }
159
+
160
+ export interface SlashCommand {
161
+ name: string;
162
+ description?: string;
163
+ // Function to get argument completions for this command
164
+ // Returns null if no argument completion is available
165
+ getArgumentCompletions?(argumentPrefix: string): AutocompleteItem[] | null;
166
+ /** Return inline hint text for the current argument state (shown as dim ghost text after cursor) */
167
+ getInlineHint?(argumentText: string): string | null;
168
+ }
169
+
170
+ export interface AutocompleteProvider {
171
+ /** Get autocomplete suggestions for current text/cursor position */
172
+ getSuggestions(
173
+ lines: string[],
174
+ cursorLine: number,
175
+ cursorCol: number,
176
+ ): Promise<{
177
+ items: AutocompleteItem[];
178
+ prefix: string; // What we're matching against (e.g., "/" or "src/")
179
+ } | null>;
180
+
181
+ /** Apply the selected item and return new text + cursor position */
182
+ applyCompletion(
183
+ lines: string[],
184
+ cursorLine: number,
185
+ cursorCol: number,
186
+ item: AutocompleteItem,
187
+ prefix: string,
188
+ ): {
189
+ lines: string[];
190
+ cursorLine: number;
191
+ cursorCol: number;
192
+ onApplied?: () => void;
193
+ };
194
+
195
+ /** Get inline hint text to show as dim ghost text after the cursor */
196
+ getInlineHint?(lines: string[], cursorLine: number, cursorCol: number): string | null;
197
+ }
198
+
199
+ // Combined provider that handles both slash commands and file paths.
200
+ export class CombinedAutocompleteProvider implements AutocompleteProvider {
201
+ #commands: (SlashCommand | AutocompleteItem)[];
202
+ #basePath: string;
203
+ // Intentionally separate from pi-natives cache: this cache is a local,
204
+ // per-directory readdir fast-path for prefix completions. Global fuzzy
205
+ // discovery continues to use native fuzzyFind + shared scan cache.
206
+ #dirCache: Map<string, { entries: fs.Dirent[]; timestamp: number }> = new Map();
207
+ #searchDb?: SearchDb;
208
+ readonly #DIR_CACHE_TTL = 2000; // 2 seconds
209
+
210
+ constructor(
211
+ commands: (SlashCommand | AutocompleteItem)[] = [],
212
+ basePath: string = getProjectDir(),
213
+ searchDb?: SearchDb,
214
+ ) {
215
+ this.#commands = commands;
216
+ this.#basePath = basePath;
217
+ this.#searchDb = searchDb;
218
+ }
219
+
220
+ async getSuggestions(
221
+ lines: string[],
222
+ cursorLine: number,
223
+ cursorCol: number,
224
+ ): Promise<{ items: AutocompleteItem[]; prefix: string } | null> {
225
+ const currentLine = lines[cursorLine] || "";
226
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
227
+
228
+ // Check for @ file reference (fuzzy search) - must be after a delimiter or at start
229
+ const atPrefix = this.#extractAtPrefix(textBeforeCursor);
230
+ if (atPrefix) {
231
+ const { rawPrefix, isQuotedPrefix } = parsePathPrefix(atPrefix);
232
+ const suggestions =
233
+ rawPrefix.length > 0
234
+ ? await this.#getFuzzyFileSuggestions(rawPrefix, { isQuotedPrefix })
235
+ : await this.#getFileSuggestions("@");
236
+ if (suggestions.length === 0 && rawPrefix.length > 0) {
237
+ const fallback = await this.#getFileSuggestions(atPrefix);
238
+ if (fallback.length === 0) return null;
239
+ return { items: fallback, prefix: atPrefix };
240
+ }
241
+ if (suggestions.length === 0) return null;
242
+
243
+ return {
244
+ items: suggestions,
245
+ prefix: atPrefix,
246
+ };
247
+ }
248
+
249
+ // Check for slash commands
250
+ if (textBeforeCursor.startsWith("/")) {
251
+ const spaceIndex = textBeforeCursor.indexOf(" ");
252
+
253
+ if (spaceIndex === -1) {
254
+ // No space yet - complete command names
255
+ const prefix = textBeforeCursor.slice(1); // Remove the "/"
256
+ const lowerPrefix = prefix.toLowerCase();
257
+
258
+ // Filter commands using fuzzy matching (subsequence match)
259
+ const matches = this.#commands
260
+ .filter(cmd => {
261
+ const name = "name" in cmd ? cmd.name : cmd.value;
262
+ if (!name) return false;
263
+ // Match name or description
264
+ if (fuzzyMatch(lowerPrefix, name.toLowerCase())) return true;
265
+ const desc = cmd.description?.toLowerCase();
266
+ return desc ? fuzzyMatch(lowerPrefix, desc) : false;
267
+ })
268
+ .map(cmd => {
269
+ const name = "name" in cmd ? cmd.name : cmd.value;
270
+ const lowerName = name?.toLowerCase() ?? "";
271
+ const lowerDesc = cmd.description?.toLowerCase() ?? "";
272
+ // Score name matches higher than description matches
273
+ const nameScore = fuzzyMatch(lowerPrefix, lowerName) ? fuzzyScore(lowerPrefix, lowerName) : 0;
274
+ const descScore = fuzzyMatch(lowerPrefix, lowerDesc) ? fuzzyScore(lowerPrefix, lowerDesc) * 0.5 : 0;
275
+ return {
276
+ value: name,
277
+ label: "name" in cmd ? cmd.name : cmd.label,
278
+ score: Math.max(nameScore, descScore),
279
+ ...(cmd.description && { description: cmd.description }),
280
+ };
281
+ })
282
+ .sort((a, b) => b.score - a.score)
283
+ .map(({ score: _, ...rest }) => rest);
284
+
285
+ if (matches.length === 0) return null;
286
+
287
+ return {
288
+ items: matches,
289
+ prefix: textBeforeCursor,
290
+ };
291
+ } else {
292
+ // Space found - complete command arguments
293
+ const commandName = textBeforeCursor.slice(1, spaceIndex); // Command without "/"
294
+ const argumentText = textBeforeCursor.slice(spaceIndex + 1); // Text after space
295
+
296
+ const command = this.#commands.find(cmd => {
297
+ const name = "name" in cmd ? cmd.name : cmd.value;
298
+ return name === commandName;
299
+ });
300
+ if (!command || !("getArgumentCompletions" in command) || !command.getArgumentCompletions) {
301
+ return null; // No argument completion for this command
302
+ }
303
+
304
+ const argumentSuggestions = command.getArgumentCompletions(argumentText);
305
+ if (!argumentSuggestions || argumentSuggestions.length === 0) {
306
+ return null;
307
+ }
308
+
309
+ return {
310
+ items: argumentSuggestions,
311
+ prefix: argumentText,
312
+ };
313
+ }
314
+ }
315
+
316
+ // Check for file paths - triggered by Tab or if we detect a path pattern
317
+ const pathMatch = this.#extractPathPrefix(textBeforeCursor, false);
318
+
319
+ if (pathMatch !== null) {
320
+ const suggestions = await this.#getFileSuggestions(pathMatch);
321
+ if (suggestions.length === 0) return null;
322
+
323
+ // Check if we have an exact match that is a directory
324
+ // In that case, we might want to return suggestions for the directory content instead
325
+ // But only if the prefix ends with /
326
+ if (suggestions.length === 1 && suggestions[0]?.value === pathMatch && !pathMatch.endsWith("/")) {
327
+ // Exact match found (e.g. user typed "src" and "src/" is the only match)
328
+ // We still return it so user can select it and add /
329
+ return {
330
+ items: suggestions,
331
+ prefix: pathMatch,
332
+ };
333
+ }
334
+
335
+ return {
336
+ items: suggestions,
337
+ prefix: pathMatch,
338
+ };
339
+ }
340
+
341
+ return null;
342
+ }
343
+
344
+ applyCompletion(
345
+ lines: string[],
346
+ cursorLine: number,
347
+ cursorCol: number,
348
+ item: AutocompleteItem,
349
+ prefix: string,
350
+ ): { lines: string[]; cursorLine: number; cursorCol: number } {
351
+ const currentLine = lines[cursorLine] || "";
352
+ const beforePrefix = currentLine.slice(0, cursorCol - prefix.length);
353
+ const afterCursor = currentLine.slice(cursorCol);
354
+
355
+ // Check if we're completing a slash command (prefix starts with "/" but NOT a file path)
356
+ // Slash commands are at the start of the line and don't contain path separators after the first /
357
+ const isSlashCommand = prefix.startsWith("/") && beforePrefix.trim() === "" && !prefix.slice(1).includes("/");
358
+ if (isSlashCommand) {
359
+ // This is a command name completion
360
+ const newLine = `${beforePrefix}/${item.value} ${afterCursor}`;
361
+ const newLines = [...lines];
362
+ newLines[cursorLine] = newLine;
363
+
364
+ return {
365
+ lines: newLines,
366
+ cursorLine,
367
+ cursorCol: beforePrefix.length + item.value.length + 2, // +2 for "/" and space
368
+ };
369
+ }
370
+
371
+ // Check if we're completing a file attachment (prefix starts with "@")
372
+ if (prefix.startsWith("@")) {
373
+ // This is a file attachment completion
374
+ const newLine = `${beforePrefix + item.value} ${afterCursor}`;
375
+ const newLines = [...lines];
376
+ newLines[cursorLine] = newLine;
377
+
378
+ return {
379
+ lines: newLines,
380
+ cursorLine,
381
+ cursorCol: beforePrefix.length + item.value.length + 1, // +1 for space
382
+ };
383
+ }
384
+
385
+ // Check if we're in a slash command context (beforePrefix contains "/command ")
386
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
387
+ if (textBeforeCursor.includes("/") && textBeforeCursor.includes(" ")) {
388
+ // This is likely a command argument completion
389
+ const newLine = beforePrefix + item.value + afterCursor;
390
+ const newLines = [...lines];
391
+ newLines[cursorLine] = newLine;
392
+
393
+ return {
394
+ lines: newLines,
395
+ cursorLine,
396
+ cursorCol: beforePrefix.length + item.value.length,
397
+ };
398
+ }
399
+
400
+ // For file paths, complete the path
401
+ const newLine = beforePrefix + item.value + afterCursor;
402
+ const newLines = [...lines];
403
+ newLines[cursorLine] = newLine;
404
+
405
+ return {
406
+ lines: newLines,
407
+ cursorLine,
408
+ cursorCol: beforePrefix.length + item.value.length,
409
+ };
410
+ }
411
+
412
+ // Extract @ prefix for fuzzy file suggestions
413
+ #extractAtPrefix(text: string): string | null {
414
+ const quotedPrefix = extractQuotedPrefix(text);
415
+ if (quotedPrefix?.startsWith('@"')) {
416
+ return quotedPrefix;
417
+ }
418
+
419
+ const lastDelimiterIndex = findLastDelimiter(text);
420
+ const tokenStart = lastDelimiterIndex === -1 ? 0 : lastDelimiterIndex + 1;
421
+
422
+ if (text[tokenStart] === "@") {
423
+ return text.slice(tokenStart);
424
+ }
425
+
426
+ return null;
427
+ }
428
+
429
+ // Extract a path-like prefix from the text before cursor
430
+ #extractPathPrefix(text: string, forceExtract: boolean = false): string | null {
431
+ const quotedPrefix = extractQuotedPrefix(text);
432
+ if (quotedPrefix) {
433
+ return quotedPrefix;
434
+ }
435
+
436
+ const lastDelimiterIndex = findLastDelimiter(text);
437
+ const pathPrefix = lastDelimiterIndex === -1 ? text : text.slice(lastDelimiterIndex + 1);
438
+
439
+ // For forced extraction (Tab key), always return something
440
+ if (forceExtract) {
441
+ return pathPrefix;
442
+ }
443
+
444
+ // For natural triggers, return if it looks like a path, ends with /, starts with ~/, .
445
+ // Only return empty string if the text looks like it's starting a path context
446
+ if (pathPrefix.includes("/") || pathPrefix.startsWith(".") || pathPrefix.startsWith("~/")) {
447
+ return pathPrefix;
448
+ }
449
+
450
+ // Return empty string only after a space (not for completely empty text)
451
+ // Empty text should not trigger file suggestions - that's for forced Tab completion
452
+ if (pathPrefix === "" && text.endsWith(" ")) {
453
+ return pathPrefix;
454
+ }
455
+
456
+ return null;
457
+ }
458
+
459
+ // Expand home directory (~/) to actual home path
460
+ #expandHomePath(filePath: string): string {
461
+ if (filePath.startsWith("~/")) {
462
+ const expandedPath = path.join(os.homedir(), filePath.slice(2));
463
+ // Preserve trailing slash if original path had one
464
+ return filePath.endsWith("/") && !expandedPath.endsWith("/") ? `${expandedPath}/` : expandedPath;
465
+ } else if (filePath === "~") {
466
+ return os.homedir();
467
+ }
468
+ return filePath;
469
+ }
470
+
471
+ async #resolveScopedFuzzyQuery(
472
+ rawQuery: string,
473
+ ): Promise<{ baseDir: string; query: string; displayBase: string } | null> {
474
+ const slashIndex = rawQuery.lastIndexOf("/");
475
+ if (slashIndex === -1) {
476
+ return null;
477
+ }
478
+
479
+ const displayBase = rawQuery.slice(0, slashIndex + 1);
480
+ const query = rawQuery.slice(slashIndex + 1);
481
+
482
+ let baseDir: string;
483
+ if (displayBase.startsWith("~/")) {
484
+ baseDir = this.#expandHomePath(displayBase);
485
+ } else if (displayBase.startsWith("/")) {
486
+ baseDir = displayBase;
487
+ } else {
488
+ baseDir = path.join(this.#basePath, displayBase);
489
+ }
490
+
491
+ try {
492
+ if (!(await fs.promises.stat(baseDir)).isDirectory()) {
493
+ return null;
494
+ }
495
+ } catch {
496
+ return null;
497
+ }
498
+
499
+ return { baseDir, query, displayBase };
500
+ }
501
+
502
+ #scopedPathForDisplay(displayBase: string, relativePath: string): string {
503
+ if (displayBase === "/") {
504
+ return `/${relativePath}`;
505
+ }
506
+ return `${displayBase}${relativePath}`;
507
+ }
508
+
509
+ async #getCachedDirEntries(searchDir: string): Promise<fs.Dirent[]> {
510
+ const now = Date.now();
511
+ const cached = this.#dirCache.get(searchDir);
512
+
513
+ if (cached && now - cached.timestamp < this.#DIR_CACHE_TTL) {
514
+ return cached.entries;
515
+ }
516
+
517
+ const entries = await fs.promises.readdir(searchDir, { withFileTypes: true });
518
+ this.#dirCache.set(searchDir, { entries, timestamp: now });
519
+
520
+ if (this.#dirCache.size > 100) {
521
+ const sortedKeys = [...this.#dirCache.entries()]
522
+ .sort((a, b) => a[1].timestamp - b[1].timestamp)
523
+ .slice(0, 50)
524
+ .map(([key]) => key);
525
+ for (const key of sortedKeys) {
526
+ this.#dirCache.delete(key);
527
+ }
528
+ }
529
+
530
+ return entries;
531
+ }
532
+
533
+ invalidateDirCache(dir?: string): void {
534
+ if (dir) {
535
+ this.#dirCache.delete(dir);
536
+ } else {
537
+ this.#dirCache.clear();
538
+ }
539
+ }
540
+
541
+ // Get file/directory suggestions for a given path prefix
542
+ async #getFileSuggestions(prefix: string): Promise<AutocompleteItem[]> {
543
+ try {
544
+ let searchDir: string;
545
+ let searchPrefix: string;
546
+ const { rawPrefix, isAtPrefix, isQuotedPrefix } = parsePathPrefix(prefix);
547
+ let expandedPrefix = rawPrefix;
548
+
549
+ // Handle home directory expansion
550
+ if (expandedPrefix.startsWith("~")) {
551
+ expandedPrefix = this.#expandHomePath(expandedPrefix);
552
+ }
553
+
554
+ const isRootPrefix =
555
+ rawPrefix === "" ||
556
+ rawPrefix === "./" ||
557
+ rawPrefix === "../" ||
558
+ rawPrefix === "~" ||
559
+ rawPrefix === "~/" ||
560
+ rawPrefix === "/" ||
561
+ (isAtPrefix && rawPrefix === "");
562
+
563
+ if (isRootPrefix) {
564
+ // Complete from specified position
565
+ if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
566
+ searchDir = expandedPrefix;
567
+ } else {
568
+ searchDir = path.join(this.#basePath, expandedPrefix);
569
+ }
570
+ searchPrefix = "";
571
+ } else if (rawPrefix.endsWith("/")) {
572
+ // If prefix ends with /, show contents of that directory
573
+ if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
574
+ searchDir = expandedPrefix;
575
+ } else {
576
+ searchDir = path.join(this.#basePath, expandedPrefix);
577
+ }
578
+ searchPrefix = "";
579
+ } else {
580
+ // Split into directory and file prefix
581
+ const dir = path.dirname(expandedPrefix);
582
+ const file = path.basename(expandedPrefix);
583
+ if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
584
+ searchDir = dir;
585
+ } else {
586
+ searchDir = path.join(this.#basePath, dir);
587
+ }
588
+ searchPrefix = file;
589
+ }
590
+
591
+ const entries = await this.#getCachedDirEntries(searchDir);
592
+ const suggestions: AutocompleteItem[] = [];
593
+
594
+ for (const entry of entries) {
595
+ if (!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase())) {
596
+ continue;
597
+ }
598
+ // Skip .git directory
599
+ if (entry.name === ".git") {
600
+ continue;
601
+ }
602
+
603
+ // Check if entry is a directory (or a symlink pointing to a directory)
604
+ let isDirectory = entry.isDirectory();
605
+ if (!isDirectory && entry.isSymbolicLink()) {
606
+ try {
607
+ const fullPath = path.join(searchDir, entry.name);
608
+ isDirectory = (await fs.promises.stat(fullPath)).isDirectory();
609
+ } catch {
610
+ // Broken symlink, file deleted between readdir and stat, or permission error
611
+ continue;
612
+ }
613
+ }
614
+
615
+ let relativePath: string;
616
+ const name = entry.name;
617
+ const displayPrefix = rawPrefix;
618
+
619
+ if (displayPrefix.endsWith("/")) {
620
+ // If prefix ends with /, append entry to the prefix
621
+ relativePath = displayPrefix + name;
622
+ } else if (displayPrefix.includes("/")) {
623
+ // Preserve ~/ format for home directory paths
624
+ if (displayPrefix.startsWith("~/")) {
625
+ const homeRelativeDir = displayPrefix.slice(2); // Remove ~/
626
+ const dir = path.dirname(homeRelativeDir);
627
+ relativePath = `~/${dir === "." ? name : path.join(dir, name)}`;
628
+ } else if (displayPrefix.startsWith("/")) {
629
+ // Absolute path - construct properly
630
+ const dir = path.dirname(displayPrefix);
631
+ if (dir === "/") {
632
+ relativePath = `/${name}`;
633
+ } else {
634
+ relativePath = `${dir}/${name}`;
635
+ }
636
+ } else {
637
+ relativePath = path.join(path.dirname(displayPrefix), name);
638
+ if (displayPrefix.startsWith("./") && !relativePath.startsWith("./")) {
639
+ relativePath = `./${relativePath}`;
640
+ }
641
+ }
642
+ } else {
643
+ // For standalone entries, preserve ~/ if original prefix was ~/
644
+ if (displayPrefix.startsWith("~")) {
645
+ relativePath = `~/${name}`;
646
+ } else {
647
+ relativePath = name;
648
+ }
649
+ }
650
+
651
+ const pathValue = isDirectory ? `${relativePath}/` : relativePath;
652
+ const value = buildCompletionValue(pathValue, {
653
+ isDirectory,
654
+ isAtPrefix,
655
+ isQuotedPrefix,
656
+ });
657
+
658
+ suggestions.push({
659
+ value,
660
+ label: name + (isDirectory ? "/" : ""),
661
+ });
662
+ }
663
+
664
+ // Sort directories first, then alphabetically
665
+ suggestions.sort((a, b) => {
666
+ const aIsDir = a.value.endsWith("/");
667
+ const bIsDir = b.value.endsWith("/");
668
+ if (aIsDir && !bIsDir) return -1;
669
+ if (!aIsDir && bIsDir) return 1;
670
+ return a.label.localeCompare(b.label);
671
+ });
672
+
673
+ return suggestions;
674
+ } catch {
675
+ // Directory doesn't exist or not accessible
676
+ return [];
677
+ }
678
+ }
679
+
680
+ async #getFuzzyFileSuggestions(query: string, options: { isQuotedPrefix: boolean }): Promise<AutocompleteItem[]> {
681
+ try {
682
+ const scopedQuery = await this.#resolveScopedFuzzyQuery(query);
683
+ const searchPath = scopedQuery?.baseDir ?? this.#basePath;
684
+ const fuzzyQuery = scopedQuery?.query ?? query;
685
+ const result = await fuzzyFind(buildAutocompleteFuzzyDiscoveryProfile(fuzzyQuery, searchPath), this.#searchDb);
686
+ const lowerQuery = fuzzyQuery.toLowerCase();
687
+ const filteredMatches = result.matches.filter(entry => {
688
+ const p = entry.path.endsWith("/") ? entry.path.slice(0, -1) : entry.path;
689
+ const normalized = p.replaceAll("\\", "/");
690
+ if (/(^|\/)\.git(\/|$)/.test(normalized)) {
691
+ return false;
692
+ }
693
+ return lowerQuery.length === 0 || fuzzyMatch(lowerQuery, normalized.toLowerCase());
694
+ });
695
+ const topEntries = filteredMatches.slice(0, 20);
696
+ const suggestions: AutocompleteItem[] = [];
697
+ for (const { path: entryPath, isDirectory } of topEntries) {
698
+ const pathWithoutSlash = isDirectory ? entryPath.slice(0, -1) : entryPath;
699
+ const displayPath = scopedQuery
700
+ ? this.#scopedPathForDisplay(scopedQuery.displayBase, pathWithoutSlash)
701
+ : pathWithoutSlash;
702
+ const entryName = path.basename(pathWithoutSlash);
703
+ const completionPath = isDirectory ? `${displayPath}/` : displayPath;
704
+ const value = buildCompletionValue(completionPath, {
705
+ isDirectory,
706
+ isAtPrefix: true,
707
+ isQuotedPrefix: options.isQuotedPrefix,
708
+ });
709
+ suggestions.push({
710
+ value,
711
+ label: entryName + (isDirectory ? "/" : ""),
712
+ description: displayPath,
713
+ });
714
+ }
715
+ return suggestions;
716
+ } catch {
717
+ return [];
718
+ }
719
+ }
720
+
721
+ // Force file completion (called on Tab key) - always returns suggestions
722
+ async getForceFileSuggestions(
723
+ lines: string[],
724
+ cursorLine: number,
725
+ cursorCol: number,
726
+ ): Promise<{ items: AutocompleteItem[]; prefix: string } | null> {
727
+ const currentLine = lines[cursorLine] || "";
728
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
729
+
730
+ // Don't trigger if we're typing a slash command at the start of the line
731
+ if (textBeforeCursor.trim().startsWith("/") && !textBeforeCursor.trim().includes(" ")) {
732
+ return null;
733
+ }
734
+
735
+ // Force extract path prefix - this will always return something
736
+ const pathMatch = this.#extractPathPrefix(textBeforeCursor, true);
737
+ if (pathMatch !== null) {
738
+ const suggestions = await this.#getFileSuggestions(pathMatch);
739
+ if (suggestions.length === 0) return null;
740
+
741
+ return {
742
+ items: suggestions,
743
+ prefix: pathMatch,
744
+ };
745
+ }
746
+
747
+ return null;
748
+ }
749
+
750
+ // Check if we should trigger file completion (called on Tab key)
751
+ shouldTriggerFileCompletion(lines: string[], cursorLine: number, cursorCol: number): boolean {
752
+ const currentLine = lines[cursorLine] || "";
753
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
754
+
755
+ // Don't trigger if we're typing a slash command at the start of the line
756
+ if (textBeforeCursor.trim().startsWith("/") && !textBeforeCursor.trim().includes(" ")) {
757
+ return false;
758
+ }
759
+
760
+ return true;
761
+ }
762
+
763
+ /** Get inline hint text for slash commands with subcommand hints */
764
+ getInlineHint(lines: string[], cursorLine: number, cursorCol: number): string | null {
765
+ const currentLine = lines[cursorLine] || "";
766
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
767
+
768
+ if (!textBeforeCursor.startsWith("/")) return null;
769
+
770
+ const spaceIndex = textBeforeCursor.indexOf(" ");
771
+ if (spaceIndex === -1) return null;
772
+
773
+ const commandName = textBeforeCursor.slice(1, spaceIndex);
774
+ const argumentText = textBeforeCursor.slice(spaceIndex + 1);
775
+
776
+ const command = this.#commands.find(cmd => {
777
+ const name = "name" in cmd ? cmd.name : cmd.value;
778
+ return name === commandName;
779
+ });
780
+
781
+ if (!command || !("getInlineHint" in command) || !command.getInlineHint) {
782
+ return null;
783
+ }
784
+
785
+ return command.getInlineHint(argumentText);
786
+ }
787
+ }