@cortexkit/aft 0.35.0 → 0.35.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -46,75 +46,1359 @@ var __export = (target, all) => {
46
46
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
47
47
  var __promiseAll = (args) => Promise.all(args);
48
48
 
49
- // src/lib/paths.ts
50
- import { homedir, tmpdir } from "node:os";
49
+ // ../aft-bridge/dist/active-logger.js
50
+ function loggerGlobal() {
51
+ return globalThis;
52
+ }
53
+ function getActiveLogger() {
54
+ return loggerGlobal()[ACTIVE_LOGGER_SYMBOL];
55
+ }
56
+ function getLogFilePath() {
57
+ try {
58
+ return getActiveLogger()?.getLogFilePath?.();
59
+ } catch (err) {
60
+ console.error(`[aft-bridge] ERROR: active logger getLogFilePath threw: ${err instanceof Error ? err.message : String(err)}`);
61
+ return;
62
+ }
63
+ }
64
+ function log(message, meta) {
65
+ const active = getActiveLogger();
66
+ if (active) {
67
+ try {
68
+ active.log(message, meta);
69
+ } catch (err) {
70
+ console.error(`[aft-bridge] ERROR: active logger log threw: ${err instanceof Error ? err.message : String(err)}`);
71
+ console.error(`[aft-bridge] ${message}`);
72
+ }
73
+ } else {
74
+ console.error(`[aft-bridge] ${message}`);
75
+ }
76
+ }
77
+ function warn(message, meta) {
78
+ const active = getActiveLogger();
79
+ if (active) {
80
+ try {
81
+ active.warn(message, meta);
82
+ } catch (err) {
83
+ console.error(`[aft-bridge] ERROR: active logger warn threw: ${err instanceof Error ? err.message : String(err)}`);
84
+ console.error(`[aft-bridge] WARN: ${message}`);
85
+ }
86
+ } else {
87
+ console.error(`[aft-bridge] WARN: ${message}`);
88
+ }
89
+ }
90
+ function error(message, meta) {
91
+ const active = getActiveLogger();
92
+ if (active) {
93
+ try {
94
+ active.error(message, meta);
95
+ } catch (err) {
96
+ console.error(`[aft-bridge] ERROR: active logger error threw: ${err instanceof Error ? err.message : String(err)}`);
97
+ console.error(`[aft-bridge] ERROR: ${message}`);
98
+ }
99
+ } else {
100
+ console.error(`[aft-bridge] ERROR: ${message}`);
101
+ }
102
+ }
103
+ var ACTIVE_LOGGER_SYMBOL;
104
+ var init_active_logger = __esm(() => {
105
+ ACTIVE_LOGGER_SYMBOL = Symbol.for("aft-bridge-active-logger");
106
+ });
107
+ // ../aft-bridge/dist/status-bar.js
108
+ function parseStatusBarCounts(value) {
109
+ if (!value || typeof value !== "object")
110
+ return;
111
+ const record = value;
112
+ const num = (key) => {
113
+ const raw = record[key];
114
+ return typeof raw === "number" && Number.isFinite(raw) ? raw : 0;
115
+ };
116
+ return {
117
+ errors: num("errors"),
118
+ warnings: num("warnings"),
119
+ dead_code: num("dead_code"),
120
+ unused_exports: num("unused_exports"),
121
+ duplicates: num("duplicates"),
122
+ todos: num("todos"),
123
+ tier2_stale: record.tier2_stale === true
124
+ };
125
+ }
126
+
127
+ // ../aft-bridge/dist/bridge.js
128
+ import { spawn } from "node:child_process";
129
+ import { homedir } from "node:os";
51
130
  import { join } from "node:path";
131
+ import { StringDecoder } from "node:string_decoder";
132
+ function tagStderrLine(line) {
133
+ return /^\[aft(-\w+)?\] /.test(line) ? line : `[aft] ${line}`;
134
+ }
135
+ function compareSemver(a, b) {
136
+ const [aMain, aPre] = a.split("-", 2);
137
+ const [bMain, bPre] = b.split("-", 2);
138
+ const aParts = aMain.split(".").map(Number);
139
+ const bParts = bMain.split(".").map(Number);
140
+ for (let i = 0;i < 3; i++) {
141
+ if (aParts[i] !== bParts[i])
142
+ return (aParts[i] ?? 0) - (bParts[i] ?? 0);
143
+ }
144
+ if (!aPre && !bPre)
145
+ return 0;
146
+ if (!aPre)
147
+ return 1;
148
+ if (!bPre)
149
+ return -1;
150
+ const aIds = aPre.split(".");
151
+ const bIds = bPre.split(".");
152
+ for (let i = 0;i < Math.max(aIds.length, bIds.length); i++) {
153
+ const ai = aIds[i];
154
+ const bi = bIds[i];
155
+ if (ai === undefined)
156
+ return -1;
157
+ if (bi === undefined)
158
+ return 1;
159
+ const aNum = /^\d+$/.test(ai);
160
+ const bNum = /^\d+$/.test(bi);
161
+ if (aNum && bNum) {
162
+ const diff = Number.parseInt(ai, 10) - Number.parseInt(bi, 10);
163
+ if (diff !== 0)
164
+ return diff;
165
+ } else if (aNum) {
166
+ return -1;
167
+ } else if (bNum) {
168
+ return 1;
169
+ } else {
170
+ const cmp = ai.localeCompare(bi);
171
+ if (cmp !== 0)
172
+ return cmp;
173
+ }
174
+ }
175
+ return 0;
176
+ }
177
+ function clampSemanticTimeout(configOverrides, bridgeTimeoutMs) {
178
+ const semantic = configOverrides.semantic;
179
+ if (!semantic || typeof semantic !== "object" || Array.isArray(semantic)) {
180
+ return configOverrides;
181
+ }
182
+ const timeoutMs = semantic.timeout_ms;
183
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs)) {
184
+ return configOverrides;
185
+ }
186
+ const maxSemanticTimeoutMs = bridgeTimeoutMs > SEMANTIC_TIMEOUT_SAFETY_MARGIN_MS ? bridgeTimeoutMs - SEMANTIC_TIMEOUT_SAFETY_MARGIN_MS : Math.max(1, bridgeTimeoutMs - 1);
187
+ if (timeoutMs <= maxSemanticTimeoutMs) {
188
+ return configOverrides;
189
+ }
190
+ warn(`semantic.timeout_ms=${timeoutMs} exceeds bridge timeout budget; clamping to ${maxSemanticTimeoutMs}ms (bridge timeout: ${bridgeTimeoutMs}ms)`);
191
+ return {
192
+ ...configOverrides,
193
+ semantic: {
194
+ ...semantic,
195
+ timeout_ms: maxSemanticTimeoutMs
196
+ }
197
+ };
198
+ }
199
+ var DEFAULT_BRIDGE_TIMEOUT_MS = 30000, BRIDGE_HANG_TIMEOUT_THRESHOLD = 2, SEMANTIC_TIMEOUT_SAFETY_MARGIN_MS = 5000, MAX_STDOUT_BUFFER, BridgeReplacedDuringVersionCheck, BinaryBridge;
200
+ var init_bridge = __esm(() => {
201
+ init_active_logger();
202
+ MAX_STDOUT_BUFFER = 64 * 1024 * 1024;
203
+ BridgeReplacedDuringVersionCheck = class BridgeReplacedDuringVersionCheck extends Error {
204
+ newBinaryPath;
205
+ constructor(newBinaryPath) {
206
+ super(`Bridge binary replaced during version check: ${newBinaryPath}`);
207
+ this.newBinaryPath = newBinaryPath;
208
+ this.name = "BridgeReplacedDuringVersionCheck";
209
+ }
210
+ };
211
+ BinaryBridge = class BinaryBridge {
212
+ static RESTART_RESET_MS = 5 * 60 * 1000;
213
+ static STDERR_TAIL_MAX = 20;
214
+ binaryPath;
215
+ cwd;
216
+ process = null;
217
+ pending = new Map;
218
+ nextId = 1;
219
+ stdoutBuffer = "";
220
+ stderrBuffer = "";
221
+ stderrTail = [];
222
+ _restartCount = 0;
223
+ _shuttingDown = false;
224
+ timeoutMs;
225
+ maxRestarts;
226
+ configured = false;
227
+ _configurePromise = null;
228
+ configOverrides;
229
+ minVersion;
230
+ onVersionMismatch;
231
+ onConfigureWarnings;
232
+ onBashCompletion;
233
+ onBashLongRunning;
234
+ onBashPatternMatch;
235
+ cachedStatus = null;
236
+ statusListeners = new Set;
237
+ configureWarningClients = new Map;
238
+ restartResetTimer = null;
239
+ lastChildActivityAt = 0;
240
+ lastStatusBar;
241
+ consecutiveRequestTimeouts = 0;
242
+ errorPrefix;
243
+ logger;
244
+ childEnv;
245
+ constructor(binaryPath, cwd, options, configOverrides) {
246
+ this.binaryPath = binaryPath;
247
+ this.cwd = cwd;
248
+ this.timeoutMs = options?.timeoutMs ?? DEFAULT_BRIDGE_TIMEOUT_MS;
249
+ this.maxRestarts = options?.maxRestarts ?? 3;
250
+ this.configOverrides = clampSemanticTimeout(configOverrides ?? {}, this.timeoutMs);
251
+ this.minVersion = options?.minVersion;
252
+ this.onVersionMismatch = options?.onVersionMismatch;
253
+ this.onConfigureWarnings = options?.onConfigureWarnings;
254
+ this.onBashCompletion = options?.onBashCompletion;
255
+ this.onBashLongRunning = options?.onBashLongRunning;
256
+ this.onBashPatternMatch = options?.onBashPatternMatch;
257
+ this.errorPrefix = options?.errorPrefix ?? "[aft-bridge]";
258
+ this.logger = options?.logger;
259
+ this.childEnv = options?.childEnv;
260
+ }
261
+ logVia(message, meta) {
262
+ const logger = this.logger ?? getActiveLogger();
263
+ if (logger) {
264
+ try {
265
+ logger.log(message, meta);
266
+ } catch (err) {
267
+ console.error(`[aft-bridge] ERROR: logger log threw: ${err instanceof Error ? err.message : String(err)}`);
268
+ console.error(`[aft-bridge] ${message}`);
269
+ }
270
+ } else {
271
+ log(message, meta);
272
+ }
273
+ }
274
+ warnVia(message, meta) {
275
+ const logger = this.logger ?? getActiveLogger();
276
+ if (logger) {
277
+ try {
278
+ logger.warn(message, meta);
279
+ } catch (err) {
280
+ console.error(`[aft-bridge] ERROR: logger warn threw: ${err instanceof Error ? err.message : String(err)}`);
281
+ console.error(`[aft-bridge] WARN: ${message}`);
282
+ }
283
+ } else {
284
+ warn(message, meta);
285
+ }
286
+ }
287
+ errorVia(message, meta) {
288
+ const logger = this.logger ?? getActiveLogger();
289
+ if (logger) {
290
+ try {
291
+ logger.error(message, meta);
292
+ } catch (err) {
293
+ console.error(`[aft-bridge] ERROR: logger error threw: ${err instanceof Error ? err.message : String(err)}`);
294
+ console.error(`[aft-bridge] ERROR: ${message}`);
295
+ }
296
+ } else {
297
+ error(message, meta);
298
+ }
299
+ }
300
+ getLogFilePathVia() {
301
+ if (this.logger?.getLogFilePath) {
302
+ try {
303
+ return this.logger.getLogFilePath();
304
+ } catch (err) {
305
+ console.error(`[aft-bridge] ERROR: logger getLogFilePath threw: ${err instanceof Error ? err.message : String(err)}`);
306
+ return;
307
+ }
308
+ }
309
+ return getLogFilePath();
310
+ }
311
+ sessionLogVia(sessionId, message) {
312
+ this.logVia(message, sessionId ? { sessionId } : undefined);
313
+ }
314
+ sessionWarnVia(sessionId, message) {
315
+ this.warnVia(message, sessionId ? { sessionId } : undefined);
316
+ }
317
+ sessionErrorVia(sessionId, message) {
318
+ this.errorVia(message, sessionId ? { sessionId } : undefined);
319
+ }
320
+ get restartCount() {
321
+ return this._restartCount;
322
+ }
323
+ isAlive() {
324
+ return this.process !== null && this.process.exitCode === null && !this.process.killed;
325
+ }
326
+ hasPendingRequests() {
327
+ return this.pending.size > 0;
328
+ }
329
+ getCachedStatus() {
330
+ return this.cachedStatus;
331
+ }
332
+ subscribeStatus(listener) {
333
+ this.statusListeners.add(listener);
334
+ if (this.cachedStatus !== null) {
335
+ this.deliverStatusSnapshot(listener, this.cachedStatus);
336
+ }
337
+ return () => {
338
+ this.statusListeners.delete(listener);
339
+ };
340
+ }
341
+ cacheStatusSnapshot(snapshot) {
342
+ this.cachedStatus = snapshot;
343
+ }
344
+ async send(command, params = {}, options) {
345
+ return this.sendWithVersionMismatchRetry(command, params, options, true);
346
+ }
347
+ async sendWithVersionMismatchRetry(command, params, options, canRetryAfterVersionSwap) {
348
+ try {
349
+ if (this._shuttingDown) {
350
+ throw new Error(`${this.errorPrefix} Bridge is shutting down, cannot send "${command}"`);
351
+ }
352
+ if (Object.hasOwn(params, "id")) {
353
+ throw new Error("params cannot contain reserved key 'id'");
354
+ }
355
+ const requestSessionId = typeof params.session_id === "string" && params.session_id.length > 0 ? params.session_id : undefined;
356
+ this.ensureSpawned(requestSessionId);
357
+ if (requestSessionId && options?.configureWarningClient !== undefined) {
358
+ this.configureWarningClients.set(requestSessionId, options.configureWarningClient);
359
+ }
360
+ const effectiveTimeoutMs = options?.transportTimeoutMs ?? options?.timeoutMs ?? this.timeoutMs;
361
+ const implicitTransportOptions = {
362
+ ...options?.transportTimeoutMs !== undefined || options?.timeoutMs !== undefined ? { transportTimeoutMs: effectiveTimeoutMs } : {},
363
+ markConfiguredOnSuccess: false
364
+ };
365
+ if (!this.configured) {
366
+ if (command !== "configure" && command !== "version") {
367
+ if (!this._configurePromise) {
368
+ const sessionIdForConfigure = typeof params.session_id === "string" ? params.session_id : undefined;
369
+ this._configurePromise = (async () => {
370
+ try {
371
+ const configResult = await this.send("configure", {
372
+ project_root: this.cwd,
373
+ ...this.configOverrides,
374
+ ...sessionIdForConfigure ? { session_id: sessionIdForConfigure } : {}
375
+ }, implicitTransportOptions);
376
+ if (configResult.success === false) {
377
+ throw new Error(`${this.errorPrefix} Configure failed: ${configResult.message ?? "unknown error"}`);
378
+ }
379
+ await this.deliverConfigureWarnings(configResult, params, options);
380
+ await this.checkVersion(implicitTransportOptions);
381
+ if (!this.isAlive()) {
382
+ throw new Error(`${this.errorPrefix} Bridge died during version check. Check logs: ${this.getLogFilePathVia()}`);
383
+ }
384
+ this.configured = true;
385
+ } finally {
386
+ this._configurePromise = null;
387
+ }
388
+ })();
389
+ }
390
+ await this._configurePromise;
391
+ }
392
+ }
393
+ const id = String(this.nextId++);
394
+ let request;
395
+ if (Object.hasOwn(params, "command") || Object.hasOwn(params, "method")) {
396
+ const nested = { ...params };
397
+ const reserved = {};
398
+ for (const key of ["session_id", "lsp_hints"]) {
399
+ if (Object.hasOwn(nested, key)) {
400
+ reserved[key] = nested[key];
401
+ delete nested[key];
402
+ }
403
+ }
404
+ request = { id, command, ...reserved, params: nested };
405
+ } else {
406
+ request = { id, command, ...params };
407
+ }
408
+ const line = `${JSON.stringify(request)}
409
+ `;
410
+ const keepBridgeOnTimeout = options?.keepBridgeOnTimeout === true;
411
+ let requestSentAt = Date.now();
412
+ const response = await new Promise((resolve, reject) => {
413
+ const timer = setTimeout(() => {
414
+ const entry = this.pending.get(id);
415
+ if (!entry)
416
+ return;
417
+ this.pending.delete(id);
418
+ clearTimeout(entry.timer);
419
+ if (keepBridgeOnTimeout) {
420
+ const timeoutMsg2 = `Request "${command}" (id=${id}) timed out after ${effectiveTimeoutMs}ms`;
421
+ if (requestSessionId) {
422
+ this.sessionWarnVia(requestSessionId, timeoutMsg2);
423
+ } else {
424
+ this.warnVia(timeoutMsg2);
425
+ }
426
+ entry.reject(new Error(`${this.errorPrefix} Request "${command}" (id=${id}) timed out after ${effectiveTimeoutMs}ms`));
427
+ return;
428
+ }
429
+ const childActiveSinceRequest = this.lastChildActivityAt > requestSentAt;
430
+ const consecutiveTimeouts = this.consecutiveRequestTimeouts + 1;
431
+ this.consecutiveRequestTimeouts = consecutiveTimeouts;
432
+ const keepWarm = childActiveSinceRequest || consecutiveTimeouts < BRIDGE_HANG_TIMEOUT_THRESHOLD;
433
+ const restartSuffix = keepWarm ? " — bridge kept warm" : " — restarting bridge";
434
+ const timeoutMsg = `Request "${command}" (id=${id}) timed out after ${effectiveTimeoutMs}ms${restartSuffix}`;
435
+ if (requestSessionId) {
436
+ this.sessionWarnVia(requestSessionId, timeoutMsg);
437
+ } else {
438
+ this.warnVia(timeoutMsg);
439
+ }
440
+ if (keepWarm) {
441
+ entry.reject(new Error(`${this.errorPrefix} request "${command}" timed out after ${effectiveTimeoutMs}ms (bridge busy/under load); bridge kept warm — retry`));
442
+ return;
443
+ }
444
+ entry.reject(new Error(`${this.errorPrefix} Request "${command}" (id=${id}) timed out after ${effectiveTimeoutMs}ms`));
445
+ this.handleTimeout(requestSessionId);
446
+ }, effectiveTimeoutMs);
447
+ this.pending.set(id, { resolve, reject, timer, onProgress: options?.onProgress });
448
+ if (!this.process?.stdin?.writable) {
449
+ this.pending.delete(id);
450
+ clearTimeout(timer);
451
+ reject(new Error(`${this.errorPrefix} stdin not writable for command "${command}"`));
452
+ return;
453
+ }
454
+ requestSentAt = Date.now();
455
+ this.process.stdin.write(line, (err) => {
456
+ if (err) {
457
+ const entry = this.pending.get(id);
458
+ if (entry) {
459
+ this.pending.delete(id);
460
+ clearTimeout(entry.timer);
461
+ entry.reject(new Error(`${this.errorPrefix} Failed to write to stdin: ${err.message}`));
462
+ }
463
+ }
464
+ });
465
+ });
466
+ if (command === "configure" && response.success === true && options?.markConfiguredOnSuccess !== false) {
467
+ this.configured = true;
468
+ }
469
+ return response;
470
+ } catch (err) {
471
+ if (err instanceof BridgeReplacedDuringVersionCheck && canRetryAfterVersionSwap && command !== "configure" && command !== "version") {
472
+ this.logVia(`Retrying request "${command}" once after coordinated binary replacement: ${err.newBinaryPath}`);
473
+ return this.sendWithVersionMismatchRetry(command, params, options, false);
474
+ }
475
+ throw err;
476
+ }
477
+ }
478
+ async deliverConfigureWarnings(configResult, params, options) {
479
+ if (!this.onConfigureWarnings || !Array.isArray(configResult.warnings))
480
+ return;
481
+ if (configResult.warnings.length === 0)
482
+ return;
483
+ const sessionId = typeof params.session_id === "string" ? params.session_id : undefined;
484
+ try {
485
+ await this.onConfigureWarnings({
486
+ projectRoot: this.cwd,
487
+ sessionId,
488
+ client: options?.configureWarningClient ?? (sessionId ? this.configureWarningClients.get(sessionId) : undefined),
489
+ warnings: configResult.warnings
490
+ });
491
+ } catch (err) {
492
+ this.warnVia(`configure warning delivery failed: ${err instanceof Error ? err.message : String(err)}`);
493
+ } finally {
494
+ if (sessionId) {
495
+ this.configureWarningClients.delete(sessionId);
496
+ }
497
+ }
498
+ }
499
+ async handleConfigureWarningsFrame(frame) {
500
+ if (!this.onConfigureWarnings)
501
+ return;
502
+ const warnings = frame.warnings;
503
+ if (!Array.isArray(warnings) || warnings.length === 0)
504
+ return;
505
+ const projectRoot = typeof frame.project_root === "string" ? frame.project_root : this.cwd;
506
+ const rawSessionId = frame.session_id;
507
+ const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : null;
508
+ try {
509
+ await this.onConfigureWarnings({
510
+ projectRoot,
511
+ sessionId,
512
+ client: sessionId ? this.configureWarningClients.get(sessionId) : undefined,
513
+ warnings
514
+ });
515
+ } finally {
516
+ if (sessionId) {
517
+ this.configureWarningClients.delete(sessionId);
518
+ }
519
+ }
520
+ }
521
+ handleStatusChangedFrame(frame) {
522
+ const snapshot = frame.snapshot;
523
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot))
524
+ return;
525
+ this.cachedStatus = snapshot;
526
+ this.logVia("Received status_changed push frame; cached AFT status snapshot");
527
+ for (const listener of this.statusListeners) {
528
+ this.deliverStatusSnapshot(listener, this.cachedStatus);
529
+ }
530
+ }
531
+ deliverStatusSnapshot(listener, snapshot) {
532
+ try {
533
+ listener(snapshot);
534
+ } catch (err) {
535
+ this.warnVia(`status listener threw: ${err instanceof Error ? err.message : String(err)}`);
536
+ }
537
+ }
538
+ async shutdown() {
539
+ this._shuttingDown = true;
540
+ this.clearRestartResetTimer();
541
+ this.configureWarningClients.clear();
542
+ this.rejectAllPending(new Error(`${this.errorPrefix} Bridge shutting down`));
543
+ if (this.process) {
544
+ const proc = this.process;
545
+ this.process = null;
546
+ return new Promise((resolve) => {
547
+ const forceKillTimer = setTimeout(() => {
548
+ proc.kill("SIGKILL");
549
+ resolve();
550
+ }, 5000);
551
+ proc.once("exit", () => {
552
+ clearTimeout(forceKillTimer);
553
+ this.logVia("Process exited during shutdown");
554
+ resolve();
555
+ });
556
+ proc.kill("SIGTERM");
557
+ });
558
+ }
559
+ }
560
+ async checkVersion(options) {
561
+ if (!this.minVersion)
562
+ return;
563
+ try {
564
+ const resp = await this.send("version", {}, options);
565
+ if (resp.success === false) {
566
+ throw new Error(`Binary version check failed: ${String(resp.code ?? "unknown")} — likely too old`);
567
+ }
568
+ const binaryVersion = resp.version;
569
+ if (typeof binaryVersion !== "string") {
570
+ throw new Error(`Binary did not report a version — likely too old (minVersion: ${this.minVersion})`);
571
+ }
572
+ this.logVia(`Binary version: ${binaryVersion}`);
573
+ if (compareSemver(binaryVersion, this.minVersion) < 0) {
574
+ this.warnVia(`Binary version ${binaryVersion} is older than required ${this.minVersion}`);
575
+ const replacementPath = await this.onVersionMismatch?.(binaryVersion, this.minVersion);
576
+ if (replacementPath === undefined) {
577
+ return;
578
+ }
579
+ if (replacementPath === null || replacementPath.length === 0) {
580
+ throw new Error(`Binary version ${binaryVersion} is older than required ${this.minVersion}; no compatible replacement binary was provided`);
581
+ }
582
+ await this.replaceCurrentBinary(replacementPath);
583
+ throw new BridgeReplacedDuringVersionCheck(replacementPath);
584
+ }
585
+ } catch (err) {
586
+ this.warnVia(`Version check failed: ${err.message}`);
587
+ throw err;
588
+ }
589
+ }
590
+ async replaceCurrentBinary(newBinaryPath) {
591
+ this.binaryPath = newBinaryPath;
592
+ this.configured = false;
593
+ this.clearRestartResetTimer();
594
+ this.rejectAllPending(new Error(`${this.errorPrefix} Bridge restarting with updated binary: ${newBinaryPath}`));
595
+ if (!this.process)
596
+ return;
597
+ const proc = this.process;
598
+ this.process = null;
599
+ await new Promise((resolve) => {
600
+ const forceKillTimer = setTimeout(() => {
601
+ proc.kill("SIGKILL");
602
+ resolve();
603
+ }, 5000);
604
+ proc.once("exit", () => {
605
+ clearTimeout(forceKillTimer);
606
+ this.logVia("Process exited during coordinated binary replacement");
607
+ resolve();
608
+ });
609
+ proc.kill("SIGTERM");
610
+ });
611
+ }
612
+ ensureSpawned(triggeringSessionId) {
613
+ if (this.isAlive())
614
+ return;
615
+ this.spawnProcess(triggeringSessionId);
616
+ }
617
+ spawnProcess(triggeringSessionId) {
618
+ this.lastStatusBar = undefined;
619
+ if (triggeringSessionId) {
620
+ this.sessionLogVia(triggeringSessionId, `Spawning binary: ${this.binaryPath} (cwd: ${this.cwd})`);
621
+ } else {
622
+ this.logVia(`Spawning binary: ${this.binaryPath} (cwd: ${this.cwd})`);
623
+ }
624
+ const semantic = this.configOverrides.semantic;
625
+ const semanticBackend = (() => {
626
+ if (semantic && typeof semantic === "object" && !Array.isArray(semantic)) {
627
+ const candidate = semantic.backend;
628
+ return typeof candidate === "string" ? candidate : undefined;
629
+ }
630
+ return;
631
+ })();
632
+ const useFastembedBackend = semanticBackend === undefined || semanticBackend === "fastembed" || semanticBackend === "";
633
+ const ortDir = typeof this.configOverrides._ort_dylib_dir === "string" && useFastembedBackend ? this.configOverrides._ort_dylib_dir : null;
634
+ const ortLibraryPath = ortDir == null ? null : join(ortDir, process.platform === "win32" ? "onnxruntime.dll" : process.platform === "darwin" ? "libonnxruntime.dylib" : "libonnxruntime.so");
635
+ const envPath = process.platform === "win32" && ortDir ? `${ortDir};${process.env.PATH ?? ""}` : process.env.PATH;
636
+ const env = {
637
+ ...process.env,
638
+ ...envPath ? { PATH: envPath } : {}
639
+ };
640
+ this.logVia(`bridge.spawnProcess: useFastembedBackend=${useFastembedBackend}, ` + `parentORT=${process.env.ORT_DYLIB_PATH ?? "(unset)"}, ` + `ortLibraryPath=${ortLibraryPath ?? "(none)"}`);
641
+ if (useFastembedBackend) {
642
+ env.FASTEMBED_CACHE_DIR = process.env.FASTEMBED_CACHE_DIR || (typeof this.configOverrides.storage_dir === "string" ? join(this.configOverrides.storage_dir, "semantic", "models") : join(homedir() || "", ".cache", "fastembed"));
643
+ if (process.env.ORT_DYLIB_PATH) {
644
+ this.logVia(`ORT_DYLIB_PATH inherited from parent env: ${process.env.ORT_DYLIB_PATH}`);
645
+ } else if (ortLibraryPath) {
646
+ env.ORT_DYLIB_PATH = ortLibraryPath;
647
+ this.logVia(`ORT_DYLIB_PATH set from managed ONNX Runtime: ${ortLibraryPath}`);
648
+ }
649
+ }
650
+ if (this.childEnv) {
651
+ for (const [key, value] of Object.entries(this.childEnv)) {
652
+ if (value === undefined) {
653
+ delete env[key];
654
+ } else {
655
+ env[key] = value;
656
+ }
657
+ }
658
+ }
659
+ const child = spawn(this.binaryPath, [], {
660
+ cwd: this.cwd,
661
+ stdio: ["pipe", "pipe", "pipe"],
662
+ env
663
+ });
664
+ const currentChild = child;
665
+ const stdoutDecoder = new StringDecoder("utf8");
666
+ child.stdout?.on("data", (chunk) => {
667
+ this.onStdoutData(stdoutDecoder.write(chunk));
668
+ });
669
+ child.stdout?.on("end", () => {
670
+ const remaining = stdoutDecoder.end();
671
+ if (remaining)
672
+ this.onStdoutData(remaining);
673
+ });
674
+ const stderrDecoder = new StringDecoder("utf8");
675
+ child.stderr?.on("data", (chunk) => {
676
+ this.onStderrData(stderrDecoder.write(chunk));
677
+ });
678
+ child.stderr?.on("end", () => {
679
+ const remaining = stderrDecoder.end();
680
+ if (remaining)
681
+ this.onStderrData(remaining);
682
+ this.flushStderrBuffer();
683
+ });
684
+ child.on("error", (err) => {
685
+ if (this.process !== currentChild)
686
+ return;
687
+ this.errorVia(`Process error: ${err.message}${this.formatStderrTail()}`);
688
+ this.handleCrash();
689
+ });
690
+ child.on("exit", (code, signal) => {
691
+ if (this.process !== currentChild)
692
+ return;
693
+ if (this._shuttingDown)
694
+ return;
695
+ this.logVia(`Process exited: code=${code}, signal=${signal}`);
696
+ if (signal === "SIGTERM" || signal === "SIGKILL" || signal === "SIGHUP" || signal === "SIGINT") {
697
+ this.process = null;
698
+ this.configured = false;
699
+ this.clearRestartResetTimer();
700
+ this.rejectAllPending(new Error(`${this.errorPrefix} Binary killed by ${signal}`));
701
+ return;
702
+ }
703
+ this.handleCrash();
704
+ });
705
+ this.process = child;
706
+ this.stdoutBuffer = "";
707
+ this.stderrBuffer = "";
708
+ this.lastChildActivityAt = 0;
709
+ this.consecutiveRequestTimeouts = 0;
710
+ this.stderrTail = [];
711
+ }
712
+ pushStderrLine(line) {
713
+ this.stderrTail.push(line);
714
+ if (this.stderrTail.length > BinaryBridge.STDERR_TAIL_MAX) {
715
+ this.stderrTail.shift();
716
+ }
717
+ }
718
+ onStderrData(data) {
719
+ this.stderrBuffer += data;
720
+ let newlineIdx;
721
+ while ((newlineIdx = this.stderrBuffer.indexOf(`
722
+ `)) !== -1) {
723
+ const line = this.stderrBuffer.slice(0, newlineIdx).replace(/\r$/, "");
724
+ this.stderrBuffer = this.stderrBuffer.slice(newlineIdx + 1);
725
+ if (!line)
726
+ continue;
727
+ const tagged = tagStderrLine(line);
728
+ this.logVia(tagged);
729
+ this.pushStderrLine(tagged);
730
+ }
731
+ }
732
+ flushStderrBuffer() {
733
+ const line = this.stderrBuffer.replace(/\r$/, "");
734
+ this.stderrBuffer = "";
735
+ if (!line)
736
+ return;
737
+ const tagged = tagStderrLine(line);
738
+ this.logVia(tagged);
739
+ this.pushStderrLine(tagged);
740
+ }
741
+ formatStderrTail() {
742
+ if (this.stderrTail.length === 0)
743
+ return "";
744
+ const tail = this.stderrTail.join(`
745
+ `);
746
+ return `
747
+ --- last ${this.stderrTail.length} stderr lines ---
748
+ ${tail}`;
749
+ }
750
+ onStdoutData(data) {
751
+ this.stdoutBuffer += data;
752
+ if (this.stdoutBuffer.length > MAX_STDOUT_BUFFER) {
753
+ this.handleCrash(new Error(`aft bridge stdout buffer exceeded ${MAX_STDOUT_BUFFER} bytes — killing bridge`));
754
+ return;
755
+ }
756
+ let newlineIdx;
757
+ while ((newlineIdx = this.stdoutBuffer.indexOf(`
758
+ `)) !== -1) {
759
+ const line = this.stdoutBuffer.slice(0, newlineIdx).trim();
760
+ this.stdoutBuffer = this.stdoutBuffer.slice(newlineIdx + 1);
761
+ if (!line)
762
+ continue;
763
+ try {
764
+ const response = JSON.parse(line);
765
+ this.lastChildActivityAt = Date.now();
766
+ if (response.type === "progress") {
767
+ const requestId = response.request_id;
768
+ const entry = requestId ? this.pending.get(requestId) : undefined;
769
+ const kind = response.kind === "stderr" ? "stderr" : "stdout";
770
+ const text = typeof response.chunk === "string" ? response.chunk : "";
771
+ entry?.onProgress?.({ kind, text });
772
+ continue;
773
+ }
774
+ if (response.type === "permission_ask") {
775
+ const requestId = response.request_id;
776
+ const entry = requestId ? this.pending.get(requestId) : undefined;
777
+ if (requestId && entry) {
778
+ this.pending.delete(requestId);
779
+ clearTimeout(entry.timer);
780
+ entry.resolve({
781
+ success: false,
782
+ code: "permission_required",
783
+ message: "bash command requires permission",
784
+ asks: response.asks
785
+ });
786
+ }
787
+ continue;
788
+ }
789
+ if (response.type === "bash_completed") {
790
+ this.onBashCompletion?.(response, this);
791
+ continue;
792
+ }
793
+ if (response.type === "bash_long_running") {
794
+ this.onBashLongRunning?.(response, this);
795
+ continue;
796
+ }
797
+ if (response.type === "bash_pattern_match") {
798
+ this.onBashPatternMatch?.(response, this);
799
+ continue;
800
+ }
801
+ if (response.type === "configure_warnings") {
802
+ this.handleConfigureWarningsFrame(response).catch((err) => {
803
+ this.warnVia(`configure warning delivery failed: ${err instanceof Error ? err.message : String(err)}`);
804
+ });
805
+ continue;
806
+ }
807
+ if (response.type === "status_changed") {
808
+ this.handleStatusChangedFrame(response);
809
+ continue;
810
+ }
811
+ const id = response.id;
812
+ if (id && this.pending.has(id)) {
813
+ const entry = this.pending.get(id);
814
+ if (!entry)
815
+ continue;
816
+ this.pending.delete(id);
817
+ clearTimeout(entry.timer);
818
+ this.consecutiveRequestTimeouts = 0;
819
+ this.scheduleRestartCountReset();
820
+ this.captureStatusBar(response);
821
+ entry.resolve(response);
822
+ } else if (typeof response.type === "string") {
823
+ this.logVia(`Ignoring unknown stdout push frame type: ${response.type}`);
824
+ }
825
+ } catch (_err) {
826
+ this.warnVia(`Failed to parse stdout line: ${line}`);
827
+ }
828
+ }
829
+ }
830
+ captureStatusBar(response) {
831
+ const parsed = parseStatusBarCounts(response.status_bar);
832
+ if (parsed)
833
+ this.lastStatusBar = parsed;
834
+ }
835
+ getStatusBar() {
836
+ return this.lastStatusBar;
837
+ }
838
+ handleTimeout(triggeringSessionId) {
839
+ this.consecutiveRequestTimeouts = 0;
840
+ this.rejectAllPending(new Error(`${this.errorPrefix} bridge killed during sibling timeout — request aborted`));
841
+ if (this.process) {
842
+ this.process.kill("SIGKILL");
843
+ this.process = null;
844
+ }
845
+ this.clearRestartResetTimer();
846
+ this.configured = false;
847
+ const tail = this.formatStderrTail();
848
+ this.stderrTail = [];
849
+ const killedMsg = tail ? `Bridge killed after timeout.${tail}` : `Bridge killed after timeout (see ${this.getLogFilePathVia()})`;
850
+ if (tail) {
851
+ if (triggeringSessionId) {
852
+ this.sessionErrorVia(triggeringSessionId, killedMsg);
853
+ } else {
854
+ this.errorVia(killedMsg);
855
+ }
856
+ } else if (triggeringSessionId) {
857
+ this.sessionWarnVia(triggeringSessionId, killedMsg);
858
+ } else {
859
+ this.warnVia(killedMsg);
860
+ }
861
+ }
862
+ handleCrash(cause) {
863
+ const proc = this.process;
864
+ this.process = null;
865
+ if (proc && proc.exitCode === null && !proc.killed) {
866
+ proc.kill("SIGKILL");
867
+ }
868
+ this.clearRestartResetTimer();
869
+ this.configured = false;
870
+ const tail = this.formatStderrTail();
871
+ if (tail) {
872
+ this.errorVia(`Binary crashed (restarts: ${this._restartCount})${cause ? `: ${cause.message}` : ""}.${tail}`);
873
+ }
874
+ this.rejectAllPending(new Error(`${this.errorPrefix} Binary crashed (restarts: ${this._restartCount})${cause ? `: ${cause.message}` : ""} (see ${this.getLogFilePathVia()})`));
875
+ if (this._restartCount < this.maxRestarts) {
876
+ const delay = 100 * 2 ** this._restartCount;
877
+ this._restartCount++;
878
+ this.logVia(`Auto-restart #${this._restartCount} in ${delay}ms`);
879
+ setTimeout(() => {
880
+ if (!this._shuttingDown && !this.isAlive()) {
881
+ try {
882
+ this.spawnProcess();
883
+ } catch (err) {
884
+ this.errorVia(`Failed to restart: ${err.message}`);
885
+ }
886
+ }
887
+ }, delay);
888
+ this.scheduleRestartCountReset();
889
+ } else {
890
+ this.errorVia(`Max restarts (${this.maxRestarts}) reached, giving up. Logs: ${this.getLogFilePathVia()}${tail}`);
891
+ this.scheduleRestartCountReset();
892
+ }
893
+ }
894
+ rejectAllPending(error2) {
895
+ for (const [_id, entry] of this.pending) {
896
+ clearTimeout(entry.timer);
897
+ entry.reject(error2);
898
+ }
899
+ this.pending.clear();
900
+ }
901
+ scheduleRestartCountReset() {
902
+ this.clearRestartResetTimer();
903
+ this.restartResetTimer = setTimeout(() => {
904
+ this._restartCount = 0;
905
+ this.restartResetTimer = null;
906
+ }, BinaryBridge.RESTART_RESET_MS);
907
+ }
908
+ clearRestartResetTimer() {
909
+ if (this.restartResetTimer) {
910
+ clearTimeout(this.restartResetTimer);
911
+ this.restartResetTimer = null;
912
+ }
913
+ }
914
+ };
915
+ });
916
+
917
+ // ../aft-bridge/dist/platform.js
918
+ var init_platform = () => {};
919
+
920
+ // ../aft-bridge/dist/downloader.js
921
+ var MAX_DOWNLOAD_BYTES, DOWNLOAD_LOCK_STALE_MS;
922
+ var init_downloader = __esm(() => {
923
+ init_active_logger();
924
+ init_platform();
925
+ MAX_DOWNLOAD_BYTES = 200 * 1024 * 1024;
926
+ DOWNLOAD_LOCK_STALE_MS = 10 * 60000;
927
+ });
928
+ // ../aft-bridge/dist/paths.js
929
+ var init_paths = () => {};
930
+
931
+ // ../aft-bridge/dist/resolver.js
932
+ import { chmodSync, closeSync, copyFileSync, existsSync, mkdirSync, openSync, readSync, renameSync, unlinkSync } from "node:fs";
933
+ function isNativeExecutable(binaryPath) {
934
+ let fd = null;
935
+ try {
936
+ fd = openSync(binaryPath, "r");
937
+ const buf = Buffer.alloc(4);
938
+ const read = readSync(fd, buf, 0, 4, 0);
939
+ if (read < 2)
940
+ return false;
941
+ const b0 = buf[0];
942
+ const b1 = buf[1];
943
+ if (b0 === 35 && b1 === 33)
944
+ return false;
945
+ const m32 = buf.readUInt32BE(0);
946
+ const machO = new Set([4277009102, 4277009103, 3472551422, 3489328638, 3405691582]);
947
+ if (read >= 4 && machO.has(m32))
948
+ return true;
949
+ if (read >= 4 && m32 === 2135247942)
950
+ return true;
951
+ if (b0 === 77 && b1 === 90)
952
+ return true;
953
+ return false;
954
+ } catch {
955
+ return false;
956
+ } finally {
957
+ if (fd !== null) {
958
+ try {
959
+ closeSync(fd);
960
+ } catch {}
961
+ }
962
+ }
963
+ }
964
+ var init_resolver = __esm(() => {
965
+ init_active_logger();
966
+ init_downloader();
967
+ init_platform();
968
+ });
969
+
970
+ // ../aft-bridge/dist/migration.js
971
+ var DEFAULT_TIMEOUT_MS;
972
+ var init_migration = __esm(() => {
973
+ init_paths();
974
+ init_resolver();
975
+ DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
976
+ });
977
+
978
+ // ../aft-bridge/dist/npm-resolver.js
979
+ import { readdirSync, statSync } from "node:fs";
980
+ import { homedir as homedir2 } from "node:os";
981
+ import { delimiter, dirname, isAbsolute, join as join2 } from "node:path";
982
+ function defaultDeps() {
983
+ return {
984
+ platform: process.platform,
985
+ env: process.env,
986
+ home: homedir2(),
987
+ execPath: process.execPath
988
+ };
989
+ }
990
+ function npmBinaryName(platform) {
991
+ return platform === "win32" ? "npm.cmd" : "npm";
992
+ }
993
+ function isFile(p) {
994
+ try {
995
+ return statSync(p).isFile();
996
+ } catch {
997
+ return false;
998
+ }
999
+ }
1000
+ function npmFromPath(deps) {
1001
+ const name = npmBinaryName(deps.platform);
1002
+ const raw = deps.env.PATH ?? deps.env.Path ?? "";
1003
+ for (const entry of raw.split(delimiter)) {
1004
+ const dir = entry.trim().replace(/^"|"$/g, "");
1005
+ if (!dir || !isAbsolute(dir))
1006
+ continue;
1007
+ if (isFile(join2(dir, name)))
1008
+ return dir;
1009
+ }
1010
+ return null;
1011
+ }
1012
+ function npmAdjacentToNode(deps) {
1013
+ const dir = dirname(deps.execPath);
1014
+ return isFile(join2(dir, npmBinaryName(deps.platform))) ? dir : null;
1015
+ }
1016
+ function highestVersionedNodeBin(installsDir, name) {
1017
+ let entries;
1018
+ try {
1019
+ entries = readdirSync(installsDir);
1020
+ } catch {
1021
+ return null;
1022
+ }
1023
+ const candidates = entries.filter((v) => isFile(join2(installsDir, v, "bin", name))).sort((a, b) => compareVersionsDesc(a, b));
1024
+ return candidates.length > 0 ? join2(installsDir, candidates[0], "bin") : null;
1025
+ }
1026
+ function compareVersionsDesc(a, b) {
1027
+ const pa = a.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10));
1028
+ const pb = b.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10));
1029
+ for (let i = 0;i < Math.max(pa.length, pb.length); i++) {
1030
+ const na = Number.isFinite(pa[i]) ? pa[i] : -1;
1031
+ const nb = Number.isFinite(pb[i]) ? pb[i] : -1;
1032
+ if (na !== nb)
1033
+ return nb - na;
1034
+ }
1035
+ return b.localeCompare(a);
1036
+ }
1037
+ function wellKnownNpmDirs(deps) {
1038
+ const { platform, env, home } = deps;
1039
+ const name = npmBinaryName(platform);
1040
+ const dirs = [];
1041
+ const push = (dir) => {
1042
+ if (dir && !dirs.includes(dir))
1043
+ dirs.push(dir);
1044
+ };
1045
+ if (platform === "win32") {
1046
+ const programFiles = env.ProgramFiles || "C:\\Program Files";
1047
+ const appData = env.APPDATA;
1048
+ const localAppData = env.LOCALAPPDATA;
1049
+ push(join2(programFiles, "nodejs"));
1050
+ if (appData)
1051
+ push(join2(appData, "npm"));
1052
+ if (localAppData)
1053
+ push(join2(localAppData, "Volta", "bin"));
1054
+ if (env.NVM_SYMLINK)
1055
+ push(env.NVM_SYMLINK);
1056
+ } else {
1057
+ if (env.NVM_BIN)
1058
+ push(env.NVM_BIN);
1059
+ push(highestVersionedNodeBin(join2(home, ".nvm", "versions", "node"), name));
1060
+ push(highestVersionedNodeBin(join2(home, ".local", "share", "mise", "installs", "node"), name));
1061
+ push(highestVersionedNodeBin(join2(home, ".asdf", "installs", "nodejs"), name));
1062
+ push(join2(home, ".volta", "bin"));
1063
+ push(join2(home, ".asdf", "shims"));
1064
+ const systemDirs = deps.systemNpmDirs ?? (platform === "darwin" ? ["/opt/homebrew/bin", "/usr/local/bin"] : ["/usr/local/bin", "/usr/bin", join2(home, ".local", "bin")]);
1065
+ for (const dir of systemDirs)
1066
+ push(dir);
1067
+ }
1068
+ return dirs;
1069
+ }
1070
+ function resolveNpm(deps = defaultDeps()) {
1071
+ const name = npmBinaryName(deps.platform);
1072
+ const onPath = npmFromPath(deps);
1073
+ if (onPath)
1074
+ return { command: join2(onPath, name), binDir: onPath };
1075
+ const adjacent = npmAdjacentToNode(deps);
1076
+ if (adjacent)
1077
+ return { command: join2(adjacent, name), binDir: adjacent };
1078
+ for (const dir of wellKnownNpmDirs(deps)) {
1079
+ const candidate = join2(dir, name);
1080
+ if (isFile(candidate))
1081
+ return { command: candidate, binDir: dir };
1082
+ }
1083
+ return null;
1084
+ }
1085
+ function npmSpawnEnv(resolved, baseEnv = process.env) {
1086
+ if (!resolved.binDir)
1087
+ return { ...baseEnv };
1088
+ const existing = baseEnv.PATH ?? baseEnv.Path ?? "";
1089
+ const next = existing ? `${resolved.binDir}${delimiter}${existing}` : resolved.binDir;
1090
+ return { ...baseEnv, PATH: next };
1091
+ }
1092
+ var init_npm_resolver = () => {};
1093
+
1094
+ // ../aft-bridge/dist/onnx-runtime.js
1095
+ var ORT_VERSION = "1.24.4", MAX_DOWNLOAD_BYTES2, MAX_EXTRACT_BYTES, STALE_LOCK_MS, ORT_PLATFORM_MAP;
1096
+ var init_onnx_runtime = __esm(() => {
1097
+ init_active_logger();
1098
+ init_platform();
1099
+ MAX_DOWNLOAD_BYTES2 = 256 * 1024 * 1024;
1100
+ MAX_EXTRACT_BYTES = 1 * 1024 * 1024 * 1024;
1101
+ STALE_LOCK_MS = 5 * 60 * 1000;
1102
+ ORT_PLATFORM_MAP = {
1103
+ darwin: {
1104
+ arm64: {
1105
+ assetName: `onnxruntime-osx-arm64-${ORT_VERSION}`,
1106
+ libName: "libonnxruntime.dylib",
1107
+ archiveType: "tgz"
1108
+ }
1109
+ },
1110
+ linux: {
1111
+ x64: {
1112
+ assetName: `onnxruntime-linux-x64-${ORT_VERSION}`,
1113
+ libName: "libonnxruntime.so",
1114
+ archiveType: "tgz"
1115
+ },
1116
+ arm64: {
1117
+ assetName: `onnxruntime-linux-aarch64-${ORT_VERSION}`,
1118
+ libName: "libonnxruntime.so",
1119
+ archiveType: "tgz"
1120
+ }
1121
+ },
1122
+ win32: {
1123
+ x64: {
1124
+ assetName: `onnxruntime-win-x64-${ORT_VERSION}`,
1125
+ libName: "onnxruntime.dll",
1126
+ archiveType: "zip"
1127
+ },
1128
+ arm64: {
1129
+ assetName: `onnxruntime-win-arm64-${ORT_VERSION}`,
1130
+ libName: "onnxruntime.dll",
1131
+ archiveType: "zip"
1132
+ }
1133
+ }
1134
+ };
1135
+ });
1136
+
1137
+ // ../aft-bridge/dist/pool.js
1138
+ import { realpathSync } from "node:fs";
1139
+
1140
+ class BridgePool {
1141
+ bridges = new Map;
1142
+ staleBridges = new Set;
1143
+ binaryPath;
1144
+ maxPoolSize;
1145
+ idleTimeoutMs;
1146
+ bridgeOptions;
1147
+ configOverrides;
1148
+ projectConfigLoader;
1149
+ logger;
1150
+ cleanupTimer = null;
1151
+ constructor(binaryPath, options = {}, configOverrides = {}) {
1152
+ this.binaryPath = binaryPath;
1153
+ this.maxPoolSize = options.maxPoolSize ?? DEFAULT_MAX_POOL_SIZE;
1154
+ this.idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
1155
+ this.logger = options.logger;
1156
+ this.projectConfigLoader = options.projectConfigLoader;
1157
+ this.bridgeOptions = {
1158
+ timeoutMs: options.timeoutMs,
1159
+ maxRestarts: options.maxRestarts,
1160
+ minVersion: options.minVersion,
1161
+ onVersionMismatch: options.onVersionMismatch,
1162
+ onConfigureWarnings: options.onConfigureWarnings,
1163
+ onBashCompletion: options.onBashCompletion,
1164
+ onBashLongRunning: options.onBashLongRunning,
1165
+ onBashPatternMatch: options.onBashPatternMatch,
1166
+ errorPrefix: options.errorPrefix,
1167
+ logger: options.logger,
1168
+ childEnv: options.childEnv
1169
+ };
1170
+ this.configOverrides = configOverrides;
1171
+ if (Number.isFinite(this.idleTimeoutMs)) {
1172
+ this.cleanupTimer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
1173
+ this.cleanupTimer.unref();
1174
+ }
1175
+ }
1176
+ getActiveBridgeForRoot(projectRoot) {
1177
+ const key = normalizeKey(projectRoot);
1178
+ const entry = this.bridges.get(key);
1179
+ if (!entry?.bridge.isAlive())
1180
+ return null;
1181
+ entry.lastUsed = Date.now();
1182
+ return entry.bridge;
1183
+ }
1184
+ getBridge(projectRoot) {
1185
+ const key = normalizeKey(projectRoot);
1186
+ const existing = this.bridges.get(key);
1187
+ if (existing) {
1188
+ existing.lastUsed = Date.now();
1189
+ return existing.bridge;
1190
+ }
1191
+ if (this.bridges.size >= this.maxPoolSize) {
1192
+ this.evictLRU();
1193
+ }
1194
+ let projectOverrides = {};
1195
+ if (this.projectConfigLoader) {
1196
+ try {
1197
+ projectOverrides = this.projectConfigLoader(key) ?? {};
1198
+ } catch (err) {
1199
+ const message = err instanceof Error ? err.message : String(err);
1200
+ this.error(`projectConfigLoader failed; using global overrides only: ${message}`);
1201
+ }
1202
+ }
1203
+ const mergedOverrides = { ...this.configOverrides, ...projectOverrides };
1204
+ const bridge = new BinaryBridge(this.binaryPath, key, this.bridgeOptions, mergedOverrides);
1205
+ this.bridges.set(key, { bridge, lastUsed: Date.now() });
1206
+ return bridge;
1207
+ }
1208
+ cleanup() {
1209
+ const now = Date.now();
1210
+ for (const [dir, entry] of this.bridges) {
1211
+ if (entry.bridge.hasPendingRequests())
1212
+ continue;
1213
+ if (now - entry.lastUsed > this.idleTimeoutMs) {
1214
+ entry.bridge.shutdown().catch((err) => this.error("cleanup shutdown failed:", err));
1215
+ this.bridges.delete(dir);
1216
+ }
1217
+ }
1218
+ for (const bridge of this.staleBridges) {
1219
+ if (bridge.hasPendingRequests())
1220
+ continue;
1221
+ bridge.shutdown().catch((err) => this.error("stale cleanup shutdown failed:", err));
1222
+ this.staleBridges.delete(bridge);
1223
+ }
1224
+ }
1225
+ evictLRU() {
1226
+ let oldestDir = null;
1227
+ let oldestTime = Infinity;
1228
+ for (const [dir, entry] of this.bridges) {
1229
+ if (entry.bridge.hasPendingRequests())
1230
+ continue;
1231
+ if (entry.lastUsed < oldestTime) {
1232
+ oldestTime = entry.lastUsed;
1233
+ oldestDir = dir;
1234
+ }
1235
+ }
1236
+ if (oldestDir) {
1237
+ const entry = this.bridges.get(oldestDir);
1238
+ entry?.bridge.shutdown().catch((err) => this.error("eviction shutdown failed:", err));
1239
+ this.bridges.delete(oldestDir);
1240
+ }
1241
+ }
1242
+ async shutdown() {
1243
+ if (this.cleanupTimer) {
1244
+ clearInterval(this.cleanupTimer);
1245
+ this.cleanupTimer = null;
1246
+ }
1247
+ const shutdowns = [
1248
+ ...Array.from(this.bridges.values(), (e) => e.bridge.shutdown()),
1249
+ ...Array.from(this.staleBridges.values(), (bridge) => bridge.shutdown())
1250
+ ];
1251
+ this.bridges.clear();
1252
+ this.staleBridges.clear();
1253
+ await Promise.allSettled(shutdowns);
1254
+ }
1255
+ async replaceBinary(newPath) {
1256
+ this.binaryPath = newPath;
1257
+ for (const entry of this.bridges.values()) {
1258
+ this.staleBridges.add(entry.bridge);
1259
+ }
1260
+ this.bridges.clear();
1261
+ this.log(`Binary path updated to ${newPath}. Active bridges marked stale — next calls will use the new binary.`);
1262
+ return newPath;
1263
+ }
1264
+ log(message, meta) {
1265
+ const logger = this.logger ?? getActiveLogger();
1266
+ if (logger) {
1267
+ try {
1268
+ logger.log(message, meta);
1269
+ } catch (err) {
1270
+ console.error(`[aft-bridge] ERROR: pool logger log threw: ${err instanceof Error ? err.message : String(err)}`);
1271
+ console.error(`[aft-bridge] ${message}`);
1272
+ }
1273
+ } else
1274
+ log(message, meta);
1275
+ }
1276
+ error(message, meta) {
1277
+ const logger = this.logger ?? getActiveLogger();
1278
+ if (logger) {
1279
+ try {
1280
+ logger.error(message, meta);
1281
+ } catch (err) {
1282
+ console.error(`[aft-bridge] ERROR: pool logger error threw: ${err instanceof Error ? err.message : String(err)}`);
1283
+ console.error(`[aft-bridge] ERROR: ${message}`);
1284
+ }
1285
+ } else
1286
+ error(message, meta);
1287
+ }
1288
+ setConfigureOverride(key, value) {
1289
+ if (value === undefined) {
1290
+ delete this.configOverrides[key];
1291
+ } else {
1292
+ this.configOverrides[key] = value;
1293
+ }
1294
+ }
1295
+ get size() {
1296
+ return this.bridges.size;
1297
+ }
1298
+ _testGetConfigOverrides() {
1299
+ return { ...this.configOverrides };
1300
+ }
1301
+ _testGetBridgeOptions() {
1302
+ return { ...this.bridgeOptions };
1303
+ }
1304
+ }
1305
+ function normalizeKey(projectRoot) {
1306
+ const stripped = projectRoot.replace(/[/\\]+$/, "");
1307
+ try {
1308
+ return realpathSync(stripped);
1309
+ } catch {
1310
+ return stripped;
1311
+ }
1312
+ }
1313
+ var DEFAULT_IDLE_TIMEOUT_MS = Infinity, DEFAULT_MAX_POOL_SIZE = 8, CLEANUP_INTERVAL_MS;
1314
+ var init_pool = __esm(() => {
1315
+ init_active_logger();
1316
+ init_bridge();
1317
+ CLEANUP_INTERVAL_MS = 60 * 1000;
1318
+ });
1319
+ // ../aft-bridge/dist/index.js
1320
+ var init_dist = __esm(() => {
1321
+ init_active_logger();
1322
+ init_bridge();
1323
+ init_downloader();
1324
+ init_migration();
1325
+ init_npm_resolver();
1326
+ init_onnx_runtime();
1327
+ init_paths();
1328
+ init_platform();
1329
+ init_pool();
1330
+ init_resolver();
1331
+ });
1332
+
1333
+ // src/lib/paths.ts
1334
+ import { homedir as homedir3, tmpdir } from "node:os";
1335
+ import { join as join3 } from "node:path";
52
1336
  function getAftBinaryCacheDir() {
53
1337
  if (process.env.AFT_CACHE_DIR) {
54
- return join(process.env.AFT_CACHE_DIR, "bin");
1338
+ return join3(process.env.AFT_CACHE_DIR, "bin");
55
1339
  }
56
1340
  if (process.platform === "win32") {
57
1341
  const localAppData = process.env.LOCALAPPDATA || process.env.APPDATA;
58
- const base2 = localAppData || join(homedir(), "AppData", "Local");
59
- return join(base2, "aft", "bin");
1342
+ const base2 = localAppData || join3(homedir3(), "AppData", "Local");
1343
+ return join3(base2, "aft", "bin");
60
1344
  }
61
- const base = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
62
- return join(base, "aft", "bin");
1345
+ const base = process.env.XDG_CACHE_HOME || join3(homedir3(), ".cache");
1346
+ return join3(base, "aft", "bin");
63
1347
  }
