foliko 1.1.93 → 2.0.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.
- package/.claude/settings.local.json +2 -1
- package/CLAUDE.md +56 -30
- package/REFACTORING_PLAN.md +645 -0
- package/docs/architecture.md +131 -0
- package/docs/migration.md +57 -0
- package/docs/public-api.md +138 -0
- package/docs/usage.md +385 -0
- package/examples/ambient-example.js +20 -137
- package/examples/basic.js +21 -48
- package/examples/bootstrap.js +16 -74
- package/examples/mcp-example.js +6 -29
- package/examples/skill-example.js +6 -19
- package/examples/workflow.js +8 -56
- package/package.json +8 -4
- package/plugins/README.md +49 -0
- package/plugins/{ambient-agent → ambient}/EventWatcher.js +1 -1
- package/plugins/{ambient-agent → ambient}/ExplorerLoop.js +3 -3
- package/plugins/{ambient-agent → ambient}/GoalManager.js +2 -2
- package/plugins/ambient/README.md +14 -0
- package/plugins/{ambient-agent → ambient}/Reflector.js +1 -1
- package/plugins/{ambient-agent → ambient}/StateStore.js +1 -1
- package/plugins/{ambient-agent → ambient}/index.js +2 -2
- package/plugins/{ai-plugin.js → core/ai/index.js} +14 -30
- package/plugins/{audit-plugin.js → core/audit/index.js} +3 -30
- package/plugins/{coordinator-plugin.js → core/coordinator/index.js} +3 -35
- package/plugins/core/default/bootstrap.js +202 -0
- package/plugins/core/default/config.js +220 -0
- package/plugins/core/default/index.js +58 -0
- package/plugins/core/mcp/index.js +1 -0
- package/plugins/{python-plugin-loader.js → core/python-loader/index.js} +7 -187
- package/plugins/{rules-plugin.js → core/rules/index.js} +121 -64
- package/plugins/{scheduler-plugin.js → core/scheduler/index.js} +12 -114
- package/plugins/{session-plugin.js → core/session/index.js} +9 -73
- package/{src/capabilities/skill-manager.js → plugins/core/skill-manager/index.js} +64 -18
- package/plugins/{storage-plugin.js → core/storage/index.js} +5 -29
- package/plugins/{subagent-plugin.js → core/sub-agent/index.js} +10 -171
- package/plugins/{think-plugin.js → core/think/index.js} +24 -91
- package/{src/capabilities/workflow-engine.js → plugins/core/workflow/index.js} +87 -85
- package/plugins/default-plugins.js +6 -720
- package/plugins/{data-splitter-plugin.js → executors/data-splitter/index.js} +9 -83
- package/plugins/{extension-executor-plugin.js → executors/extension/index.js} +13 -97
- package/plugins/{python-executor-plugin.js → executors/python/index.js} +6 -31
- package/plugins/{shell-executor-plugin.js → executors/shell/index.js} +2 -5
- package/plugins/install/README.md +9 -0
- package/plugins/{install-plugin.js → install/index.js} +3 -3
- package/plugins/{file-system-plugin.js → io/file-system/index.js} +34 -236
- package/plugins/{web-plugin.js → io/web/index.js} +11 -113
- package/plugins/memory/README.md +13 -0
- package/plugins/{memory-plugin.js → memory/index.js} +4 -18
- package/plugins/messaging/email/README.md +19 -0
- package/plugins/{email → messaging/email}/index.js +2 -2
- package/plugins/{feishu-plugin.js → messaging/feishu/index.js} +3 -3
- package/plugins/{qq-plugin.js → messaging/qq/index.js} +5 -16
- package/plugins/{telegram-plugin.js → messaging/telegram/index.js} +3 -3
- package/plugins/{weixin-plugin.js → messaging/weixin/index.js} +15 -15
- package/plugins/{plugin-manager-plugin.js → plugin-manager/index.js} +36 -180
- package/plugins/{tools-plugin.js → tools/index.js} +68 -116
- package/plugins/trading/README.md +15 -0
- package/plugins/{gate-trading.js → trading/index.js} +8 -8
- package/{examples → sandbox}/test-concurrent-chat.js +2 -2
- package/{examples → sandbox}/test-long-chat.js +2 -2
- package/{examples → sandbox}/test-session-chat.js +2 -2
- package/{examples → sandbox}/test-web-plugin.js +1 -1
- package/{examples → sandbox}/test-weixin-feishu.js +2 -2
- package/src/agent/base.js +56 -0
- package/src/{core/agent-chat.js → agent/chat.js} +11 -11
- package/src/{core/coordinator-manager.js → agent/coordinator.js} +3 -3
- package/src/agent/index.js +111 -0
- package/src/agent/main.js +337 -0
- package/src/agent/prompt.js +78 -0
- package/src/agent/sub.js +198 -0
- package/src/agent/worker.js +104 -0
- package/{cli/bin/foliko.js → src/cli/bin.js} +1 -1
- package/{cli/src → src/cli}/commands/chat.js +25 -21
- package/{cli/src → src/cli}/index.js +1 -0
- package/{cli/src → src/cli}/ui/chat-ui-old.js +40 -178
- package/{cli/src → src/cli}/ui/chat-ui.js +3 -3
- package/{cli/src → src/cli}/ui/components/footer-bar.js +1 -1
- package/src/common/errors.js +402 -0
- package/src/{utils → common}/logger.js +33 -0
- package/src/{utils/chat-queue.js → common/queue.js} +2 -2
- package/src/config/plugin-config.js +50 -0
- package/src/context/agent.js +32 -0
- package/src/context/compaction-prompts.js +170 -0
- package/src/context/compaction-utils.js +191 -0
- package/src/context/compressor.js +413 -0
- package/src/context/index.js +9 -0
- package/src/{core/context-manager.js → context/manager.js} +1 -1
- package/src/context/request.js +50 -0
- package/src/context/session.js +33 -0
- package/src/context/storage.js +30 -0
- package/src/executors/mcp-client.js +153 -0
- package/src/executors/mcp-desc.js +236 -0
- package/src/executors/mcp-executor.js +91 -956
- package/src/{core → framework}/command-registry.js +1 -1
- package/src/framework/framework.js +300 -0
- package/src/framework/index.js +18 -0
- package/src/framework/lifecycle.js +203 -0
- package/src/framework/loader.js +78 -0
- package/src/framework/registry.js +86 -0
- package/src/{core/ui-extension-context.js → framework/ui-extension.js} +1 -1
- package/src/index.js +130 -15
- package/src/llm/index.js +26 -0
- package/src/llm/provider.js +212 -0
- package/src/llm/registry.js +11 -0
- package/src/{core/token-counter.js → llm/tokens.js} +4 -37
- package/src/{core/plugin-base.js → plugin/base.js} +10 -136
- package/src/plugin/index.js +14 -0
- package/src/plugin/loader.js +101 -0
- package/src/plugin/manager.js +261 -0
- package/src/{core → session}/branch-summary-auto.js +2 -2
- package/src/{core/chat-session.js → session/chat.js} +2 -2
- package/src/session/index.js +7 -0
- package/src/{core/session-manager.js → session/session.js} +2 -2
- package/src/session/ttl.js +92 -0
- package/src/{core/jsonl-storage.js → storage/jsonl.js} +1 -1
- package/src/tool/executor.js +85 -0
- package/src/tool/index.js +15 -0
- package/src/tool/registry.js +143 -0
- package/src/{core/tool-router.js → tool/router.js} +17 -124
- package/src/tool/schema.js +108 -0
- package/src/utils/data-splitter.js +1 -1
- package/src/utils/download.js +1 -1
- package/src/utils/index.js +6 -6
- package/src/utils/message-validator.js +1 -1
- package/tests/core/context-storage.test.js +46 -0
- package/tests/core/llm.test.js +54 -0
- package/tests/core/plugin.test.js +42 -0
- package/tests/core/tool.test.js +60 -0
- package/tests/setup.js +10 -0
- package/tests/smoke.test.js +58 -0
- package/vitest.config.js +9 -0
- package/cli/src/daemon.js +0 -149
- package/docs/CONTEXT_DESIGN.md +0 -1596
- package/docs/ai-sdk-optimization.md +0 -655
- package/docs/features.md +0 -120
- package/docs/qq-bot.md +0 -976
- package/docs/quick-reference.md +0 -160
- package/docs/user-manual.md +0 -1391
- package/images/geometric_shapes.jpg +0 -0
- package/images/sunset_mountain_lake.jpg +0 -0
- package/skills/poster-guide/SKILL.md +0 -792
- package/src/capabilities/index.js +0 -11
- package/src/core/agent.js +0 -808
- package/src/core/context-compressor.js +0 -959
- package/src/core/enhanced-context-compressor.js +0 -210
- package/src/core/framework.js +0 -1422
- package/src/core/index.js +0 -30
- package/src/core/plugin-manager.js +0 -961
- package/src/core/provider-registry.js +0 -159
- package/src/core/provider.js +0 -156
- package/src/core/request-context.js +0 -98
- package/src/core/subagent.js +0 -442
- package/src/core/system-prompt-builder.js +0 -120
- package/src/core/tool-executor.js +0 -202
- package/src/core/tool-registry.js +0 -517
- package/src/core/worker-agent.js +0 -192
- package/src/executors/executor-base.js +0 -58
- package/src/utils/error-boundary.js +0 -363
- package/src/utils/error.js +0 -374
- package/system.md +0 -1645
- package/website_v2/README.md +0 -57
- package/website_v2/SPEC.md +0 -1
- package/website_v2/docs/api.html +0 -128
- package/website_v2/docs/configuration.html +0 -147
- package/website_v2/docs/plugin-development.html +0 -129
- package/website_v2/docs/project-structure.html +0 -89
- package/website_v2/docs/skill-development.html +0 -85
- package/website_v2/index.html +0 -489
- package/website_v2/scripts/main.js +0 -93
- package/website_v2/styles/animations.css +0 -8
- package/website_v2/styles/docs.css +0 -83
- package/website_v2/styles/main.css +0 -417
- package/xhs_auth.json +0 -268
- package//346/265/267/346/212/245/346/217/222/344/273/266.md +0 -621
- /package/plugins/{ambient-agent → ambient}/constants.js +0 -0
- /package/plugins/{email → messaging/email}/constants.js +0 -0
- /package/plugins/{email → messaging/email}/handlers.js +0 -0
- /package/plugins/{email → messaging/email}/monitor.js +0 -0
- /package/plugins/{email → messaging/email}/parser.js +0 -0
- /package/plugins/{email → messaging/email}/reply.js +0 -0
- /package/plugins/{email → messaging/email}/utils.js +0 -0
- /package/{examples → sandbox}/test-chat.js +0 -0
- /package/{examples → sandbox}/test-mcp.js +0 -0
- /package/{examples → sandbox}/test-reload.js +0 -0
- /package/{examples → sandbox}/test-telegram.js +0 -0
- /package/{examples → sandbox}/test-tg-bot.js +0 -0
- /package/{examples → sandbox}/test-tg-simple.js +0 -0
- /package/{examples → sandbox}/test-tg.js +0 -0
- /package/{examples → sandbox}/test-think.js +0 -0
- /package/src/{core/sub-agent-config.js → agent/sub-config.js} +0 -0
- /package/{cli/src → src/cli}/commands/daemon.js +0 -0
- /package/{cli/src → src/cli}/commands/list.js +0 -0
- /package/{cli/src → src/cli}/commands/plugin.js +0 -0
- /package/{cli/src → src/cli}/ui/components/agent-mention-provider.js +0 -0
- /package/{cli/src → src/cli}/ui/components/chained-autocomplete-provider.js +0 -0
- /package/{cli/src → src/cli}/ui/components/message-bubble.js +0 -0
- /package/{cli/src → src/cli}/ui/components/status-bar.js +0 -0
- /package/{cli/src → src/cli}/utils/ansi.js +0 -0
- /package/{cli/src → src/cli}/utils/config.js +0 -0
- /package/{cli/src → src/cli}/utils/markdown.js +0 -0
- /package/{cli/src → src/cli}/utils/plugin-config.js +0 -0
- /package/{cli/src → src/cli}/utils/render-diff.js +0 -0
- /package/src/{utils/circuit-breaker.js → common/circuit.js} +0 -0
- /package/src/{core → common}/constants.js +0 -0
- /package/src/{utils/edit-diff.js → common/diff.js} +0 -0
- /package/src/{utils/event-emitter.js → common/events.js} +0 -0
- /package/src/{utils → common}/id.js +0 -0
- /package/src/{utils → common}/retry.js +0 -0
- /package/src/{core/notification-manager.js → notification/manager.js} +0 -0
- /package/src/{core/session-entry.js → session/entry.js} +0 -0
- /package/src/{core/storage-manager.js → storage/manager.js} +0 -0
package/src/core/worker-agent.js
DELETED
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* WorkerAgent - 独立子Agent
|
|
3
|
-
* 用于Coordinator模式下的Worker,基于Subagent轻量级实现
|
|
4
|
-
* 任务完成后通过事件通知Coordinator
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
const { Subagent } = require('./subagent');
|
|
8
|
-
const { EventEmitter } = require('../utils/event-emitter');
|
|
9
|
-
|
|
10
|
-
class WorkerAgent extends EventEmitter {
|
|
11
|
-
/**
|
|
12
|
-
* @param {Framework} framework - 框架实例
|
|
13
|
-
* @param {Object} config - 配置
|
|
14
|
-
* @param {string} config.workerId - Worker唯一ID
|
|
15
|
-
* @param {string} [config.coordinatorId] - Coordinator的agentId
|
|
16
|
-
* @param {string} [config.name] - Worker名称
|
|
17
|
-
* @param {string} [config.role] - 角色描述
|
|
18
|
-
* @param {string} [config.description] - 描述
|
|
19
|
-
* @param {string} [config.systemPrompt] - 系统提示
|
|
20
|
-
* @param {string[]} [config.tools] - 可用工具名称列表
|
|
21
|
-
* @param {string[]} [config.parentTools] - 从父Agent继承的工具名称列表
|
|
22
|
-
*/
|
|
23
|
-
constructor(framework, config) {
|
|
24
|
-
super();
|
|
25
|
-
|
|
26
|
-
this.framework = framework;
|
|
27
|
-
this.workerId = config.workerId;
|
|
28
|
-
this.coordinatorId = config.coordinatorId;
|
|
29
|
-
this._status = 'idle'; // idle, running, completed, error, stopped
|
|
30
|
-
this._task = config.task || '';
|
|
31
|
-
|
|
32
|
-
// 获取AI配置
|
|
33
|
-
const aiPlugin = framework.pluginManager?.get('ai');
|
|
34
|
-
const aiConfig = aiPlugin ? aiPlugin.getConfig() : {};
|
|
35
|
-
const mergedAIConfig = { ...aiConfig, ...config.llmConfig };
|
|
36
|
-
|
|
37
|
-
// 构建工具列表
|
|
38
|
-
const toolList = [];
|
|
39
|
-
if (config.tools) {
|
|
40
|
-
const allTools = framework.getTools();
|
|
41
|
-
const allowedTools = new Set(config.tools);
|
|
42
|
-
for (const toolName of allowedTools) {
|
|
43
|
-
const toolDef = allTools.find((t) => t.name === toolName);
|
|
44
|
-
if (toolDef) {
|
|
45
|
-
toolList.push(toolDef);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// 创建轻量子Agent
|
|
51
|
-
this._subagent = new Subagent({
|
|
52
|
-
name: config.name || `worker_${this.workerId}`,
|
|
53
|
-
role: config.role || 'Worker',
|
|
54
|
-
description: config.description || '',
|
|
55
|
-
systemPrompt: config.systemPrompt || WorkerAgent.defaultPrompt(),
|
|
56
|
-
model: config.model || mergedAIConfig.model || 'deepseek-chat',
|
|
57
|
-
provider: config.provider || mergedAIConfig.provider || 'deepseek',
|
|
58
|
-
apiKey: config.apiKey || mergedAIConfig.apiKey,
|
|
59
|
-
baseURL: config.baseURL || mergedAIConfig.baseURL,
|
|
60
|
-
tools: toolList,
|
|
61
|
-
// parentTools: config.parentTools || [],
|
|
62
|
-
framework: framework,
|
|
63
|
-
maxRetries: config.maxRetries ?? 2,
|
|
64
|
-
disableTools: config.disableTools ?? false,
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
// 转发Subagent事件
|
|
68
|
-
this._subagent.on('chunk', (chunk) => this.emit('chunk', chunk));
|
|
69
|
-
this._subagent.on('complete', (data) => {
|
|
70
|
-
this._status = 'completed';
|
|
71
|
-
this.emit('complete', data);
|
|
72
|
-
});
|
|
73
|
-
this._subagent.on('error', (data) => {
|
|
74
|
-
this._status = 'error';
|
|
75
|
-
this.emit('error', data);
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* 获取Worker状态
|
|
81
|
-
*/
|
|
82
|
-
getStatus() {
|
|
83
|
-
return this._status;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* 设置状态
|
|
88
|
-
*/
|
|
89
|
-
setStatus(status) {
|
|
90
|
-
this._status = status;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* 获取内部Subagent实例
|
|
95
|
-
*/
|
|
96
|
-
getSubagent() {
|
|
97
|
-
return this._subagent;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* 执行初始任务
|
|
102
|
-
* @param {string} task - 任务描述
|
|
103
|
-
* @param {Object} [options] - 选项
|
|
104
|
-
* @returns {Promise<Object>} 任务结果
|
|
105
|
-
*/
|
|
106
|
-
async runTask(task, options) {
|
|
107
|
-
this._task = task;
|
|
108
|
-
this._status = 'running';
|
|
109
|
-
|
|
110
|
-
try {
|
|
111
|
-
const result = await this._subagent.chat(task, options);
|
|
112
|
-
if (!result.success) {
|
|
113
|
-
this._status = 'error';
|
|
114
|
-
}
|
|
115
|
-
return result;
|
|
116
|
-
} catch (err) {
|
|
117
|
-
this._status = 'error';
|
|
118
|
-
throw err;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* 发送消息继续Worker
|
|
124
|
-
* @param {string} message - 继续消息
|
|
125
|
-
* @param {Object} [options] - 选项
|
|
126
|
-
* @returns {Promise<Object>} 处理结果
|
|
127
|
-
*/
|
|
128
|
-
async sendMessage(message, options) {
|
|
129
|
-
if (this._status === 'stopped') {
|
|
130
|
-
throw new Error(`Worker ${this.workerId} has been stopped`);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
this._status = 'running';
|
|
134
|
-
try {
|
|
135
|
-
const result = await this._subagent.chat(message, options);
|
|
136
|
-
return result;
|
|
137
|
-
} catch (err) {
|
|
138
|
-
this._status = 'error';
|
|
139
|
-
throw err;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* 停止Worker
|
|
145
|
-
*/
|
|
146
|
-
stop() {
|
|
147
|
-
this._status = 'stopped';
|
|
148
|
-
this._subagent.destroy();
|
|
149
|
-
this.emit('stopped', { workerId: this.workerId });
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* 生成<task-notification> JSON
|
|
154
|
-
* @param {string} status - completed, error, stopped
|
|
155
|
-
* @param {string} result - 任务结果
|
|
156
|
-
* @param {string} [error] - 错误信息
|
|
157
|
-
* @returns {string} JSON字符串
|
|
158
|
-
*/
|
|
159
|
-
static formatNotification(workerId, status, result, error = null) {
|
|
160
|
-
const notification = {
|
|
161
|
-
worker_id: workerId,
|
|
162
|
-
status: status,
|
|
163
|
-
timestamp: new Date().toISOString(),
|
|
164
|
-
};
|
|
165
|
-
|
|
166
|
-
if (error) {
|
|
167
|
-
notification.error = error;
|
|
168
|
-
} else if (result) {
|
|
169
|
-
notification.result = result;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
return JSON.stringify(notification);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* 默认系统提示
|
|
177
|
-
*/
|
|
178
|
-
static defaultPrompt() {
|
|
179
|
-
return `你是一个独立的Worker Agent。
|
|
180
|
-
你的职责:
|
|
181
|
-
1. 接收并理解Coordinator分配的任务
|
|
182
|
-
2. 使用你的工具集完成任务
|
|
183
|
-
3. 返回完整的任务结果
|
|
184
|
-
|
|
185
|
-
重要规则:
|
|
186
|
-
- 任务完成或出错时,在响应末尾添加JSON格式的<task-notification>说明状态
|
|
187
|
-
- 不要主动联系Coordinator,由Coordinator主动查询结果
|
|
188
|
-
- 如果需要更多信息,等待Coordinator发送continue消息`;
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
module.exports = { WorkerAgent };
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Executor 基类
|
|
3
|
-
* 执行器的基类,定义执行器接口
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
const { EventEmitter } = require('../utils/event-emitter');
|
|
7
|
-
|
|
8
|
-
class ExecutorBase extends EventEmitter {
|
|
9
|
-
/**
|
|
10
|
-
* @param {string} name - 执行器名称
|
|
11
|
-
*/
|
|
12
|
-
constructor(name) {
|
|
13
|
-
super();
|
|
14
|
-
this.name = name;
|
|
15
|
-
this._enabled = true;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* 执行
|
|
20
|
-
* @param {Object} params - 执行参数
|
|
21
|
-
* @returns {Promise<any>}
|
|
22
|
-
*/
|
|
23
|
-
async execute(params) {
|
|
24
|
-
throw new Error('execute() must be implemented');
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* 启用执行器
|
|
29
|
-
*/
|
|
30
|
-
enable() {
|
|
31
|
-
this._enabled = true;
|
|
32
|
-
return this;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* 禁用执行器
|
|
37
|
-
*/
|
|
38
|
-
disable() {
|
|
39
|
-
this._enabled = false;
|
|
40
|
-
return this;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* 是否启用
|
|
45
|
-
*/
|
|
46
|
-
isEnabled() {
|
|
47
|
-
return this._enabled;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* 销毁
|
|
52
|
-
*/
|
|
53
|
-
destroy() {
|
|
54
|
-
this.removeAllListeners();
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
module.exports = { ExecutorBase };
|
|
@@ -1,363 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Foliko Error Boundary - 错误边界系统
|
|
3
|
-
* 捕获、处理和恢复错误,提供降级方案
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
const { EventEmitter } = require('./event-emitter');
|
|
7
|
-
const { logger } = require('./logger');
|
|
8
|
-
const { safeErrorInfo, isErrorOfType } = require('./error');
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* 错误严重级别
|
|
12
|
-
*/
|
|
13
|
-
const Severity = {
|
|
14
|
-
LOW: 'low', // 可忽略的小问题
|
|
15
|
-
MEDIUM: 'medium', // 需要关注但不阻断流程
|
|
16
|
-
HIGH: 'high', // 阻断当前操作但可恢复
|
|
17
|
-
CRITICAL: 'critical', // 致命错误,需要完全降级
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* 错误恢复动作
|
|
22
|
-
*/
|
|
23
|
-
const RecoveryAction = {
|
|
24
|
-
RETRY: 'retry', // 重试操作
|
|
25
|
-
SKIP: 'skip', // 跳过当前步骤
|
|
26
|
-
FALLBACK: 'fallback', // 使用降级方案
|
|
27
|
-
ABORT: 'abort', // 中止流程
|
|
28
|
-
IGNORE: 'ignore', // 忽略错误继续
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* 错误上下文
|
|
33
|
-
* @typedef {Object} ErrorContext
|
|
34
|
-
* @property {string} operation - 操作名称
|
|
35
|
-
* @property {string} component - 组件名称
|
|
36
|
-
* @property {Object} metadata - 额外元数据
|
|
37
|
-
* @property {number} attempt - 当前尝试次数
|
|
38
|
-
*/
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* 错误边界配置
|
|
42
|
-
* @typedef {Object} ErrorBoundaryConfig
|
|
43
|
-
* @property {string} name - 边界名称
|
|
44
|
-
* @property {Function} [onError] - 全局错误处理器
|
|
45
|
-
* @property {Function} [onRecovery] - 恢复处理器
|
|
46
|
-
* @property {Function} [fallback] - 降级函数
|
|
47
|
-
* @property {boolean} [logErrors=true] - 是否记录错误
|
|
48
|
-
* @property {boolean} [propagateErrors=false] - 是否向上传播错误
|
|
49
|
-
*/
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* 错误边界类
|
|
53
|
-
* 用于捕获和管理错误,提供恢复机制
|
|
54
|
-
*/
|
|
55
|
-
class ErrorBoundary extends EventEmitter {
|
|
56
|
-
/**
|
|
57
|
-
* @param {ErrorBoundaryConfig} config
|
|
58
|
-
*/
|
|
59
|
-
constructor(config = {}) {
|
|
60
|
-
super();
|
|
61
|
-
|
|
62
|
-
this.name = config.name || 'AnonymousBoundary';
|
|
63
|
-
this._onError = config.onError || null;
|
|
64
|
-
this._onRecovery = config.onRecovery || null;
|
|
65
|
-
this._fallback = config.fallback || null;
|
|
66
|
-
this._logErrors = config.logErrors !== false;
|
|
67
|
-
this._propagateErrors = config.propagateErrors || false;
|
|
68
|
-
this._logger = logger.child('ErrorBoundary');
|
|
69
|
-
|
|
70
|
-
// 错误统计
|
|
71
|
-
this._errorCount = 0;
|
|
72
|
-
this._lastError = null;
|
|
73
|
-
this._errorHistory = [];
|
|
74
|
-
this._maxHistorySize = config.maxHistorySize || 50;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* 执行可能抛出错误的操作
|
|
79
|
-
* @param {Function} operation - 要执行的操作
|
|
80
|
-
* @param {Object} [context] - 错误上下文
|
|
81
|
-
* @returns {Promise<{success: boolean, result?: any, error?: Error, recovered?: boolean}>}
|
|
82
|
-
*/
|
|
83
|
-
async execute(operation, context = {}) {
|
|
84
|
-
const operationName = context.operation || 'anonymous';
|
|
85
|
-
|
|
86
|
-
try {
|
|
87
|
-
const result = await (typeof operation === 'function' ? operation() : operation);
|
|
88
|
-
return { success: true, result };
|
|
89
|
-
} catch (error) {
|
|
90
|
-
this._errorCount++;
|
|
91
|
-
this._lastError = error;
|
|
92
|
-
|
|
93
|
-
// 记录到历史
|
|
94
|
-
this._addToHistory(error, context);
|
|
95
|
-
|
|
96
|
-
// 记录错误日志
|
|
97
|
-
if (this._logErrors) {
|
|
98
|
-
this._logError(error, context);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// 触发错误事件
|
|
102
|
-
this.emit('error', {
|
|
103
|
-
error,
|
|
104
|
-
context,
|
|
105
|
-
boundary: this.name,
|
|
106
|
-
});
|
|
107
|
-
|
|
108
|
-
// 调用全局错误处理器
|
|
109
|
-
let recoveryAction = RecoveryAction.ABORT;
|
|
110
|
-
if (this._onError) {
|
|
111
|
-
try {
|
|
112
|
-
// 使用 Promise.resolve 以支持 async 函数
|
|
113
|
-
recoveryAction = await Promise.resolve(this._onError(error, context, this));
|
|
114
|
-
} catch (handlerError) {
|
|
115
|
-
this._logger.warn(`Error in onError handler: ${handlerError.message}`);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// 根据恢复动作处理
|
|
120
|
-
const { action, fallbackResult } = await this._handleRecovery(error, context, recoveryAction);
|
|
121
|
-
|
|
122
|
-
// 触发恢复事件
|
|
123
|
-
if (action !== RecoveryAction.ABORT) {
|
|
124
|
-
this.emit('recovery', {
|
|
125
|
-
error,
|
|
126
|
-
context,
|
|
127
|
-
action,
|
|
128
|
-
boundary: this.name,
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
if (this._onRecovery) {
|
|
132
|
-
try {
|
|
133
|
-
await this._onRecovery(error, context, action, this);
|
|
134
|
-
} catch (recoveryError) {
|
|
135
|
-
log.warn(`Error in onRecovery handler: ${recoveryError.message}`);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// 如果需要传播错误,或者没有降级方案且要求传播,则抛出错误
|
|
141
|
-
if (this._propagateErrors || (action === RecoveryAction.ABORT && !fallbackResult)) {
|
|
142
|
-
throw error;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
return {
|
|
146
|
-
success: false,
|
|
147
|
-
error,
|
|
148
|
-
recovered: action !== RecoveryAction.ABORT,
|
|
149
|
-
fallbackResult,
|
|
150
|
-
action,
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* 执行带重试的操作
|
|
157
|
-
* @param {Function} operation - 要执行的操作
|
|
158
|
-
* @param {Object} retryConfig - 重试配置
|
|
159
|
-
* @param {Object} [context] - 错误上下文
|
|
160
|
-
* @returns {Promise<any>}
|
|
161
|
-
*/
|
|
162
|
-
async executeWithRetry(operation, retryConfig = {}, context = {}) {
|
|
163
|
-
const { maxAttempts = 3, baseDelay = 1000, shouldRetry = () => true } = retryConfig;
|
|
164
|
-
|
|
165
|
-
let lastError;
|
|
166
|
-
|
|
167
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
168
|
-
try {
|
|
169
|
-
return await this.execute(operation, { ...context, attempt });
|
|
170
|
-
} catch (error) {
|
|
171
|
-
lastError = error;
|
|
172
|
-
|
|
173
|
-
if (attempt >= maxAttempts || !shouldRetry(error, attempt)) {
|
|
174
|
-
throw error;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// 计算延迟
|
|
178
|
-
const delay = baseDelay * Math.pow(2, attempt - 1);
|
|
179
|
-
log.debug(`Retry attempt ${attempt}/${maxAttempts} after ${delay}ms...`);
|
|
180
|
-
|
|
181
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
throw lastError;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
* 包装一个函数,使其错误被边界捕获
|
|
190
|
-
* @param {Function} fn - 要包装的函数
|
|
191
|
-
* @param {Object} [defaultContext] - 默认上下文
|
|
192
|
-
* @returns {Function}
|
|
193
|
-
*/
|
|
194
|
-
wrap(fn, defaultContext = {}) {
|
|
195
|
-
return async (...args) => {
|
|
196
|
-
const result = await this.execute(() => fn(...args), defaultContext);
|
|
197
|
-
return result.success ? result.result : result.fallbackResult;
|
|
198
|
-
};
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* 处理错误恢复
|
|
203
|
-
* @private
|
|
204
|
-
*/
|
|
205
|
-
async _handleRecovery(error, context, recoveryAction) {
|
|
206
|
-
let fallbackResult = null;
|
|
207
|
-
let action = recoveryAction;
|
|
208
|
-
|
|
209
|
-
switch (recoveryAction) {
|
|
210
|
-
case RecoveryAction.FALLBACK:
|
|
211
|
-
if (this._fallback) {
|
|
212
|
-
try {
|
|
213
|
-
fallbackResult = await this._fallback(error, context, this);
|
|
214
|
-
action = RecoveryAction.RETRY; // fallback 成功后视为恢复
|
|
215
|
-
} catch (fallbackError) {
|
|
216
|
-
log.warn(`Fallback also failed: ${fallbackError.message}`);
|
|
217
|
-
action = RecoveryAction.ABORT;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
break;
|
|
221
|
-
|
|
222
|
-
case RecoveryAction.SKIP:
|
|
223
|
-
log.debug(`Skipping operation: ${context.operation}`);
|
|
224
|
-
fallbackResult = null;
|
|
225
|
-
break;
|
|
226
|
-
|
|
227
|
-
case RecoveryAction.IGNORE:
|
|
228
|
-
log.debug(`Ignoring error: ${error.message}`);
|
|
229
|
-
fallbackResult = undefined;
|
|
230
|
-
break;
|
|
231
|
-
|
|
232
|
-
default:
|
|
233
|
-
action = RecoveryAction.ABORT;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
return { action, fallbackResult };
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* 记录错误
|
|
241
|
-
* @private
|
|
242
|
-
*/
|
|
243
|
-
_logError(error, context) {
|
|
244
|
-
if (!this._logErrors) return;
|
|
245
|
-
|
|
246
|
-
const errorInfo = safeErrorInfo(error);
|
|
247
|
-
const severity = this._determineSeverity(error);
|
|
248
|
-
|
|
249
|
-
const logMessage = `[${this.name}] Error in ${context.operation || 'unknown'}: ${error.message}`;
|
|
250
|
-
|
|
251
|
-
switch (severity) {
|
|
252
|
-
case Severity.LOW:
|
|
253
|
-
this._logger.debug(logMessage);
|
|
254
|
-
break;
|
|
255
|
-
case Severity.MEDIUM:
|
|
256
|
-
this._logger.warn(logMessage);
|
|
257
|
-
break;
|
|
258
|
-
case Severity.HIGH:
|
|
259
|
-
this._logger.error(logMessage);
|
|
260
|
-
break;
|
|
261
|
-
case Severity.CRITICAL:
|
|
262
|
-
this._logger.error(`CRITICAL: ${logMessage}`, { stack: error.stack });
|
|
263
|
-
break;
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* 确定错误严重级别
|
|
269
|
-
* @private
|
|
270
|
-
*/
|
|
271
|
-
_determineSeverity(error) {
|
|
272
|
-
if (isErrorOfType(error, require('./error').FolikoError)) {
|
|
273
|
-
return error.context?.severity || Severity.MEDIUM;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// 根据错误类型和消息判断
|
|
277
|
-
const message = (error.message || '').toLowerCase();
|
|
278
|
-
|
|
279
|
-
if (message.includes('timeout') || message.includes('network')) {
|
|
280
|
-
return Severity.MEDIUM;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
if (message.includes('memory') || message.includes('fatal')) {
|
|
284
|
-
return Severity.CRITICAL;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
return Severity.HIGH;
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
/**
|
|
291
|
-
* 添加错误到历史记录
|
|
292
|
-
* @private
|
|
293
|
-
*/
|
|
294
|
-
_addToHistory(error, context) {
|
|
295
|
-
this._errorHistory.push({
|
|
296
|
-
timestamp: new Date().toISOString(),
|
|
297
|
-
error: safeErrorInfo(error),
|
|
298
|
-
context,
|
|
299
|
-
});
|
|
300
|
-
|
|
301
|
-
// 保持历史记录大小
|
|
302
|
-
if (this._errorHistory.length > this._maxHistorySize) {
|
|
303
|
-
this._errorHistory.shift();
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* 获取错误统计
|
|
309
|
-
* @returns {Object}
|
|
310
|
-
*/
|
|
311
|
-
getStats() {
|
|
312
|
-
return {
|
|
313
|
-
totalErrors: this._errorCount,
|
|
314
|
-
lastError: this._lastError ? safeErrorInfo(this._lastError) : null,
|
|
315
|
-
historySize: this._errorHistory.length,
|
|
316
|
-
recentErrors: this._errorHistory.slice(-10),
|
|
317
|
-
};
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
/**
|
|
321
|
-
* 清空错误历史
|
|
322
|
-
*/
|
|
323
|
-
clearHistory() {
|
|
324
|
-
this._errorHistory = [];
|
|
325
|
-
this._lastError = null;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
/**
|
|
330
|
-
* 创建错误边界实例的工厂函数
|
|
331
|
-
* @param {ErrorBoundaryConfig} config
|
|
332
|
-
* @returns {ErrorBoundary}
|
|
333
|
-
*/
|
|
334
|
-
function createErrorBoundary(config = {}) {
|
|
335
|
-
return new ErrorBoundary(config);
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
/**
|
|
339
|
-
* 组合多个错误边界
|
|
340
|
-
* @param {ErrorBoundary[]} boundaries
|
|
341
|
-
* @returns {ErrorBoundary}
|
|
342
|
-
*/
|
|
343
|
-
function combineBoundaries(boundaries) {
|
|
344
|
-
const combined = new ErrorBoundary({
|
|
345
|
-
name: 'CombinedBoundary',
|
|
346
|
-
});
|
|
347
|
-
|
|
348
|
-
// 将错误传播到所有子边界
|
|
349
|
-
for (const boundary of boundaries) {
|
|
350
|
-
boundary.on('error', (data) => combined.emit('error', data));
|
|
351
|
-
boundary.on('recovery', (data) => combined.emit('recovery', data));
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
return combined;
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
module.exports = {
|
|
358
|
-
ErrorBoundary,
|
|
359
|
-
Severity,
|
|
360
|
-
RecoveryAction,
|
|
361
|
-
createErrorBoundary,
|
|
362
|
-
combineBoundaries,
|
|
363
|
-
};
|