@visual-z/xeno 0.1.0

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 (180) hide show
  1. package/README.md +498 -0
  2. package/docs/install.md +130 -0
  3. package/package.json +43 -0
  4. package/src/apps/approve.ts +49 -0
  5. package/src/apps/cli.ts +37 -0
  6. package/src/apps/commands.ts +226 -0
  7. package/src/apps/completions.ts +28 -0
  8. package/src/apps/input.ts +297 -0
  9. package/src/apps/render.ts +207 -0
  10. package/src/apps/shell.ts +2353 -0
  11. package/src/apps/startup.ts +1302 -0
  12. package/src/core/benchmark.ts +195 -0
  13. package/src/core/boundary.ts +174 -0
  14. package/src/core/churn.ts +59 -0
  15. package/src/core/completion-review.ts +66 -0
  16. package/src/core/context-policy.ts +60 -0
  17. package/src/core/context-window.ts +54 -0
  18. package/src/core/continuation.ts +114 -0
  19. package/src/core/cycle.ts +17 -0
  20. package/src/core/data-query.ts +201 -0
  21. package/src/core/deadline.ts +39 -0
  22. package/src/core/derive.ts +489 -0
  23. package/src/core/edit-plan.ts +200 -0
  24. package/src/core/environment.ts +29 -0
  25. package/src/core/event-validation.ts +99 -0
  26. package/src/core/events.ts +486 -0
  27. package/src/core/evidence-links.ts +71 -0
  28. package/src/core/evidence.ts +89 -0
  29. package/src/core/execution.ts +12 -0
  30. package/src/core/exhaustive.ts +18 -0
  31. package/src/core/experiment.ts +40 -0
  32. package/src/core/export.ts +169 -0
  33. package/src/core/file-references.ts +35 -0
  34. package/src/core/frontmatter.ts +213 -0
  35. package/src/core/handoff.ts +397 -0
  36. package/src/core/harness-comparison.ts +90 -0
  37. package/src/core/history-query.ts +103 -0
  38. package/src/core/history.ts +100 -0
  39. package/src/core/json-event.ts +135 -0
  40. package/src/core/json-pointer.ts +46 -0
  41. package/src/core/keymap.ts +241 -0
  42. package/src/core/observation-view.ts +87 -0
  43. package/src/core/outcome.ts +45 -0
  44. package/src/core/overflow.ts +59 -0
  45. package/src/core/permissions.ts +182 -0
  46. package/src/core/policy-evaluation.ts +55 -0
  47. package/src/core/progress.ts +101 -0
  48. package/src/core/project.ts +372 -0
  49. package/src/core/prompts.ts +83 -0
  50. package/src/core/queue.ts +60 -0
  51. package/src/core/read-bounds.ts +15 -0
  52. package/src/core/recall-analysis.ts +90 -0
  53. package/src/core/recall-trial.ts +153 -0
  54. package/src/core/response-recovery.ts +46 -0
  55. package/src/core/scheduling.ts +8 -0
  56. package/src/core/settings.ts +174 -0
  57. package/src/core/skills.ts +121 -0
  58. package/src/core/stall.ts +48 -0
  59. package/src/core/text-normalize.ts +81 -0
  60. package/src/core/theme.ts +179 -0
  61. package/src/core/tokens.ts +149 -0
  62. package/src/core/tool-contract.ts +102 -0
  63. package/src/core/tool-input.ts +38 -0
  64. package/src/core/transcript.ts +60 -0
  65. package/src/core/window-trial.ts +65 -0
  66. package/src/core/work-state.ts +103 -0
  67. package/src/core/yaml.ts +282 -0
  68. package/src/index.ts +10 -0
  69. package/src/runtime/auth.ts +255 -0
  70. package/src/runtime/benchmark.ts +187 -0
  71. package/src/runtime/catalog.ts +365 -0
  72. package/src/runtime/evidence-notes.ts +33 -0
  73. package/src/runtime/exec-sessions.ts +214 -0
  74. package/src/runtime/execution-control.ts +39 -0
  75. package/src/runtime/harness-comparison.ts +356 -0
  76. package/src/runtime/history-tools.ts +108 -0
  77. package/src/runtime/loop.ts +1983 -0
  78. package/src/runtime/model.ts +614 -0
  79. package/src/runtime/models-fetch.ts +155 -0
  80. package/src/runtime/oauth-device.ts +86 -0
  81. package/src/runtime/oauth.ts +759 -0
  82. package/src/runtime/openai-responses.ts +286 -0
  83. package/src/runtime/openai.ts +675 -0
  84. package/src/runtime/provider.ts +498 -0
  85. package/src/runtime/recall-trial.ts +226 -0
  86. package/src/runtime/resume.ts +66 -0
  87. package/src/runtime/retry.ts +297 -0
  88. package/src/runtime/tools.ts +1193 -0
  89. package/src/runtime/usage.ts +225 -0
  90. package/src/runtime/window-trial.ts +140 -0
  91. package/src/runtime/working-notes.ts +30 -0
  92. package/src/store/atomic.ts +31 -0
  93. package/src/store/auth-store.ts +50 -0
  94. package/src/store/blobs.ts +142 -0
  95. package/src/store/command.ts +75 -0
  96. package/src/store/config.ts +69 -0
  97. package/src/store/context-files.ts +356 -0
  98. package/src/store/file-index.ts +81 -0
  99. package/src/store/git-branch.ts +35 -0
  100. package/src/store/history-search.ts +19 -0
  101. package/src/store/log.ts +642 -0
  102. package/src/store/models.ts +41 -0
  103. package/src/store/observations.ts +181 -0
  104. package/src/store/query-source.ts +44 -0
  105. package/src/store/recovery.ts +39 -0
  106. package/src/store/replay.ts +63 -0
  107. package/src/store/resources.ts +361 -0
  108. package/src/store/restore.ts +302 -0
  109. package/src/store/search.ts +644 -0
  110. package/src/store/serial.ts +13 -0
  111. package/src/store/sessions.ts +463 -0
  112. package/src/store/trust.ts +69 -0
  113. package/src/store/workspace.ts +256 -0
  114. package/src/store/worktree.ts +233 -0
  115. package/src/tui/ansi.ts +67 -0
  116. package/src/tui/autocomplete.ts +29 -0
  117. package/src/tui/complete.ts +87 -0
  118. package/src/tui/diff.ts +160 -0
  119. package/src/tui/editor.ts +893 -0
  120. package/src/tui/exhaustive.ts +14 -0
  121. package/src/tui/fuzzy.ts +75 -0
  122. package/src/tui/host.ts +223 -0
  123. package/src/tui/input.ts +69 -0
  124. package/src/tui/keys.ts +378 -0
  125. package/src/tui/markdown.ts +17 -0
  126. package/src/tui/render.ts +153 -0
  127. package/src/tui/select.ts +240 -0
  128. package/src/tui/settings.ts +40 -0
  129. package/src/tui/statusline.ts +162 -0
  130. package/src/tui/style.ts +205 -0
  131. package/src/tui/terminal.ts +30 -0
  132. package/src/tui/text.ts +52 -0
  133. package/src/tui/toolview.ts +386 -0
  134. package/src/tui/transcript.ts +71 -0
  135. package/src/tui/tree.ts +405 -0
  136. package/src/tui/width.ts +567 -0
  137. package/src/vendor/pi-tui/LICENSE.upstream +21 -0
  138. package/src/vendor/pi-tui/VENDOR.md +23 -0
  139. package/src/vendor/pi-tui/alt-screen-search.ts +327 -0
  140. package/src/vendor/pi-tui/autocomplete.ts +835 -0
  141. package/src/vendor/pi-tui/components/alt-screen-flash.ts +51 -0
  142. package/src/vendor/pi-tui/components/box.ts +167 -0
  143. package/src/vendor/pi-tui/components/cancellable-loader.ts +40 -0
  144. package/src/vendor/pi-tui/components/editor.ts +2470 -0
  145. package/src/vendor/pi-tui/components/h-stack.ts +44 -0
  146. package/src/vendor/pi-tui/components/image.ts +127 -0
  147. package/src/vendor/pi-tui/components/input.ts +494 -0
  148. package/src/vendor/pi-tui/components/loader.ts +101 -0
  149. package/src/vendor/pi-tui/components/markdown.ts +1015 -0
  150. package/src/vendor/pi-tui/components/mouse-region.ts +33 -0
  151. package/src/vendor/pi-tui/components/scroll-view.ts +224 -0
  152. package/src/vendor/pi-tui/components/select-list.ts +273 -0
  153. package/src/vendor/pi-tui/components/settings-list.ts +328 -0
  154. package/src/vendor/pi-tui/components/spacer.ts +28 -0
  155. package/src/vendor/pi-tui/components/stack.ts +154 -0
  156. package/src/vendor/pi-tui/components/text.ts +107 -0
  157. package/src/vendor/pi-tui/components/truncated-text.ts +65 -0
  158. package/src/vendor/pi-tui/components/v-stack.ts +33 -0
  159. package/src/vendor/pi-tui/editor-component.ts +74 -0
  160. package/src/vendor/pi-tui/fuzzy.ts +138 -0
  161. package/src/vendor/pi-tui/index.ts +156 -0
  162. package/src/vendor/pi-tui/keybindings.ts +320 -0
  163. package/src/vendor/pi-tui/keys.ts +1401 -0
  164. package/src/vendor/pi-tui/kill-ring.ts +46 -0
  165. package/src/vendor/pi-tui/latex.ts +1506 -0
  166. package/src/vendor/pi-tui/layout-node.ts +51 -0
  167. package/src/vendor/pi-tui/layout.ts +449 -0
  168. package/src/vendor/pi-tui/native-modifiers.ts +13 -0
  169. package/src/vendor/pi-tui/native-module-path.ts +31 -0
  170. package/src/vendor/pi-tui/native-platform.ts +63 -0
  171. package/src/vendor/pi-tui/stdin-buffer.ts +444 -0
  172. package/src/vendor/pi-tui/terminal-colors.ts +73 -0
  173. package/src/vendor/pi-tui/terminal-image.ts +696 -0
  174. package/src/vendor/pi-tui/terminal.ts +547 -0
  175. package/src/vendor/pi-tui/tui-alt-screen.ts +1742 -0
  176. package/src/vendor/pi-tui/tui-main-screen.ts +655 -0
  177. package/src/vendor/pi-tui/tui.ts +1456 -0
  178. package/src/vendor/pi-tui/undo-stack.ts +28 -0
  179. package/src/vendor/pi-tui/utils.ts +1345 -0
  180. package/src/vendor/pi-tui/word-navigation.ts +117 -0
