codebuff 1.0.684 → 1.0.686

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