64
1348
  function getAftBinaryName() {
65
1349
  return process.platform === "win32" ? "aft.exe" : "aft";
66
1350
  }
67
1351
  function getAftLspPackagesDir() {
68
1352
  if (process.env.AFT_CACHE_DIR) {
69
- return join(process.env.AFT_CACHE_DIR, "lsp-packages");
1353
+ return join3(process.env.AFT_CACHE_DIR, "lsp-packages");
70
1354
  }
71
1355
  if (process.platform === "win32") {
72
1356
  const localAppData = process.env.LOCALAPPDATA || process.env.APPDATA;
73
- const base2 = localAppData || join(homedir(), "AppData", "Local");
74
- return join(base2, "aft", "lsp-packages");
1357
+ const base2 = localAppData || join3(homedir3(), "AppData", "Local");
1358
+ return join3(base2, "aft", "lsp-packages");
75
1359
  }
76
- const base = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
77
- return join(base, "aft", "lsp-packages");
1360
+ const base = process.env.XDG_CACHE_HOME || join3(homedir3(), ".cache");
1361
+ return join3(base, "aft", "lsp-packages");
78
1362
  }
79
1363
  function getAftLspBinariesDir() {
80
1364
  if (process.env.AFT_CACHE_DIR) {
81
- return join(process.env.AFT_CACHE_DIR, "lsp-binaries");
1365
+ return join3(process.env.AFT_CACHE_DIR, "lsp-binaries");
82
1366
  }
83
1367
  if (process.platform === "win32") {
84
1368
  const localAppData = process.env.LOCALAPPDATA || process.env.APPDATA;
85
- const base2 = localAppData || join(homedir(), "AppData", "Local");
86
- return join(base2, "aft", "lsp-binaries");
1369
+ const base2 = localAppData || join3(homedir3(), "AppData", "Local");
1370
+ return join3(base2, "aft", "lsp-binaries");
87
1371
  }
88
- const base = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
89
- return join(base, "aft", "lsp-binaries");
1372
+ const base = process.env.XDG_CACHE_HOME || join3(homedir3(), ".cache");
1373
+ return join3(base, "aft", "lsp-binaries");
90
1374
  }
