@causyne/agent 1.20.95 → 1.20.97
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.
- package/package.json +1 -1
- package/src/tui/completion.js +35 -123
- package/src/tui/inlineSlash.js +93 -0
- package/src/tui/inlineSlash.ts +121 -0
- package/src/tui/prompt.js +104 -4
- package/src/tui/workspaceFileIndex.js +183 -0
- package/src/tui/workspaceFileIndex.ts +179 -0
package/package.json
CHANGED
package/src/tui/completion.js
CHANGED
|
@@ -13,11 +13,13 @@
|
|
|
13
13
|
// Pure Node. No dependency, no shell.
|
|
14
14
|
|
|
15
15
|
import fs from 'fs';
|
|
16
|
-
import fsp from 'fs/promises';
|
|
17
16
|
import path from 'path';
|
|
18
17
|
import { listCommands } from '../commands.js';
|
|
19
18
|
import { listCompiledSkills as listSkillsForCompletion } from '../skillsManager.js';
|
|
20
19
|
import { sanitize, shortenHome } from './text.js';
|
|
20
|
+
import { WorkspaceFileIndex } from './workspaceFileIndex.js';
|
|
21
|
+
import { detectInlineSlashTrigger } from './inlineSlash.js';
|
|
22
|
+
export { WorkspaceFileIndex as FileIndex };
|
|
21
23
|
|
|
22
24
|
export const MAX_VISIBLE = 8;
|
|
23
25
|
|
|
@@ -29,8 +31,6 @@ const SKIP_DIRECTORIES = new Set([
|
|
|
29
31
|
'.idea', '.cache', 'coverage', 'vendor', 'Pods', '.causyne'
|
|
30
32
|
]);
|
|
31
33
|
|
|
32
|
-
const MAX_INDEX_ENTRIES = 20000;
|
|
33
|
-
const MAX_INDEX_DEPTH = 12;
|
|
34
34
|
|
|
35
35
|
/** A value is offerable only if printing it changes nothing. */
|
|
36
36
|
export function isTerminalSafe(value) {
|
|
@@ -52,26 +52,28 @@ export function isTerminalSafe(value) {
|
|
|
52
52
|
*/
|
|
53
53
|
export function score(candidate, query) {
|
|
54
54
|
if (!query) return 0;
|
|
55
|
-
const
|
|
56
|
-
const needle = query.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
if (
|
|
63
|
-
if (
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
55
|
+
const full = candidate.toLocaleLowerCase();
|
|
56
|
+
const needle = query.toLocaleLowerCase();
|
|
57
|
+
const leaf = full.replace(/\/$/, '').split('/').at(-1) || '';
|
|
58
|
+
const isDirectory = candidate.endsWith('/');
|
|
59
|
+
const pathPenalty = Math.min(candidate.length, 180);
|
|
60
|
+
const fileBonus = isDirectory ? 0 : 20;
|
|
61
|
+
|
|
62
|
+
if (leaf === needle) return 1800 + fileBonus - pathPenalty;
|
|
63
|
+
if (leaf.startsWith(needle)) return 1500 + fileBonus - pathPenalty;
|
|
64
|
+
if (leaf.includes(needle)) return 1200 + fileBonus - pathPenalty;
|
|
65
|
+
if (full.startsWith(needle)) return 1050 + fileBonus - pathPenalty;
|
|
66
|
+
if (full.includes(needle)) return 900 + fileBonus - pathPenalty;
|
|
67
|
+
|
|
68
|
+
// Fallback: a bounded subsequence match for abbreviations such as tuich.
|
|
69
|
+
let cursor = 0;
|
|
68
70
|
let gaps = 0;
|
|
69
|
-
for (const character of
|
|
70
|
-
if (character === needle[
|
|
71
|
-
|
|
72
|
-
if (
|
|
73
|
-
} else if (
|
|
74
|
-
gaps
|
|
71
|
+
for (const character of full) {
|
|
72
|
+
if (character === needle[cursor]) {
|
|
73
|
+
cursor++;
|
|
74
|
+
if (cursor === needle.length) return 400 - gaps - pathPenalty;
|
|
75
|
+
} else if (cursor > 0) {
|
|
76
|
+
gaps++;
|
|
75
77
|
}
|
|
76
78
|
}
|
|
77
79
|
return -1;
|
|
@@ -110,7 +112,7 @@ function rank(items, query, limit = 50, focusDir = null) {
|
|
|
110
112
|
value += 2000;
|
|
111
113
|
}
|
|
112
114
|
if (focusPrefix && val.toLowerCase().startsWith(focusPrefix)) {
|
|
113
|
-
value +=
|
|
115
|
+
value += 90;
|
|
114
116
|
}
|
|
115
117
|
const resultItem = matchedAlias
|
|
116
118
|
? { ...item, description: `(alias: /${matchedAlias}) ${item.description}` }
|
|
@@ -118,7 +120,7 @@ function rank(items, query, limit = 50, focusDir = null) {
|
|
|
118
120
|
scored.push({ item: resultItem, value });
|
|
119
121
|
}
|
|
120
122
|
}
|
|
121
|
-
scored.sort((a, b) => b.value - a.value);
|
|
123
|
+
scored.sort((a, b) => b.value - a.value || a.item.value.localeCompare(b.item.value));
|
|
122
124
|
const ranked = scored.slice(0, limit).map((entry) => entry.item);
|
|
123
125
|
ranked.total = scored.length;
|
|
124
126
|
return ranked;
|
|
@@ -244,67 +246,7 @@ function argumentItems(name) {
|
|
|
244
246
|
* upgrades the experience once it is ready. If it is never ready, nothing
|
|
245
247
|
* breaks — the caller must never await it.
|
|
246
248
|
*/
|
|
247
|
-
|
|
248
|
-
constructor(root) {
|
|
249
|
-
this.root = root;
|
|
250
|
-
this.entries = null;
|
|
251
|
-
this.building = null;
|
|
252
|
-
this.truncated = false;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
get isReady() {
|
|
256
|
-
return Array.isArray(this.entries);
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/** Kick off the walk. Safe to call repeatedly; only the first one runs. */
|
|
260
|
-
ensure() {
|
|
261
|
-
if (this.entries || this.building) return this.building;
|
|
262
|
-
this.building = this.walk()
|
|
263
|
-
.then((entries) => { this.entries = entries; return entries; })
|
|
264
|
-
.catch(() => { this.entries = []; return []; })
|
|
265
|
-
.finally(() => { this.building = null; });
|
|
266
|
-
return this.building;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
async walk() {
|
|
270
|
-
const found = [];
|
|
271
|
-
const queue = [{ dir: this.root, depth: 0 }];
|
|
272
|
-
let next = 0;
|
|
273
|
-
|
|
274
|
-
while (next < queue.length && found.length < MAX_INDEX_ENTRIES) {
|
|
275
|
-
const { dir, depth } = queue[next++];
|
|
276
|
-
let listing;
|
|
277
|
-
try {
|
|
278
|
-
listing = await fsp.readdir(dir, { withFileTypes: true });
|
|
279
|
-
} catch (e) {
|
|
280
|
-
continue; // unreadable directory is not an error worth surfacing here
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
for (const entry of listing) {
|
|
284
|
-
if (entry.name.startsWith('.') && entry.name !== '.env.example') continue;
|
|
285
|
-
const full = path.join(dir, entry.name);
|
|
286
|
-
|
|
287
|
-
if (entry.isDirectory()) {
|
|
288
|
-
if (SKIP_DIRECTORIES.has(entry.name) || depth >= MAX_INDEX_DEPTH) continue;
|
|
289
|
-
queue.push({ dir: full, depth: depth + 1 });
|
|
290
|
-
const relDir = path.relative(this.root, full).split(path.sep).join('/') + '/';
|
|
291
|
-
if (isTerminalSafe(relDir)) found.push(relDir);
|
|
292
|
-
continue;
|
|
293
|
-
}
|
|
294
|
-
if (!entry.isFile()) continue;
|
|
295
|
-
|
|
296
|
-
const relative = path.relative(this.root, full).split(path.sep).join('/');
|
|
297
|
-
if (!isTerminalSafe(relative)) continue;
|
|
298
|
-
found.push(relative);
|
|
299
|
-
if (found.length >= MAX_INDEX_ENTRIES) {
|
|
300
|
-
this.truncated = true;
|
|
301
|
-
break;
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
return found;
|
|
306
|
-
}
|
|
307
|
-
}
|
|
249
|
+
// FileIndex is now owned by src/tui/workspaceFileIndex.ts.
|
|
308
250
|
|
|
309
251
|
/**
|
|
310
252
|
* Resolve both the authorized root and candidate to physical paths before
|
|
@@ -371,44 +313,14 @@ function directoryItems(root, partial) {
|
|
|
371
313
|
// ---------------------------------------------------------------------------
|
|
372
314
|
|
|
373
315
|
/**
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
*
|
|
377
|
-
* that merely mentions `/usr/local/bin` from opening a command picker, the same
|
|
378
|
-
* rule parseCommand() enforces when the line is finally submitted.
|
|
316
|
+
* Find a slash command or @ reference at the current caret position.
|
|
317
|
+
* Slash detection works at any whitespace-delimited token boundary. Execution
|
|
318
|
+
* remains exclusive to explicit selection; normal prompt dispatch is unchanged.
|
|
379
319
|
*/
|
|
380
320
|
export function detectTrigger(text, cursor) {
|
|
381
321
|
const before = text.slice(0, cursor);
|
|
382
|
-
|
|
383
|
-
if (
|
|
384
|
-
return { kind: 'command', start: 0, query: before.slice(1) };
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
// `/command <argument>` — the command's OWN suggestions.
|
|
388
|
-
//
|
|
389
|
-
// Completion used to stop dead at the space: `/skills d` offered nothing, so
|
|
390
|
-
// the only way to reach a skill was to submit `/skills` bare and browse. With
|
|
391
|
-
// a hundred of them that is a poor trade for someone who already knows the
|
|
392
|
-
// name they want.
|
|
393
|
-
//
|
|
394
|
-
// openclaw's contract (src/tui/commands.ts): a command declares its argument
|
|
395
|
-
// completions and the prompt asks it for the ones matching what has been typed
|
|
396
|
-
// — `getArgumentCompletions(prefix)`. Same shape here, generic over every
|
|
397
|
-
// command, so `/mcp`, `/model` and the rest can adopt it by adding one
|
|
398
|
-
// function and nothing in this file changes.
|
|
399
|
-
//
|
|
400
|
-
// Anchored, and a single argument token only: a second word ends the
|
|
401
|
-
// completion rather than trying to complete inside a sentence. opencode hides
|
|
402
|
-
// its picker on exactly the same condition.
|
|
403
|
-
const argument = before.match(/^\/([a-z0-9_?-]+)[ \t]+(\S*)$/i);
|
|
404
|
-
if (argument) {
|
|
405
|
-
return {
|
|
406
|
-
kind: 'command-argument',
|
|
407
|
-
command: argument[1],
|
|
408
|
-
start: cursor - argument[2].length,
|
|
409
|
-
query: argument[2]
|
|
410
|
-
};
|
|
411
|
-
}
|
|
322
|
+
const slash = detectInlineSlashTrigger(text, cursor);
|
|
323
|
+
if (slash) return slash;
|
|
412
324
|
|
|
413
325
|
// 1. Quoted @ file mention: @"pixel2d games/ or @'pixel2d games/
|
|
414
326
|
// Supports spaces in directory or file names
|
|
@@ -462,11 +374,11 @@ export function suggest(text, cursor, options = {}) {
|
|
|
462
374
|
const root = options.root || process.cwd();
|
|
463
375
|
const index = options.index;
|
|
464
376
|
const focusDir = options.focusDir || null;
|
|
465
|
-
if (index
|
|
377
|
+
if (index) void index.ensure();
|
|
466
378
|
|
|
467
379
|
let pool;
|
|
468
380
|
if (index && index.isReady && trigger.query) {
|
|
469
|
-
pool = index.
|
|
381
|
+
pool = index.candidates(trigger.query).map((relative) => ({
|
|
470
382
|
value: relative,
|
|
471
383
|
match: relative,
|
|
472
384
|
label: relative,
|
|
@@ -495,7 +407,7 @@ export function suggest(text, cursor, options = {}) {
|
|
|
495
407
|
pool = directoryItems(root, trigger.query);
|
|
496
408
|
}
|
|
497
409
|
|
|
498
|
-
const items = rank(pool, trigger.query,
|
|
410
|
+
const items = rank(pool, trigger.query, 500, focusDir);
|
|
499
411
|
if (items.length === 0) return null;
|
|
500
412
|
return { ...trigger, items, total: items.total };
|
|
501
413
|
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slash completion framing for the Causyne chat composer.
|
|
3
|
+
*
|
|
4
|
+
* This is intentionally a lexical, zero-model operation. It never executes a
|
|
5
|
+
* command. Only an explicit picker selection can hand a command to ChatPrompt.
|
|
6
|
+
* Existing command dispatch keeps its beginning-of-input parser unchanged.
|
|
7
|
+
*/
|
|
8
|
+
const ARGUMENT = /(?:^|[ \t\r\n])\/([a-z0-9_?-]+)[ \t]+([^\s]*)$/i;
|
|
9
|
+
const COMMAND = /(?:^|[ \t\r\n])\/([a-z0-9_?-]*)$/i;
|
|
10
|
+
/**
|
|
11
|
+
* Find a complete slash prefix at the caret, even when other prose precedes it.
|
|
12
|
+
* A slash must start a whitespace-delimited token: URLs, division, and paths
|
|
13
|
+
* with inner slashes do not open the command menu.
|
|
14
|
+
*
|
|
15
|
+
* Offsets are UTF-16 code units, which is the existing completion.js contract.
|
|
16
|
+
*/
|
|
17
|
+
export function detectInlineSlashTrigger(text, cursor) {
|
|
18
|
+
if (typeof text !== 'string' || !Number.isFinite(cursor))
|
|
19
|
+
return null;
|
|
20
|
+
if (cursor < 0 || cursor > text.length)
|
|
21
|
+
return null;
|
|
22
|
+
const before = text.slice(0, cursor);
|
|
23
|
+
const argument = ARGUMENT.exec(before);
|
|
24
|
+
if (argument) {
|
|
25
|
+
const fragment = argument[0];
|
|
26
|
+
const offset = cursor - fragment.length + fragment.indexOf('/');
|
|
27
|
+
const query = argument[2] ?? '';
|
|
28
|
+
return {
|
|
29
|
+
kind: 'command-argument',
|
|
30
|
+
command: argument[1] ?? '',
|
|
31
|
+
query,
|
|
32
|
+
start: cursor - query.length,
|
|
33
|
+
tokenStart: offset,
|
|
34
|
+
inline: before.slice(0, offset).trim().length > 0
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const command = COMMAND.exec(before);
|
|
38
|
+
if (!command)
|
|
39
|
+
return null;
|
|
40
|
+
const fragment = command[0];
|
|
41
|
+
const offset = cursor - fragment.length + fragment.indexOf('/');
|
|
42
|
+
return {
|
|
43
|
+
kind: 'command',
|
|
44
|
+
query: command[1] ?? '',
|
|
45
|
+
start: offset,
|
|
46
|
+
tokenStart: offset,
|
|
47
|
+
inline: before.slice(0, offset).trim().length > 0
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Remove the command token, NOT the surrounding draft.
|
|
52
|
+
* An editor caret can sit in the middle of a token. In that case, remove the
|
|
53
|
+
* untyped suffix of the same token too, stopping at the following whitespace.
|
|
54
|
+
*/
|
|
55
|
+
export function removeInlineSlashToken(text, cursor, trigger) {
|
|
56
|
+
if (typeof text !== 'string' || !Number.isFinite(cursor)) {
|
|
57
|
+
throw new TypeError('Invalid inline command text or cursor');
|
|
58
|
+
}
|
|
59
|
+
const position = Math.trunc(cursor);
|
|
60
|
+
const start = trigger.tokenStart;
|
|
61
|
+
if (!Number.isInteger(start) || start < 0 || start >= text.length ||
|
|
62
|
+
position < start || position > text.length || text[start] !== '/') {
|
|
63
|
+
throw new RangeError('Stale inline command selection');
|
|
64
|
+
}
|
|
65
|
+
const actual = text.slice(start, position);
|
|
66
|
+
if (trigger.kind === 'command') {
|
|
67
|
+
if (actual !== `/${trigger.query}`) {
|
|
68
|
+
throw new RangeError('Stale inline command selection');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
const argument = /^\/([a-z0-9_?-]+)[ \t]+([^\s]*)$/i.exec(actual);
|
|
73
|
+
if (!argument || argument[1] !== trigger.command || argument[2] !== trigger.query) {
|
|
74
|
+
throw new RangeError('Stale inline command selection');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const suffix = text.slice(position);
|
|
78
|
+
const trailingToken = trigger.kind === 'command'
|
|
79
|
+
? /^[a-z0-9_?-]*/i.exec(suffix)?.[0] ?? ''
|
|
80
|
+
: /^[^\s]*/.exec(suffix)?.[0] ?? '';
|
|
81
|
+
const end = position + trailingToken.length;
|
|
82
|
+
return {
|
|
83
|
+
text: text.slice(0, start) + text.slice(end),
|
|
84
|
+
cursor: start
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Compiled-skill menu entries are the only commands that consume the current
|
|
89
|
+
* draft as their task instruction. Management commands keep the draft intact.
|
|
90
|
+
*/
|
|
91
|
+
export function isInlineSkillInvocation(command) {
|
|
92
|
+
return /^\/skills\s+[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(command);
|
|
93
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slash completion framing for the Causyne chat composer.
|
|
3
|
+
*
|
|
4
|
+
* This is intentionally a lexical, zero-model operation. It never executes a
|
|
5
|
+
* command. Only an explicit picker selection can hand a command to ChatPrompt.
|
|
6
|
+
* Existing command dispatch keeps its beginning-of-input parser unchanged.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type SlashTrigger =
|
|
10
|
+
| {
|
|
11
|
+
readonly kind: 'command';
|
|
12
|
+
readonly query: string;
|
|
13
|
+
readonly start: number;
|
|
14
|
+
readonly tokenStart: number;
|
|
15
|
+
readonly inline: boolean;
|
|
16
|
+
}
|
|
17
|
+
| {
|
|
18
|
+
readonly kind: 'command-argument';
|
|
19
|
+
readonly command: string;
|
|
20
|
+
readonly query: string;
|
|
21
|
+
readonly start: number;
|
|
22
|
+
readonly tokenStart: number;
|
|
23
|
+
readonly inline: boolean;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export interface RemovedSlashToken {
|
|
27
|
+
readonly text: string;
|
|
28
|
+
readonly cursor: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const ARGUMENT = /(?:^|[ \t\r\n])\/([a-z0-9_?-]+)[ \t]+([^\s]*)$/i;
|
|
32
|
+
const COMMAND = /(?:^|[ \t\r\n])\/([a-z0-9_?-]*)$/i;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Find a complete slash prefix at the caret, even when other prose precedes it.
|
|
36
|
+
* A slash must start a whitespace-delimited token: URLs, division, and paths
|
|
37
|
+
* with inner slashes do not open the command menu.
|
|
38
|
+
*
|
|
39
|
+
* Offsets are UTF-16 code units, which is the existing completion.js contract.
|
|
40
|
+
*/
|
|
41
|
+
export function detectInlineSlashTrigger(text: string, cursor: number): SlashTrigger | null {
|
|
42
|
+
if (typeof text !== 'string' || !Number.isFinite(cursor)) return null;
|
|
43
|
+
if (cursor < 0 || cursor > text.length) return null;
|
|
44
|
+
|
|
45
|
+
const before = text.slice(0, cursor);
|
|
46
|
+
const argument = ARGUMENT.exec(before);
|
|
47
|
+
if (argument) {
|
|
48
|
+
const fragment = argument[0];
|
|
49
|
+
const offset = cursor - fragment.length + fragment.indexOf('/');
|
|
50
|
+
const query = argument[2] ?? '';
|
|
51
|
+
return {
|
|
52
|
+
kind: 'command-argument',
|
|
53
|
+
command: argument[1] ?? '',
|
|
54
|
+
query,
|
|
55
|
+
start: cursor - query.length,
|
|
56
|
+
tokenStart: offset,
|
|
57
|
+
inline: before.slice(0, offset).trim().length > 0
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const command = COMMAND.exec(before);
|
|
62
|
+
if (!command) return null;
|
|
63
|
+
const fragment = command[0];
|
|
64
|
+
const offset = cursor - fragment.length + fragment.indexOf('/');
|
|
65
|
+
return {
|
|
66
|
+
kind: 'command',
|
|
67
|
+
query: command[1] ?? '',
|
|
68
|
+
start: offset,
|
|
69
|
+
tokenStart: offset,
|
|
70
|
+
inline: before.slice(0, offset).trim().length > 0
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Remove the command token, NOT the surrounding draft.
|
|
76
|
+
* An editor caret can sit in the middle of a token. In that case, remove the
|
|
77
|
+
* untyped suffix of the same token too, stopping at the following whitespace.
|
|
78
|
+
*/
|
|
79
|
+
export function removeInlineSlashToken(
|
|
80
|
+
text: string,
|
|
81
|
+
cursor: number,
|
|
82
|
+
trigger: SlashTrigger
|
|
83
|
+
): RemovedSlashToken {
|
|
84
|
+
if (typeof text !== 'string' || !Number.isFinite(cursor)) {
|
|
85
|
+
throw new TypeError('Invalid inline command text or cursor');
|
|
86
|
+
}
|
|
87
|
+
const position = Math.trunc(cursor);
|
|
88
|
+
const start = trigger.tokenStart;
|
|
89
|
+
if (!Number.isInteger(start) || start < 0 || start >= text.length ||
|
|
90
|
+
position < start || position > text.length || text[start] !== '/') {
|
|
91
|
+
throw new RangeError('Stale inline command selection');
|
|
92
|
+
}
|
|
93
|
+
const actual = text.slice(start, position);
|
|
94
|
+
if (trigger.kind === 'command') {
|
|
95
|
+
if (actual !== `/${trigger.query}`) {
|
|
96
|
+
throw new RangeError('Stale inline command selection');
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
const argument = /^\/([a-z0-9_?-]+)[ \t]+([^\s]*)$/i.exec(actual);
|
|
100
|
+
if (!argument || argument[1] !== trigger.command || argument[2] !== trigger.query) {
|
|
101
|
+
throw new RangeError('Stale inline command selection');
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const suffix = text.slice(position);
|
|
105
|
+
const trailingToken = trigger.kind === 'command'
|
|
106
|
+
? /^[a-z0-9_?-]*/i.exec(suffix)?.[0] ?? ''
|
|
107
|
+
: /^[^\s]*/.exec(suffix)?.[0] ?? '';
|
|
108
|
+
const end = position + trailingToken.length;
|
|
109
|
+
return {
|
|
110
|
+
text: text.slice(0, start) + text.slice(end),
|
|
111
|
+
cursor: start
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Compiled-skill menu entries are the only commands that consume the current
|
|
117
|
+
* draft as their task instruction. Management commands keep the draft intact.
|
|
118
|
+
*/
|
|
119
|
+
export function isInlineSkillInvocation(command: string): boolean {
|
|
120
|
+
return /^\/skills\s+[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(command);
|
|
121
|
+
}
|
package/src/tui/prompt.js
CHANGED
|
@@ -22,6 +22,7 @@ import { TerminalInputFramer, INPUT_PREFIX_TIMEOUT_MS, shouldTreatAsAtomicPaste
|
|
|
22
22
|
import { LineEditor } from './lineEditor.js';
|
|
23
23
|
import { PromptHistory } from './history.js';
|
|
24
24
|
import { FileIndex, suggest, applyCompletion, detectTrigger, renderPicker, MAX_VISIBLE } from './completion.js';
|
|
25
|
+
import { removeInlineSlashToken, isInlineSkillInvocation } from './inlineSlash.js';
|
|
25
26
|
import { paint, dim, bold, GLYPHS, terminalWidth, HAS_COLOR } from './theme.js';
|
|
26
27
|
import { barBlock, GUTTER } from './block.js';
|
|
27
28
|
import { composerGeometry } from './composerGeometry.js';
|
|
@@ -121,6 +122,8 @@ export class ChatPrompt {
|
|
|
121
122
|
this.editor = new LineEditor();
|
|
122
123
|
this.history = options.history || new PromptHistory();
|
|
123
124
|
this.index = new FileIndex(this.root);
|
|
125
|
+
this._unsubscribeFileIndex = null;
|
|
126
|
+
this.bindFileIndex(this.index);
|
|
124
127
|
this.decoder = new KeyDecoder();
|
|
125
128
|
this.inputFramer = new TerminalInputFramer();
|
|
126
129
|
this.inputFrameTimer = null;
|
|
@@ -1304,12 +1307,32 @@ export class ChatPrompt {
|
|
|
1304
1307
|
// Completion
|
|
1305
1308
|
// -------------------------------------------------------------------------
|
|
1306
1309
|
|
|
1310
|
+
/** A completed scan must refresh the currently displayed @ picker. */
|
|
1311
|
+
bindFileIndex(index) {
|
|
1312
|
+
if (typeof this._unsubscribeFileIndex === 'function') this._unsubscribeFileIndex();
|
|
1313
|
+
this._unsubscribeFileIndex = index.subscribe(() => {
|
|
1314
|
+
// Ignore a late callback from a previous workspace or a dismissed prompt.
|
|
1315
|
+
if (this.index !== index || !this.active) return;
|
|
1316
|
+
const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
|
|
1317
|
+
if (!trigger || trigger.kind !== 'file') return;
|
|
1318
|
+
this.openCompletion(false);
|
|
1319
|
+
if (index.truncated) this.notice = 'Workspace file index reached its safety limit; narrow the project root.';
|
|
1320
|
+
else if (this.notice === 'Indexing workspace files…') this.notice = null;
|
|
1321
|
+
this.scheduleDraw();
|
|
1322
|
+
});
|
|
1323
|
+
void index.ensure();
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1307
1326
|
/** Dynamically re-target the prompt root and optional focused subproject. */
|
|
1308
1327
|
setWorkingRoot(newRoot, focusDir = null) {
|
|
1328
|
+
if (typeof this._unsubscribeFileIndex === 'function') this._unsubscribeFileIndex();
|
|
1329
|
+
this.index?.dispose();
|
|
1309
1330
|
this.root = newRoot;
|
|
1310
1331
|
this.focusDir = focusDir;
|
|
1311
1332
|
this.index = new FileIndex(newRoot);
|
|
1312
|
-
this.index
|
|
1333
|
+
this.bindFileIndex(this.index);
|
|
1334
|
+
const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
|
|
1335
|
+
if (trigger?.kind === 'file') this.openCompletion(false);
|
|
1313
1336
|
}
|
|
1314
1337
|
|
|
1315
1338
|
cursorOffset() {
|
|
@@ -1424,6 +1447,12 @@ export class ChatPrompt {
|
|
|
1424
1447
|
}
|
|
1425
1448
|
|
|
1426
1449
|
if (item) {
|
|
1450
|
+
if (this.completion.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
|
|
1451
|
+
const selectedCommand = this.completion.kind === 'command'
|
|
1452
|
+
? item.value : `/${this.completion.command} ${item.value}`;
|
|
1453
|
+
this.runInlineSlashSelection(selectedCommand);
|
|
1454
|
+
return true;
|
|
1455
|
+
}
|
|
1427
1456
|
if (this.completion.kind === 'command') {
|
|
1428
1457
|
// A skill entry goes onto the line so the user can say what to do
|
|
1429
1458
|
// with it; clicking it used to invoke it immediately with no task.
|
|
@@ -1444,8 +1473,14 @@ export class ChatPrompt {
|
|
|
1444
1473
|
}
|
|
1445
1474
|
return true;
|
|
1446
1475
|
}
|
|
1447
|
-
if (key.name === 'enter' && !key.alt) {
|
|
1476
|
+
if (key.name === 'enter' && !key.alt && !key.shift) {
|
|
1448
1477
|
const item = this.completion.items && this.completion.items[this.selected];
|
|
1478
|
+
if (item && this.completion.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
|
|
1479
|
+
const selectedCommand = this.completion.kind === 'command'
|
|
1480
|
+
? item.value : `/${this.completion.command} ${item.value}`;
|
|
1481
|
+
this.runInlineSlashSelection(selectedCommand);
|
|
1482
|
+
return true;
|
|
1483
|
+
}
|
|
1449
1484
|
if (this.completion.kind === 'command' && item) {
|
|
1450
1485
|
if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
|
|
1451
1486
|
this.acceptCompletion();
|
|
@@ -1464,10 +1499,22 @@ export class ChatPrompt {
|
|
|
1464
1499
|
this.acceptCompletion();
|
|
1465
1500
|
return true;
|
|
1466
1501
|
}
|
|
1467
|
-
if (key.name === 'tab') {
|
|
1502
|
+
if (key.name === 'tab') {
|
|
1503
|
+
if (this.completion?.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
|
|
1504
|
+
// Tab must never silently turn an unsent message into a local command.
|
|
1505
|
+
this.notice = 'Press Enter to run the selected command; your unsent draft is preserved.';
|
|
1506
|
+
this.scheduleDraw();
|
|
1507
|
+
return true;
|
|
1508
|
+
}
|
|
1509
|
+
this.acceptCompletion();
|
|
1510
|
+
return true;
|
|
1511
|
+
}
|
|
1468
1512
|
if (key.name === 'escape') {
|
|
1513
|
+
const dismissed = this.completion;
|
|
1469
1514
|
this.completion = null;
|
|
1470
|
-
|
|
1515
|
+
// Only discard a standalone leading command token. Never erase a
|
|
1516
|
+
// longer draft just because its first character happens to be /.
|
|
1517
|
+
if (!dismissed?.inline && /^\s*\/[a-z0-9_?-]*$/i.test(this.editor.getText())) {
|
|
1471
1518
|
this.editor.clear();
|
|
1472
1519
|
}
|
|
1473
1520
|
this.scheduleDraw();
|
|
@@ -1501,6 +1548,56 @@ export class ChatPrompt {
|
|
|
1501
1548
|
this.submit();
|
|
1502
1549
|
}
|
|
1503
1550
|
|
|
1551
|
+
/**
|
|
1552
|
+
* Execute an explicitly selected slash action from anywhere in a draft.
|
|
1553
|
+
* Ordinary commands run through submit() with the unsent draft suspended;
|
|
1554
|
+
* selecting a compiled skill applies it to the draft as its instruction.
|
|
1555
|
+
* Neither path changes parseCommand() or interprets ambient prose as control.
|
|
1556
|
+
*/
|
|
1557
|
+
runInlineSlashSelection(value) {
|
|
1558
|
+
const trigger = this.completion;
|
|
1559
|
+
if (!trigger?.inline || (trigger.kind !== 'command' && trigger.kind !== 'command-argument')) {
|
|
1560
|
+
this.submitPickedCommand(value);
|
|
1561
|
+
return;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
const currentText = this.editor.getText();
|
|
1565
|
+
const currentCursor = this.cursorOffset();
|
|
1566
|
+
let remaining;
|
|
1567
|
+
try {
|
|
1568
|
+
remaining = removeInlineSlashToken(currentText, currentCursor, trigger);
|
|
1569
|
+
} catch (error) {
|
|
1570
|
+
// The draft might have changed since the last render. Never execute a
|
|
1571
|
+
// command selected against stale input or erase user-authored text.
|
|
1572
|
+
this.notice = 'The command text changed. Reopen the / menu and select again.';
|
|
1573
|
+
this.completion = null;
|
|
1574
|
+
this.scheduleDraw();
|
|
1575
|
+
return;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
const consumeDraft = isInlineSkillInvocation(value) && remaining.text.trim().length > 0;
|
|
1579
|
+
const commandText = consumeDraft ? `${value} ${remaining.text.trim()}` : value;
|
|
1580
|
+
|
|
1581
|
+
// submit() itself protects the queue, but return early here to avoid
|
|
1582
|
+
// discarding the unfinished inline token when the command was not queued.
|
|
1583
|
+
if (this.busy && this.queue.length >= 32 && !/^\/(?:stop|interrupt)$/i.test(commandText)) {
|
|
1584
|
+
this.notice = '32 queued messages: command not submitted; your draft is unchanged.';
|
|
1585
|
+
this.scheduleDraw();
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
this.completion = null;
|
|
1590
|
+
try {
|
|
1591
|
+
this.editor.setText(commandText);
|
|
1592
|
+
this.submit(); // existing history, permission and command-dispatch boundary
|
|
1593
|
+
} finally {
|
|
1594
|
+
this.editor.setText(consumeDraft ? '' : remaining.text);
|
|
1595
|
+
if (!consumeDraft) this.setCursorOffset(remaining.cursor);
|
|
1596
|
+
this.completion = null;
|
|
1597
|
+
this.scheduleDraw();
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1504
1601
|
acceptCompletion() {
|
|
1505
1602
|
const item = this.completion.items[this.selected];
|
|
1506
1603
|
if (!item) { this.completion = null; return; }
|
|
@@ -1823,6 +1920,9 @@ export class ChatPrompt {
|
|
|
1823
1920
|
const matched = this.completion.total || this.completion.items.length;
|
|
1824
1921
|
const hidden = matched - drawn.length;
|
|
1825
1922
|
if (hidden > 0) drawn.push(dim(` ${GLYPHS.ellipsis} ${hidden} more`));
|
|
1923
|
+
if (this.completion?.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
|
|
1924
|
+
drawn.push(dim(' ' + truncate('Enter run · Esc dismiss · draft protected', Math.max(0, width - 5))));
|
|
1925
|
+
}
|
|
1826
1926
|
return drawn;
|
|
1827
1927
|
}
|
|
1828
1928
|
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne: bounded, asynchronous, workspace-scoped index for @ references.
|
|
3
|
+
* This module never follows symlinks or invokes external binaries.
|
|
4
|
+
* It indexes nested project paths once, not on each keystroke.
|
|
5
|
+
*/
|
|
6
|
+
import { readdir } from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
const SKIP = new Set([
|
|
9
|
+
'.git', '.causyne', 'node_modules', '.next', '.nuxt', '.svelte-kit',
|
|
10
|
+
'.venv', 'venv', '__pycache__', '.gradle', '.idea', '.cache',
|
|
11
|
+
'coverage', 'vendor', 'Pods', 'dist', 'build', 'out', 'target'
|
|
12
|
+
]);
|
|
13
|
+
const DEFAULT_MAX_ENTRIES = 100_000;
|
|
14
|
+
const DEFAULT_MAX_DIRS = 20_000;
|
|
15
|
+
const DEFAULT_MAX_DEPTH = 32;
|
|
16
|
+
const DEFAULT_REFRESH_MS = 45_000;
|
|
17
|
+
const YIELD_EVERY = 48;
|
|
18
|
+
function finiteInt(value, fallback, minimum = 1) {
|
|
19
|
+
return Number.isSafeInteger(value) && value !== undefined && value >= minimum ? value : fallback;
|
|
20
|
+
}
|
|
21
|
+
/** Terminal control codes must never be inserted into a selectable path. */
|
|
22
|
+
function safeRelative(relative) {
|
|
23
|
+
return relative.length > 0 && relative.length <= 4096
|
|
24
|
+
&& !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(relative);
|
|
25
|
+
}
|
|
26
|
+
export class WorkspaceFileIndex {
|
|
27
|
+
root;
|
|
28
|
+
entries = null;
|
|
29
|
+
truncated = false;
|
|
30
|
+
indexed = [];
|
|
31
|
+
listeners = new Set();
|
|
32
|
+
building = null;
|
|
33
|
+
generation = 0;
|
|
34
|
+
completedAt = 0;
|
|
35
|
+
disposed = false;
|
|
36
|
+
maxEntries;
|
|
37
|
+
maxDirs;
|
|
38
|
+
maxDepth;
|
|
39
|
+
refreshMs;
|
|
40
|
+
constructor(root, options = {}) {
|
|
41
|
+
this.root = path.resolve(root);
|
|
42
|
+
this.maxEntries = finiteInt(options.maxEntries, DEFAULT_MAX_ENTRIES);
|
|
43
|
+
this.maxDirs = finiteInt(options.maxDirs, DEFAULT_MAX_DIRS);
|
|
44
|
+
this.maxDepth = finiteInt(options.maxDepth, DEFAULT_MAX_DEPTH);
|
|
45
|
+
this.refreshMs = finiteInt(options.refreshMs, DEFAULT_REFRESH_MS, 0);
|
|
46
|
+
}
|
|
47
|
+
get isReady() { return this.entries !== null; }
|
|
48
|
+
get isBuilding() { return this.building !== null; }
|
|
49
|
+
subscribe(listener) {
|
|
50
|
+
if (this.disposed)
|
|
51
|
+
return () => { };
|
|
52
|
+
this.listeners.add(listener);
|
|
53
|
+
return () => { this.listeners.delete(listener); };
|
|
54
|
+
}
|
|
55
|
+
invalidate() { this.completedAt = 0; }
|
|
56
|
+
dispose() {
|
|
57
|
+
this.disposed = true;
|
|
58
|
+
this.generation++;
|
|
59
|
+
this.listeners.clear();
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Starts a scan only when required. Existing results remain available while
|
|
63
|
+
* a TTL refresh runs. Consumers receive one event when the snapshot changes.
|
|
64
|
+
*/
|
|
65
|
+
ensure(force = false) {
|
|
66
|
+
if (this.disposed)
|
|
67
|
+
return Promise.resolve(this.entries ?? []);
|
|
68
|
+
if (this.building)
|
|
69
|
+
return this.building;
|
|
70
|
+
if (!force && this.entries && Date.now() - this.completedAt < this.refreshMs) {
|
|
71
|
+
return Promise.resolve(this.entries);
|
|
72
|
+
}
|
|
73
|
+
const generation = ++this.generation;
|
|
74
|
+
this.building = this.scan(generation)
|
|
75
|
+
.then(({ entries, truncated }) => {
|
|
76
|
+
if (this.disposed || generation !== this.generation)
|
|
77
|
+
return this.entries ?? [];
|
|
78
|
+
this.entries = entries;
|
|
79
|
+
this.indexed = entries.map(value => ({ value, folded: value.toLocaleLowerCase() }));
|
|
80
|
+
this.truncated = truncated;
|
|
81
|
+
this.completedAt = Date.now();
|
|
82
|
+
for (const listener of [...this.listeners]) {
|
|
83
|
+
try {
|
|
84
|
+
listener();
|
|
85
|
+
}
|
|
86
|
+
catch { /* UI listeners cannot fail the index */ }
|
|
87
|
+
}
|
|
88
|
+
return entries;
|
|
89
|
+
})
|
|
90
|
+
.catch(() => {
|
|
91
|
+
// Keep any previous snapshot if the root becomes unreadable.
|
|
92
|
+
if (!this.disposed && generation === this.generation && this.entries === null) {
|
|
93
|
+
this.entries = [];
|
|
94
|
+
this.indexed = [];
|
|
95
|
+
this.completedAt = Date.now();
|
|
96
|
+
for (const listener of [...this.listeners]) {
|
|
97
|
+
try {
|
|
98
|
+
listener();
|
|
99
|
+
}
|
|
100
|
+
catch { /* never propagate to keyboard handling */ }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return this.entries ?? [];
|
|
104
|
+
})
|
|
105
|
+
.finally(() => { if (generation === this.generation)
|
|
106
|
+
this.building = null; });
|
|
107
|
+
return this.building;
|
|
108
|
+
}
|
|
109
|
+
/** Contiguous matches take priority; fuzzy matching remains the JS fallback. */
|
|
110
|
+
candidates(query) {
|
|
111
|
+
if (!query)
|
|
112
|
+
return this.entries ?? [];
|
|
113
|
+
const needle = query.toLocaleLowerCase();
|
|
114
|
+
const direct = this.indexed.filter(entry => entry.folded.includes(needle));
|
|
115
|
+
return (direct.length > 0 ? direct.map(entry => entry.value) : this.entries ?? []);
|
|
116
|
+
}
|
|
117
|
+
async scan(generation) {
|
|
118
|
+
const found = [];
|
|
119
|
+
const queue = [
|
|
120
|
+
{ absolute: this.root, relative: '', depth: 0 }
|
|
121
|
+
];
|
|
122
|
+
let cursor = 0;
|
|
123
|
+
let truncated = false;
|
|
124
|
+
while (cursor < queue.length) {
|
|
125
|
+
if (this.disposed || generation !== this.generation)
|
|
126
|
+
break;
|
|
127
|
+
if (cursor >= this.maxDirs || found.length >= this.maxEntries) {
|
|
128
|
+
truncated = true;
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
const current = queue[cursor++];
|
|
132
|
+
if (!current)
|
|
133
|
+
break;
|
|
134
|
+
let listing;
|
|
135
|
+
try {
|
|
136
|
+
listing = await readdir(current.absolute, { withFileTypes: true });
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
listing.sort((a, b) => a.name.localeCompare(b.name));
|
|
142
|
+
for (const entry of listing) {
|
|
143
|
+
if (this.disposed || generation !== this.generation)
|
|
144
|
+
break;
|
|
145
|
+
if (entry.isSymbolicLink())
|
|
146
|
+
continue;
|
|
147
|
+
if (!entry.isFile() && !entry.isDirectory())
|
|
148
|
+
continue;
|
|
149
|
+
const relative = current.relative ? `${current.relative}/${entry.name}` : entry.name;
|
|
150
|
+
if (!safeRelative(relative))
|
|
151
|
+
continue;
|
|
152
|
+
if (entry.isDirectory()) {
|
|
153
|
+
if (SKIP.has(entry.name))
|
|
154
|
+
continue;
|
|
155
|
+
if (current.depth < this.maxDepth) {
|
|
156
|
+
if (queue.length >= this.maxDirs)
|
|
157
|
+
truncated = true;
|
|
158
|
+
else
|
|
159
|
+
queue.push({
|
|
160
|
+
absolute: path.join(current.absolute, entry.name),
|
|
161
|
+
relative, depth: current.depth + 1
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
else
|
|
165
|
+
truncated = true;
|
|
166
|
+
found.push(`${relative}/`);
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
found.push(relative);
|
|
170
|
+
}
|
|
171
|
+
if (found.length >= this.maxEntries) {
|
|
172
|
+
truncated = true;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
// Periodically yield: typing, rendering and cancellation must remain responsive.
|
|
177
|
+
if (cursor % YIELD_EVERY === 0) {
|
|
178
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return { entries: found, truncated };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne: bounded, asynchronous, workspace-scoped index for @ references.
|
|
3
|
+
* This module never follows symlinks or invokes external binaries.
|
|
4
|
+
* It indexes nested project paths once, not on each keystroke.
|
|
5
|
+
*/
|
|
6
|
+
import { readdir } from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
const SKIP = new Set([
|
|
10
|
+
'.git', '.causyne', 'node_modules', '.next', '.nuxt', '.svelte-kit',
|
|
11
|
+
'.venv', 'venv', '__pycache__', '.gradle', '.idea', '.cache',
|
|
12
|
+
'coverage', 'vendor', 'Pods', 'dist', 'build', 'out', 'target'
|
|
13
|
+
]);
|
|
14
|
+
const DEFAULT_MAX_ENTRIES = 100_000;
|
|
15
|
+
const DEFAULT_MAX_DIRS = 20_000;
|
|
16
|
+
const DEFAULT_MAX_DEPTH = 32;
|
|
17
|
+
const DEFAULT_REFRESH_MS = 45_000;
|
|
18
|
+
const YIELD_EVERY = 48;
|
|
19
|
+
|
|
20
|
+
export interface WorkspaceFileIndexOptions {
|
|
21
|
+
maxEntries?: number;
|
|
22
|
+
maxDirs?: number;
|
|
23
|
+
maxDepth?: number;
|
|
24
|
+
refreshMs?: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function finiteInt(value: number | undefined, fallback: number, minimum = 1): number {
|
|
28
|
+
return Number.isSafeInteger(value) && value !== undefined && value >= minimum ? value : fallback;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Terminal control codes must never be inserted into a selectable path. */
|
|
32
|
+
function safeRelative(relative: string): boolean {
|
|
33
|
+
return relative.length > 0 && relative.length <= 4096
|
|
34
|
+
&& !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(relative);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface IndexedPath {
|
|
38
|
+
value: string;
|
|
39
|
+
folded: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class WorkspaceFileIndex {
|
|
43
|
+
readonly root: string;
|
|
44
|
+
entries: string[] | null = null;
|
|
45
|
+
truncated = false;
|
|
46
|
+
private indexed: IndexedPath[] = [];
|
|
47
|
+
private listeners = new Set<() => void>();
|
|
48
|
+
private building: Promise<string[]> | null = null;
|
|
49
|
+
private generation = 0;
|
|
50
|
+
private completedAt = 0;
|
|
51
|
+
private disposed = false;
|
|
52
|
+
private readonly maxEntries: number;
|
|
53
|
+
private readonly maxDirs: number;
|
|
54
|
+
private readonly maxDepth: number;
|
|
55
|
+
private readonly refreshMs: number;
|
|
56
|
+
|
|
57
|
+
constructor(root: string, options: WorkspaceFileIndexOptions = {}) {
|
|
58
|
+
this.root = path.resolve(root);
|
|
59
|
+
this.maxEntries = finiteInt(options.maxEntries, DEFAULT_MAX_ENTRIES);
|
|
60
|
+
this.maxDirs = finiteInt(options.maxDirs, DEFAULT_MAX_DIRS);
|
|
61
|
+
this.maxDepth = finiteInt(options.maxDepth, DEFAULT_MAX_DEPTH);
|
|
62
|
+
this.refreshMs = finiteInt(options.refreshMs, DEFAULT_REFRESH_MS, 0);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
get isReady(): boolean { return this.entries !== null; }
|
|
66
|
+
get isBuilding(): boolean { return this.building !== null; }
|
|
67
|
+
|
|
68
|
+
subscribe(listener: () => void): () => void {
|
|
69
|
+
if (this.disposed) return () => {};
|
|
70
|
+
this.listeners.add(listener);
|
|
71
|
+
return () => { this.listeners.delete(listener); };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
invalidate(): void { this.completedAt = 0; }
|
|
75
|
+
|
|
76
|
+
dispose(): void {
|
|
77
|
+
this.disposed = true;
|
|
78
|
+
this.generation++;
|
|
79
|
+
this.listeners.clear();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Starts a scan only when required. Existing results remain available while
|
|
84
|
+
* a TTL refresh runs. Consumers receive one event when the snapshot changes.
|
|
85
|
+
*/
|
|
86
|
+
ensure(force = false): Promise<string[]> {
|
|
87
|
+
if (this.disposed) return Promise.resolve(this.entries ?? []);
|
|
88
|
+
if (this.building) return this.building;
|
|
89
|
+
if (!force && this.entries && Date.now() - this.completedAt < this.refreshMs) {
|
|
90
|
+
return Promise.resolve(this.entries);
|
|
91
|
+
}
|
|
92
|
+
const generation = ++this.generation;
|
|
93
|
+
this.building = this.scan(generation)
|
|
94
|
+
.then(({ entries, truncated }) => {
|
|
95
|
+
if (this.disposed || generation !== this.generation) return this.entries ?? [];
|
|
96
|
+
this.entries = entries;
|
|
97
|
+
this.indexed = entries.map(value => ({ value, folded: value.toLocaleLowerCase() }));
|
|
98
|
+
this.truncated = truncated;
|
|
99
|
+
this.completedAt = Date.now();
|
|
100
|
+
for (const listener of [...this.listeners]) {
|
|
101
|
+
try { listener(); } catch { /* UI listeners cannot fail the index */ }
|
|
102
|
+
}
|
|
103
|
+
return entries;
|
|
104
|
+
})
|
|
105
|
+
.catch(() => {
|
|
106
|
+
// Keep any previous snapshot if the root becomes unreadable.
|
|
107
|
+
if (!this.disposed && generation === this.generation && this.entries === null) {
|
|
108
|
+
this.entries = [];
|
|
109
|
+
this.indexed = [];
|
|
110
|
+
this.completedAt = Date.now();
|
|
111
|
+
for (const listener of [...this.listeners]) {
|
|
112
|
+
try { listener(); } catch { /* never propagate to keyboard handling */ }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return this.entries ?? [];
|
|
116
|
+
})
|
|
117
|
+
.finally(() => { if (generation === this.generation) this.building = null; });
|
|
118
|
+
return this.building;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Contiguous matches take priority; fuzzy matching remains the JS fallback. */
|
|
122
|
+
candidates(query: string): string[] {
|
|
123
|
+
if (!query) return this.entries ?? [];
|
|
124
|
+
const needle = query.toLocaleLowerCase();
|
|
125
|
+
const direct = this.indexed.filter(entry => entry.folded.includes(needle));
|
|
126
|
+
return (direct.length > 0 ? direct.map(entry => entry.value) : this.entries ?? []);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private async scan(generation: number): Promise<{ entries: string[]; truncated: boolean }> {
|
|
130
|
+
const found: string[] = [];
|
|
131
|
+
const queue: Array<{ absolute: string; relative: string; depth: number }> = [
|
|
132
|
+
{ absolute: this.root, relative: '', depth: 0 }
|
|
133
|
+
];
|
|
134
|
+
let cursor = 0;
|
|
135
|
+
let truncated = false;
|
|
136
|
+
|
|
137
|
+
while (cursor < queue.length) {
|
|
138
|
+
if (this.disposed || generation !== this.generation) break;
|
|
139
|
+
if (cursor >= this.maxDirs || found.length >= this.maxEntries) {
|
|
140
|
+
truncated = true;
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
const current = queue[cursor++];
|
|
144
|
+
if (!current) break;
|
|
145
|
+
let listing;
|
|
146
|
+
try { listing = await readdir(current.absolute, { withFileTypes: true }); }
|
|
147
|
+
catch { continue; }
|
|
148
|
+
listing.sort((a, b) => a.name.localeCompare(b.name));
|
|
149
|
+
|
|
150
|
+
for (const entry of listing) {
|
|
151
|
+
if (this.disposed || generation !== this.generation) break;
|
|
152
|
+
if (entry.isSymbolicLink()) continue;
|
|
153
|
+
if (!entry.isFile() && !entry.isDirectory()) continue;
|
|
154
|
+
const relative = current.relative ? `${current.relative}/${entry.name}` : entry.name;
|
|
155
|
+
if (!safeRelative(relative)) continue;
|
|
156
|
+
|
|
157
|
+
if (entry.isDirectory()) {
|
|
158
|
+
if (SKIP.has(entry.name)) continue;
|
|
159
|
+
if (current.depth < this.maxDepth) {
|
|
160
|
+
if (queue.length >= this.maxDirs) truncated = true;
|
|
161
|
+
else queue.push({
|
|
162
|
+
absolute: path.join(current.absolute, entry.name),
|
|
163
|
+
relative, depth: current.depth + 1
|
|
164
|
+
});
|
|
165
|
+
} else truncated = true;
|
|
166
|
+
found.push(`${relative}/`);
|
|
167
|
+
} else {
|
|
168
|
+
found.push(relative);
|
|
169
|
+
}
|
|
170
|
+
if (found.length >= this.maxEntries) { truncated = true; break; }
|
|
171
|
+
}
|
|
172
|
+
// Periodically yield: typing, rendering and cancellation must remain responsive.
|
|
173
|
+
if (cursor % YIELD_EVERY === 0) {
|
|
174
|
+
await new Promise<void>(resolve => setImmediate(resolve));
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return { entries: found, truncated };
|
|
178
|
+
}
|
|
179
|
+
}
|