jeopi-tui 16.2.13

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 (75) hide show
  1. package/CHANGELOG.md +1861 -0
  2. package/README.md +705 -0
  3. package/dist/types/autocomplete.d.ts +99 -0
  4. package/dist/types/bracketed-paste.d.ts +51 -0
  5. package/dist/types/components/box.d.ts +31 -0
  6. package/dist/types/components/cancellable-loader.d.ts +21 -0
  7. package/dist/types/components/editor.d.ts +155 -0
  8. package/dist/types/components/image.d.ts +112 -0
  9. package/dist/types/components/input.d.ts +23 -0
  10. package/dist/types/components/loader.d.ts +20 -0
  11. package/dist/types/components/markdown.d.ts +64 -0
  12. package/dist/types/components/scroll-view.d.ts +62 -0
  13. package/dist/types/components/select-list.d.ts +68 -0
  14. package/dist/types/components/settings-list.d.ts +123 -0
  15. package/dist/types/components/spacer.d.ts +11 -0
  16. package/dist/types/components/tab-bar.d.ts +89 -0
  17. package/dist/types/components/text.d.ts +14 -0
  18. package/dist/types/components/truncated-text.d.ts +10 -0
  19. package/dist/types/deccara.d.ts +49 -0
  20. package/dist/types/desktop-notify.d.ts +51 -0
  21. package/dist/types/editor-component.d.ts +38 -0
  22. package/dist/types/fuzzy.d.ts +32 -0
  23. package/dist/types/index.d.ts +32 -0
  24. package/dist/types/keybindings.d.ts +191 -0
  25. package/dist/types/keys.d.ts +208 -0
  26. package/dist/types/kill-ring.d.ts +20 -0
  27. package/dist/types/kitty-graphics.d.ts +79 -0
  28. package/dist/types/latex-block.d.ts +7 -0
  29. package/dist/types/latex-to-unicode.d.ts +33 -0
  30. package/dist/types/loop-watchdog.d.ts +39 -0
  31. package/dist/types/mouse.d.ts +67 -0
  32. package/dist/types/stdin-buffer.d.ts +60 -0
  33. package/dist/types/symbols.d.ts +25 -0
  34. package/dist/types/terminal-capabilities.d.ts +284 -0
  35. package/dist/types/terminal.d.ts +107 -0
  36. package/dist/types/ttyid.d.ts +9 -0
  37. package/dist/types/tui.d.ts +423 -0
  38. package/dist/types/utils.d.ts +95 -0
  39. package/package.json +73 -0
  40. package/src/autocomplete.ts +1026 -0
  41. package/src/bracketed-paste.ts +123 -0
  42. package/src/components/box.ts +194 -0
  43. package/src/components/cancellable-loader.ts +40 -0
  44. package/src/components/editor.ts +3092 -0
  45. package/src/components/image.ts +444 -0
  46. package/src/components/input.ts +474 -0
  47. package/src/components/loader.ts +103 -0
  48. package/src/components/markdown.ts +2068 -0
  49. package/src/components/scroll-view.ts +227 -0
  50. package/src/components/select-list.ts +531 -0
  51. package/src/components/settings-list.ts +793 -0
  52. package/src/components/spacer.ts +32 -0
  53. package/src/components/tab-bar.ts +300 -0
  54. package/src/components/text.ts +122 -0
  55. package/src/components/truncated-text.ts +69 -0
  56. package/src/deccara.ts +314 -0
  57. package/src/desktop-notify.ts +186 -0
  58. package/src/editor-component.ts +74 -0
  59. package/src/fuzzy.ts +356 -0
  60. package/src/index.ts +51 -0
  61. package/src/keybindings.ts +337 -0
  62. package/src/keys.ts +561 -0
  63. package/src/kill-ring.ts +51 -0
  64. package/src/kitty-graphics.ts +171 -0
  65. package/src/latex-block.ts +461 -0
  66. package/src/latex-to-unicode.ts +1994 -0
  67. package/src/loop-watchdog.ts +106 -0
  68. package/src/mouse.ts +105 -0
  69. package/src/stdin-buffer.ts +669 -0
  70. package/src/symbols.ts +26 -0
  71. package/src/terminal-capabilities.ts +1152 -0
  72. package/src/terminal.ts +1463 -0
  73. package/src/ttyid.ts +84 -0
  74. package/src/tui.ts +3901 -0
  75. package/src/utils.ts +570 -0
