forked from CodebuffAI/codebuff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
592 lines (514 loc) · 16.8 KB
/
Copy pathindex.js
File metadata and controls
592 lines (514 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#!/usr/bin/env node
const { spawn } = require('child_process')
const fs = require('fs')
const http = require('http')
const https = require('https')
const os = require('os')
const path = require('path')
const zlib = require('zlib')
const tar = require('tar')
const { createReleaseHttpClient } = require('./http')
const packageName = 'codebuff'
/**
* Terminal escape sequences to reset terminal state after the child process exits.
* When the binary is SIGKILL'd, it can't clean up its own terminal state.
* The wrapper (this process) survives and must reset these modes.
*
* Keep in sync with TERMINAL_RESET_SEQUENCES in cli/src/utils/renderer-cleanup.ts
*/
const TERMINAL_RESET_SEQUENCES =
'\x1b[?1049l' + // Exit alternate screen buffer
'\x1b[?1000l' + // Disable X10 mouse mode
'\x1b[?1002l' + // Disable button event mouse mode
'\x1b[?1003l' + // Disable any-event mouse mode (all motion)
'\x1b[?1006l' + // Disable SGR extended mouse mode
'\x1b[?1004l' + // Disable focus reporting
'\x1b[?2004l' + // Disable bracketed paste mode
'\x1b[?25h' // Show cursor
function resetTerminal() {
try {
if (process.stdin.isTTY && process.stdin.setRawMode) {
process.stdin.setRawMode(false)
}
} catch {
// stdin may be closed
}
try {
if (process.stdout.isTTY) {
process.stdout.write(TERMINAL_RESET_SEQUENCES)
}
} catch {
// stdout may be closed
}
}
function createConfig(packageName) {
const homeDir = os.homedir()
const configDir = path.join(homeDir, '.config', 'manicode')
const binaryName =
process.platform === 'win32' ? `${packageName}.exe` : packageName
return {
homeDir,
configDir,
binaryName,
binaryPath: path.join(configDir, binaryName),
metadataPath: path.join(configDir, 'codebuff-metadata.json'),
tempDownloadDir: path.join(configDir, '.download-temp'),
userAgent: `${packageName}-cli`,
requestTimeout: 20000,
}
}
const CONFIG = createConfig(packageName)
const { getProxyUrl, httpGet } = createReleaseHttpClient({
env: process.env,
userAgent: CONFIG.userAgent,
requestTimeout: CONFIG.requestTimeout,
})
function getPostHogConfig() {
const apiKey =
process.env.CODEBUFF_POSTHOG_API_KEY ||
process.env.NEXT_PUBLIC_POSTHOG_API_KEY
const host =
process.env.CODEBUFF_POSTHOG_HOST ||
process.env.NEXT_PUBLIC_POSTHOG_HOST_URL
if (!apiKey || !host) {
return null
}
return { apiKey, host }
}
/**
* Track update failure event to PostHog.
* Fire-and-forget - errors are silently ignored.
*/
function trackUpdateFailed(errorMessage, version, context = {}) {
try {
const posthogConfig = getPostHogConfig()
if (!posthogConfig) {
return
}
const payload = JSON.stringify({
api_key: posthogConfig.apiKey,
event: 'cli.update_codebuff_failed',
properties: {
distinct_id: `anonymous-${CONFIG.homeDir}`,
error: errorMessage,
version: version || 'unknown',
platform: process.platform,
arch: process.arch,
...context,
},
timestamp: new Date().toISOString(),
})
const parsedUrl = new URL(`${posthogConfig.host}/capture/`)
const isHttps = parsedUrl.protocol === 'https:'
const options = {
hostname: parsedUrl.hostname,
port: parsedUrl.port || (isHttps ? 443 : 80),
path: parsedUrl.pathname + parsedUrl.search,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
},
}
const transport = isHttps ? https : http
const req = transport.request(options)
req.on('error', () => {}) // Silently ignore errors
req.write(payload)
req.end()
} catch (e) {
// Silently ignore any tracking errors
}
}
const PLATFORM_TARGETS = {
'linux-x64': `${packageName}-linux-x64.tar.gz`,
'linux-arm64': `${packageName}-linux-arm64.tar.gz`,
'darwin-x64': `${packageName}-darwin-x64.tar.gz`,
'darwin-arm64': `${packageName}-darwin-arm64.tar.gz`,
'win32-x64': `${packageName}-win32-x64.tar.gz`,
}
const term = {
clearLine: () => {
if (process.stderr.isTTY) {
process.stderr.write('\r\x1b[K')
}
},
write: (text) => {
term.clearLine()
process.stderr.write(text)
},
writeLine: (text) => {
term.clearLine()
process.stderr.write(text + '\n')
},
}
async function getLatestVersion() {
try {
const res = await httpGet(
`https://registry.npmjs.org/${packageName}/latest`,
)
if (res.statusCode !== 200) return null
const body = await streamToString(res)
const packageData = JSON.parse(body)
return packageData.version || null
} catch (error) {
return null
}
}
function streamToString(stream) {
return new Promise((resolve, reject) => {
let data = ''
stream.on('data', (chunk) => (data += chunk))
stream.on('end', () => resolve(data))
stream.on('error', reject)
})
}
function getCurrentVersion() {
try {
if (!fs.existsSync(CONFIG.metadataPath)) {
return null
}
const metadata = JSON.parse(fs.readFileSync(CONFIG.metadataPath, 'utf8'))
// Also verify the binary still exists
if (!fs.existsSync(CONFIG.binaryPath)) {
return null
}
return metadata.version || null
} catch (error) {
return null
}
}
function compareVersions(v1, v2) {
if (!v1 || !v2) return 0
// Always update if the current version is not a valid semver
// e.g. 1.0.420-beta.1
if (!v1.match(/^\d+(\.\d+)*$/)) {
return -1
}
const parseVersion = (version) => {
const parts = version.split('-')
const mainParts = parts[0].split('.').map(Number)
const prereleaseParts = parts[1] ? parts[1].split('.') : []
return { main: mainParts, prerelease: prereleaseParts }
}
const p1 = parseVersion(v1)
const p2 = parseVersion(v2)
for (let i = 0; i < Math.max(p1.main.length, p2.main.length); i++) {
const n1 = p1.main[i] || 0
const n2 = p2.main[i] || 0
if (n1 < n2) return -1
if (n1 > n2) return 1
}
if (p1.prerelease.length === 0 && p2.prerelease.length === 0) {
return 0
} else if (p1.prerelease.length === 0) {
return 1
} else if (p2.prerelease.length === 0) {
return -1
} else {
for (
let i = 0;
i < Math.max(p1.prerelease.length, p2.prerelease.length);
i++
) {
const pr1 = p1.prerelease[i] || ''
const pr2 = p2.prerelease[i] || ''
const isNum1 = !isNaN(parseInt(pr1))
const isNum2 = !isNaN(parseInt(pr2))
if (isNum1 && isNum2) {
const num1 = parseInt(pr1)
const num2 = parseInt(pr2)
if (num1 < num2) return -1
if (num1 > num2) return 1
} else if (isNum1 && !isNum2) {
return 1
} else if (!isNum1 && isNum2) {
return -1
} else if (pr1 < pr2) {
return -1
} else if (pr1 > pr2) {
return 1
}
}
return 0
}
}
function formatBytes(bytes) {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}
function createProgressBar(percentage, width = 30) {
const filled = Math.round((width * percentage) / 100)
const empty = width - filled
return '[' + '█'.repeat(filled) + '░'.repeat(empty) + ']'
}
async function downloadBinary(version) {
const platformKey = `${process.platform}-${process.arch}`
const fileName = PLATFORM_TARGETS[platformKey]
if (!fileName) {
const error = new Error(`Unsupported platform: ${process.platform} ${process.arch}`)
trackUpdateFailed(error.message, version, { stage: 'platform_check' })
throw error
}
const downloadUrl = `${
process.env.NEXT_PUBLIC_CODEBUFF_APP_URL || 'https://codebuff.com'
}/api/releases/download/${version}/${fileName}`
// Ensure config directory exists
fs.mkdirSync(CONFIG.configDir, { recursive: true })
// Clean up any previous temp download directory
if (fs.existsSync(CONFIG.tempDownloadDir)) {
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
}
fs.mkdirSync(CONFIG.tempDownloadDir, { recursive: true })
term.write('Downloading...')
const res = await httpGet(downloadUrl)
if (res.statusCode !== 200) {
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
const error = new Error(`Download failed: HTTP ${res.statusCode}`)
trackUpdateFailed(error.message, version, { stage: 'http_download', statusCode: res.statusCode })
throw error
}
const totalSize = parseInt(res.headers['content-length'] || '0', 10)
let downloadedSize = 0
let lastProgressTime = Date.now()
res.on('data', (chunk) => {
downloadedSize += chunk.length
const now = Date.now()
if (now - lastProgressTime >= 100 || downloadedSize === totalSize) {
lastProgressTime = now
if (totalSize > 0) {
const pct = Math.round((downloadedSize / totalSize) * 100)
term.write(
`Downloading... ${createProgressBar(pct)} ${pct}% of ${formatBytes(
totalSize,
)}`,
)
} else {
term.write(`Downloading... ${formatBytes(downloadedSize)}`)
}
}
})
// Extract to temp directory
await new Promise((resolve, reject) => {
res
.pipe(zlib.createGunzip())
.pipe(tar.x({ cwd: CONFIG.tempDownloadDir }))
.on('finish', resolve)
.on('error', reject)
})
const tempBinaryPath = path.join(CONFIG.tempDownloadDir, CONFIG.binaryName)
// Verify the binary was extracted
if (!fs.existsSync(tempBinaryPath)) {
const files = fs.readdirSync(CONFIG.tempDownloadDir)
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
const error = new Error(
`Binary not found after extraction. Expected: ${CONFIG.binaryName}, Available files: ${files.join(', ')}`,
)
trackUpdateFailed(error.message, version, { stage: 'extraction' })
throw error
}
// Set executable permissions
if (process.platform !== 'win32') {
fs.chmodSync(tempBinaryPath, 0o755)
}
// Move binary to final location
try {
if (fs.existsSync(CONFIG.binaryPath)) {
try {
fs.unlinkSync(CONFIG.binaryPath)
} catch (err) {
// Fallback: try renaming the locked/undeletable binary (Windows)
const backupPath = CONFIG.binaryPath + `.old.${Date.now()}`
try {
fs.renameSync(CONFIG.binaryPath, backupPath)
} catch (renameErr) {
throw new Error(
`Failed to replace existing binary. ` +
`unlink error: ${err.code || err.message}, ` +
`rename error: ${renameErr.code || renameErr.message}`,
)
}
}
}
fs.renameSync(tempBinaryPath, CONFIG.binaryPath)
// Move tree-sitter.wasm next to the binary if the tarball included
// it. The CLI binary loads this at startup; embedding it inside the
// binary itself was unreliable on Windows (bun --compile asset
// bundling silently dropped or unbound it across several attempts),
// so we ship it as a sibling file instead. Older artifacts that
// pre-date this change won't have the wasm and will still install —
// they'll just hit the same crash they had before, which is fine.
const tempWasmPath = path.join(CONFIG.tempDownloadDir, 'tree-sitter.wasm')
if (fs.existsSync(tempWasmPath)) {
const targetWasmPath = path.join(
path.dirname(CONFIG.binaryPath),
'tree-sitter.wasm',
)
try {
if (fs.existsSync(targetWasmPath)) fs.unlinkSync(targetWasmPath)
} catch {
// best effort; rename below will surface the real error if it matters
}
fs.renameSync(tempWasmPath, targetWasmPath)
}
// Save version metadata for fast version checking
fs.writeFileSync(
CONFIG.metadataPath,
JSON.stringify({ version }, null, 2),
)
} finally {
// Clean up temp directory even if rename fails
if (fs.existsSync(CONFIG.tempDownloadDir)) {
fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
}
}
term.clearLine()
console.log('Download complete! Starting Codebuff...')
}
async function ensureBinaryExists() {
const currentVersion = getCurrentVersion()
if (currentVersion !== null) {
return
}
const version = await getLatestVersion()
if (!version) {
console.error('❌ Failed to determine latest version')
console.error('Please check your internet connection and try again')
if (!getProxyUrl()) {
console.error(
'If you are behind a proxy, set the HTTPS_PROXY environment variable',
)
}
process.exit(1)
}
try {
await downloadBinary(version)
} catch (error) {
term.clearLine()
console.error('❌ Failed to download codebuff:', error.message)
console.error('Please check your internet connection and try again')
if (!getProxyUrl()) {
console.error(
'If you are behind a proxy, set the HTTPS_PROXY environment variable',
)
}
process.exit(1)
}
}
async function checkForUpdates(runningProcess, exitListener) {
try {
const currentVersion = getCurrentVersion()
const latestVersion = await getLatestVersion()
if (!latestVersion) return
if (
// Download new version if current version is unknown or outdated.
currentVersion === null ||
compareVersions(currentVersion, latestVersion) < 0
) {
term.clearLine()
runningProcess.removeListener('exit', exitListener)
await new Promise((resolve) => {
let exited = false
runningProcess.once('exit', () => {
exited = true
resolve()
})
runningProcess.kill('SIGTERM')
setTimeout(() => {
if (!exited) {
runningProcess.kill('SIGKILL')
// Safety: resolve after giving SIGKILL time to take effect
setTimeout(() => resolve(), 1000)
}
}, 5000)
})
resetTerminal()
console.log(`Update available: ${currentVersion} → ${latestVersion}`)
await downloadBinary(latestVersion)
const newChild = spawn(CONFIG.binaryPath, process.argv.slice(2), {
stdio: 'inherit',
detached: false,
})
newChild.on('exit', (code, signal) => {
resetTerminal()
printCrashDiagnostics(code, signal)
process.exit(signal ? 1 : (code || 0))
})
newChild.on('error', (err) => {
console.error('Failed to start codebuff:', err.message)
process.exit(1)
})
return new Promise(() => {})
}
} catch (error) {
// Ignore update failures
}
}
function printCrashDiagnostics(code, signal) {
// Windows NTSTATUS codes (unsigned DWORD)
const unsignedCode = code != null && code < 0 ? (code >>> 0) : code
const isIllegalInstruction =
signal === 'SIGILL' ||
(process.platform === 'win32' && unsignedCode === 0xC000001D)
const isAccessViolation =
signal === 'SIGSEGV' ||
(process.platform === 'win32' && unsignedCode === 0xC0000005)
const isBusError = signal === 'SIGBUS'
const isAbort =
signal === 'SIGABRT' ||
(process.platform === 'win32' && unsignedCode === 0xC0000409)
if (!isIllegalInstruction && !isAccessViolation && !isBusError && !isAbort) return
const exitInfo = signal ? `signal ${signal}` : `code ${code}`
console.error('')
console.error(`❌ ${packageName} exited immediately (${exitInfo})`)
console.error('')
if (isIllegalInstruction) {
console.error('Your CPU may not support the required instruction set (AVX2).')
console.error('This typically affects CPUs from before 2013.')
console.error('Unfortunately, this binary is not compatible with your system.')
console.error('')
} else if (isAccessViolation) {
console.error('The binary crashed with an access violation.')
console.error('')
} else if (isBusError) {
console.error('The binary crashed with a bus error.')
console.error('This may indicate a platform compatibility issue.')
console.error('')
} else if (isAbort) {
console.error('The binary crashed with an abort signal.')
console.error('')
}
console.error('System info:')
console.error(` Platform: ${process.platform} ${process.arch}`)
console.error(` Node: ${process.version}`)
console.error(` Binary: ${CONFIG.binaryPath}`)
console.error('')
console.error('Please report this issue at:')
console.error(' https://github.com/CodebuffAI/codebuff/issues')
console.error('')
}
async function main() {
await ensureBinaryExists()
const child = spawn(CONFIG.binaryPath, process.argv.slice(2), {
stdio: 'inherit',
})
const exitListener = (code, signal) => {
resetTerminal()
printCrashDiagnostics(code, signal)
process.exit(signal ? 1 : (code || 0))
}
child.on('exit', exitListener)
child.on('error', (err) => {
console.error('Failed to start codebuff:', err.message)
process.exit(1)
})
setTimeout(() => {
checkForUpdates(child, exitListener)
}, 100)
}
main().catch((error) => {
console.error('❌ Unexpected error:', error.message)
process.exit(1)
})