aegiscode 3.1.10 → 3.4.2
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.
- package/bin/aegis.js +165 -0
- package/package.json +18 -86
- package/LICENSE +0 -21
- package/README.md +0 -394
- package/dist/main.js +0 -2171
- package/gui/run-gui.cjs +0 -13
- package/src/agent/Agent.ts +0 -903
- package/src/agent/SimpleAgent.ts +0 -48
- package/src/agent/index.ts +0 -54
- package/src/agent/orchestrator/AppBuilder.ts +0 -443
- package/src/agent/orchestrator/CouncilAgent.ts +0 -310
- package/src/agent/orchestrator/DiscussionRoom.ts +0 -462
- package/src/agent/orchestrator/OrchestratorAgent.ts +0 -637
- package/src/agent/orchestrator/index.ts +0 -38
- package/src/agent/orchestrator/utils.ts +0 -397
- package/src/agent/pricing.ts +0 -115
- package/src/agent/router.ts +0 -74
- package/src/agent/routerStats.ts +0 -121
- package/src/agent/types.ts +0 -318
- package/src/auth/login.ts +0 -383
- package/src/cli/config.ts +0 -189
- package/src/cli/index.ts +0 -17
- package/src/cli/middleware.ts +0 -119
- package/src/cli/types.ts +0 -75
- package/src/config/ConfigManager.ts +0 -587
- package/src/config/index.ts +0 -7
- package/src/config/types.ts +0 -584
- package/src/context/CompactionService.ts +0 -300
- package/src/context/ContextManager.ts +0 -450
- package/src/context/FileAnalyzer.ts +0 -267
- package/src/context/TokenCounter.ts +0 -265
- package/src/context/index.ts +0 -27
- package/src/context/storage/CacheStore.ts +0 -176
- package/src/context/storage/JSONLStore.ts +0 -201
- package/src/context/storage/MemoryStore.ts +0 -205
- package/src/context/storage/PersistentStore.ts +0 -327
- package/src/context/storage/index.ts +0 -9
- package/src/context/storage/pathUtils.ts +0 -114
- package/src/context/test.ts +0 -309
- package/src/context/types.ts +0 -268
- package/src/hooks/HookExecutor.ts +0 -434
- package/src/hooks/HookManager.ts +0 -596
- package/src/hooks/HookService.ts +0 -269
- package/src/hooks/Matcher.ts +0 -157
- package/src/hooks/index.ts +0 -63
- package/src/hooks/types.ts +0 -424
- package/src/main.tsx +0 -596
- package/src/mcp/HealthMonitor.ts +0 -150
- package/src/mcp/McpClient.ts +0 -491
- package/src/mcp/McpRegistry.ts +0 -321
- package/src/mcp/createMcpTool.ts +0 -251
- package/src/mcp/index.ts +0 -15
- package/src/mcp/server.ts +0 -334
- package/src/mcp/test-server.ts +0 -88
- package/src/mcp/test.ts +0 -372
- package/src/mcp/types.ts +0 -247
- package/src/memory/AgentMemoryBus.ts +0 -432
- package/src/memory/CloudSync.ts +0 -99
- package/src/memory/DriveSync.ts +0 -106
- package/src/memory/SharedMemory.ts +0 -951
- package/src/memory/index.ts +0 -14
- package/src/memory/machineFingerprint.ts +0 -40
- package/src/orchestrator/SubAgentMetadata.ts +0 -136
- package/src/prompts/builder.ts +0 -213
- package/src/prompts/default.ts +0 -144
- package/src/prompts/index.ts +0 -16
- package/src/prompts/plan.ts +0 -64
- package/src/prompts/test.ts +0 -78
- package/src/services/AnthropicChatService.ts +0 -341
- package/src/services/ChatService.ts +0 -347
- package/src/services/ClaudeCliChatService.ts +0 -256
- package/src/services/CloudSync.ts +0 -168
- package/src/services/CostLedger.ts +0 -211
- package/src/services/Heartbeat.ts +0 -135
- package/src/services/LearningCollector.ts +0 -291
- package/src/services/OllamaInstaller.ts +0 -342
- package/src/services/VersionChecker.ts +0 -445
- package/src/services/index.ts +0 -57
- package/src/services/streaming/OpenAIEventAdapter.ts +0 -126
- package/src/services/streaming/RenderingProfile.ts +0 -90
- package/src/services/streaming/StreamEventParser.ts +0 -181
- package/src/services/streaming/ThrottledRenderer.ts +0 -139
- package/src/services/streaming/TranscriptBuffer.ts +0 -574
- package/src/services/streaming/eventStatusMap.ts +0 -52
- package/src/services/streaming/index.ts +0 -46
- package/src/services/streaming/renderFormatting.ts +0 -79
- package/src/services/streaming/types.ts +0 -234
- package/src/skills/SkillLoader.ts +0 -126
- package/src/skills/SkillRegistry.ts +0 -366
- package/src/skills/index.ts +0 -48
- package/src/skills/types.ts +0 -146
- package/src/slash-commands/billing.ts +0 -70
- package/src/slash-commands/build.ts +0 -413
- package/src/slash-commands/builtinCommands.ts +0 -2733
- package/src/slash-commands/clone.ts +0 -242
- package/src/slash-commands/council.ts +0 -125
- package/src/slash-commands/custom/CustomCommandExecutor.ts +0 -143
- package/src/slash-commands/custom/CustomCommandLoader.ts +0 -251
- package/src/slash-commands/custom/CustomCommandRegistry.ts +0 -144
- package/src/slash-commands/custom/index.ts +0 -7
- package/src/slash-commands/debate.ts +0 -254
- package/src/slash-commands/gmail.ts +0 -105
- package/src/slash-commands/index.ts +0 -388
- package/src/slash-commands/mcpCommand.ts +0 -205
- package/src/slash-commands/types.ts +0 -201
- package/src/store/index.ts +0 -76
- package/src/store/selectors.ts +0 -246
- package/src/store/slices/appSlice.ts +0 -205
- package/src/store/slices/commandSlice.ts +0 -115
- package/src/store/slices/configSlice.ts +0 -46
- package/src/store/slices/focusSlice.ts +0 -64
- package/src/store/slices/index.ts +0 -9
- package/src/store/slices/sessionSlice.ts +0 -424
- package/src/store/streaming-buffer.ts +0 -425
- package/src/store/test.ts +0 -296
- package/src/store/types.ts +0 -274
- package/src/store/vanilla.ts +0 -186
- package/src/tools/builtin/bash.ts +0 -236
- package/src/tools/builtin/council.ts +0 -105
- package/src/tools/builtin/edit.ts +0 -213
- package/src/tools/builtin/glob.ts +0 -136
- package/src/tools/builtin/grep.ts +0 -263
- package/src/tools/builtin/index.ts +0 -61
- package/src/tools/builtin/memory.ts +0 -66
- package/src/tools/builtin/read.ts +0 -168
- package/src/tools/builtin/skill.ts +0 -97
- package/src/tools/builtin/snapshot.ts +0 -40
- package/src/tools/builtin/task.ts +0 -106
- package/src/tools/builtin/write.ts +0 -134
- package/src/tools/createTool.ts +0 -221
- package/src/tools/execution/ExecutionPipeline.ts +0 -263
- package/src/tools/execution/index.ts +0 -40
- package/src/tools/execution/stages/CacheStage.ts +0 -131
- package/src/tools/execution/stages/ConfirmationStage.ts +0 -203
- package/src/tools/execution/stages/DiscoveryStage.ts +0 -46
- package/src/tools/execution/stages/ExecutionStage.ts +0 -48
- package/src/tools/execution/stages/FormattingStage.ts +0 -44
- package/src/tools/execution/stages/HookStage.ts +0 -72
- package/src/tools/execution/stages/PermissionStage.ts +0 -287
- package/src/tools/execution/stages/PostHookStage.ts +0 -71
- package/src/tools/execution/stages/index.ts +0 -12
- package/src/tools/execution/test.ts +0 -266
- package/src/tools/execution/types.ts +0 -273
- package/src/tools/index.ts +0 -81
- package/src/tools/registry.ts +0 -304
- package/src/tools/schemas.ts +0 -109
- package/src/tools/test.ts +0 -220
- package/src/tools/types.ts +0 -175
- package/src/tools/validation/PermissionChecker.ts +0 -242
- package/src/tools/validation/SensitiveFileDetector.ts +0 -210
- package/src/tools/validation/index.ts +0 -11
- package/src/ui/App.tsx +0 -166
- package/src/ui/components/AegisInterface.tsx +0 -484
- package/src/ui/components/common/ChatSearch.tsx +0 -150
- package/src/ui/components/common/ErrorBoundary.tsx +0 -82
- package/src/ui/components/common/ExitMessage.tsx +0 -120
- package/src/ui/components/common/LoadingIndicator.tsx +0 -49
- package/src/ui/components/common/index.ts +0 -6
- package/src/ui/components/dialog/ConfirmationPrompt.tsx +0 -208
- package/src/ui/components/dialog/InteractiveSelector.tsx +0 -149
- package/src/ui/components/dialog/SetupWizard.tsx +0 -297
- package/src/ui/components/dialog/UpdatePrompt.tsx +0 -155
- package/src/ui/components/dialog/index.ts +0 -8
- package/src/ui/components/index.ts +0 -28
- package/src/ui/components/input/CommandSuggestions.tsx +0 -139
- package/src/ui/components/input/CustomTextInput.tsx +0 -220
- package/src/ui/components/input/InputArea.tsx +0 -361
- package/src/ui/components/input/PromptSuggestions.tsx +0 -66
- package/src/ui/components/input/index.ts +0 -6
- package/src/ui/components/layout/ChatStatusBar.tsx +0 -90
- package/src/ui/components/layout/ContextBar.tsx +0 -79
- package/src/ui/components/layout/MessageArea.tsx +0 -96
- package/src/ui/components/layout/MessageList.tsx +0 -647
- package/src/ui/components/layout/MessageSeparator.tsx +0 -26
- package/src/ui/components/layout/WelcomeMessage.tsx +0 -93
- package/src/ui/components/layout/index.ts +0 -7
- package/src/ui/components/markdown/CodeHighlighter.tsx +0 -292
- package/src/ui/components/markdown/MessageRenderer.tsx +0 -1211
- package/src/ui/components/markdown/index.ts +0 -8
- package/src/ui/components/markdown/parser.ts +0 -336
- package/src/ui/components/markdown/types.ts +0 -66
- package/src/ui/focus/FocusManager.ts +0 -137
- package/src/ui/focus/index.ts +0 -13
- package/src/ui/focus/types.ts +0 -54
- package/src/ui/focus/useFocus.ts +0 -75
- package/src/ui/hooks/index.ts +0 -11
- package/src/ui/hooks/useAgent.ts +0 -284
- package/src/ui/hooks/useCommandHistory.ts +0 -87
- package/src/ui/hooks/useCommandProcessor.ts +0 -443
- package/src/ui/hooks/useConfirmation.ts +0 -99
- package/src/ui/hooks/useCtrlCHandler.ts +0 -100
- package/src/ui/hooks/useInputBuffer.ts +0 -122
- package/src/ui/hooks/useTerminalSize.ts +0 -68
- package/src/ui/hooks/useTerminalWidth.ts +0 -5
- package/src/ui/hooks/useWindowedList.ts +0 -118
- package/src/ui/render-debugger.ts +0 -621
- package/src/ui/test.ts +0 -189
- package/src/ui/themes/ThemeManager.ts +0 -332
- package/src/ui/themes/aegisTheme.ts +0 -87
- package/src/ui/themes/darkTheme.ts +0 -87
- package/src/ui/themes/defaultTheme.ts +0 -85
- package/src/ui/themes/index.ts +0 -10
- package/src/ui/themes/lightTheme.ts +0 -89
- package/src/ui/themes/popularThemes.ts +0 -187
- package/src/ui/themes/types.ts +0 -130
- package/src/utils/clipboard.ts +0 -48
- package/src/utils/debug.ts +0 -43
- package/src/utils/environment.ts +0 -68
- package/src/utils/index.ts +0 -10
package/src/mcp/HealthMonitor.ts
DELETED
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* MCP 服务器健康监控
|
|
3
|
-
*
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { EventEmitter } from 'events';
|
|
7
|
-
import type { HealthCheckConfig, McpClientInterface } from './types.js';
|
|
8
|
-
import { McpConnectionStatus, DEFAULT_HEALTH_CHECK_CONFIG } from './types.js';
|
|
9
|
-
import { createDebugLogger } from '../utils/debug.js';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
*
|
|
13
|
-
*/
|
|
14
|
-
export class HealthMonitor extends EventEmitter {
|
|
15
|
-
private checkTimer: NodeJS.Timeout | null = null;
|
|
16
|
-
private consecutiveFailures = 0;
|
|
17
|
-
private isRunning = false;
|
|
18
|
-
private lastCheckTime: Date | null = null;
|
|
19
|
-
private lastCheckResult: 'healthy' | 'unhealthy' | 'unknown' = 'unknown';
|
|
20
|
-
private debug: ReturnType<typeof createDebugLogger>;
|
|
21
|
-
|
|
22
|
-
constructor(
|
|
23
|
-
private client: McpClientInterface,
|
|
24
|
-
private config: HealthCheckConfig = DEFAULT_HEALTH_CHECK_CONFIG
|
|
25
|
-
) {
|
|
26
|
-
super();
|
|
27
|
-
this.debug = createDebugLogger(`HealthMonitor:${client.serverName}`);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
*
|
|
32
|
-
*/
|
|
33
|
-
start(): void {
|
|
34
|
-
if (this.isRunning) {
|
|
35
|
-
return;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
this.isRunning = true;
|
|
39
|
-
this.consecutiveFailures = 0;
|
|
40
|
-
this.scheduleNextCheck();
|
|
41
|
-
|
|
42
|
-
this.debug.log(
|
|
43
|
-
`健康监控已启动`,
|
|
44
|
-
`(间隔: ${this.config.intervalMs}ms, 超时: ${this.config.timeoutMs}ms)`
|
|
45
|
-
);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
*
|
|
50
|
-
*/
|
|
51
|
-
stop(): void {
|
|
52
|
-
this.isRunning = false;
|
|
53
|
-
if (this.checkTimer) {
|
|
54
|
-
clearTimeout(this.checkTimer);
|
|
55
|
-
this.checkTimer = null;
|
|
56
|
-
}
|
|
57
|
-
this.debug.log(`健康监控已停止`);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
*
|
|
62
|
-
*/
|
|
63
|
-
getStatus(): {
|
|
64
|
-
isHealthy: boolean;
|
|
65
|
-
consecutiveFailures: number;
|
|
66
|
-
lastCheckTime: Date | null;
|
|
67
|
-
lastCheckResult: 'healthy' | 'unhealthy' | 'unknown';
|
|
68
|
-
} {
|
|
69
|
-
return {
|
|
70
|
-
isHealthy: this.consecutiveFailures < this.config.maxFailures,
|
|
71
|
-
consecutiveFailures: this.consecutiveFailures,
|
|
72
|
-
lastCheckTime: this.lastCheckTime,
|
|
73
|
-
lastCheckResult: this.lastCheckResult,
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
*
|
|
79
|
-
*/
|
|
80
|
-
private scheduleNextCheck(): void {
|
|
81
|
-
if (!this.isRunning) {
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
this.checkTimer = setTimeout(async () => {
|
|
86
|
-
await this.performCheck();
|
|
87
|
-
this.scheduleNextCheck();
|
|
88
|
-
}, this.config.intervalMs);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
*
|
|
93
|
-
*/
|
|
94
|
-
private async performCheck(): Promise<void> {
|
|
95
|
-
if (!this.isRunning) {
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// 只在连接状态下进行检
|
|
100
|
-
if (this.client.connectionStatus !== McpConnectionStatus.CONNECTED) {
|
|
101
|
-
this.lastCheckResult = 'unknown';
|
|
102
|
-
return;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
this.lastCheckTime = new Date();
|
|
106
|
-
|
|
107
|
-
try {
|
|
108
|
-
// 使用超时包装检
|
|
109
|
-
const checkPromise = this.doHealthCheck();
|
|
110
|
-
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
111
|
-
setTimeout(() => reject(new Error('健康检查超时')), this.config.timeoutMs);
|
|
112
|
-
});
|
|
113
|
-
|
|
114
|
-
await Promise.race([checkPromise, timeoutPromise]);
|
|
115
|
-
|
|
116
|
-
// 检查成
|
|
117
|
-
this.consecutiveFailures = 0;
|
|
118
|
-
this.lastCheckResult = 'healthy';
|
|
119
|
-
this.emit('healthy');
|
|
120
|
-
} catch (error) {
|
|
121
|
-
// 检查失
|
|
122
|
-
this.consecutiveFailures++;
|
|
123
|
-
this.lastCheckResult = 'unhealthy';
|
|
124
|
-
|
|
125
|
-
this.debug.warn(
|
|
126
|
-
`健康检查失败`,
|
|
127
|
-
`(${this.consecutiveFailures}/${this.config.maxFailures}):`,
|
|
128
|
-
(error as Error).message
|
|
129
|
-
);
|
|
130
|
-
|
|
131
|
-
// 超过最大失败次数,触发不健康事
|
|
132
|
-
if (this.consecutiveFailures >= this.config.maxFailures) {
|
|
133
|
-
this.debug.error(
|
|
134
|
-
`服务器不健康,连续失败 ${this.consecutiveFailures} 次`
|
|
135
|
-
);
|
|
136
|
-
this.emit('unhealthy', this.consecutiveFailures, error);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*/
|
|
145
|
-
private async doHealthCheck(): Promise<void> {
|
|
146
|
-
// 简单的健康检查:尝试重新加载工具列
|
|
147
|
-
// 如果能成功获取,说明连接是健康
|
|
148
|
-
await this.client.reloadTools();
|
|
149
|
-
}
|
|
150
|
-
}
|
package/src/mcp/McpClient.ts
DELETED
|
@@ -1,491 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* MCP 客户端
|
|
3
|
-
*
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { EventEmitter } from 'events';
|
|
7
|
-
import {
|
|
8
|
-
McpConnectionStatus,
|
|
9
|
-
McpToolDefinition,
|
|
10
|
-
McpToolCallResponse,
|
|
11
|
-
McpServerConfig,
|
|
12
|
-
HealthCheckConfig,
|
|
13
|
-
ErrorType,
|
|
14
|
-
ClassifiedError,
|
|
15
|
-
DEFAULT_CONNECTION_CONFIG,
|
|
16
|
-
type McpClientInterface,
|
|
17
|
-
} from './types.js';
|
|
18
|
-
import { HealthMonitor } from './HealthMonitor.js';
|
|
19
|
-
import { createDebugLogger } from '../utils/debug.js';
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
*
|
|
23
|
-
*/
|
|
24
|
-
function classifyError(error: unknown): ClassifiedError {
|
|
25
|
-
if (!(error instanceof Error)) {
|
|
26
|
-
return {
|
|
27
|
-
type: ErrorType.UNKNOWN,
|
|
28
|
-
isRetryable: false,
|
|
29
|
-
originalError: new Error(String(error)),
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const msg = error.message.toLowerCase();
|
|
34
|
-
|
|
35
|
-
// 永久性配置错误(不重
|
|
36
|
-
const permanentErrors = [
|
|
37
|
-
'command not found',
|
|
38
|
-
'no such file',
|
|
39
|
-
'permission denied',
|
|
40
|
-
'invalid configuration',
|
|
41
|
-
'enoent',
|
|
42
|
-
'spawn',
|
|
43
|
-
];
|
|
44
|
-
if (permanentErrors.some(p => msg.includes(p))) {
|
|
45
|
-
return { type: ErrorType.CONFIG_ERROR, isRetryable: false, originalError: error };
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// 认证错误(需要用户介
|
|
49
|
-
if (msg.includes('unauthorized') || msg.includes('401') || msg.includes('authentication failed')) {
|
|
50
|
-
return { type: ErrorType.AUTH_ERROR, isRetryable: false, originalError: error };
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// 临时网络错误(可重
|
|
54
|
-
const temporaryErrors = [
|
|
55
|
-
'timeout',
|
|
56
|
-
'connection refused',
|
|
57
|
-
'network error',
|
|
58
|
-
'rate limit',
|
|
59
|
-
'503',
|
|
60
|
-
'429',
|
|
61
|
-
'econnrefused',
|
|
62
|
-
'etimedout',
|
|
63
|
-
];
|
|
64
|
-
if (temporaryErrors.some(t => msg.includes(t))) {
|
|
65
|
-
return { type: ErrorType.NETWORK_TEMPORARY, isRetryable: true, originalError: error };
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// 默认允许重
|
|
69
|
-
return { type: ErrorType.UNKNOWN, isRetryable: true, originalError: error };
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* MCP 客户端实现
|
|
74
|
-
*/
|
|
75
|
-
export class McpClient extends EventEmitter implements McpClientInterface {
|
|
76
|
-
private status: McpConnectionStatus = McpConnectionStatus.DISCONNECTED;
|
|
77
|
-
private sdkClient: any = null; // @modelcontextprotocol/sdk Client
|
|
78
|
-
private tools = new Map<string, McpToolDefinition>();
|
|
79
|
-
private serverInfo: { name: string; version: string } | null = null;
|
|
80
|
-
|
|
81
|
-
// 重连配
|
|
82
|
-
private reconnectAttempts = 0;
|
|
83
|
-
private reconnectTimer: NodeJS.Timeout | null = null;
|
|
84
|
-
private isManualDisconnect = false;
|
|
85
|
-
|
|
86
|
-
// 健康监
|
|
87
|
-
private healthMonitor: HealthMonitor | null = null;
|
|
88
|
-
|
|
89
|
-
// 服务器名称(用于日
|
|
90
|
-
public readonly serverName: string;
|
|
91
|
-
|
|
92
|
-
// Debug logger
|
|
93
|
-
private debug: ReturnType<typeof createDebugLogger>;
|
|
94
|
-
|
|
95
|
-
constructor(
|
|
96
|
-
private config: McpServerConfig,
|
|
97
|
-
serverName?: string,
|
|
98
|
-
healthCheckConfig?: HealthCheckConfig
|
|
99
|
-
) {
|
|
100
|
-
super();
|
|
101
|
-
this.serverName = serverName || 'default';
|
|
102
|
-
this.debug = createDebugLogger(`McpClient:${this.serverName}`);
|
|
103
|
-
|
|
104
|
-
// 初始化健康监
|
|
105
|
-
if (healthCheckConfig?.enabled) {
|
|
106
|
-
this.healthMonitor = new HealthMonitor(this, healthCheckConfig);
|
|
107
|
-
this.healthMonitor.on('unhealthy', (failures: number, error: Error) => {
|
|
108
|
-
this.emit('unhealthy', failures, error);
|
|
109
|
-
// 触发重
|
|
110
|
-
if (this.status === McpConnectionStatus.CONNECTED) {
|
|
111
|
-
this.handleUnexpectedClose();
|
|
112
|
-
}
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
*
|
|
119
|
-
*/
|
|
120
|
-
get connectionStatus(): McpConnectionStatus {
|
|
121
|
-
return this.status;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
*
|
|
126
|
-
*/
|
|
127
|
-
get availableTools(): McpToolDefinition[] {
|
|
128
|
-
return Array.from(this.tools.values());
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
*
|
|
133
|
-
*/
|
|
134
|
-
private setStatus(status: McpConnectionStatus): void {
|
|
135
|
-
const oldStatus = this.status;
|
|
136
|
-
this.status = status;
|
|
137
|
-
if (oldStatus !== status) {
|
|
138
|
-
this.emit('statusChanged', status, oldStatus);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
*
|
|
144
|
-
*/
|
|
145
|
-
async connectWithRetry(
|
|
146
|
-
maxRetries = DEFAULT_CONNECTION_CONFIG.maxRetries,
|
|
147
|
-
initialDelay = DEFAULT_CONNECTION_CONFIG.initialDelay
|
|
148
|
-
): Promise<void> {
|
|
149
|
-
if (this.status !== McpConnectionStatus.DISCONNECTED) {
|
|
150
|
-
throw new Error('客户端已连接或正在连接中');
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
let lastError: Error | null = null;
|
|
154
|
-
|
|
155
|
-
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
156
|
-
try {
|
|
157
|
-
await this.doConnect();
|
|
158
|
-
this.reconnectAttempts = 0;
|
|
159
|
-
return;
|
|
160
|
-
} catch (error) {
|
|
161
|
-
lastError = error as Error;
|
|
162
|
-
const classified = classifyError(error);
|
|
163
|
-
|
|
164
|
-
this.debug.warn(
|
|
165
|
-
`连接失败(${attempt}/${maxRetries}):`,
|
|
166
|
-
classified.type,
|
|
167
|
-
(error as Error).message
|
|
168
|
-
);
|
|
169
|
-
|
|
170
|
-
// 永久性错误不重
|
|
171
|
-
if (!classified.isRetryable) {
|
|
172
|
-
this.debug.error(`检测到永久性错误,放弃重试`);
|
|
173
|
-
throw error;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// 指数退避重
|
|
177
|
-
if (attempt < maxRetries) {
|
|
178
|
-
const delay = initialDelay * Math.pow(2, attempt - 1);
|
|
179
|
-
this.debug.log(`${delay}ms 后重试...`);
|
|
180
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
throw lastError || new Error('连接失败');
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
*
|
|
190
|
-
*/
|
|
191
|
-
private async doConnect(): Promise<void> {
|
|
192
|
-
try {
|
|
193
|
-
this.setStatus(McpConnectionStatus.CONNECTING);
|
|
194
|
-
|
|
195
|
-
// 动态导
|
|
196
|
-
const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
|
|
197
|
-
|
|
198
|
-
// 创建 SDK 客户
|
|
199
|
-
this.sdkClient = new Client(
|
|
200
|
-
{ name: 'aegis', version: '1.0.0' },
|
|
201
|
-
{ capabilities: { roots: { listChanged: true }, sampling: {} } }
|
|
202
|
-
);
|
|
203
|
-
|
|
204
|
-
// 监听关闭事
|
|
205
|
-
this.sdkClient.onclose = () => this.handleUnexpectedClose();
|
|
206
|
-
|
|
207
|
-
// 创建传输
|
|
208
|
-
const transport = await this.createTransport();
|
|
209
|
-
|
|
210
|
-
// 连
|
|
211
|
-
await this.sdkClient.connect(transport);
|
|
212
|
-
|
|
213
|
-
// 获取服务器信
|
|
214
|
-
const serverVersion = this.sdkClient.getServerVersion?.();
|
|
215
|
-
this.serverInfo = {
|
|
216
|
-
name: serverVersion?.name || 'Unknown',
|
|
217
|
-
version: serverVersion?.version || '0.0.0',
|
|
218
|
-
};
|
|
219
|
-
|
|
220
|
-
// 加载工具列
|
|
221
|
-
await this.loadTools();
|
|
222
|
-
|
|
223
|
-
this.setStatus(McpConnectionStatus.CONNECTED);
|
|
224
|
-
this.emit('connected', this.serverInfo);
|
|
225
|
-
|
|
226
|
-
// 启动健康监
|
|
227
|
-
if (this.healthMonitor) {
|
|
228
|
-
this.healthMonitor.start();
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
this.debug.log(
|
|
232
|
-
`已连接到服务器:`,
|
|
233
|
-
this.serverInfo.name,
|
|
234
|
-
`v${this.serverInfo.version}`,
|
|
235
|
-
`(${this.tools.size} 个工具)`
|
|
236
|
-
);
|
|
237
|
-
} catch (error) {
|
|
238
|
-
this.setStatus(McpConnectionStatus.ERROR);
|
|
239
|
-
this.emit('error', error);
|
|
240
|
-
throw error;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
/**
|
|
245
|
-
*
|
|
246
|
-
*/
|
|
247
|
-
private async createTransport(): Promise<any> {
|
|
248
|
-
const { type, command, args, env, cwd, url, headers } = this.config;
|
|
249
|
-
|
|
250
|
-
if (type === 'stdio') {
|
|
251
|
-
if (!command) {
|
|
252
|
-
throw new Error('stdio 传输需要 command 参数');
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
const { StdioClientTransport } = await import(
|
|
256
|
-
'@modelcontextprotocol/sdk/client/stdio.js'
|
|
257
|
-
);
|
|
258
|
-
|
|
259
|
-
// Whitelist — skicka bara säkra env-variabler till MCP child processes
|
|
260
|
-
const SAFE_ENV_KEYS = ['PATH', 'HOME', 'USER', 'SHELL', 'LANG', 'LC_ALL', 'TERM', 'TZ'];
|
|
261
|
-
const mergedEnv: Record<string, string> = {};
|
|
262
|
-
for (const key of SAFE_ENV_KEYS) {
|
|
263
|
-
const value = process.env[key];
|
|
264
|
-
if (value !== undefined) mergedEnv[key] = value;
|
|
265
|
-
}
|
|
266
|
-
// Tillåt explicit konfigurerade env-variabler från MCP-serverns config
|
|
267
|
-
if (env) {
|
|
268
|
-
Object.assign(mergedEnv, env);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
return new StdioClientTransport({
|
|
272
|
-
command,
|
|
273
|
-
args: args || [],
|
|
274
|
-
env: mergedEnv,
|
|
275
|
-
cwd: cwd || process.cwd(),
|
|
276
|
-
stderr: 'ignore',
|
|
277
|
-
});
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
if (type === 'sse') {
|
|
281
|
-
if (!url) {
|
|
282
|
-
throw new Error('sse 传输需要 url 参数');
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
const { SSEClientTransport } = await import(
|
|
286
|
-
'@modelcontextprotocol/sdk/client/sse.js'
|
|
287
|
-
);
|
|
288
|
-
|
|
289
|
-
return new SSEClientTransport(new URL(url), {
|
|
290
|
-
requestInit: { headers: headers || {} },
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
if (type === 'http') {
|
|
295
|
-
if (!url) {
|
|
296
|
-
throw new Error('http 传输需要 url 参数');
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// HTTP Streamable 传输(如果 SDK 支
|
|
300
|
-
try {
|
|
301
|
-
const { StreamableHTTPClientTransport } = await import(
|
|
302
|
-
'@modelcontextprotocol/sdk/client/streamableHttp.js'
|
|
303
|
-
);
|
|
304
|
-
return new StreamableHTTPClientTransport(new URL(url), {
|
|
305
|
-
requestInit: { headers: headers || {} },
|
|
306
|
-
});
|
|
307
|
-
} catch {
|
|
308
|
-
// 回退
|
|
309
|
-
const { SSEClientTransport } = await import(
|
|
310
|
-
'@modelcontextprotocol/sdk/client/sse.js'
|
|
311
|
-
);
|
|
312
|
-
return new SSEClientTransport(new URL(url), {
|
|
313
|
-
requestInit: { headers: headers || {} },
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
throw new Error(`不支持的传输类型: ${type}`);
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
/**
|
|
322
|
-
*
|
|
323
|
-
*/
|
|
324
|
-
private async loadTools(): Promise<void> {
|
|
325
|
-
if (!this.sdkClient) {
|
|
326
|
-
throw new Error('客户端未连接');
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
try {
|
|
330
|
-
const result = await this.sdkClient.listTools();
|
|
331
|
-
const oldCount = this.tools.size;
|
|
332
|
-
|
|
333
|
-
this.tools.clear();
|
|
334
|
-
if (result.tools && Array.isArray(result.tools)) {
|
|
335
|
-
for (const tool of result.tools) {
|
|
336
|
-
this.tools.set(tool.name, {
|
|
337
|
-
name: tool.name,
|
|
338
|
-
description: tool.description,
|
|
339
|
-
inputSchema: tool.inputSchema || { type: 'object' },
|
|
340
|
-
});
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
if (oldCount !== this.tools.size) {
|
|
345
|
-
this.emit('toolsUpdated', this.availableTools);
|
|
346
|
-
}
|
|
347
|
-
} catch (error) {
|
|
348
|
-
this.debug.error(`加载工具列表失败:`, error);
|
|
349
|
-
throw error;
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
/**
|
|
354
|
-
*
|
|
355
|
-
*/
|
|
356
|
-
async reloadTools(): Promise<void> {
|
|
357
|
-
await this.loadTools();
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
/**
|
|
361
|
-
*
|
|
362
|
-
*/
|
|
363
|
-
async callTool(
|
|
364
|
-
name: string,
|
|
365
|
-
arguments_: Record<string, any> = {}
|
|
366
|
-
): Promise<McpToolCallResponse> {
|
|
367
|
-
if (!this.sdkClient) {
|
|
368
|
-
throw new Error('客户端未连接到服务器');
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
if (!this.tools.has(name)) {
|
|
372
|
-
throw new Error(`工具 "${name}" 不存在`);
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
try {
|
|
376
|
-
const result = await this.sdkClient.callTool({
|
|
377
|
-
name,
|
|
378
|
-
arguments: arguments_,
|
|
379
|
-
});
|
|
380
|
-
|
|
381
|
-
return result as McpToolCallResponse;
|
|
382
|
-
} catch (error) {
|
|
383
|
-
this.debug.error(`调用工具 "${name}" 失败:`, error);
|
|
384
|
-
throw error;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
/**
|
|
389
|
-
*
|
|
390
|
-
*/
|
|
391
|
-
async disconnect(): Promise<void> {
|
|
392
|
-
this.isManualDisconnect = true;
|
|
393
|
-
|
|
394
|
-
// 停止健康监
|
|
395
|
-
if (this.healthMonitor) {
|
|
396
|
-
this.healthMonitor.stop();
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
// 清除重连计时
|
|
400
|
-
if (this.reconnectTimer) {
|
|
401
|
-
clearTimeout(this.reconnectTimer);
|
|
402
|
-
this.reconnectTimer = null;
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
// 关闭 SDK 客户
|
|
406
|
-
if (this.sdkClient) {
|
|
407
|
-
try {
|
|
408
|
-
await this.sdkClient.close();
|
|
409
|
-
} catch (error) {
|
|
410
|
-
this.debug.warn(`关闭连接时出错:`, error);
|
|
411
|
-
}
|
|
412
|
-
this.sdkClient = null;
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
this.tools.clear();
|
|
416
|
-
this.setStatus(McpConnectionStatus.DISCONNECTED);
|
|
417
|
-
this.emit('disconnected');
|
|
418
|
-
|
|
419
|
-
this.debug.log(`已断开连接`);
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/**
|
|
423
|
-
*
|
|
424
|
-
*/
|
|
425
|
-
private handleUnexpectedClose(): void {
|
|
426
|
-
if (this.isManualDisconnect) {
|
|
427
|
-
return;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
if (this.status === McpConnectionStatus.CONNECTED) {
|
|
431
|
-
this.debug.warn(`检测到意外断连,准备重连...`);
|
|
432
|
-
this.setStatus(McpConnectionStatus.ERROR);
|
|
433
|
-
this.emit('error', new Error('MCP服务器连接意外关闭'));
|
|
434
|
-
this.scheduleReconnect();
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
*
|
|
440
|
-
*/
|
|
441
|
-
private scheduleReconnect(): void {
|
|
442
|
-
if (this.reconnectTimer) {
|
|
443
|
-
clearTimeout(this.reconnectTimer);
|
|
444
|
-
this.reconnectTimer = null;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
if (this.reconnectAttempts >= DEFAULT_CONNECTION_CONFIG.maxReconnectAttempts) {
|
|
448
|
-
this.debug.error(`达到最大重连次数,放弃重连`);
|
|
449
|
-
this.emit('reconnectFailed');
|
|
450
|
-
return;
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
// 指数退避:1s, 2s, 4s, 8s, 16s(最
|
|
454
|
-
const delay = Math.min(
|
|
455
|
-
1000 * Math.pow(2, this.reconnectAttempts),
|
|
456
|
-
DEFAULT_CONNECTION_CONFIG.maxReconnectDelay
|
|
457
|
-
);
|
|
458
|
-
this.reconnectAttempts++;
|
|
459
|
-
|
|
460
|
-
this.debug.log(
|
|
461
|
-
`将在 ${delay}ms 后进行第 ${this.reconnectAttempts} 次重连...`
|
|
462
|
-
);
|
|
463
|
-
|
|
464
|
-
this.emit('reconnecting', this.reconnectAttempts);
|
|
465
|
-
|
|
466
|
-
this.reconnectTimer = setTimeout(async () => {
|
|
467
|
-
try {
|
|
468
|
-
// 清理旧连
|
|
469
|
-
if (this.sdkClient) {
|
|
470
|
-
await this.sdkClient.close().catch(() => {});
|
|
471
|
-
this.sdkClient = null;
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
this.setStatus(McpConnectionStatus.DISCONNECTED);
|
|
475
|
-
await this.doConnect();
|
|
476
|
-
|
|
477
|
-
this.debug.log(`重连成功`);
|
|
478
|
-
this.reconnectAttempts = 0;
|
|
479
|
-
this.emit('reconnected');
|
|
480
|
-
} catch (error) {
|
|
481
|
-
const classified = classifyError(error);
|
|
482
|
-
if (classified.isRetryable) {
|
|
483
|
-
this.scheduleReconnect();
|
|
484
|
-
} else {
|
|
485
|
-
this.debug.error(`检测到永久性错误,停止重连`);
|
|
486
|
-
this.emit('reconnectFailed');
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
}, delay);
|
|
490
|
-
}
|
|
491
|
-
}
|