erosolar-cli 1.5.2 → 1.5.3

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.
Files changed (36) hide show
  1. package/dist/capabilities/cloudCapability.d.ts +13 -0
  2. package/dist/capabilities/cloudCapability.d.ts.map +1 -0
  3. package/dist/capabilities/cloudCapability.js +38 -0
  4. package/dist/capabilities/cloudCapability.js.map +1 -0
  5. package/dist/capabilities/index.d.ts +1 -0
  6. package/dist/capabilities/index.d.ts.map +1 -1
  7. package/dist/capabilities/index.js +1 -0
  8. package/dist/capabilities/index.js.map +1 -1
  9. package/dist/plugins/tools/cloud/cloudPlugin.d.ts +3 -0
  10. package/dist/plugins/tools/cloud/cloudPlugin.d.ts.map +1 -0
  11. package/dist/plugins/tools/cloud/cloudPlugin.js +14 -0
  12. package/dist/plugins/tools/cloud/cloudPlugin.js.map +1 -0
  13. package/dist/plugins/tools/nodeDefaults.d.ts.map +1 -1
  14. package/dist/plugins/tools/nodeDefaults.js +2 -0
  15. package/dist/plugins/tools/nodeDefaults.js.map +1 -1
  16. package/dist/security/persistence-analyzer.d.ts +56 -0
  17. package/dist/security/persistence-analyzer.d.ts.map +1 -0
  18. package/dist/security/persistence-analyzer.js +187 -0
  19. package/dist/security/persistence-analyzer.js.map +1 -0
  20. package/dist/security/persistence-research.d.ts +89 -0
  21. package/dist/security/persistence-research.d.ts.map +1 -0
  22. package/dist/security/persistence-research.js +361 -0
  23. package/dist/security/persistence-research.js.map +1 -0
  24. package/dist/shell/bracketedPasteManager.d.ts +43 -0
  25. package/dist/shell/bracketedPasteManager.d.ts.map +1 -1
  26. package/dist/shell/bracketedPasteManager.js +166 -9
  27. package/dist/shell/bracketedPasteManager.js.map +1 -1
  28. package/dist/shell/interactiveShell.d.ts +12 -0
  29. package/dist/shell/interactiveShell.d.ts.map +1 -1
  30. package/dist/shell/interactiveShell.js +47 -0
  31. package/dist/shell/interactiveShell.js.map +1 -1
  32. package/dist/tools/cloudTools.d.ts +46 -0
  33. package/dist/tools/cloudTools.d.ts.map +1 -0
  34. package/dist/tools/cloudTools.js +854 -0
  35. package/dist/tools/cloudTools.js.map +1 -0
  36. package/package.json +1 -1
