@mcpilotx/intentorch 0.5.0

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 (101) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +545 -0
  3. package/dist/ai/ai.d.ts +205 -0
  4. package/dist/ai/ai.js +1200 -0
  5. package/dist/ai/cloud-intent-engine.d.ts +270 -0
  6. package/dist/ai/cloud-intent-engine.js +956 -0
  7. package/dist/ai/command.d.ts +59 -0
  8. package/dist/ai/command.js +285 -0
  9. package/dist/ai/config.d.ts +66 -0
  10. package/dist/ai/config.js +211 -0
  11. package/dist/ai/enhanced-intent.d.ts +17 -0
  12. package/dist/ai/enhanced-intent.js +32 -0
  13. package/dist/ai/index.d.ts +29 -0
  14. package/dist/ai/index.js +44 -0
  15. package/dist/ai/intent.d.ts +16 -0
  16. package/dist/ai/intent.js +30 -0
  17. package/dist/core/ai-config.d.ts +25 -0
  18. package/dist/core/ai-config.js +326 -0
  19. package/dist/core/config-manager.d.ts +36 -0
  20. package/dist/core/config-manager.js +400 -0
  21. package/dist/core/config-validator.d.ts +9 -0
  22. package/dist/core/config-validator.js +184 -0
  23. package/dist/core/constants.d.ts +34 -0
  24. package/dist/core/constants.js +37 -0
  25. package/dist/core/error-ai.d.ts +23 -0
  26. package/dist/core/error-ai.js +217 -0
  27. package/dist/core/error-handler.d.ts +197 -0
  28. package/dist/core/error-handler.js +467 -0
  29. package/dist/core/index.d.ts +13 -0
  30. package/dist/core/index.js +17 -0
  31. package/dist/core/logger.d.ts +27 -0
  32. package/dist/core/logger.js +108 -0
  33. package/dist/core/performance-monitor.d.ts +74 -0
  34. package/dist/core/performance-monitor.js +260 -0
  35. package/dist/core/providers.d.ts +36 -0
  36. package/dist/core/providers.js +304 -0
  37. package/dist/core/retry-manager.d.ts +41 -0
  38. package/dist/core/retry-manager.js +204 -0
  39. package/dist/core/types.d.ts +155 -0
  40. package/dist/core/types.js +2 -0
  41. package/dist/daemon/index.d.ts +10 -0
  42. package/dist/daemon/index.js +15 -0
  43. package/dist/daemon/intent-engine.d.ts +22 -0
  44. package/dist/daemon/intent-engine.js +50 -0
  45. package/dist/daemon/orchestrator.d.ts +24 -0
  46. package/dist/daemon/orchestrator.js +100 -0
  47. package/dist/daemon/pm.d.ts +33 -0
  48. package/dist/daemon/pm.js +127 -0
  49. package/dist/daemon/process.d.ts +11 -0
  50. package/dist/daemon/process.js +49 -0
  51. package/dist/daemon/server.d.ts +17 -0
  52. package/dist/daemon/server.js +435 -0
  53. package/dist/daemon/service.d.ts +36 -0
  54. package/dist/daemon/service.js +278 -0
  55. package/dist/index.d.ts +30 -0
  56. package/dist/index.js +36 -0
  57. package/dist/mcp/client.d.ts +51 -0
  58. package/dist/mcp/client.js +276 -0
  59. package/dist/mcp/index.d.ts +162 -0
  60. package/dist/mcp/index.js +199 -0
  61. package/dist/mcp/tool-registry.d.ts +71 -0
  62. package/dist/mcp/tool-registry.js +308 -0
  63. package/dist/mcp/transport.d.ts +83 -0
  64. package/dist/mcp/transport.js +515 -0
  65. package/dist/mcp/types.d.ts +136 -0
  66. package/dist/mcp/types.js +31 -0
  67. package/dist/runtime/adapter-advanced.d.ts +184 -0
  68. package/dist/runtime/adapter-advanced.js +160 -0
  69. package/dist/runtime/adapter.d.ts +9 -0
  70. package/dist/runtime/adapter.js +2 -0
  71. package/dist/runtime/detector-advanced.d.ts +59 -0
  72. package/dist/runtime/detector-advanced.js +487 -0
  73. package/dist/runtime/detector.d.ts +5 -0
  74. package/dist/runtime/detector.js +56 -0
  75. package/dist/runtime/docker-adapter.d.ts +18 -0
  76. package/dist/runtime/docker-adapter.js +170 -0
  77. package/dist/runtime/docker.d.ts +17 -0
  78. package/dist/runtime/docker.js +71 -0
  79. package/dist/runtime/executable-analyzer.d.ts +56 -0
  80. package/dist/runtime/executable-analyzer.js +391 -0
  81. package/dist/runtime/go-adapter.d.ts +19 -0
  82. package/dist/runtime/go-adapter.js +190 -0
  83. package/dist/runtime/index.d.ts +9 -0
  84. package/dist/runtime/index.js +10 -0
  85. package/dist/runtime/node-adapter.d.ts +10 -0
  86. package/dist/runtime/node-adapter.js +23 -0
  87. package/dist/runtime/node.d.ts +20 -0
  88. package/dist/runtime/node.js +86 -0
  89. package/dist/runtime/python-adapter.d.ts +11 -0
  90. package/dist/runtime/python-adapter.js +102 -0
  91. package/dist/runtime/python.d.ts +17 -0
  92. package/dist/runtime/python.js +72 -0
  93. package/dist/runtime/rust-adapter.d.ts +21 -0
  94. package/dist/runtime/rust-adapter.js +267 -0
  95. package/dist/sdk.d.ts +500 -0
  96. package/dist/sdk.js +904 -0
  97. package/docs/README.ZH_CN.md +545 -0
  98. package/docs/api.md +888 -0
  99. package/docs/architecture.md +731 -0
  100. package/docs/development.md +744 -0
  101. package/package.json +112 -0
