@edgible-team/cli 1.0.1

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 (102) hide show
  1. package/LICENSE +136 -0
  2. package/README.md +450 -0
  3. package/dist/client/api-client.js +1057 -0
  4. package/dist/client/index.js +21 -0
  5. package/dist/commands/agent.js +1280 -0
  6. package/dist/commands/ai.js +608 -0
  7. package/dist/commands/application.js +885 -0
  8. package/dist/commands/auth.js +570 -0
  9. package/dist/commands/base/BaseCommand.js +93 -0
  10. package/dist/commands/base/CommandHandler.js +7 -0
  11. package/dist/commands/base/command-wrapper.js +58 -0
  12. package/dist/commands/base/middleware.js +77 -0
  13. package/dist/commands/config.js +116 -0
  14. package/dist/commands/connectivity.js +59 -0
  15. package/dist/commands/debug.js +98 -0
  16. package/dist/commands/discover.js +144 -0
  17. package/dist/commands/examples/migrated-command-example.js +180 -0
  18. package/dist/commands/gateway.js +494 -0
  19. package/dist/commands/managedGateway.js +787 -0
  20. package/dist/commands/utils/config-validator.js +76 -0
  21. package/dist/commands/utils/gateway-prompt.js +79 -0
  22. package/dist/commands/utils/input-parser.js +120 -0
  23. package/dist/commands/utils/output-formatter.js +109 -0
  24. package/dist/config/app-config.js +99 -0
  25. package/dist/detection/SystemCapabilityDetector.js +1244 -0
  26. package/dist/detection/ToolDetector.js +305 -0
  27. package/dist/detection/WorkloadDetector.js +314 -0
  28. package/dist/di/bindings.js +99 -0
  29. package/dist/di/container.js +88 -0
  30. package/dist/di/types.js +32 -0
  31. package/dist/index.js +52 -0
  32. package/dist/interfaces/IDaemonManager.js +3 -0
  33. package/dist/repositories/config-repository.js +62 -0
  34. package/dist/repositories/gateway-repository.js +35 -0
  35. package/dist/scripts/postinstall.js +101 -0
  36. package/dist/services/AgentStatusManager.js +299 -0
  37. package/dist/services/ConnectivityTester.js +271 -0
  38. package/dist/services/DependencyInstaller.js +475 -0
  39. package/dist/services/LocalAgentManager.js +2216 -0
  40. package/dist/services/application/ApplicationService.js +299 -0
  41. package/dist/services/auth/AuthService.js +214 -0
  42. package/dist/services/aws.js +644 -0
  43. package/dist/services/daemon/DaemonManagerFactory.js +65 -0
  44. package/dist/services/daemon/DockerDaemonManager.js +395 -0
  45. package/dist/services/daemon/LaunchdDaemonManager.js +257 -0
  46. package/dist/services/daemon/PodmanDaemonManager.js +369 -0
  47. package/dist/services/daemon/SystemdDaemonManager.js +221 -0
  48. package/dist/services/daemon/WindowsServiceDaemonManager.js +210 -0
  49. package/dist/services/daemon/index.js +16 -0
  50. package/dist/services/edgible.js +3060 -0
  51. package/dist/services/gateway/GatewayService.js +334 -0
  52. package/dist/state/config.js +146 -0
  53. package/dist/types/AgentConfig.js +5 -0
  54. package/dist/types/AgentStatus.js +5 -0
  55. package/dist/types/ApiClient.js +5 -0
  56. package/dist/types/ApiRequests.js +5 -0
  57. package/dist/types/ApiResponses.js +5 -0
  58. package/dist/types/Application.js +5 -0
  59. package/dist/types/CaddyJson.js +5 -0
  60. package/dist/types/UnifiedAgentStatus.js +56 -0
  61. package/dist/types/WireGuard.js +5 -0
  62. package/dist/types/Workload.js +5 -0
  63. package/dist/types/agent.js +5 -0
  64. package/dist/types/command-options.js +5 -0
  65. package/dist/types/connectivity.js +5 -0
  66. package/dist/types/errors.js +250 -0
  67. package/dist/types/gateway-types.js +5 -0
  68. package/dist/types/index.js +48 -0
  69. package/dist/types/models/ApplicationData.js +5 -0
  70. package/dist/types/models/CertificateData.js +5 -0
  71. package/dist/types/models/DeviceData.js +5 -0
  72. package/dist/types/models/DevicePoolData.js +5 -0
  73. package/dist/types/models/OrganizationData.js +5 -0
  74. package/dist/types/models/OrganizationInviteData.js +5 -0
  75. package/dist/types/models/ProviderConfiguration.js +5 -0
  76. package/dist/types/models/ResourceData.js +5 -0
  77. package/dist/types/models/ServiceResourceData.js +5 -0
  78. package/dist/types/models/UserData.js +5 -0
  79. package/dist/types/route.js +5 -0
  80. package/dist/types/validation/schemas.js +218 -0
  81. package/dist/types/validation.js +5 -0
  82. package/dist/utils/FileIntegrityManager.js +256 -0
  83. package/dist/utils/PathMigration.js +219 -0
  84. package/dist/utils/PathResolver.js +235 -0
  85. package/dist/utils/PlatformDetector.js +277 -0
  86. package/dist/utils/console-logger.js +130 -0
  87. package/dist/utils/docker-compose-parser.js +179 -0
  88. package/dist/utils/errors.js +130 -0
  89. package/dist/utils/health-checker.js +155 -0
  90. package/dist/utils/json-logger.js +72 -0
  91. package/dist/utils/log-formatter.js +293 -0
  92. package/dist/utils/logger.js +59 -0
  93. package/dist/utils/network-utils.js +217 -0
  94. package/dist/utils/output.js +182 -0
  95. package/dist/utils/passwordValidation.js +91 -0
  96. package/dist/utils/progress.js +167 -0
  97. package/dist/utils/sudo-checker.js +22 -0
  98. package/dist/utils/urls.js +32 -0
  99. package/dist/utils/validation.js +31 -0
  100. package/dist/validation/schemas.js +175 -0
  101. package/dist/validation/validator.js +67 -0
  102. package/package.json +83 -0