@@ -0,0 +1,835 @@
1
+ import { spawn } from "child_process";
2
+ import { readdirSync, statSync } from "fs";
3
+ import { homedir } from "os";
4
+ import { basename, dirname, join } from "path";
5
+ import { fuzzyFilter } from "./fuzzy.ts";
6
+ import { autocompleteBoundaryRegex, autocompleteSeparatorRegex } from "./utils.ts";
7
+
8
+ const PATH_DELIMITERS = new Set([" ", "\t", '"', "'", "="]);
9
+ const tokenStartRegex = new RegExp(`${autocompleteBoundaryRegex.source}$`, "u");
10
+
11
+ function toDisplayPath(value: string): string {
12
+ return value.replace(/\\/g, "/");
13
+ }
14
+
15
+ function escapeRegex(value: string): string {
16
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17
+ }
18
+
19
+ function buildFdPathQuery(query: string): string {
20
+ const normalized = toDisplayPath(query);
21
+ if (!normalized.includes("/")) {
22
+ return normalized;
23
+ }
24
+
25
+ const hasTrailingSeparator = normalized.endsWith("/");
26
+ const trimmed = normalized.replace(/^\/+|\/+$/g, "");
27
+ if (!trimmed) {
28
+ return normalized;
29
+ }
30
+
31
+ const separatorPattern = "[\\\\/]";
32
+ const segments = trimmed
33
+ .split("/")
34
+ .filter(Boolean)
35
+ .map((segment) => escapeRegex(segment));
36
+ if (segments.length === 0) {
37
+ return normalized;
38
+ }
39
+
40
+ let pattern = segments.join(separatorPattern);
41
+ if (hasTrailingSeparator) {
42
+ pattern += separatorPattern;
43
+ }
44
+ return pattern;
45
+ }
46
+
47
+ function findLastDelimiter(text: string): number {
48
+ let lastDelimiter = -1;
49
+ let index = 0;
50
+ for (const character of text) {
51
+ index += character.length;
52
+ if (PATH_DELIMITERS.has(character) || autocompleteSeparatorRegex.test(character)) {
53
+ lastDelimiter = index - 1;
54
+ }
55
+ }
56
+ return lastDelimiter;
57
+ }
58
+
59
+ function findUnclosedQuoteStart(text: string): number | null {
60
+ let inQuotes = false;
61
+ let quoteStart = -1;
62
+
63
+ for (let i = 0; i < text.length; i += 1) {
64
+ if (text[i] === '"') {
65
+ inQuotes = !inQuotes;
66
+ if (inQuotes) {
67
+ quoteStart = i;
68
+ }
69
+ }
70
+ }
71
+
72
+ return inQuotes ? quoteStart : null;
73
+ }
74
+
75
+ function isTokenStart(text: string, index: number): boolean {
76
+ return PATH_DELIMITERS.has(text[index - 1] ?? "") || tokenStartRegex.test(text.slice(0, index));
77
+ }
78
+
79
+ function extractQuotedPrefix(text: string): string | null {
80
+ const quoteStart = findUnclosedQuoteStart(text);
81
+ if (quoteStart === null) {
82
+ return null;
83
+ }
84
+
85
+ if (quoteStart > 0 && text[quoteStart - 1] === "@") {
86
+ if (!isTokenStart(text, quoteStart - 1)) {
87
+ return null;
88
+ }
89
+ return text.slice(quoteStart - 1);
90
+ }
91
+
92
+ if (!isTokenStart(text, quoteStart)) {
93
+ return null;
94
+ }
95
+
96
+ return text.slice(quoteStart);
97
+ }
98
+
99
+ function parsePathPrefix(prefix: string): { rawPrefix: string; isAtPrefix: boolean; isQuotedPrefix: boolean } {
100
+ if (prefix.startsWith('@"')) {
101
+ return { rawPrefix: prefix.slice(2), isAtPrefix: true, isQuotedPrefix: true };
102
+ }
103
+ if (prefix.startsWith('"')) {
104
+ return { rawPrefix: prefix.slice(1), isAtPrefix: false, isQuotedPrefix: true };
105
+ }
106
+ if (prefix.startsWith("@")) {
107
+ return { rawPrefix: prefix.slice(1), isAtPrefix: true, isQuotedPrefix: false };
108
+ }
109
+ return { rawPrefix: prefix, isAtPrefix: false, isQuotedPrefix: false };
110
+ }
111
+
112
+ function buildCompletionValue(
113
+ path: string,
114
+ options: { isDirectory: boolean; isAtPrefix: boolean; isQuotedPrefix: boolean },
115
+ ): string {
116
+ const needsQuotes = options.isQuotedPrefix || autocompleteSeparatorRegex.test(path);
117
+ const prefix = options.isAtPrefix ? "@" : "";
118
+
119
+ if (!needsQuotes) {
120
+ return `${prefix}${path}`;
121
+ }
122
+
123
+ const openQuote = `${prefix}"`;
124
+ const closeQuote = '"';
125
+ return `${openQuote}${path}${closeQuote}`;
126
+ }
127
+
128
+ // Use fd to walk directory tree (fast, respects .gitignore)
129
+ async function walkDirectoryWithFd(
130
+ baseDir: string,
131
+ fdPath: string,
132
+ query: string,
133
+ maxResults: number,
134
+ signal: AbortSignal,
135
+ maxDepth?: number,
136
+ ): Promise<Array<{ path: string; isDirectory: boolean }>> {
137
+ const args = [
138
+ "--base-directory",
139
+ baseDir,
140
+ "--max-results",
141
+ String(maxResults),
142
+ "--type",
143
+ "f",
144
+ "--type",
145
+ "d",
146
+ "--follow",
147
+ "--hidden",
148
+ "--exclude",
149
+ ".git",
150
+ "--exclude",
151
+ ".git/*",
152
+ "--exclude",
153
+ ".git/**",
154
+ ];
155
+
156
+ if (maxDepth !== undefined) {
157
+ args.push("--max-depth", String(maxDepth));
158
+ }
159
+
160
+ if (toDisplayPath(query).includes("/")) {
161
+ args.push("--full-path");
162
+ }
163
+
164
+ if (query) {
165
+ args.push(buildFdPathQuery(query));
166
+ }
167
+
168
+ return await new Promise((resolve) => {
169
+ if (signal.aborted) {
170
+ resolve([]);
171
+ return;
172
+ }
173
+
174
+ const child = spawn(fdPath, args, {
175
+ stdio: ["ignore", "pipe", "pipe"],
176
+ });
177
+ let stdout = "";
178
+ let resolved = false;
179
+
180
+ const finish = (results: Array<{ path: string; isDirectory: boolean }>) => {
181
+ if (resolved) return;
182
+ resolved = true;
183
+ signal.removeEventListener("abort", onAbort);
184
+ resolve(results);
185
+ };
186
+
187
+ const onAbort = () => {
188
+ if (child.exitCode === null) {
189
+ child.kill("SIGKILL");
190
+ }
191
+ };
192
+
193
+ signal.addEventListener("abort", onAbort, { once: true });
194
+ child.stdout.setEncoding("utf-8");
195
+ child.stdout.on("data", (chunk: string) => {
196
+ stdout += chunk;
197
+ });
198
+ child.on("error", () => {
199
+ finish([]);
200
+ });
201
+ child.on("close", (code) => {
202
+ if (signal.aborted || code !== 0 || !stdout) {
203
+ finish([]);
204
+ return;
205
+ }
206
+
207
+ const lines = stdout.trim().split("\n").filter(Boolean);
208
+ const results: Array<{ path: string; isDirectory: boolean }> = [];
209
+
210
+ for (const line of lines) {
211
+ const displayLine = toDisplayPath(line);
212
+ const hasTrailingSeparator = displayLine.endsWith("/");
213
+ const normalizedPath = hasTrailingSeparator ? displayLine.slice(0, -1) : displayLine;
214
+ if (normalizedPath === ".git" || normalizedPath.startsWith(".git/") || normalizedPath.includes("/.git/")) {
215
+ continue;
216
+ }
217
+
218
+ results.push({
219
+ path: displayLine,
220
+ isDirectory: hasTrailingSeparator,
221
+ });
222
+ }
223
+
224
+ finish(results);
225
+ });
226
+ });
227
+ }
228
+
229
+ export interface AutocompleteItem {
230
+ value: string;
231
+ label: string;
232
+ description?: string;
233
+ }
234
+
235
+ type Awaitable<T> = T | Promise<T>;
236
+
237
+ export interface SlashCommand {
238
+ name: string;
239
+ description?: string;
240
+ argumentHint?: string;
241
+ // Function to get argument completions for this command
242
+ // Returns null if no argument completion is available
243
+ getArgumentCompletions?(argumentPrefix: string): Awaitable<AutocompleteItem[] | null>;
244
+ }
245
+
246
+ export interface AutocompleteSuggestions {
247
+ items: AutocompleteItem[];
248
+ prefix: string; // What we're matching against (e.g., "/" or "src/")
249
+ }
250
+
251
+ export interface AutocompleteProvider {
252
+ /** Characters that should naturally trigger this provider at token boundaries. */
253
+ triggerCharacters?: string[];
254
+
255
+ // Get autocomplete suggestions for current text/cursor position
256
+ // Returns null if no suggestions available
257
+ getSuggestions(
258
+ lines: string[],
259
+ cursorLine: number,
260
+ cursorCol: number,
261
+ options: { signal: AbortSignal; force?: boolean },
262
+ ): Promise<AutocompleteSuggestions | null>;
263
+
264
+ // Apply the selected item
265
+ // Returns the new text and cursor position
266
+ applyCompletion(
267
+ lines: string[],
268
+ cursorLine: number,
269
+ cursorCol: number,
270
+ item: AutocompleteItem,
271
+ prefix: string,
272
+ ): {
273
+ lines: string[];
274
+ cursorLine: number;
275
+ cursorCol: number;
276
+ };
277
+
278
+ // Check if file completion should trigger for explicit Tab completion
279
+ shouldTriggerFileCompletion?(lines: string[], cursorLine: number, cursorCol: number): boolean;
280
+ }
281
+
282
+ // Combined provider that handles both slash commands and file paths
283
+ export class CombinedAutocompleteProvider implements AutocompleteProvider {
284
+ private commands: (SlashCommand | AutocompleteItem)[];
285
+ private basePath: string;
286
+ private fdPath: string | null;
287
+
288
+ constructor(commands: (SlashCommand | AutocompleteItem)[] = [], basePath: string, fdPath: string | null = null) {
289
+ this.commands = commands;
290
+ this.basePath = basePath;
291
+ this.fdPath = fdPath;
292
+ }
293
+
294
+ async getSuggestions(
295
+ lines: string[],
296
+ cursorLine: number,
297
+ cursorCol: number,
298
+ options: { signal: AbortSignal; force?: boolean },
299
+ ): Promise<AutocompleteSuggestions | null> {
300
+ const currentLine = lines[cursorLine] || "";
301
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
302
+
303
+ const atPrefix = this.extractAtPrefix(textBeforeCursor);
304
+ if (atPrefix) {
305
+ const { rawPrefix, isQuotedPrefix } = parsePathPrefix(atPrefix);
306
+ const suggestions = await this.getFuzzyFileSuggestions(rawPrefix, {
307
+ isQuotedPrefix,
308
+ signal: options.signal,
309
+ });
310
+ if (suggestions.length === 0) return null;
311
+
312
+ return {
313
+ items: suggestions,
314
+ prefix: atPrefix,
315
+ };
316
+ }
317
+
318
+ if (!options.force && textBeforeCursor.startsWith("/")) {
319
+ const spaceIndex = textBeforeCursor.indexOf(" ");
320
+
321
+ if (spaceIndex === -1) {
322
+ const prefix = textBeforeCursor.slice(1);
323
+ const commandItems = this.commands.map((cmd) => {
324
+ const name = "name" in cmd ? cmd.name : cmd.value;
325
+ const hint = "argumentHint" in cmd && cmd.argumentHint ? cmd.argumentHint : undefined;
326
+ const desc = cmd.description ?? "";
327
+ const fullDesc = hint ? (desc ? `${hint} — ${desc}` : hint) : desc;
328
+ return {
329
+ name,
330
+ label: name,
331
+ description: fullDesc || undefined,
332
+ };
333
+ });
334
+
335
+ const filtered = fuzzyFilter(commandItems, prefix, (item) =>
336
+ !prefix.startsWith("skill:") && item.name.startsWith("skill:")
337
+ ? item.name.slice("skill:".length)
338
+ : item.name,
339
+ ).map((item) => ({
340
+ value: item.name,
341
+ label: item.label,
342
+ ...(item.description && { description: item.description }),
343
+ }));
344
+
345
+ if (filtered.length === 0) return null;
346
+
347
+ return {
348
+ items: filtered,
349
+ prefix: textBeforeCursor,
350
+ };
351
+ }
352
+
353
+ const commandName = textBeforeCursor.slice(1, spaceIndex);
354
+ const argumentText = textBeforeCursor.slice(spaceIndex + 1);
355
+
356
+ const command = this.commands.find((cmd) => {
357
+ const name = "name" in cmd ? cmd.name : cmd.value;
358
+ return name === commandName;
359
+ });
360
+ if (!command || !("getArgumentCompletions" in command) || !command.getArgumentCompletions) {
361
+ return null;
362
+ }
363
+
364
+ const argumentSuggestions = await command.getArgumentCompletions(argumentText);
365
+ if (!Array.isArray(argumentSuggestions) || argumentSuggestions.length === 0) {
366
+ return null;
367
+ }
368
+
369
+ return {
370
+ items: argumentSuggestions,
371
+ prefix: argumentText,
372
+ };
373
+ }
374
+
375
+ const pathMatch = this.extractPathPrefix(textBeforeCursor, options.force ?? false);
376
+ if (pathMatch === null) {
377
+ return null;
378
+ }
379
+
380
+ const suggestions = this.getFileSuggestions(pathMatch);
381
+ if (suggestions.length === 0) return null;
382
+
383
+ return {
384
+ items: suggestions,
385
+ prefix: pathMatch,
386
+ };
387
+ }
388
+
389
+ applyCompletion(
390
+ lines: string[],
391
+ cursorLine: number,
392
+ cursorCol: number,
393
+ item: AutocompleteItem,
394
+ prefix: string,
395
+ ): { lines: string[]; cursorLine: number; cursorCol: number } {
396
+ const currentLine = lines[cursorLine] || "";
397
+ const beforePrefix = currentLine.slice(0, cursorCol - prefix.length);
398
+ const afterCursor = currentLine.slice(cursorCol);
399
+ const isQuotedPrefix = prefix.startsWith('"') || prefix.startsWith('@"');
400
+ const hasLeadingQuoteAfterCursor = afterCursor.startsWith('"');
401
+ const hasTrailingQuoteInItem = item.value.endsWith('"');
402
+ const adjustedAfterCursor =
403
+ isQuotedPrefix && hasTrailingQuoteInItem && hasLeadingQuoteAfterCursor ? afterCursor.slice(1) : afterCursor;
404
+
405
+ // Check if we're completing a slash command (prefix starts with "/" but NOT a file path)
406
+ // Slash commands are at the start of the line and don't contain path separators after the first /
407
+ const isSlashCommand = prefix.startsWith("/") && beforePrefix.trim() === "" && !prefix.slice(1).includes("/");
408
+ if (isSlashCommand) {
409
+ // This is a command name completion
410
+ const newLine = `${beforePrefix}/${item.value} ${adjustedAfterCursor}`;
411
+ const newLines = [...lines];
412
+ newLines[cursorLine] = newLine;
413
+
414
+ return {
415
+ lines: newLines,
416
+ cursorLine,
417
+ cursorCol: beforePrefix.length + item.value.length + 2, // +2 for "/" and space
418
+ };
419
+ }
420
+
421
+ // Check if we're completing a file attachment (prefix starts with "@")
422
+ if (prefix.startsWith("@")) {
423
+ // This is a file attachment completion
424
+ // Don't add space after directories so user can continue autocompleting
425
+ const isDirectory = item.label.endsWith("/");
426
+ const suffix = isDirectory ? "" : " ";
427
+ const newLine = `${beforePrefix + item.value}${suffix}${adjustedAfterCursor}`;
428
+ const newLines = [...lines];
429
+ newLines[cursorLine] = newLine;
430
+
431
+ const hasTrailingQuote = item.value.endsWith('"');
432
+ const cursorOffset = isDirectory && hasTrailingQuote ? item.value.length - 1 : item.value.length;
433
+
434
+ return {
435
+ lines: newLines,
436
+ cursorLine,
437
+ cursorCol: beforePrefix.length + cursorOffset + suffix.length,
438
+ };
439
+ }
440
+
441
+ // Check if we're in a slash command context (beforePrefix contains "/command ")
442
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
443
+ if (textBeforeCursor.includes("/") && textBeforeCursor.includes(" ")) {
444
+ // This is likely a command argument completion
445
+ const newLine = beforePrefix + item.value + adjustedAfterCursor;
446
+ const newLines = [...lines];
447
+ newLines[cursorLine] = newLine;
448
+
449
+ const isDirectory = item.label.endsWith("/");
450
+ const hasTrailingQuote = item.value.endsWith('"');
451
+ const cursorOffset = isDirectory && hasTrailingQuote ? item.value.length - 1 : item.value.length;
452
+
453
+ return {
454
+ lines: newLines,
455
+ cursorLine,
456
+ cursorCol: beforePrefix.length + cursorOffset,
457
+ };
458
+ }
459
+
460
+ // For file paths, complete the path
461
+ const newLine = beforePrefix + item.value + adjustedAfterCursor;
462
+ const newLines = [...lines];
463
+ newLines[cursorLine] = newLine;
464
+
465
+ const isDirectory = item.label.endsWith("/");
466
+ const hasTrailingQuote = item.value.endsWith('"');
467
+ const cursorOffset = isDirectory && hasTrailingQuote ? item.value.length - 1 : item.value.length;
468
+
469
+ return {
470
+ lines: newLines,
471
+ cursorLine,
472
+ cursorCol: beforePrefix.length + cursorOffset,
473
+ };
474
+ }
475
+
476
+ // Extract @ prefix for fuzzy file suggestions
477
+ private extractAtPrefix(text: string): string | null {
478
+ const quotedPrefix = extractQuotedPrefix(text);
479
+ if (quotedPrefix?.startsWith('@"')) {
480
+ return quotedPrefix;
481
+ }
482
+
483
+ const lastDelimiterIndex = findLastDelimiter(text);
484
+ const tokenStart = lastDelimiterIndex === -1 ? 0 : lastDelimiterIndex + 1;
485
+
486
+ if (text[tokenStart] === "@") {
487
+ return text.slice(tokenStart);
488
+ }
489
+
490
+ return null;
491
+ }
492
+
493
+ // Extract a path-like prefix from the text before cursor
494
+ private extractPathPrefix(text: string, forceExtract: boolean = false): string | null {
495
+ const quotedPrefix = extractQuotedPrefix(text);
496
+ if (quotedPrefix) {
497
+ return quotedPrefix;
498
+ }
499
+
500
+ const lastDelimiterIndex = findLastDelimiter(text);
501
+ const pathPrefix = lastDelimiterIndex === -1 ? text : text.slice(lastDelimiterIndex + 1);
502
+
503
+ // For forced extraction (Tab key), always return something
504
+ if (forceExtract) {
505
+ return pathPrefix;
506
+ }
507
+
508
+ // For natural triggers, return if it looks like a path, ends with /, starts with ~/, .
509
+ // Only return empty string if the text looks like it's starting a path context
510
+ if (pathPrefix.includes("/") || pathPrefix.startsWith(".") || pathPrefix.startsWith("~/")) {
511
+ return pathPrefix;
512
+ }
513
+
514
+ // Return an empty prefix after whitespace or CJK punctuation, but not for empty text.
515
+ // Empty text should not trigger file suggestions - that's for forced Tab completion
516
+ if (pathPrefix === "" && text !== "" && tokenStartRegex.test(text)) {
517
+ return pathPrefix;
518
+ }
519
+
520
+ return null;
521
+ }
522
+
523
+ // Expand home directory (~/) to actual home path
524
+ private expandHomePath(path: string): string {
525
+ if (path.startsWith("~/")) {
526
+ const expandedPath = join(homedir(), path.slice(2));
527
+ // Preserve trailing slash if original path had one
528
+ return path.endsWith("/") && !expandedPath.endsWith("/") ? `${expandedPath}/` : expandedPath;
529
+ } else if (path === "~") {
530
+ return homedir();
531
+ }
532
+ return path;
533
+ }
534
+
535
+ private resolveScopedFuzzyQuery(rawQuery: string): { baseDir: string; query: string; displayBase: string } | null {
536
+ const normalizedQuery = toDisplayPath(rawQuery);
537
+ const slashIndex = normalizedQuery.lastIndexOf("/");
538
+ if (slashIndex === -1) {
539
+ return null;
540
+ }
541
+
542
+ const displayBase = normalizedQuery.slice(0, slashIndex + 1);
543
+ const query = normalizedQuery.slice(slashIndex + 1);
544
+
545
+ let baseDir: string;
546
+ if (displayBase.startsWith("~/")) {
547
+ baseDir = this.expandHomePath(displayBase);
548
+ } else if (displayBase.startsWith("/")) {
549
+ baseDir = displayBase;
550
+ } else {
551
+ baseDir = join(this.basePath, displayBase);
552
+ }
553
+
554
+ try {
555
+ if (!statSync(baseDir).isDirectory()) {
556
+ return null;
557
+ }
558
+ } catch {
559
+ return null;
560
+ }
561
+
562
+ return { baseDir, query, displayBase };
563
+ }
564
+
565
+ private scopedPathForDisplay(displayBase: string, relativePath: string): string {
566
+ const normalizedRelativePath = toDisplayPath(relativePath);
567
+ if (displayBase === "/") {
568
+ return `/${normalizedRelativePath}`;
569
+ }
570
+ return `${toDisplayPath(displayBase)}${normalizedRelativePath}`;
571
+ }
572
+
573
+ // Get file/directory suggestions for a given path prefix
574
+ private getFileSuggestions(prefix: string): AutocompleteItem[] {
575
+ try {
576
+ let searchDir: string;
577
+ let searchPrefix: string;
578
+ const { rawPrefix, isAtPrefix, isQuotedPrefix } = parsePathPrefix(prefix);
579
+ let expandedPrefix = rawPrefix;
580
+
581
+ // Handle home directory expansion
582
+ if (expandedPrefix.startsWith("~")) {
583
+ expandedPrefix = this.expandHomePath(expandedPrefix);
584
+ }
585
+
586
+ const isRootPrefix =
587
+ rawPrefix === "" ||
588
+ rawPrefix === "./" ||
589
+ rawPrefix === "../" ||
590
+ rawPrefix === "~" ||
591
+ rawPrefix === "~/" ||
592
+ rawPrefix === "/" ||
593
+ (isAtPrefix && rawPrefix === "");
594
+
595
+ if (isRootPrefix) {
596
+ // Complete from specified position
597
+ if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
598
+ searchDir = expandedPrefix;
599
+ } else {
600
+ searchDir = join(this.basePath, expandedPrefix);
601
+ }
602
+ searchPrefix = "";
603
+ } else if (rawPrefix.endsWith("/")) {
604
+ // If prefix ends with /, show contents of that directory
605
+ if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
606
+ searchDir = expandedPrefix;
607
+ } else {
608
+ searchDir = join(this.basePath, expandedPrefix);
609
+ }
610
+ searchPrefix = "";
611
+ } else {
612
+ // Split into directory and file prefix
613
+ const dir = dirname(expandedPrefix);
614
+ const file = basename(expandedPrefix);
615
+ if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
616
+ searchDir = dir;
617
+ } else {
618
+ searchDir = join(this.basePath, dir);
619
+ }
620
+ searchPrefix = file;
621
+ }
622
+
623
+ const entries = readdirSync(searchDir, { withFileTypes: true });
624
+ const suggestions: AutocompleteItem[] = [];
625
+
626
+ for (const entry of entries) {
627
+ if (!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase())) {
628
+ continue;
629
+ }
630
+
631
+ // Check if entry is a directory (or a symlink pointing to a directory)
632
+ let isDirectory = entry.isDirectory();
633
+ if (!isDirectory && entry.isSymbolicLink()) {
634
+ try {
635
+ const fullPath = join(searchDir, entry.name);
636
+ isDirectory = statSync(fullPath).isDirectory();
637
+ } catch {
638
+ // Broken symlink or permission error - treat as file
639
+ }
640
+ }
641
+
642
+ let relativePath: string;
643
+ const name = entry.name;
644
+ const displayPrefix = rawPrefix;
645
+
646
+ if (displayPrefix.endsWith("/")) {
647
+ // If prefix ends with /, append entry to the prefix
648
+ relativePath = displayPrefix + name;
649
+ } else if (displayPrefix.includes("/") || displayPrefix.includes("\\")) {
650
+ // Preserve ~/ format for home directory paths
651
+ if (displayPrefix.startsWith("~/")) {
652
+ const homeRelativeDir = displayPrefix.slice(2); // Remove ~/
653
+ const dir = dirname(homeRelativeDir);
654
+ relativePath = `~/${dir === "." ? name : join(dir, name)}`;
655
+ } else if (displayPrefix.startsWith("/")) {
656
+ // Absolute path - construct properly
657
+ const dir = dirname(displayPrefix);
658
+ if (dir === "/") {
659
+ relativePath = `/${name}`;
660
+ } else {
661
+ relativePath = `${dir}/${name}`;
662
+ }
663
+ } else {
664
+ relativePath = join(dirname(displayPrefix), name);
665
+ // path.join normalizes away ./ prefix, preserve it
666
+ if (displayPrefix.startsWith("./") && !relativePath.startsWith("./")) {
667
+ relativePath = `./${relativePath}`;
668
+ }
669
+ }
670
+ } else {
671
+ // For standalone entries, preserve ~/ if original prefix was ~/
672
+ if (displayPrefix.startsWith("~")) {
673
+ relativePath = `~/${name}`;
674
+ } else {
675
+ relativePath = name;
676
+ }
677
+ }
678
+
679
+ relativePath = toDisplayPath(relativePath);
680
+ const pathValue = isDirectory ? `${relativePath}/` : relativePath;
681
+ const value = buildCompletionValue(pathValue, {
682
+ isDirectory,
683
+ isAtPrefix,
684
+ isQuotedPrefix,
685
+ });
686
+
687
+ suggestions.push({
688
+ value,
689
+ label: name + (isDirectory ? "/" : ""),
690
+ });
691
+ }
692
+
693
+ // Sort directories first, then alphabetically
694
+ suggestions.sort((a, b) => {
695
+ const aIsDir = a.label.endsWith("/");
696
+ const bIsDir = b.label.endsWith("/");
697
+ if (aIsDir && !bIsDir) return -1;
698
+ if (!aIsDir && bIsDir) return 1;
699
+ return a.label.localeCompare(b.label);
700
+ });
701
+
702
+ return suggestions;
703
+ } catch (_e) {
704
+ // Directory doesn't exist or not accessible
705
+ return [];
706
+ }
707
+ }
708
+
709
+ // Score an entry against the query (higher = better match)
710
+ // isDirectory adds bonus to prioritize folders
711
+ private scoreEntry(filePath: string, query: string, isDirectory: boolean): number {
712
+ const fileName = basename(filePath);
713
+ const lowerFileName = fileName.toLowerCase();
714
+ const lowerQuery = query.toLowerCase();
715
+
716
+ let score = 0;
717
+
718
+ // Exact filename match (highest)
719
+ if (lowerFileName === lowerQuery) score = 100;
720
+ // Filename starts with query
721
+ else if (lowerFileName.startsWith(lowerQuery)) score = 80;
722
+ // Substring match in filename
723
+ else if (lowerFileName.includes(lowerQuery)) score = 50;
724
+ // Substring match in full path
725
+ else if (filePath.toLowerCase().includes(lowerQuery)) score = 30;
726
+
727
+ // Directories get a bonus to appear first
728
+ if (isDirectory && score > 0) score += 10;
729
+
730
+ return score;
731
+ }
732
+
733
+ private async getBaseDirSuggestions(
734
+ baseDir: string,
735
+ query: string,
736
+ signal: AbortSignal,
737
+ ): Promise<Array<{ path: string; isDirectory: boolean }>> {
738
+ if (!this.fdPath || signal.aborted) {
739
+ return [];
740
+ }
741
+
742
+ return await walkDirectoryWithFd(baseDir, this.fdPath, query, 100, signal, 1);
743
+ }
744
+
745
+ // Fuzzy file search using fd (fast, respects .gitignore)
746
+ private async getFuzzyFileSuggestions(
747
+ query: string,
748
+ options: { isQuotedPrefix: boolean; signal: AbortSignal },
749
+ ): Promise<AutocompleteItem[]> {
750
+ if (!this.fdPath || options.signal.aborted) {
751
+ return [];
752
+ }
753
+
754
+ try {
755
+ const scopedQuery = this.resolveScopedFuzzyQuery(query);
756
+ const fdBaseDir = scopedQuery?.baseDir ?? this.basePath;
757
+ const fdQuery = scopedQuery?.query ?? query;
758
+ const baseDirEntries = await this.getBaseDirSuggestions(fdBaseDir, fdQuery, options.signal);
759
+ const recursiveEntries = await walkDirectoryWithFd(fdBaseDir, this.fdPath, fdQuery, 100, options.signal);
760
+ const seenPaths = new Set(baseDirEntries.map((entry) => entry.path));
761
+ const entries = [
762
+ ...baseDirEntries,
763
+ ...recursiveEntries.filter((entry) => {
764
+ if (seenPaths.has(entry.path)) return false;
765
+ seenPaths.add(entry.path);
766
+ return true;
767
+ }),
768
+ ];
769
+ if (options.signal.aborted) {
770
+ return [];
771
+ }
772
+
773
+ const scoredEntries = entries
774
+ .map((entry) => ({
775
+ ...entry,
776
+ score: fdQuery ? this.scoreEntry(entry.path, fdQuery, entry.isDirectory) : 1,
777
+ }))
778
+ .filter((entry) => entry.score > 0);
779
+
780
+ scoredEntries.sort((a, b) => {
781
+ const scoreDiff = b.score - a.score;
782
+ if (scoreDiff !== 0) return scoreDiff;
783
+
784
+ const aDepth = toDisplayPath(a.path).split("/").filter(Boolean).length;
785
+ const bDepth = toDisplayPath(b.path).split("/").filter(Boolean).length;
786
+ const depthDiff = aDepth - bDepth;
787
+ if (depthDiff !== 0) return depthDiff;
788
+
789
+ const lengthDiff = a.path.length - b.path.length;
790
+ if (lengthDiff !== 0) return lengthDiff;
791
+
792
+ return a.path.localeCompare(b.path);
793
+ });
794
+ const topEntries = scoredEntries.slice(0, 20);
795
+
796
+ const suggestions: AutocompleteItem[] = [];
797
+ for (const { path: entryPath, isDirectory } of topEntries) {
798
+ const pathWithoutSlash = isDirectory ? entryPath.slice(0, -1) : entryPath;
799
+ const displayPath = scopedQuery
800
+ ? this.scopedPathForDisplay(scopedQuery.displayBase, pathWithoutSlash)
801
+ : pathWithoutSlash;
802
+ const entryName = basename(pathWithoutSlash);
803
+ const completionPath = isDirectory ? `${displayPath}/` : displayPath;
804
+ const value = buildCompletionValue(completionPath, {
805
+ isDirectory,
806
+ isAtPrefix: true,
807
+ isQuotedPrefix: options.isQuotedPrefix,
808
+ });
809
+
810
+ suggestions.push({
811
+ value,
812
+ label: entryName + (isDirectory ? "/" : ""),
813
+ description: displayPath,
814
+ });
815
+ }
816
+
817
+ return suggestions;
818
+ } catch {
819
+ return [];
820
+ }
821
+ }
822
+
823
+ // Check if we should trigger file completion (called on Tab key)
824
+ shouldTriggerFileCompletion(lines: string[], cursorLine: number, cursorCol: number): boolean {
825
+ const currentLine = lines[cursorLine] || "";
826
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
827
+
828
+ // Don't trigger if we're typing a slash command at the start of the line
829
+ if (textBeforeCursor.trim().startsWith("/") && !textBeforeCursor.trim().includes(" ")) {
830
+ return false;
831
+ }
832
+
833
+ return true;
834
+ }
835
+ }