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