91
1375
  function homeDir() {
92
1376
  if (process.platform === "win32")
93
- return process.env.USERPROFILE || process.env.HOME || homedir();
94
- return process.env.HOME || homedir();
1377
+ return process.env.USERPROFILE || process.env.HOME || homedir3();
1378
+ return process.env.HOME || homedir3();
95
1379
  }
96
1380
  function dataHome() {
97
1381
  if (process.env.XDG_DATA_HOME)
98
1382
  return process.env.XDG_DATA_HOME;
99
1383
  if (process.platform === "win32") {
100
- return process.env.LOCALAPPDATA || process.env.APPDATA || join(homeDir(), "AppData", "Local");
1384
+ return process.env.LOCALAPPDATA || process.env.APPDATA || join3(homeDir(), "AppData", "Local");
101
1385
  }
102
- return join(homeDir(), ".local", "share");
1386
+ return join3(homeDir(), ".local", "share");
103
1387
  }
104
1388
  function getCortexKitStorageRoot() {
105
- return join(dataHome(), "cortexkit", "aft");
1389
+ return join3(dataHome(), "cortexkit", "aft");
106
1390
  }
107
1391
  function getTmpLogPath(filename) {
108
- return join(tmpdir(), filename);
1392
+ return join3(tmpdir(), filename);
109
1393
  }
