-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupdate-ai-tools.js
More file actions
executable file
·533 lines (455 loc) · 16.1 KB
/
update-ai-tools.js
File metadata and controls
executable file
·533 lines (455 loc) · 16.1 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
#!/usr/bin/env node
import { execSync } from "node:child_process";
import { existsSync, readdirSync, rmSync } from "node:fs";
import { join } from "node:path";
import { createInterface } from "node:readline";
const packages = {
claude: "@anthropic-ai/claude-code",
gemini: "@google/gemini-cli",
copilot: "@github/copilot",
codex: "@openai/codex",
kilocode: "@kilocode/cli",
};
const binaries = {
claude: "claude",
gemini: "gemini",
copilot: "copilot",
codex: "codex",
kilocode: "kilocode",
};
let globalNodeModulesDir = null;
function getGlobalNodeModulesDir() {
if (globalNodeModulesDir) return globalNodeModulesDir;
try {
globalNodeModulesDir = execSync("npm root -g", {
encoding: "utf8",
stdio: "pipe",
})
.trim()
.replace(/\n/g, "");
} catch {
globalNodeModulesDir = null;
}
return globalNodeModulesDir;
}
function removeGeminiInstallDir() {
const baseDir = getGlobalNodeModulesDir();
if (!baseDir) {
return false;
}
const geminiDir = join(baseDir, "@google", "gemini-cli");
const geminiNamespaceDir = join(baseDir, "@google");
if (!existsSync(geminiDir)) {
try {
if (existsSync(geminiNamespaceDir)) {
const staleDirs = readdirSync(geminiNamespaceDir).filter((entry) => entry.startsWith(".gemini-cli"));
staleDirs.forEach((entry) => {
const dirPath = join(geminiNamespaceDir, entry);
rmSync(dirPath, { recursive: true, force: true });
});
}
return true;
} catch {
return false;
}
}
try {
rmSync(geminiDir, { recursive: true, force: true });
if (existsSync(geminiNamespaceDir)) {
const staleDirs = readdirSync(geminiNamespaceDir).filter((entry) => entry.startsWith(".gemini-cli"));
staleDirs.forEach((entry) => {
const dirPath = join(geminiNamespaceDir, entry);
rmSync(dirPath, { recursive: true, force: true });
});
}
return true;
} catch {
return false;
}
}
function askUser(question) {
const rl = createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close();
resolve(answer.toLowerCase().trim());
});
});
}
function getLocalPackageVersion(packageName) {
try {
const result = execSync(`npm list -g ${packageName} --depth=0 --json`, {
encoding: "utf8",
stdio: "pipe",
});
const data = JSON.parse(result);
return data.dependencies?.[packageName]?.version || null;
} catch {
return null;
}
}
function getRemotePackageVersion(packageName) {
try {
const result = execSync(`npm view ${packageName} version`, {
encoding: "utf8",
stdio: "pipe",
});
return result.trim();
} catch {
return null;
}
}
function compareVersions(v1, v2) {
if (!v1 || !v2) return false;
const parts1 = v1.split(".").map(Number);
const parts2 = v2.split(".").map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const part1 = parts1[i] || 0;
const part2 = parts2[i] || 0;
if (part1 < part2) return -1;
if (part1 > part2) return 1;
}
return 0;
}
function getBinaryVersion(binaryName) {
try {
const output = execSync(`${binaryName} --version`, { encoding: "utf8", stdio: "pipe" }).trim();
// Handle copilot which returns multiple lines
if (binaryName === "copilot") {
return output.split("\n")[0]; // Return only the first line (version number)
}
return output;
} catch {
return null;
}
}
function isPackageInstalled(packageName) {
const nameKey = Object.keys(packages).find((key) => packages[key] === packageName);
const binaryName = binaries[nameKey];
if (binaryName) {
try {
execSync(`${binaryName} --version`, { encoding: "utf8", stdio: "ignore" });
return true;
} catch {
// Fall back to npm list check below
}
}
try {
const result = execSync(`npm list -g ${packageName} --depth=0 --json`, {
encoding: "utf8",
stdio: "pipe",
});
const data = JSON.parse(result);
return Boolean(data.dependencies?.[packageName]);
} catch {
return false;
}
}
function run(cmd, allowFailure = false) {
try {
console.log(`➡️ ${cmd}`);
execSync(cmd, { stdio: "inherit" });
return true;
} catch (err) {
if (allowFailure) {
console.error(`⚠️ Failed: ${cmd}`);
return false;
} else {
console.error("❌ Error running:", cmd);
process.exit(1);
}
}
}
function isCacheError(error) {
const errorString = error.toString();
return (
errorString.includes("ENOENT") ||
errorString.includes("ENOTEMPTY") ||
errorString.includes("_cacache") ||
errorString.includes("git-clone") ||
(errorString.includes("package.json") && errorString.includes("tmp"))
);
}
function isNetworkError(error) {
const errorString = error.toString();
return errorString.includes("ENOTFOUND") || errorString.includes("ECONNRESET") || errorString.includes("ETIMEDOUT") || errorString.includes("network");
}
function getErrorType(error) {
if (isCacheError(error)) return "cache";
if (isNetworkError(error)) return "network";
return "unknown";
}
function clearNpmCache() {
try {
console.log("🧹 Clearing npm cache...");
execSync("npm cache clean --force", { stdio: "pipe" });
console.log("✅ npm cache cleared");
return true;
} catch (err) {
console.log("⚠️ Failed to clear npm cache, continuing anyway...");
return false;
}
}
function runWithRetry(cmd, retries = 2, options = {}) {
let cacheCleared = false;
for (let i = 0; i <= retries; i++) {
try {
console.log(`➡️ ${cmd}${i > 0 ? ` (retry ${i})` : ""}`);
execSync(cmd, { stdio: "inherit" });
return true;
} catch (err) {
let errorType = getErrorType(err);
if (typeof options.onError === "function") {
try {
const result = options.onError(err, {
attempt: i,
retries,
cmd,
errorType,
});
if (result && typeof result === "object") {
if (result.errorTypeOverride) {
errorType = result.errorTypeOverride;
}
if (result.retryImmediately) {
continue;
}
}
} catch (hookError) {
console.log("⚠️ onError hook failed:", hookError.message || hookError);
}
}
if (i === retries) {
console.error(`❌ Failed after ${retries + 1} attempts: ${cmd}`);
// Provide specific error guidance
if (errorType === "cache") {
console.log("💡 This appears to be an npm cache issue. You can try:");
console.log(" npm cache clean --force");
console.log(" Then run the command again");
} else if (errorType === "network") {
console.log("💡 This appears to be a network issue. You can try:");
console.log(" Check your internet connection");
console.log(" Try again later");
}
return false;
} else {
console.log(`⚠️ Attempt ${i + 1} failed (${errorType} error)`);
// Handle different error types
if (errorType === "cache" && !cacheCleared) {
console.log("🧹 Detected npm cache error, clearing cache before retry...");
if (clearNpmCache()) {
cacheCleared = true;
// Don't wait after cache clear, retry immediately
continue;
}
} else if (errorType === "network") {
console.log("🌐 Network error detected, waiting longer before retry...");
execSync("sleep 5", { stdio: "ignore" });
} else {
console.log("⏳ Waiting before retry...");
execSync("sleep 2", { stdio: "ignore" });
}
}
}
}
}
async function installPackagesWithConfirmation(packageList, individual = false) {
console.log("🔍 Checking package versions...");
// Check which packages are already installed and need updates
const installedPackages = [];
const newPackages = [];
const upToDatePackages = [];
for (const pkg of packageList) {
const name = Object.keys(packages).find((key) => packages[key] === pkg);
if (isPackageInstalled(pkg)) {
const localVersion = getLocalPackageVersion(pkg);
const remoteVersion = getRemotePackageVersion(pkg);
if (localVersion && remoteVersion) {
const comparison = compareVersions(localVersion, remoteVersion);
if (comparison < 0) {
console.log(`📦 ${name}: ${localVersion} → ${remoteVersion} (update available)`);
installedPackages.push(pkg);
} else {
console.log(`✅ ${name}: ${localVersion} (up to date)`);
upToDatePackages.push(pkg);
}
} else {
console.log(`⚠️ ${name}: Could not check version, will update`);
installedPackages.push(pkg);
}
} else {
const remoteVersion = getRemotePackageVersion(pkg);
console.log(`📦 ${name}: not installed (latest: ${remoteVersion || "unknown"})`);
newPackages.push(pkg);
}
}
// Show summary
if (upToDatePackages.length > 0) {
console.log(`\n✅ Already up to date (${upToDatePackages.length} packages):`);
upToDatePackages.forEach((pkg) => {
const name = Object.keys(packages).find((key) => packages[key] === pkg);
console.log(` - ${name}`);
});
}
if (installedPackages.length > 0) {
console.log(`\n🔄 Packages with updates available (${installedPackages.length} packages):`);
installedPackages.forEach((pkg) => {
const name = Object.keys(packages).find((key) => packages[key] === pkg);
console.log(` - ${name} (${pkg})`);
});
}
if (newPackages.length > 0) {
console.log(`\n📦 New packages to install (${newPackages.length} packages):`);
newPackages.forEach((pkg) => {
const name = Object.keys(packages).find((key) => packages[key] === pkg);
console.log(` - ${name} (${pkg})`);
});
const answer = await askUser("\n❓ Do you want to install the new packages? (y/N): ");
if (answer !== "y" && answer !== "yes") {
console.log("❌ Installation of new packages cancelled by user.");
newPackages.length = 0; // Clear new packages array
}
}
// Determine what to install
const packagesToInstall = [...installedPackages, ...newPackages];
if (packagesToInstall.length === 0) {
if (upToDatePackages.length > 0) {
console.log("\n🎉 All packages are up to date! No updates needed.");
} else {
console.log("\nℹ️ No packages to install or update.");
}
return;
}
// Show what will be updated/installed
if (installedPackages.length > 0 || newPackages.length > 0) {
console.log(`\n🚀 Processing ${packagesToInstall.length} package(s)...`);
await installPackages(packagesToInstall, individual);
}
}
async function installPackages(packageList, individual = false) {
if (!individual && packageList.length > 1) {
// Try installing all at once first
const bulkCmd = `npm install -g ${packageList.join(" ")}`;
if (runWithRetry(bulkCmd, 1)) {
console.log("✅ All packages installed successfully!");
return;
}
console.log("⚠️ Bulk installation failed, trying individual installations...");
}
// Install packages individually
let successCount = 0;
let failedPackages = [];
let cacheErrorsFound = false;
for (const pkg of packageList) {
const name = Object.keys(packages).find((key) => packages[key] === pkg) || pkg;
const isGemini = pkg === packages.gemini;
let geminiCleanupAttempted = false;
console.log(`\n📦 Installing ${name} (${pkg})...`);
const installSucceeded = runWithRetry(`npm install -g ${pkg}`, 2, {
onError: (error) => {
if (!isGemini || geminiCleanupAttempted) {
return null;
}
const message = typeof error?.toString === "function" ? error.toString() : "";
if (message.includes("ENOTEMPTY") && message.includes("@google/gemini-cli")) {
geminiCleanupAttempted = true;
console.log("🧹 Detected existing Gemini CLI install directory, removing before retry...");
if (removeGeminiInstallDir()) {
console.log("✅ Removed existing Gemini CLI directory. Retrying installation...");
return { retryImmediately: true };
}
console.log("⚠️ Automatic cleanup failed. You may need to close running processes and try again.");
}
return null;
},
});
if (installSucceeded) {
console.log(`✅ ${name} installed successfully`);
successCount++;
} else {
console.log(`❌ ${name} failed to install`);
failedPackages.push({ pkg, name });
// Check if we encountered cache errors
if (!cacheErrorsFound) {
cacheErrorsFound = true;
}
}
}
console.log(`\n📊 Installation Summary:`);
console.log(`✅ Successfully installed: ${successCount}/${packageList.length} packages`);
if (failedPackages.length > 0) {
console.log(`❌ Failed packages: ${failedPackages.map((f) => f.name).join(", ")}`);
if (cacheErrorsFound) {
console.log(`\n🔧 Troubleshooting failed installations:`);
console.log(` 1. Clear npm cache: npm cache clean --force`);
console.log(` 2. Clear npm global cache: rm -rf ~/.npm`);
console.log(` 3. Try installing manually:`);
} else {
console.log(`\n💡 Try running these manually:`);
}
failedPackages.forEach(({ pkg, name }) => {
console.log(` npm install -g ${pkg} # ${name}`);
});
if (successCount > 0) {
console.log(`\n✨ Good news: ${successCount} package(s) were installed successfully!`);
}
}
}
const arg = process.argv[2] || "all";
async function main() {
console.log(`
_ ____ ____ ____ _____ _____ ____ _ _____ ____ ____ _ ____
/ \\ /\\/ __\\/ _ \\/ _ Y__ __Y __/ / _ \\/ \\ /__ __Y _ \\/ _ \\/ \\ / ___\\
| | ||| \\/|| | \\|| / \\| / \\ | \\ _____ | / \\|| |_____ / \\ | / \\|| / \\|| | | \\
| \\_/|| __/| |_/|| |-|| | | | /_\\____\\| |-||| |\\____\\| | | \\_/|| \\_/|| |_/\\\\___ |
\\____/\\_/ \\____/\\_/ \\| \\_/ \\____\\ \\_/ \\|\\_/ \\_/ \\____/\\____/\\____/\\____/
`);
console.log();
if (arg === "all") {
console.log("📦 Updating all AI tools...");
await installPackagesWithConfirmation(Object.values(packages));
} else if (arg === "check") {
console.log("🔎 Checking installed versions and updates...");
console.log();
for (const [name, bin] of Object.entries(binaries)) {
const pkg = packages[name];
const binaryVersion = getBinaryVersion(bin);
const localVersion = getLocalPackageVersion(pkg);
const displayVersion = binaryVersion || localVersion;
if (displayVersion) {
const remoteVersion = getRemotePackageVersion(pkg);
if (localVersion && remoteVersion) {
const comparison = compareVersions(localVersion, remoteVersion);
if (comparison < 0) {
console.log(`${name}: ${displayVersion} → ${remoteVersion} available ⬆️`);
} else {
console.log(`${name}: ${displayVersion} ✅`);
}
} else {
console.log(`${name}: ${displayVersion} (unable to check for updates)`);
}
} else {
const remoteVersion = getRemotePackageVersion(pkg);
console.log(`${name}: not installed (latest: ${remoteVersion || "unknown"}) ❌`);
}
}
} else if (packages[arg]) {
console.log(`📦 Updating ${arg}...`);
await installPackagesWithConfirmation([packages[arg]], true);
} else {
console.log("Usage: update-ai-tools [all|claude|gemini|copilot|codex|kilocode|check]");
console.log("\nOptions:");
console.log(" all - Update all AI tools (with confirmation for new installs)");
console.log(" claude - Update Claude CLI only");
console.log(" gemini - Update Gemini CLI only");
console.log(" copilot - Update GitHub Copilot CLI only");
console.log(" codex - Update Codex CLI only");
console.log(" kilocode - Update Kilo Code CLI only");
console.log(" check - Check installed versions");
process.exit(1);
}
}
main().catch(console.error);