@@ -0,0 +1,1026 @@
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 "jeopi-natives";
5
+ import { getProjectDir } from "jeopi-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
+ /**
60
+ * Locate the slash that opens a slash command on the line, allowing leading
61
+ * whitespace. Returns the index of the `/` or `null` when the line is not a
62
+ * slash command. Aligns with `trimStart` semantics so the editor and provider
63
+ * agree on which prefixes count.
64
+ */
65
+ export function findLeadingSlashCommandStart(text: string): number | null {
66
+ const trimmed = text.trimStart();
67
+ if (!trimmed.startsWith("/")) return null;
68
+ return text.length - trimmed.length;
69
+ }
70
+
71
+ export function findTrailingSlashCommandStart(text: string): number | null {
72
+ const match = /(?:^|\s)\/([^\s/]*)$/.exec(text);
73
+ if (!match || match.index === undefined) return null;
74
+ const slashOffset = match[0].indexOf("/");
75
+ return match.index + slashOffset;
76
+ }
77
+
78
+ function extractQuotedPrefix(text: string): string | null {
79
+ const quoteStart = findUnclosedQuoteStart(text);
80
+ if (quoteStart === null) {
81
+ return null;
82
+ }
83
+
84
+ if (quoteStart > 0 && text[quoteStart - 1] === "@") {
85
+ if (!isTokenStart(text, quoteStart - 1)) {
86
+ return null;
87
+ }
88
+ return text.slice(quoteStart - 1);
89
+ }
90
+
91
+ if (!isTokenStart(text, quoteStart)) {
92
+ return null;
93
+ }
94
+
95
+ return text.slice(quoteStart);
96
+ }
97
+
98
+ function parsePathPrefix(prefix: string): { rawPrefix: string; isAtPrefix: boolean; isQuotedPrefix: boolean } {
99
+ if (prefix.startsWith('@"')) {
100
+ return { rawPrefix: prefix.slice(2), isAtPrefix: true, isQuotedPrefix: true };
101
+ }
102
+ if (prefix.startsWith('"')) {
103
+ return { rawPrefix: prefix.slice(1), isAtPrefix: false, isQuotedPrefix: true };
104
+ }
105
+ if (prefix.startsWith("@")) {
106
+ return { rawPrefix: prefix.slice(1), isAtPrefix: true, isQuotedPrefix: false };
107
+ }
108
+ return { rawPrefix: prefix, isAtPrefix: false, isQuotedPrefix: false };
109
+ }
110
+
111
+ function buildCompletionValue(
112
+ path: string,
113
+ options: { isDirectory: boolean; isAtPrefix: boolean; isQuotedPrefix: boolean },
114
+ ): string {
115
+ const needsQuotes = options.isQuotedPrefix || path.includes(" ");
116
+ const prefix = options.isAtPrefix ? "@" : "";
117
+
118
+ if (!needsQuotes) {
119
+ return `${prefix}${path}`;
120
+ }
121
+
122
+ const openQuote = `${prefix}"`;
123
+ const closeQuote = options.isDirectory ? "" : '"';
124
+ return `${openQuote}${path}${closeQuote}`;
125
+ }
126
+
127
+ /**
128
+ * Check if query is a subsequence of target (fuzzy match).
129
+ * "wig" matches "skill:wig" because w-i-g appear in order.
130
+ */
131
+ function fuzzyMatch(query: string, target: string): boolean {
132
+ if (query.length === 0) return true;
133
+ if (query.length > target.length) return false;
134
+
135
+ let qi = 0;
136
+ for (let ti = 0; ti < target.length && qi < query.length; ti++) {
137
+ if (query[qi] === target[ti]) qi++;
138
+ }
139
+ return qi === query.length;
140
+ }
141
+
142
+ /**
143
+ * Score a fuzzy match. Higher = better match.
144
+ * Prioritizes: exact match > starts-with > contains > subsequence
145
+ */
146
+ function fuzzyScore(query: string, target: string): number {
147
+ if (query.length === 0) return 1;
148
+ if (target === query) return 100;
149
+ if (target.startsWith(query)) return 80;
150
+ if (target.includes(query)) return 60;
151
+
152
+ // Subsequence match - score by how "tight" the match is
153
+ // (fewer gaps between matched characters = higher score)
154
+ let qi = 0;
155
+ let gaps = 0;
156
+ let lastMatchIdx = -1;
157
+ for (let ti = 0; ti < target.length && qi < query.length; ti++) {
158
+ if (query[qi] === target[ti]) {
159
+ if (lastMatchIdx >= 0 && ti - lastMatchIdx > 1) gaps++;
160
+ lastMatchIdx = ti;
161
+ qi++;
162
+ }
163
+ }
164
+ if (qi !== query.length) return 0;
165
+
166
+ // Base score 40 for subsequence, minus penalty for gaps
167
+ return Math.max(1, 40 - gaps * 5);
168
+ }
169
+
170
+ export interface AutocompleteItem {
171
+ value: string;
172
+ label: string;
173
+ description?: string;
174
+ /** Dim hint text shown inline after cursor when this item is selected */
175
+ hint?: string;
176
+ }
177
+
178
+ type Awaitable<T> = T | Promise<T>;
179
+
180
+ export interface SlashCommand {
181
+ name: string;
182
+ aliases?: string[];
183
+ description?: string;
184
+ argumentHint?: string;
185
+ /** Dynamic display-only description for slash-command autocomplete. Must be synchronous and side-effect free. */
186
+ getAutocompleteDescription?: () => string | undefined;
187
+ // Function to get argument completions for this command
188
+ // Returns null if no argument completion is available
189
+ getArgumentCompletions?(argumentPrefix: string): Awaitable<AutocompleteItem[] | null>;
190
+ /** Return inline hint text for the current argument state (shown as dim ghost text after cursor) */
191
+ getInlineHint?(argumentText: string): string | null;
192
+ }
193
+
194
+ export interface AutocompleteProvider {
195
+ /** Get autocomplete suggestions for current text/cursor position */
196
+ getSuggestions(
197
+ lines: string[],
198
+ cursorLine: number,
199
+ cursorCol: number,
200
+ ): Promise<{
201
+ items: AutocompleteItem[];
202
+ prefix: string; // What we're matching against (e.g., "/" or "src/")
203
+ } | null>;
204
+
205
+ /** Apply the selected item and return new text + cursor position */
206
+ applyCompletion(
207
+ lines: string[],
208
+ cursorLine: number,
209
+ cursorCol: number,
210
+ item: AutocompleteItem,
211
+ prefix: string,
212
+ ): {
213
+ lines: string[];
214
+ cursorLine: number;
215
+ cursorCol: number;
216
+ onApplied?: () => void;
217
+ };
218
+
219
+ /** Get inline hint text to show as dim ghost text after the cursor */
220
+ getInlineHint?(lines: string[], cursorLine: number, cursorCol: number): string | null;
221
+ /** Synchronously try to complete a slash command at the start of a line (no async I/O). */
222
+ /** Returns matched items and the full prefix, or null if not applicable. */
223
+ trySyncSlashCompletion?(textBeforeCursor: string): { items: AutocompleteItem[]; prefix: string } | null;
224
+ /**
225
+ * Synchronously try to expand text immediately before the cursor (no async I/O).
226
+ * Called after every single-character insert. Implementations MUST cheaply
227
+ * early-return when the trailing context cannot trigger them.
228
+ * Returns the number of characters to delete immediately before the cursor
229
+ * and the literal string to insert in their place, or null to leave the
230
+ * buffer untouched.
231
+ */
232
+ trySyncInlineReplace?(textBeforeCursor: string): { replaceLen: number; insert: string } | null;
233
+
234
+ /**
235
+ * Force file-path completion (called on Tab). Returns matched items plus the
236
+ * full prefix, or null when no path token sits before the cursor. Present on
237
+ * file-aware providers; absent on slash-only ones.
238
+ */
239
+ getForceFileSuggestions?(
240
+ lines: string[],
241
+ cursorLine: number,
242
+ cursorCol: number,
243
+ ): Promise<{ items: AutocompleteItem[]; prefix: string } | null>;
244
+
245
+ /** Whether a Tab press should attempt file completion at the cursor. */
246
+ shouldTriggerFileCompletion?(lines: string[], cursorLine: number, cursorCol: number): boolean;
247
+ }
248
+
249
+ type CommandEntry = SlashCommand | AutocompleteItem;
250
+
251
+ function getCommandName(cmd: CommandEntry): string | undefined {
252
+ return "name" in cmd ? cmd.name : cmd.value;
253
+ }
254
+
255
+ function getCommandAliases(cmd: CommandEntry): string[] {
256
+ if (!("aliases" in cmd) || !Array.isArray(cmd.aliases)) return [];
257
+ return cmd.aliases.filter(alias => typeof alias === "string" && alias.length > 0);
258
+ }
259
+
260
+ function getStaticCommandDescription(cmd: CommandEntry): string {
261
+ return cmd.description ?? "";
262
+ }
263
+
264
+ function getAutocompleteCommandDescription(cmd: CommandEntry): string {
265
+ if ("getAutocompleteDescription" in cmd && typeof cmd.getAutocompleteDescription === "function") {
266
+ return cmd.getAutocompleteDescription() ?? cmd.description ?? "";
267
+ }
268
+ return cmd.description ?? "";
269
+ }
270
+
271
+ function commandMatchesNameOrAlias(cmd: CommandEntry, commandName: string): boolean {
272
+ const name = getCommandName(cmd);
273
+ if (name === commandName) return true;
274
+ return getCommandAliases(cmd).includes(commandName);
275
+ }
276
+
277
+ function scoreCommandTextMatch(lowerPrefix: string, lowerTarget: string): number {
278
+ if (lowerPrefix.length === 0) return 1;
279
+ if (lowerPrefix === lowerTarget) return 1000;
280
+ // Flat score for every prefix match so same-prefix commands keep registry
281
+ // order under the stable sort. A length penalty here would rank the shorter
282
+ // name first (e.g. `/set` → `setup` above `settings`), silently changing the
283
+ // command that the sync-completion path applies on Enter.
284
+ if (lowerTarget.startsWith(lowerPrefix)) return 900;
285
+ return fuzzyMatch(lowerPrefix, lowerTarget) ? fuzzyScore(lowerPrefix, lowerTarget) : 0;
286
+ }
287
+
288
+ function buildSlashCommandCompletions(commands: CommandEntry[], lowerPrefix: string): AutocompleteItem[] {
289
+ return commands
290
+ .flatMap(cmd => {
291
+ const name = getCommandName(cmd);
292
+ if (!name) return [];
293
+ const hint = "argumentHint" in cmd && cmd.argumentHint ? cmd.argumentHint : undefined;
294
+ const staticDesc = getStaticCommandDescription(cmd);
295
+ let fullDescMemo: string | undefined;
296
+ let fullDescComputed = false;
297
+ // Resolve the (possibly live) display description lazily, only once a
298
+ // candidate actually matches — getAutocompleteDescription reads live
299
+ // session state and must not run for every command on each keystroke.
300
+ const resolveFullDesc = (): string | undefined => {
301
+ if (!fullDescComputed) {
302
+ const displayDesc = getAutocompleteCommandDescription(cmd);
303
+ fullDescMemo = hint ? (displayDesc ? `${hint} - ${displayDesc}` : hint) : displayDesc;
304
+ fullDescComputed = true;
305
+ }
306
+ return fullDescMemo;
307
+ };
308
+ const candidates: Array<AutocompleteItem & { score: number }> = [];
309
+
310
+ const isSkillCommand = name.startsWith("skill:");
311
+ const nameScore =
312
+ lowerPrefix.length === 0 && isSkillCommand ? 950 : scoreCommandTextMatch(lowerPrefix, name.toLowerCase());
313
+ const lowerDesc = staticDesc.toLowerCase();
314
+ const descScore =
315
+ lowerDesc && fuzzyMatch(lowerPrefix, lowerDesc) ? fuzzyScore(lowerPrefix, lowerDesc) * 0.5 : 0;
316
+ const primaryScore = Math.max(nameScore, descScore);
317
+ if (primaryScore > 0) {
318
+ const fullDesc = resolveFullDesc();
319
+ candidates.push({
320
+ value: name,
321
+ label: "name" in cmd ? cmd.name : cmd.label,
322
+ score: primaryScore,
323
+ ...(fullDesc && { description: fullDesc }),
324
+ });
325
+ }
326
+
327
+ if (lowerPrefix.length > 0) {
328
+ for (const alias of getCommandAliases(cmd)) {
329
+ if (alias === name) continue;
330
+ const aliasScore = scoreCommandTextMatch(lowerPrefix, alias.toLowerCase());
331
+ if (aliasScore === 0) continue;
332
+ const fullDesc = resolveFullDesc();
333
+ candidates.push({
334
+ value: alias,
335
+ label: alias,
336
+ score: aliasScore,
337
+ ...(fullDesc && { description: fullDesc }),
338
+ });
339
+ }
340
+ }
341
+
342
+ return candidates;
343
+ })
344
+ .sort((a, b) => b.score - a.score)
345
+ .map(({ score: _, ...rest }) => rest);
346
+ }
347
+
348
+ function hasPromptTextBeforeSlash(
349
+ lines: string[],
350
+ cursorLine: number,
351
+ textBeforeCursor: string,
352
+ slashStart: number,
353
+ ): boolean {
354
+ for (let i = 0; i < cursorLine; i += 1) {
355
+ if ((lines[i] || "").trim() !== "") return true;
356
+ }
357
+ return textBeforeCursor.slice(0, slashStart).trim() !== "";
358
+ }
359
+
360
+ function buildMidPromptSkillCompletions(commands: CommandEntry[], lowerPrefix: string): AutocompleteItem[] {
361
+ return buildSlashCommandCompletions(
362
+ commands.filter(cmd => getCommandName(cmd)?.startsWith("skill:")),
363
+ lowerPrefix,
364
+ );
365
+ }
366
+
367
+ // Combined provider that handles both slash commands and file paths.
368
+ export class CombinedAutocompleteProvider implements AutocompleteProvider {
369
+ #commands: CommandEntry[];
370
+ #basePath: string;
371
+ // Intentionally separate from pi-natives cache: this cache is a local,
372
+ // per-directory readdir fast-path for prefix completions. Global fuzzy
373
+ // discovery continues to use native fuzzyFind + shared scan cache.
374
+ #dirCache: Map<string, { entries: fs.Dirent[]; timestamp: number }> = new Map();
375
+ readonly #DIR_CACHE_TTL = 2000; // 2 seconds
376
+
377
+ constructor(commands: CommandEntry[] = [], basePath: string = getProjectDir()) {
378
+ this.#commands = commands;
379
+ this.#basePath = basePath;
380
+ }
381
+
382
+ async getSuggestions(
383
+ lines: string[],
384
+ cursorLine: number,
385
+ cursorCol: number,
386
+ ): Promise<{ items: AutocompleteItem[]; prefix: string } | null> {
387
+ const currentLine = lines[cursorLine] || "";
388
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
389
+
390
+ // Check for @ file reference (fuzzy search) - must be after a delimiter or at start
391
+ const atPrefix = this.#extractAtPrefix(textBeforeCursor);
392
+ if (atPrefix) {
393
+ const { rawPrefix, isQuotedPrefix } = parsePathPrefix(atPrefix);
394
+ // Recursive fuzzy walks rooted outside the project (e.g. `@../`,
395
+ // `@~/`, `@/abs`) can be huge — a parent dir full of sibling
396
+ // projects blows past several seconds of latency. Outside cwd,
397
+ // fall back to plain prefix listing of the immediate directory
398
+ // (matches Claude Code's behavior). Inside cwd we keep the
399
+ // fuzzy-then-prefix flow.
400
+ if (rawPrefix.length > 0 && this.#isOutsideCwd(rawPrefix)) {
401
+ const items = await this.#getFileSuggestions(atPrefix);
402
+ if (items.length === 0) return null;
403
+ return { items, prefix: atPrefix };
404
+ }
405
+ const suggestions =
406
+ rawPrefix.length > 0
407
+ ? await this.#getFuzzyFileSuggestions(rawPrefix, { isQuotedPrefix })
408
+ : await this.#getFileSuggestions("@");
409
+ if (suggestions.length === 0 && rawPrefix.length > 0) {
410
+ const fallback = await this.#getFileSuggestions(atPrefix);
411
+ if (fallback.length === 0) return null;
412
+ return { items: fallback, prefix: atPrefix };
413
+ }
414
+ if (suggestions.length === 0) return null;
415
+
416
+ return {
417
+ items: suggestions,
418
+ prefix: atPrefix,
419
+ };
420
+ }
421
+
422
+ const leadingSlashStart = findLeadingSlashCommandStart(textBeforeCursor);
423
+ const trailingSlashStart = findTrailingSlashCommandStart(textBeforeCursor);
424
+ const hasPromptTextBeforeTrailingSlash =
425
+ trailingSlashStart !== null &&
426
+ hasPromptTextBeforeSlash(lines, cursorLine, textBeforeCursor, trailingSlashStart);
427
+ const slashStart = hasPromptTextBeforeTrailingSlash ? trailingSlashStart : leadingSlashStart;
428
+ if (slashStart !== null) {
429
+ const commandText = textBeforeCursor.slice(slashStart);
430
+ const spaceIndex = commandText.indexOf(" ");
431
+ const isMidPromptSkillLookup = hasPromptTextBeforeTrailingSlash;
432
+
433
+ if (spaceIndex === -1) {
434
+ // No space yet - complete command names
435
+ const prefix = commandText.slice(1); // Remove the "/"
436
+ const lowerPrefix = prefix.toLowerCase();
437
+
438
+ const matches = isMidPromptSkillLookup
439
+ ? buildMidPromptSkillCompletions(this.#commands, lowerPrefix)
440
+ : buildSlashCommandCompletions(this.#commands, lowerPrefix);
441
+
442
+ if (matches.length > 0) {
443
+ return {
444
+ items: matches,
445
+ // Preserve the full text-before-cursor for submitted slash
446
+ // commands so the editor's Enter-staleness check still applies
447
+ // completion for ` /sk`. Mid-prompt skill lookup keeps only
448
+ // the slash token because accepting it replaces the whole draft.
449
+ prefix: isMidPromptSkillLookup ? commandText : textBeforeCursor,
450
+ };
451
+ }
452
+ if (!isMidPromptSkillLookup) return null;
453
+ // A mid-prompt slash token with no matching skill may still be an
454
+ // absolute path (`see /tmp`); fall through to file-path completion.
455
+ } else if (!isMidPromptSkillLookup) {
456
+ // Space found - complete command arguments
457
+ const commandName = commandText.slice(1, spaceIndex); // Command without "/"
458
+ const argumentText = commandText.slice(spaceIndex + 1); // Text after space
459
+
460
+ const command = this.#commands.find(cmd => commandMatchesNameOrAlias(cmd, commandName));
461
+ if (!command || !("getArgumentCompletions" in command) || !command.getArgumentCompletions) {
462
+ return null; // No argument completion for this command
463
+ }
464
+
465
+ const argumentSuggestions = await command.getArgumentCompletions(argumentText);
466
+ if (!Array.isArray(argumentSuggestions) || argumentSuggestions.length === 0) {
467
+ return null;
468
+ }
469
+
470
+ return {
471
+ items: argumentSuggestions,
472
+ prefix: argumentText,
473
+ };
474
+ }
475
+ if (!isMidPromptSkillLookup) return null;
476
+ }
477
+
478
+ // Check for file paths - triggered by Tab or if we detect a path pattern
479
+ const pathMatch = this.#extractPathPrefix(textBeforeCursor, false);
480
+
481
+ if (pathMatch !== null) {
482
+ const suggestions = await this.#getFileSuggestions(pathMatch);
483
+ if (suggestions.length === 0) return null;
484
+
485
+ // Check if we have an exact match that is a directory
486
+ // In that case, we might want to return suggestions for the directory content instead
487
+ // But only if the prefix ends with /
488
+ if (suggestions.length === 1 && suggestions[0]?.value === pathMatch && !pathMatch.endsWith("/")) {
489
+ // Exact match found (e.g. user typed "src" and "src/" is the only match)
490
+ // We still return it so user can select it and add /
491
+ return {
492
+ items: suggestions,
493
+ prefix: pathMatch,
494
+ };
495
+ }
496
+
497
+ return {
498
+ items: suggestions,
499
+ prefix: pathMatch,
500
+ };
501
+ }
502
+
503
+ return null;
504
+ }
505
+
506
+ applyCompletion(
507
+ lines: string[],
508
+ cursorLine: number,
509
+ cursorCol: number,
510
+ item: AutocompleteItem,
511
+ prefix: string,
512
+ ): { lines: string[]; cursorLine: number; cursorCol: number } {
513
+ const currentLine = lines[cursorLine] || "";
514
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
515
+ const afterCursor = currentLine.slice(cursorCol);
516
+
517
+ const leadingSlashStart = findLeadingSlashCommandStart(textBeforeCursor);
518
+ const trailingSlashStart = findTrailingSlashCommandStart(textBeforeCursor);
519
+ const isMidPromptSkillLookup =
520
+ item.value.startsWith("skill:") &&
521
+ trailingSlashStart !== null &&
522
+ hasPromptTextBeforeSlash(lines, cursorLine, textBeforeCursor, trailingSlashStart) &&
523
+ findTrailingSlashCommandStart(prefix) !== null;
524
+
525
+ if (isMidPromptSkillLookup && trailingSlashStart !== null) {
526
+ // Replace ONLY the partial slash token (e.g. "/sec") at the cursor with
527
+ // `/skill:<name> `; the rest of the user's draft — prose typed before
528
+ // the slash, text after the cursor, and any other lines — is preserved.
529
+ // The submit-time parser (`parseSkillInvocation` in coding-agent/skills)
530
+ // detects the mid-prompt `/skill:<name>` token and threads the surrounding
531
+ // prose through as `args`, so the skill still invokes (issue #3913, after
532
+ // the original mid-prompt autocomplete landed in #3654 wiped the draft).
533
+ const beforeSlash = currentLine.slice(0, trailingSlashStart);
534
+ const insert = `/${item.value} `;
535
+ const newLine = `${beforeSlash}${insert}${afterCursor}`;
536
+ const newLines = [...lines];
537
+ newLines[cursorLine] = newLine;
538
+ return {
539
+ lines: newLines,
540
+ cursorLine,
541
+ cursorCol: beforeSlash.length + insert.length,
542
+ };
543
+ }
544
+
545
+ // Slash command suggestions can be accepted before the debounced refresh
546
+ // catches up to newly typed characters. Replace the live command token,
547
+ // not only the prefix captured when the suggestion list was rendered.
548
+ if (findLeadingSlashCommandStart(prefix) !== null && leadingSlashStart !== null) {
549
+ const slashPrefix = textBeforeCursor.slice(leadingSlashStart);
550
+ if (!slashPrefix.includes(" ") && !slashPrefix.slice(1).includes("/")) {
551
+ const beforeSlash = currentLine.slice(0, leadingSlashStart);
552
+ const newLine = `${beforeSlash}/${item.value} ${afterCursor}`;
553
+ const newLines = [...lines];
554
+ newLines[cursorLine] = newLine;
555
+
556
+ return {
557
+ lines: newLines,
558
+ cursorLine,
559
+ cursorCol: beforeSlash.length + item.value.length + 2, // +2 for "/" and space
560
+ };
561
+ }
562
+ }
563
+
564
+ let beforePrefix = currentLine.slice(0, cursorCol - prefix.length);
565
+
566
+ // Check if we're completing a file attachment (prefix starts with "@")
567
+ if (prefix.startsWith("@")) {
568
+ const liveAtPrefix = this.#extractAtPrefix(textBeforeCursor);
569
+ if (liveAtPrefix) {
570
+ beforePrefix = currentLine.slice(0, cursorCol - liveAtPrefix.length);
571
+ }
572
+ // This is a file attachment completion
573
+ const newLine = `${beforePrefix + item.value} ${afterCursor}`;
574
+ const newLines = [...lines];
575
+ newLines[cursorLine] = newLine;
576
+
577
+ return {
578
+ lines: newLines,
579
+ cursorLine,
580
+ cursorCol: beforePrefix.length + item.value.length + 1, // +1 for space
581
+ };
582
+ }
583
+
584
+ // Slash command argument and plain file path completion both fall through
585
+ // to the path-completion tail below — `beforePrefix` already covers the
586
+ // rendered prefix, which preserves earlier arguments (e.g. accepting
587
+ // `package.json` for `/swarm run pac<Tab>` keeps the `run` token intact).
588
+ // For file paths, complete the path
589
+ const newLine = beforePrefix + item.value + afterCursor;
590
+ const newLines = [...lines];
591
+ newLines[cursorLine] = newLine;
592
+
593
+ return {
594
+ lines: newLines,
595
+ cursorLine,
596
+ cursorCol: beforePrefix.length + item.value.length,
597
+ };
598
+ }
599
+
600
+ // Extract @ prefix for fuzzy file suggestions
601
+ #extractAtPrefix(text: string): string | null {
602
+ const quotedPrefix = extractQuotedPrefix(text);
603
+ if (quotedPrefix?.startsWith('@"')) {
604
+ return quotedPrefix;
605
+ }
606
+
607
+ const lastDelimiterIndex = findLastDelimiter(text);
608
+ const tokenStart = lastDelimiterIndex === -1 ? 0 : lastDelimiterIndex + 1;
609
+
610
+ if (text[tokenStart] === "@") {
611
+ return text.slice(tokenStart);
612
+ }
613
+
614
+ return null;
615
+ }
616
+
617
+ // Extract a path-like prefix from the text before cursor
618
+ #extractPathPrefix(text: string, forceExtract: boolean = false): string | null {
619
+ const quotedPrefix = extractQuotedPrefix(text);
620
+ if (quotedPrefix) {
621
+ return quotedPrefix;
622
+ }
623
+
624
+ const lastDelimiterIndex = findLastDelimiter(text);
625
+ const pathPrefix = lastDelimiterIndex === -1 ? text : text.slice(lastDelimiterIndex + 1);
626
+
627
+ // For forced extraction (Tab key), always return something
628
+ if (forceExtract) {
629
+ return pathPrefix;
630
+ }
631
+
632
+ // For natural triggers, return if it looks like a path, ends with /, starts with ~/, .
633
+ // Only return empty string if the text looks like it's starting a path context
634
+ if (pathPrefix.includes("/") || pathPrefix.startsWith(".") || pathPrefix.startsWith("~/")) {
635
+ return pathPrefix;
636
+ }
637
+
638
+ // Return empty string only after a space (not for completely empty text)
639
+ // Empty text should not trigger file suggestions - that's for forced Tab completion
640
+ if (pathPrefix === "" && text.endsWith(" ")) {
641
+ return pathPrefix;
642
+ }
643
+
644
+ return null;
645
+ }
646
+
647
+ // Expand home directory (~/) to actual home path
648
+ #expandHomePath(filePath: string): string {
649
+ if (filePath.startsWith("~/")) {
650
+ const expandedPath = path.join(os.homedir(), filePath.slice(2));
651
+ // Preserve trailing slash if original path had one
652
+ return filePath.endsWith("/") && !expandedPath.endsWith("/") ? `${expandedPath}/` : expandedPath;
653
+ } else if (filePath === "~") {
654
+ return os.homedir();
655
+ }
656
+ return filePath;
657
+ }
658
+
659
+ // Resolve `rawPrefix` lexically (no I/O) and report whether it points
660
+ // somewhere outside `this.#basePath`. Used to skip recursive fuzzy walks
661
+ // rooted at parent / absolute / home paths — those routinely include
662
+ // thousands of unrelated files and stall the UI for seconds.
663
+ #isOutsideCwd(rawPrefix: string): boolean {
664
+ if (rawPrefix.length === 0) return false;
665
+ let target: string;
666
+ if (rawPrefix.startsWith("~")) {
667
+ target = this.#expandHomePath(rawPrefix);
668
+ } else if (path.isAbsolute(rawPrefix)) {
669
+ target = rawPrefix;
670
+ } else {
671
+ target = path.resolve(this.#basePath, rawPrefix);
672
+ }
673
+ const rel = path.relative(this.#basePath, target);
674
+ if (rel === "" || rel === ".") return false;
675
+ if (path.isAbsolute(rel)) return true;
676
+ const firstSep = rel.indexOf(path.sep);
677
+ const head = firstSep === -1 ? rel : rel.slice(0, firstSep);
678
+ return head === "..";
679
+ }
680
+
681
+ async #resolveScopedFuzzyQuery(
682
+ rawQuery: string,
683
+ ): Promise<{ baseDir: string; query: string; displayBase: string } | null> {
684
+ const slashIndex = rawQuery.lastIndexOf("/");
685
+ if (slashIndex === -1) {
686
+ return null;
687
+ }
688
+
689
+ const displayBase = rawQuery.slice(0, slashIndex + 1);
690
+ const query = rawQuery.slice(slashIndex + 1);
691
+
692
+ let baseDir: string;
693
+ if (displayBase.startsWith("~/")) {
694
+ baseDir = this.#expandHomePath(displayBase);
695
+ } else if (displayBase.startsWith("/")) {
696
+ baseDir = displayBase;
697
+ } else {
698
+ baseDir = path.join(this.#basePath, displayBase);
699
+ }
700
+
701
+ try {
702
+ if (!(await fs.promises.stat(baseDir)).isDirectory()) {
703
+ return null;
704
+ }
705
+ } catch {
706
+ return null;
707
+ }
708
+
709
+ return { baseDir, query, displayBase };
710
+ }
711
+
712
+ #scopedPathForDisplay(displayBase: string, relativePath: string): string {
713
+ if (displayBase === "/") {
714
+ return `/${relativePath}`;
715
+ }
716
+ return `${displayBase}${relativePath}`;
717
+ }
718
+
719
+ async #getCachedDirEntries(searchDir: string): Promise<fs.Dirent[]> {
720
+ const now = Date.now();
721
+ const cached = this.#dirCache.get(searchDir);
722
+
723
+ if (cached && now - cached.timestamp < this.#DIR_CACHE_TTL) {
724
+ return cached.entries;
725
+ }
726
+
727
+ const entries = await fs.promises.readdir(searchDir, { withFileTypes: true });
728
+ this.#dirCache.set(searchDir, { entries, timestamp: now });
729
+
730
+ if (this.#dirCache.size > 100) {
731
+ const sortedKeys = [...this.#dirCache.entries()]
732
+ .sort((a, b) => a[1].timestamp - b[1].timestamp)
733
+ .slice(0, 50)
734
+ .map(([key]) => key);
735
+ for (const key of sortedKeys) {
736
+ this.#dirCache.delete(key);
737
+ }
738
+ }
739
+
740
+ return entries;
741
+ }
742
+
743
+ invalidateDirCache(dir?: string): void {
744
+ if (dir) {
745
+ this.#dirCache.delete(dir);
746
+ } else {
747
+ this.#dirCache.clear();
748
+ }
749
+ }
750
+
751
+ // Get file/directory suggestions for a given path prefix
752
+ async #getFileSuggestions(prefix: string): Promise<AutocompleteItem[]> {
753
+ try {
754
+ let searchDir: string;
755
+ let searchPrefix: string;
756
+ const { rawPrefix, isAtPrefix, isQuotedPrefix } = parsePathPrefix(prefix);
757
+ let expandedPrefix = rawPrefix;
758
+
759
+ // Normalize backslashes to forward slashes so Windows native paths
760
+ // (C:\tmp\foo) work with the /-based splitting/joining below.
761
+ expandedPrefix = expandedPrefix.replace(/\\/g, "/");
762
+
763
+ // Capture the pre-expansion prefix so root checks can still
764
+ // detect bare "~" and "~/" after #expandHomePath rewrites them.
765
+ const preExpand = expandedPrefix;
766
+
767
+ // Handle home directory expansion
768
+ if (expandedPrefix.startsWith("~")) {
769
+ expandedPrefix = this.#expandHomePath(expandedPrefix);
770
+ }
771
+
772
+ const isRootPrefix =
773
+ preExpand === "" ||
774
+ preExpand === "./" ||
775
+ preExpand === "../" ||
776
+ preExpand === "~" ||
777
+ preExpand === "~/" ||
778
+ preExpand === "/" ||
779
+ (isAtPrefix && preExpand === "");
780
+
781
+ if (isRootPrefix) {
782
+ // Complete from specified position
783
+ if (expandedPrefix.startsWith("~") || path.isAbsolute(expandedPrefix)) {
784
+ searchDir = expandedPrefix;
785
+ } else {
786
+ searchDir = path.join(this.#basePath, expandedPrefix);
787
+ }
788
+ searchPrefix = "";
789
+ } else if (expandedPrefix.endsWith("/")) {
790
+ // If prefix ends with /, show contents of that directory
791
+ if (expandedPrefix.startsWith("~") || path.isAbsolute(expandedPrefix)) {
792
+ searchDir = expandedPrefix;
793
+ } else {
794
+ searchDir = path.join(this.#basePath, expandedPrefix);
795
+ }
796
+ searchPrefix = "";
797
+ } else {
798
+ // Split into directory and file prefix
799
+ const dir = path.dirname(expandedPrefix);
800
+ const file = path.basename(expandedPrefix);
801
+ if (expandedPrefix.startsWith("~") || path.isAbsolute(expandedPrefix)) {
802
+ searchDir = dir;
803
+ } else {
804
+ searchDir = path.join(this.#basePath, dir);
805
+ }
806
+ searchPrefix = file;
807
+ }
808
+
809
+ const entries = await this.#getCachedDirEntries(searchDir);
810
+ const suggestions: AutocompleteItem[] = [];
811
+
812
+ for (const entry of entries) {
813
+ if (!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase())) {
814
+ continue;
815
+ }
816
+ // Skip .git directory
817
+ if (entry.name === ".git") {
818
+ continue;
819
+ }
820
+
821
+ // Check if entry is a directory (or a symlink pointing to a directory)
822
+ let isDirectory = entry.isDirectory();
823
+ if (!isDirectory && entry.isSymbolicLink()) {
824
+ try {
825
+ const fullPath = path.join(searchDir, entry.name);
826
+ isDirectory = (await fs.promises.stat(fullPath)).isDirectory();
827
+ } catch {
828
+ // Broken symlink, file deleted between readdir and stat, or permission error
829
+ continue;
830
+ }
831
+ }
832
+
833
+ let relativePath: string;
834
+ const name = entry.name;
835
+ const displayPrefix = rawPrefix.replace(/\\/g, "/");
836
+
837
+ if (displayPrefix.endsWith("/")) {
838
+ // If prefix ends with /, append entry to the prefix
839
+ relativePath = displayPrefix + name;
840
+ } else if (displayPrefix.includes("/")) {
841
+ // Preserve ~/ format for home directory paths
842
+ if (displayPrefix.startsWith("~/")) {
843
+ const homeRelativeDir = displayPrefix.slice(2); // Remove ~/
844
+ const dir = path.dirname(homeRelativeDir);
845
+ relativePath = `~/${dir === "." ? name : path.join(dir, name)}`;
846
+ } else if (path.isAbsolute(displayPrefix)) {
847
+ // Absolute path — covers both /unix/paths and Windows C:/drive/paths.
848
+ // Use string concat with / instead of path.join (which uses platform-native
849
+ // separators and produces drive-relative results like "C:alpha" when
850
+ // dirname returns "C:" without a trailing slash).
851
+ const dir = displayPrefix.slice(0, displayPrefix.lastIndexOf("/"));
852
+ relativePath = dir === "" || dir === "/" ? `/${name}` : `${dir}/${name}`;
853
+ } else {
854
+ relativePath = path.join(path.dirname(displayPrefix), name);
855
+ if (displayPrefix.startsWith("./") && !relativePath.startsWith("./")) {
856
+ relativePath = `./${relativePath}`;
857
+ }
858
+ }
859
+ } else {
860
+ // For standalone entries, preserve ~/ if original prefix was ~/
861
+ if (displayPrefix.startsWith("~")) {
862
+ relativePath = `~/${name}`;
863
+ } else {
864
+ relativePath = name;
865
+ }
866
+ }
867
+
868
+ // Normalize backslashes to forward slashes so suggestions are consistent
869
+ // with the user's input (which uses / on all platforms) and work correctly
870
+ // when inserted back into the editor. Forward slashes are valid on Windows.
871
+ relativePath = relativePath.replace(/\\/g, "/");
872
+ const pathValue = isDirectory ? `${relativePath}/` : relativePath;
873
+ const value = buildCompletionValue(pathValue, {
874
+ isDirectory,
875
+ isAtPrefix,
876
+ isQuotedPrefix,
877
+ });
878
+
879
+ suggestions.push({
880
+ value,
881
+ label: name + (isDirectory ? "/" : ""),
882
+ });
883
+ }
884
+
885
+ // Sort directories first, then alphabetically
886
+ suggestions.sort((a, b) => {
887
+ const aIsDir = a.value.endsWith("/");
888
+ const bIsDir = b.value.endsWith("/");
889
+ if (aIsDir && !bIsDir) return -1;
890
+ if (!aIsDir && bIsDir) return 1;
891
+ return a.label.localeCompare(b.label);
892
+ });
893
+
894
+ return suggestions;
895
+ } catch {
896
+ // Directory doesn't exist or not accessible
897
+ return [];
898
+ }
899
+ }
900
+
901
+ async #getFuzzyFileSuggestions(query: string, options: { isQuotedPrefix: boolean }): Promise<AutocompleteItem[]> {
902
+ try {
903
+ const scopedQuery = await this.#resolveScopedFuzzyQuery(query);
904
+ const searchPath = scopedQuery?.baseDir ?? this.#basePath;
905
+ const fuzzyQuery = scopedQuery?.query ?? query;
906
+ const result = await fuzzyFind(buildAutocompleteFuzzyDiscoveryProfile(fuzzyQuery, searchPath));
907
+ const lowerQuery = fuzzyQuery.toLowerCase();
908
+ const filteredMatches = result.matches.filter(entry => {
909
+ const p = entry.path.endsWith("/") ? entry.path.slice(0, -1) : entry.path;
910
+ const normalized = p.replaceAll("\\", "/");
911
+ if (/(^|\/)\.git(\/|$)/.test(normalized)) {
912
+ return false;
913
+ }
914
+ return lowerQuery.length === 0 || fuzzyMatch(lowerQuery, normalized.toLowerCase());
915
+ });
916
+ // `fuzzyFind` is already capped via `maxResults` in
917
+ // `buildAutocompleteFuzzyDiscoveryProfile`; no extra slice here.
918
+ const topEntries = filteredMatches;
919
+ const suggestions: AutocompleteItem[] = [];
920
+ for (const { path: entryPath, isDirectory } of topEntries) {
921
+ const pathWithoutSlash = isDirectory ? entryPath.slice(0, -1) : entryPath;
922
+ const displayPath = scopedQuery
923
+ ? this.#scopedPathForDisplay(scopedQuery.displayBase, pathWithoutSlash)
924
+ : pathWithoutSlash;
925
+ const entryName = path.basename(pathWithoutSlash);
926
+ const completionPath = isDirectory ? `${displayPath}/` : displayPath;
927
+ const value = buildCompletionValue(completionPath, {
928
+ isDirectory,
929
+ isAtPrefix: true,
930
+ isQuotedPrefix: options.isQuotedPrefix,
931
+ });
932
+ suggestions.push({
933
+ value,
934
+ label: entryName + (isDirectory ? "/" : ""),
935
+ description: displayPath,
936
+ });
937
+ }
938
+ return suggestions;
939
+ } catch {
940
+ return [];
941
+ }
942
+ }
943
+
944
+ // Force file completion (called on Tab key) - always returns suggestions
945
+ async getForceFileSuggestions(
946
+ lines: string[],
947
+ cursorLine: number,
948
+ cursorCol: number,
949
+ ): Promise<{ items: AutocompleteItem[]; prefix: string } | null> {
950
+ const currentLine = lines[cursorLine] || "";
951
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
952
+
953
+ // Don't trigger if we're typing a slash command at the start of the line
954
+ if (textBeforeCursor.trim().startsWith("/") && !textBeforeCursor.trim().includes(" ")) {
955
+ return null;
956
+ }
957
+
958
+ // Force extract path prefix - this will always return something
959
+ const pathMatch = this.#extractPathPrefix(textBeforeCursor, true);
960
+ if (pathMatch !== null) {
961
+ const suggestions = await this.#getFileSuggestions(pathMatch);
962
+ if (suggestions.length === 0) return null;
963
+
964
+ return {
965
+ items: suggestions,
966
+ prefix: pathMatch,
967
+ };
968
+ }
969
+
970
+ return null;
971
+ }
972
+
973
+ // Check if we should trigger file completion (called on Tab key)
974
+ shouldTriggerFileCompletion(lines: string[], cursorLine: number, cursorCol: number): boolean {
975
+ const currentLine = lines[cursorLine] || "";
976
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
977
+
978
+ // Don't trigger if we're typing a slash command at the start of the line
979
+ if (textBeforeCursor.trim().startsWith("/") && !textBeforeCursor.trim().includes(" ")) {
980
+ return false;
981
+ }
982
+
983
+ return true;
984
+ }
985
+
986
+ /** Get inline hint text for slash commands with subcommand hints */
987
+ getInlineHint(lines: string[], cursorLine: number, cursorCol: number): string | null {
988
+ const currentLine = lines[cursorLine] || "";
989
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
990
+
991
+ const slashStart = findLeadingSlashCommandStart(textBeforeCursor);
992
+ if (slashStart === null) return null;
993
+
994
+ const commandText = textBeforeCursor.slice(slashStart);
995
+ const spaceIndex = commandText.indexOf(" ");
996
+ if (spaceIndex === -1) return null;
997
+
998
+ const commandName = commandText.slice(1, spaceIndex);
999
+ const argumentText = commandText.slice(spaceIndex + 1);
1000
+
1001
+ const command = this.#commands.find(cmd => commandMatchesNameOrAlias(cmd, commandName));
1002
+
1003
+ if (!command || !("getInlineHint" in command) || !command.getInlineHint) {
1004
+ return null;
1005
+ }
1006
+
1007
+ return command.getInlineHint(argumentText);
1008
+ }
1009
+ trySyncSlashCompletion(textBeforeCursor: string): { items: AutocompleteItem[]; prefix: string } | null {
1010
+ const slashStart = findLeadingSlashCommandStart(textBeforeCursor);
1011
+ if (slashStart === null) return null;
1012
+ const commandText = textBeforeCursor.slice(slashStart);
1013
+ if (commandText.length <= 1) return null; // Bare "/" alone, don't auto-complete
1014
+ if (commandText.includes(" ")) return null; // Only complete command name, not args
1015
+
1016
+ const prefix = commandText.slice(1);
1017
+ const lowerPrefix = prefix.toLowerCase();
1018
+
1019
+ const matches = buildSlashCommandCompletions(this.#commands, lowerPrefix);
1020
+
1021
+ if (matches.length === 0) return null;
1022
+ // Mirror `getSuggestions`: preserve leading whitespace so the editor's
1023
+ // sync apply path passes the full text-before-cursor through.
1024
+ return { items: matches, prefix: textBeforeCursor };
1025
+ }
1026
+ }