110
- var init_paths = () => {};
1394
+ var init_paths2 = () => {};
111
1395
 
112
1396
  // src/lib/binary-probe.ts
113
1397
  import { execSync, spawnSync } from "node:child_process";
114
- import { existsSync } from "node:fs";
1398
+ import { existsSync as existsSync2 } from "node:fs";
115
1399
  import { createRequire } from "node:module";
116
- import { homedir as homedir2 } from "node:os";
117
- import { join as join2 } from "node:path";
1400
+ import { homedir as homedir4 } from "node:os";
1401
+ import { join as join4 } from "node:path";
118
1402
  async function loadPluginVersion() {
119
1403
  try {
120
1404
  const bridgePackageName = "@cortexkit/aft-bridge";
@@ -167,7 +1451,7 @@ function probeAftBinary(preferredVersion) {
167
1451
  const candidates = [];
168
1452
  for (const candidate of aftBinaryCandidates(preferredVersion)) {
169
1453
  try {
170
- if (!existsSync(candidate))
1454
+ if (!existsSync2(candidate))
171
1455
  continue;
172
1456
  const result = spawnSync(candidate, ["--version"], {
173
1457
  stdio: ["ignore", "pipe", "pipe"],
@@ -198,12 +1482,12 @@ ${result.stderr ?? ""}`.trim();
198
1482
  }
199
1483
  candidates.push({ path: candidate, status: "matched", version, output });
200
1484
  return { version, path: candidate, expectedVersion, expectedMajorMinor, candidates };
201
- } catch (error) {
1485
+ } catch (error2) {
202
1486
  candidates.push({
203
1487
  path: candidate,
204
1488
  status: "error",
205
1489
  version: null,
206
- error: error instanceof Error ? error.message : String(error)
1490
+ error: error2 instanceof Error ? error2.message : String(error2)
207
1491
  });
208
1492
  }
209
1493
  }
@@ -218,14 +1502,14 @@ function pushCandidate(candidates, candidate) {
218
1502
  function firstExisting(candidates) {
219
1503
  for (const candidate of candidates) {
220
1504
  try {
221
- if (!existsSync(candidate))
1505
+ if (!existsSync2(candidate))
222
1506
  continue;
223
1507
  return candidate;
224
1508
  } catch {}
225
1509
  }
226
1510
  return null;
227
1511
  }
228
- function platformKey(platform = process.platform, arch = process.arch) {
1512
+ function platformKey2(platform = process.platform, arch = process.arch) {
229
1513
  const table = {
230
1514
  darwin: { arm64: "darwin-arm64", x64: "darwin-x64" },
231
1515
  linux: { arm64: "linux-arm64", x64: "linux-x64" },
@@ -237,9 +1521,9 @@ function aftBinaryCandidates(preferredVersion) {
237
1521
  const candidates = [];
238
1522
  if (preferredVersion) {
239
1523
  const tag = preferredVersion.startsWith("v") ? preferredVersion : `v${preferredVersion}`;
240
- pushCandidate(candidates, join2(getAftBinaryCacheDir(), tag, getAftBinaryName()));
1524
+ pushCandidate(candidates, join4(getAftBinaryCacheDir(), tag, getAftBinaryName()));
241
1525
  }
242
- const key = platformKey();
1526
+ const key = platformKey2();
243
1527
  if (key) {
244
1528
  try {
245
1529
  const require2 = createRequire(import.meta.url);
@@ -253,11 +1537,14 @@ function aftBinaryCandidates(preferredVersion) {
253
1537
  encoding: "utf-8",
254
1538
  env: process.env
255
1539
  }).trim();
256
- if (resolved) {
257
- pushCandidate(candidates, resolved.split(/\r?\n/)[0]);
1540
+ for (const line of resolved.split(/\r?\n/)) {
1541
+ const candidate = line.trim();
1542
+ if (candidate && isNativeExecutable(candidate)) {
1543
+ pushCandidate(candidates, candidate);
1544
+ }
258
1545
  }
259
1546
  } catch {}
260
- pushCandidate(candidates, join2(homedir2(), ".cargo", "bin", getAftBinaryName()));
1547
+ pushCandidate(candidates, join4(homedir4(), ".cargo", "bin", getAftBinaryName()));
261
1548
  return candidates;
262
1549
  }
263
1550
  function findAftBinary(preferredVersion) {
@@ -265,19 +1552,20 @@ function findAftBinary(preferredVersion) {
265
1552
  }
266
1553
  var PLUGIN_VERSION, VERSION_LINE;
267
1554
  var init_binary_probe = __esm(async () => {
268
- init_paths();
1555
+ init_dist();
1556
+ init_paths2();
269
1557
  PLUGIN_VERSION = await loadPluginVersion();
270
1558
  VERSION_LINE = /^(?:aft\s+)?v?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/i;
271
1559
  });
272
1560
 
273
1561
  // src/lib/fs-util.ts
274
- import { existsSync as existsSync2, readdirSync, statSync } from "node:fs";
275
- import { join as join3 } from "node:path";
1562
+ import { existsSync as existsSync3, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
1563
+ import { join as join5 } from "node:path";
276
1564
  function dirSize(path) {
277
- if (!existsSync2(path)) {
1565
+ if (!existsSync3(path)) {
278
1566
  return 0;
279
1567
  }
280
- const stat = statSync(path);
1568
+ const stat = statSync2(path);
281
1569
  if (stat.isFile()) {
282
1570
  return stat.size;
283
1571
  }
@@ -285,8 +1573,8 @@ function dirSize(path) {
285
1573
  return 0;
286
1574
  }
287
1575
  let total = 0;
288
- for (const entry of readdirSync(path)) {
289
- total += dirSize(join3(path, entry));
1576
+ for (const entry of readdirSync2(path)) {
1577
+ total += dirSize(join5(path, entry));
290
1578
  }
291
1579
  return total;
292
1580
  }
@@ -4840,45 +6128,45 @@ var require_esprima = __commonJS((exports, module) => {
4840
6128
  this.errors = [];
4841
6129
  this.tolerant = false;
4842
6130
  }
4843
- ErrorHandler2.prototype.recordError = function(error) {
4844
- this.errors.push(error);
6131
+ ErrorHandler2.prototype.recordError = function(error2) {
6132
+ this.errors.push(error2);
4845
6133
  };
4846
- ErrorHandler2.prototype.tolerate = function(error) {
6134
+ ErrorHandler2.prototype.tolerate = function(error2) {
4847
6135
  if (this.tolerant) {
4848
- this.recordError(error);
6136
+ this.recordError(error2);
4849
6137
  } else {
4850
- throw error;
6138
+ throw error2;
4851
6139
  }
4852
6140
  };
4853
6141
  ErrorHandler2.prototype.constructError = function(msg, column) {
4854
- var error = new Error(msg);
6142
+ var error2 = new Error(msg);
4855
6143
  try {
4856
- throw error;
6144
+ throw error2;
4857
6145
  } catch (base) {
4858
6146
  if (Object.create && Object.defineProperty) {
4859
- error = Object.create(base);
4860
- Object.defineProperty(error, "column", { value: column });
6147
+ error2 = Object.create(base);
6148
+ Object.defineProperty(error2, "column", { value: column });
4861
6149
  }
4862
6150
  }
4863
- return error;
6151
+ return error2;
4864
6152
  };
4865
6153
  ErrorHandler2.prototype.createError = function(index, line, col, description) {
4866
6154
  var msg = "Line " + line + ": " + description;
4867
- var error = this.constructError(msg, col);
4868
- error.index = index;
4869
- error.lineNumber = line;
4870
- error.description = description;
4871
- return error;
6155
+ var error2 = this.constructError(msg, col);
6156
+ error2.index = index;
6157
+ error2.lineNumber = line;
6158
+ error2.description = description;
6159
+ return error2;
4872
6160
  };
4873
6161
  ErrorHandler2.prototype.throwError = function(index, line, col, description) {
4874
6162
  throw this.createError(index, line, col, description);
4875
6163
  };
4876
6164
  ErrorHandler2.prototype.tolerateError = function(index, line, col, description) {
4877
- var error = this.createError(index, line, col, description);
6165
+ var error2 = this.createError(index, line, col, description);
4878
6166
  if (this.tolerant) {
4879
- this.recordError(error);
6167
+ this.recordError(error2);
4880
6168
  } else {
4881
- throw error;
6169
+ throw error2;
4882
6170
  }
4883
6171
  };
4884
6172
  return ErrorHandler2;
@@ -7548,19 +8836,19 @@ var require_parse = __commonJS((exports, module) => {
7548
8836
  var symbolFor = (prefix) => Symbol.for(last_prop !== UNDEFINED ? prefix + COLON + last_prop : prefix);
7549
8837
  var transform = (k, { value, context = {} }) => reviver ? reviver(k, value, context) : value;
7550
8838
  var unexpected = () => {
7551
- const error = new SyntaxError(`Unexpected token '${current.value.slice(0, 1)}', "${current_code}" is not valid JSON`);
7552
- Object.assign(error, current.loc.start);
8839
+ const error2 = new SyntaxError(`Unexpected token '${current.value.slice(0, 1)}', "${current_code}" is not valid JSON`);
8840
+ Object.assign(error2, current.loc.start);
7553
8841
  free();
7554
- throw error;
8842
+ throw error2;
7555
8843
  };
7556
8844
  var unexpected_end = () => {
7557
- const error = new SyntaxError("Unexpected end of JSON input");
7558
- Object.assign(error, last ? last.loc.end : {
8845
+ const error2 = new SyntaxError("Unexpected end of JSON input");
8846
+ Object.assign(error2, last ? last.loc.end : {
7559
8847
  line: 1,
7560
8848
  column: 0
7561
8849
  });
7562
8850
  free();
7563
- throw error;
8851
+ throw error2;
7564
8852
  };
7565
8853
  var next = () => {
7566
8854
  const new_token = tokens[++index];
@@ -7894,9 +9182,9 @@ var require_stringify = __commonJS((exports, module) => {
7894
9182
  if (line_breaks_before === null) {
7895
9183
  line_breaks_before = inline ? 0 : 1;
7896
9184
  }
7897
- const delimiter = line_breaks_before > 0 ? repeat_line_breaks(line_breaks_before, deeper_gap) : inline ? SPACE : i === 0 ? EMPTY : LF + deeper_gap;
9185
+ const delimiter2 = line_breaks_before > 0 ? repeat_line_breaks(line_breaks_before, deeper_gap) : inline ? SPACE : i === 0 ? EMPTY : LF + deeper_gap;
7898
9186
  const is_line_comment = type === "LineComment";
7899
- str += delimiter + comment_stringify(value, is_line_comment);
9187
+ str += delimiter2 + comment_stringify(value, is_line_comment);
7900
9188
  last_comment = comment;
7901
9189
  });
7902
9190
  const default_line_breaks_after = display_block || last_comment.type === "LineComment" ? 1 : 0;
@@ -7909,10 +9197,10 @@ var require_stringify = __commonJS((exports, module) => {
7909
9197
  replacer = null;
7910
9198
  indent = EMPTY;
7911
9199
  };
7912
- var join4 = (one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(one, gap)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two, gap)), gap) : EMPTY;
9200
+ var join6 = (one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(one, gap)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two, gap)), gap) : EMPTY;
7913
9201
  var join_content = (inside, value, gap) => {
7914
9202
  const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
7915
- return join4(comment, inside, gap);
9203
+ return join6(comment, inside, gap);
7916
9204
  };
7917
9205
  var stringify_string = (holder, key, value) => {
7918
9206
  const raw = get_raw_string_literal(holder, key);
@@ -7934,13 +9222,13 @@ var require_stringify = __commonJS((exports, module) => {
7934
9222
  if (i !== 0) {
7935
9223
  inside += COMMA;
7936
9224
  }
7937
- const before = join4(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
9225
+ const before = join6(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
7938
9226
  inside += before || LF + deeper_gap;
7939
9227
  inside += stringify(i, value, deeper_gap) || STR_NULL;
7940
9228
  inside += process_comments(value, AFTER_VALUE(i), deeper_gap);
7941
9229
  after_comma = process_comments(value, AFTER(i), deeper_gap);
7942
9230
  }
7943
- inside += join4(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
9231
+ inside += join6(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7944
9232
  return BRACKET_OPEN + join_content(inside, value, gap) + BRACKET_CLOSE;
7945
9233
  };
7946
9234
  var object_stringify = (value, gap) => {
@@ -7961,13 +9249,13 @@ var require_stringify = __commonJS((exports, module) => {
7961
9249
  inside += COMMA;
7962
9250
  }
7963
9251
  first = false;
7964
- const before = join4(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
9252
+ const before = join6(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
7965
9253
  inside += before || LF + deeper_gap;
7966
9254
  inside += quote(key) + process_comments(value, AFTER_PROP(key), deeper_gap) + COLON + process_comments(value, AFTER_COLON(key), deeper_gap) + SPACE + sv + process_comments(value, AFTER_VALUE(key), deeper_gap);
7967
9255
  after_comma = process_comments(value, AFTER(key), deeper_gap);
7968
9256
  };
7969
9257
  keys.forEach(iteratee);
7970
- inside += join4(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
9258
+ inside += join6(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7971
9259
  return CURLY_BRACKET_OPEN + join_content(inside, value, gap) + CURLY_BRACKET_CLOSE;
7972
9260
  };
7973
9261
  function stringify(key, holder, gap) {
@@ -8060,42 +9348,42 @@ var require_src2 = __commonJS((exports, module) => {
8060
9348
  });
8061
9349
 
8062
9350
  // src/lib/jsonc.ts
8063
- import { existsSync as existsSync3, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8064
- import { dirname } from "node:path";
9351
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "node:fs";
9352
+ import { dirname as dirname2 } from "node:path";
8065
9353
  function detectJsoncFile(configDir, baseName) {
8066
9354
  const jsoncPath = `${configDir}/${baseName}.jsonc`;
8067
9355
  const jsonPath = `${configDir}/${baseName}.json`;
8068
- if (existsSync3(jsoncPath)) {
9356
+ if (existsSync4(jsoncPath)) {
8069
9357
  return { path: jsoncPath, format: "jsonc" };
8070
9358
  }
8071
- if (existsSync3(jsonPath)) {
9359
+ if (existsSync4(jsonPath)) {
8072
9360
  return { path: jsonPath, format: "json" };
8073
9361
  }
8074
9362
  return { path: jsonPath, format: "none" };
8075
9363
  }
8076
9364
  function readJsoncFile(path) {
8077
- if (!existsSync3(path)) {
9365
+ if (!existsSync4(path)) {
8078
9366
  return { value: null };
8079
9367
  }
8080
9368
  try {
8081
9369
  const raw = readFileSync(path, "utf-8");
8082
9370
  const value = import_comment_json.parse(raw);
8083
9371
  return { value };
8084
- } catch (error) {
9372
+ } catch (error2) {
8085
9373
  return {
8086
9374
  value: null,
8087
- error: error instanceof Error ? error.message : String(error)
9375
+ error: error2 instanceof Error ? error2.message : String(error2)
8088
9376
  };
8089
9377
  }
8090
9378
  }
8091
9379
  function writeJsoncFile(path, value, format = "json") {
8092
- mkdirSync(dirname(path), { recursive: true });
9380
+ mkdirSync2(dirname2(path), { recursive: true });
8093
9381
  const serialized = format === "jsonc" ? import_comment_json.stringify(value, null, 2) : JSON.stringify(value, null, 2);
8094
9382
  writeFileSync(path, `${serialized}
8095
9383
  `);
8096
9384
  }
8097
9385
  function ensureAftSchemaUrl(path, format) {
8098
- const existed = existsSync3(path);
9386
+ const existed = existsSync4(path);
8099
9387
  if (!existed) {
8100
9388
  const writeFormat = format === "jsonc" ? "jsonc" : "json";
8101
9389
  writeJsoncFile(path, { $schema: AFT_SCHEMA_URL }, writeFormat);
@@ -8104,9 +9392,9 @@ function ensureAftSchemaUrl(path, format) {
8104
9392
  message: `created ${path} with $schema URL for editor autocomplete`
8105
9393
  };
8106
9394
  }
8107
- const { value, error } = readJsoncFile(path);
9395
+ const { value, error: error2 } = readJsoncFile(path);
8108
9396
  if (!value) {
8109
- throw new Error(error ? `failed to parse ${path}: ${error}` : `failed to parse ${path}`);
9397
+ throw new Error(error2 ? `failed to parse ${path}: ${error2}` : `failed to parse ${path}`);
8110
9398
  }
8111
9399
  const previous = value.$schema;
8112
9400
  if (previous === AFT_SCHEMA_URL) {
@@ -8148,26 +9436,52 @@ var init_self_version = () => {};
8148
9436
 
8149
9437
  // src/adapters/opencode.ts
8150
9438
  import { execSync as execSync2 } from "node:child_process";
8151
- import { existsSync as existsSync4, readFileSync as readFileSync2, rmSync, statSync as statSync2 } from "node:fs";
8152
- import { homedir as homedir3 } from "node:os";
8153
- import { dirname as dirname2, join as join4, parse, resolve } from "node:path";
9439
+ import { existsSync as existsSync5, readFileSync as readFileSync2, rmSync, statSync as statSync3 } from "node:fs";
9440
+ import { homedir as homedir5 } from "node:os";
9441
+ import { dirname as dirname3, join as join6, parse, resolve } from "node:path";
8154
9442
  import { fileURLToPath } from "node:url";
8155
9443
  function getOpenCodeConfigDir() {
8156
9444
  const envDir = process.env.OPENCODE_CONFIG_DIR?.trim();
8157
9445
  if (envDir)
8158
9446
  return resolve(envDir);
8159
- const xdg = process.env.XDG_CONFIG_HOME || join4(homedir3(), ".config");
8160
- return join4(xdg, "opencode");
9447
+ const xdg = process.env.XDG_CONFIG_HOME || join6(homedir5(), ".config");
9448
+ return join6(xdg, "opencode");
8161
9449
  }
8162
9450
  function getOpenCodeCacheDir() {
8163
9451
  const xdg = process.env.XDG_CACHE_HOME;
8164
9452
  if (xdg)
8165
- return join4(xdg, "opencode");
9453
+ return join6(xdg, "opencode");
8166
9454
  if (process.platform === "win32") {
8167
- const localAppData = process.env.LOCALAPPDATA ?? join4(homedir3(), "AppData", "Local");
8168
- return join4(localAppData, "opencode");
9455
+ const localAppData = process.env.LOCALAPPDATA ?? join6(homedir5(), "AppData", "Local");
9456
+ return join6(localAppData, "opencode");
9457
+ }
9458
+ return join6(homedir5(), ".cache", "opencode");
9459
+ }
9460
+ function hasOpenCodeCli() {
9461
+ try {
9462
+ execSync2("opencode --version", { stdio: "ignore", timeout: 5000 });
9463
+ return true;
9464
+ } catch {
9465
+ return false;
8169
9466
  }
8170
- return join4(homedir3(), ".cache", "opencode");
9467
+ }
9468
+ function openCodeDesktopAppExists() {
9469
+ const candidates = [];
9470
+ if (process.platform === "darwin") {
9471
+ candidates.push("/Applications/OpenCode.app", "/Applications/OpenCode Beta.app", join6(homedir5(), "Applications", "OpenCode.app"), join6(homedir5(), "Applications", "OpenCode Beta.app"));
9472
+ } else if (process.platform === "win32") {
9473
+ const localAppData = process.env.LOCALAPPDATA ?? join6(homedir5(), "AppData", "Local");
9474
+ candidates.push(join6(localAppData, "Programs", "opencode"), join6(localAppData, "opencode"));
9475
+ } else {
9476
+ candidates.push("/opt/OpenCode", "/usr/lib/opencode", join6(homedir5(), ".local", "share", "applications", "opencode.desktop"));
9477
+ }
9478
+ return candidates.some((p) => {
9479
+ try {
9480
+ return existsSync5(p);
9481
+ } catch {
9482
+ return false;
9483
+ }
9484
+ });
8171
9485
  }
8172
9486
  function pathFromEntry(entry) {
8173
9487
  if (entry.startsWith("file://")) {
@@ -8186,17 +9500,17 @@ function pathPointsToOurPlugin(entry) {
8186
9500
  if (!fsPath)
8187
9501
  return false;
8188
9502
  try {
8189
- if (!existsSync4(fsPath))
9503
+ if (!existsSync5(fsPath))
8190
9504
  return false;
8191
- let searchDir = statSync2(fsPath).isDirectory() ? fsPath : dirname2(fsPath);
9505
+ let searchDir = statSync3(fsPath).isDirectory() ? fsPath : dirname3(fsPath);
8192
9506
  let pkgJsonPath = null;
8193
9507
  while (true) {
8194
- const candidate = join4(searchDir, "package.json");
8195
- if (existsSync4(candidate)) {
9508
+ const candidate = join6(searchDir, "package.json");
9509
+ if (existsSync5(candidate)) {
8196
9510
  pkgJsonPath = candidate;
8197
9511
  break;
8198
9512
  }
8199
- const parent = dirname2(searchDir);
9513
+ const parent = dirname3(searchDir);
8200
9514
  if (parent === searchDir || searchDir === parse(searchDir).root)
8201
9515
  break;
8202
9516
  searchDir = parent;
@@ -8223,16 +9537,19 @@ class OpenCodeAdapter {
8223
9537
  pluginPackageName = PLUGIN_NAME;
8224
9538
  pluginEntryWithVersion = PLUGIN_ENTRY;
8225
9539
  isInstalled() {
8226
- try {
8227
- execSync2("opencode --version", { stdio: "ignore" });
9540
+ if (existsSync5(getOpenCodeConfigDir()))
8228
9541
  return true;
8229
- } catch {
8230
- return false;
8231
- }
9542
+ if (openCodeDesktopAppExists())
9543
+ return true;
9544
+ return hasOpenCodeCli();
8232
9545
  }
8233
9546
  getHostVersion() {
8234
9547
  try {
8235
- return execSync2("opencode --version", { encoding: "utf-8", stdio: "pipe" }).trim();
9548
+ return execSync2("opencode --version", {
9549
+ encoding: "utf-8",
9550
+ stdio: "pipe",
9551
+ timeout: 5000
9552
+ }).trim();
8236
9553
  } catch {
8237
9554
  return null;
8238
9555
  }
@@ -8271,12 +9588,12 @@ class OpenCodeAdapter {
8271
9588
  configPath
8272
9589
  };
8273
9590
  }
8274
- const { value, error } = readJsoncFile(configPath);
8275
- if (error || !value) {
9591
+ const { value, error: error2 } = readJsoncFile(configPath);
9592
+ if (error2 || !value) {
8276
9593
  return {
8277
9594
  ok: false,
8278
9595
  action: "error",
8279
- message: `Could not parse ${configPath}: ${error ?? "unknown error"}`,
9596
+ message: `Could not parse ${configPath}: ${error2 ?? "unknown error"}`,
8280
9597
  configPath
8281
9598
  };
8282
9599
  }
@@ -8301,11 +9618,11 @@ class OpenCodeAdapter {
8301
9618
  };
8302
9619
  }
8303
9620
  getPluginCacheInfo() {
8304
- const path = join4(getOpenCodeCacheDir(), "packages", PLUGIN_ENTRY);
9621
+ const path = join6(getOpenCodeCacheDir(), "packages", PLUGIN_ENTRY);
8305
9622
  let cached;
8306
9623
  try {
8307
- const installedPkgPath = join4(path, "node_modules", "@cortexkit", "aft-opencode", "package.json");
8308
- if (existsSync4(installedPkgPath)) {
9624
+ const installedPkgPath = join6(path, "node_modules", "@cortexkit", "aft-opencode", "package.json");
9625
+ if (existsSync5(installedPkgPath)) {
8309
9626
  const pkg = JSON.parse(readFileSync2(installedPkgPath, "utf-8"));
8310
9627
  cached = typeof pkg.version === "string" ? pkg.version : undefined;
8311
9628
  }
@@ -8316,7 +9633,7 @@ class OpenCodeAdapter {
8316
9633
  path,
8317
9634
  cached,
8318
9635
  latest: getSelfVersion(),
8319
- exists: existsSync4(path)
9636
+ exists: existsSync5(path)
8320
9637
  };
8321
9638
  }
8322
9639
  getStorageDir() {
@@ -8349,13 +9666,13 @@ class OpenCodeAdapter {
8349
9666
  cached: info.cached,
8350
9667
  latest: info.latest
8351
9668
  };
8352
- } catch (error) {
9669
+ } catch (error2) {
8353
9670
  return {
8354
9671
  action: "error",
8355
9672
  path: info.path,
8356
9673
  cached: info.cached,
8357
9674
  latest: info.latest,
8358
- error: error instanceof Error ? error.message : String(error)
9675
+ error: error2 instanceof Error ? error2.message : String(error2)
8359
9676
  };
8360
9677
  }
8361
9678
  }
@@ -8365,11 +9682,11 @@ class OpenCodeAdapter {
8365
9682
  describeStorageSubtrees() {
8366
9683
  const storage = this.getStorageDir();
8367
9684
  return {
8368
- index: dirSize(join4(storage, "index")),
8369
- semantic: dirSize(join4(storage, "semantic")),
8370
- backups: dirSize(join4(storage, "backups")),
8371
- url_cache: dirSize(join4(storage, "url_cache")),
8372
- onnxruntime: dirSize(join4(storage, "onnxruntime"))
9685
+ index: dirSize(join6(storage, "index")),
9686
+ semantic: dirSize(join6(storage, "semantic")),
9687
+ backups: dirSize(join6(storage, "backups")),
9688
+ url_cache: dirSize(join6(storage, "url_cache")),
9689
+ onnxruntime: dirSize(join6(storage, "onnxruntime"))
8373
9690
  };
8374
9691
  }
8375
9692
  }
@@ -8377,24 +9694,24 @@ var PLUGIN_NAME = "@cortexkit/aft-opencode", PLUGIN_ENTRY;
8377
9694
  var init_opencode = __esm(() => {
8378
9695
  init_fs_util();
8379
9696
  init_jsonc();
8380
- init_paths();
9697
+ init_paths2();
8381
9698
  init_self_version();
8382
9699
  PLUGIN_ENTRY = `${PLUGIN_NAME}@latest`;
8383
9700
  });
8384
9701
 
8385
9702
  // src/adapters/pi.ts
8386
9703
  import { execSync as execSync3, spawnSync as spawnSync2 } from "node:child_process";
8387
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
8388
- import { homedir as homedir4 } from "node:os";
8389
- import { join as join5 } from "node:path";
9704
+ import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
9705
+ import { homedir as homedir6 } from "node:os";
9706
+ import { join as join7 } from "node:path";
8390
9707
  function getPiAgentDir() {
8391
9708
  const envHome = process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME;
8392
- const home = envHome && envHome.length > 0 ? envHome : homedir4();
8393
- return join5(home, ".pi", "agent");
9709
+ const home = envHome && envHome.length > 0 ? envHome : homedir6();
9710
+ return join7(home, ".pi", "agent");
8394
9711
  }
8395
9712
  function readPiExtensionIndex() {
8396
- const settingsPath = join5(getPiAgentDir(), "settings.json");
8397
- if (existsSync5(settingsPath)) {
9713
+ const settingsPath = join7(getPiAgentDir(), "settings.json");
9714
+ if (existsSync6(settingsPath)) {
8398
9715
  try {
8399
9716
  const raw = readFileSync3(settingsPath, "utf-8");
8400
9717
  const trimmed = raw.replace(/^\uFEFF/, "");
@@ -8407,13 +9724,13 @@ function readPiExtensionIndex() {
8407
9724
  } catch {}
8408
9725
  }
8409
9726
  const candidates = [
8410
- join5(getPiAgentDir(), "extensions.json"),
8411
- join5(getPiAgentDir(), "extensions.jsonc"),
8412
- join5(getPiAgentDir(), "config.json"),
8413
- join5(getPiAgentDir(), "config.jsonc")
9727
+ join7(getPiAgentDir(), "extensions.json"),
9728
+ join7(getPiAgentDir(), "extensions.jsonc"),
9729
+ join7(getPiAgentDir(), "config.json"),
9730
+ join7(getPiAgentDir(), "config.jsonc")
8414
9731
  ];
8415
9732
  for (const path of candidates) {
8416
- if (!existsSync5(path))
9733
+ if (!existsSync6(path))
8417
9734
  continue;
8418
9735
  try {
8419
9736
  const { value } = readJsoncFile(path);
@@ -8446,15 +9763,15 @@ function piEntryMatchesAft(entry) {
8446
9763
  } else if (entry.startsWith("/")) {
8447
9764
  resolved = entry;
8448
9765
  } else if (entry.length > 0) {
8449
- resolved = join5(getPiAgentDir(), entry);
9766
+ resolved = join7(getPiAgentDir(), entry);
8450
9767
  }
8451
9768
  if (!resolved)
8452
9769
  return false;
8453
9770
  try {
8454
- if (!existsSync5(resolved))
9771
+ if (!existsSync6(resolved))
8455
9772
  return false;
8456
- const pkgPath = join5(resolved, "package.json");
8457
- if (!existsSync5(pkgPath))
9773
+ const pkgPath = join7(resolved, "package.json");
9774
+ if (!existsSync6(pkgPath))
8458
9775
  return false;
8459
9776
  const pkg = JSON.parse(readFileSync3(pkgPath, "utf-8"));
8460
9777
  return pkg.name === PLUGIN_NAME2;
@@ -8474,7 +9791,7 @@ class PiAdapter {
8474
9791
  pluginEntryWithVersion = PLUGIN_ENTRY2;
8475
9792
  isInstalled() {
8476
9793
  try {
8477
- execSync3("pi --version", { stdio: "ignore" });
9794
+ execSync3("pi --version", { stdio: "ignore", timeout: 5000 });
8478
9795
  return true;
8479
9796
  } catch {
8480
9797
  return false;
@@ -8484,7 +9801,8 @@ class PiAdapter {
8484
9801
  try {
8485
9802
  const result = spawnSync2("pi", ["--version"], {
8486
9803
  stdio: ["ignore", "pipe", "pipe"],
8487
- encoding: "utf-8"
9804
+ encoding: "utf-8",
9805
+ timeout: 5000
8488
9806
  });
8489
9807
  if (result.status !== 0)
8490
9808
  return null;
@@ -8503,7 +9821,7 @@ class PiAdapter {
8503
9821
  const aft = detectJsoncFile(configDir, "aft");
8504
9822
  return {
8505
9823
  configDir,
8506
- harnessConfig: index.path ?? join5(configDir, "extensions.json"),
9824
+ harnessConfig: index.path ?? join7(configDir, "extensions.json"),
8507
9825
  harnessConfigFormat: index.path ? "json" : "none",
8508
9826
  aftConfig: aft.path,
8509
9827
  aftConfigFormat: aft.format
@@ -8537,22 +9855,22 @@ class PiAdapter {
8537
9855
  message: `Installed ${PLUGIN_ENTRY2} via \`pi install\``,
8538
9856
  configPath: this.detectConfigPaths().harnessConfig
8539
9857
  };
8540
- } catch (error) {
9858
+ } catch (error2) {
8541
9859
  return {
8542
9860
  ok: false,
8543
9861
  action: "error",
8544
- message: `Failed to run \`pi install ${PLUGIN_ENTRY2}\`: ${error instanceof Error ? error.message : String(error)}`,
9862
+ message: `Failed to run \`pi install ${PLUGIN_ENTRY2}\`: ${error2 instanceof Error ? error2.message : String(error2)}`,
8545
9863
  configPath: this.detectConfigPaths().harnessConfig
8546
9864
  };
8547
9865
  }
8548
9866
  }
8549
9867
  getPluginCacheInfo() {
8550
9868
  const candidates = [
8551
- join5(getPiAgentDir(), "node_modules", "@cortexkit", "aft-pi", "package.json"),
8552
- join5(getPiAgentDir(), "extensions", "node_modules", "@cortexkit", "aft-pi", "package.json")
9869
+ join7(getPiAgentDir(), "node_modules", "@cortexkit", "aft-pi", "package.json"),
9870
+ join7(getPiAgentDir(), "extensions", "node_modules", "@cortexkit", "aft-pi", "package.json")
8553
9871
  ];
8554
9872
  for (const candidate of candidates) {
8555
- if (!existsSync5(candidate))
9873
+ if (!existsSync6(candidate))
8556
9874
  continue;
8557
9875
  try {
8558
9876
  const pkg = JSON.parse(readFileSync3(candidate, "utf-8"));
@@ -8566,7 +9884,7 @@ class PiAdapter {
8566
9884
  } catch {}
8567
9885
  }
8568
9886
  return {
8569
- path: join5(getPiAgentDir(), "extensions"),
9887
+ path: join7(getPiAgentDir(), "extensions"),
8570
9888
  exists: false
8571
9889
  };
8572
9890
  }
@@ -8588,11 +9906,11 @@ class PiAdapter {
8588
9906
  describeStorageSubtrees() {
8589
9907
  const storage = this.getStorageDir();
8590
9908
  return {
8591
- index: dirSize(join5(storage, "index")),
8592
- semantic: dirSize(join5(storage, "semantic")),
8593
- backups: dirSize(join5(storage, "backups")),
8594
- url_cache: dirSize(join5(storage, "url_cache")),
8595
- onnxruntime: dirSize(join5(storage, "onnxruntime"))
9909
+ index: dirSize(join7(storage, "index")),
9910
+ semantic: dirSize(join7(storage, "semantic")),
9911
+ backups: dirSize(join7(storage, "backups")),
9912
+ url_cache: dirSize(join7(storage, "url_cache")),
9913
+ onnxruntime: dirSize(join7(storage, "onnxruntime"))
8596
9914
  };
8597
9915
  }
8598
9916
  }
@@ -8600,7 +9918,7 @@ var PLUGIN_NAME2 = "@cortexkit/aft-pi", PLUGIN_ENTRY2;
8600
9918
  var init_pi = __esm(() => {
8601
9919
  init_fs_util();
8602
9920
  init_jsonc();
8603
- init_paths();
9921
+ init_paths2();
8604
9922
  PLUGIN_ENTRY2 = `npm:${PLUGIN_NAME2}`;
8605
9923
  });
8606
9924
 
@@ -8778,7 +10096,7 @@ var ANSI_RE, CONTROL_RE, TAB_RE, EMOJI_RE, LATIN_RE, MODIFIER_RE, NO_TRUNCATION,
8778
10096
  ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
8779
10097
  };
8780
10098
  }, dist_default;
8781
- var init_dist = __esm(() => {
10099
+ var init_dist2 = __esm(() => {
8782
10100
  init_utils();
8783
10101
  ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y;
8784
10102
  CONTROL_RE = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
@@ -8794,8 +10112,8 @@ var init_dist = __esm(() => {
8794
10112
  var NO_TRUNCATION2, fastStringWidth = (input, options = {}) => {
8795
10113
  return dist_default(input, NO_TRUNCATION2, options).width;
8796
10114
  }, dist_default2;
8797
- var init_dist2 = __esm(() => {
8798
- init_dist();
10115
+ var init_dist3 = __esm(() => {
10116
+ init_dist2();
8799
10117
  NO_TRUNCATION2 = {
8800
10118
  limit: Infinity,
8801
10119
  ellipsis: "",
@@ -8998,7 +10316,7 @@ var ESC = "\x1B", CSI = "›", END_CODE = 39, ANSI_ESCAPE_BELL = "\x07", ANSI_CSI
8998
10316
  return returnValue;
8999
10317
  }, CRLF_OR_LF;
9000
10318
  var init_main = __esm(() => {
9001
- init_dist2();
10319
+ init_dist3();
9002
10320
  ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
9003
10321
  GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");
9004
10322
  CRLF_OR_LF = /\r?\n/;
@@ -9278,7 +10596,7 @@ var import_sisteransi, E, G, u, Y, C, O = (r) => ("columns" in r) && typeof r.co
9278
10596
  }
9279
10597
  }
9280
10598
  }, H, Q, X, et, st, it, nt, at;
9281
- var init_dist3 = __esm(() => {
10599
+ var init_dist4 = __esm(() => {
9282
10600
  init_main();
9283
10601
  import_sisteransi = __toESM(require_src3(), 1);
9284
10602
  E = ["up", "down", "left", "right", "space", "enter", "cancel"];
@@ -9900,11 +11218,11 @@ ${c2}
9900
11218
  }
9901
11219
  }
9902
11220
  } }).prompt();
9903
- var init_dist4 = __esm(() => {
9904
- init_dist3();
9905
- init_dist3();
11221
+ var init_dist5 = __esm(() => {
11222
+ init_dist4();
11223
+ init_dist4();
9906
11224
  init_main();
9907
- init_dist2();
11225
+ init_dist3();
9908
11226
  import_sisteransi2 = __toESM(require_src3(), 1);
9909
11227
  ee = Ze();
9910
11228
  _e = w2("◆", "*");
@@ -10014,7 +11332,7 @@ async function text(message, options = {}) {
10014
11332
  return result;
10015
11333
  }
10016
11334
  var init_prompts = __esm(() => {
10017
- init_dist4();
11335
+ init_dist5();
10018
11336
  });
10019
11337
 
10020
11338
  // src/lib/harness-select.ts
@@ -10162,8 +11480,8 @@ async function runSetup(argv) {
10162
11480
  if (schemaResult.action === "added" || schemaResult.action === "updated") {
10163
11481
  O2.success(`${adapter.displayName}: ${schemaResult.message}`);
10164
11482
  }
10165
- } catch (error) {
10166
- O2.warn(`${adapter.displayName}: could not set $schema on aft.jsonc: ${error instanceof Error ? error.message : String(error)}`);
11483
+ } catch (error2) {
11484
+ O2.warn(`${adapter.displayName}: could not set $schema on aft.jsonc: ${error2 instanceof Error ? error2.message : String(error2)}`);
10167
11485
  }
10168
11486
  printNextSteps(adapter);
10169
11487
  }
@@ -10198,7 +11516,7 @@ var init_setup = __esm(() => {
10198
11516
  });
10199
11517
 
10200
11518
  // src/lib/aft-bridge.ts
10201
- import { spawn } from "node:child_process";
11519
+ import { spawn as spawn2 } from "node:child_process";
10202
11520
  function isResponseForRequest(parsed, expectedIds) {
10203
11521
  if (!parsed || typeof parsed !== "object")
10204
11522
  return false;
@@ -10210,7 +11528,7 @@ function isResponseForRequest(parsed, expectedIds) {
10210
11528
  }
10211
11529
  async function sendAftRequests(binaryPath, requests) {
10212
11530
  return new Promise((resolve2, reject) => {
10213
- const child = spawn(binaryPath, [], {
11531
+ const child = spawn2(binaryPath, [], {
10214
11532
  stdio: ["pipe", "pipe", "pipe"]
10215
11533
  });
10216
11534
  const responses = [];
@@ -10268,8 +11586,8 @@ async function sendAftRequests(binaryPath, requests) {
10268
11586
  child.stderr.on("data", (chunk) => {
10269
11587
  stderr += chunk;
10270
11588
  });
10271
- child.on("error", (error) => {
10272
- finish(() => reject(error));
11589
+ child.on("error", (error2) => {
11590
+ finish(() => reject(error2));
10273
11591
  });
10274
11592
  child.on("close", (code) => {
10275
11593
  if (settled)
@@ -10321,23 +11639,23 @@ __export(exports_lsp, {
10321
11639
  printLspDoctorHelp: () => printLspDoctorHelp,
10322
11640
  findProjectRootForFile: () => findProjectRootForFile
10323
11641
  });
10324
- import { existsSync as existsSync6, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
10325
- import { dirname as dirname3, join as join6, resolve as resolve2 } from "node:path";
11642
+ import { existsSync as existsSync7, readdirSync as readdirSync3, statSync as statSync4 } from "node:fs";
11643
+ import { dirname as dirname4, join as join8, resolve as resolve2 } from "node:path";
10326
11644
  function findProjectRootForFile(filePath, fallbackCwd = process.cwd()) {
10327
11645
  const resolvedFile = resolve2(fallbackCwd, filePath);
10328
- let dir = dirname3(resolvedFile);
11646
+ let dir = dirname4(resolvedFile);
10329
11647
  try {
10330
- if (existsSync6(resolvedFile) && statSync3(resolvedFile).isDirectory()) {
11648
+ if (existsSync7(resolvedFile) && statSync4(resolvedFile).isDirectory()) {
10331
11649
  dir = resolvedFile;
10332
11650
  }
10333
11651
  } catch {
10334
- dir = dirname3(resolvedFile);
11652
+ dir = dirname4(resolvedFile);
10335
11653
  }
10336
11654
  while (true) {
10337
- if (PROJECT_ROOT_MARKERS.some((marker) => existsSync6(join6(dir, marker)))) {
11655
+ if (PROJECT_ROOT_MARKERS.some((marker) => existsSync7(join8(dir, marker)))) {
10338
11656
  return dir;
10339
11657
  }
10340
- const parent = dirname3(dir);
11658
+ const parent = dirname4(dir);
10341
11659
  if (parent === dir)
10342
11660
  return resolve2(fallbackCwd);
10343
11661
  dir = parent;
@@ -10364,8 +11682,8 @@ async function runLspDoctor(options) {
10364
11682
  O2.error("No harness selected.");
10365
11683
  return 1;
10366
11684
  }
10367
- const findBinary = options.findBinary ?? findAftBinary;
10368
- const binary = findBinary(getSelfVersion());
11685
+ const findBinary2 = options.findBinary ?? findAftBinary;
11686
+ const binary = findBinary2(getSelfVersion());
10369
11687
  if (!binary) {
10370
11688
  O2.error("Could not find the aft binary in the cache, platform package, PATH, or ~/.cargo/bin.");
10371
11689
  return 1;
@@ -10472,11 +11790,11 @@ function buildConfigureParams(adapter, projectRoot) {
10472
11790
  }
10473
11791
  function readProjectConfig(kind, projectRoot) {
10474
11792
  const dir = kind === "pi" ? ".pi" : ".opencode";
10475
- const jsonc = join6(projectRoot, dir, "aft.jsonc");
10476
- const json = join6(projectRoot, dir, "aft.json");
10477
- if (existsSync6(jsonc))
11793
+ const jsonc = join8(projectRoot, dir, "aft.jsonc");
11794
+ const json = join8(projectRoot, dir, "aft.json");
11795
+ if (existsSync7(jsonc))
10478
11796
  return readJsoncFile(jsonc).value ?? {};
10479
- if (existsSync6(json))
11797
+ if (existsSync7(json))
10480
11798
  return readJsoncFile(json).value ?? {};
10481
11799
  return {};
10482
11800
  }
@@ -10539,20 +11857,20 @@ function resolveCustomServers(servers) {
10539
11857
  function inferLspPathsExtra(_lsp) {
10540
11858
  const paths = new Set;
10541
11859
  for (const entry of childDirs(getAftLspPackagesDir())) {
10542
- paths.add(join6(entry, "node_modules", ".bin"));
11860
+ paths.add(join8(entry, "node_modules", ".bin"));
10543
11861
  }
10544
11862
  for (const entry of childDirs(getAftLspBinariesDir())) {
10545
- paths.add(join6(entry, "bin"));
11863
+ paths.add(join8(entry, "bin"));
10546
11864
  }
10547
11865
  return [...paths];
10548
11866
  }
10549
11867
  function childDirs(path) {
10550
- if (!existsSync6(path))
11868
+ if (!existsSync7(path))
10551
11869
  return [];
10552
11870
  try {
10553
- return readdirSync2(path).map((entry) => join6(path, entry)).filter((entry) => {
11871
+ return readdirSync3(path).map((entry) => join8(path, entry)).filter((entry) => {
10554
11872
  try {
10555
- return statSync3(entry).isDirectory();
11873
+ return statSync4(entry).isDirectory();
10556
11874
  } catch {
10557
11875
  return false;
10558
11876
  }
@@ -10600,7 +11918,7 @@ var init_lsp = __esm(async () => {
10600
11918
  init_aft_bridge();
10601
11919
  init_harness_select();
10602
11920
  init_jsonc();
10603
- init_paths();
11921
+ init_paths2();
10604
11922
  init_prompts();
10605
11923
  init_self_version();
10606
11924
  await init_binary_probe();
@@ -10630,8 +11948,8 @@ __export(exports_doctor_filters, {
10630
11948
  renderFilterList: () => renderFilterList,
10631
11949
  printDoctorFiltersHelp: () => printDoctorFiltersHelp
10632
11950
  });
10633
- import { existsSync as existsSync7 } from "node:fs";
10634
- import { homedir as homedir5 } from "node:os";
11951
+ import { existsSync as existsSync8 } from "node:fs";
11952
+ import { homedir as homedir7 } from "node:os";
10635
11953
  import { relative, resolve as resolve3 } from "node:path";
10636
11954
  function printDoctorFiltersHelp() {
10637
11955
  console.log("Usage: aft doctor filters [--show <name>] [trust|untrust]");
@@ -10661,8 +11979,8 @@ async function runDoctorFilters(options) {
10661
11979
  O2.error("No harness selected.");
10662
11980
  return 1;
10663
11981
  }
10664
- const findBinary = options.findBinary ?? findAftBinary;
10665
- const binary = findBinary(getSelfVersion());
11982
+ const findBinary2 = options.findBinary ?? findAftBinary;
11983
+ const binary = findBinary2(getSelfVersion());
10666
11984
  if (!binary) {
10667
11985
  O2.error("Could not find the aft binary in the cache, platform package, PATH, or ~/.cargo/bin.");
10668
11986
  return 1;
@@ -10673,7 +11991,7 @@ async function runDoctorFilters(options) {
10673
11991
  O2.error(list.message ?? list.code ?? "list_filters failed");
10674
11992
  return 1;
10675
11993
  }
10676
- list.project_dir_exists = list.project_dir ? existsSync7(list.project_dir) : false;
11994
+ list.project_dir_exists = list.project_dir ? existsSync8(list.project_dir) : false;
10677
11995
  if (mode.kind === "list") {
10678
11996
  console.log(renderFilterList(list, projectRoot));
10679
11997
  return 0;
@@ -10849,7 +12167,7 @@ function truncate(value) {
10849
12167
  return value.length <= 80 ? value : `${value.slice(0, 77)}…`;
10850
12168
  }
10851
12169
  function formatHome(path) {
10852
- const home = homedir5();
12170
+ const home = homedir7();
10853
12171
  return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
10854
12172
  }
10855
12173
  function formatProjectPath(path, projectRoot) {
@@ -10872,11 +12190,11 @@ var init_doctor_filters = __esm(async () => {
10872
12190
  });
10873
12191
 
10874
12192
  // src/lib/binary-cache.ts
10875
- import { existsSync as existsSync8, readdirSync as readdirSync3, statSync as statSync4 } from "node:fs";
10876
- import { join as join7 } from "node:path";
12193
+ import { existsSync as existsSync9, readdirSync as readdirSync4, statSync as statSync5 } from "node:fs";
12194
+ import { join as join9 } from "node:path";
10877
12195
  function getBinaryCacheInfo(activeVersion) {
10878
12196
  const path = getAftBinaryCacheDir();
10879
- if (!existsSync8(path)) {
12197
+ if (!existsSync9(path)) {
10880
12198
  return {
10881
12199
  versions: [],
10882
12200
  activeVersion: null,
@@ -10884,9 +12202,9 @@ function getBinaryCacheInfo(activeVersion) {
10884
12202
  path
10885
12203
  };
10886
12204
  }
10887
- const versions = readdirSync3(path).filter((entry) => {
12205
+ const versions = readdirSync4(path).filter((entry) => {
10888
12206
  try {
10889
- return statSync4(join7(path, entry)).isDirectory();
12207
+ return statSync5(join9(path, entry)).isDirectory();
10890
12208
  } catch {
10891
12209
  return false;
10892
12210
  }
@@ -10902,28 +12220,28 @@ function getBinaryCacheInfo(activeVersion) {
10902
12220
  }
10903
12221
  var init_binary_cache = __esm(() => {
10904
12222
  init_fs_util();
10905
- init_paths();
12223
+ init_paths2();
10906
12224
  });
10907
12225
 
10908
12226
  // src/lib/lsp-cache.ts
10909
- import { existsSync as existsSync9, readdirSync as readdirSync4, rmSync as rmSync2, statSync as statSync5 } from "node:fs";
10910
- import { join as join8 } from "node:path";
12227
+ import { existsSync as existsSync10, readdirSync as readdirSync5, rmSync as rmSync2, statSync as statSync6 } from "node:fs";
12228
+ import { join as join10 } from "node:path";
10911
12229
  function inspectDir(path) {
10912
- if (!existsSync9(path)) {
12230
+ if (!existsSync10(path)) {
10913
12231
  return { entries: [], totalSize: 0 };
10914
12232
  }
10915
12233
  const entries = [];
10916
12234
  let totalSize = 0;
10917
12235
  let names;
10918
12236
  try {
10919
- names = readdirSync4(path);
12237
+ names = readdirSync5(path);
10920
12238
  } catch {
10921
12239
  return { entries: [], totalSize: 0 };
10922
12240
  }
10923
12241
  for (const name of names) {
10924
- const full = join8(path, name);
12242
+ const full = join10(path, name);
10925
12243
  try {
10926
- if (!statSync5(full).isDirectory())
12244
+ if (!statSync6(full).isDirectory())
10927
12245
  continue;
10928
12246
  const size = dirSize(full);
10929
12247
  entries.push({
@@ -10975,12 +12293,12 @@ function clearLspCaches() {
10975
12293
  }
10976
12294
  var init_lsp_cache = __esm(() => {
10977
12295
  init_fs_util();
10978
- init_paths();
12296
+ init_paths2();
10979
12297
  });
10980
12298
 
10981
12299
  // src/lib/onnx.ts
10982
- import { existsSync as existsSync10, readdirSync as readdirSync5, readlinkSync, realpathSync, statSync as statSync6 } from "node:fs";
10983
- import { basename, isAbsolute, join as join9, resolve as resolve4, win32 } from "node:path";
12300
+ import { existsSync as existsSync11, readdirSync as readdirSync6, readlinkSync, realpathSync as realpathSync2, statSync as statSync7 } from "node:fs";
12301
+ import { basename, isAbsolute as isAbsolute2, join as join11, resolve as resolve4, win32 } from "node:path";
10984
12302
  function getOnnxLibraryName() {
10985
12303
  if (process.platform === "darwin")
10986
12304
  return "libonnxruntime.dylib";
@@ -10988,7 +12306,7 @@ function getOnnxLibraryName() {
10988
12306
  return "onnxruntime.dll";
10989
12307
  return "libonnxruntime.so";
10990
12308
  }
10991
- function getManualInstallHint() {
12309
+ function getManualInstallHint2() {
10992
12310
  const p2 = process.platform;
10993
12311
  const a = process.arch;
10994
12312
  if (p2 === "darwin") {
@@ -11013,16 +12331,16 @@ function pathEnvValue() {
11013
12331
  return process.env.PATH ?? process.env.Path ?? process.env.path ?? "";
11014
12332
  }
11015
12333
  function pathEntriesForPlatform() {
11016
- const delimiter = process.platform === "win32" ? ";" : ":";
11017
- return pathEnvValue().split(delimiter).map((entry) => entry.trim().replace(/^"|"$/g, "")).filter((entry) => {
12334
+ const delimiter2 = process.platform === "win32" ? ";" : ":";
12335
+ return pathEnvValue().split(delimiter2).map((entry) => entry.trim().replace(/^"|"$/g, "")).filter((entry) => {
11018
12336
  if (!entry || entry === "." || entry.includes("\x00"))
11019
12337
  return false;
11020
- return isAbsolute(entry) || win32.isAbsolute(entry);
12338
+ return isAbsolute2(entry) || win32.isAbsolute(entry);
11021
12339
  });
11022
12340
  }
11023
12341
  function directoryContainsLibrary(dir, libName) {
11024
12342
  try {
11025
- const entries = readdirSync5(dir);
12343
+ const entries = readdirSync6(dir);
11026
12344
  if (process.platform === "win32") {
11027
12345
  const expected = libName.toLowerCase();
11028
12346
  return entries.some((entry) => entry.toLowerCase() === expected);
@@ -11043,21 +12361,21 @@ function findSystemOnnxRuntime() {
11043
12361
  searchPaths.push(...pathEntriesForPlatform());
11044
12362
  const programFiles = process.env.ProgramFiles ?? "C:\\Program Files";
11045
12363
  const programFilesX86 = process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)";
11046
- searchPaths.push(join9(programFiles, "onnxruntime", "lib"), join9(programFiles, "Microsoft ONNX Runtime", "lib"), join9(programFiles, "Microsoft Machine Learning", "lib"), join9(programFilesX86, "onnxruntime", "lib"), ...(() => {
12364
+ searchPaths.push(join11(programFiles, "onnxruntime", "lib"), join11(programFiles, "Microsoft ONNX Runtime", "lib"), join11(programFiles, "Microsoft Machine Learning", "lib"), join11(programFilesX86, "onnxruntime", "lib"), ...(() => {
11047
12365
  const nugetPaths = [];
11048
12366
  const userProfile = process.env.USERPROFILE ?? "";
11049
12367
  if (!userProfile)
11050
12368
  return nugetPaths;
11051
- const nugetPackageDir = join9(userProfile, ".nuget", "packages", "microsoft.ml.onnxruntime");
11052
- if (!existsSync10(nugetPackageDir))
12369
+ const nugetPackageDir = join11(userProfile, ".nuget", "packages", "microsoft.ml.onnxruntime");
12370
+ if (!existsSync11(nugetPackageDir))
11053
12371
  return nugetPaths;
11054
12372
  try {
11055
- for (const entry of readdirSync5(nugetPackageDir, { withFileTypes: true })) {
12373
+ for (const entry of readdirSync6(nugetPackageDir, { withFileTypes: true })) {
11056
12374
  if (!entry.isDirectory())
11057
12375
  continue;
11058
12376
  if (entry.name === "__globalPackagesFolder" || entry.name.startsWith("."))
11059
12377
  continue;
11060
- nugetPaths.push(join9(nugetPackageDir, entry.name, "runtimes", "win-x64", "native"), join9(nugetPackageDir, entry.name, "runtimes", "win-arm64", "native"));
12378
+ nugetPaths.push(join11(nugetPackageDir, entry.name, "runtimes", "win-x64", "native"), join11(nugetPackageDir, entry.name, "runtimes", "win-arm64", "native"));
11061
12379
  }
11062
12380
  } catch {}
11063
12381
  return nugetPaths;
@@ -11087,12 +12405,12 @@ function findSystemOnnxRuntime() {
11087
12405
  return unknownVersionPaths[0] ?? null;
11088
12406
  }
11089
12407
  function findCachedOnnxRuntime(storageDir) {
11090
- const ortDir = join9(storageDir, "onnxruntime", ONNX_RUNTIME_VERSION);
12408
+ const ortDir = join11(storageDir, "onnxruntime", ONNX_RUNTIME_VERSION);
11091
12409
  const libName = getOnnxLibraryName();
11092
- if (existsSync10(join9(ortDir, libName)))
12410
+ if (existsSync11(join11(ortDir, libName)))
11093
12411
  return ortDir;
11094
- const libSubdir = join9(ortDir, "lib");
11095
- if (existsSync10(join9(libSubdir, libName)))
12412
+ const libSubdir = join11(ortDir, "lib");
12413
+ if (existsSync11(join11(libSubdir, libName)))
11096
12414
  return libSubdir;
11097
12415
  return null;
11098
12416
  }
@@ -11113,11 +12431,11 @@ function parseOrtVersionFromDirectoryPath(value) {
11113
12431
  return null;
11114
12432
  }
11115
12433
  function detectOrtVersion(libDir) {
11116
- if (!existsSync10(libDir))
12434
+ if (!existsSync11(libDir))
11117
12435
  return null;
11118
12436
  const libName = getOnnxLibraryName();
11119
12437
  try {
11120
- const entries = readdirSync5(libDir);
12438
+ const entries = readdirSync6(libDir);
11121
12439
  const barePrefix = libName.replace(/\.(so|dylib|dll)$/, "");
11122
12440
  const expectedPrefix = process.platform === "win32" ? barePrefix.toLowerCase() : barePrefix;
11123
12441
  for (const entry of entries) {
@@ -11128,10 +12446,10 @@ function detectOrtVersion(libDir) {
11128
12446
  if (version)
11129
12447
  return version;
11130
12448
  }
11131
- const base = join9(libDir, libName);
11132
- if (existsSync10(base)) {
12449
+ const base = join11(libDir, libName);
12450
+ if (existsSync11(base)) {
11133
12451
  try {
11134
- const real = realpathSync(base);
12452
+ const real = realpathSync2(base);
11135
12453
  const version = parseOrtVersionFromPath(real) ?? parseOrtVersionFromDirectoryPath(real);
11136
12454
  if (version)
11137
12455
  return version;
@@ -11160,14 +12478,14 @@ var ONNX_RUNTIME_VERSION = "1.24.4", INVALID_ORT_VERSION = "<invalid>", REQUIRED
11160
12478
  var init_onnx = () => {};
11161
12479
 
11162
12480
  // src/lib/sanitize.ts
11163
- import { realpathSync as realpathSync2 } from "node:fs";
11164
- import { homedir as homedir6, userInfo } from "node:os";
12481
+ import { realpathSync as realpathSync3 } from "node:fs";
12482
+ import { homedir as homedir8, userInfo } from "node:os";
11165
12483
  function escapeRegex(value) {
11166
12484
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11167
12485
  }
11168
12486
  function safeRealpath(p2) {
11169
12487
  try {
11170
- return realpathSync2(p2);
12488
+ return realpathSync3(p2);
11171
12489
  } catch {
11172
12490
  return null;
11173
12491
  }
@@ -11192,7 +12510,7 @@ function redactSecrets(content) {
11192
12510
  }
11193
12511
  function sanitizeContent(content) {
11194
12512
  const username = userInfo().username;
11195
- const home = homedir6();
12513
+ const home = homedir8();
11196
12514
  let sanitized = redactSecrets(content);
11197
12515
  const cwd = process.cwd();
11198
12516
  for (const candidate of new Set([cwd, safeRealpath(cwd)])) {
@@ -11239,12 +12557,12 @@ var init_sanitize = __esm(() => {
11239
12557
  // src/lib/diagnostics.ts
11240
12558
  import {
11241
12559
  accessSync,
11242
- closeSync,
12560
+ closeSync as closeSync2,
11243
12561
  constants,
11244
- existsSync as existsSync11,
11245
- openSync,
11246
- readSync,
11247
- statSync as statSync7
12562
+ existsSync as existsSync12,
12563
+ openSync as openSync2,
12564
+ readSync as readSync2,
12565
+ statSync as statSync8
11248
12566
  } from "node:fs";
11249
12567
  async function collectDiagnostics(adapters) {
11250
12568
  const cliVersion = getSelfVersion();
@@ -11273,7 +12591,7 @@ async function diagnoseHarness(adapter) {
11273
12591
  const logPath = adapter.getLogFile();
11274
12592
  const pluginCache = adapter.getPluginCacheInfo();
11275
12593
  const storageAccessible = (() => {
11276
- if (!existsSync11(storage))
12594
+ if (!existsSync12(storage))
11277
12595
  return false;
11278
12596
  try {
11279
12597
  accessSync(storage, constants.R_OK | constants.W_OK);
@@ -11296,14 +12614,14 @@ async function diagnoseHarness(adapter) {
11296
12614
  pluginRegistered: adapter.hasPluginEntry(),
11297
12615
  configPaths,
11298
12616
  aftConfig: {
11299
- exists: existsSync11(configPaths.aftConfig),
12617
+ exists: existsSync12(configPaths.aftConfig),
11300
12618
  ...aftConfigRead.error ? { parseError: aftConfigRead.error } : {},
11301
12619
  flags: aftFlags
11302
12620
  },
11303
12621
  pluginCache,
11304
12622
  storageDir: {
11305
12623
  path: storage,
11306
- exists: existsSync11(storage),
12624
+ exists: existsSync12(storage),
11307
12625
  accessible: storageAccessible,
11308
12626
  sizesByKey: describeStorage
11309
12627
  },
@@ -11316,13 +12634,13 @@ async function diagnoseHarness(adapter) {
11316
12634
  cachedVersion,
11317
12635
  cachedCompatible: cachedVersion ? isOrtVersionCompatible(cachedVersion) : null,
11318
12636
  platform: `${process.platform}-${process.arch}`,
11319
- installHint: getManualInstallHint(),
12637
+ installHint: getManualInstallHint2(),
11320
12638
  requirement: `>=${REQUIRED_ORT_MAJOR}.${REQUIRED_ORT_MIN_MINOR}`
11321
12639
  },
11322
12640
  logFile: {
11323
12641
  path: logPath,
11324
- exists: existsSync11(logPath),
11325
- sizeKb: existsSync11(logPath) ? Math.round(statSync7(logPath).size / 1024) : 0
12642
+ exists: existsSync12(logPath),
12643
+ sizeKb: existsSync12(logPath) ? Math.round(statSync8(logPath).size / 1024) : 0
11326
12644
  }
11327
12645
  };
11328
12646
  }
@@ -11516,15 +12834,15 @@ function formatDiagnosticIssuesSection(report) {
11516
12834
  return lines;
11517
12835
  }
11518
12836
  function tailLogFile(path, lines) {
11519
- if (!existsSync11(path))
12837
+ if (!existsSync12(path))
11520
12838
  return "";
11521
12839
  if (lines <= 0)
11522
12840
  return "";
11523
12841
  const chunkSize = 64 * 1024;
11524
12842
  let fd = null;
11525
12843
  try {
11526
- const size = statSync7(path).size;
11527
- fd = openSync(path, "r");
12844
+ const size = statSync8(path).size;
12845
+ fd = openSync2(path, "r");
11528
12846
  const chunks = [];
11529
12847
  let position = size;
11530
12848
  let newlineCount = 0;
@@ -11532,7 +12850,7 @@ function tailLogFile(path, lines) {
11532
12850
  const readLength = Math.min(chunkSize, position);
11533
12851
  position -= readLength;
11534
12852
  const buffer = Buffer.allocUnsafe(readLength);
11535
- const bytesRead = readSync(fd, buffer, 0, readLength, position);
12853
+ const bytesRead = readSync2(fd, buffer, 0, readLength, position);
11536
12854
  const chunk = bytesRead === readLength ? buffer : buffer.subarray(0, bytesRead);
11537
12855
  chunks.unshift(chunk);
11538
12856
  for (let i = chunk.length - 1;i >= 0; i -= 1) {
@@ -11547,7 +12865,7 @@ function tailLogFile(path, lines) {
11547
12865
  } finally {
11548
12866
  if (fd !== null) {
11549
12867
  try {
11550
- closeSync(fd);
12868
+ closeSync2(fd);
11551
12869
  } catch {}
11552
12870
  }
11553
12871
  }
@@ -11643,7 +12961,7 @@ function capBodyToGithubLimit(body, maxBytes = MAX_GITHUB_BODY_BYTES) {
11643
12961
  const logBlockStart = headingEol + 1;
11644
12962
  const logBlockEnd = nextSectionIdx === -1 ? body.length : nextSectionIdx;
11645
12963
  const head = body.slice(0, logBlockStart);
11646
- const log = body.slice(logBlockStart, logBlockEnd);
12964
+ const log2 = body.slice(logBlockStart, logBlockEnd);
11647
12965
  const tail = body.slice(logBlockEnd);
11648
12966
  const overheadBytes = Buffer.byteLength(head, "utf8") + Buffer.byteLength(tail, "utf8");
11649
12967
  const truncationMarker = `[truncated for GitHub 64KB limit — older log lines dropped]
@@ -11653,7 +12971,7 @@ function capBodyToGithubLimit(body, maxBytes = MAX_GITHUB_BODY_BYTES) {
11653
12971
  if (logBudget <= 0) {
11654
12972
  return `${head}${truncationMarker}${tail}`;
11655
12973
  }
11656
- const lines = log.split(`
12974
+ const lines = log2.split(`
11657
12975
  `);
11658
12976
  let keepLines = lines;
11659
12977
  let kept = keepLines.join(`
@@ -11702,8 +13020,8 @@ var init_issue_body = __esm(() => {
11702
13020
  });
11703
13021
 
11704
13022
  // src/lib/onnx-fix.ts
11705
- import { existsSync as existsSync12, rmSync as rmSync3 } from "node:fs";
11706
- import { join as join10 } from "node:path";
13023
+ import { existsSync as existsSync13, rmSync as rmSync3 } from "node:fs";
13024
+ import { join as join12 } from "node:path";
11707
13025
  function findOnnxFixCandidates(report) {
11708
13026
  const candidates = [];
11709
13027
  for (const harness of report.harnesses) {
@@ -11711,7 +13029,7 @@ function findOnnxFixCandidates(report) {
11711
13029
  continue;
11712
13030
  if (!harness.storageDir.exists)
11713
13031
  continue;
11714
- const storageOnnxDir = join10(harness.storageDir.path, "onnxruntime");
13032
+ const storageOnnxDir = join12(harness.storageDir.path, "onnxruntime");
11715
13033
  const systemTooOld = harness.onnxRuntime.systemPath !== null && harness.onnxRuntime.systemCompatible === false;
11716
13034
  const cachedTooOld = harness.onnxRuntime.cachedPath !== null && harness.onnxRuntime.cachedCompatible === false;
11717
13035
  const hasCompatibleCached = harness.onnxRuntime.cachedCompatible === true;
@@ -11720,7 +13038,7 @@ function findOnnxFixCandidates(report) {
11720
13038
  harness,
11721
13039
  reason: `cached ONNX Runtime at ${harness.onnxRuntime.cachedPath} is v${harness.onnxRuntime.cachedVersion}, but AFT requires ${harness.onnxRuntime.requirement}. Clearing forces a fresh download on next start.`,
11722
13040
  storageOnnxDir,
11723
- storageOnnxBytes: existsSync12(storageOnnxDir) ? dirSize(storageOnnxDir) : 0
13041
+ storageOnnxBytes: existsSync13(storageOnnxDir) ? dirSize(storageOnnxDir) : 0
11724
13042
  });
11725
13043
  continue;
11726
13044
  }
@@ -11729,7 +13047,7 @@ function findOnnxFixCandidates(report) {
11729
13047
  harness,
11730
13048
  reason: `system ONNX Runtime at ${harness.onnxRuntime.systemPath} is v${harness.onnxRuntime.systemVersion}, but AFT requires ${harness.onnxRuntime.requirement}, and no AFT-managed install is present. AFT v0.19.5+ skips incompatible system installs and auto-downloads v1.24 on next start; clearing any stale state here ensures a clean slate.`,
11731
13049
  storageOnnxDir,
11732
- storageOnnxBytes: existsSync12(storageOnnxDir) ? dirSize(storageOnnxDir) : 0
13050
+ storageOnnxBytes: existsSync13(storageOnnxDir) ? dirSize(storageOnnxDir) : 0
11733
13051
  });
11734
13052
  }
11735
13053
  }
@@ -11759,7 +13077,7 @@ async function runOnnxFix(adapters, report, options = {}) {
11759
13077
  const result = { cleared: 0, bytesReclaimed: 0, errors: [] };
11760
13078
  const rmFn = options.rmFn ?? rmSync3;
11761
13079
  for (const c2 of candidates) {
11762
- if (!existsSync12(c2.storageOnnxDir)) {
13080
+ if (!existsSync13(c2.storageOnnxDir)) {
11763
13081
  O2.success(`${c2.harness.displayName}: no cached state to clear; restart your harness to trigger a fresh ONNX download`);
11764
13082
  continue;
11765
13083
  }
@@ -11785,10 +13103,10 @@ var init_onnx_fix = __esm(() => {
11785
13103
  });
11786
13104
 
11787
13105
  // src/lib/sessions.ts
11788
- import { existsSync as existsSync13, readdirSync as readdirSync6, readFileSync as readFileSync4, statSync as statSync8 } from "node:fs";
13106
+ import { existsSync as existsSync14, readdirSync as readdirSync7, readFileSync as readFileSync4, statSync as statSync9 } from "node:fs";
11789
13107
  import { createRequire as createRequire3 } from "node:module";
11790
- import { homedir as homedir7 } from "node:os";
11791
- import { basename as basename2, join as join11 } from "node:path";
13108
+ import { homedir as homedir9 } from "node:os";
13109
+ import { basename as basename2, join as join13 } from "node:path";
11792
13110
  function listRecentSessions(adapter) {
11793
13111
  try {
11794
13112
  if (adapter.kind === "opencode")
@@ -11817,8 +13135,8 @@ function mapOpenCodeSessionRows(rows) {
11817
13135
  }).filter((session) => session !== null).sort((a, b) => b.lastActivity - a.lastActivity).slice(0, MAX_RECENT_SESSIONS);
11818
13136
  }
11819
13137
  function listRecentOpenCodeSessions() {
11820
- const dbPath = join11(getXdgDataHome(), "opencode", "opencode.db");
11821
- if (!existsSync13(dbPath))
13138
+ const dbPath = join13(getXdgDataHome(), "opencode", "opencode.db");
13139
+ if (!existsSync14(dbPath))
11822
13140
  return [];
11823
13141
  let db = null;
11824
13142
  try {
@@ -11837,22 +13155,22 @@ function listRecentOpenCodeSessions() {
11837
13155
  }
11838
13156
  function getXdgDataHome() {
11839
13157
  const xdgDataHome = process.env.XDG_DATA_HOME;
11840
- return xdgDataHome && xdgDataHome.length > 0 ? xdgDataHome : join11(homedir7(), ".local", "share");
13158
+ return xdgDataHome && xdgDataHome.length > 0 ? xdgDataHome : join13(homedir9(), ".local", "share");
11841
13159
  }
11842
13160
  function listRecentPiSessions() {
11843
- return listPiSessionsFromDir(join11(getHomeDir(), ".pi", "agent", "sessions"));
13161
+ return listPiSessionsFromDir(join13(getHomeDir(), ".pi", "agent", "sessions"));
11844
13162
  }
11845
13163
  function getHomeDir() {
11846
13164
  const envHome = process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME;
11847
- return envHome && envHome.length > 0 ? envHome : homedir7();
13165
+ return envHome && envHome.length > 0 ? envHome : homedir9();
11848
13166
  }
11849
13167
  function listPiSessionsFromDir(sessionsDir) {
11850
13168
  try {
11851
- if (!existsSync13(sessionsDir))
13169
+ if (!existsSync14(sessionsDir))
11852
13170
  return [];
11853
13171
  const files = collectJsonlFiles(sessionsDir).map((filePath) => {
11854
13172
  try {
11855
- const stats = statSync8(filePath);
13173
+ const stats = statSync9(filePath);
11856
13174
  return { filePath, mtimeMs: stats.mtimeMs };
11857
13175
  } catch {
11858
13176
  return null;
@@ -11881,12 +13199,12 @@ function collectJsonlFiles(root) {
11881
13199
  continue;
11882
13200
  let entries;
11883
13201
  try {
11884
- entries = readdirSync6(dir, { withFileTypes: true });
13202
+ entries = readdirSync7(dir, { withFileTypes: true });
11885
13203
  } catch {
11886
13204
  continue;
11887
13205
  }
11888
13206
  for (const entry of entries) {
11889
- const path = join11(dir, entry.name);
13207
+ const path = join13(dir, entry.name);
11890
13208
  if (entry.isDirectory()) {
11891
13209
  stack.push(path);
11892
13210
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -11983,19 +13301,20 @@ __export(exports_doctor, {
11983
13301
  DOCTOR_FORCE_CLEAR_TARGETS: () => DOCTOR_FORCE_CLEAR_TARGETS,
11984
13302
  DOCTOR_CLEAR_TARGET_OPTIONS: () => DOCTOR_CLEAR_TARGET_OPTIONS
11985
13303
  });
13304
+ import { execFileSync } from "node:child_process";
11986
13305
  import {
11987
- chmodSync,
11988
- existsSync as existsSync14,
11989
- mkdirSync as mkdirSync2,
13306
+ chmodSync as chmodSync2,
13307
+ existsSync as existsSync15,
13308
+ mkdirSync as mkdirSync3,
11990
13309
  mkdtempSync,
11991
13310
  readFileSync as readFileSync5,
11992
- realpathSync as realpathSync3,
13311
+ realpathSync as realpathSync4,
11993
13312
  rmSync as rmSync4,
11994
- statSync as statSync9,
13313
+ statSync as statSync10,
11995
13314
  writeFileSync as writeFileSync2
11996
13315
  } from "node:fs";
11997
13316
  import { tmpdir as tmpdir2 } from "node:os";
11998
- import { join as join12 } from "node:path";
13317
+ import { join as join14 } from "node:path";
11999
13318
  async function runDoctor(options) {
12000
13319
  if (options.issue) {
12001
13320
  return runIssueFlow(options.argv);
@@ -12149,7 +13468,7 @@ function clearOldBinaries() {
12149
13468
  errors: [],
12150
13469
  keptVersion: keepTag
12151
13470
  };
12152
- if (!existsSync14(info.path)) {
13471
+ if (!existsSync15(info.path)) {
12153
13472
  O2.info(`Binary cache: nothing to clear at ${info.path}`);
12154
13473
  return result;
12155
13474
  }
@@ -12159,10 +13478,10 @@ function clearOldBinaries() {
12159
13478
  return result;
12160
13479
  }
12161
13480
  for (const version of stale) {
12162
- const dir = join12(info.path, version);
13481
+ const dir = join14(info.path, version);
12163
13482
  let bytes = 0;
12164
13483
  try {
12165
- bytes = statSync9(dir).isDirectory() ? dirSize(dir) : 0;
13484
+ bytes = statSync10(dir).isDirectory() ? dirSize(dir) : 0;
12166
13485
  } catch {
12167
13486
  bytes = 0;
12168
13487
  }
@@ -12182,6 +13501,31 @@ function clearOldBinaries() {
12182
13501
  }
12183
13502
  return result;
12184
13503
  }
13504
+ function findPluginUpdateTargets(adapters, report) {
13505
+ const adaptersByKind = new Map(adapters.map((a) => [a.kind, a]));
13506
+ const targets = [];
13507
+ for (const harness of report.harnesses) {
13508
+ if (harness.kind !== "opencode")
13509
+ continue;
13510
+ if (!harness.hostInstalled || !harness.pluginRegistered)
13511
+ continue;
13512
+ const cache = harness.pluginCache;
13513
+ if (!cache?.exists || !cache.cached || !cache.latest)
13514
+ continue;
13515
+ if (cache.cached === cache.latest)
13516
+ continue;
13517
+ const adapter = adaptersByKind.get(harness.kind);
13518
+ if (!adapter)
13519
+ continue;
13520
+ targets.push({
13521
+ adapter,
13522
+ installDir: cache.path,
13523
+ cached: cache.cached,
13524
+ latest: cache.latest
13525
+ });
13526
+ }
13527
+ return targets;
13528
+ }
12185
13529
  function findSchemaFixTargets(adapters) {
12186
13530
  const targets = [];
12187
13531
  for (const adapter of adapters) {
@@ -12201,6 +13545,35 @@ function findSchemaFixTargets(adapters) {
12201
13545
  }
12202
13546
  return targets;
12203
13547
  }
13548
+ async function applyPluginUpdates(targets) {
13549
+ let updated = 0;
13550
+ let errors = 0;
13551
+ if (targets.length === 0)
13552
+ return { updated, errors };
13553
+ const npm = resolveNpm();
13554
+ if (!npm) {
13555
+ errors += targets.length;
13556
+ O2.error("Could not find npm on PATH or in known version-manager locations, so the plugin cannot be updated automatically. Install Node/npm, or launch your editor from a shell where npm is available.");
13557
+ return { updated, errors };
13558
+ }
13559
+ for (const target of targets) {
13560
+ try {
13561
+ execFileSync(npm.command, ["install", "--no-audit", "--no-fund", "--no-progress", "--ignore-scripts"], {
13562
+ cwd: target.installDir,
13563
+ env: npmSpawnEnv(npm),
13564
+ stdio: ["ignore", "pipe", "pipe"],
13565
+ timeout: 120000
13566
+ });
13567
+ updated += 1;
13568
+ O2.success(`${target.adapter.displayName}: plugin updated ${target.cached} → ${target.latest} (restart ${target.adapter.displayName} to apply)`);
13569
+ } catch (err) {
13570
+ errors += 1;
13571
+ const message = err instanceof Error ? err.message : String(err);
13572
+ O2.error(`${target.adapter.displayName}: plugin update failed: ${message}`);
13573
+ }
13574
+ }
13575
+ return { updated, errors };
13576
+ }
12204
13577
  function applySchemaFixes(targets) {
12205
13578
  let changed = 0;
12206
13579
  let errors = 0;
@@ -12211,9 +13584,9 @@ function applySchemaFixes(targets) {
12211
13584
  changed += 1;
12212
13585
  O2.success(`${target.adapter.displayName}: ${result.message}`);
12213
13586
  }
12214
- } catch (error) {
13587
+ } catch (error2) {
12215
13588
  errors += 1;
12216
- O2.warn(`${target.adapter.displayName}: could not set $schema on ${target.aftConfig}: ${error instanceof Error ? error.message : String(error)}`);
13589
+ O2.warn(`${target.adapter.displayName}: could not set $schema on ${target.aftConfig}: ${error2 instanceof Error ? error2.message : String(error2)}`);
12217
13590
  }
12218
13591
  }
12219
13592
  return { changed, errors };
@@ -12237,6 +13610,12 @@ function buildDoctorFixPlan(adapters, report) {
12237
13610
  });
12238
13611
  }
12239
13612
  }
13613
+ for (const target of findPluginUpdateTargets(adapters, report)) {
13614
+ items.push({
13615
+ kind: "plugin-update",
13616
+ message: `Will update ${target.adapter.displayName} plugin ${target.cached} → ${target.latest} via npm (the plugin's own auto-update could not run, often no npm on PATH)`
13617
+ });
13618
+ }
12240
13619
  if (!report.binaryVersion) {
12241
13620
  const skews = findPluginCliVersionSkews(report);
12242
13621
  items.push({
@@ -12330,6 +13709,7 @@ async function runFixFlow(argv) {
12330
13709
  }
12331
13710
  }
12332
13711
  await fixPluginEntries(adapters);
13712
+ const pluginUpdateSummary = await applyPluginUpdates(findPluginUpdateTargets(adapters, report));
12333
13713
  const storageSummary = ensureStorageDirsForRegisteredPlugins(adapters);
12334
13714
  const schemaSummary = applySchemaFixes(findSchemaFixTargets(adapters));
12335
13715
  let binaryDownloaded = false;
@@ -12343,8 +13723,8 @@ async function runFixFlow(argv) {
12343
13723
  O2.info("AFT binary not found. Downloading…");
12344
13724
  try {
12345
13725
  const bridgePackageName = "@cortexkit/aft-bridge";
12346
- const { ensureBinary } = await import(bridgePackageName);
12347
- const path = await ensureBinary(`v${report.cliVersion}`);
13726
+ const { ensureBinary: ensureBinary2 } = await import(bridgePackageName);
13727
+ const path = await ensureBinary2(`v${report.cliVersion}`);
12348
13728
  if (path) {
12349
13729
  O2.success(`AFT binary installed at ${path}`);
12350
13730
  binaryDownloaded = true;
@@ -12360,7 +13740,7 @@ async function runFixFlow(argv) {
12360
13740
  }
12361
13741
  }
12362
13742
  const onnxResult = await runOnnxFix(adapters, report, { yes: true });
12363
- if (onnxResult === null && !binaryDownloaded && !binaryDownloadSkipped && !binaryDownloadError && storageSummary.created === 0 && storageSummary.errors === 0 && schemaSummary.changed === 0 && schemaSummary.errors === 0) {
13743
+ if (onnxResult === null && !binaryDownloaded && !binaryDownloadSkipped && !binaryDownloadError && storageSummary.created === 0 && storageSummary.errors === 0 && schemaSummary.changed === 0 && schemaSummary.errors === 0 && pluginUpdateSummary.updated === 0 && pluginUpdateSummary.errors === 0) {
12364
13744
  O2.info("No auto-fixable issues detected.");
12365
13745
  wt("If you're still seeing 'Semantic Index: failed' in the TUI sidebar, run `aft doctor` (without --fix) for a full diagnostic dump.", "Tip");
12366
13746
  const afterReport2 = await collectDiagnostics(adapters);
@@ -12368,7 +13748,7 @@ async function runFixFlow(argv) {
12368
13748
  gt(stillHasProblems2 ? "Done — some issues remain." : "Done.");
12369
13749
  return stillHasProblems2 ? 1 : 0;
12370
13750
  }
12371
- const hadErrors = (onnxResult?.errors.length ?? 0) > 0 || binaryDownloadError !== null || storageSummary.errors > 0 || schemaSummary.errors > 0;
13751
+ const hadErrors = (onnxResult?.errors.length ?? 0) > 0 || binaryDownloadError !== null || storageSummary.errors > 0 || schemaSummary.errors > 0 || pluginUpdateSummary.errors > 0;
12372
13752
  const afterReport = await collectDiagnostics(adapters);
12373
13753
  const stillHasProblems = hasDoctorProblems(afterReport);
12374
13754
  gt(hadErrors ? "Done — some fixes failed." : stillHasProblems ? "Done — some issues remain." : "Done.");
@@ -12423,9 +13803,9 @@ function ensureStorageDirsForRegisteredPlugins(adapters) {
12423
13803
  if (!adapter.isInstalled() || !adapter.hasPluginEntry())
12424
13804
  continue;
12425
13805
  const storageDir = adapter.getStorageDir();
12426
- if (existsSync14(storageDir))
13806
+ if (existsSync15(storageDir))
12427
13807
  continue;
12428
- mkdirSync2(storageDir, { recursive: true });
13808
+ mkdirSync3(storageDir, { recursive: true });
12429
13809
  summary.created += 1;
12430
13810
  O2.success(`${adapter.displayName}: created AFT storage directory at ${storageDir}`);
12431
13811
  } catch (err) {
@@ -12526,14 +13906,14 @@ function deriveIssueTitleFromBody(body) {
12526
13906
  function writeIssueReviewFile(body) {
12527
13907
  let reviewDir = null;
12528
13908
  try {
12529
- reviewDir = mkdtempSync(join12(tmpdir2(), "aft-issue-"));
13909
+ reviewDir = mkdtempSync(join14(tmpdir2(), "aft-issue-"));
12530
13910
  if (process.platform !== "win32") {
12531
- chmodSync(reviewDir, 448);
13911
+ chmodSync2(reviewDir, 448);
12532
13912
  }
12533
- const outPath = join12(reviewDir, "issue.md");
13913
+ const outPath = join14(reviewDir, "issue.md");
12534
13914
  writeFileSync2(outPath, `${body}
12535
13915
  `, { encoding: "utf8", mode: 384, flag: "wx" });
12536
- return { path: outPath, realPath: realpathSync3(outPath) };
13916
+ return { path: outPath, realPath: realpathSync4(outPath) };
12537
13917
  } catch (err) {
12538
13918
  if (reviewDir) {
12539
13919
  try {
@@ -12546,7 +13926,7 @@ function writeIssueReviewFile(body) {
12546
13926
  }
12547
13927
  function readReviewedIssueFile(reviewFile) {
12548
13928
  try {
12549
- const realPath = realpathSync3(reviewFile.path);
13929
+ const realPath = realpathSync4(reviewFile.path);
12550
13930
  if (realPath !== reviewFile.realPath) {
12551
13931
  O2.error(`Review file path changed before filing; refusing to read ${reviewFile.path}.`);
12552
13932
  return null;
@@ -12688,6 +14068,7 @@ https://github.com/cortexkit/aft/issues/new and paste the contents of ${outPath}
12688
14068
  }
12689
14069
  var DOCTOR_CLEAR_TARGET_OPTIONS, DOCTOR_FORCE_CLEAR_TARGETS;
12690
14070
  var init_doctor = __esm(async () => {
14071
+ init_dist();
12691
14072
  init_binary_cache();
12692
14073
  init_fs_util();
12693
14074
  init_github();