@sayknow-cli/tui 0.2.2

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