@loxia-labs/loxia-autopilot-one 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 (80) hide show
  1. package/LICENSE +267 -0
  2. package/README.md +509 -0
  3. package/bin/cli.js +117 -0
  4. package/package.json +94 -0
  5. package/scripts/install-scanners.js +236 -0
  6. package/src/analyzers/CSSAnalyzer.js +297 -0
  7. package/src/analyzers/ConfigValidator.js +690 -0
  8. package/src/analyzers/ESLintAnalyzer.js +320 -0
  9. package/src/analyzers/JavaScriptAnalyzer.js +261 -0
  10. package/src/analyzers/PrettierFormatter.js +247 -0
  11. package/src/analyzers/PythonAnalyzer.js +266 -0
  12. package/src/analyzers/SecurityAnalyzer.js +729 -0
  13. package/src/analyzers/TypeScriptAnalyzer.js +247 -0
  14. package/src/analyzers/codeCloneDetector/analyzer.js +344 -0
  15. package/src/analyzers/codeCloneDetector/detector.js +203 -0
  16. package/src/analyzers/codeCloneDetector/index.js +160 -0
  17. package/src/analyzers/codeCloneDetector/parser.js +199 -0
  18. package/src/analyzers/codeCloneDetector/reporter.js +148 -0
  19. package/src/analyzers/codeCloneDetector/scanner.js +59 -0
  20. package/src/core/agentPool.js +1474 -0
  21. package/src/core/agentScheduler.js +2147 -0
  22. package/src/core/contextManager.js +709 -0
  23. package/src/core/messageProcessor.js +732 -0
  24. package/src/core/orchestrator.js +548 -0
  25. package/src/core/stateManager.js +877 -0
  26. package/src/index.js +631 -0
  27. package/src/interfaces/cli.js +549 -0
  28. package/src/interfaces/webServer.js +2162 -0
  29. package/src/modules/fileExplorer/controller.js +280 -0
  30. package/src/modules/fileExplorer/index.js +37 -0
  31. package/src/modules/fileExplorer/middleware.js +92 -0
  32. package/src/modules/fileExplorer/routes.js +125 -0
  33. package/src/modules/fileExplorer/types.js +44 -0
  34. package/src/services/aiService.js +1232 -0
  35. package/src/services/apiKeyManager.js +164 -0
  36. package/src/services/benchmarkService.js +366 -0
  37. package/src/services/budgetService.js +539 -0
  38. package/src/services/contextInjectionService.js +247 -0
  39. package/src/services/conversationCompactionService.js +637 -0
  40. package/src/services/errorHandler.js +810 -0
  41. package/src/services/fileAttachmentService.js +544 -0
  42. package/src/services/modelRouterService.js +366 -0
  43. package/src/services/modelsService.js +322 -0
  44. package/src/services/qualityInspector.js +796 -0
  45. package/src/services/tokenCountingService.js +536 -0
  46. package/src/tools/agentCommunicationTool.js +1344 -0
  47. package/src/tools/agentDelayTool.js +485 -0
  48. package/src/tools/asyncToolManager.js +604 -0
  49. package/src/tools/baseTool.js +800 -0
  50. package/src/tools/browserTool.js +920 -0
  51. package/src/tools/cloneDetectionTool.js +621 -0
  52. package/src/tools/dependencyResolverTool.js +1215 -0
  53. package/src/tools/fileContentReplaceTool.js +875 -0
  54. package/src/tools/fileSystemTool.js +1107 -0
  55. package/src/tools/fileTreeTool.js +853 -0
  56. package/src/tools/imageTool.js +901 -0
  57. package/src/tools/importAnalyzerTool.js +1060 -0
  58. package/src/tools/jobDoneTool.js +248 -0
  59. package/src/tools/seekTool.js +956 -0
  60. package/src/tools/staticAnalysisTool.js +1778 -0
  61. package/src/tools/taskManagerTool.js +2873 -0
  62. package/src/tools/terminalTool.js +2304 -0
  63. package/src/tools/webTool.js +1430 -0
  64. package/src/types/agent.js +519 -0
  65. package/src/types/contextReference.js +972 -0
  66. package/src/types/conversation.js +730 -0
  67. package/src/types/toolCommand.js +747 -0
  68. package/src/utilities/attachmentValidator.js +292 -0
  69. package/src/utilities/configManager.js +582 -0
  70. package/src/utilities/constants.js +722 -0
  71. package/src/utilities/directoryAccessManager.js +535 -0
  72. package/src/utilities/fileProcessor.js +307 -0
  73. package/src/utilities/logger.js +436 -0
  74. package/src/utilities/tagParser.js +1246 -0
  75. package/src/utilities/toolConstants.js +317 -0
  76. package/web-ui/build/index.html +15 -0
  77. package/web-ui/build/logo.png +0 -0
  78. package/web-ui/build/logo2.png +0 -0
  79. package/web-ui/build/static/index-CjkkcnFA.js +344 -0
  80. package/web-ui/build/static/index-Dy2bYbOa.css +1 -0
