@causyne/agent 1.20.94 → 1.20.96

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.
@@ -16,6 +16,7 @@ import fs from 'node:fs';
16
16
  import path from 'node:path';
17
17
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
18
18
  import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall, type ChatResponseUsage } from './base.js';
19
+ import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError, DESKTOP_TASK_WALL_MS } from '../budget/budgetPolicy.js';
19
20
  import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
20
21
 
21
22
  /**
@@ -944,6 +945,10 @@ export class AntigravityProvider extends LLMProvider {
944
945
  const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
945
946
  const launchOnly = (options as any).taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
946
947
  const desktopTask = (options as any).taskArchetype === 'desktop_personalization';
948
+ const remainingWall = desktopTask ? remainingDesktopTime((options as any).taskDeadlineMs) : null;
949
+ if (remainingWall !== null && remainingWall <= 0) {
950
+ throw createBudgetError('AGY_TASK_DEADLINE', 'Desktop task wall-clock budget reached before the next peer invocation.');
951
+ }
947
952
  let promptText: string;
948
953
 
949
954
  if (useConversation) {
@@ -1058,9 +1063,7 @@ export class AntigravityProvider extends LLMProvider {
1058
1063
  }
1059
1064
  };
1060
1065
  const configuredActions = Number(options.maxNativeActions);
1061
- const isAutonomous = (options as any).hardBudget === false;
1062
- let maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
1063
- ? configuredActions : desktopTask ? 12 : isAutonomous ? Infinity : 35;
1066
+ const maxNativeActions = peerNativeActionCeiling(configuredActions, desktopTask);
1064
1067
  let nativeActionStarts = 0;
1065
1068
  let lastMutationActionIndex = 0;
1066
1069
  let progressiveActionsCount = 0;
@@ -1085,21 +1088,21 @@ export class AntigravityProvider extends LLMProvider {
1085
1088
  // disabled. Users can set a lower task budget through the existing UI.
1086
1089
  const remainingTaskBudget = Number(options.maxTokensThisCall);
1087
1090
  const rawTokenLimit = Number((options as any).tokenLimit);
1088
- const hasExplicitLimit = (Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0)
1089
- || (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0);
1090
1091
  const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
1091
- const defaultTokenLimit = 100_000;
1092
- const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
1093
- ? remainingTaskBudget
1094
- : (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
1095
- ? rawTokenLimit
1096
- : defaultTokenLimit);
1097
- const wallTimer = desktopTask ? setTimeout(() => {
1098
- const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.') as Error & { code: string };
1099
- error.code = 'AGY_DESKTOP_TASK_LIMIT';
1092
+ // A peer may execute many model steps without returning to AgentLoop.
1093
+ // Count uncached input + output for the conservative default ceiling.
1094
+ const requestedLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
1095
+ ? remainingTaskBudget : Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
1096
+ ? rawTokenLimit : Infinity;
1097
+ const tokenLimit = peerCallTokenCeiling(requestedLimit);
1098
+ const wallMs = desktopTask ? Math.min(DESKTOP_TASK_WALL_MS,
1099
+ remainingWall === null ? DESKTOP_TASK_WALL_MS : remainingWall) : null;
1100
+ const wallTimer = wallMs !== null ? setTimeout(() => {
1101
+ const error = createBudgetError('AGY_DESKTOP_TASK_LIMIT',
1102
+ 'Antigravity exceeded the remaining desktop task wall-clock allowance. Outcome is unverified.');
1100
1103
  safeReject(error);
1101
1104
  terminateChild();
1102
- }, 180_000) : null;
1105
+ }, wallMs) : null;
1103
1106
  wallTimer?.unref();
1104
1107
 
1105
1108
  const cleanup = () => {
@@ -1210,21 +1213,15 @@ export class AntigravityProvider extends LLMProvider {
1210
1213
  const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
1211
1214
  const uncachedTotal = noncachedTokens(partialUsage);
1212
1215
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1213
- if (Number.isFinite(tokenLimit) && tokenLimit > 0
1214
- && spentAgainstLimit >= tokenLimit) {
1215
- if ((options as any).hardBudget === false) {
1216
- if (process.env.CAUSYNE_DEBUG === '1') {
1217
- console.log(`[BUDGET] Turn spent ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Continuing execution.`);
1218
- }
1219
- } else {
1220
- const error = Object.assign(
1221
- new Error(`Antigravity reported ${spentAgainstLimit} tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`),
1222
- { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }
1223
- );
1224
- safeReject(error);
1225
- terminateChild();
1226
- return;
1227
- }
1216
+ if (spentAgainstLimit >= tokenLimit) {
1217
+ const error = Object.assign(
1218
+ createBudgetError('AGY_TOKEN_BUDGET',
1219
+ `Antigravity reached the ${tokenLimit}-token per-call ceiling. Outcome is unverified.`),
1220
+ { tokenLimit, partialUsage: { ...partialUsage } }
1221
+ );
1222
+ safeReject(error);
1223
+ terminateChild();
1224
+ return;
1228
1225
  }
1229
1226
  }
1230
1227
  }
@@ -1321,7 +1318,7 @@ export class AntigravityProvider extends LLMProvider {
1321
1318
 
1322
1319
  if (newNativeAction) {
1323
1320
  nativeActionStarts++;
1324
- if (!isAutonomous && Number.isFinite(maxNativeActions) && nativeActionStarts > maxNativeActions) {
1321
+ if (nativeActionStarts > maxNativeActions) {
1325
1322
  const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`) as Error & { code: string };
1326
1323
  error.code = 'AGY_NATIVE_ACTION_BUDGET';
1327
1324
  safeReject(error);
@@ -1699,16 +1696,11 @@ export class AntigravityProvider extends LLMProvider {
1699
1696
  const uncachedTotal = noncachedTokens(response.usage);
1700
1697
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1701
1698
  if (spentAgainstLimit >= tokenLimit) {
1702
- if ((options as any).hardBudget === false) {
1703
- if (process.env.CAUSYNE_DEBUG === '1') {
1704
- console.log(`[BUDGET] Turn finished with ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Preserving result.`);
1705
- }
1706
- } else {
1707
- Object.assign(partialUsage, response.usage);
1708
- safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
1709
- { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1710
- return;
1711
- }
1699
+ Object.assign(partialUsage, response.usage);
1700
+ safeReject(Object.assign(createBudgetError('AGY_TOKEN_BUDGET',
1701
+ `Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
1702
+ { tokenLimit, partialUsage: { ...partialUsage } }));
1703
+ return;
1712
1704
  }
1713
1705
  safeResolve(response);
1714
1706
  });
@@ -1723,10 +1715,8 @@ export class AntigravityProvider extends LLMProvider {
1723
1715
  try {
1724
1716
  return await this._executeOnce(messages, options);
1725
1717
  } catch (err: any) {
1726
- if (options.signal?.aborted || err?.name === 'AbortError') {
1727
- throw err;
1728
- }
1729
- if (err?.code === 'AGY_NATIVE_ACTION_DENIED' || err?.code === 'AGY_TOKEN_BUDGET' || err?.code === 'PROVIDER_NO_PROGRESS') {
1718
+ if (!shouldRetryPeerError(err, options.signal?.aborted === true || err?.name === 'AbortError')
1719
+ || err?.code === 'AGY_NATIVE_ACTION_DENIED' || err?.code === 'PROVIDER_NO_PROGRESS') {
1730
1720
  throw err;
1731
1721
  }
1732
1722
  const msg = String(err?.message || '').toLowerCase();
@@ -27,6 +27,9 @@ export class TokenTracker {
27
27
  sessionTokens;
28
28
  sessionCostUsd;
29
29
  largestStepTokens;
30
+ // Applied after every settings reload; prevents trackUsage() from silently
31
+ // dropping the limit selected at the beginning of this run.
32
+ enforcedTaskTokenLimit;
30
33
  constructor() {
31
34
  this.config = loadConfig();
32
35
  this.budget = this.config.tokenBudget || { enabled: false };
@@ -35,6 +38,7 @@ export class TokenTracker {
35
38
  this.sessionTokens = 0;
36
39
  this.sessionCostUsd = 0;
37
40
  this.largestStepTokens = 0;
41
+ this.enforcedTaskTokenLimit = null;
38
42
  this.ensureUsageDir();
39
43
  }
40
44
  getPricing(promptTokens = 0) {
@@ -178,6 +182,7 @@ export class TokenTracker {
178
182
  async trackMediaUsage(provider, mediaType, model, quantityUnits = 1, onWarning = null) {
179
183
  this.config = loadConfig();
180
184
  this.budget = this.config.tokenBudget || { enabled: false };
185
+ this.applyEnforcedTaskLimit();
181
186
  const unitPrice = this.getMediaPricing(provider, model, mediaType);
182
187
  const cost = unitPrice * (quantityUnits || 1);
183
188
  const equivalentTokens = Math.round(cost / 0.000002);
@@ -354,12 +359,30 @@ export class TokenTracker {
354
359
  }
355
360
  }
356
361
  }
362
+ setEnforcedTaskLimit(limit) {
363
+ this.enforcedTaskTokenLimit = Number.isSafeInteger(limit) && Number(limit) > 0
364
+ ? Number(limit) : null;
365
+ this.applyEnforcedTaskLimit();
366
+ }
367
+ applyEnforcedTaskLimit() {
368
+ const limit = this.enforcedTaskTokenLimit;
369
+ if (limit === null)
370
+ return;
371
+ this.budget = {
372
+ ...this.budget,
373
+ enabled: true,
374
+ hardStop: true,
375
+ maxTokensPerTask: limit
376
+ };
377
+ }
357
378
  resetTask() {
379
+ this.enforcedTaskTokenLimit = null;
358
380
  this.taskTokens = 0;
359
381
  this.taskCostUsd = 0;
360
382
  this.largestStepTokens = 0;
361
383
  }
362
384
  resetSession() {
385
+ this.enforcedTaskTokenLimit = null;
363
386
  this.sessionTokens = 0;
364
387
  this.sessionCostUsd = 0;
365
388
  this.taskTokens = 0;
@@ -391,6 +414,7 @@ export class TokenTracker {
391
414
  async trackUsage(promptTokens, completionTokens, onWarning = null, usageDetail = null) {
392
415
  this.config = loadConfig();
393
416
  this.budget = this.config.tokenBudget || { enabled: false };
417
+ this.applyEnforcedTaskLimit();
394
418
  const finite = (v) => (Number.isFinite(v) ? Math.max(0, Number(v)) : 0);
395
419
  const pTokens = finite(promptTokens);
396
420
  const cTokens = finite(completionTokens);
@@ -107,6 +107,9 @@ export class TokenTracker {
107
107
  sessionTokens: number;
108
108
  sessionCostUsd: number;
109
109
  largestStepTokens: number;
110
+ // Applied after every settings reload; prevents trackUsage() from silently
111
+ // dropping the limit selected at the beginning of this run.
112
+ enforcedTaskTokenLimit: number | null;
110
113
 
111
114
  constructor() {
112
115
  this.config = loadConfig() as TrackerConfig;
@@ -116,6 +119,7 @@ export class TokenTracker {
116
119
  this.sessionTokens = 0;
117
120
  this.sessionCostUsd = 0;
118
121
  this.largestStepTokens = 0;
122
+ this.enforcedTaskTokenLimit = null;
119
123
  this.ensureUsageDir();
120
124
  }
121
125
 
@@ -260,6 +264,7 @@ export class TokenTracker {
260
264
  ): Promise<{ allowed: boolean; used: number; costUsd: number; taskCostUsd: number; equivalentTokens: number; reason?: string }> {
261
265
  this.config = loadConfig() as TrackerConfig;
262
266
  this.budget = this.config.tokenBudget || { enabled: false };
267
+ this.applyEnforcedTaskLimit();
263
268
 
264
269
  const unitPrice = this.getMediaPricing(provider, model, mediaType);
265
270
  const cost = unitPrice * (quantityUnits || 1);
@@ -468,13 +473,32 @@ export class TokenTracker {
468
473
  }
469
474
  }
470
475
 
476
+ setEnforcedTaskLimit(limit: number | null): void {
477
+ this.enforcedTaskTokenLimit = Number.isSafeInteger(limit) && Number(limit) > 0
478
+ ? Number(limit) : null;
479
+ this.applyEnforcedTaskLimit();
480
+ }
481
+
482
+ private applyEnforcedTaskLimit(): void {
483
+ const limit = this.enforcedTaskTokenLimit;
484
+ if (limit === null) return;
485
+ this.budget = {
486
+ ...this.budget,
487
+ enabled: true,
488
+ hardStop: true,
489
+ maxTokensPerTask: limit
490
+ };
491
+ }
492
+
471
493
  resetTask(): void {
494
+ this.enforcedTaskTokenLimit = null;
472
495
  this.taskTokens = 0;
473
496
  this.taskCostUsd = 0;
474
497
  this.largestStepTokens = 0;
475
498
  }
476
499
 
477
500
  resetSession(): void {
501
+ this.enforcedTaskTokenLimit = null;
478
502
  this.sessionTokens = 0;
479
503
  this.sessionCostUsd = 0;
480
504
  this.taskTokens = 0;
@@ -514,6 +538,7 @@ export class TokenTracker {
514
538
  ): Promise<SettledUsage> {
515
539
  this.config = loadConfig() as TrackerConfig;
516
540
  this.budget = this.config.tokenBudget || { enabled: false };
541
+ this.applyEnforcedTaskLimit();
517
542
 
518
543
  const finite = (v: number | undefined | null): number => (Number.isFinite(v) ? Math.max(0, Number(v)) : 0);
519
544
  const pTokens = finite(promptTokens);
@@ -13,11 +13,12 @@
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
+ export { WorkspaceFileIndex as FileIndex };
21
22
 
22
23
  export const MAX_VISIBLE = 8;
23
24
 
@@ -29,8 +30,6 @@ const SKIP_DIRECTORIES = new Set([
29
30
  '.idea', '.cache', 'coverage', 'vendor', 'Pods', '.causyne'
30
31
  ]);
31
32
 
32
- const MAX_INDEX_ENTRIES = 20000;
33
- const MAX_INDEX_DEPTH = 12;
34
33
 
35
34
  /** A value is offerable only if printing it changes nothing. */