@@ -0,0 +1,467 @@
1
+ /**
2
+ * IntentOrch SDK Unified Error Handling System
3
+ * Balances minimalist style with functional robustness
4
+ * Formerly known as MCPilot SDK
5
+ */
6
+ /**
7
+ * Error Code Enumeration
8
+ * Clear categorization for easy identification and handling
9
+ */
10
+ export var ErrorCode;
11
+ (function (ErrorCode) {
12
+ // ==================== Configuration Errors (1xx) ====================
13
+ ErrorCode["CONFIG_INVALID"] = "CONFIG_001";
14
+ ErrorCode["CONFIG_MISSING"] = "CONFIG_002";
15
+ ErrorCode["CONFIG_VALIDATION_FAILED"] = "CONFIG_003";
16
+ ErrorCode["CONFIG_MIGRATION_FAILED"] = "CONFIG_004";
17
+ // ==================== Service Errors (2xx) ====================
18
+ ErrorCode["SERVICE_NOT_FOUND"] = "SERVICE_001";
19
+ ErrorCode["SERVICE_ALREADY_EXISTS"] = "SERVICE_002";
20
+ ErrorCode["SERVICE_START_FAILED"] = "SERVICE_003";
21
+ ErrorCode["SERVICE_STOP_FAILED"] = "SERVICE_004";
22
+ ErrorCode["SERVICE_HEALTH_CHECK_FAILED"] = "SERVICE_005";
23
+ // ==================== Runtime Errors (3xx) ====================
24
+ ErrorCode["RUNTIME_DETECTION_FAILED"] = "RUNTIME_001";
25
+ ErrorCode["RUNTIME_NOT_SUPPORTED"] = "RUNTIME_002";
26
+ ErrorCode["RUNTIME_NOT_INSTALLED"] = "RUNTIME_003";
27
+ ErrorCode["RUNTIME_ADAPTER_ERROR"] = "RUNTIME_004";
28
+ // ==================== Process Errors (4xx) ====================
29
+ ErrorCode["PROCESS_NOT_FOUND"] = "PROCESS_001";
30
+ ErrorCode["PROCESS_START_FAILED"] = "PROCESS_002";
31
+ ErrorCode["PROCESS_STOP_FAILED"] = "PROCESS_003";
32
+ ErrorCode["PROCESS_TIMEOUT"] = "PROCESS_004";
33
+ // ==================== Resource Errors (5xx) ====================
34
+ ErrorCode["RESOURCE_LIMIT_EXCEEDED"] = "RESOURCE_001";
35
+ ErrorCode["MEMORY_LIMIT_EXCEEDED"] = "RESOURCE_002";
36
+ ErrorCode["CPU_LIMIT_EXCEEDED"] = "RESOURCE_003";
37
+ ErrorCode["DISK_SPACE_INSUFFICIENT"] = "RESOURCE_004";
38
+ // ==================== Permission Errors (6xx) ====================
39
+ ErrorCode["PERMISSION_DENIED"] = "PERMISSION_001";
40
+ ErrorCode["FILE_PERMISSION_ERROR"] = "PERMISSION_002";
41
+ ErrorCode["NETWORK_PERMISSION_ERROR"] = "PERMISSION_003";
42
+ // ==================== Network Errors (7xx) ====================
43
+ ErrorCode["NETWORK_ERROR"] = "NETWORK_001";
44
+ ErrorCode["CONNECTION_REFUSED"] = "NETWORK_002";
45
+ ErrorCode["CONNECTION_TIMEOUT"] = "NETWORK_003";
46
+ ErrorCode["DNS_RESOLUTION_FAILED"] = "NETWORK_004";
47
+ // ==================== AI Errors (8xx) ====================
48
+ ErrorCode["AI_CONFIG_INVALID"] = "AI_001";
49
+ ErrorCode["AI_PROVIDER_NOT_AVAILABLE"] = "AI_002";
50
+ ErrorCode["AI_QUERY_FAILED"] = "AI_003";
51
+ ErrorCode["AI_MODEL_NOT_FOUND"] = "AI_004";
52
+ // ==================== System Errors (9xx) ====================
53
+ ErrorCode["SYSTEM_ERROR"] = "SYSTEM_001";
54
+ ErrorCode["UNEXPECTED_ERROR"] = "SYSTEM_002";
55
+ ErrorCode["NOT_IMPLEMENTED"] = "SYSTEM_003";
56
+ // ==================== Validation Errors (10xx) ====================
57
+ ErrorCode["VALIDATION_FAILED"] = "VALIDATION_001";
58
+ ErrorCode["REQUIRED_FIELD_MISSING"] = "VALIDATION_002";
59
+ ErrorCode["INVALID_FORMAT"] = "VALIDATION_003";
60
+ ErrorCode["OUT_OF_RANGE"] = "VALIDATION_004";
61
+ })(ErrorCode || (ErrorCode = {}));
62
+ /**
63
+ * Error Severity Levels
64
+ */
65
+ export var ErrorSeverity;
66
+ (function (ErrorSeverity) {
67
+ ErrorSeverity["LOW"] = "low";
68
+ ErrorSeverity["MEDIUM"] = "medium";
69
+ ErrorSeverity["HIGH"] = "high";
70
+ ErrorSeverity["CRITICAL"] = "critical";
71
+ })(ErrorSeverity || (ErrorSeverity = {}));
72
+ /**
73
+ * IntentOrch Unified Error Class
74
+ */
75
+ export class IntentOrchError extends Error {
76
+ code;
77
+ message;
78
+ severity;
79
+ context;
80
+ suggestions;
81
+ cause;
82
+ constructor(code, message, severity = ErrorSeverity.MEDIUM, context = {}, suggestions = [], cause) {
83
+ super(message);
84
+ this.code = code;
85
+ this.message = message;
86
+ this.severity = severity;
87
+ this.context = context;
88
+ this.suggestions = suggestions;
89
+ this.cause = cause;
90
+ this.name = 'IntentOrchError';
91
+ // Ensure stack trace includes original error
92
+ if (cause && cause.stack) {
93
+ this.stack = `${this.stack}\nCaused by: ${cause.stack}`;
94
+ }
95
+ // Automatically add timestamp
96
+ if (!context.timestamp) {
97
+ context.timestamp = new Date();
98
+ }
99
+ }
100
+ /**
101
+ * Convert to JSON format for easy logging and transmission
102
+ */
103
+ toJSON() {
104
+ return {
105
+ name: this.name,
106
+ code: this.code,
107
+ message: this.message,
108
+ severity: this.severity,
109
+ context: this.context,
110
+ suggestions: this.suggestions,
111
+ stack: this.stack,
112
+ cause: this.cause ? (this.cause instanceof IntentOrchError ? this.cause.toJSON() : {
113
+ name: this.cause.name,
114
+ message: this.cause.message,
115
+ stack: this.cause.stack,
116
+ }) : undefined,
117
+ };
118
+ }
119
+ /**
120
+ * Get error summary for display
121
+ */
122
+ getSummary() {
123
+ return `[${this.code}] ${this.message}`;
124
+ }
125
+ /**
126
+ * Get detailed error information
127
+ */
128
+ getDetails() {
129
+ const details = [
130
+ `Error: ${this.name}`,
131
+ `Code: ${this.code}`,
132
+ `Message: ${this.message}`,
133
+ `Severity: ${this.severity}`,
134
+ ];
135
+ if (Object.keys(this.context).length > 0) {
136
+ details.push(`Context: ${JSON.stringify(this.context, null, 2)}`);
137
+ }
138
+ if (this.suggestions.length > 0) {
139
+ details.push('Suggestions:');
140
+ this.suggestions.forEach((suggestion, index) => {
141
+ details.push(` ${index + 1}. ${suggestion.title}: ${suggestion.description}`);
142
+ });
143
+ }
144
+ if (this.stack) {
145
+ details.push(`Stack: ${this.stack}`);
146
+ }
147
+ return details.join('\n');
148
+ }
149
+ }
150
+ /**
151
+ * MCPilot Unified Error Class (for backward compatibility)
152
+ * @deprecated Use IntentOrchError instead
153
+ */
154
+ export class MCPilotError extends IntentOrchError {
155
+ constructor(code, message, severity = ErrorSeverity.MEDIUM, context = {}, suggestions = [], cause) {
156
+ super(code, message, severity, context, suggestions, cause);
157
+ this.name = 'MCPilotError';
158
+ }
159
+ }
160
+ /**
161
+ * Error Factory - Create standardized error instances
162
+ */
163
+ export class ErrorFactory {
164
+ /**
165
+ * Configuration error
166
+ */
167
+ static configInvalid(message, context = {}, cause) {
168
+ return new MCPilotError(ErrorCode.CONFIG_INVALID, message, ErrorSeverity.HIGH, context, [
169
+ {
170
+ title: 'Check configuration file',
171
+ description: 'Please check if the configuration file format and content are correct',
172
+ steps: [
173
+ 'Verify configuration file path is correct',
174
+ 'Check if JSON format is correct',
175
+ 'Confirm all required fields are filled',
176
+ 'Refer to configuration examples in documentation',
177
+ ],
178
+ documentationUrl: 'https://github.com/MCPilotX/IntentOrch/docs/configuration',
179
+ },
180
+ ], cause);
181
+ }
182
+ /**
183
+ * Service not found error
184
+ */
185
+ static serviceNotFound(serviceName, context = {}) {
186
+ return new MCPilotError(ErrorCode.SERVICE_NOT_FOUND, `Service '${serviceName}' not found`, ErrorSeverity.MEDIUM, { ...context, serviceName }, [
187
+ {
188
+ title: 'Check service name',
189
+ description: 'Please confirm if the service name is correct',
190
+ steps: [
191
+ 'Use \'mcp ls\' command to view all services',
192
+ 'Confirm service name spelling is correct',
193
+ 'Check if service has been deleted',
194
+ 'If needed, re-add service: mcp add <path>',
195
+ ],
196
+ },
197
+ ]);
198
+ }
199
+ /**
200
+ * Runtime detection failed error
201
+ */
202
+ static runtimeDetectionFailed(path, context = {}, cause) {
203
+ return new MCPilotError(ErrorCode.RUNTIME_DETECTION_FAILED, `Failed to detect runtime for path: ${path}`, ErrorSeverity.MEDIUM, { ...context, path }, [
204
+ {
205
+ title: 'Manually specify runtime type',
206
+ description: 'Auto-detection failed, please manually specify runtime type',
207
+ steps: [
208
+ 'Use --type parameter to specify runtime: mcp add <path> --type <runtime>',
209
+ 'Supported runtime types: node, python, docker, go, rust, binary',
210
+ 'Check if project directory contains correct configuration files',
211
+ 'Confirm project structure meets expectations',
212
+ ],
213
+ codeExample: 'mcp add ./my-service --type node',
214
+ },
215
+ ], cause);
216
+ }
217
+ /**
218
+ * Process start failed error
219
+ */
220
+ static processStartFailed(serviceName, context = {}, cause) {
221
+ return new MCPilotError(ErrorCode.PROCESS_START_FAILED, `Failed to start process for service '${serviceName}'`, ErrorSeverity.HIGH, { ...context, serviceName }, [
222
+ {
223
+ title: 'Check service configuration',
224
+ description: 'Service startup failed, please check configuration and dependencies',
225
+ steps: [
226
+ 'Check if service path is correct',
227
+ 'Confirm runtime environment is installed',
228
+ `View service logs: mcp logs ${serviceName}`,
229
+ 'Check if port is occupied',
230
+ 'Verify dependencies are installed',
231
+ ],
232
+ },
233
+ ], cause);
234
+ }
235
+ /**
236
+ * Permission denied error
237
+ */
238
+ static permissionDenied(operation, resource, context = {}) {
239
+ return new MCPilotError(ErrorCode.PERMISSION_DENIED, `Permission denied for ${operation} on ${resource}`, ErrorSeverity.HIGH, { ...context, operation, resource }, [
240
+ {
241
+ title: 'Check file permissions',
242
+ description: 'Insufficient permissions to perform operation',
243
+ steps: [
244
+ `Check file/directory permissions: ls -la ${resource}`,
245
+ 'Use sudo to run command (if applicable)',
246
+ `Modify file permissions: chmod +x ${resource}`,
247
+ `Change file owner: chown $(whoami) ${resource}`,
248
+ ],
249
+ },
250
+ ]);
251
+ }
252
+ /**
253
+ * Network error
254
+ */
255
+ static networkError(operation, url, context = {}, cause) {
256
+ return new MCPilotError(ErrorCode.NETWORK_ERROR, `Network error during ${operation} to ${url}`, ErrorSeverity.MEDIUM, { ...context, operation, url }, [
257
+ {
258
+ title: 'Check network connection',
259
+ description: 'Network connection failed, please check network settings',
260
+ steps: [
261
+ 'Check if network connection is normal',
262
+ 'Verify URL is correct',
263
+ 'Check firewall settings',
264
+ 'Try using proxy (if configured)',
265
+ 'Wait and retry after some time',
266
+ ],
267
+ },
268
+ ], cause);
269
+ }
270
+ /**
271
+ * Not implemented error
272
+ */
273
+ static notImplemented(feature, context = {}) {
274
+ return new MCPilotError(ErrorCode.NOT_IMPLEMENTED, `Feature '${feature}' is not implemented yet`, ErrorSeverity.LOW, { ...context, feature }, [
275
+ {
276
+ title: 'Feature under development',
277
+ description: 'This feature is under development and will be available in future versions',
278
+ steps: [
279
+ 'View project roadmap',
280
+ 'Follow GitHub release page',
281
+ 'Consider using alternative solutions',
282
+ 'Submit feature request (if urgently needed)',
283
+ ],
284
+ documentationUrl: 'https://github.com/MCPilotX/IntentOrch/issues',
285
+ },
286
+ ]);
287
+ }
288
+ /**
289
+ * Validation error
290
+ */
291
+ static validationFailed(field, reason, context = {}) {
292
+ return new MCPilotError(ErrorCode.VALIDATION_FAILED, `Validation failed for field '${field}': ${reason}`, ErrorSeverity.MEDIUM, { ...context, field, reason }, [
293
+ {
294
+ title: 'Fix validation error',
295
+ description: 'Input data validation failed',
296
+ steps: [
297
+ `Check value of ${field} field`,
298
+ `Ensure value meets requirements: ${reason}`,
299
+ 'Refer to field description in documentation',
300
+ 'Use valid example values',
301
+ ],
302
+ },
303
+ ]);
304
+ }
305
+ }
306
+ /**
307
+ * Error Handler - Handle, log and recover from errors
308
+ */
309
+ export class ErrorHandler {
310
+ static instance;
311
+ handlers = [];
312
+ constructor() { }
313
+ static getInstance() {
314
+ if (!ErrorHandler.instance) {
315
+ ErrorHandler.instance = new ErrorHandler();
316
+ }
317
+ return ErrorHandler.instance;
318
+ }
319
+ /**
320
+ * Register error handler
321
+ */
322
+ registerHandler(handler) {
323
+ this.handlers.push(handler);
324
+ }
325
+ /**
326
+ * Handle error
327
+ */
328
+ async handle(error) {
329
+ // Convert to MCPilotError (if not already)
330
+ const mcError = error instanceof MCPilotError
331
+ ? error
332
+ : new MCPilotError(ErrorCode.UNEXPECTED_ERROR, error.message, ErrorSeverity.HIGH, {}, [], error);
333
+ // Log error
334
+ console.error(`[IntentOrch Error] ${mcError.getSummary()}`);
335
+ // Execute all registered handlers
336
+ for (const handler of this.handlers) {
337
+ try {
338
+ await handler(mcError);
339
+ }
340
+ catch (handlerError) {
341
+ console.error('Error handler failed:', handlerError);
342
+ }
343
+ }
344
+ }
345
+ /**
346
+ * Safely execute function, automatically handle errors
347
+ */
348
+ async execute(operation, fn, context = {}) {
349
+ try {
350
+ return await fn();
351
+ }
352
+ catch (error) {
353
+ const mcError = error instanceof MCPilotError
354
+ ? error
355
+ : new MCPilotError(ErrorCode.UNEXPECTED_ERROR, `Operation '${operation}' failed: ${error instanceof Error ? error.message : String(error)}`, ErrorSeverity.HIGH, { ...context, operation }, [], error instanceof Error ? error : undefined);
356
+ await this.handle(mcError);
357
+ throw mcError;
358
+ }
359
+ }
360
+ }
361
+ /**
362
+ * Default Error Handler - Console Output
363
+ */
364
+ export class ConsoleErrorHandler {
365
+ static async handle(error) {
366
+ const colors = {
367
+ low: '\x1b[36m', // cyan
368
+ medium: '\x1b[33m', // yellow
369
+ high: '\x1b[31m', // red
370
+ critical: '\x1b[41m\x1b[37m', // red background, white text
371
+ };
372
+ const color = colors[error.severity] || '\x1b[0m';
373
+ const reset = '\x1b[0m';
374
+ console.error(`\n${color}╔══════════════════════════════════════════════════════════════╗${reset}`);
375
+ console.error(`${color}║ IntentOrch Error: ${error.getSummary().padEnd(48)} ║${reset}`);
376
+ console.error(`${color}╚══════════════════════════════════════════════════════════════╝${reset}`);
377
+ console.error(`\n${color}Details:${reset}`);
378
+ console.error(error.getDetails());
379
+ if (error.suggestions.length > 0) {
380
+ console.error(`\n${color}Suggestions:${reset}`);
381
+ error.suggestions.forEach((suggestion, index) => {
382
+ console.error(` ${index + 1}. ${suggestion.title}`);
383
+ console.error(` ${suggestion.description}`);
384
+ if (suggestion.steps.length > 0) {
385
+ console.error(' Steps:');
386
+ suggestion.steps.forEach(step => {
387
+ console.error(` • ${step}`);
388
+ });
389
+ }
390
+ });
391
+ }
392
+ console.error(`\n${color}Need more help?${reset}`);
393
+ console.error(' • Check documentation: https://github.com/MCPilotX/IntentOrch/docs');
394
+ console.error(' • Report issue: https://github.com/MCPilotX/IntentOrch/issues');
395
+ console.error(' • Ask community: https://github.com/MCPilotX/IntentOrch/discussions\n');
396
+ }
397
+ }
398
+ /**
399
+ * Error Handler with Retry
400
+ */
401
+ export class RetryErrorHandler {
402
+ static async withRetry(operation, fn, strategy = {
403
+ maxAttempts: 3,
404
+ backoff: 'exponential',
405
+ baseDelay: 1000,
406
+ maxDelay: 10000,
407
+ }, context = {}) {
408
+ let lastError;
409
+ for (let attempt = 1; attempt <= strategy.maxAttempts; attempt++) {
410
+ try {
411
+ return await fn();
412
+ }
413
+ catch (error) {
414
+ lastError = error instanceof Error ? error : new Error(String(error));
415
+ // If this is the last attempt, throw error directly
416
+ if (attempt === strategy.maxAttempts) {
417
+ throw error;
418
+ }
419
+ // Calculate delay time
420
+ let delay = strategy.baseDelay;
421
+ if (strategy.backoff === 'exponential') {
422
+ delay = strategy.baseDelay * Math.pow(2, attempt - 1);
423
+ }
424
+ else if (strategy.backoff === 'linear') {
425
+ delay = strategy.baseDelay * attempt;
426
+ }
427
+ // Apply maximum delay limit
428
+ if (strategy.maxDelay && delay > strategy.maxDelay) {
429
+ delay = strategy.maxDelay;
430
+ }
431
+ console.warn(`[Retry] Attempt ${attempt}/${strategy.maxAttempts} failed for '${operation}'. Retrying in ${delay}ms...`);
432
+ // Wait for delay
433
+ await new Promise(resolve => setTimeout(resolve, delay));
434
+ }
435
+ }
436
+ // Theoretically won't reach here because error will be thrown in loop
437
+ throw lastError || new Error(`Operation '${operation}' failed after ${strategy.maxAttempts} attempts`);
438
+ }
439
+ }
440
+ // Initialize default error handler
441
+ const errorHandler = ErrorHandler.getInstance();
442
+ errorHandler.registerHandler(ConsoleErrorHandler.handle);
443
+ // Export common functions
444
+ export function createError(code, message, severity, context) {
445
+ return new MCPilotError(code, message, severity, context);
446
+ }
447
+ export function wrapError(error, code = ErrorCode.UNEXPECTED_ERROR, context) {
448
+ return new MCPilotError(code, error.message, ErrorSeverity.HIGH, context, [], error);
449
+ }
450
+ export function isMCPilotError(error) {
451
+ return error instanceof MCPilotError;
452
+ }
453
+ export function shouldRetry(error) {
454
+ if (!isMCPilotError(error)) {
455
+ return false;
456
+ }
457
+ // These error types can usually be resolved by retrying
458
+ const retryableCodes = [
459
+ ErrorCode.NETWORK_ERROR,
460
+ ErrorCode.CONNECTION_TIMEOUT,
461
+ ErrorCode.CONNECTION_REFUSED,
462
+ ErrorCode.PROCESS_START_FAILED,
463
+ ErrorCode.SERVICE_START_FAILED,
464
+ ];
465
+ return retryableCodes.includes(error.code);
466
+ }
467
+ //# sourceMappingURL=error-handler.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Core Module Exports
3
+ * Provides unified interface for core functionality
4
+ */
5
+ export { ConfigManager } from './config-manager';
6
+ export type { RuntimeType, ServiceConfig, Config, AIConfig, DetectionResult, DockerConnectionConfig, RuntimeSpecificConfig, } from './types';
7
+ export { MCPILOT_HOME, CONFIG_PATH, } from './constants';
8
+ export { MCPilotError, ErrorCode, ErrorSeverity, ErrorFactory, ErrorHandler, ConsoleErrorHandler, RetryErrorHandler, createError, wrapError, isMCPilotError, shouldRetry, } from './error-handler';
9
+ export { AIError } from './error-ai';
10
+ export { logger } from './logger';
11
+ export { PerformanceMonitor } from './performance-monitor';
12
+ export { RetryManager } from './retry-manager';
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Core Module Exports
3
+ * Provides unified interface for core functionality
4
+ */
5
+ // Export configuration management
6
+ export { ConfigManager } from './config-manager.js';
7
+ // Export constants
8
+ export { MCPILOT_HOME, CONFIG_PATH, } from './constants.js';
9
+ // Export error handling
10
+ export { MCPilotError, ErrorCode, ErrorSeverity, ErrorFactory, ErrorHandler, ConsoleErrorHandler, RetryErrorHandler, createError, wrapError, isMCPilotError, shouldRetry, } from './error-handler.js';
11
+ // Export logger
12
+ export { logger } from './logger.js';
13
+ // Export performance monitor
14
+ export { PerformanceMonitor } from './performance-monitor.js';
15
+ // Export retry manager
16
+ export { RetryManager } from './retry-manager.js';
17
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,27 @@
1
+ export declare enum LogLevel {
2
+ DEBUG = "DEBUG",
3
+ INFO = "INFO",
4
+ WARN = "WARN",
5
+ ERROR = "ERROR"
6
+ }
7
+ export declare class Logger {
8
+ private static instance;
9
+ private logFile;
10
+ private logLevel;
11
+ private constructor();
12
+ static getInstance(): Logger;
13
+ setLogLevel(level: LogLevel): void;
14
+ private shouldLog;
15
+ private formatMessage;
16
+ private writeToFile;
17
+ debug(message: string, context?: any): void;
18
+ info(message: string, context?: any): void;
19
+ warn(message: string, context?: any): void;
20
+ error(message: string, context?: any): void;
21
+ logRequest(command: string, data?: any): void;
22
+ logServiceEvent(serviceName: string, event: string, details?: any): void;
23
+ logAIQuery(query: string, result?: any): void;
24
+ logConfigUpdate(configType: string, config: any): void;
25
+ }
26
+ export declare const logger: Logger;
27
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1,108 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { LOGS_DIR } from './constants.js';
4
+ export var LogLevel;
5
+ (function (LogLevel) {
6
+ LogLevel["DEBUG"] = "DEBUG";
7
+ LogLevel["INFO"] = "INFO";
8
+ LogLevel["WARN"] = "WARN";
9
+ LogLevel["ERROR"] = "ERROR";
10
+ })(LogLevel || (LogLevel = {}));
11
+ export class Logger {
12
+ static instance;
13
+ logFile;
14
+ logLevel = LogLevel.INFO;
15
+ constructor() {
16
+ // Ensure log directory exists
17
+ if (!fs.existsSync(LOGS_DIR)) {
18
+ fs.mkdirSync(LOGS_DIR, { recursive: true });
19
+ }
20
+ // Create date-named log file
21
+ const date = new Date().toISOString().split('T')[0];
22
+ this.logFile = path.join(LOGS_DIR, `mcpilot-${date}.log`);
23
+ }
24
+ static getInstance() {
25
+ if (!Logger.instance) {
26
+ Logger.instance = new Logger();
27
+ }
28
+ return Logger.instance;
29
+ }
30
+ setLogLevel(level) {
31
+ this.logLevel = level;
32
+ }
33
+ shouldLog(level) {
34
+ const levels = [LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR];
35
+ return levels.indexOf(level) >= levels.indexOf(this.logLevel);
36
+ }
37
+ formatMessage(level, message, context) {
38
+ const timestamp = new Date().toISOString();
39
+ const contextStr = context ? ` ${JSON.stringify(context)}` : '';
40
+ return `[${timestamp}] [${level}] ${message}${contextStr}`;
41
+ }
42
+ writeToFile(message) {
43
+ try {
44
+ // Ensure log directory exists
45
+ const logDir = path.dirname(this.logFile);
46
+ if (!fs.existsSync(logDir)) {
47
+ fs.mkdirSync(logDir, { recursive: true });
48
+ }
49
+ // Ensure log file exists
50
+ if (!fs.existsSync(this.logFile)) {
51
+ fs.writeFileSync(this.logFile, '', 'utf8');
52
+ }
53
+ fs.appendFileSync(this.logFile, message + '\n', 'utf8');
54
+ }
55
+ catch (error) {
56
+ // If file write fails, at least output to console
57
+ console.error(`Failed to write to log file ${this.logFile}: ${error.message}`);
58
+ }
59
+ }
60
+ debug(message, context) {
61
+ if (this.shouldLog(LogLevel.DEBUG)) {
62
+ const formatted = this.formatMessage(LogLevel.DEBUG, message, context);
63
+ console.debug(formatted);
64
+ this.writeToFile(formatted);
65
+ }
66
+ }
67
+ info(message, context) {
68
+ if (this.shouldLog(LogLevel.INFO)) {
69
+ const formatted = this.formatMessage(LogLevel.INFO, message, context);
70
+ console.info(formatted);
71
+ this.writeToFile(formatted);
72
+ }
73
+ }
74
+ warn(message, context) {
75
+ if (this.shouldLog(LogLevel.WARN)) {
76
+ const formatted = this.formatMessage(LogLevel.WARN, message, context);
77
+ console.warn(formatted);
78
+ this.writeToFile(formatted);
79
+ }
80
+ }
81
+ error(message, context) {
82
+ if (this.shouldLog(LogLevel.ERROR)) {
83
+ const formatted = this.formatMessage(LogLevel.ERROR, message, context);
84
+ console.error(formatted);
85
+ this.writeToFile(formatted);
86
+ }
87
+ }
88
+ logRequest(command, data) {
89
+ this.info(`Received command: ${command}`, { data });
90
+ }
91
+ logServiceEvent(serviceName, event, details) {
92
+ this.info(`Service ${serviceName}: ${event}`, details);
93
+ }
94
+ logAIQuery(query, result) {
95
+ this.info(`AI Query: "${query}"`, { result });
96
+ }
97
+ logConfigUpdate(configType, config) {
98
+ // Safely record configuration updates, hide sensitive information
99
+ const safeConfig = { ...config };
100
+ if (safeConfig.apiKey) {
101
+ safeConfig.apiKey = '***' + safeConfig.apiKey.slice(-4);
102
+ }
103
+ this.info(`Configuration updated: ${configType}`, { config: safeConfig });
104
+ }
105
+ }
106
+ // Export singleton instance
107
+ export const logger = Logger.getInstance();
108
+ //# sourceMappingURL=logger.js.map