@@ -0,0 +1,854 @@
1
+ /**
2
+ * Cloud Deployment Tools - Unified cloud CLI capabilities with auto-detection and auto-fix
3
+ *
4
+ * Supports:
5
+ * - Firebase (Hosting, Functions, Firestore, Storage, Auth)
6
+ * - Aliyun/Alibaba Cloud (OSS, FC, ACR, etc.)
7
+ * - AWS (S3, Lambda, CloudFront, etc.)
8
+ * - GCP (Cloud Run, Storage, Functions)
9
+ * - Azure (Static Web Apps, Functions, Blob Storage)
10
+ * - Vercel, Netlify, Cloudflare Pages
11
+ *
12
+ * Features:
13
+ * - Automatic CLI detection and installation checking
14
+ * - Authentication status verification
15
+ * - Auto-fix for common issues
16
+ * - AI-driven error resolution
17
+ */
18
+ import { spawn } from 'child_process';
19
+ import * as fs from 'fs';
20
+ import * as path from 'path';
21
+ const CLOUD_PROVIDERS = {
22
+ firebase: {
23
+ id: 'firebase',
24
+ name: 'Firebase',
25
+ cliCommand: 'firebase',
26
+ versionFlag: '--version',
27
+ installCommand: 'npm install -g firebase-tools',
28
+ installUrl: 'https://firebase.google.com/docs/cli',
29
+ loginCommand: 'firebase login',
30
+ checkAuthCommand: 'firebase projects:list',
31
+ configFile: 'firebase.json',
32
+ envVars: ['FIREBASE_TOKEN', 'GOOGLE_APPLICATION_CREDENTIALS'],
33
+ },
34
+ aliyun: {
35
+ id: 'aliyun',
36
+ name: 'Alibaba Cloud (Aliyun)',
37
+ cliCommand: 'aliyun',
38
+ versionFlag: 'version',
39
+ installCommand: 'brew install aliyun-cli || curl -O https://aliyuncli.alicdn.com/aliyun-cli-linux-amd64-*.tgz',
40
+ installUrl: 'https://www.alibabacloud.com/help/doc-detail/139508.htm',
41
+ loginCommand: 'aliyun configure',
42
+ checkAuthCommand: 'aliyun ecs DescribeRegions',
43
+ configFile: '~/.aliyun/config.json',
44
+ envVars: ['ALIBABA_CLOUD_ACCESS_KEY_ID', 'ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
45
+ },
46
+ aws: {
47
+ id: 'aws',
48
+ name: 'Amazon Web Services',
49
+ cliCommand: 'aws',
50
+ versionFlag: '--version',
51
+ installCommand: 'brew install awscli || pip install awscli',
52
+ installUrl: 'https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html',
53
+ loginCommand: 'aws configure',
54
+ checkAuthCommand: 'aws sts get-caller-identity',
55
+ configFile: '~/.aws/credentials',
56
+ envVars: ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN'],
57
+ },
58
+ gcloud: {
59
+ id: 'gcloud',
60
+ name: 'Google Cloud Platform',
61
+ cliCommand: 'gcloud',
62
+ versionFlag: '--version',
63
+ installCommand: 'brew install --cask google-cloud-sdk',
64
+ installUrl: 'https://cloud.google.com/sdk/docs/install',
65
+ loginCommand: 'gcloud auth login',
66
+ checkAuthCommand: 'gcloud auth list',
67
+ configFile: '~/.config/gcloud/credentials.db',
68
+ envVars: ['GOOGLE_APPLICATION_CREDENTIALS', 'CLOUDSDK_CORE_PROJECT'],
69
+ },
70
+ azure: {
71
+ id: 'azure',
72
+ name: 'Microsoft Azure',
73
+ cliCommand: 'az',
74
+ versionFlag: '--version',
75
+ installCommand: 'brew install azure-cli || curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash',
76
+ installUrl: 'https://docs.microsoft.com/en-us/cli/azure/install-azure-cli',
77
+ loginCommand: 'az login',
78
+ checkAuthCommand: 'az account show',
79
+ configFile: '~/.azure/accessTokens.json',
80
+ envVars: ['AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_TENANT_ID'],
81
+ },
82
+ vercel: {
83
+ id: 'vercel',
84
+ name: 'Vercel',
85
+ cliCommand: 'vercel',
86
+ versionFlag: '--version',
87
+ installCommand: 'npm install -g vercel',
88
+ installUrl: 'https://vercel.com/docs/cli',
89
+ loginCommand: 'vercel login',
90
+ checkAuthCommand: 'vercel whoami',
91
+ envVars: ['VERCEL_TOKEN'],
92
+ },
93
+ netlify: {
94
+ id: 'netlify',
95
+ name: 'Netlify',
96
+ cliCommand: 'netlify',
97
+ versionFlag: '--version',
98
+ installCommand: 'npm install -g netlify-cli',
99
+ installUrl: 'https://docs.netlify.com/cli/get-started/',
100
+ loginCommand: 'netlify login',
101
+ checkAuthCommand: 'netlify status',
102
+ envVars: ['NETLIFY_AUTH_TOKEN'],
103
+ },
104
+ cloudflare: {
105
+ id: 'cloudflare',
106
+ name: 'Cloudflare',
107
+ cliCommand: 'wrangler',
108
+ versionFlag: '--version',
109
+ installCommand: 'npm install -g wrangler',
110
+ installUrl: 'https://developers.cloudflare.com/workers/wrangler/install-and-update/',
111
+ loginCommand: 'wrangler login',
112
+ checkAuthCommand: 'wrangler whoami',
113
+ envVars: ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID'],
114
+ },
115
+ fly: {
116
+ id: 'fly',
117
+ name: 'Fly.io',
118
+ cliCommand: 'flyctl',
119
+ versionFlag: 'version',
120
+ installCommand: 'brew install flyctl || curl -L https://fly.io/install.sh | sh',
121
+ installUrl: 'https://fly.io/docs/hands-on/install-flyctl/',
122
+ loginCommand: 'flyctl auth login',
123
+ checkAuthCommand: 'flyctl auth whoami',
124
+ envVars: ['FLY_API_TOKEN'],
125
+ },
126
+ railway: {
127
+ id: 'railway',
128
+ name: 'Railway',
129
+ cliCommand: 'railway',
130
+ versionFlag: '--version',
131
+ installCommand: 'npm install -g @railway/cli',
132
+ installUrl: 'https://docs.railway.app/develop/cli',
133
+ loginCommand: 'railway login',
134
+ checkAuthCommand: 'railway whoami',
135
+ envVars: ['RAILWAY_TOKEN'],
136
+ },
137
+ supabase: {
138
+ id: 'supabase',
139
+ name: 'Supabase',
140
+ cliCommand: 'supabase',
141
+ versionFlag: '--version',
142
+ installCommand: 'npm install -g supabase',
143
+ installUrl: 'https://supabase.com/docs/guides/cli',
144
+ loginCommand: 'supabase login',
145
+ checkAuthCommand: 'supabase projects list',
146
+ envVars: ['SUPABASE_ACCESS_TOKEN'],
147
+ },
148
+ };
149
+ async function runCommand(command, timeout = 30000) {
150
+ return new Promise((resolve) => {
151
+ const child = spawn('sh', ['-c', command], {
152
+ timeout,
153
+ env: { ...process.env },
154
+ });
155
+ let stdout = '';
156
+ let stderr = '';
157
+ child.stdout?.on('data', (data) => {
158
+ stdout += data.toString();
159
+ });
160
+ child.stderr?.on('data', (data) => {
161
+ stderr += data.toString();
162
+ });
163
+ child.on('close', (code) => {
164
+ resolve({ stdout: stdout.trim(), stderr: stderr.trim(), exitCode: code ?? 1 });
165
+ });
166
+ child.on('error', (err) => {
167
+ resolve({ stdout: '', stderr: err.message, exitCode: 1 });
168
+ });
169
+ });
170
+ }
171
+ async function checkCLIInstalled(provider) {
172
+ try {
173
+ const result = await runCommand(`which ${provider.cliCommand} && ${provider.cliCommand} ${provider.versionFlag} 2>&1 | head -5`);
174
+ if (result.exitCode === 0 && result.stdout) {
175
+ // Extract version from output
176
+ const versionMatch = result.stdout.match(/(\d+\.\d+\.\d+[\w.-]*)/);
177
+ return {
178
+ installed: true,
179
+ version: versionMatch?.[1] || result.stdout.split('\n')[1] || 'unknown',
180
+ };
181
+ }
182
+ return { installed: false, error: result.stderr || 'CLI not found in PATH' };
183
+ }
184
+ catch (error) {
185
+ return { installed: false, error: error instanceof Error ? error.message : String(error) };
186
+ }
187
+ }
188
+ async function checkAuthentication(provider) {
189
+ try {
190
+ const result = await runCommand(provider.checkAuthCommand, 15000);
191
+ if (result.exitCode === 0) {
192
+ return {
193
+ authenticated: true,
194
+ details: result.stdout.slice(0, 500),
195
+ };
196
+ }
197
+ // Check for specific auth errors
198
+ const errorLower = (result.stderr + result.stdout).toLowerCase();
199
+ if (errorLower.includes('not logged in') ||
200
+ errorLower.includes('authentication') ||
201
+ errorLower.includes('credentials') ||
202
+ errorLower.includes('login') ||
203
+ errorLower.includes('token') ||
204
+ errorLower.includes('unauthorized')) {
205
+ return {
206
+ authenticated: false,
207
+ error: 'Not authenticated. Run: ' + provider.loginCommand,
208
+ };
209
+ }
210
+ return { authenticated: false, error: result.stderr || result.stdout };
211
+ }
212
+ catch (error) {
213
+ return { authenticated: false, error: error instanceof Error ? error.message : String(error) };
214
+ }
215
+ }
216
+ async function checkConfigFile(provider, workingDir) {
217
+ if (!provider.configFile) {
218
+ return true;
219
+ }
220
+ // Check for project-level config
221
+ const projectConfig = path.join(workingDir, provider.configFile);
222
+ if (fs.existsSync(projectConfig)) {
223
+ return true;
224
+ }
225
+ // Check for user-level config (expand ~)
226
+ if (provider.configFile.startsWith('~')) {
227
+ const homeConfig = provider.configFile.replace('~', process.env['HOME'] || '');
228
+ if (fs.existsSync(homeConfig)) {
229
+ return true;
230
+ }
231
+ }
232
+ return false;
233
+ }
234
+ async function getFullCLIStatus(providerId, workingDir) {
235
+ const provider = CLOUD_PROVIDERS[providerId];
236
+ if (!provider) {
237
+ return {
238
+ installed: false,
239
+ authenticated: false,
240
+ configExists: false,
241
+ errors: [`Unknown provider: ${providerId}`],
242
+ suggestions: ['Available providers: ' + Object.keys(CLOUD_PROVIDERS).join(', ')],
243
+ };
244
+ }
245
+ const status = {
246
+ installed: false,
247
+ authenticated: false,
248
+ configExists: false,
249
+ errors: [],
250
+ suggestions: [],
251
+ };
252
+ // Check installation
253
+ const installCheck = await checkCLIInstalled(provider);
254
+ status.installed = installCheck.installed;
255
+ status.version = installCheck.version;
256
+ if (!installCheck.installed) {
257
+ status.errors.push(`${provider.name} CLI not installed`);
258
+ status.suggestions.push(`Install with: ${provider.installCommand}`);
259
+ status.suggestions.push(`Documentation: ${provider.installUrl}`);
260
+ return status;
261
+ }
262
+ // Check authentication
263
+ const authCheck = await checkAuthentication(provider);
264
+ status.authenticated = authCheck.authenticated;
265
+ status.authDetails = authCheck.details;
266
+ if (!authCheck.authenticated) {
267
+ status.errors.push(authCheck.error || 'Not authenticated');
268
+ status.suggestions.push(`Authenticate with: ${provider.loginCommand}`);
269
+ if (provider.envVars?.length) {
270
+ status.suggestions.push(`Or set environment variables: ${provider.envVars.join(', ')}`);
271
+ }
272
+ }
273
+ // Check config file
274
+ status.configExists = await checkConfigFile(provider, workingDir);
275
+ if (!status.configExists && provider.configFile) {
276
+ status.errors.push(`Config file not found: ${provider.configFile}`);
277
+ if (provider.configFile.includes('firebase.json')) {
278
+ status.suggestions.push('Initialize project with: firebase init');
279
+ }
280
+ else if (provider.configFile.includes('aliyun')) {
281
+ status.suggestions.push('Configure with: aliyun configure');
282
+ }
283
+ }
284
+ return status;
285
+ }
286
+ async function autoFixIssues(providerId, workingDir) {
287
+ const fixes = [];
288
+ const provider = CLOUD_PROVIDERS[providerId];
289
+ if (!provider) {
290
+ return ['Unknown provider'];
291
+ }
292
+ const status = await getFullCLIStatus(providerId, workingDir);
293
+ // Try to install if not present
294
+ if (!status.installed) {
295
+ fixes.push(`Attempting to install ${provider.name} CLI...`);
296
+ // Try npm install first for npm-based CLIs
297
+ if (provider.installCommand.includes('npm install')) {
298
+ const result = await runCommand(provider.installCommand, 120000);
299
+ if (result.exitCode === 0) {
300
+ fixes.push(`✅ Successfully installed ${provider.name} CLI`);
301
+ }
302
+ else {
303
+ fixes.push(`❌ Failed to install: ${result.stderr}`);
304
+ fixes.push(`Manual install: ${provider.installCommand}`);
305
+ }
306
+ }
307
+ else {
308
+ fixes.push(`Manual installation required: ${provider.installCommand}`);
309
+ fixes.push(`Visit: ${provider.installUrl}`);
310
+ }
311
+ }
312
+ // Check for CI environment variables if not authenticated
313
+ if (!status.authenticated && provider.envVars) {
314
+ const hasEnvAuth = provider.envVars.some((v) => process.env[v]);
315
+ if (hasEnvAuth) {
316
+ fixes.push(`Environment credentials detected for ${provider.name}`);
317
+ }
318
+ else {
319
+ fixes.push(`Authentication required. Run: ${provider.loginCommand}`);
320
+ // For headless/CI environments
321
+ if (process.env['CI'] || !process.stdin.isTTY) {
322
+ fixes.push(`For CI/headless environments, set: ${provider.envVars.join(' or ')}`);
323
+ }
324
+ }
325
+ }
326
+ return fixes;
327
+ }
328
+ export function createCloudTools(workingDir = process.cwd()) {
329
+ return [
330
+ {
331
+ name: 'cloud_status',
332
+ description: `Check the status of cloud CLIs on this system.
333
+
334
+ Detects and reports on:
335
+ - CLI installation status and versions
336
+ - Authentication status
337
+ - Project configuration
338
+ - Required environment variables
339
+
340
+ Supports: Firebase, Aliyun, AWS, GCP, Azure, Vercel, Netlify, Cloudflare, Fly.io, Railway, Supabase
341
+
342
+ Use this before attempting any cloud deployment to ensure everything is properly configured.`,
343
+ parameters: {
344
+ type: 'object',
345
+ properties: {
346
+ providers: {
347
+ type: 'array',
348
+ items: { type: 'string' },
349
+ description: 'Specific providers to check (default: all). Options: firebase, aliyun, aws, gcloud, azure, vercel, netlify, cloudflare, fly, railway, supabase',
350
+ },
351
+ },
352
+ },
353
+ handler: async (args) => {
354
+ const providersToCheck = args['providers'] || Object.keys(CLOUD_PROVIDERS);
355
+ const results = ['☁️ Cloud CLI Status Report\n'];
356
+ for (const providerId of providersToCheck) {
357
+ const provider = CLOUD_PROVIDERS[providerId];
358
+ if (!provider) {
359
+ results.push(`❓ Unknown provider: ${providerId}`);
360
+ continue;
361
+ }
362
+ results.push(`\n--- ${provider.name} (${provider.cliCommand}) ---`);
363
+ const status = await getFullCLIStatus(providerId, workingDir);
364
+ if (status.installed) {
365
+ results.push(`✅ Installed: v${status.version}`);
366
+ }
367
+ else {
368
+ results.push(`❌ Not installed`);
369
+ }
370
+ if (status.installed) {
371
+ if (status.authenticated) {
372
+ results.push(`✅ Authenticated`);
373
+ if (status.authDetails) {
374
+ results.push(` ${status.authDetails.split('\n')[0]}`);
375
+ }
376
+ }
377
+ else {
378
+ results.push(`❌ Not authenticated`);
379
+ }
380
+ if (status.configExists) {
381
+ results.push(`✅ Project config found`);
382
+ }
383
+ else if (provider.configFile) {
384
+ results.push(`⚠️ No project config (${provider.configFile})`);
385
+ }
386
+ }
387
+ if (status.errors.length > 0) {
388
+ results.push(`\nIssues:`);
389
+ for (const err of status.errors) {
390
+ results.push(` ⚠️ ${err}`);
391
+ }
392
+ }
393
+ if (status.suggestions.length > 0) {
394
+ results.push(`\nSuggestions:`);
395
+ for (const sug of status.suggestions) {
396
+ results.push(` 💡 ${sug}`);
397
+ }
398
+ }
399
+ }
400
+ return results.join('\n');
401
+ },
402
+ },
403
+ {
404
+ name: 'cloud_fix',
405
+ description: `Automatically fix cloud CLI issues.
406
+
407
+ Attempts to:
408
+ - Install missing CLIs (via npm/brew where possible)
409
+ - Detect environment credentials
410
+ - Provide step-by-step fix instructions for issues that can't be auto-fixed
411
+
412
+ Use this when cloud_status reports issues.`,
413
+ parameters: {
414
+ type: 'object',
415
+ properties: {
416
+ provider: {
417
+ type: 'string',
418
+ description: 'The cloud provider to fix. Options: firebase, aliyun, aws, gcloud, azure, vercel, netlify, cloudflare, fly, railway, supabase',
419
+ },
420
+ },
421
+ required: ['provider'],
422
+ },
423
+ handler: async (args) => {
424
+ const providerId = args['provider']?.toLowerCase();
425
+ if (!CLOUD_PROVIDERS[providerId]) {
426
+ return `Unknown provider: ${providerId}\n\nAvailable: ${Object.keys(CLOUD_PROVIDERS).join(', ')}`;
427
+ }
428
+ const fixes = await autoFixIssues(providerId, workingDir);
429
+ return `🔧 Auto-Fix Results for ${CLOUD_PROVIDERS[providerId]?.name}\n\n${fixes.join('\n')}`;
430
+ },
431
+ },
432
+ {
433
+ name: 'firebase_deploy',
434
+ description: `Deploy to Firebase (Hosting, Functions, Firestore rules, Storage rules).
435
+
436
+ Automatically:
437
+ - Checks Firebase CLI status
438
+ - Validates firebase.json configuration
439
+ - Handles authentication issues
440
+ - Provides detailed deployment logs
441
+
442
+ Supports:
443
+ - firebase deploy --only hosting
444
+ - firebase deploy --only functions
445
+ - firebase deploy --only firestore
446
+ - firebase deploy --only storage
447
+ - firebase deploy (all)`,
448
+ parameters: {
449
+ type: 'object',
450
+ properties: {
451
+ target: {
452
+ type: 'string',
453
+ description: 'Deployment target: "hosting", "functions", "firestore", "storage", "all" (default: all)',
454
+ },
455
+ project: {
456
+ type: 'string',
457
+ description: 'Firebase project ID (uses default if not specified)',
458
+ },
459
+ dry_run: {
460
+ type: 'boolean',
461
+ description: 'Preview deployment without actually deploying (default: false)',
462
+ },
463
+ },
464
+ },
465
+ handler: async (args) => {
466
+ const target = args['target'] || 'all';
467
+ const project = args['project'];
468
+ const dryRun = args['dry_run'] === true;
469
+ // First check status
470
+ const status = await getFullCLIStatus('firebase', workingDir);
471
+ if (!status.installed) {
472
+ return `Firebase CLI not installed.\n\n🔧 Auto-fix: Run \`npm install -g firebase-tools\`\n\nOr use cloud_fix tool with provider="firebase"`;
473
+ }
474
+ if (!status.authenticated) {
475
+ return `Firebase not authenticated.\n\n🔧 Fix options:\n1. Interactive: \`firebase login\`\n2. CI/Headless: \`firebase login:ci\` and set FIREBASE_TOKEN\n3. Service account: Set GOOGLE_APPLICATION_CREDENTIALS`;
476
+ }
477
+ if (!status.configExists) {
478
+ return `No firebase.json found in ${workingDir}.\n\n🔧 Initialize with: \`firebase init\``;
479
+ }
480
+ // Build deploy command
481
+ let cmd = 'firebase deploy';
482
+ if (target !== 'all') {
483
+ cmd += ` --only ${target}`;
484
+ }
485
+ if (project) {
486
+ cmd += ` --project ${project}`;
487
+ }
488
+ if (dryRun) {
489
+ cmd += ' --dry-run';
490
+ }
491
+ cmd += ' 2>&1';
492
+ const result = await runCommand(`cd "${workingDir}" && ${cmd}`, 300000); // 5 min timeout
493
+ if (result.exitCode === 0) {
494
+ return `✅ Firebase deployment successful!\n\n${result.stdout}`;
495
+ }
496
+ // Analyze error and provide fixes
497
+ const output = result.stdout + result.stderr;
498
+ let fix = '';
499
+ if (output.includes('authentication') || output.includes('login')) {
500
+ fix = '\n\n🔧 Fix: Run `firebase login --reauth`';
501
+ }
502
+ else if (output.includes('permission') || output.includes('denied')) {
503
+ fix = '\n\n🔧 Fix: Check Firebase project permissions at https://console.firebase.google.com';
504
+ }
505
+ else if (output.includes('quota') || output.includes('limit')) {
506
+ fix = '\n\n🔧 Fix: Quota exceeded. Check billing at https://console.firebase.google.com/billing';
507
+ }
508
+ else if (output.includes('build') || output.includes('compile')) {
509
+ fix = '\n\n🔧 Fix: Build errors detected. Run your build command first (e.g., npm run build)';
510
+ }
511
+ return `❌ Firebase deployment failed\n\n${output}${fix}`;
512
+ },
513
+ },
514
+ {
515
+ name: 'aliyun_deploy',
516
+ description: `Deploy to Alibaba Cloud (Aliyun).
517
+
518
+ Supports:
519
+ - OSS (Object Storage Service) - static file hosting
520
+ - FC (Function Compute) - serverless functions
521
+ - ACR (Container Registry) - Docker images
522
+ - ECS (Elastic Compute Service) - VM management
523
+
524
+ Automatically handles authentication and common issues.`,
525
+ parameters: {
526
+ type: 'object',
527
+ properties: {
528
+ service: {
529
+ type: 'string',
530
+ description: 'Service to deploy: "oss", "fc", "acr", "ecs"',
531
+ },
532
+ action: {
533
+ type: 'string',
534
+ description: 'Action to perform (service-specific)',
535
+ },
536
+ region: {
537
+ type: 'string',
538
+ description: 'Aliyun region (e.g., cn-hangzhou, cn-shanghai)',
539
+ },
540
+ args: {
541
+ type: 'string',
542
+ description: 'Additional CLI arguments',
543
+ },
544
+ },
545
+ required: ['service', 'action'],
546
+ },
547
+ handler: async (args) => {
548
+ const service = args['service'];
549
+ const action = args['action'];
550
+ const region = args['region'];
551
+ const extraArgs = args['args'];
552
+ // Check status
553
+ const status = await getFullCLIStatus('aliyun', workingDir);
554
+ if (!status.installed) {
555
+ return `Aliyun CLI not installed.\n\n🔧 Install:\n- macOS: brew install aliyun-cli\n- Linux: curl -O https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz\n\nDocs: https://www.alibabacloud.com/help/doc-detail/139508.htm`;
556
+ }
557
+ if (!status.authenticated) {
558
+ return `Aliyun not configured.\n\n🔧 Fix:\n1. Run: aliyun configure\n2. Enter your AccessKey ID and Secret\n3. Get keys at: https://ram.console.aliyun.com/manage/ak\n\nOr set environment variables:\n- ALIBABA_CLOUD_ACCESS_KEY_ID\n- ALIBABA_CLOUD_ACCESS_KEY_SECRET`;
559
+ }
560
+ // Build command
561
+ let cmd = `aliyun ${service} ${action}`;
562
+ if (region) {
563
+ cmd += ` --region ${region}`;
564
+ }
565
+ if (extraArgs) {
566
+ cmd += ` ${extraArgs}`;
567
+ }
568
+ cmd += ' 2>&1';
569
+ const result = await runCommand(cmd, 120000);
570
+ if (result.exitCode === 0) {
571
+ return `✅ Aliyun ${service} ${action} successful!\n\n${result.stdout}`;
572
+ }
573
+ // Error analysis
574
+ const output = result.stdout + result.stderr;
575
+ let fix = '';
576
+ if (output.includes('InvalidAccessKeyId') || output.includes('SignatureDoesNotMatch')) {
577
+ fix = '\n\n🔧 Fix: Invalid credentials. Run `aliyun configure` with correct AccessKey';
578
+ }
579
+ else if (output.includes('Forbidden')) {
580
+ fix = '\n\n🔧 Fix: Permission denied. Check RAM policies at https://ram.console.aliyun.com';
581
+ }
582
+ return `❌ Aliyun command failed\n\n${output}${fix}`;
583
+ },
584
+ },
585
+ {
586
+ name: 'cloud_deploy',
587
+ description: `Universal cloud deployment command that works across providers.
588
+
589
+ Automatically:
590
+ - Detects project type and configuration
591
+ - Selects appropriate deployment target
592
+ - Handles provider-specific requirements
593
+ - Auto-fixes common issues
594
+
595
+ Supports deployment to:
596
+ - Firebase, Vercel, Netlify for web apps
597
+ - AWS Lambda, GCP Functions, Azure Functions for serverless
598
+ - Cloudflare Workers/Pages for edge deployments
599
+ - Fly.io, Railway for containers`,
600
+ parameters: {
601
+ type: 'object',
602
+ properties: {
603
+ provider: {
604
+ type: 'string',
605
+ description: 'Cloud provider: firebase, vercel, netlify, cloudflare, fly, railway, aws, gcloud, azure',
606
+ },
607
+ command: {
608
+ type: 'string',
609
+ description: 'Deployment command (e.g., "deploy", "deploy --prod")',
610
+ },
611
+ auto_fix: {
612
+ type: 'boolean',
613
+ description: 'Automatically attempt to fix issues (default: true)',
614
+ },
615
+ },
616
+ required: ['provider'],
617
+ },
618
+ handler: async (args) => {
619
+ const providerId = args['provider']?.toLowerCase();
620
+ const command = args['command'] || 'deploy';
621
+ const autoFix = args['auto_fix'] !== false;
622
+ const provider = CLOUD_PROVIDERS[providerId];
623
+ if (!provider) {
624
+ return `Unknown provider: ${providerId}\n\nAvailable: ${Object.keys(CLOUD_PROVIDERS).join(', ')}`;
625
+ }
626
+ // Check and potentially fix status
627
+ let status = await getFullCLIStatus(providerId, workingDir);
628
+ if (!status.installed && autoFix) {
629
+ const fixes = await autoFixIssues(providerId, workingDir);
630
+ // Re-check after fix attempt
631
+ status = await getFullCLIStatus(providerId, workingDir);
632
+ if (!status.installed) {
633
+ return `${provider.name} CLI could not be installed.\n\n${fixes.join('\n')}`;
634
+ }
635
+ }
636
+ if (!status.installed) {
637
+ return `${provider.name} CLI not installed.\n\nInstall: ${provider.installCommand}\nDocs: ${provider.installUrl}`;
638
+ }
639
+ if (!status.authenticated) {
640
+ return `${provider.name} not authenticated.\n\nFix: ${provider.loginCommand}\n\nFor CI, set: ${provider.envVars?.join(' or ') || 'appropriate credentials'}`;
641
+ }
642
+ // Execute deployment
643
+ const cmd = `${provider.cliCommand} ${command} 2>&1`;
644
+ const result = await runCommand(`cd "${workingDir}" && ${cmd}`, 300000);
645
+ if (result.exitCode === 0) {
646
+ return `✅ ${provider.name} deployment successful!\n\n${result.stdout}`;
647
+ }
648
+ // Provide error context and fixes
649
+ const output = result.stdout + result.stderr;
650
+ // AI-driven error analysis
651
+ const errorAnalysis = analyzeDeploymentError(output, provider);
652
+ return `❌ ${provider.name} deployment failed\n\n${output}\n\n${errorAnalysis}`;
653
+ },
654
+ },
655
+ {
656
+ name: 'cloud_init',
657
+ description: `Initialize a cloud project configuration.
658
+
659
+ Creates configuration files and sets up project structure for:
660
+ - Firebase (firebase.json, .firebaserc)
661
+ - Vercel (vercel.json)
662
+ - Netlify (netlify.toml)
663
+ - Cloudflare (wrangler.toml)
664
+
665
+ Auto-detects project type (React, Vue, Angular, Next.js, etc.) and configures appropriately.`,
666
+ parameters: {
667
+ type: 'object',
668
+ properties: {
669
+ provider: {
670
+ type: 'string',
671
+ description: 'Cloud provider to initialize: firebase, vercel, netlify, cloudflare',
672
+ },
673
+ project_type: {
674
+ type: 'string',
675
+ description: 'Project type: react, vue, angular, nextjs, static, node (auto-detected if not specified)',
676
+ },
677
+ },
678
+ required: ['provider'],
679
+ },
680
+ handler: async (args) => {
681
+ const providerId = args['provider']?.toLowerCase();
682
+ const projectType = args['project_type'];
683
+ // Detect project type if not specified
684
+ const detectedType = projectType || detectProjectType(workingDir);
685
+ const configs = {
686
+ firebase: () => generateFirebaseConfig(detectedType, workingDir),
687
+ vercel: () => generateVercelConfig(detectedType),
688
+ netlify: () => generateNetlifyConfig(detectedType),
689
+ cloudflare: () => generateCloudflareConfig(detectedType),
690
+ };
691
+ if (!configs[providerId]) {
692
+ return `Initialization not supported for: ${providerId}\n\nSupported: firebase, vercel, netlify, cloudflare`;
693
+ }
694
+ const config = configs[providerId]();
695
+ return `📝 ${CLOUD_PROVIDERS[providerId]?.name || providerId} Configuration\n\nProject type: ${detectedType}\n\n${config}`;
696
+ },
697
+ },
698
+ ];
699
+ }
700
+ // Helper functions
701
+ function analyzeDeploymentError(output, provider) {
702
+ const suggestions = ['🔍 Error Analysis:'];
703
+ const lower = output.toLowerCase();
704
+ // Authentication issues
705
+ if (lower.includes('auth') || lower.includes('login') || lower.includes('token') || lower.includes('credential')) {
706
+ suggestions.push(`• Authentication issue detected`);
707
+ suggestions.push(` Fix: ${provider.loginCommand}`);
708
+ if (provider.envVars?.length) {
709
+ suggestions.push(` CI: Set ${provider.envVars[0]}`);
710
+ }
711
+ }
712
+ // Permission issues
713
+ if (lower.includes('permission') || lower.includes('denied') || lower.includes('forbidden') || lower.includes('access')) {
714
+ suggestions.push(`• Permission issue detected`);
715
+ suggestions.push(` Check your account permissions/roles`);
716
+ }
717
+ // Build issues
718
+ if (lower.includes('build') || lower.includes('compile') || lower.includes('error') || lower.includes('failed')) {
719
+ suggestions.push(`• Build/compile error detected`);
720
+ suggestions.push(` Run your build command locally first`);
721
+ }
722
+ // Network issues
723
+ if (lower.includes('network') || lower.includes('timeout') || lower.includes('econnrefused') || lower.includes('dns')) {
724
+ suggestions.push(`• Network connectivity issue`);
725
+ suggestions.push(` Check your internet connection`);
726
+ }
727
+ // Quota/limits
728
+ if (lower.includes('quota') || lower.includes('limit') || lower.includes('exceeded') || lower.includes('billing')) {
729
+ suggestions.push(`• Quota/billing issue detected`);
730
+ suggestions.push(` Check your account billing status`);
731
+ }
732
+ // Config issues
733
+ if (lower.includes('config') || lower.includes('not found') || lower.includes('missing')) {
734
+ suggestions.push(`• Configuration issue detected`);
735
+ suggestions.push(` Use cloud_init to create configuration`);
736
+ }
737
+ if (suggestions.length === 1) {
738
+ suggestions.push(`• Unable to determine specific cause`);
739
+ suggestions.push(` Try running the command directly for more details`);
740
+ }
741
+ return suggestions.join('\n');
742
+ }
743
+ function detectProjectType(dir) {
744
+ // Check for common framework indicators
745
+ const packageJsonPath = path.join(dir, 'package.json');
746
+ if (fs.existsSync(packageJsonPath)) {
747
+ try {
748
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
749
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
750
+ if (deps['next'])
751
+ return 'nextjs';
752
+ if (deps['@angular/core'])
753
+ return 'angular';
754
+ if (deps['vue'])
755
+ return 'vue';
756
+ if (deps['react'])
757
+ return 'react';
758
+ if (deps['svelte'])
759
+ return 'svelte';
760
+ if (deps['express'] || deps['fastify'] || deps['koa'])
761
+ return 'node';
762
+ }
763
+ catch {
764
+ // Ignore parse errors
765
+ }
766
+ }
767
+ // Check for index.html (static site)
768
+ if (fs.existsSync(path.join(dir, 'index.html')) || fs.existsSync(path.join(dir, 'public', 'index.html'))) {
769
+ return 'static';
770
+ }
771
+ return 'unknown';
772
+ }
773
+ function generateFirebaseConfig(projectType, _dir) {
774
+ const buildDirs = {
775
+ react: 'build',
776
+ nextjs: 'out',
777
+ angular: 'dist',
778
+ vue: 'dist',
779
+ svelte: 'public',
780
+ static: 'public',
781
+ unknown: 'public',
782
+ };
783
+ const buildDir = buildDirs[projectType] || 'public';
784
+ const config = {
785
+ hosting: {
786
+ public: buildDir,
787
+ ignore: ['firebase.json', '**/.*', '**/node_modules/**'],
788
+ rewrites: [{ source: '**', destination: '/index.html' }],
789
+ },
790
+ };
791
+ return `Create firebase.json:
792
+ \`\`\`json
793
+ ${JSON.stringify(config, null, 2)}
794
+ \`\`\`
795
+
796
+ Then run: firebase init
797
+ Select Hosting and follow the prompts.`;
798
+ }
799
+ function generateVercelConfig(projectType) {
800
+ const configs = {
801
+ nextjs: {}, // Vercel auto-detects Next.js
802
+ react: { buildCommand: 'npm run build', outputDirectory: 'build' },
803
+ vue: { buildCommand: 'npm run build', outputDirectory: 'dist' },
804
+ angular: { buildCommand: 'npm run build', outputDirectory: 'dist' },
805
+ static: { buildCommand: null, outputDirectory: '.' },
806
+ unknown: {},
807
+ };
808
+ const config = configs[projectType] || configs['unknown'];
809
+ return `Create vercel.json:
810
+ \`\`\`json
811
+ ${JSON.stringify(config, null, 2)}
812
+ \`\`\`
813
+
814
+ Then run: vercel`;
815
+ }
816
+ function generateNetlifyConfig(projectType) {
817
+ const configs = {
818
+ react: { command: 'npm run build', publish: 'build' },
819
+ nextjs: { command: 'npm run build', publish: '.next' },
820
+ vue: { command: 'npm run build', publish: 'dist' },
821
+ angular: { command: 'npm run build', publish: 'dist' },
822
+ static: { command: '', publish: '.' },
823
+ unknown: { command: 'npm run build', publish: 'public' },
824
+ };
825
+ const config = configs[projectType] || configs['unknown'] || { command: 'npm run build', publish: 'public' };
826
+ return `Create netlify.toml:
827
+ \`\`\`toml
828
+ [build]
829
+ command = "${config.command}"
830
+ publish = "${config.publish}"
831
+
832
+ [[redirects]]
833
+ from = "/*"
834
+ to = "/index.html"
835
+ status = 200
836
+ \`\`\`
837
+
838
+ Then run: netlify deploy`;
839
+ }
840
+ function generateCloudflareConfig(projectType) {
841
+ return `Create wrangler.toml:
842
+ \`\`\`toml
843
+ name = "my-${projectType}-app"
844
+ main = "src/index.js"
845
+ compatibility_date = "${new Date().toISOString().split('T')[0]}"
846
+
847
+ [site]
848
+ bucket = "./dist"
849
+ \`\`\`
850
+
851
+ For Pages, run: npx wrangler pages project create`;
852
+ }
853
+ export { CLOUD_PROVIDERS, getFullCLIStatus, autoFixIssues };
854
+ //# sourceMappingURL=cloudTools.js.map