codebuff 1.0.683 → 1.0.685

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/index.js CHANGED
@@ -1,947 +1,34 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const { spawn, execFileSync } = require('child_process')
4
3
  const fs = require('fs')
5
- const http = require('http')
6
- const https = require('https')
7
- const os = require('os')
8
4
  const path = require('path')
9
- const zlib = require('zlib')
10
5
 
11
- const tar = require('tar')
12
- const { createReleaseHttpClient } = require('./http')
13
-
14
- const packageName = 'codebuff'
15
-
16
- /**
17
- * Terminal escape sequences to reset terminal state after the child process exits.
18
- * When the binary is SIGKILL'd, it can't clean up its own terminal state.
19
- * The wrapper (this process) survives and must reset these modes.
20
- */
21
- const EXIT_ALTERNATE_SCREEN_SEQUENCE = '\x1b[?1049l'
22
- const SAFE_TERMINAL_RESET_SEQUENCES =
23
- '\x1b[?1000l' + // Disable X10 mouse mode
24
- '\x1b[?1002l' + // Disable button event mouse mode
25
- '\x1b[?1003l' + // Disable any-event mouse mode (all motion)
26
- '\x1b[?1006l' + // Disable SGR extended mouse mode
27
- '\x1b[?1004l' + // Disable focus reporting
28
- '\x1b[?2004l' + // Disable bracketed paste mode
29
- '\x1b[?25h' // Show cursor
30
-
31
- const FULL_TERMINAL_RESET_SEQUENCES =
32
- EXIT_ALTERNATE_SCREEN_SEQUENCE + SAFE_TERMINAL_RESET_SEQUENCES
33
-
34
- function resetTerminal(options = {}) {
35
- const { exitAlternateScreen = false } = options
36
-
37
- try {
38
- if (process.stdin.isTTY && process.stdin.setRawMode) {
39
- process.stdin.setRawMode(false)
40
- }
41
- } catch {
42
- // stdin may be closed
43
- }
44
- try {
45
- if (process.stdout.isTTY) {
46
- // Exiting the alternate screen is only safe after an interactive child.
47
- // Plain CLI paths like --help never enter it, and ?1049l can erase output.
48
- process.stdout.write(
49
- exitAlternateScreen
50
- ? FULL_TERMINAL_RESET_SEQUENCES
51
- : SAFE_TERMINAL_RESET_SEQUENCES,
52
- )
53
- }
54
- } catch {
55
- // stdout may be closed
56
- }
57
- }
58
-
59
- function getUnsignedExitCode(code) {
60
- return code != null && code < 0 ? (code >>> 0) : code
61
- }
62
-
63
- function isWindowsNativeCrashCode(code) {
64
- const unsignedCode = getUnsignedExitCode(code)
65
- return (
66
- process.platform === 'win32' &&
67
- (unsignedCode === 0xC000001D ||
68
- unsignedCode === 0xC0000005 ||
69
- unsignedCode === 0xC0000409)
70
- )
71
- }
72
-
73
- function shouldExitAlternateScreen(code, signal) {
74
- return Boolean(signal) || isWindowsNativeCrashCode(code)
75
- }
76
-
77
- function isIllegalInstructionExit(code, signal) {
78
- const unsignedCode = getUnsignedExitCode(code)
79
- return (
80
- signal === 'SIGILL' ||
81
- (process.platform === 'win32' && unsignedCode === 0xC000001D)
82
- )
83
- }
84
-
85
- function createConfig(packageName) {
86
- const homeDir = os.homedir()
87
- const configDir = path.join(homeDir, '.config', 'manicode')
88
- const binaryName =
89
- process.platform === 'win32' ? `${packageName}.exe` : packageName
90
-
91
- return {
92
- homeDir,
93
- configDir,
94
- binaryName,
95
- binaryPath: path.join(configDir, binaryName),
96
- metadataPath: path.join(configDir, 'codebuff-metadata.json'),
97
- tempDownloadDir: path.join(configDir, '.download-temp'),
98
- userAgent: `${packageName}-cli`,
99
- requestTimeout: 20000,
100
- }
101
- }
102
-
103
- const CONFIG = createConfig(packageName)
104
- const { getProxyUrl, httpGet } = createReleaseHttpClient({
105
- env: process.env,
106
- userAgent: CONFIG.userAgent,
107
- requestTimeout: CONFIG.requestTimeout,
6
+ const packagedLauncherPath = path.join(__dirname, 'launcher.js')
7
+ const sourceLauncherPath = path.join(
8
+ __dirname,
9
+ '..',
10
+ 'release-core',
11
+ 'launcher.js',
12
+ )
13
+ // Published packages must not let an unrelated sibling path shadow their
14
+ // bundled launcher. Source checkouts only fall back when that copy is absent.
15
+ const { createLauncher } = require(
16
+ fs.existsSync(packagedLauncherPath)
17
+ ? packagedLauncherPath
18
+ : sourceLauncherPath,
19
+ )
20
+
21
+ const launcher = createLauncher({
22
+ packageName: 'codebuff',
23
+ displayName: 'Codebuff',
24
+ tempDownloadDirName: '.download-temp',
108
25
  })
109
26
 
110
- function getPostHogConfig() {
111
- const apiKey =
112
- process.env.CODEBUFF_POSTHOG_API_KEY ||
113
- process.env.NEXT_PUBLIC_POSTHOG_API_KEY
114
- const host =
115
- process.env.CODEBUFF_POSTHOG_HOST ||
116
- process.env.NEXT_PUBLIC_POSTHOG_HOST_URL
117
-
118
- if (!apiKey || !host) {
119
- return null
120
- }
121
-
122
- return { apiKey, host }
123
- }
124
-
125
- /**
126
- * Track update failure event to PostHog.
127
- * Fire-and-forget - errors are silently ignored.
128
- */
129
- function trackUpdateFailed(errorMessage, version, context = {}) {
130
- try {
131
- const posthogConfig = getPostHogConfig()
132
- if (!posthogConfig) {
133
- return
134
- }
135
-
136
- const payload = JSON.stringify({
137
- api_key: posthogConfig.apiKey,
138
- event: 'cli.update_codebuff_failed',
139
- properties: {
140
- distinct_id: `anonymous-${CONFIG.homeDir}`,
141
- error: errorMessage,
142
- version: version || 'unknown',
143
- platform: process.platform,
144
- arch: process.arch,
145
- ...context,
146
- },
147
- timestamp: new Date().toISOString(),
148
- })
149
-
150
- const parsedUrl = new URL(`${posthogConfig.host}/capture/`)
151
- const isHttps = parsedUrl.protocol === 'https:'
152
- const options = {
153
- hostname: parsedUrl.hostname,
154
- port: parsedUrl.port || (isHttps ? 443 : 80),
155
- path: parsedUrl.pathname + parsedUrl.search,
156
- method: 'POST',
157
- headers: {
158
- 'Content-Type': 'application/json',
159
- 'Content-Length': Buffer.byteLength(payload),
160
- },
161
- }
162
-
163
- const transport = isHttps ? https : http
164
- const req = transport.request(options)
165
- req.on('error', () => {}) // Silently ignore errors
166
- req.write(payload)
167
- req.end()
168
- } catch (e) {
169
- // Silently ignore any tracking errors
170
- }
171
- }
172
-
173
- const PLATFORM_TARGETS = {
174
- 'linux-x64': `${packageName}-linux-x64.tar.gz`,
175
- 'linux-x64-baseline': `${packageName}-linux-x64-baseline.tar.gz`,
176
- 'linux-arm64': `${packageName}-linux-arm64.tar.gz`,
177
- 'darwin-x64': `${packageName}-darwin-x64.tar.gz`,
178
- 'darwin-arm64': `${packageName}-darwin-arm64.tar.gz`,
179
- 'win32-x64': `${packageName}-win32-x64.tar.gz`,
180
- 'win32-x64-baseline': `${packageName}-win32-x64-baseline.tar.gz`,
181
- }
182
-
183
- const BASELINE_FALLBACK_TARGETS = {
184
- 'linux-x64': 'linux-x64-baseline',
185
- 'win32-x64': 'win32-x64-baseline',
186
- }
187
-
188
- const term = {
189
- clearLine: () => {
190
- if (process.stderr.isTTY) {
191
- process.stderr.write('\r\x1b[K')
192
- }
193
- },
194
- write: (text) => {
195
- term.clearLine()
196
- process.stderr.write(text)
197
- },
198
- writeLine: (text) => {
199
- term.clearLine()
200
- process.stderr.write(text + '\n')
201
- },
202
- }
203
-
204
- function getPlatformKey() {
205
- return `${process.platform}-${process.arch}`
206
- }
207
-
208
- function getTargetOverride() {
209
- const envNames = [
210
- `${packageName.toUpperCase()}_BINARY_TARGET`,
211
- 'CODEBUFF_BINARY_TARGET',
212
- 'CLI_BINARY_TARGET',
213
- ]
214
-
215
- for (const envName of envNames) {
216
- const target = process.env[envName]
217
- if (target && PLATFORM_TARGETS[target]) {
218
- return target
219
- }
220
- }
221
-
222
- return null
223
- }
224
-
225
- function linuxCpuHasAvx2() {
226
- try {
227
- return /\bavx2\b/i.test(fs.readFileSync('/proc/cpuinfo', 'utf8'))
228
- } catch {
229
- return true
230
- }
231
- }
232
-
233
- // Returns true (AVX2 present), false (absent), or null (couldn't determine).
234
- // Ask the OS directly via IsProcessorFeaturePresent (kernel32), which is
235
- // backed by CPUID — far more reliable than matching CPU model names, and it
236
- // works on the stock Windows PowerShell that ships with every supported
237
- // Windows version. Feature 40 = PF_AVX2_INSTRUCTIONS_AVAILABLE.
238
- function probeWindowsAvx2() {
239
- const script =
240
- "$f = Add-Type -MemberDefinition '[DllImport(\"kernel32.dll\")] " +
241
- "public static extern bool IsProcessorFeaturePresent(uint feature);' " +
242
- "-Name Cpu -Namespace Win32 -PassThru; $f::IsProcessorFeaturePresent(40)"
243
- try {
244
- const out = execFileSync(
245
- 'powershell.exe',
246
- ['-NoProfile', '-NonInteractive', '-Command', script],
247
- { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] },
248
- ).trim()
249
- if (out === 'True') return true
250
- if (out === 'False') return false
251
- return null
252
- } catch {
253
- // No PowerShell, locked-down policy, timeout, etc. — inconclusive.
254
- return null
255
- }
256
- }
257
-
258
- let _hasAvx2Cache
259
-
260
- function machineHasAvx2() {
261
- if (_hasAvx2Cache === undefined) {
262
- _hasAvx2Cache = detectMachineHasAvx2()
263
- }
264
- return _hasAvx2Cache
265
- }
266
-
267
- function detectMachineHasAvx2() {
268
- if (process.arch !== 'x64') {
269
- return true
270
- }
271
-
272
- // Linux detection is a cheap file read, so we don't bother persisting it.
273
- if (process.platform === 'linux') {
274
- return linuxCpuHasAvx2()
275
- }
276
-
277
- if (process.platform !== 'win32') {
278
- return true
279
- }
280
-
281
- // Windows detection shells out to PowerShell. getDefaultTargetKey runs on
282
- // every launch (via the version check), so cache the result on disk to keep
283
- // startup fast after the first probe.
284
- const cached = readCachedAvx2()
285
- if (cached !== null) {
286
- return cached
287
- }
288
- const detected = probeWindowsAvx2()
289
- if (detected === null) {
290
- // Inconclusive probe: assume AVX2 for this launch and rely on the SIGILL
291
- // fallback, but don't persist it — a transient failure must not lock in a
292
- // wrong answer for the lifetime of the install. We'll re-probe next launch.
293
- return true
294
- }
295
- writeCachedAvx2(detected)
296
- return detected
297
- }
298
-
299
- function getCpuFeatureCachePath() {
300
- return path.join(CONFIG.configDir, 'cpu-features.json')
301
- }
302
-
303
- function readCachedAvx2() {
304
- try {
305
- const cache = JSON.parse(fs.readFileSync(getCpuFeatureCachePath(), 'utf8'))
306
- return typeof cache.avx2 === 'boolean' ? cache.avx2 : null
307
- } catch {
308
- return null
309
- }
310
- }
311
-
312
- function writeCachedAvx2(value) {
313
- try {
314
- fs.mkdirSync(CONFIG.configDir, { recursive: true })
315
- fs.writeFileSync(getCpuFeatureCachePath(), JSON.stringify({ avx2: value }))
316
- } catch {
317
- // Best effort; we'll just re-probe next launch.
318
- }
319
- }
320
-
321
- function getDefaultTargetKey() {
322
- const override = getTargetOverride()
323
- if (override) {
324
- return override
325
- }
326
-
327
- const platformKey = getPlatformKey()
328
- // Select the binary up front from explicit CPU feature detection rather than
329
- // optimistically launching the AVX2 build and waiting for it to crash with
330
- // an illegal instruction. The crash isn't always a clean immediate failure —
331
- // it can surface later from a deeper code path — so older CPUs (e.g. an
332
- // Intel Xeon with AVX but no AVX2) are safer on baseline from the start.
333
- //
334
- // This assumes every baseline target is gated on AVX2 specifically, which
335
- // holds today (only linux-x64 and win32-x64 have baseline builds, both
336
- // AVX2-gated). If a baseline build is ever added for a different reason, give
337
- // BASELINE_FALLBACK_TARGETS a per-target capability and check that instead.
338
- if (BASELINE_FALLBACK_TARGETS[platformKey] && !machineHasAvx2()) {
339
- return BASELINE_FALLBACK_TARGETS[platformKey]
340
- }
341
-
342
- return platformKey
343
- }
344
-
345
- function getBaselineFallbackTargetKey() {
346
- // Runtime safety net: if proactive detection was unavailable or wrong and the
347
- // optimized binary still dies with SIGILL, fall back to baseline.
348
- return BASELINE_FALLBACK_TARGETS[getPlatformKey()] || null
349
- }
350
-
351
- function isTargetAllowedForThisMachine(target) {
352
- const override = getTargetOverride()
353
- if (override) {
354
- return target === override
355
- }
356
- // Check the baseline fallback first: it's always safe on its platform and
357
- // avoids running CPU detection when a baseline binary is already installed.
358
- return (
359
- target === getBaselineFallbackTargetKey() ||
360
- target === getDefaultTargetKey()
361
- )
362
- }
363
-
364
- function getDownloadTargetKey() {
365
- const override = getTargetOverride()
366
- if (override) {
367
- return override
368
- }
369
-
370
- const metadata = getCurrentMetadata()
371
- if (metadata?.target && isTargetAllowedForThisMachine(metadata.target)) {
372
- return metadata.target
373
- }
374
-
375
- return getDefaultTargetKey()
376
- }
377
-
378
- async function getLatestVersion() {
379
- try {
380
- const res = await httpGet(
381
- `https://registry.npmjs.org/${packageName}/latest`,
382
- )
383
-
384
- if (res.statusCode !== 200) return null
385
-
386
- const body = await streamToString(res)
387
- const packageData = JSON.parse(body)
388
-
389
- return packageData.version || null
390
- } catch (error) {
391
- return null
392
- }
393
- }
394
-
395
- function streamToString(stream) {
396
- return new Promise((resolve, reject) => {
397
- let data = ''
398
- stream.on('data', (chunk) => (data += chunk))
399
- stream.on('end', () => resolve(data))
400
- stream.on('error', reject)
401
- })
402
- }
403
-
404
- function getCurrentVersion() {
405
- try {
406
- const metadata = getCurrentMetadata()
407
- if (!metadata) {
408
- return null
409
- }
410
- // Also verify the binary still exists
411
- if (!fs.existsSync(CONFIG.binaryPath)) {
412
- return null
413
- }
414
- const metadataTarget = metadata.target || getPlatformKey()
415
- if (!isTargetAllowedForThisMachine(metadataTarget)) {
416
- return null
417
- }
418
- return metadata.version || null
419
- } catch (error) {
420
- return null
421
- }
422
- }
423
-
424
- function getCurrentMetadata() {
425
- try {
426
- if (!fs.existsSync(CONFIG.metadataPath)) {
427
- return null
428
- }
429
- return JSON.parse(fs.readFileSync(CONFIG.metadataPath, 'utf8'))
430
- } catch {
431
- return null
432
- }
433
- }
434
-
435
- function compareVersions(v1, v2) {
436
- if (!v1 || !v2) return 0
437
-
438
- // Always update if the current version is not a valid semver
439
- // e.g. 1.0.420-beta.1
440
- if (!v1.match(/^\d+(\.\d+)*$/)) {
441
- return -1
442
- }
443
-
444
- const parseVersion = (version) => {
445
- const parts = version.split('-')
446
- const mainParts = parts[0].split('.').map(Number)
447
- const prereleaseParts = parts[1] ? parts[1].split('.') : []
448
- return { main: mainParts, prerelease: prereleaseParts }
449
- }
450
-
451
- const p1 = parseVersion(v1)
452
- const p2 = parseVersion(v2)
453
-
454
- for (let i = 0; i < Math.max(p1.main.length, p2.main.length); i++) {
455
- const n1 = p1.main[i] || 0
456
- const n2 = p2.main[i] || 0
27
+ module.exports = launcher
457
28
 
458
- if (n1 < n2) return -1
459
- if (n1 > n2) return 1
460
- }
461
-
462
- if (p1.prerelease.length === 0 && p2.prerelease.length === 0) {
463
- return 0
464
- } else if (p1.prerelease.length === 0) {
465
- return 1
466
- } else if (p2.prerelease.length === 0) {
467
- return -1
468
- } else {
469
- for (
470
- let i = 0;
471
- i < Math.max(p1.prerelease.length, p2.prerelease.length);
472
- i++
473
- ) {
474
- const pr1 = p1.prerelease[i] || ''
475
- const pr2 = p2.prerelease[i] || ''
476
-
477
- const isNum1 = !isNaN(parseInt(pr1))
478
- const isNum2 = !isNaN(parseInt(pr2))
479
-
480
- if (isNum1 && isNum2) {
481
- const num1 = parseInt(pr1)
482
- const num2 = parseInt(pr2)
483
- if (num1 < num2) return -1
484
- if (num1 > num2) return 1
485
- } else if (isNum1 && !isNum2) {
486
- return 1
487
- } else if (!isNum1 && isNum2) {
488
- return -1
489
- } else if (pr1 < pr2) {
490
- return -1
491
- } else if (pr1 > pr2) {
492
- return 1
493
- }
494
- }
495
- return 0
496
- }
497
- }
498
-
499
- function formatBytes(bytes) {
500
- if (bytes === 0) return '0 B'
501
- const k = 1024
502
- const sizes = ['B', 'KB', 'MB', 'GB']
503
- const i = Math.floor(Math.log(bytes) / Math.log(k))
504
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
505
- }
506
-
507
- function createProgressBar(percentage, width = 30) {
508
- const filled = Math.round((width * percentage) / 100)
509
- const empty = width - filled
510
- return '[' + '█'.repeat(filled) + '░'.repeat(empty) + ']'
511
- }
512
-
513
- async function downloadBinary(version, targetKey = getDownloadTargetKey()) {
514
- const fileName = PLATFORM_TARGETS[targetKey]
515
-
516
- if (!fileName) {
517
- const error = new Error(`Unsupported platform: ${process.platform} ${process.arch}`)
518
- trackUpdateFailed(error.message, version, { stage: 'platform_check', target: targetKey })
519
- throw error
520
- }
521
-
522
- const downloadUrl = `${
523
- process.env.NEXT_PUBLIC_CODEBUFF_APP_URL || 'https://codebuff.com'
524
- }/api/releases/download/${version}/${fileName}`
525
-
526
- // Ensure config directory exists
527
- fs.mkdirSync(CONFIG.configDir, { recursive: true })
528
-
529
- // Clean up any previous temp download directory
530
- if (fs.existsSync(CONFIG.tempDownloadDir)) {
531
- fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
532
- }
533
- fs.mkdirSync(CONFIG.tempDownloadDir, { recursive: true })
534
-
535
- term.write('Downloading...')
536
-
537
- const res = await httpGet(downloadUrl)
538
-
539
- if (res.statusCode !== 200) {
540
- fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
541
- const error = new Error(`Download failed: HTTP ${res.statusCode}`)
542
- trackUpdateFailed(error.message, version, { stage: 'http_download', statusCode: res.statusCode, target: targetKey })
543
- throw error
544
- }
545
-
546
- const totalSize = parseInt(res.headers['content-length'] || '0', 10)
547
- let downloadedSize = 0
548
- let lastProgressTime = Date.now()
549
-
550
- res.on('data', (chunk) => {
551
- downloadedSize += chunk.length
552
- const now = Date.now()
553
- if (now - lastProgressTime >= 100 || downloadedSize === totalSize) {
554
- lastProgressTime = now
555
- if (totalSize > 0) {
556
- const pct = Math.round((downloadedSize / totalSize) * 100)
557
- term.write(
558
- `Downloading... ${createProgressBar(pct)} ${pct}% of ${formatBytes(
559
- totalSize,
560
- )}`,
561
- )
562
- } else {
563
- term.write(`Downloading... ${formatBytes(downloadedSize)}`)
564
- }
565
- }
566
- })
567
-
568
- // Extract to temp directory
569
- await new Promise((resolve, reject) => {
570
- res
571
- .pipe(zlib.createGunzip())
572
- .pipe(tar.x({ cwd: CONFIG.tempDownloadDir }))
573
- .on('finish', resolve)
574
- .on('error', reject)
575
- })
576
-
577
- const tempBinaryPath = path.join(CONFIG.tempDownloadDir, CONFIG.binaryName)
578
-
579
- // Verify the binary was extracted
580
- if (!fs.existsSync(tempBinaryPath)) {
581
- const files = fs.readdirSync(CONFIG.tempDownloadDir)
582
- fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
583
- const error = new Error(
584
- `Binary not found after extraction. Expected: ${CONFIG.binaryName}, Available files: ${files.join(', ')}`,
585
- )
586
- trackUpdateFailed(error.message, version, { stage: 'extraction', target: targetKey })
587
- throw error
588
- }
589
-
590
- // Set executable permissions
591
- if (process.platform !== 'win32') {
592
- fs.chmodSync(tempBinaryPath, 0o755)
593
- }
594
-
595
- // Move binary to final location
596
- try {
597
- if (fs.existsSync(CONFIG.binaryPath)) {
598
- try {
599
- fs.unlinkSync(CONFIG.binaryPath)
600
- } catch (err) {
601
- // Fallback: try renaming the locked/undeletable binary (Windows)
602
- const backupPath = CONFIG.binaryPath + `.old.${Date.now()}`
603
- try {
604
- fs.renameSync(CONFIG.binaryPath, backupPath)
605
- } catch (renameErr) {
606
- throw new Error(
607
- `Failed to replace existing binary. ` +
608
- `unlink error: ${err.code || err.message}, ` +
609
- `rename error: ${renameErr.code || renameErr.message}`,
610
- )
611
- }
612
- }
613
- }
614
- fs.renameSync(tempBinaryPath, CONFIG.binaryPath)
615
-
616
- // Move tree-sitter.wasm next to the binary if the tarball included
617
- // it. The CLI binary loads this at startup; embedding it inside the
618
- // binary itself was unreliable on Windows (bun --compile asset
619
- // bundling silently dropped or unbound it across several attempts),
620
- // so we ship it as a sibling file instead. Older artifacts that
621
- // pre-date this change won't have the wasm and will still install —
622
- // they'll just hit the same crash they had before, which is fine.
623
- const tempWasmPath = path.join(CONFIG.tempDownloadDir, 'tree-sitter.wasm')
624
- if (fs.existsSync(tempWasmPath)) {
625
- const targetWasmPath = path.join(
626
- path.dirname(CONFIG.binaryPath),
627
- 'tree-sitter.wasm',
628
- )
629
- try {
630
- if (fs.existsSync(targetWasmPath)) fs.unlinkSync(targetWasmPath)
631
- } catch {
632
- // best effort; rename below will surface the real error if it matters
633
- }
634
- fs.renameSync(tempWasmPath, targetWasmPath)
635
- }
636
-
637
- // Save version metadata for fast version checking
638
- fs.writeFileSync(
639
- CONFIG.metadataPath,
640
- JSON.stringify({ version, target: targetKey }, null, 2),
641
- )
642
- } finally {
643
- // Clean up temp directory even if rename fails
644
- if (fs.existsSync(CONFIG.tempDownloadDir)) {
645
- fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
646
- }
647
- }
648
-
649
- term.clearLine()
650
- console.log('Download complete! Starting Codebuff...')
651
- }
652
-
653
- async function ensureBinaryExists() {
654
- const currentVersion = getCurrentVersion()
655
- if (currentVersion !== null) {
656
- return
657
- }
658
-
659
- const version = await getLatestVersion()
660
- if (!version) {
661
- console.error('❌ Failed to determine latest version')
662
- console.error('Please check your internet connection and try again')
663
- if (!getProxyUrl()) {
664
- console.error(
665
- 'If you are behind a proxy, set the HTTPS_PROXY environment variable',
666
- )
667
- }
668
- process.exit(1)
669
- }
670
-
671
- try {
672
- await downloadBinary(version)
673
- } catch (error) {
674
- term.clearLine()
675
- console.error('❌ Failed to download codebuff:', error.message)
676
- console.error('Please check your internet connection and try again')
677
- if (!getProxyUrl()) {
678
- console.error(
679
- 'If you are behind a proxy, set the HTTPS_PROXY environment variable',
680
- )
681
- }
29
+ if (require.main === module) {
30
+ launcher.main().catch((error) => {
31
+ console.error('❌ Unexpected error:', error.message)
682
32
  process.exit(1)
683
- }
684
- }
685
-
686
- async function checkForUpdates(runningProcess, exitListener) {
687
- try {
688
- const currentVersion = getCurrentVersion()
689
-
690
- const latestVersion = await getLatestVersion()
691
- if (!latestVersion) return
692
-
693
- if (
694
- // Download new version if current version is unknown or outdated.
695
- currentVersion === null ||
696
- compareVersions(currentVersion, latestVersion) < 0
697
- ) {
698
- term.clearLine()
699
-
700
- runningProcess.removeListener('exit', exitListener)
701
-
702
- await new Promise((resolve) => {
703
- let exited = false
704
- runningProcess.once('exit', () => {
705
- exited = true
706
- resolve()
707
- })
708
- runningProcess.kill('SIGTERM')
709
- setTimeout(() => {
710
- if (!exited) {
711
- runningProcess.kill('SIGKILL')
712
- // Safety: resolve after giving SIGKILL time to take effect
713
- setTimeout(() => resolve(), 1000)
714
- }
715
- }, 5000)
716
- })
717
-
718
- resetTerminal({ exitAlternateScreen: true })
719
- console.log(`Update available: ${currentVersion} → ${latestVersion}`)
720
-
721
- await downloadBinary(latestVersion)
722
-
723
- const newChild = spawnInstalledBinary({ detached: false })
724
- attachExitHandler(newChild)
725
-
726
- return new Promise(() => {})
727
- }
728
- } catch (error) {
729
- // Ignore update failures
730
- }
731
- }
732
-
733
- function printCrashDiagnostics(code, signal) {
734
- // Windows NTSTATUS codes (unsigned DWORD)
735
- const unsignedCode = getUnsignedExitCode(code)
736
- const isIllegalInstruction = isIllegalInstructionExit(code, signal)
737
- const isAccessViolation =
738
- signal === 'SIGSEGV' ||
739
- (process.platform === 'win32' && unsignedCode === 0xC0000005)
740
- const isBusError = signal === 'SIGBUS'
741
- const isAbort =
742
- signal === 'SIGABRT' ||
743
- (process.platform === 'win32' && unsignedCode === 0xC0000409)
744
-
745
- if (!isIllegalInstruction && !isAccessViolation && !isBusError && !isAbort) return
746
-
747
- const exitInfo = signal ? `signal ${signal}` : `code ${code}`
748
- console.error('')
749
- console.error(`❌ ${packageName} exited immediately (${exitInfo})`)
750
- console.error('')
751
-
752
- if (isIllegalInstruction) {
753
- console.error('Your CPU may not support the required instruction set (AVX2).')
754
- console.error('This typically affects CPUs from before 2013.')
755
- console.error('')
756
- printBaselineOverrideHint()
757
- } else if (isAccessViolation) {
758
- console.error('The binary crashed with an access violation.')
759
- console.error('')
760
- } else if (isBusError) {
761
- console.error('The binary crashed with a bus error.')
762
- console.error('This may indicate a platform compatibility issue.')
763
- console.error('')
764
- } else if (isAbort) {
765
- console.error('The binary crashed with an abort signal.')
766
- console.error('')
767
- }
768
-
769
- printSystemInfo()
770
- console.error('')
771
- console.error('Please report this issue at:')
772
- console.error(' https://github.com/CodebuffAI/codebuff/issues')
773
- console.error('')
774
- }
775
-
776
- function printBaselineOverrideHint() {
777
- const fallbackTarget = getBaselineFallbackTargetKey()
778
- if (!fallbackTarget) return
779
- console.error('To force the baseline (non-AVX2) build, set:')
780
- console.error(` ${packageName.toUpperCase()}_BINARY_TARGET=${fallbackTarget}`)
781
- console.error('')
782
- }
783
-
784
- function printSystemInfo() {
785
- const metadata = getCurrentMetadata()
786
- console.error('System info:')
787
- console.error(` Platform: ${process.platform} ${process.arch}`)
788
- console.error(` Node: ${process.version}`)
789
- if (process.arch === 'x64') {
790
- console.error(` AVX2: ${machineHasAvx2() ? 'yes' : 'no'}`)
791
- }
792
- console.error(` Target: ${metadata?.target || getDefaultTargetKey()}`)
793
- console.error(` Binary: ${CONFIG.binaryPath}`)
794
- }
795
-
796
- function getInstalledBinaryStatus() {
797
- try {
798
- const stats = fs.statSync(CONFIG.binaryPath)
799
- return stats.isFile() ? `yes (${formatBytes(stats.size)})` : 'no'
800
- } catch {
801
- return 'no'
802
- }
803
- }
804
-
805
- function printSpawnFailure(err) {
806
- resetTerminal()
807
- const code = err && err.code ? ` (${err.code})` : ''
808
-
809
- console.error(`Failed to start ${packageName}: ${err.message}${code}`)
810
- console.error('')
811
- printSystemInfo()
812
- console.error(` Exists: ${getInstalledBinaryStatus()}`)
813
-
814
- if (process.platform === 'win32') {
815
- console.error('')
816
- console.error(
817
- 'On Windows, this can happen when Windows Security or antivirus blocks',
818
- )
819
- console.error(
820
- 'or quarantines the downloaded executable, or when the binary requires',
821
- )
822
- console.error('CPU instructions that are not available on this machine.')
823
- console.error('')
824
- printBaselineOverrideHint()
825
- }
826
-
827
- console.error('')
828
- console.error('Try deleting the downloaded files and running again:')
829
- console.error(` ${CONFIG.configDir}`)
830
- console.error('')
831
- }
832
-
833
- function exitOnSpawnFailure(err) {
834
- printSpawnFailure(err)
835
- process.exit(1)
836
- }
837
-
838
- function spawnInstalledBinary(options = {}) {
839
- if (!fs.existsSync(CONFIG.binaryPath)) {
840
- try {
841
- if (fs.existsSync(CONFIG.metadataPath)) fs.unlinkSync(CONFIG.metadataPath)
842
- } catch {
843
- // best effort
844
- }
845
- const error = new Error(
846
- `downloaded binary is missing at ${CONFIG.binaryPath}`,
847
- )
848
- error.code = 'BINARY_MISSING'
849
- exitOnSpawnFailure(error)
850
- }
851
-
852
- // spawn() only emits 'error' asynchronously for a few errno values
853
- // (EACCES, EAGAIN, EMFILE, ENFILE, ENOENT); everything else — notably
854
- // UNKNOWN on Windows when antivirus or Smart App Control blocks the
855
- // exe or the download is corrupt — is thrown synchronously.
856
- let child
857
- try {
858
- child = spawn(CONFIG.binaryPath, process.argv.slice(2), {
859
- stdio: 'inherit',
860
- ...options,
861
- })
862
- } catch (err) {
863
- exitOnSpawnFailure(err)
864
- }
865
-
866
- child.on('error', exitOnSpawnFailure)
867
-
868
- return child
869
- }
870
-
871
- async function tryFallbackToBaseline(code, signal) {
872
- if (!isIllegalInstructionExit(code, signal)) {
873
- return false
874
- }
875
-
876
- const fallbackTarget = getBaselineFallbackTargetKey()
877
- if (!fallbackTarget) {
878
- return false
879
- }
880
-
881
- const metadata = getCurrentMetadata()
882
- const currentTarget = metadata?.target || getDefaultTargetKey()
883
- if (currentTarget === fallbackTarget) {
884
- return false
885
- }
886
-
887
- const version = metadata?.version || (await getLatestVersion())
888
- if (!version) {
889
- return false
890
- }
891
-
892
- resetTerminal({
893
- exitAlternateScreen: shouldExitAlternateScreen(code, signal),
894
33
  })
895
- console.error('')
896
- console.error(
897
- `${packageName} is switching to the older-CPU binary for this machine.`,
898
- )
899
-
900
- try {
901
- await downloadBinary(version, fallbackTarget)
902
- } catch (error) {
903
- term.clearLine()
904
- console.error(`Failed to download ${fallbackTarget}: ${error.message}`)
905
- return false
906
- }
907
-
908
- const child = spawnInstalledBinary({ detached: false })
909
- attachExitHandler(child, false)
910
- return true
911
34
  }
912
-
913
- function attachExitHandler(child, allowBaselineFallback = true) {
914
- const exitListener = async (code, signal) => {
915
- if (
916
- allowBaselineFallback &&
917
- (await tryFallbackToBaseline(code, signal))
918
- ) {
919
- return
920
- }
921
-
922
- resetTerminal({
923
- exitAlternateScreen: shouldExitAlternateScreen(code, signal),
924
- })
925
- printCrashDiagnostics(code, signal)
926
- process.exit(signal ? 1 : (code || 0))
927
- }
928
-
929
- child.on('exit', exitListener)
930
- return exitListener
931
- }
932
-
933
- async function main() {
934
- await ensureBinaryExists()
935
-
936
- const child = spawnInstalledBinary()
937
- const exitListener = attachExitHandler(child)
938
-
939
- setTimeout(() => {
940
- checkForUpdates(child, exitListener)
941
- }, 100)
942
- }
943
-
944
- main().catch((error) => {
945
- console.error('❌ Unexpected error:', error.message)
946
- process.exit(1)
947
- })