package/src/index.js ADDED
@@ -0,0 +1,631 @@
1
+ /**
2
+ * Loxia Autopilot One - Main Application Entry Point
3
+ *
4
+ * Purpose:
5
+ * - Initialize all system components
6
+ * - Setup dependency injection
7
+ * - Start interface handlers
8
+ * - Handle graceful shutdown
9
+ */
10
+
11
+ import path from 'path';
12
+ import { fileURLToPath } from 'url';
13
+ import { createLogger } from './utilities/logger.js';
14
+ import { createConfigManager } from './utilities/configManager.js';
15
+ import Orchestrator from './core/orchestrator.js';
16
+ import AgentPool from './core/agentPool.js';
17
+ import MessageProcessor from './core/messageProcessor.js';
18
+ import AgentScheduler from './core/agentScheduler.js';
19
+ import ContextManager from './core/contextManager.js';
20
+ import StateManager from './core/stateManager.js';
21
+ import AIService from './services/aiService.js';
22
+ import BudgetService from './services/budgetService.js';
23
+ import ErrorHandler from './services/errorHandler.js';
24
+ import BenchmarkService from './services/benchmarkService.js';
25
+ import ModelRouterService from './services/modelRouterService.js';
26
+ import ModelsService from './services/modelsService.js';
27
+ import ApiKeyManager from './services/apiKeyManager.js';
28
+ import FileAttachmentService from './services/fileAttachmentService.js';
29
+ import { ToolsRegistry } from './tools/baseTool.js';
30
+ import AgentDelayTool from './tools/agentDelayTool.js';
31
+ import TerminalTool from './tools/terminalTool.js';
32
+ import FileSystemTool from './tools/fileSystemTool.js';
33
+ import BrowserTool from './tools/browserTool.js';
34
+ import JobDoneTool from './tools/jobDoneTool.js';
35
+ import AgentCommunicationTool from './tools/agentCommunicationTool.js';
36
+ import TaskManagerTool from './tools/taskManagerTool.js';
37
+ import ImportAnalyzerTool from './tools/importAnalyzerTool.js';
38
+ import DependencyResolverTool from './tools/dependencyResolverTool.js';
39
+ import ImageTool from './tools/imageTool.js';
40
+ import StaticAnalysisTool from './tools/staticAnalysisTool.js';
41
+ import CloneDetectionTool from './tools/cloneDetectionTool.js';
42
+ import FileTreeTool from './tools/fileTreeTool.js';
43
+ import FileContentReplaceTool from './tools/fileContentReplaceTool.js';
44
+ import SeekTool from './tools/seekTool.js';
45
+ import WebTool from './tools/webTool.js';
46
+ import AsyncToolManager from './tools/asyncToolManager.js';
47
+ import WebServer from './interfaces/webServer.js';
48
+
49
+ import {
50
+ SYSTEM_VERSION,
51
+ INTERFACE_TYPES
52
+ } from './utilities/constants.js';
53
+
54
+ class LoxiaApplication {
55
+ constructor() {
56
+ this.logger = null;
57
+ this.config = null;
58
+ this.orchestrator = null;
59
+ this.interfaces = new Map();
60
+ this.isShuttingDown = false;
61
+
62
+ // Bind shutdown handler
63
+ this.shutdown = this.shutdown.bind(this);
64
+ }
65
+
66
+ /**
67
+ * Initialize the application
68
+ * @param {Object} options - Initialization options
69
+ * @returns {Promise<void>}
70
+ */
71
+ async initialize(options = {}) {
72
+ try {
73
+ console.log(`šŸš€ Starting Loxia Autopilot One v${SYSTEM_VERSION}`);
74
+
75
+ // Initialize configuration
76
+ await this.initializeConfig(options);
77
+
78
+ // Initialize logging
79
+ await this.initializeLogging();
80
+
81
+ this.logger.info('Loxia Autopilot One starting up', {
82
+ version: SYSTEM_VERSION,
83
+ nodeVersion: process.version,
84
+ platform: process.platform,
85
+ projectDir: options.projectDir || process.cwd()
86
+ });
87
+
88
+ // Initialize core components
89
+ await this.initializeCoreComponents();
90
+
91
+ // Initialize tools
92
+ await this.initializeTools();
93
+
94
+ this.logger.info('Starting interface initialization...');
95
+
96
+ // Initialize interfaces
97
+ await this.initializeInterfaces(options);
98
+
99
+ this.logger.info('Interface initialization completed');
100
+
101
+ // Setup shutdown handlers
102
+ this.setupShutdownHandlers();
103
+
104
+ this.logger.info('Loxia Autopilot One startup complete');
105
+ console.log('āœ… Loxia Autopilot One is ready!');
106
+
107
+ } catch (error) {
108
+ console.error('āŒ Failed to initialize Loxia Autopilot One:', error.message);
109
+ if (this.logger) {
110
+ this.logger.error('Application initialization failed', {
111
+ error: error.message,
112
+ stack: error.stack
113
+ });
114
+ }
115
+ process.exit(1);
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Initialize configuration management
121
+ * @private
122
+ */
123
+ async initializeConfig(options) {
124
+ const __filename = fileURLToPath(import.meta.url);
125
+ const __dirname = path.dirname(__filename);
126
+
127
+ const configPaths = [
128
+ path.join(__dirname, '../config/default.json'),
129
+ ...(options.configPaths || [])
130
+ ];
131
+
132
+ this.configManager = createConfigManager({
133
+ configPaths,
134
+ envPrefix: 'LOXIA'
135
+ });
136
+
137
+ this.config = await this.configManager.loadConfig();
138
+
139
+ // Enable config watching if requested
140
+ if (options.watchConfig) {
141
+ await this.configManager.watchConfig(true);
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Initialize logging system
147
+ * @private
148
+ */
149
+ async initializeLogging() {
150
+ const loggingConfig = this.config.logging || {};
151
+
152
+ this.logger = createLogger({
153
+ level: loggingConfig.level || 'info',
154
+ outputs: loggingConfig.outputs || ['console'],
155
+ colors: loggingConfig.colors !== false,
156
+ timestamp: loggingConfig.timestamp !== false,
157
+ logFile: loggingConfig.logFile,
158
+ maxFileSize: loggingConfig.maxFileSize,
159
+ maxFiles: loggingConfig.maxFiles
160
+ });
161
+
162
+ await this.logger.initialize();
163
+ }
164
+
165
+ /**
166
+ * Initialize core system components
167
+ * @private
168
+ */
169
+ async initializeCoreComponents() {
170
+ this.logger.info('Initializing core components...');
171
+
172
+ // State Manager
173
+ this.stateManager = new StateManager(this.config, this.logger);
174
+
175
+ // File Attachment Service
176
+ this.fileAttachmentService = new FileAttachmentService(this.config, this.logger);
177
+ await this.fileAttachmentService.initialize();
178
+
179
+ // Context Manager
180
+ this.contextManager = new ContextManager(this.config, this.logger);
181
+
182
+ // Tools Registry and Async Tool Manager
183
+ this.toolsRegistry = new ToolsRegistry(this.logger);
184
+ this.asyncToolManager = new AsyncToolManager(this.config, this.logger);
185
+
186
+ // Agent Pool (with tools registry for prompt enhancement)
187
+ this.agentPool = new AgentPool(
188
+ this.config,
189
+ this.logger,
190
+ this.stateManager,
191
+ this.contextManager,
192
+ this.toolsRegistry
193
+ );
194
+
195
+ // Initialize Budget Service and Error Handler
196
+ this.budgetService = new BudgetService(this.config, this.logger);
197
+ this.errorHandler = new ErrorHandler(this.config, this.logger);
198
+
199
+ // API Key Manager
200
+ this.apiKeyManager = new ApiKeyManager(this.logger);
201
+
202
+ // AI Service
203
+ this.aiService = new AIService(
204
+ this.config,
205
+ this.logger,
206
+ this.budgetService,
207
+ this.errorHandler
208
+ );
209
+
210
+ // Set API Key Manager reference in AI Service
211
+ this.aiService.setApiKeyManager(this.apiKeyManager);
212
+
213
+ // Set Agent Pool reference in AI Service
214
+ this.aiService.setAgentPool(this.agentPool);
215
+
216
+ // Initialize Model Routing Services
217
+ this.benchmarkService = new BenchmarkService(this.config, this.logger);
218
+ this.modelsService = new ModelsService(this.config, this.logger);
219
+ this.modelRouterService = new ModelRouterService(
220
+ this.config,
221
+ this.logger,
222
+ this.benchmarkService,
223
+ this.aiService
224
+ );
225
+
226
+ // Set API Key Manager reference in ModelsService
227
+ this.modelsService.setApiKeyManager(this.apiKeyManager);
228
+
229
+ // Initialize services
230
+ await this.benchmarkService.initialize();
231
+ await this.modelsService.initialize();
232
+
233
+ // Message Processor
234
+ this.messageProcessor = new MessageProcessor(
235
+ this.config,
236
+ this.logger,
237
+ this.toolsRegistry,
238
+ this.agentPool,
239
+ this.contextManager,
240
+ this.aiService,
241
+ this.modelRouterService,
242
+ this.modelsService
243
+ );
244
+
245
+ // Agent Scheduler - NEW ARCHITECTURE
246
+ this.agentScheduler = new AgentScheduler(
247
+ this.agentPool,
248
+ this.messageProcessor,
249
+ this.aiService,
250
+ this.logger,
251
+ null, // webSocketManager will be set later
252
+ this.modelRouterService,
253
+ this.modelsService
254
+ );
255
+
256
+ // Note: Scheduler will be started after WebSocketManager is initialized
257
+
258
+ // Orchestrator
259
+ this.orchestrator = new Orchestrator(
260
+ this.config,
261
+ this.logger,
262
+ this.agentPool,
263
+ this.messageProcessor,
264
+ this.aiService,
265
+ this.stateManager
266
+ );
267
+
268
+ // Set cross-references between components
269
+ this.messageProcessor.orchestrator = this.orchestrator;
270
+ this.messageProcessor.setScheduler(this.agentScheduler);
271
+ this.agentPool.setMessageProcessor(this.messageProcessor);
272
+ this.agentPool.setScheduler(this.agentScheduler);
273
+ this.agentPool.setFileAttachmentService(this.fileAttachmentService);
274
+
275
+ // Attach FileAttachmentService to orchestrator for webServer access
276
+ this.orchestrator.fileAttachmentService = this.fileAttachmentService;
277
+
278
+ this.logger.info('Core components initialized');
279
+ }
280
+
281
+ /**
282
+ * Initialize tools system
283
+ * @private
284
+ */
285
+ async initializeTools() {
286
+ this.logger.info('Initializing tools...');
287
+
288
+ // Register Agent Delay Tool
289
+ await this.toolsRegistry.registerTool(AgentDelayTool);
290
+
291
+ // Register Terminal Tool
292
+ await this.toolsRegistry.registerTool(TerminalTool);
293
+
294
+ // Register File System Tool
295
+ await this.toolsRegistry.registerTool(FileSystemTool);
296
+
297
+ // Register Job Done Tool
298
+ await this.toolsRegistry.registerTool(JobDoneTool);
299
+
300
+ // Register Agent Communication Tool
301
+ await this.toolsRegistry.registerTool(AgentCommunicationTool);
302
+
303
+ // Register Task Manager Tool
304
+ await this.toolsRegistry.registerTool(TaskManagerTool);
305
+
306
+ // Register Import Analyzer Tool
307
+ await this.toolsRegistry.registerTool(ImportAnalyzerTool);
308
+
309
+ // Register Dependency Resolver Tool
310
+ await this.toolsRegistry.registerTool(DependencyResolverTool);
311
+
312
+ // Register Image Generation Tool
313
+ await this.toolsRegistry.registerTool(ImageTool);
314
+
315
+ // Register Static Analysis Tool
316
+ await this.toolsRegistry.registerTool(StaticAnalysisTool);
317
+
318
+ // Register Clone Detection Tool
319
+ await this.toolsRegistry.registerTool(CloneDetectionTool);
320
+
321
+ // Register File Tree Tool
322
+ await this.toolsRegistry.registerTool(FileTreeTool);
323
+
324
+ // Register File Content Replace Tool
325
+ await this.toolsRegistry.registerTool(FileContentReplaceTool);
326
+
327
+ // Register Seek Tool
328
+ await this.toolsRegistry.registerTool(SeekTool);
329
+
330
+ // Register Web Tool
331
+ await this.toolsRegistry.registerTool(WebTool);
332
+
333
+ // Register Browser Tool (if enabled)
334
+ if (this.config.tools?.browser?.enabled !== false) {
335
+ try {
336
+ await this.toolsRegistry.registerTool(BrowserTool);
337
+ this.logger.info('Browser tool registered (requires puppeteer)');
338
+ } catch (error) {
339
+ this.logger.warn('Browser tool registration skipped', {
340
+ reason: error.message,
341
+ suggestion: 'Install puppeteer to enable browser automation'
342
+ });
343
+ }
344
+ }
345
+
346
+ // Set AgentPool dependency for AgentDelayTool
347
+ const agentDelayTool = this.toolsRegistry.getTool('agentdelay');
348
+ if (agentDelayTool && typeof agentDelayTool.setAgentPool === 'function') {
349
+ agentDelayTool.setAgentPool(this.agentPool);
350
+ }
351
+
352
+ // Set AgentPool dependency for JobDoneTool
353
+ const jobDoneTool = this.toolsRegistry.getTool('jobdone');
354
+ if (jobDoneTool && typeof jobDoneTool.setAgentPool === 'function') {
355
+ jobDoneTool.setAgentPool(this.agentPool);
356
+ }
357
+
358
+ // Set AgentPool and Scheduler dependencies for TaskManagerTool
359
+ const taskManagerTool = this.toolsRegistry.getTool('taskmanager');
360
+ if (taskManagerTool && typeof taskManagerTool.setAgentPool === 'function') {
361
+ taskManagerTool.setAgentPool(this.agentPool);
362
+ }
363
+ if (taskManagerTool && typeof taskManagerTool.setScheduler === 'function') {
364
+ taskManagerTool.setScheduler(this.scheduler);
365
+ }
366
+
367
+ // Note: AgentCommunicationTool receives agentPool through execution context
368
+ // No need to set it directly as it's passed in the context parameter
369
+ const agentCommTool = this.toolsRegistry.getTool('agentcommunication');
370
+ if (agentCommTool) {
371
+ this.logger.info('Agent Communication Tool registered successfully');
372
+ }
373
+
374
+ // Set AIService dependency for ImageTool
375
+ const imageTool = this.toolsRegistry.getTool('image-gen');
376
+ if (imageTool && typeof imageTool.setAIService === 'function') {
377
+ imageTool.setAIService(this.aiService);
378
+ this.logger.info('AIService set for Image Generation Tool');
379
+ }
380
+
381
+ // Set AgentPool dependency for ImageTool (for conversation history persistence)
382
+ if (imageTool && typeof imageTool.setAgentPool === 'function') {
383
+ imageTool.setAgentPool(this.agentPool);
384
+ this.logger.info('AgentPool set for Image Generation Tool');
385
+ }
386
+
387
+ const toolCapabilities = this.toolsRegistry.getToolCapabilities();
388
+ this.logger.info('Tools initialized', {
389
+ toolCount: Object.keys(toolCapabilities).length,
390
+ enabledTools: Object.keys(toolCapabilities).filter(id => toolCapabilities[id].capabilities.enabled),
391
+ registeredTools: this.toolsRegistry.listTools()
392
+ });
393
+
394
+ // Log tool descriptions for debugging
395
+ if (this.logger.level === 'debug') {
396
+ for (const [toolId, tool] of toolCapabilities.entries()) {
397
+ this.logger.debug(`Tool ${toolId} capabilities`, tool.capabilities);
398
+ }
399
+ }
400
+ }
401
+
402
+ /**
403
+ * Initialize interface handlers
404
+ * @private
405
+ */
406
+ async initializeInterfaces(options) {
407
+ this.logger.info('Initializing interfaces...');
408
+
409
+ const interfaceConfig = this.config.interfaces || {};
410
+
411
+ // CLI Interface (basic implementation)
412
+ if (interfaceConfig.cli?.enabled !== false) {
413
+ const { default: CLIInterface } = await import('./interfaces/cli.js');
414
+ const cliInterface = new CLIInterface(
415
+ this.orchestrator,
416
+ this.logger,
417
+ interfaceConfig.cli || {}
418
+ );
419
+
420
+ await cliInterface.initialize();
421
+ this.interfaces.set(INTERFACE_TYPES.CLI, cliInterface);
422
+
423
+ this.logger.info('CLI interface initialized');
424
+ }
425
+
426
+ // Web Interface - now implemented
427
+ if (interfaceConfig.web?.enabled !== false) {
428
+ const webServer = new WebServer(
429
+ this.orchestrator,
430
+ this.logger,
431
+ interfaceConfig.web || { port: 8080, host: 'localhost' }
432
+ );
433
+
434
+ // Pass toolsRegistry to webServer for the /api/tools endpoint
435
+ webServer.toolsRegistry = this.toolsRegistry;
436
+
437
+ // Set API Key Manager reference in Web Server
438
+ webServer.setApiKeyManager(this.apiKeyManager);
439
+
440
+ await webServer.initialize();
441
+ this.interfaces.set(INTERFACE_TYPES.WEB, webServer);
442
+
443
+ // Attach WebServer to orchestrator for MessageProcessor broadcasting
444
+ this.orchestrator.webServer = webServer;
445
+
446
+ // Connect MessageProcessor to WebServer for real-time updates
447
+ this.messageProcessor.setWebSocketManager(webServer);
448
+
449
+ // Connect AgentScheduler to WebServer for real-time updates
450
+ this.agentScheduler.webSocketManager = webServer;
451
+
452
+ // Start the scheduler now that WebSocketManager is available
453
+ this.agentScheduler.start();
454
+ this.logger.info('Agent Scheduler started with WebSocket integration');
455
+
456
+ // Set global reference for tools that need to broadcast
457
+ global.loxiaWebServer = webServer;
458
+
459
+ const status = webServer.getStatus();
460
+ this.logger.info('Web interface initialized', { url: status.url });
461
+ console.log(`🌐 Web Server running at ${status.url}`);
462
+ console.log(`šŸ“± Web UI available at: http://localhost:3001 (if running)`);
463
+ }
464
+
465
+ // VSCode Extension Interface (placeholder)
466
+ if (interfaceConfig.vscode?.enabled === true) {
467
+ this.logger.info('VSCode interface configured but not implemented yet');
468
+ // TODO: Initialize VSCode extension interface
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Setup graceful shutdown handlers
474
+ * @private
475
+ */
476
+ setupShutdownHandlers() {
477
+ // Handle SIGINT (Ctrl+C)
478
+ process.on('SIGINT', async () => {
479
+ console.log('\nšŸ“‹ Received SIGINT, shutting down gracefully...');
480
+ await this.shutdown();
481
+ });
482
+
483
+ // Handle SIGTERM
484
+ process.on('SIGTERM', async () => {
485
+ console.log('\nšŸ“‹ Received SIGTERM, shutting down gracefully...');
486
+ await this.shutdown();
487
+ });
488
+
489
+ // Handle uncaught exceptions
490
+ process.on('uncaughtException', async (error) => {
491
+ console.error('āŒ Uncaught exception:', error);
492
+ if (this.logger) {
493
+ this.logger.error('Uncaught exception', {
494
+ error: error.message,
495
+ stack: error.stack
496
+ });
497
+ }
498
+
499
+ await this.shutdown();
500
+ process.exit(1);
501
+ });
502
+
503
+ // Handle unhandled promise rejections
504
+ process.on('unhandledRejection', async (reason, promise) => {
505
+ console.error('āŒ Unhandled promise rejection:', reason);
506
+ if (this.logger) {
507
+ this.logger.error('Unhandled promise rejection', {
508
+ reason: reason?.message || reason,
509
+ promise: promise.toString()
510
+ });
511
+ }
512
+
513
+ await this.shutdown();
514
+ process.exit(1);
515
+ });
516
+ }
517
+
518
+ /**
519
+ * Gracefully shutdown the application
520
+ * @returns {Promise<void>}
521
+ */
522
+ async shutdown() {
523
+ if (this.isShuttingDown) {
524
+ return;
525
+ }
526
+
527
+ this.isShuttingDown = true;
528
+
529
+ try {
530
+ console.log('šŸ›‘ Shutting down Loxia Autopilot One...');
531
+
532
+ if (this.logger) {
533
+ this.logger.info('Application shutdown initiated');
534
+ }
535
+
536
+ // Shutdown interfaces
537
+ for (const [type, interface_] of this.interfaces) {
538
+ try {
539
+ if (interface_.shutdown) {
540
+ await interface_.shutdown();
541
+ }
542
+ this.logger?.info(`${type} interface shutdown complete`);
543
+ } catch (error) {
544
+ console.error(`Failed to shutdown ${type} interface:`, error.message);
545
+ }
546
+ }
547
+
548
+ // Shutdown async tool manager
549
+ if (this.asyncToolManager) {
550
+ await this.asyncToolManager.shutdown();
551
+ this.logger?.info('Async tool manager shutdown complete');
552
+ }
553
+
554
+ // Shutdown orchestrator
555
+ if (this.orchestrator) {
556
+ await this.orchestrator.shutdown();
557
+ this.logger?.info('Orchestrator shutdown complete');
558
+ }
559
+
560
+ // Cleanup configuration manager
561
+ if (this.configManager) {
562
+ this.configManager.cleanup();
563
+ }
564
+
565
+ // Close logger
566
+ if (this.logger) {
567
+ await this.logger.close();
568
+ }
569
+
570
+ console.log('āœ… Loxia Autopilot One shutdown complete');
571
+
572
+ } catch (error) {
573
+ console.error('āŒ Error during shutdown:', error.message);
574
+ } finally {
575
+ process.exit(0);
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Get application status
581
+ * @returns {Object} Application status
582
+ */
583
+ getStatus() {
584
+ return {
585
+ version: SYSTEM_VERSION,
586
+ uptime: process.uptime(),
587
+ memoryUsage: process.memoryUsage(),
588
+ interfaces: Array.from(this.interfaces.keys()),
589
+ isShuttingDown: this.isShuttingDown
590
+ };
591
+ }
592
+ }
593
+
594
+ /**
595
+ * Main application entry point
596
+ */
597
+ async function main() {
598
+ const app = new LoxiaApplication();
599
+
600
+ // Parse command line arguments
601
+ const args = process.argv.slice(2);
602
+ const options = {
603
+ projectDir: process.cwd(),
604
+ watchConfig: args.includes('--watch-config'),
605
+ configPaths: []
606
+ };
607
+
608
+ // Look for custom config file
609
+ const configIndex = args.indexOf('--config');
610
+ if (configIndex !== -1 && args[configIndex + 1]) {
611
+ options.configPaths.push(args[configIndex + 1]);
612
+ }
613
+
614
+ await app.initialize(options);
615
+
616
+ // Keep the application running
617
+ return app;
618
+ }
619
+
620
+ // Start the application if this file is run directly
621
+ const __filename = fileURLToPath(import.meta.url);
622
+ if (process.argv[1] === __filename) {
623
+ console.log('šŸš€ Starting Loxia Autopilot One...');
624
+ main().catch(error => {
625
+ console.error('āŒ Failed to start Loxia Autopilot One:', error.message);
626
+ console.error('Stack trace:', error.stack);
627
+ process.exit(1);
628
+ });
629
+ }
630
+
631
+ export { LoxiaApplication, main };