planexe-cli 0.0.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/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # The most powerful coding agent
2
+
3
+ Codebuff is a CLI tool that writes code for you.
4
+
5
+ 1. Run `codebuff` from your project directory
6
+ 2. Tell it what to do
7
+ 3. It will read and write to files and run commands to produce the code you want
8
+
9
+ Note: Codebuff will run commands in your terminal as it deems necessary to fulfill your request.
10
+
11
+ ## Installation
12
+
13
+ To install Codebuff, run:
14
+
15
+ ```bash
16
+ npm install -g codebuff
17
+ ```
18
+
19
+ (Use `sudo` if you get a permission error.)
20
+
21
+ ## Usage
22
+
23
+ After installation, you can start Codebuff by running:
24
+
25
+ ```bash
26
+ codebuff [project-directory]
27
+ ```
28
+
29
+ If no project directory is specified, Codebuff will use the current directory.
30
+
31
+ Once running, simply chat with Codebuff to say what coding task you want done.
32
+
33
+ ## Features
34
+
35
+ - Understands your whole codebase
36
+ - Creates and edits multiple files based on your request
37
+ - Can run your tests or type checker or linter; can install packages
38
+ - It's powerful: ask Codebuff to keep working until it reaches a condition and it will.
39
+
40
+ Our users regularly use Codebuff to implement new features, write unit tests, refactor code,write scripts, or give advice.
41
+
42
+ ## Knowledge Files
43
+
44
+ To unlock the full benefits of modern LLMs, we recommend storing knowledge alongside your code. Add a `knowledge.md` file anywhere in your project to provide helpful context, guidance, and tips for the LLM as it performs tasks for you.
45
+
46
+ Codebuff can fluently read and write files, so it will add knowledge as it goes. You don't need to write knowledge manually!
47
+
48
+ Some have said every change should be paired with a unit test. In 2024, every change should come with a knowledge update!
49
+
50
+ ## Tips
51
+
52
+ 1. Type '/help' or just '/' to see available commands.
53
+ 2. Create a `knowledge.md` file and collect specific points of advice. The assistant will use this knowledge to improve its responses.
54
+ 3. Type `undo` or `redo` to revert or reapply file changes from the conversation.
55
+ 4. Press `Esc` or `Ctrl+C` while Codebuff is generating a response to stop it.
56
+
57
+ ## Troubleshooting
58
+
59
+ If you are getting permission errors during installation, try using sudo:
60
+
61
+ ```
62
+ sudo npm install -g codebuff
63
+ ```
64
+
65
+ If you still have errors, it's a good idea to [reinstall Node](https://nodejs.org/en/download).
66
+
67
+ ## Feedback
68
+
69
+ We value your input! Please email your feedback to `founders@codebuff.com`. Thank you for using Codebuff!
package/index.js ADDED
@@ -0,0 +1,482 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { spawn } = require('child_process')
4
+ const fs = require('fs')
5
+ const http = require('http')
6
+ const https = require('https')
7
+ const os = require('os')
8
+ const path = require('path')
9
+ const zlib = require('zlib')
10
+
11
+ const tar = require('tar')
12
+
13
+ const packageName = 'planexe'
14
+
15
+ function createConfig(packageName) {
16
+ const homeDir = os.homedir()
17
+ const configDir = path.join(homeDir, '.config', 'manicode')
18
+ const binaryName =
19
+ process.platform === 'win32' ? `${packageName}.exe` : packageName
20
+
21
+ return {
22
+ homeDir,
23
+ configDir,
24
+ binaryName,
25
+ binaryPath: path.join(configDir, binaryName),
26
+ metadataPath: path.join(configDir, 'codebuff-metadata.json'),
27
+ tempDownloadDir: path.join(configDir, '.download-temp'),
28
+ userAgent: `${packageName}-cli`,
29
+ requestTimeout: 20000,
30
+ }
31
+ }
32
+
33
+ const CONFIG = createConfig(packageName)
34
+
35
+ function getPostHogConfig() {
36
+ const apiKey =
37
+ process.env.CODEBUFF_POSTHOG_API_KEY ||
38
+ process.env.NEXT_PUBLIC_POSTHOG_API_KEY
39
+ const host =
40
+ process.env.CODEBUFF_POSTHOG_HOST ||
41
+ process.env.NEXT_PUBLIC_POSTHOG_HOST_URL
42
+
43
+ if (!apiKey || !host) {
44
+ return null
45
+ }
46
+
47
+ return { apiKey, host }
48
+ }
49
+
50
+ /**
51
+ * Track update failure event to PostHog.
52
+ * Fire-and-forget - errors are silently ignored.
53
+ */
54
+ function trackUpdateFailed(errorMessage, version, context = {}) {
55
+ try {
56
+ const posthogConfig = getPostHogConfig()
57
+ if (!posthogConfig) {
58
+ return
59
+ }
60
+
61
+ const payload = JSON.stringify({
62
+ api_key: posthogConfig.apiKey,
63
+ event: 'cli.update_codebuff_failed',
64
+ properties: {
65
+ distinct_id: `anonymous-${CONFIG.homeDir}`,
66
+ error: errorMessage,
67
+ version: version || 'unknown',
68
+ platform: process.platform,
69
+ arch: process.arch,
70
+ ...context,
71
+ },
72
+ timestamp: new Date().toISOString(),
73
+ })
74
+
75
+ const parsedUrl = new URL(`${posthogConfig.host}/capture/`)
76
+ const isHttps = parsedUrl.protocol === 'https:'
77
+ const options = {
78
+ hostname: parsedUrl.hostname,
79
+ port: parsedUrl.port || (isHttps ? 443 : 80),
80
+ path: parsedUrl.pathname + parsedUrl.search,
81
+ method: 'POST',
82
+ headers: {
83
+ 'Content-Type': 'application/json',
84
+ 'Content-Length': Buffer.byteLength(payload),
85
+ },
86
+ }
87
+
88
+ const transport = isHttps ? https : http
89
+ const req = transport.request(options)
90
+ req.on('error', () => {}) // Silently ignore errors
91
+ req.write(payload)
92
+ req.end()
93
+ } catch (e) {
94
+ // Silently ignore any tracking errors
95
+ }
96
+ }
97
+
98
+ const PLATFORM_TARGETS = {
99
+ 'linux-x64': `${packageName}-linux-x64.tar.gz`,
100
+ 'linux-arm64': `${packageName}-linux-arm64.tar.gz`,
101
+ 'darwin-x64': `${packageName}-darwin-x64.tar.gz`,
102
+ 'darwin-arm64': `${packageName}-darwin-arm64.tar.gz`,
103
+ 'win32-x64': `${packageName}-win32-x64.tar.gz`,
104
+ }
105
+
106
+ const term = {
107
+ clearLine: () => {
108
+ if (process.stderr.isTTY) {
109
+ process.stderr.write('\r\x1b[K')
110
+ }
111
+ },
112
+ write: (text) => {
113
+ term.clearLine()
114
+ process.stderr.write(text)
115
+ },
116
+ writeLine: (text) => {
117
+ term.clearLine()
118
+ process.stderr.write(text + '\n')
119
+ },
120
+ }
121
+
122
+ function httpGet(url, options = {}) {
123
+ return new Promise((resolve, reject) => {
124
+ const parsedUrl = new URL(url)
125
+ const reqOptions = {
126
+ hostname: parsedUrl.hostname,
127
+ path: parsedUrl.pathname + parsedUrl.search,
128
+ headers: {
129
+ 'User-Agent': CONFIG.userAgent,
130
+ ...options.headers,
131
+ },
132
+ }
133
+
134
+ const req = https.get(reqOptions, (res) => {
135
+ if (res.statusCode === 302 || res.statusCode === 301) {
136
+ return httpGet(new URL(res.headers.location, url).href, options)
137
+ .then(resolve)
138
+ .catch(reject)
139
+ }
140
+ resolve(res)
141
+ })
142
+
143
+ req.on('error', reject)
144
+
145
+ const timeout = options.timeout || CONFIG.requestTimeout
146
+ req.setTimeout(timeout, () => {
147
+ req.destroy()
148
+ reject(new Error('Request timeout.'))
149
+ })
150
+ })
151
+ }
152
+
153
+ async function getLatestVersion() {
154
+ try {
155
+ const res = await httpGet(
156
+ `https://registry.npmjs.org/planexe-cli/latest`,
157
+ )
158
+
159
+ if (res.statusCode !== 200) return null
160
+
161
+ const body = await streamToString(res)
162
+ const packageData = JSON.parse(body)
163
+
164
+ return packageData.version || null
165
+ } catch (error) {
166
+ return null
167
+ }
168
+ }
169
+
170
+ function streamToString(stream) {
171
+ return new Promise((resolve, reject) => {
172
+ let data = ''
173
+ stream.on('data', (chunk) => (data += chunk))
174
+ stream.on('end', () => resolve(data))
175
+ stream.on('error', reject)
176
+ })
177
+ }
178
+
179
+ function getCurrentVersion() {
180
+ try {
181
+ if (!fs.existsSync(CONFIG.metadataPath)) {
182
+ return null
183
+ }
184
+ const metadata = JSON.parse(fs.readFileSync(CONFIG.metadataPath, 'utf8'))
185
+ // Also verify the binary still exists
186
+ if (!fs.existsSync(CONFIG.binaryPath)) {
187
+ return null
188
+ }
189
+ return metadata.version || null
190
+ } catch (error) {
191
+ return null
192
+ }
193
+ }
194
+
195
+ function compareVersions(v1, v2) {
196
+ if (!v1 || !v2) return 0
197
+
198
+ // Always update if the current version is not a valid semver
199
+ // e.g. 1.0.420-beta.1
200
+ if (!v1.match(/^\d+(\.\d+)*$/)) {
201
+ return -1
202
+ }
203
+
204
+ const parseVersion = (version) => {
205
+ const parts = version.split('-')
206
+ const mainParts = parts[0].split('.').map(Number)
207
+ const prereleaseParts = parts[1] ? parts[1].split('.') : []
208
+ return { main: mainParts, prerelease: prereleaseParts }
209
+ }
210
+
211
+ const p1 = parseVersion(v1)
212
+ const p2 = parseVersion(v2)
213
+
214
+ for (let i = 0; i < Math.max(p1.main.length, p2.main.length); i++) {
215
+ const n1 = p1.main[i] || 0
216
+ const n2 = p2.main[i] || 0
217
+
218
+ if (n1 < n2) return -1
219
+ if (n1 > n2) return 1
220
+ }
221
+
222
+ if (p1.prerelease.length === 0 && p2.prerelease.length === 0) {
223
+ return 0
224
+ } else if (p1.prerelease.length === 0) {
225
+ return 1
226
+ } else if (p2.prerelease.length === 0) {
227
+ return -1
228
+ } else {
229
+ for (
230
+ let i = 0;
231
+ i < Math.max(p1.prerelease.length, p2.prerelease.length);
232
+ i++
233
+ ) {
234
+ const pr1 = p1.prerelease[i] || ''
235
+ const pr2 = p2.prerelease[i] || ''
236
+
237
+ const isNum1 = !isNaN(parseInt(pr1))
238
+ const isNum2 = !isNaN(parseInt(pr2))
239
+
240
+ if (isNum1 && isNum2) {
241
+ const num1 = parseInt(pr1)
242
+ const num2 = parseInt(pr2)
243
+ if (num1 < num2) return -1
244
+ if (num1 > num2) return 1
245
+ } else if (isNum1 && !isNum2) {
246
+ return 1
247
+ } else if (!isNum1 && isNum2) {
248
+ return -1
249
+ } else if (pr1 < pr2) {
250
+ return -1
251
+ } else if (pr1 > pr2) {
252
+ return 1
253
+ }
254
+ }
255
+ return 0
256
+ }
257
+ }
258
+
259
+ function formatBytes(bytes) {
260
+ if (bytes === 0) return '0 B'
261
+ const k = 1024
262
+ const sizes = ['B', 'KB', 'MB', 'GB']
263
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
264
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
265
+ }
266
+
267
+ function createProgressBar(percentage, width = 30) {
268
+ const filled = Math.round((width * percentage) / 100)
269
+ const empty = width - filled
270
+ return '[' + '█'.repeat(filled) + '░'.repeat(empty) + ']'
271
+ }
272
+
273
+ async function downloadBinary(version) {
274
+ const platformKey = `${process.platform}-${process.arch}`
275
+ const fileName = PLATFORM_TARGETS[platformKey]
276
+
277
+ if (!fileName) {
278
+ const error = new Error(`Unsupported platform: ${process.platform} ${process.arch}`)
279
+ trackUpdateFailed(error.message, version, { stage: 'platform_check' })
280
+ throw error
281
+ }
282
+
283
+ const downloadUrl = `https://github.com/VoynichLabs/codebuff/releases/download/v${version}/${fileName}`
284
+
285
+ // Ensure config directory exists
286
+ fs.mkdirSync(CONFIG.configDir, { recursive: true })
287
+
288
+ // Clean up any previous temp download directory
289
+ if (fs.existsSync(CONFIG.tempDownloadDir)) {
290
+ fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
291
+ }
292
+ fs.mkdirSync(CONFIG.tempDownloadDir, { recursive: true })
293
+
294
+ term.write('Downloading...')
295
+
296
+ const res = await httpGet(downloadUrl)
297
+
298
+ if (res.statusCode !== 200) {
299
+ fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
300
+ const error = new Error(`Download failed: HTTP ${res.statusCode}`)
301
+ trackUpdateFailed(error.message, version, { stage: 'http_download', statusCode: res.statusCode })
302
+ throw error
303
+ }
304
+
305
+ const totalSize = parseInt(res.headers['content-length'] || '0', 10)
306
+ let downloadedSize = 0
307
+ let lastProgressTime = Date.now()
308
+
309
+ res.on('data', (chunk) => {
310
+ downloadedSize += chunk.length
311
+ const now = Date.now()
312
+ if (now - lastProgressTime >= 100 || downloadedSize === totalSize) {
313
+ lastProgressTime = now
314
+ if (totalSize > 0) {
315
+ const pct = Math.round((downloadedSize / totalSize) * 100)
316
+ term.write(
317
+ `Downloading... ${createProgressBar(pct)} ${pct}% of ${formatBytes(
318
+ totalSize,
319
+ )}`,
320
+ )
321
+ } else {
322
+ term.write(`Downloading... ${formatBytes(downloadedSize)}`)
323
+ }
324
+ }
325
+ })
326
+
327
+ // Extract to temp directory
328
+ await new Promise((resolve, reject) => {
329
+ res
330
+ .pipe(zlib.createGunzip())
331
+ .pipe(tar.x({ cwd: CONFIG.tempDownloadDir }))
332
+ .on('finish', resolve)
333
+ .on('error', reject)
334
+ })
335
+
336
+ const tempBinaryPath = path.join(CONFIG.tempDownloadDir, CONFIG.binaryName)
337
+
338
+ // Verify the binary was extracted
339
+ if (!fs.existsSync(tempBinaryPath)) {
340
+ const files = fs.readdirSync(CONFIG.tempDownloadDir)
341
+ fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
342
+ const error = new Error(
343
+ `Binary not found after extraction. Expected: ${CONFIG.binaryName}, Available files: ${files.join(', ')}`,
344
+ )
345
+ trackUpdateFailed(error.message, version, { stage: 'extraction' })
346
+ throw error
347
+ }
348
+
349
+ // Set executable permissions
350
+ if (process.platform !== 'win32') {
351
+ fs.chmodSync(tempBinaryPath, 0o755)
352
+ }
353
+
354
+ // Move binary to final location
355
+ try {
356
+ if (fs.existsSync(CONFIG.binaryPath)) {
357
+ try {
358
+ fs.unlinkSync(CONFIG.binaryPath)
359
+ } catch (err) {
360
+ // Fallback: try renaming the locked/undeletable binary (Windows)
361
+ const backupPath = CONFIG.binaryPath + `.old.${Date.now()}`
362
+ try {
363
+ fs.renameSync(CONFIG.binaryPath, backupPath)
364
+ } catch (renameErr) {
365
+ throw new Error(
366
+ `Failed to replace existing binary. ` +
367
+ `unlink error: ${err.code || err.message}, ` +
368
+ `rename error: ${renameErr.code || renameErr.message}`,
369
+ )
370
+ }
371
+ }
372
+ }
373
+ fs.renameSync(tempBinaryPath, CONFIG.binaryPath)
374
+
375
+ // Save version metadata for fast version checking
376
+ fs.writeFileSync(
377
+ CONFIG.metadataPath,
378
+ JSON.stringify({ version }, null, 2),
379
+ )
380
+ } finally {
381
+ // Clean up temp directory even if rename fails
382
+ if (fs.existsSync(CONFIG.tempDownloadDir)) {
383
+ fs.rmSync(CONFIG.tempDownloadDir, { recursive: true })
384
+ }
385
+ }
386
+
387
+ term.clearLine()
388
+ console.log('Download complete! Starting Codebuff...')
389
+ }
390
+
391
+ async function ensureBinaryExists() {
392
+ const currentVersion = getCurrentVersion()
393
+ if (currentVersion !== null) {
394
+ return
395
+ }
396
+
397
+ const version = await getLatestVersion()
398
+ if (!version) {
399
+ console.error('❌ Failed to determine latest version')
400
+ console.error('Please check your internet connection and try again')
401
+ process.exit(1)
402
+ }
403
+
404
+ try {
405
+ await downloadBinary(version)
406
+ } catch (error) {
407
+ term.clearLine()
408
+ console.error('❌ Failed to download codebuff:', error.message)
409
+ console.error('Please check your internet connection and try again')
410
+ process.exit(1)
411
+ }
412
+ }
413
+
414
+ async function checkForUpdates(runningProcess, exitListener) {
415
+ try {
416
+ const currentVersion = getCurrentVersion()
417
+
418
+ const latestVersion = await getLatestVersion()
419
+ if (!latestVersion) return
420
+
421
+ if (
422
+ // Download new version if current version is unknown or outdated.
423
+ currentVersion === null ||
424
+ compareVersions(currentVersion, latestVersion) < 0
425
+ ) {
426
+ term.clearLine()
427
+
428
+ runningProcess.removeListener('exit', exitListener)
429
+ runningProcess.kill('SIGTERM')
430
+
431
+ await new Promise((resolve) => {
432
+ runningProcess.on('exit', resolve)
433
+ setTimeout(() => {
434
+ if (!runningProcess.killed) {
435
+ runningProcess.kill('SIGKILL')
436
+ }
437
+ resolve()
438
+ }, 5000)
439
+ })
440
+
441
+ console.log(`Update available: ${currentVersion} → ${latestVersion}`)
442
+
443
+ await downloadBinary(latestVersion)
444
+
445
+ const newChild = spawn(CONFIG.binaryPath, process.argv.slice(2), {
446
+ stdio: 'inherit',
447
+ detached: false,
448
+ })
449
+
450
+ newChild.on('exit', (code) => {
451
+ process.exit(code || 0)
452
+ })
453
+
454
+ return new Promise(() => {})
455
+ }
456
+ } catch (error) {
457
+ // Ignore update failures
458
+ }
459
+ }
460
+
461
+ async function main() {
462
+ await ensureBinaryExists()
463
+
464
+ const child = spawn(CONFIG.binaryPath, process.argv.slice(2), {
465
+ stdio: 'inherit',
466
+ })
467
+
468
+ const exitListener = (code) => {
469
+ process.exit(code || 0)
470
+ }
471
+
472
+ child.on('exit', exitListener)
473
+
474
+ setTimeout(() => {
475
+ checkForUpdates(child, exitListener)
476
+ }, 100)
477
+ }
478
+
479
+ main().catch((error) => {
480
+ console.error('❌ Unexpected error:', error.message)
481
+ process.exit(1)
482
+ })
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "planexe-cli",
3
+ "version": "0.0.2",
4
+ "description": "PlanExe CLI — AI planning and coding agent",
5
+ "license": "MIT",
6
+ "bin": {
7
+ "planexe": "index.js",
8
+ "px": "index.js"
9
+ },
10
+ "scripts": {
11
+ "postinstall": "node postinstall.js",
12
+ "preuninstall": "node -e \"const fs = require('fs'); const path = require('path'); const os = require('os'); const binaryPath = path.join(os.homedir(), '.config', 'manicode', process.platform === 'win32' ? 'codebuff.exe' : 'codebuff'); try { fs.unlinkSync(binaryPath) } catch (e) { /* ignore if file doesn't exist */ }\""
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "postinstall.js",
17
+ "README.md"
18
+ ],
19
+ "os": [
20
+ "darwin",
21
+ "linux",
22
+ "win32"
23
+ ],
24
+ "cpu": [
25
+ "x64",
26
+ "arm64"
27
+ ],
28
+ "engines": {
29
+ "node": ">=16"
30
+ },
31
+ "dependencies": {
32
+ "tar": "^7.0.0"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/VoynichLabs/codebuff.git"
37
+ },
38
+ "homepage": "https://github.com/VoynichLabs/codebuff",
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }
package/postinstall.js ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+
7
+ // Clean up old binary
8
+ const binaryPath = path.join(
9
+ os.homedir(),
10
+ '.config',
11
+ 'manicode',
12
+ process.platform === 'win32' ? 'planexe.exe' : 'planexe'
13
+ );
14
+
15
+ try {
16
+ fs.unlinkSync(binaryPath);
17
+ } catch (e) {
18
+ /* ignore if file doesn't exist */
19
+ }
20
+
21
+ // Print welcome message
22
+ console.log('\n');
23
+ console.log('🦞 Welcome to PlanExe CLI!');
24
+ console.log('\n');
25
+ console.log('To get started:');
26
+ console.log(' 1. cd to your project directory');
27
+ console.log(' 2. Run: planexe');
28
+ console.log('\n');
29
+ console.log('Example:');
30
+ console.log(' $ cd ~/my-project');
31
+ console.log(' $ planexe');
32
+ console.log('\n');
33
+ console.log('For more information, visit: https://github.com/VoynichLabs/codebuff');
34
+ console.log('\n');