36
35
  export function isTerminalSafe(value) {
@@ -52,26 +51,28 @@ export function isTerminalSafe(value) {
52
51
  */
53
52
  export function score(candidate, query) {
54
53
  if (!query) return 0;
55
- const haystack = candidate.toLowerCase();
56
- const needle = query.toLowerCase();
57
-
58
- if (haystack.startsWith(needle)) return 1000 - candidate.length;
59
-
60
- const base = haystack.slice(haystack.lastIndexOf('/') + 1);
61
- if (base.startsWith(needle)) return 800 - candidate.length;
62
- if (haystack.includes(needle)) return 700 - candidate.length;
63
- if (base.includes(needle)) return 600 - candidate.length;
64
-
65
- // Subsequence: every character of the query in order, gaps allowed. This is
66
- // what lets "tuich" find "tui/chatRenderer.js".
67
- let index = 0;
54
+ const full = candidate.toLocaleLowerCase();
55
+ const needle = query.toLocaleLowerCase();
56
+ const leaf = full.replace(/\/$/, '').split('/').at(-1) || '';
57
+ const isDirectory = candidate.endsWith('/');
58
+ const pathPenalty = Math.min(candidate.length, 180);
59
+ const fileBonus = isDirectory ? 0 : 20;
60
+
61
+ if (leaf === needle) return 1800 + fileBonus - pathPenalty;
62
+ if (leaf.startsWith(needle)) return 1500 + fileBonus - pathPenalty;
63
+ if (leaf.includes(needle)) return 1200 + fileBonus - pathPenalty;
64
+ if (full.startsWith(needle)) return 1050 + fileBonus - pathPenalty;
65
+ if (full.includes(needle)) return 900 + fileBonus - pathPenalty;
66
+
67
+ // Fallback: a bounded subsequence match for abbreviations such as tuich.
68
+ let cursor = 0;
68
69
  let gaps = 0;
69
- for (const character of haystack) {
70
- if (character === needle[index]) {
71
- index += 1;
72
- if (index === needle.length) return 400 - gaps - candidate.length;
73
- } else if (index > 0) {
74
- gaps += 1;
70
+ for (const character of full) {
71
+ if (character === needle[cursor]) {
72
+ cursor++;
73
+ if (cursor === needle.length) return 400 - gaps - pathPenalty;
74
+ } else if (cursor > 0) {
75
+ gaps++;
75
76
  }
76
77
  }
77
78
  return -1;
@@ -110,7 +111,7 @@ function rank(items, query, limit = 50, focusDir = null) {
110
111
  value += 2000;
111
112
  }
112
113
  if (focusPrefix && val.toLowerCase().startsWith(focusPrefix)) {
113
- value += 3000;
114
+ value += 90;
114
115
  }
115
116
  const resultItem = matchedAlias
116
117
  ? { ...item, description: `(alias: /${matchedAlias}) ${item.description}` }
@@ -118,7 +119,7 @@ function rank(items, query, limit = 50, focusDir = null) {
118
119
  scored.push({ item: resultItem, value });
119
120
  }
120
121
  }
121
- scored.sort((a, b) => b.value - a.value);
122
+ scored.sort((a, b) => b.value - a.value || a.item.value.localeCompare(b.item.value));
122
123
  const ranked = scored.slice(0, limit).map((entry) => entry.item);
123
124
  ranked.total = scored.length;
124
125
  return ranked;
@@ -244,67 +245,7 @@ function argumentItems(name) {
244
245
  * upgrades the experience once it is ready. If it is never ready, nothing
245
246
  * breaks — the caller must never await it.
246
247
  */
247
- export class FileIndex {
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
- }
248
+ // FileIndex is now owned by src/tui/workspaceFileIndex.ts.
308
249
 
309
250
  /**
310
251
  * Resolve both the authorized root and candidate to physical paths before
@@ -462,11 +403,11 @@ export function suggest(text, cursor, options = {}) {
462
403
  const root = options.root || process.cwd();
463
404
  const index = options.index;
464
405
  const focusDir = options.focusDir || null;
465
- if (index && !index.isReady) index.ensure();
406
+ if (index) void index.ensure();
466
407
 
467
408
  let pool;
468
409
  if (index && index.isReady && trigger.query) {
469
- pool = index.entries.map((relative) => ({
410
+ pool = index.candidates(trigger.query).map((relative) => ({
470
411
  value: relative,
471
412
  match: relative,
472
413
  label: relative,
@@ -495,7 +436,7 @@ export function suggest(text, cursor, options = {}) {
495
436
  pool = directoryItems(root, trigger.query);
496
437
  }
497
438
 
498
- const items = rank(pool, trigger.query, 50, focusDir);
439
+ const items = rank(pool, trigger.query, 500, focusDir);
499
440
  if (items.length === 0) return null;
500
441
  return { ...trigger, items, total: items.total };
501
442
  }
package/src/tui/prompt.js CHANGED
@@ -121,6 +121,8 @@ export class ChatPrompt {
121
121
  this.editor = new LineEditor();
122
122
  this.history = options.history || new PromptHistory();
123
123
  this.index = new FileIndex(this.root);
124
+ this._unsubscribeFileIndex = null;
125
+ this.bindFileIndex(this.index);
124
126
  this.decoder = new KeyDecoder();
125
127
  this.inputFramer = new TerminalInputFramer();
126
128
  this.inputFrameTimer = null;
@@ -1304,12 +1306,32 @@ export class ChatPrompt {
1304
1306
  // Completion
1305
1307
  // -------------------------------------------------------------------------
1306
1308
 
1309
+ /** A completed scan must refresh the currently displayed @ picker. */
1310
+ bindFileIndex(index) {
1311
+ if (typeof this._unsubscribeFileIndex === 'function') this._unsubscribeFileIndex();
1312
+ this._unsubscribeFileIndex = index.subscribe(() => {
1313
+ // Ignore a late callback from a previous workspace or a dismissed prompt.
1314
+ if (this.index !== index || !this.active) return;
1315
+ const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
1316
+ if (!trigger || trigger.kind !== 'file') return;
1317
+ this.openCompletion(false);
1318
+ if (index.truncated) this.notice = 'Workspace file index reached its safety limit; narrow the project root.';
1319
+ else if (this.notice === 'Indexing workspace files…') this.notice = null;
1320
+ this.scheduleDraw();
1321
+ });
1322
+ void index.ensure();
1323
+ }
1324
+
1307
1325
  /** Dynamically re-target the prompt root and optional focused subproject. */
1308
1326
  setWorkingRoot(newRoot, focusDir = null) {
1327
+ if (typeof this._unsubscribeFileIndex === 'function') this._unsubscribeFileIndex();
1328
+ this.index?.dispose();
1309
1329
  this.root = newRoot;
1310
1330
  this.focusDir = focusDir;
1311
1331
  this.index = new FileIndex(newRoot);
1312
- this.index.ensure();
1332
+ this.bindFileIndex(this.index);
1333
+ const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
1334
+ if (trigger?.kind === 'file') this.openCompletion(false);
1313
1335
  }
1314
1336
 
1315
1337
  cursorOffset() {
@@ -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
+ }