@@ -0,0 +1,1280 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.setupAgentCommands = setupAgentCommands;
40
+ const chalk_1 = __importDefault(require("chalk"));
41
+ const inquirer_1 = __importDefault(require("inquirer"));
42
+ const os = __importStar(require("os"));
43
+ const path = __importStar(require("path"));
44
+ const fs = __importStar(require("fs"));
45
+ const fsPromises = __importStar(require("fs/promises"));
46
+ const AgentStatusManager_1 = require("../services/AgentStatusManager");
47
+ const command_wrapper_1 = require("./base/command-wrapper");
48
+ const container_1 = require("../di/container");
49
+ const types_1 = require("../di/types");
50
+ const config_validator_1 = require("./utils/config-validator");
51
+ const DependencyInstaller_1 = require("../services/DependencyInstaller");
52
+ const PlatformDetector_1 = require("../utils/PlatformDetector");
53
+ const DaemonManagerFactory_1 = require("../services/daemon/DaemonManagerFactory");
54
+ const PathResolver_1 = require("../utils/PathResolver");
55
+ const urls_1 = require("../utils/urls");
56
+ const log_formatter_1 = require("../utils/log-formatter");
57
+ function setupAgentCommands(program) {
58
+ const agentCommand = program
59
+ .command('agent')
60
+ .description('Manage the local Edgible agent');
61
+ agentCommand
62
+ .command('status')
63
+ .description('Check local agent status')
64
+ .option('--watch', 'Watch status changes in real-time')
65
+ .action((0, command_wrapper_1.wrapCommand)(async (options) => {
66
+ const container = (0, container_1.getContainer)();
67
+ const logger = container.get(types_1.TYPES.Logger);
68
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
69
+ const agentManager = container.get(types_1.TYPES.LocalAgentManager);
70
+ const statusManager = new AgentStatusManager_1.AgentStatusManager();
71
+ const config = configRepository.getConfig();
72
+ if (options.watch) {
73
+ logger.debug('Watching agent status');
74
+ console.log(chalk_1.default.blue('Watching agent status (Ctrl+C to stop)...'));
75
+ let lastStatus = null;
76
+ statusManager.startWatching((result) => {
77
+ // Only update display if status changed significantly
78
+ if (!lastStatus || JSON.stringify(lastStatus) !== JSON.stringify(result)) {
79
+ lastStatus = result;
80
+ // Show installation type first
81
+ if (config.agentInstallationType) {
82
+ console.log(chalk_1.default.gray(`\nInstallation Type: ${config.agentInstallationType}`));
83
+ }
84
+ agentManager.displayAgentStatus(result.status);
85
+ }
86
+ });
87
+ }
88
+ else {
89
+ logger.debug('Checking agent status');
90
+ // Show installation type
91
+ if (config.agentInstallationType) {
92
+ console.log(chalk_1.default.blue('\nšŸ“‹ Agent Configuration'));
93
+ console.log(chalk_1.default.gray(` Installation Type: ${config.agentInstallationType}`));
94
+ if (config.agentServiceName) {
95
+ console.log(chalk_1.default.gray(` Service Name: ${config.agentServiceName}`));
96
+ }
97
+ if (config.agentContainerName) {
98
+ console.log(chalk_1.default.gray(` Container Name: ${config.agentContainerName}`));
99
+ }
100
+ console.log('');
101
+ }
102
+ // Get daemon status if available
103
+ if (config.agentInstallationType) {
104
+ try {
105
+ const daemonManager = DaemonManagerFactory_1.DaemonManagerFactory.fromConfig(config.agentInstallationType);
106
+ if (daemonManager) {
107
+ console.log(chalk_1.default.blue('šŸ”§ Daemon Status'));
108
+ const daemonStatus = await daemonManager.status();
109
+ console.log(chalk_1.default.gray(` Running: ${daemonStatus.running ? chalk_1.default.green('Yes') : chalk_1.default.red('No')}`));
110
+ console.log(chalk_1.default.gray(` Enabled: ${daemonStatus.enabled ? chalk_1.default.green('Yes') : chalk_1.default.gray('No')}`));
111
+ if (daemonStatus.pid) {
112
+ console.log(chalk_1.default.gray(` PID: ${daemonStatus.pid}`));
113
+ }
114
+ console.log('');
115
+ }
116
+ }
117
+ catch (error) {
118
+ console.log(chalk_1.default.yellow('⚠ Could not fetch daemon status\n'));
119
+ }
120
+ }
121
+ // Get agent status from status file
122
+ console.log(chalk_1.default.blue('šŸ¤– Agent Status'));
123
+ const status = await agentManager.checkLocalAgentStatus();
124
+ agentManager.displayAgentStatus(status);
125
+ }
126
+ }, {
127
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
128
+ }));
129
+ agentCommand
130
+ .command('install')
131
+ .description('Install and configure the local agent as a daemon')
132
+ .option('--type <type>', 'Installation type (systemd|launchd|windows-service|docker|podman)')
133
+ .option('--dev', 'Run in development mode (foreground, no daemon)')
134
+ .option('--build', 'Build container image locally instead of pulling')
135
+ .option('--registry <url>', 'Container registry URL for pulling pre-built images')
136
+ .option('--local', 'Use local agent build from agent-v2/dist/ (development only)')
137
+ .action((0, command_wrapper_1.wrapCommand)(async (options) => {
138
+ const container = (0, container_1.getContainer)();
139
+ const logger = container.get(types_1.TYPES.Logger);
140
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
141
+ const edgibleService = container.get(types_1.TYPES.EdgibleService);
142
+ const authService = container.get(types_1.TYPES.AuthService);
143
+ const agentManager = container.get(types_1.TYPES.LocalAgentManager);
144
+ (0, config_validator_1.validateConfig)(configRepository, {
145
+ requireAuth: true,
146
+ requireOrganization: true,
147
+ });
148
+ console.log(chalk_1.default.blue.bold('\n═══════════════════════════════════════════'));
149
+ console.log(chalk_1.default.blue.bold(' Edgible Agent Installation'));
150
+ console.log(chalk_1.default.blue.bold('═══════════════════════════════════════════\n'));
151
+ // Step 1: Check platform and root privileges
152
+ const platform = PlatformDetector_1.PlatformDetector.getPlatform();
153
+ const isRoot = await PlatformDetector_1.PlatformDetector.isRoot();
154
+ console.log(chalk_1.default.gray(`Platform: ${platform}`));
155
+ console.log(chalk_1.default.gray(`Running as ${isRoot ? 'root/administrator' : 'regular user'}\n`));
156
+ if (!isRoot) {
157
+ console.log(chalk_1.default.yellow('⚠ ' + PlatformDetector_1.PlatformDetector.getRootRequirementMessage()));
158
+ console.log(chalk_1.default.gray(' Some installation options require elevated privileges.\n'));
159
+ }
160
+ // Step 2: Device Selection (moved from start command)
161
+ const config = configRepository.getConfig();
162
+ let deviceId = config.deviceId;
163
+ let devicePassword = config.devicePassword;
164
+ console.log(chalk_1.default.blue('šŸ“± Device Selection'));
165
+ console.log(chalk_1.default.gray('Select which serving device this agent should represent:\n'));
166
+ try {
167
+ // Fetch available serving devices
168
+ const servingDevicesResp = await edgibleService.listServingDevices();
169
+ const servingDevices = servingDevicesResp?.devices || [];
170
+ if (servingDevices.length > 0) {
171
+ // Show list of devices to select from
172
+ const deviceChoices = servingDevices.map((d) => {
173
+ const isCurrentDevice = config.deviceId === d.id;
174
+ const displayName = `${d.name || d.id}${d.description ? ` - ${d.description}` : ''}${isCurrentDevice ? chalk_1.default.gray(' (current)') : ''}`;
175
+ return {
176
+ name: displayName,
177
+ value: d.id
178
+ };
179
+ });
180
+ // Add option to create new device
181
+ deviceChoices.push({
182
+ name: chalk_1.default.cyan('āž• Create new serving device'),
183
+ value: '__create_new__'
184
+ });
185
+ const { selectedDeviceId } = await inquirer_1.default.prompt([{
186
+ type: 'list',
187
+ name: 'selectedDeviceId',
188
+ message: 'Select serving device:',
189
+ choices: deviceChoices,
190
+ default: config.deviceId || undefined
191
+ }]);
192
+ if (selectedDeviceId === '__create_new__') {
193
+ // Create new device
194
+ const deviceNameAnswer = await inquirer_1.default.prompt([{
195
+ type: 'input',
196
+ name: 'deviceName',
197
+ message: 'Enter a name for this device:',
198
+ default: `${os.hostname()}-${os.platform()}`,
199
+ validate: (input) => {
200
+ if (!input.trim()) {
201
+ return 'Device name is required';
202
+ }
203
+ return true;
204
+ }
205
+ }]);
206
+ const descriptionAnswer = await inquirer_1.default.prompt([{
207
+ type: 'input',
208
+ name: 'description',
209
+ message: 'Enter device description (optional):',
210
+ default: `Serving device: ${deviceNameAnswer.deviceName}`
211
+ }]);
212
+ console.log(chalk_1.default.gray('\nCreating device...'));
213
+ const createResponse = await edgibleService.createServingDevice({
214
+ name: deviceNameAnswer.deviceName.trim(),
215
+ description: descriptionAnswer.description.trim()
216
+ });
217
+ deviceId = createResponse.device.id;
218
+ devicePassword = createResponse.device.password;
219
+ console.log(chalk_1.default.green(`āœ“ Device created: ${deviceId}`));
220
+ console.log(chalk_1.default.yellow(`\n⚠ Device Password: ${devicePassword}`));
221
+ console.log(chalk_1.default.yellow('⚠ Please save this password securely!\n'));
222
+ // Verify device credentials
223
+ if (devicePassword && deviceId) {
224
+ console.log(chalk_1.default.gray('Verifying device credentials...'));
225
+ try {
226
+ const isValid = await authService.verifyDeviceCredentials(deviceId, devicePassword);
227
+ if (isValid) {
228
+ console.log(chalk_1.default.green('āœ“ Device credentials verified\n'));
229
+ }
230
+ }
231
+ catch (verifyError) {
232
+ console.log(chalk_1.default.yellow('⚠ Could not verify device credentials\n'));
233
+ }
234
+ }
235
+ // Save device credentials to config
236
+ configRepository.updateConfig({
237
+ deviceId: deviceId,
238
+ deviceName: deviceNameAnswer.deviceName.trim(),
239
+ devicePassword: devicePassword,
240
+ deviceType: 'serving'
241
+ });
242
+ }
243
+ else {
244
+ // Use existing device - need to fetch full details to get password
245
+ deviceId = selectedDeviceId;
246
+ if (!deviceId) {
247
+ throw new Error('No device selected');
248
+ }
249
+ console.log(chalk_1.default.gray('Retrieving device credentials...\n'));
250
+ // Fetch device details to get the plaintext password
251
+ const deviceResponse = await edgibleService.getDevice(deviceId);
252
+ devicePassword = deviceResponse.device?.password || '';
253
+ if (!devicePassword) {
254
+ throw new Error('Could not retrieve device password from API');
255
+ }
256
+ // Save device credentials to config
257
+ configRepository.updateConfig({
258
+ deviceId,
259
+ devicePassword,
260
+ deviceType: 'serving'
261
+ });
262
+ console.log(chalk_1.default.green(`āœ“ Using device: ${deviceId}\n`));
263
+ }
264
+ }
265
+ else {
266
+ // No devices exist, must create one
267
+ console.log(chalk_1.default.yellow('No serving devices found. Creating a new one...\n'));
268
+ const deviceNameAnswer = await inquirer_1.default.prompt([{
269
+ type: 'input',
270
+ name: 'deviceName',
271
+ message: 'Enter a name for this device:',
272
+ default: `${os.hostname()}-${os.platform()}`,
273
+ validate: (input) => input.trim().length > 0 || 'Device name is required'
274
+ }]);
275
+ const createResponse = await edgibleService.createServingDevice({
276
+ name: deviceNameAnswer.deviceName.trim(),
277
+ description: `Serving device: ${deviceNameAnswer.deviceName}`
278
+ });
279
+ deviceId = createResponse.device.id;
280
+ devicePassword = createResponse.device.password;
281
+ console.log(chalk_1.default.green(`āœ“ Device created: ${deviceId}`));
282
+ console.log(chalk_1.default.yellow(`\n⚠ Device Password: ${devicePassword}`));
283
+ console.log(chalk_1.default.yellow('⚠ Please save this password securely!\n'));
284
+ configRepository.updateConfig({
285
+ deviceId,
286
+ deviceName: deviceNameAnswer.deviceName.trim(),
287
+ devicePassword,
288
+ deviceType: 'serving'
289
+ });
290
+ }
291
+ }
292
+ catch (error) {
293
+ logger.error('Error during device selection', error);
294
+ const errorMessage = error instanceof Error ? error.message : 'An unexpected error occurred';
295
+ console.error(chalk_1.default.red('Error during device selection:'), errorMessage);
296
+ throw error;
297
+ }
298
+ // Verify we have device credentials
299
+ if (!deviceId || !devicePassword) {
300
+ throw new Error('Device credentials are required');
301
+ }
302
+ // Step 3: Installation Method Selection
303
+ console.log(chalk_1.default.blue('šŸ”§ Installation Method'));
304
+ console.log(chalk_1.default.gray('Choose how to run the agent:\n'));
305
+ const availableOptions = await PlatformDetector_1.PlatformDetector.getAvailableOptions();
306
+ if (availableOptions.length === 0) {
307
+ console.error(chalk_1.default.red('āœ— No installation methods available on this system'));
308
+ console.error(chalk_1.default.yellow('\nPlease install Docker or Podman to continue.'));
309
+ return;
310
+ }
311
+ let selectedType;
312
+ if (options.type) {
313
+ // Type specified via flag
314
+ selectedType = options.type;
315
+ const option = availableOptions.find(opt => opt.type === selectedType);
316
+ if (!option) {
317
+ console.error(chalk_1.default.red(`āœ— Installation type '${selectedType}' not found`));
318
+ return;
319
+ }
320
+ if (!option.available) {
321
+ console.error(chalk_1.default.red(`āœ— Installation type '${selectedType}' is not available on this system`));
322
+ console.error(chalk_1.default.yellow(` Requirements: ${option.requires.join(', ')}`));
323
+ return;
324
+ }
325
+ }
326
+ else {
327
+ // Interactive selection
328
+ const choices = availableOptions.map(opt => {
329
+ const status = opt.available ? chalk_1.default.green('āœ“') : chalk_1.default.red('āœ—');
330
+ const rootBadge = opt.requiresRoot ? chalk_1.default.yellow('[requires root]') : '';
331
+ return {
332
+ name: `${status} ${opt.name} ${rootBadge}\n ${chalk_1.default.gray(opt.description)}\n ${chalk_1.default.gray('Pros:')} ${opt.pros.join(', ')}\n ${chalk_1.default.gray('Best for:')} ${opt.bestFor}`,
333
+ value: opt.type,
334
+ disabled: !opt.available ? `Requires: ${opt.requires.join(', ')}` : false
335
+ };
336
+ });
337
+ const { installType } = await inquirer_1.default.prompt([{
338
+ type: 'list',
339
+ name: 'installType',
340
+ message: 'Select installation method:',
341
+ choices,
342
+ pageSize: 10
343
+ }]);
344
+ selectedType = installType;
345
+ }
346
+ console.log(chalk_1.default.green(`\nāœ“ Selected: ${selectedType}\n`));
347
+ // Validate --local flag is only used with system service managers
348
+ if (options.local && selectedType !== 'systemd' && selectedType !== 'launchd') {
349
+ console.error(chalk_1.default.red('āœ— --local flag is only supported with systemd or launchd installation'));
350
+ console.error(chalk_1.default.yellow(' Please use --type systemd/launchd or omit --type for interactive selection'));
351
+ return;
352
+ }
353
+ // Step 4: Check and Install Dependencies (for non-container installations)
354
+ const isContainerInstall = selectedType === 'docker' || selectedType === 'podman';
355
+ if (!isContainerInstall) {
356
+ console.log(chalk_1.default.blue('šŸ” Checking System Dependencies'));
357
+ console.log(chalk_1.default.gray('Verifying required tools are installed...\n'));
358
+ const dependencyInstaller = new DependencyInstaller_1.DependencyInstaller();
359
+ try {
360
+ await dependencyInstaller.checkAndInstallDependencies({
361
+ includeWireGuardGo: false, // Use kernel WireGuard by default
362
+ includeIptables: platform === 'linux', // Only check iptables on Linux
363
+ autoInstall: false // Prompt user for installation
364
+ });
365
+ console.log(chalk_1.default.green('āœ“ Dependencies verified\n'));
366
+ }
367
+ catch (error) {
368
+ console.error(chalk_1.default.red('āœ— Dependency check failed'));
369
+ console.error(chalk_1.default.red(` ${error instanceof Error ? error.message : String(error)}`));
370
+ console.log(chalk_1.default.yellow('\n⚠ Some dependencies are missing. The agent may not function correctly.'));
371
+ console.log(chalk_1.default.yellow(' You can install them manually or run: edgible agent setup --auto-install\n'));
372
+ // Ask if user wants to continue anyway
373
+ const { continueAnyway } = await inquirer_1.default.prompt([{
374
+ type: 'confirm',
375
+ name: 'continueAnyway',
376
+ message: 'Continue with installation anyway?',
377
+ default: false
378
+ }]);
379
+ if (!continueAnyway) {
380
+ console.log(chalk_1.default.gray('Installation cancelled.'));
381
+ return;
382
+ }
383
+ }
384
+ }
385
+ // Step 5: Install Agent Files (only for native installations)
386
+ let agentPath;
387
+ // Use system path for system services, user path for others
388
+ const useSystemPath = selectedType === 'systemd' ||
389
+ selectedType === 'launchd' ||
390
+ selectedType === 'windows-service' ||
391
+ selectedType === 'docker' ||
392
+ selectedType === 'podman';
393
+ const configPath = PathResolver_1.PathResolver.getAgentConfigPath(useSystemPath);
394
+ if (isContainerInstall) {
395
+ // For container installations, agent is in the image
396
+ console.log(chalk_1.default.blue('šŸ“¦ Using Container Image'));
397
+ console.log(chalk_1.default.gray(' Agent files will be managed inside the container\n'));
398
+ // Ensure config, applications, and logs directories exist with proper permissions
399
+ // Note: System paths may require sudo, but the daemon manager will handle this
400
+ try {
401
+ await fsPromises.mkdir(configPath, { recursive: true, mode: 0o755 });
402
+ await fsPromises.mkdir(path.join(configPath, 'applications'), { recursive: true, mode: 0o755 });
403
+ await fsPromises.mkdir(path.join(configPath, 'logs'), { recursive: true, mode: 0o755 });
404
+ }
405
+ catch (mkdirError) {
406
+ // If directory creation fails (e.g., needs sudo), that's okay
407
+ // The daemon manager or container will create it with proper permissions
408
+ console.log(chalk_1.default.yellow(`⚠ Could not create directory ${configPath} (may need sudo)`));
409
+ console.log(chalk_1.default.gray(' The directory will be created by the daemon manager\n'));
410
+ }
411
+ agentPath = configPath; // Config path for daemon manager
412
+ }
413
+ else {
414
+ // For native installations, download/install agent files
415
+ console.log(chalk_1.default.blue('šŸ“¦ Installing Agent Files'));
416
+ const installResult = await agentManager.installLocalAgent({
417
+ installationType: selectedType,
418
+ installFromLocal: options.local
419
+ });
420
+ if (!installResult.success) {
421
+ console.error(chalk_1.default.red('āœ— Failed to install agent files'));
422
+ console.error(chalk_1.default.red(` ${installResult.error}`));
423
+ return;
424
+ }
425
+ agentPath = installResult.path || configPath;
426
+ console.log(chalk_1.default.green('āœ“ Agent files installed\n'));
427
+ }
428
+ // Step 6: Configure Daemon
429
+ console.log(chalk_1.default.blue('āš™ļø Configuring Daemon'));
430
+ // Create agent config at the correct path for this installation type
431
+ await agentManager.updateAgentConfig(configPath);
432
+ const daemonConfig = {
433
+ deviceId,
434
+ devicePassword,
435
+ deviceType: 'serving',
436
+ apiBaseUrl: (0, urls_1.getApiBaseUrl)(),
437
+ organizationId: config.organizationId,
438
+ configPath,
439
+ agentPath
440
+ };
441
+ const daemonManager = DaemonManagerFactory_1.DaemonManagerFactory.create(selectedType);
442
+ try {
443
+ await daemonManager.install(daemonConfig);
444
+ console.log(chalk_1.default.green('āœ“ Daemon configured\n'));
445
+ }
446
+ catch (error) {
447
+ console.error(chalk_1.default.red('āœ— Failed to configure daemon'));
448
+ console.error(chalk_1.default.red(` ${error instanceof Error ? error.message : String(error)}`));
449
+ return;
450
+ }
451
+ // Save installation type to config
452
+ configRepository.updateConfig({
453
+ agentInstallationType: selectedType,
454
+ agentServiceName: 'edgible-agent',
455
+ agentContainerName: selectedType === 'docker' || selectedType === 'podman' ? 'edgible-agent' : undefined,
456
+ agentDataPath: configPath
457
+ });
458
+ // Step 7: Enable and Start
459
+ console.log(chalk_1.default.blue('šŸš€ Starting Agent'));
460
+ try {
461
+ await daemonManager.enable();
462
+ console.log(chalk_1.default.green('āœ“ Enabled for startup\n'));
463
+ }
464
+ catch (error) {
465
+ console.warn(chalk_1.default.yellow(`⚠ Could not enable auto-start: ${error instanceof Error ? error.message : String(error)}`));
466
+ }
467
+ try {
468
+ await daemonManager.start();
469
+ console.log(chalk_1.default.green('āœ“ Agent started\n'));
470
+ }
471
+ catch (error) {
472
+ console.error(chalk_1.default.red('āœ— Failed to start agent'));
473
+ console.error(chalk_1.default.red(` ${error instanceof Error ? error.message : String(error)}`));
474
+ return;
475
+ }
476
+ // Wait a moment for agent to initialize
477
+ await new Promise(resolve => setTimeout(resolve, 3000));
478
+ // Show status
479
+ console.log(chalk_1.default.blue('šŸ“Š Agent Status'));
480
+ try {
481
+ const status = await daemonManager.status();
482
+ console.log(` Running: ${status.running ? chalk_1.default.green('Yes') : chalk_1.default.red('No')}`);
483
+ console.log(` Enabled: ${status.enabled ? chalk_1.default.green('Yes') : chalk_1.default.gray('No')}`);
484
+ if (status.pid) {
485
+ console.log(` PID: ${status.pid}`);
486
+ }
487
+ }
488
+ catch (error) {
489
+ console.warn(chalk_1.default.yellow(' Could not fetch status'));
490
+ }
491
+ console.log(chalk_1.default.blue.bold('\n═══════════════════════════════════════════'));
492
+ console.log(chalk_1.default.green.bold(' āœ“ Installation Complete!'));
493
+ console.log(chalk_1.default.blue.bold('═══════════════════════════════════════════\n'));
494
+ console.log(chalk_1.default.gray('Next steps:'));
495
+ console.log(chalk_1.default.gray(` • View status: ${chalk_1.default.white('edgible agent status')}`));
496
+ console.log(chalk_1.default.gray(` • View logs: ${chalk_1.default.white('edgible agent logs --follow')}`));
497
+ console.log(chalk_1.default.gray(` • Stop agent: ${chalk_1.default.white('edgible agent stop')}`));
498
+ console.log(chalk_1.default.gray(` • Restart agent: ${chalk_1.default.white('edgible agent restart')}\n`));
499
+ }, {
500
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
501
+ }));
502
+ agentCommand
503
+ .command('start')
504
+ .description('Start the local agent')
505
+ .option('--passthrough', 'Run agent with interactive output (required for sudo password prompt)')
506
+ .option('--debug', 'Enable debug logging')
507
+ .option('--docker', 'Run agent in Docker container')
508
+ .option('--root', 'Run agent with sudo/root privileges (required for WireGuard and iptables management)')
509
+ .action((0, command_wrapper_1.wrapCommand)(async (options) => {
510
+ const container = (0, container_1.getContainer)();
511
+ const logger = container.get(types_1.TYPES.Logger);
512
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
513
+ const edgibleService = container.get(types_1.TYPES.EdgibleService);
514
+ const authService = container.get(types_1.TYPES.AuthService);
515
+ const agentManager = container.get(types_1.TYPES.LocalAgentManager);
516
+ (0, config_validator_1.validateConfig)(configRepository, {
517
+ requireAuth: true,
518
+ requireOrganization: true,
519
+ });
520
+ const config = configRepository.getConfig();
521
+ let deviceId = config.deviceId;
522
+ let devicePassword = config.devicePassword;
523
+ // Always ask user to select or create a device
524
+ console.log(chalk_1.default.blue('\nšŸ”§ Device Selection'));
525
+ console.log(chalk_1.default.gray('Select which serving device this agent should represent:\n'));
526
+ try {
527
+ // Fetch available serving devices
528
+ const servingDevicesResp = await edgibleService.listServingDevices();
529
+ const servingDevices = servingDevicesResp?.devices || [];
530
+ if (servingDevices.length > 0) {
531
+ // Show list of devices to select from
532
+ const deviceChoices = servingDevices.map((d) => {
533
+ const isCurrentDevice = config.deviceId === d.id;
534
+ const displayName = `${d.name || d.id}${d.description ? ` - ${d.description}` : ''}${isCurrentDevice ? chalk_1.default.gray(' (current)') : ''}`;
535
+ return {
536
+ name: displayName,
537
+ value: d.id
538
+ };
539
+ });
540
+ // Add option to create new device
541
+ deviceChoices.push({
542
+ name: chalk_1.default.cyan('āž• Create new serving device'),
543
+ value: '__create_new__'
544
+ });
545
+ const { selectedDeviceId } = await inquirer_1.default.prompt([{
546
+ type: 'list',
547
+ name: 'selectedDeviceId',
548
+ message: 'Select serving device:',
549
+ choices: deviceChoices,
550
+ default: config.deviceId || undefined
551
+ }]);
552
+ if (selectedDeviceId === '__create_new__') {
553
+ // Create new device
554
+ const deviceNameAnswer = await inquirer_1.default.prompt([{
555
+ type: 'input',
556
+ name: 'deviceName',
557
+ message: 'Enter a name for this device:',
558
+ default: `${os.hostname()}-${os.platform()}`,
559
+ validate: (input) => {
560
+ if (!input.trim()) {
561
+ return 'Device name is required';
562
+ }
563
+ return true;
564
+ }
565
+ }]);
566
+ const descriptionAnswer = await inquirer_1.default.prompt([{
567
+ type: 'input',
568
+ name: 'description',
569
+ message: 'Enter device description (optional):',
570
+ default: `Serving device: ${deviceNameAnswer.deviceName}`
571
+ }]);
572
+ console.log(chalk_1.default.gray('\nCreating device...'));
573
+ // Create device via API - password will be generated and returned by the API
574
+ const createResponse = await edgibleService.createServingDevice({
575
+ name: deviceNameAnswer.deviceName.trim(),
576
+ description: descriptionAnswer.description.trim()
577
+ });
578
+ deviceId = createResponse.device.id;
579
+ devicePassword = createResponse.device.password; // Get password from API response
580
+ console.log(chalk_1.default.green(`āœ“ Device created: ${deviceId}`));
581
+ console.log(chalk_1.default.yellow(`\n⚠ Device Password: ${devicePassword}`));
582
+ console.log(chalk_1.default.yellow('⚠ Please save this password securely! You will need it to login as this device.\n'));
583
+ // Verify device credentials (don't login as device - CLI should use user credentials)
584
+ if (devicePassword && deviceId) {
585
+ const password = devicePassword;
586
+ const id = deviceId;
587
+ console.log(chalk_1.default.gray('Verifying device credentials...'));
588
+ try {
589
+ const isValid = await authService.verifyDeviceCredentials(id, password);
590
+ if (isValid) {
591
+ console.log(chalk_1.default.green('āœ“ Device credentials verified'));
592
+ }
593
+ else {
594
+ console.log(chalk_1.default.yellow('⚠ Device credentials verification failed, but continuing anyway.'));
595
+ console.log(chalk_1.default.gray('The agent will use these credentials when it starts.'));
596
+ }
597
+ }
598
+ catch (verifyError) {
599
+ console.log(chalk_1.default.yellow('⚠ Could not verify device credentials. The agent will use these credentials when it starts.'));
600
+ // Continue anyway - credentials are stored and agent will use them
601
+ }
602
+ }
603
+ // Save device credentials to config
604
+ logger.info('Saving device credentials to config', { deviceId });
605
+ configRepository.updateConfig({
606
+ deviceId: deviceId,
607
+ deviceName: deviceNameAnswer.deviceName.trim(),
608
+ devicePassword: devicePassword,
609
+ deviceType: 'serving'
610
+ });
611
+ }
612
+ else {
613
+ // Use existing device - need to get password
614
+ deviceId = selectedDeviceId;
615
+ let passwordVerified = false;
616
+ // Check if we have password for this device in config
617
+ if (config.deviceId === deviceId && config.devicePassword) {
618
+ devicePassword = config.devicePassword;
619
+ // Verify the stored password is still valid (without overwriting user tokens)
620
+ console.log(chalk_1.default.gray('Verifying device credentials...'));
621
+ if (!deviceId || !devicePassword) {
622
+ throw new Error('Device ID or password is missing');
623
+ }
624
+ const isValid = await authService.verifyDeviceCredentials(deviceId, devicePassword);
625
+ if (isValid) {
626
+ console.log(chalk_1.default.green('āœ“ Device credentials verified'));
627
+ // Update config with current device info (password already stored)
628
+ const selectedDevice = servingDevices.find((d) => d.id === deviceId);
629
+ logger.info('Updating device config', { deviceId });
630
+ configRepository.updateConfig({
631
+ deviceId: deviceId,
632
+ deviceName: selectedDevice?.name || deviceId,
633
+ devicePassword: devicePassword,
634
+ deviceType: 'serving'
635
+ });
636
+ passwordVerified = true;
637
+ }
638
+ else {
639
+ console.log(chalk_1.default.yellow('⚠ Stored password is invalid, please enter the device password'));
640
+ devicePassword = undefined; // Clear invalid password
641
+ }
642
+ }
643
+ // If we don't have a valid password yet, prompt for it
644
+ if (!devicePassword) {
645
+ const passwordAnswer = await inquirer_1.default.prompt([{
646
+ type: 'password',
647
+ name: 'password',
648
+ message: 'Enter device password:',
649
+ validate: (input) => {
650
+ if (!input.trim()) {
651
+ return 'Device password is required';
652
+ }
653
+ return true;
654
+ }
655
+ }]);
656
+ devicePassword = passwordAnswer.password;
657
+ }
658
+ // Verify password (in case it was newly entered or verification failed)
659
+ if (!passwordVerified && devicePassword && deviceId) {
660
+ console.log(chalk_1.default.gray('Verifying device credentials...'));
661
+ if (!deviceId || !devicePassword) {
662
+ throw new Error('Device ID or password is missing');
663
+ }
664
+ const isValid = await authService.verifyDeviceCredentials(deviceId, devicePassword);
665
+ if (isValid) {
666
+ console.log(chalk_1.default.green('āœ“ Device credentials verified'));
667
+ // Save device credentials to config
668
+ const selectedDevice = servingDevices.find((d) => d.id === deviceId);
669
+ logger.info('Saving device credentials to config', { deviceId });
670
+ configRepository.updateConfig({
671
+ deviceId: deviceId,
672
+ deviceName: selectedDevice?.name || deviceId,
673
+ devicePassword: devicePassword,
674
+ deviceType: 'serving'
675
+ });
676
+ }
677
+ else {
678
+ console.error(chalk_1.default.red('āœ— Invalid device password'));
679
+ console.log(chalk_1.default.gray('Please check your password and try again'));
680
+ return;
681
+ }
682
+ }
683
+ }
684
+ }
685
+ else {
686
+ // No devices available, offer to create one
687
+ console.log(chalk_1.default.yellow('⚠ No serving devices found in your organization.\n'));
688
+ const { createNew } = await inquirer_1.default.prompt([{
689
+ type: 'confirm',
690
+ name: 'createNew',
691
+ message: 'Would you like to create a new serving device?',
692
+ default: true
693
+ }]);
694
+ if (!createNew) {
695
+ console.log(chalk_1.default.gray('Agent start cancelled'));
696
+ return;
697
+ }
698
+ // Create new device
699
+ const deviceNameAnswer = await inquirer_1.default.prompt([{
700
+ type: 'input',
701
+ name: 'deviceName',
702
+ message: 'Enter a name for this device:',
703
+ default: `${os.hostname()}-${os.platform()}`,
704
+ validate: (input) => {
705
+ if (!input.trim()) {
706
+ return 'Device name is required';
707
+ }
708
+ return true;
709
+ }
710
+ }]);
711
+ const descriptionAnswer = await inquirer_1.default.prompt([{
712
+ type: 'input',
713
+ name: 'description',
714
+ message: 'Enter device description (optional):',
715
+ default: `Serving device: ${deviceNameAnswer.deviceName}`
716
+ }]);
717
+ console.log(chalk_1.default.gray('\nCreating device...'));
718
+ // Create device via API - password will be generated and returned by the API
719
+ const createResponse = await edgibleService.createServingDevice({
720
+ name: deviceNameAnswer.deviceName.trim(),
721
+ description: descriptionAnswer.description.trim()
722
+ });
723
+ deviceId = createResponse.device.id;
724
+ devicePassword = createResponse.device.password; // Get password from API response
725
+ console.log(chalk_1.default.green(`āœ“ Device created: ${deviceId}`));
726
+ console.log(chalk_1.default.yellow(`\n⚠ Device Password: ${devicePassword}`));
727
+ console.log(chalk_1.default.yellow('⚠ Please save this password securely! You will need it to login as this device.\n'));
728
+ // Verify device credentials (don't login as device - CLI should use user credentials)
729
+ if (devicePassword && deviceId) {
730
+ const password = devicePassword;
731
+ const id = deviceId;
732
+ console.log(chalk_1.default.gray('Verifying device credentials...'));
733
+ try {
734
+ const isValid = await edgibleService.verifyDeviceCredentials(id, password);
735
+ if (isValid) {
736
+ console.log(chalk_1.default.green('āœ“ Device credentials verified'));
737
+ }
738
+ else {
739
+ console.log(chalk_1.default.yellow('⚠ Device credentials verification failed, but continuing anyway.'));
740
+ console.log(chalk_1.default.gray('The agent will use these credentials when it starts.'));
741
+ }
742
+ }
743
+ catch (verifyError) {
744
+ console.log(chalk_1.default.yellow('⚠ Could not verify device credentials. The agent will use these credentials when it starts.'));
745
+ // Continue anyway - credentials are stored and agent will use them
746
+ }
747
+ }
748
+ // Save device credentials to config
749
+ logger.info('Saving device credentials to config', { deviceId });
750
+ configRepository.updateConfig({
751
+ deviceId: deviceId,
752
+ deviceName: deviceNameAnswer.deviceName.trim(),
753
+ devicePassword: devicePassword,
754
+ deviceType: 'serving'
755
+ });
756
+ }
757
+ }
758
+ catch (error) {
759
+ logger.error('Error selecting device', error);
760
+ const errorMessage = error instanceof Error ? error.message : 'An unexpected error occurred';
761
+ console.error(chalk_1.default.red('Error selecting device:'), errorMessage);
762
+ throw error;
763
+ }
764
+ // Now start the agent with the selected/created device
765
+ logger.info('Starting local agent', { passthrough: options.passthrough, debug: options.debug, docker: options.docker, root: options.root });
766
+ if (options.docker) {
767
+ console.log(chalk_1.default.blue('\n🐳 Starting agent in Docker...'));
768
+ }
769
+ else {
770
+ console.log(chalk_1.default.blue('\nšŸš€ Starting agent...'));
771
+ }
772
+ await agentManager.startLocalAgent({
773
+ passthrough: options.passthrough || false,
774
+ debug: options.debug || false,
775
+ docker: options.docker || false,
776
+ root: options.root || false,
777
+ });
778
+ }, {
779
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
780
+ requireAuth: true,
781
+ requireOrganization: true,
782
+ }));
783
+ agentCommand
784
+ .command('stop')
785
+ .description('Stop the local agent')
786
+ .action((0, command_wrapper_1.wrapCommand)(async () => {
787
+ const container = (0, container_1.getContainer)();
788
+ const logger = container.get(types_1.TYPES.Logger);
789
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
790
+ const config = configRepository.getConfig();
791
+ if (!config.agentInstallationType) {
792
+ console.log(chalk_1.default.yellow('⚠ Agent installation type not found in config'));
793
+ console.log(chalk_1.default.gray(' Run "edgible agent install" to install the agent\n'));
794
+ return;
795
+ }
796
+ logger.info('Stopping local agent');
797
+ console.log(chalk_1.default.blue('Stopping agent...\n'));
798
+ const daemonManager = DaemonManagerFactory_1.DaemonManagerFactory.fromConfig(config.agentInstallationType);
799
+ if (!daemonManager) {
800
+ console.error(chalk_1.default.red('āœ— Could not create daemon manager'));
801
+ return;
802
+ }
803
+ try {
804
+ await daemonManager.stop();
805
+ console.log(chalk_1.default.green('āœ“ Agent stopped successfully\n'));
806
+ }
807
+ catch (error) {
808
+ console.error(chalk_1.default.red('āœ— Failed to stop agent'));
809
+ console.error(chalk_1.default.red(` ${error instanceof Error ? error.message : String(error)}\n`));
810
+ throw error;
811
+ }
812
+ }, {
813
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
814
+ }));
815
+ agentCommand
816
+ .command('restart')
817
+ .description('Restart the local agent')
818
+ .action((0, command_wrapper_1.wrapCommand)(async () => {
819
+ const container = (0, container_1.getContainer)();
820
+ const logger = container.get(types_1.TYPES.Logger);
821
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
822
+ const config = configRepository.getConfig();
823
+ if (!config.agentInstallationType) {
824
+ console.log(chalk_1.default.yellow('⚠ Agent installation type not found in config'));
825
+ console.log(chalk_1.default.gray(' Run "edgible agent install" to install the agent\n'));
826
+ return;
827
+ }
828
+ logger.info('Restarting local agent');
829
+ console.log(chalk_1.default.blue('Restarting agent...\n'));
830
+ const daemonManager = DaemonManagerFactory_1.DaemonManagerFactory.fromConfig(config.agentInstallationType);
831
+ if (!daemonManager) {
832
+ console.error(chalk_1.default.red('āœ— Could not create daemon manager'));
833
+ return;
834
+ }
835
+ try {
836
+ await daemonManager.restart();
837
+ console.log(chalk_1.default.green('āœ“ Agent restarted successfully\n'));
838
+ }
839
+ catch (error) {
840
+ console.error(chalk_1.default.red('āœ— Failed to restart agent'));
841
+ console.error(chalk_1.default.red(` ${error instanceof Error ? error.message : String(error)}\n`));
842
+ throw error;
843
+ }
844
+ }, {
845
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
846
+ }));
847
+ agentCommand
848
+ .command('logs')
849
+ .description('View agent logs')
850
+ .option('-f, --follow', 'Follow log output in real-time')
851
+ .option('-n, --lines <number>', 'Number of lines to show', '100')
852
+ .option('-l, --level <level>', 'Log level filter (error, warn, info, debug, all)', 'all')
853
+ .option('-m, --module <module>', 'Filter logs by module name (comma-separated for multiple modules, e.g., "agent,caddy")')
854
+ .option('-c, --comprehensive', 'Show comprehensive diagnostics (raw output without filtering)')
855
+ .option('--single-line', 'Exclude data and error traces from output (single line per log entry)')
856
+ .action((0, command_wrapper_1.wrapCommand)(async (options) => {
857
+ const container = (0, container_1.getContainer)();
858
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
859
+ const config = configRepository.getConfig();
860
+ if (!config.agentInstallationType) {
861
+ console.log(chalk_1.default.yellow('⚠ Agent installation type not found in config'));
862
+ console.log(chalk_1.default.gray(' Run "edgible agent install" to install the agent\n'));
863
+ return;
864
+ }
865
+ const daemonManager = DaemonManagerFactory_1.DaemonManagerFactory.fromConfig(config.agentInstallationType);
866
+ if (!daemonManager) {
867
+ console.error(chalk_1.default.red('āœ— Could not create daemon manager'));
868
+ return;
869
+ }
870
+ const lines = options.lines ? parseInt(options.lines, 10) : 100;
871
+ const follow = options.follow || false;
872
+ const level = options.level || 'all';
873
+ const module = options.module;
874
+ const comprehensive = options.comprehensive || false;
875
+ const singleLine = options.singleLine || false;
876
+ try {
877
+ const rawLogs = await daemonManager.logs(follow, lines);
878
+ // For follow mode, logs are streamed directly and rawLogs will be empty
879
+ if (follow) {
880
+ return;
881
+ }
882
+ // For comprehensive mode, just output raw logs
883
+ if (comprehensive) {
884
+ console.log(rawLogs);
885
+ }
886
+ else {
887
+ // For launchd, logs are plain text, not JSON - output directly
888
+ // unless filtering is requested
889
+ const isLaunchd = config.agentInstallationType === 'launchd';
890
+ if (isLaunchd && !module && level === 'all') {
891
+ // Plain text logs without filtering - just output them
892
+ console.log(rawLogs);
893
+ }
894
+ else if (isLaunchd) {
895
+ // Launchd with filtering requested - try to parse JSON but fall back to raw
896
+ const formattedLogs = (0, log_formatter_1.processLogs)(rawLogs, {
897
+ module: module,
898
+ level: level,
899
+ singleLine: singleLine
900
+ });
901
+ // If no formatted logs, it means either no matches or non-JSON logs
902
+ if (formattedLogs.trim()) {
903
+ console.log(formattedLogs);
904
+ }
905
+ else {
906
+ // No JSON found, just output raw logs
907
+ console.log(chalk_1.default.yellow('Note: Filtering not available for plain text logs. Showing all logs:\n'));
908
+ console.log(rawLogs);
909
+ }
910
+ }
911
+ else {
912
+ // Systemd/Docker/Podman - parse and format JSON logs
913
+ const formattedLogs = (0, log_formatter_1.processLogs)(rawLogs, {
914
+ module: module,
915
+ level: level,
916
+ singleLine: singleLine
917
+ });
918
+ if (formattedLogs.trim()) {
919
+ console.log(formattedLogs);
920
+ }
921
+ else {
922
+ if (module) {
923
+ console.log(chalk_1.default.yellow(`No logs found for module(s): ${module}`));
924
+ }
925
+ else {
926
+ console.log(chalk_1.default.yellow('No logs found'));
927
+ }
928
+ }
929
+ }
930
+ }
931
+ }
932
+ catch (error) {
933
+ console.error(chalk_1.default.red('āœ— Failed to read logs'));
934
+ console.error(chalk_1.default.red(` ${error instanceof Error ? error.message : String(error)}\n`));
935
+ throw error;
936
+ }
937
+ }, {
938
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
939
+ }));
940
+ agentCommand
941
+ .command('uninstall')
942
+ .description('Uninstall the agent daemon')
943
+ .option('--remove-files', 'Also remove agent files and configuration')
944
+ .option('--force', 'Skip confirmation prompts')
945
+ .action((0, command_wrapper_1.wrapCommand)(async (options) => {
946
+ const container = (0, container_1.getContainer)();
947
+ const logger = container.get(types_1.TYPES.Logger);
948
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
949
+ const config = configRepository.getConfig();
950
+ if (!config.agentInstallationType) {
951
+ console.log(chalk_1.default.yellow('⚠ Agent installation type not found in config'));
952
+ console.log(chalk_1.default.gray(' No agent installation detected.\n'));
953
+ return;
954
+ }
955
+ console.log(chalk_1.default.blue.bold('\n═══════════════════════════════════════════'));
956
+ console.log(chalk_1.default.blue.bold(' Edgible Agent Uninstallation'));
957
+ console.log(chalk_1.default.blue.bold('═══════════════════════════════════════════\n'));
958
+ console.log(chalk_1.default.gray(`Installation Type: ${config.agentInstallationType}`));
959
+ if (config.agentServiceName) {
960
+ console.log(chalk_1.default.gray(`Service Name: ${config.agentServiceName}`));
961
+ }
962
+ if (config.agentContainerName) {
963
+ console.log(chalk_1.default.gray(`Container Name: ${config.agentContainerName}`));
964
+ }
965
+ if (config.agentDataPath) {
966
+ console.log(chalk_1.default.gray(`Data Path: ${config.agentDataPath}`));
967
+ }
968
+ console.log('');
969
+ // Confirm uninstallation unless --force is used
970
+ if (!options.force) {
971
+ const { confirm } = await inquirer_1.default.prompt([
972
+ {
973
+ type: 'confirm',
974
+ name: 'confirm',
975
+ message: 'Are you sure you want to uninstall the agent?',
976
+ default: false
977
+ }
978
+ ]);
979
+ if (!confirm) {
980
+ console.log(chalk_1.default.gray('\nUninstallation cancelled.\n'));
981
+ return;
982
+ }
983
+ }
984
+ logger.info('Uninstalling agent', { installationType: config.agentInstallationType });
985
+ // Get daemon manager
986
+ const daemonManager = DaemonManagerFactory_1.DaemonManagerFactory.fromConfig(config.agentInstallationType);
987
+ if (!daemonManager) {
988
+ console.error(chalk_1.default.red('āœ— Could not create daemon manager'));
989
+ console.error(chalk_1.default.red(` Invalid installation type: ${config.agentInstallationType}\n`));
990
+ return;
991
+ }
992
+ // Step 1: Uninstall daemon
993
+ console.log(chalk_1.default.blue('šŸ”§ Uninstalling Daemon'));
994
+ try {
995
+ await daemonManager.uninstall();
996
+ console.log(chalk_1.default.green('āœ“ Daemon uninstalled successfully\n'));
997
+ }
998
+ catch (error) {
999
+ console.error(chalk_1.default.red('āœ— Failed to uninstall daemon'));
1000
+ console.error(chalk_1.default.red(` ${error instanceof Error ? error.message : String(error)}\n`));
1001
+ // Continue with cleanup even if daemon uninstall partially failed
1002
+ }
1003
+ // Step 2: Optionally remove agent files and configuration
1004
+ let removeFiles = options.removeFiles;
1005
+ if (removeFiles === undefined && !options.force) {
1006
+ const { removeFilesAnswer } = await inquirer_1.default.prompt([
1007
+ {
1008
+ type: 'confirm',
1009
+ name: 'removeFilesAnswer',
1010
+ message: 'Do you want to remove agent files and configuration?',
1011
+ default: false
1012
+ }
1013
+ ]);
1014
+ removeFiles = removeFilesAnswer;
1015
+ }
1016
+ if (removeFiles) {
1017
+ console.log(chalk_1.default.blue('šŸ—‘ļø Removing Agent Files'));
1018
+ const agentDataPath = config.agentDataPath || PathResolver_1.PathResolver.resolveAgentConfigPath(config.agentInstallationType);
1019
+ const agentConfigPath = PathResolver_1.PathResolver.resolveAgentConfigPath(config.agentInstallationType);
1020
+ try {
1021
+ // Remove agent data directory if it exists
1022
+ if (agentDataPath && fs.existsSync(agentDataPath)) {
1023
+ await fsPromises.rm(agentDataPath, { recursive: true, force: true });
1024
+ console.log(chalk_1.default.green(`āœ“ Removed agent data directory: ${agentDataPath}`));
1025
+ }
1026
+ // Also try removing config path if different
1027
+ if (agentConfigPath !== agentDataPath && fs.existsSync(agentConfigPath)) {
1028
+ await fsPromises.rm(agentConfigPath, { recursive: true, force: true });
1029
+ console.log(chalk_1.default.green(`āœ“ Removed agent config directory: ${agentConfigPath}`));
1030
+ }
1031
+ console.log('');
1032
+ }
1033
+ catch (error) {
1034
+ console.warn(chalk_1.default.yellow('⚠ Could not remove all agent files'));
1035
+ console.warn(chalk_1.default.yellow(` ${error instanceof Error ? error.message : String(error)}`));
1036
+ console.warn(chalk_1.default.gray(' You may need to remove them manually with appropriate permissions\n'));
1037
+ }
1038
+ }
1039
+ else {
1040
+ console.log(chalk_1.default.gray(' Agent files and configuration preserved\n'));
1041
+ }
1042
+ // Step 3: Clean up CLI config
1043
+ console.log(chalk_1.default.blue('🧹 Cleaning Up Configuration'));
1044
+ try {
1045
+ // Note: ConfigManager filters out undefined values, so fields may remain in config.json
1046
+ // However, the daemon is uninstalled which is the important part
1047
+ // The installation type check will fail if agentInstallationType is undefined,
1048
+ // effectively treating it as uninstalled
1049
+ console.log(chalk_1.default.green('āœ“ CLI configuration cleaned up\n'));
1050
+ console.log(chalk_1.default.gray(' Note: Agent installation fields may remain in config.json'));
1051
+ console.log(chalk_1.default.gray(' but the agent is uninstalled and will not be used.\n'));
1052
+ }
1053
+ catch (error) {
1054
+ console.warn(chalk_1.default.yellow('⚠ Could not clean up CLI configuration'));
1055
+ console.warn(chalk_1.default.yellow(` ${error instanceof Error ? error.message : String(error)}\n`));
1056
+ }
1057
+ console.log(chalk_1.default.blue.bold('═══════════════════════════════════════════'));
1058
+ console.log(chalk_1.default.green.bold(' āœ“ Uninstallation Complete!'));
1059
+ console.log(chalk_1.default.blue.bold('═══════════════════════════════════════════\n'));
1060
+ if (!removeFiles) {
1061
+ console.log(chalk_1.default.gray('Note: Agent files and configuration were preserved.'));
1062
+ console.log(chalk_1.default.gray('To remove them, run: edgible agent uninstall --remove-files\n'));
1063
+ }
1064
+ }, {
1065
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
1066
+ }));
1067
+ agentCommand
1068
+ .command('set-log-level')
1069
+ .description('Set the agent log level')
1070
+ .option('-l, --level <level>', 'Log level: debug, info, warn, or error')
1071
+ .option('--no-restart', 'Do not restart the agent after updating log level')
1072
+ .action((0, command_wrapper_1.wrapCommand)(async (options) => {
1073
+ const container = (0, container_1.getContainer)();
1074
+ const logger = container.get(types_1.TYPES.Logger);
1075
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
1076
+ const agentManager = container.get(types_1.TYPES.LocalAgentManager);
1077
+ const validLevels = ['debug', 'info', 'warn', 'error'];
1078
+ let logLevel;
1079
+ if (options.level) {
1080
+ const level = options.level.toLowerCase();
1081
+ if (!validLevels.includes(level)) {
1082
+ console.error(chalk_1.default.red(`āœ— Invalid log level: ${options.level}`));
1083
+ console.error(chalk_1.default.red(` Valid levels are: ${validLevels.join(', ')}\n`));
1084
+ return;
1085
+ }
1086
+ logLevel = level;
1087
+ }
1088
+ else {
1089
+ // Interactive selection
1090
+ const { selectedLevel } = await inquirer_1.default.prompt([
1091
+ {
1092
+ type: 'list',
1093
+ name: 'selectedLevel',
1094
+ message: 'Select log level:',
1095
+ choices: validLevels.map(level => ({
1096
+ name: level.charAt(0).toUpperCase() + level.slice(1),
1097
+ value: level
1098
+ })),
1099
+ default: 'info'
1100
+ }
1101
+ ]);
1102
+ logLevel = selectedLevel;
1103
+ }
1104
+ try {
1105
+ // Determine the correct config file path based on installation type
1106
+ const userConfig = configRepository.getConfig();
1107
+ const configFilePath = PathResolver_1.PathResolver.resolveAgentConfigFilePath(userConfig.agentInstallationType);
1108
+ if (!fs.existsSync(configFilePath)) {
1109
+ console.error(chalk_1.default.red('āœ— Agent configuration file not found'));
1110
+ console.error(chalk_1.default.red(` Expected at: ${configFilePath}`));
1111
+ console.error(chalk_1.default.red(' Run "edgible agent install" to install the agent first\n'));
1112
+ return;
1113
+ }
1114
+ const configData = await fsPromises.readFile(configFilePath, 'utf8');
1115
+ const agentConfig = JSON.parse(configData);
1116
+ // Check if log level is already set to this value
1117
+ if (agentConfig.logLevel === logLevel) {
1118
+ console.log(chalk_1.default.yellow(`⚠ Log level is already set to: ${logLevel}\n`));
1119
+ return;
1120
+ }
1121
+ // Update log level
1122
+ agentConfig.logLevel = logLevel;
1123
+ // Write back to file
1124
+ await fsPromises.writeFile(configFilePath, JSON.stringify(agentConfig, null, 2), 'utf8');
1125
+ logger.info('Agent log level updated', { logLevel, configFilePath });
1126
+ console.log(chalk_1.default.green(`āœ“ Log level set to: ${logLevel}`));
1127
+ console.log(chalk_1.default.gray(` Updated: ${configFilePath}\n`));
1128
+ // Restart agent if it's installed and running (unless --no-restart is specified)
1129
+ const shouldRestart = options.restart !== false && userConfig.agentInstallationType;
1130
+ if (shouldRestart && userConfig.agentInstallationType) {
1131
+ try {
1132
+ const daemonManager = DaemonManagerFactory_1.DaemonManagerFactory.fromConfig(userConfig.agentInstallationType);
1133
+ if (daemonManager) {
1134
+ const status = await daemonManager.status();
1135
+ if (status.running) {
1136
+ console.log(chalk_1.default.gray('\nRestarting agent to apply new log level...'));
1137
+ await daemonManager.restart();
1138
+ console.log(chalk_1.default.green('āœ“ Agent restarted\n'));
1139
+ }
1140
+ else {
1141
+ console.log(chalk_1.default.gray('\nAgent is not running. Start it with "edgible agent start" to apply the new log level.\n'));
1142
+ }
1143
+ }
1144
+ }
1145
+ catch (restartError) {
1146
+ console.warn(chalk_1.default.yellow('⚠ Could not restart agent automatically'));
1147
+ console.warn(chalk_1.default.yellow(` ${restartError instanceof Error ? restartError.message : String(restartError)}`));
1148
+ console.log(chalk_1.default.gray('\nPlease restart the agent manually for the log level change to take effect.\n'));
1149
+ }
1150
+ }
1151
+ else {
1152
+ console.log(chalk_1.default.gray('\nRestart the agent for the log level change to take effect:\n'));
1153
+ console.log(chalk_1.default.gray(' edgible agent restart\n'));
1154
+ }
1155
+ }
1156
+ catch (error) {
1157
+ logger.error('Failed to update log level', error);
1158
+ console.error(chalk_1.default.red('āœ— Failed to update log level'));
1159
+ console.error(chalk_1.default.red(` ${error instanceof Error ? error.message : String(error)}\n`));
1160
+ throw error;
1161
+ }
1162
+ }, {
1163
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
1164
+ }));
1165
+ agentCommand
1166
+ .command('setup')
1167
+ .description('Setup agent dependencies and configure the agent')
1168
+ .option('--wireguard-mode <mode>', 'WireGuard mode: kernel or userspace', 'kernel')
1169
+ .option('--wireguard-go-binary <path>', 'Path to wireguard-go binary (only used with userspace mode)', 'wireguard-go')
1170
+ .option('--auto-install', 'Automatically install missing dependencies without prompting')
1171
+ .action((0, command_wrapper_1.wrapCommand)(async (options) => {
1172
+ const container = (0, container_1.getContainer)();
1173
+ const logger = container.get(types_1.TYPES.Logger);
1174
+ const configRepository = container.get(types_1.TYPES.ConfigRepository);
1175
+ const agentManager = container.get(types_1.TYPES.LocalAgentManager);
1176
+ logger.info('Setting up agent dependencies and configuration');
1177
+ console.log(chalk_1.default.blue('\nšŸ”§ Agent Setup'));
1178
+ console.log(chalk_1.default.gray('This will check and install dependencies, then configure the agent.\n'));
1179
+ // Step 1: Check and install dependencies
1180
+ console.log(chalk_1.default.blue('Step 1: Checking dependencies...\n'));
1181
+ const dependencyInstaller = new DependencyInstaller_1.DependencyInstaller();
1182
+ // Determine if we should check for wireguard-go based on mode
1183
+ const wireguardMode = (options.wireguardMode || 'kernel').toLowerCase();
1184
+ const includeWireGuardGo = wireguardMode === 'userspace';
1185
+ await dependencyInstaller.checkAndInstallDependencies({
1186
+ includeWireGuardGo,
1187
+ includeIptables: true,
1188
+ autoInstall: options.autoInstall || false
1189
+ });
1190
+ console.log(chalk_1.default.green('\nāœ“ Dependencies check complete\n'));
1191
+ // Step 2: Configure WireGuard mode
1192
+ let selectedMode = wireguardMode;
1193
+ if (!options.wireguardMode) {
1194
+ // Prompt user for WireGuard mode if not provided
1195
+ const { mode } = await inquirer_1.default.prompt([
1196
+ {
1197
+ type: 'list',
1198
+ name: 'mode',
1199
+ message: 'Select WireGuard implementation mode:',
1200
+ choices: [
1201
+ {
1202
+ name: 'Kernel (default, requires kernel module support)',
1203
+ value: 'kernel'
1204
+ },
1205
+ {
1206
+ name: 'Userspace (wireguard-go, works without kernel module)',
1207
+ value: 'userspace'
1208
+ }
1209
+ ],
1210
+ default: 'kernel'
1211
+ }
1212
+ ]);
1213
+ selectedMode = mode;
1214
+ }
1215
+ // Step 3: Update CLI config with WireGuard settings
1216
+ const currentConfig = configRepository.getConfig();
1217
+ configRepository.updateConfig({
1218
+ wireguardMode: selectedMode,
1219
+ wireguardGoBinary: options.wireguardGoBinary || 'wireguard-go'
1220
+ });
1221
+ console.log(chalk_1.default.green(`āœ“ WireGuard mode set to: ${selectedMode}`));
1222
+ if (selectedMode === 'userspace') {
1223
+ console.log(chalk_1.default.gray(` wireguard-go binary: ${options.wireguardGoBinary || 'wireguard-go'}`));
1224
+ }
1225
+ // Step 4: Update agent config
1226
+ console.log(chalk_1.default.blue('\nStep 2: Updating agent configuration...\n'));
1227
+ // Check if device credentials exist
1228
+ if (!currentConfig.deviceId || !currentConfig.devicePassword) {
1229
+ console.log(chalk_1.default.yellow('⚠ No device credentials found in CLI config.'));
1230
+ console.log(chalk_1.default.yellow('⚠ You will need to run "edgible agent start" to set up device credentials.'));
1231
+ console.log(chalk_1.default.yellow('⚠ The agent config will be created with default values.\n'));
1232
+ }
1233
+ try {
1234
+ await agentManager.updateAgentConfig();
1235
+ console.log(chalk_1.default.green('āœ“ Agent configuration updated\n'));
1236
+ }
1237
+ catch (error) {
1238
+ // If update fails due to missing credentials, create a basic config
1239
+ if (error instanceof Error && error.message.includes('No device credentials')) {
1240
+ console.log(chalk_1.default.yellow('⚠ Creating agent config with default values (device credentials will be set when you start the agent)\n'));
1241
+ // Create a basic config file
1242
+ const agentConfigPath = path.join(os.homedir(), '.edgible', 'agent', 'agent.config.json');
1243
+ const defaultConfig = {
1244
+ deviceId: 'your-device-id',
1245
+ devicePassword: 'your-device-password',
1246
+ deviceType: 'serving',
1247
+ apiBaseUrl: (0, urls_1.getApiBaseUrl)(),
1248
+ organizationId: currentConfig.organizationId,
1249
+ firewallEnabled: true,
1250
+ pollingInterval: 60000,
1251
+ healthCheckTimeout: 5000,
1252
+ maxRetries: 3,
1253
+ logLevel: 'info',
1254
+ updateEnabled: true,
1255
+ updateCheckInterval: 3600000,
1256
+ wireguardMode: selectedMode,
1257
+ wireguardGoBinary: options.wireguardGoBinary || 'wireguard-go'
1258
+ };
1259
+ const configDir = path.dirname(agentConfigPath);
1260
+ await fsPromises.mkdir(configDir, { recursive: true });
1261
+ await fsPromises.writeFile(agentConfigPath, JSON.stringify(defaultConfig, null, 2));
1262
+ console.log(chalk_1.default.green('āœ“ Agent configuration file created\n'));
1263
+ }
1264
+ else {
1265
+ throw error;
1266
+ }
1267
+ }
1268
+ console.log(chalk_1.default.green('āœ“ Agent setup complete!\n'));
1269
+ console.log(chalk_1.default.blue('Next steps:'));
1270
+ console.log(chalk_1.default.gray(' 1. Run "edgible agent start" to start the agent'));
1271
+ console.log(chalk_1.default.gray(' 2. The agent will use the configured WireGuard mode'));
1272
+ if (selectedMode === 'userspace') {
1273
+ console.log(chalk_1.default.gray(' 3. Ensure wireguard-go is available in your PATH'));
1274
+ }
1275
+ console.log('');
1276
+ }, {
1277
+ configRepository: (0, container_1.getContainer)().get(types_1.TYPES.ConfigRepository),
1278
+ }));
1279
+ }
1280
+ //# sourceMappingURL=agent.js.map