my-ai-chat-framework 1.1.0 → 2.7.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/README.md +218 -406
- package/dist/my-ai-chat-framework.browser.es.js +1284 -2904
- package/dist/my-ai-chat-framework.browser.es.js.map +1 -1
- package/dist/my-ai-chat-framework.browser.umd.js +1310 -2917
- package/dist/my-ai-chat-framework.browser.umd.js.map +1 -1
- package/dist/my-ai-chat-framework.node.cjs.js +1296 -1654
- package/dist/my-ai-chat-framework.node.cjs.js.map +1 -1
- package/package.json +18 -35
- package/src/adapters/openai.js +280 -0
- package/src/core/ChatService.js +298 -0
- package/src/core/Errors.js +60 -0
- package/src/core/EventEmitter.js +51 -126
- package/src/core/MessageStore.js +112 -0
- package/src/core/SystemPromptStore.js +118 -0
- package/src/index.js +11 -540
- package/src/plugins/model-registry.js +187 -0
- package/src/plugins/tool-calling.js +213 -0
- package/src/utils/MessageFormatter.js +204 -0
- package/src/utils/typeCheck.js +12 -0
- package/src/utils/url.js +18 -0
- package/README_ZH.md +0 -545
- package/src/config/defaults.js +0 -25
- package/src/core/ApiClient.js +0 -316
- package/src/core/ConfigManager.js +0 -173
- package/src/core/MessageFormatter.js +0 -136
- package/src/core/Messages.js +0 -589
- package/src/core/RequestBuilder.js +0 -99
- package/src/core/ToolManager.js +0 -175
- package/src/utils/index.js +0 -21
|
@@ -1,2914 +1,1294 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
throw new Error("[系统提示异常] 检测到无效的参数格式");
|
|
45
|
-
}
|
|
46
|
-
const parameters = {};
|
|
47
|
-
for (let i = 0; i < paramsArray.length; i++) {
|
|
48
|
-
const param = paramsArray[i];
|
|
49
|
-
if (!param?.name?.trim()) {
|
|
50
|
-
throw new Error(`[系统提示异常] 检测到空参数名称 位置: 第 ${i + 1} 个参数`);
|
|
51
|
-
}
|
|
52
|
-
if (!param?.type?.trim()) {
|
|
53
|
-
throw new Error(`[系统提示异常] 检测到空参数类型 位置: 参数 "${param.name}"`);
|
|
54
|
-
}
|
|
55
|
-
if (!param?.description?.trim()) {
|
|
56
|
-
throw new Error(`[系统提示异常] 检测到空参数描述 位置: 参数 "${param.name}"`);
|
|
57
|
-
}
|
|
58
|
-
parameters[param.name] = {
|
|
59
|
-
type: param.type,
|
|
60
|
-
description: param.description
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
return {
|
|
64
|
-
type: "object",
|
|
65
|
-
properties: parameters,
|
|
66
|
-
required: Object.keys(parameters)
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* 构造工具定义
|
|
71
|
-
*/
|
|
72
|
-
static constructTool({ name, description, parameters }) {
|
|
73
|
-
if (!name?.trim()) {
|
|
74
|
-
throw new Error("[系统提示异常] 检测到空工具名称");
|
|
75
|
-
}
|
|
76
|
-
if (!description?.trim()) {
|
|
77
|
-
throw new Error("[系统提示异常] 检测到空工具描述");
|
|
78
|
-
}
|
|
79
|
-
let processedParameters;
|
|
80
|
-
try {
|
|
81
|
-
processedParameters = this.constructParameters(parameters);
|
|
82
|
-
} catch (error) {
|
|
83
|
-
throw new Error(`[系统提示异常] 工具参数验证失败 工具名称: ${name} 错误详情: ${error.message}`);
|
|
84
|
-
}
|
|
85
|
-
return {
|
|
86
|
-
type: "function",
|
|
87
|
-
function: {
|
|
88
|
-
name,
|
|
89
|
-
description,
|
|
90
|
-
parameters: processedParameters
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* 过滤消息以供API使用(只移除空content的消息,保留所有字段)
|
|
96
|
-
*/
|
|
97
|
-
static filterForAPI(messages) {
|
|
98
|
-
return messages.filter((msg) => {
|
|
99
|
-
if (msg.role === "tool") {
|
|
100
|
-
return true;
|
|
101
|
-
}
|
|
102
|
-
return msg.content !== "" && msg.content !== void 0 && msg.content !== null;
|
|
103
|
-
});
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
class Messages {
|
|
107
|
-
constructor() {
|
|
108
|
-
this.messages = [];
|
|
109
|
-
this.systemPrompts = [];
|
|
110
|
-
this.tools = [];
|
|
111
|
-
this.metadata = {
|
|
112
|
-
name: "",
|
|
113
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
114
|
-
lastModified: /* @__PURE__ */ new Date()
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
// ========== 核心消息方法 ==========
|
|
118
|
-
/**
|
|
119
|
-
* 添加消息(通用方法)
|
|
120
|
-
* @param {string} role - 角色:user/assistant/system/tool
|
|
121
|
-
* @param {string} content - 消息内容(允许空字符串)
|
|
122
|
-
* @param {object} metadata - 额外元数据
|
|
123
|
-
* @returns {number} 新消息的索引
|
|
124
|
-
*/
|
|
125
|
-
addMessage(role, content, metadata = {}) {
|
|
126
|
-
const validRoles = ["user", "assistant", "system", "tool"];
|
|
127
|
-
if (!validRoles.includes(role)) {
|
|
128
|
-
throw new Error(`无效的角色: ${role},有效值: ${validRoles.join(", ")}`);
|
|
129
|
-
}
|
|
130
|
-
if (role === "tool") {
|
|
131
|
-
if (!metadata.tool_call_id) {
|
|
132
|
-
throw new Error("tool消息必须包含tool_call_id");
|
|
133
|
-
}
|
|
134
|
-
} else {
|
|
135
|
-
if (content === void 0 || content === null) {
|
|
136
|
-
throw new Error("消息内容不能为undefined或null");
|
|
137
|
-
}
|
|
138
|
-
if (typeof content !== "string") {
|
|
139
|
-
throw new Error("消息内容必须是字符串");
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
const message = {
|
|
143
|
-
role,
|
|
144
|
-
content: content ? content.trim() : "",
|
|
145
|
-
// 允许空字符串
|
|
146
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
147
|
-
};
|
|
148
|
-
if (metadata && typeof metadata === "object") {
|
|
149
|
-
for (const [key, value] of Object.entries(metadata)) {
|
|
150
|
-
if (value !== void 0 && value !== null) {
|
|
151
|
-
message[key] = value;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return this.messages.push(message) - 1;
|
|
156
|
-
}
|
|
157
|
-
/**
|
|
158
|
-
* 添加用户消息(便捷方法)
|
|
159
|
-
*/
|
|
160
|
-
addUserMessage(content, metadata = {}) {
|
|
161
|
-
return this.addMessage("user", content, metadata);
|
|
162
|
-
}
|
|
163
|
-
/**
|
|
164
|
-
* 添加助手消息(便捷方法)
|
|
165
|
-
*/
|
|
166
|
-
addAssistantMessage(content, metadata = {}) {
|
|
167
|
-
return this.addMessage("assistant", content, metadata);
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* 添加系统消息(便捷方法)
|
|
171
|
-
*/
|
|
172
|
-
addSystemMessage(content, metadata = {}) {
|
|
173
|
-
return this.addMessage("system", content, metadata);
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* 添加工具消息(便捷方法)
|
|
177
|
-
*/
|
|
178
|
-
addToolMessage(content, toolCallId, metadata = {}) {
|
|
179
|
-
if (!toolCallId || typeof toolCallId !== "string") {
|
|
180
|
-
throw new Error("tool_call_id不能为空");
|
|
181
|
-
}
|
|
182
|
-
return this.addMessage("tool", content, {
|
|
183
|
-
tool_call_id: toolCallId,
|
|
184
|
-
...metadata
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* 批量添加消息
|
|
189
|
-
*/
|
|
190
|
-
addMessages(messagesArray) {
|
|
191
|
-
if (!Array.isArray(messagesArray)) {
|
|
192
|
-
throw new Error("参数必须是数组");
|
|
193
|
-
}
|
|
194
|
-
const indices = [];
|
|
195
|
-
for (const msg of messagesArray) {
|
|
196
|
-
if (!msg.role || !msg.content) {
|
|
197
|
-
throw new Error("消息必须包含role和content属性");
|
|
198
|
-
}
|
|
199
|
-
const { role, content, ...metadata } = msg;
|
|
200
|
-
const index2 = this.addMessage(role, content, metadata);
|
|
201
|
-
indices.push(index2);
|
|
202
|
-
}
|
|
203
|
-
return indices;
|
|
204
|
-
}
|
|
205
|
-
// ========== 消息查询 ==========
|
|
206
|
-
/**
|
|
207
|
-
* 获取所有消息
|
|
208
|
-
*/
|
|
209
|
-
getMessages() {
|
|
210
|
-
return [...this.messages];
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* 按角色获取消息
|
|
214
|
-
*/
|
|
215
|
-
getMessagesByRole(role) {
|
|
216
|
-
const validRoles = ["user", "assistant", "system", "tool"];
|
|
217
|
-
if (!validRoles.includes(role)) {
|
|
218
|
-
throw new Error(`无效的角色: ${role}`);
|
|
219
|
-
}
|
|
220
|
-
return this.messages.filter((msg) => msg.role === role);
|
|
221
|
-
}
|
|
222
|
-
/**
|
|
223
|
-
* 获取最后一条消息
|
|
224
|
-
*/
|
|
225
|
-
getLastMessage() {
|
|
226
|
-
return this.messages.length > 0 ? { ...this.messages[this.messages.length - 1] } : null;
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* 获取最后一条用户消息
|
|
230
|
-
*/
|
|
231
|
-
getLastUserMessage() {
|
|
232
|
-
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
233
|
-
if (this.messages[i].role === "user") {
|
|
234
|
-
return { ...this.messages[i] };
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
return null;
|
|
238
|
-
}
|
|
239
|
-
/**
|
|
240
|
-
* 获取最后一条助手消息
|
|
241
|
-
*/
|
|
242
|
-
getLastAssistantMessage() {
|
|
243
|
-
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
244
|
-
if (this.messages[i].role === "assistant") {
|
|
245
|
-
return { ...this.messages[i] };
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
return null;
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* 获取消息数量
|
|
252
|
-
*/
|
|
253
|
-
getMessageCount() {
|
|
254
|
-
return this.messages.length;
|
|
255
|
-
}
|
|
256
|
-
// ========== 消息修改 ==========
|
|
257
|
-
/**
|
|
258
|
-
* 更新消息内容(允许空字符串)
|
|
259
|
-
*/
|
|
260
|
-
updateMessage(index2, content) {
|
|
261
|
-
if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
|
|
262
|
-
throw new Error(`无效的消息索引: ${index2}`);
|
|
263
|
-
}
|
|
264
|
-
if (typeof content !== "string") {
|
|
265
|
-
throw new Error("消息内容必须是字符串");
|
|
266
|
-
}
|
|
267
|
-
this.messages[index2].content = content;
|
|
268
|
-
this.messages[index2].lastModified = /* @__PURE__ */ new Date();
|
|
269
|
-
return this;
|
|
270
|
-
}
|
|
271
|
-
/**
|
|
272
|
-
* 更新最后一条消息
|
|
273
|
-
*/
|
|
274
|
-
updateLastMessage(content) {
|
|
275
|
-
if (this.messages.length === 0) {
|
|
276
|
-
throw new Error("没有消息可以修改");
|
|
277
|
-
}
|
|
278
|
-
return this.updateMessage(this.messages.length - 1, content);
|
|
279
|
-
}
|
|
280
|
-
/**
|
|
281
|
-
* 设置消息字段
|
|
282
|
-
*/
|
|
283
|
-
setMessageField(index2, field, value) {
|
|
284
|
-
if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
|
|
285
|
-
throw new Error(`无效的消息索引: ${index2}`);
|
|
286
|
-
}
|
|
287
|
-
this.messages[index2][field] = value;
|
|
288
|
-
this.messages[index2].lastModified = /* @__PURE__ */ new Date();
|
|
289
|
-
return this;
|
|
290
|
-
}
|
|
291
|
-
/**
|
|
292
|
-
* 批量设置消息字段
|
|
293
|
-
*/
|
|
294
|
-
setMessageFields(index2, fields) {
|
|
295
|
-
if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
|
|
296
|
-
throw new Error(`无效的消息索引: ${index2}`);
|
|
297
|
-
}
|
|
298
|
-
for (const [field, value] of Object.entries(fields)) {
|
|
299
|
-
if (value !== void 0 && value !== null) {
|
|
300
|
-
this.messages[index2][field] = value;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
this.messages[index2].lastModified = /* @__PURE__ */ new Date();
|
|
304
|
-
return this;
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* 批量更新最后一条消息的字段
|
|
308
|
-
*/
|
|
309
|
-
updateLastMessageFields(fields) {
|
|
310
|
-
if (this.messages.length === 0) {
|
|
311
|
-
throw new Error("没有消息可以修改");
|
|
312
|
-
}
|
|
313
|
-
return this.setMessageFields(this.messages.length - 1, fields);
|
|
314
|
-
}
|
|
315
|
-
// ========== 消息删除 ==========
|
|
316
|
-
/**
|
|
317
|
-
* 删除消息
|
|
318
|
-
*/
|
|
319
|
-
removeMessage(index2) {
|
|
320
|
-
if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
|
|
321
|
-
throw new Error(`无效的消息索引: ${index2}`);
|
|
322
|
-
}
|
|
323
|
-
return this.messages.splice(index2, 1)[0];
|
|
324
|
-
}
|
|
325
|
-
/**
|
|
326
|
-
* 删除最后一条消息
|
|
327
|
-
*/
|
|
328
|
-
removeLastMessage() {
|
|
329
|
-
if (this.messages.length === 0) {
|
|
330
|
-
throw new Error("没有消息可以删除");
|
|
331
|
-
}
|
|
332
|
-
return this.removeMessage(this.messages.length - 1);
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* 撤回到上一条助手消息
|
|
336
|
-
*/
|
|
337
|
-
undoToAssistant() {
|
|
338
|
-
if (this.messages.length === 0) {
|
|
339
|
-
return [];
|
|
340
|
-
}
|
|
341
|
-
let lastAssistantIndex = -1;
|
|
342
|
-
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
343
|
-
if (this.messages[i].role === "assistant") {
|
|
344
|
-
lastAssistantIndex = i;
|
|
345
|
-
break;
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
if (lastAssistantIndex >= 0) {
|
|
349
|
-
return this.messages.splice(lastAssistantIndex + 1);
|
|
350
|
-
} else {
|
|
351
|
-
const removed = [...this.messages];
|
|
352
|
-
this.messages = [];
|
|
353
|
-
return removed;
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
/**
|
|
357
|
-
* 是否可以撤回
|
|
358
|
-
*/
|
|
359
|
-
canUndo() {
|
|
360
|
-
return this.messages.some((msg) => msg.role === "assistant");
|
|
361
|
-
}
|
|
362
|
-
/**
|
|
363
|
-
* 清空所有消息
|
|
364
|
-
*/
|
|
365
|
-
clearMessages() {
|
|
366
|
-
const removed = [...this.messages];
|
|
367
|
-
this.messages = [];
|
|
368
|
-
this.metadata.lastModified = /* @__PURE__ */ new Date();
|
|
369
|
-
return removed;
|
|
370
|
-
}
|
|
371
|
-
// ========== 系统提示管理 ==========
|
|
372
|
-
/**
|
|
373
|
-
* 添加系统提示
|
|
374
|
-
*/
|
|
375
|
-
addSystemPrompt(content, enabled = true) {
|
|
376
|
-
if (typeof content !== "string" || !content.trim()) {
|
|
377
|
-
throw new Error("系统提示内容不能为空");
|
|
378
|
-
}
|
|
379
|
-
const prompt = {
|
|
380
|
-
role: "system",
|
|
381
|
-
content: content.trim(),
|
|
382
|
-
enabled: Boolean(enabled),
|
|
383
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
384
|
-
};
|
|
385
|
-
return this.systemPrompts.push(prompt) - 1;
|
|
386
|
-
}
|
|
387
|
-
/**
|
|
388
|
-
* 获取启用的系统提示
|
|
389
|
-
*/
|
|
390
|
-
getEnabledSystemPrompts() {
|
|
391
|
-
return this.systemPrompts.filter((prompt) => prompt.enabled).map((prompt) => ({ role: prompt.role, content: prompt.content }));
|
|
392
|
-
}
|
|
393
|
-
/**
|
|
394
|
-
* 切换系统提示状态
|
|
395
|
-
*/
|
|
396
|
-
toggleSystemPrompt(index2) {
|
|
397
|
-
if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
|
|
398
|
-
throw new Error(`无效的系统提示索引: ${index2}`);
|
|
399
|
-
}
|
|
400
|
-
this.systemPrompts[index2].enabled = !this.systemPrompts[index2].enabled;
|
|
401
|
-
return this;
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* 更新系统提示内容
|
|
405
|
-
*/
|
|
406
|
-
updateSystemPrompt(index2, content) {
|
|
407
|
-
if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
|
|
408
|
-
throw new Error(`无效的系统提示索引: ${index2}`);
|
|
409
|
-
}
|
|
410
|
-
if (typeof content !== "string" || !content.trim()) {
|
|
411
|
-
throw new Error("系统提示内容不能为空");
|
|
412
|
-
}
|
|
413
|
-
this.systemPrompts[index2].content = content.trim();
|
|
414
|
-
this.systemPrompts[index2].lastModified = /* @__PURE__ */ new Date();
|
|
415
|
-
return this;
|
|
416
|
-
}
|
|
417
|
-
/**
|
|
418
|
-
* 删除系统提示
|
|
419
|
-
*/
|
|
420
|
-
removeSystemPrompt(index2) {
|
|
421
|
-
if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
|
|
422
|
-
throw new Error(`无效的系统提示索引: ${index2}`);
|
|
423
|
-
}
|
|
424
|
-
return this.systemPrompts.splice(index2, 1)[0];
|
|
425
|
-
}
|
|
426
|
-
// ========== 工具管理 ==========
|
|
427
|
-
/**
|
|
428
|
-
* 添加工具
|
|
429
|
-
*/
|
|
430
|
-
addTool(toolDefinition) {
|
|
431
|
-
if (typeof toolDefinition === "object" && toolDefinition !== null) {
|
|
432
|
-
if (!toolDefinition.type || toolDefinition.type !== "function") {
|
|
433
|
-
throw new Error(`无效的工具类型,期望: 'function',实际: '${toolDefinition.type || "undefined"}'`);
|
|
434
|
-
}
|
|
435
|
-
if (!toolDefinition.function?.name?.trim()) {
|
|
436
|
-
throw new Error("工具名称不能为空");
|
|
437
|
-
}
|
|
438
|
-
return this.tools.push(toolDefinition) - 1;
|
|
439
|
-
}
|
|
440
|
-
if (toolDefinition.name && toolDefinition.description && toolDefinition.parameters) {
|
|
441
|
-
const constructedTool = MessageFormatter.constructTool(toolDefinition);
|
|
442
|
-
return this.tools.push(constructedTool) - 1;
|
|
443
|
-
}
|
|
444
|
-
throw new Error("无效的工具格式");
|
|
445
|
-
}
|
|
446
|
-
/**
|
|
447
|
-
* 从定义添加工具
|
|
448
|
-
*/
|
|
449
|
-
addToolFromDefinition(name, description, parameters) {
|
|
450
|
-
const tool = MessageFormatter.constructTool({ name, description, parameters });
|
|
451
|
-
return this.tools.push(tool) - 1;
|
|
452
|
-
}
|
|
453
|
-
/**
|
|
454
|
-
* 获取所有工具
|
|
455
|
-
*/
|
|
456
|
-
getTools() {
|
|
457
|
-
return [...this.tools];
|
|
458
|
-
}
|
|
459
|
-
/**
|
|
460
|
-
* 删除工具
|
|
461
|
-
*/
|
|
462
|
-
removeTool(index2) {
|
|
463
|
-
if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.tools.length) {
|
|
464
|
-
throw new Error(`无效的工具索引: ${index2}`);
|
|
465
|
-
}
|
|
466
|
-
return this.tools.splice(index2, 1)[0];
|
|
467
|
-
}
|
|
468
|
-
/**
|
|
469
|
-
* 清空所有工具
|
|
470
|
-
*/
|
|
471
|
-
clearTools() {
|
|
472
|
-
const removed = [...this.tools];
|
|
473
|
-
this.tools = [];
|
|
474
|
-
return removed;
|
|
475
|
-
}
|
|
476
|
-
// ========== 元数据管理 ==========
|
|
477
|
-
setName(name) {
|
|
478
|
-
if (typeof name !== "string" || !name.trim()) {
|
|
479
|
-
throw new Error("名称不能为空");
|
|
480
|
-
}
|
|
481
|
-
this.metadata.name = name.trim();
|
|
482
|
-
this.metadata.lastModified = /* @__PURE__ */ new Date();
|
|
483
|
-
return this;
|
|
484
|
-
}
|
|
485
|
-
getName() {
|
|
486
|
-
return this.metadata.name;
|
|
487
|
-
}
|
|
488
|
-
// ========== 兼容性方法 ==========
|
|
489
|
-
/**
|
|
490
|
-
* 获取最近的消息(兼容旧方法)
|
|
491
|
-
*/
|
|
492
|
-
getRecentMessages(baseRounds, cycleRounds) {
|
|
493
|
-
const messages = this.messages.map((item) => {
|
|
494
|
-
return MessageFormatter.toStandardFormat(item);
|
|
495
|
-
});
|
|
496
|
-
const msgTotal = messages.length;
|
|
497
|
-
const totalRounds = msgTotal / 2;
|
|
498
|
-
if (!baseRounds || isNaN(baseRounds) || baseRounds <= 0) {
|
|
499
|
-
return messages;
|
|
500
|
-
}
|
|
501
|
-
const maxCycleRoundMultiple = cycleRounds > 0 ? Math.floor(totalRounds / cycleRounds) * cycleRounds : 0;
|
|
502
|
-
const actualRounds = baseRounds + (totalRounds - maxCycleRoundMultiple);
|
|
503
|
-
const actualMsgCount = actualRounds * 2;
|
|
504
|
-
const n = Math.max(msgTotal - actualMsgCount, 0);
|
|
505
|
-
return messages.slice(n);
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* 获取所有格式化消息(兼容旧方法)
|
|
509
|
-
*/
|
|
510
|
-
getMessagesFormatted(baseRounds, cycleRounds) {
|
|
511
|
-
const systems = this.getEnabledSystemPrompts();
|
|
512
|
-
const hintSystem = {
|
|
513
|
-
role: "system",
|
|
514
|
-
content: `你的名字||标题是:${this.metadata.name || "未知"}`
|
|
515
|
-
};
|
|
516
|
-
systems.unshift(hintSystem);
|
|
517
|
-
const recentMessages = this.getRecentMessages(baseRounds, cycleRounds);
|
|
518
|
-
return [...systems, ...recentMessages];
|
|
519
|
-
}
|
|
520
|
-
// ========== 导入导出 ==========
|
|
521
|
-
export() {
|
|
522
|
-
return {
|
|
523
|
-
__format_version: 2,
|
|
524
|
-
exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
525
|
-
metadata: { ...this.metadata },
|
|
526
|
-
payload: {
|
|
527
|
-
messages: JSON.parse(JSON.stringify(this.messages)),
|
|
528
|
-
systemPrompts: JSON.parse(JSON.stringify(this.systemPrompts)),
|
|
529
|
-
tools: JSON.parse(JSON.stringify(this.tools))
|
|
530
|
-
}
|
|
531
|
-
};
|
|
532
|
-
}
|
|
533
|
-
import(data) {
|
|
534
|
-
const obj = typeof data === "string" ? JSON.parse(data) : data;
|
|
535
|
-
const parsed = Messages.parseCompatible(obj);
|
|
536
|
-
this.messages = parsed.messages || [];
|
|
537
|
-
this.systemPrompts = parsed.systemPrompts || [];
|
|
538
|
-
this.tools = parsed.tools || [];
|
|
539
|
-
this.metadata = parsed.metadata || {
|
|
540
|
-
name: "",
|
|
541
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
542
|
-
lastModified: /* @__PURE__ */ new Date()
|
|
543
|
-
};
|
|
544
|
-
this.metadata.lastModified = /* @__PURE__ */ new Date();
|
|
545
|
-
return this;
|
|
546
|
-
}
|
|
547
|
-
static parseCompatible(obj) {
|
|
548
|
-
if (obj?.__format_version === 2 && obj.payload) {
|
|
549
|
-
return {
|
|
550
|
-
messages: obj.payload.messages || [],
|
|
551
|
-
systemPrompts: obj.payload.systemPrompts || [],
|
|
552
|
-
tools: obj.payload.tools || [],
|
|
553
|
-
metadata: obj.metadata || {
|
|
554
|
-
name: "",
|
|
555
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
556
|
-
lastModified: /* @__PURE__ */ new Date()
|
|
557
|
-
}
|
|
558
|
-
};
|
|
559
|
-
}
|
|
560
|
-
if (obj?.__format_version === 1 && obj.payload) {
|
|
561
|
-
return {
|
|
562
|
-
messages: obj.payload.messages || [],
|
|
563
|
-
systemPrompts: obj.payload.systems || [],
|
|
564
|
-
tools: obj.payload.tools || [],
|
|
565
|
-
metadata: {
|
|
566
|
-
name: obj.payload.hintData?.name || "",
|
|
567
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
568
|
-
lastModified: /* @__PURE__ */ new Date()
|
|
569
|
-
}
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
if (obj?.messages && Array.isArray(obj.messages)) {
|
|
573
|
-
return {
|
|
574
|
-
messages: obj.messages || [],
|
|
575
|
-
systemPrompts: obj.systems || [],
|
|
576
|
-
tools: obj.tools || [],
|
|
577
|
-
metadata: {
|
|
578
|
-
name: obj.hintData?.name || "",
|
|
579
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
580
|
-
lastModified: /* @__PURE__ */ new Date()
|
|
581
|
-
}
|
|
582
|
-
};
|
|
583
|
-
}
|
|
584
|
-
throw new Error("无法识别的聊天数据格式");
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
class EventEmitter {
|
|
588
|
-
constructor() {
|
|
589
|
-
this.events = {};
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* 监听事件
|
|
593
|
-
* @param {string} eventName - 要注册的事件名称
|
|
594
|
-
* @param {Function} callback - 事件触发时执行的回调函数
|
|
595
|
-
*/
|
|
596
|
-
//实现一个监听事件的方法
|
|
597
|
-
on(eventName, callback) {
|
|
598
|
-
if (!this.events[eventName]) {
|
|
599
|
-
this.events[eventName] = [];
|
|
600
|
-
}
|
|
601
|
-
this.events[eventName].push(callback);
|
|
602
|
-
return () => this.off(eventName, callback);
|
|
603
|
-
}
|
|
604
|
-
/**
|
|
605
|
-
* 触发事件
|
|
606
|
-
* @param {string} eventName --要触发的事件名称
|
|
607
|
-
* @param {any} data --传递给回调函数的数据
|
|
608
|
-
*/
|
|
609
|
-
emit(eventName, data) {
|
|
610
|
-
const callbacks = this.events[eventName];
|
|
611
|
-
if (!callbacks) return;
|
|
612
|
-
const callbakesCopy = callbacks.slice();
|
|
613
|
-
for (let i = 0; i < callbakesCopy.length; i++) {
|
|
614
|
-
try {
|
|
615
|
-
callbakesCopy[i](data);
|
|
616
|
-
} catch (error) {
|
|
617
|
-
console.error(`事件 ${eventName} 的回调函数执行出错:`, error);
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
/**
|
|
622
|
-
* 取消监听事件
|
|
623
|
-
* @param {string} eventName --要取消的事件名称
|
|
624
|
-
* @param {Function} callback --要移除的回调函数
|
|
625
|
-
*/
|
|
626
|
-
off(eventName, callback) {
|
|
627
|
-
const callbacks = this.events[eventName];
|
|
628
|
-
if (!callbacks) return;
|
|
629
|
-
this.events[eventName] = callbacks.filter((item) => item !== callback);
|
|
630
|
-
if (this.events[eventName].length === 0) {
|
|
631
|
-
delete this.events[eventName];
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
/**
|
|
635
|
-
* 只监听一次事件(触发后自动取消)
|
|
636
|
-
* @param {string} eventName - 事件名称
|
|
637
|
-
* @param {Function} callback - 回调函数
|
|
638
|
-
*/
|
|
639
|
-
once(evenName, callback) {
|
|
640
|
-
const onceCallback = (data) => {
|
|
641
|
-
this.off(evenName, onceCallback);
|
|
642
|
-
callback(data);
|
|
643
|
-
};
|
|
644
|
-
this.on(evenName, onceCallback);
|
|
645
|
-
return () => this.off(evenName, onceCallback);
|
|
646
|
-
}
|
|
647
|
-
/**
|
|
648
|
-
* 移除某个事件的所有监听器
|
|
649
|
-
* @param {string} eventName - 事件名称
|
|
650
|
-
*/
|
|
651
|
-
removeAllListeners(eventName) {
|
|
652
|
-
if (eventName) {
|
|
653
|
-
delete this.events[eventName];
|
|
654
|
-
} else {
|
|
655
|
-
this.events = {};
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
/**
|
|
659
|
-
* 获取某个事件的所有监听器数量
|
|
660
|
-
* @param {string} eventName - 事件名称
|
|
661
|
-
* @returns {number} 监听器数量
|
|
662
|
-
*/
|
|
663
|
-
listenerCount(eventName) {
|
|
664
|
-
const callbacks = this.events[eventName];
|
|
665
|
-
return callbacks ? callbacks.length : 0;
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
class ToolManager extends EventEmitter {
|
|
669
|
-
constructor() {
|
|
670
|
-
super();
|
|
671
|
-
this.tools = /* @__PURE__ */ new Map();
|
|
672
|
-
}
|
|
673
|
-
/**
|
|
674
|
-
* 注册工具
|
|
675
|
-
* @param {string} name - 工具名称
|
|
676
|
-
* @param {object} toolDefinition - 工具定义(包含描述和参数信息)
|
|
677
|
-
* @param {Function} executor - 工具执行函数,接受参数对象并返回结果
|
|
678
|
-
*/
|
|
679
|
-
registerTool(name, toolDefinition, executor) {
|
|
680
|
-
if (this.tools.has(name)) {
|
|
681
|
-
throw new Error(`[系统提示异常] 工具 "${name}" 已经注册过了`);
|
|
682
|
-
}
|
|
683
|
-
this.tools.set(name, {
|
|
684
|
-
definition: toolDefinition,
|
|
685
|
-
executor
|
|
686
|
-
});
|
|
687
|
-
this.emit("tool-registered", { name, definition: toolDefinition });
|
|
688
|
-
return this;
|
|
689
|
-
}
|
|
690
|
-
/**
|
|
691
|
-
* 执行工具调用
|
|
692
|
-
* @param {object} toolCall - 工具调用信息,包含工具名称和参数
|
|
693
|
-
* @returns {Promise<any>} - 工具执行结果
|
|
694
|
-
*/
|
|
695
|
-
async executeToolCall(toolCall) {
|
|
696
|
-
const { id, function: func } = toolCall;
|
|
697
|
-
const { name, arguments: argsStr } = func;
|
|
698
|
-
if (!this.tools.has(name)) {
|
|
699
|
-
throw new Error(`未找到工具: ${name}`);
|
|
700
|
-
}
|
|
701
|
-
const tool = this.tools.get(name);
|
|
702
|
-
try {
|
|
703
|
-
const args = JSON.parse(argsStr);
|
|
704
|
-
this.emit("tool-execute-start", { name, args });
|
|
705
|
-
const result = await tool.executor(args);
|
|
706
|
-
this.emit("tool-execute-success", { name, args, result });
|
|
707
|
-
return {
|
|
708
|
-
tool_call_id: id,
|
|
709
|
-
// 必须包含tool_call_id
|
|
710
|
-
name,
|
|
711
|
-
result: JSON.stringify(result),
|
|
712
|
-
success: true
|
|
713
|
-
};
|
|
714
|
-
} catch (error) {
|
|
715
|
-
this.emit("tool-execute-error", { name, error });
|
|
716
|
-
return {
|
|
717
|
-
tool_call_id: id,
|
|
718
|
-
name,
|
|
719
|
-
error: error.message,
|
|
720
|
-
success: false
|
|
721
|
-
};
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
/**
|
|
725
|
-
* 获取所有工具定义(用于发送给AI)
|
|
726
|
-
*/
|
|
727
|
-
getToolDefinitions() {
|
|
728
|
-
const definitions = [];
|
|
729
|
-
for (const [name, tool] of this.tools) {
|
|
730
|
-
definitions.push(tool.definition);
|
|
731
|
-
}
|
|
732
|
-
return definitions;
|
|
733
|
-
}
|
|
734
|
-
/**
|
|
735
|
-
* 检查是否有工具
|
|
736
|
-
*/
|
|
737
|
-
hasTools() {
|
|
738
|
-
return this.tools.size > 0;
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
* 批量执行工具调用
|
|
742
|
-
* @param {Array} toolCalls - 工具调用数组
|
|
743
|
-
* @returns {Promise<Array>} - 所有工具的执行结果
|
|
744
|
-
*/
|
|
745
|
-
async executeToolCalls(toolCalls) {
|
|
746
|
-
if (!Array.isArray(toolCalls)) {
|
|
747
|
-
throw new Error("toolCalls必须是数组");
|
|
748
|
-
}
|
|
749
|
-
const results = [];
|
|
750
|
-
const promises = toolCalls.map(async (toolCall) => {
|
|
751
|
-
try {
|
|
752
|
-
const result = await this.executeToolCall(toolCall);
|
|
753
|
-
return result;
|
|
754
|
-
} catch (error) {
|
|
755
|
-
return {
|
|
756
|
-
tool_call_id: toolCall.id,
|
|
757
|
-
name: toolCall.function.name,
|
|
758
|
-
error: error.message,
|
|
759
|
-
success: false
|
|
760
|
-
};
|
|
761
|
-
}
|
|
762
|
-
});
|
|
763
|
-
const settledResults = await Promise.allSettled(promises);
|
|
764
|
-
for (const settled of settledResults) {
|
|
765
|
-
if (settled.status === "fulfilled") {
|
|
766
|
-
results.push(settled.value);
|
|
767
|
-
} else {
|
|
768
|
-
results.push({
|
|
769
|
-
error: settled.reason.message,
|
|
770
|
-
success: false
|
|
771
|
-
});
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
return results;
|
|
775
|
-
}
|
|
776
|
-
/**
|
|
777
|
-
* 串行执行工具调用(如果需要顺序执行)
|
|
778
|
-
*/
|
|
779
|
-
async executeToolCallsSequentially(toolCalls) {
|
|
780
|
-
const results = [];
|
|
781
|
-
for (const toolCall of toolCalls) {
|
|
782
|
-
try {
|
|
783
|
-
const result = await this.executeToolCall(toolCall);
|
|
784
|
-
results.push(result);
|
|
785
|
-
} catch (error) {
|
|
786
|
-
results.push({
|
|
787
|
-
tool_call_id: toolCall.id,
|
|
788
|
-
name: toolCall.function.name,
|
|
789
|
-
error: error.message,
|
|
790
|
-
success: false
|
|
791
|
-
});
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
return results;
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
class RequestBuilder {
|
|
798
|
-
constructor(model, messagesInstance, config = {}) {
|
|
799
|
-
this.model = model;
|
|
800
|
-
this.messages = messagesInstance;
|
|
801
|
-
this.config = {
|
|
802
|
-
// temperature: 0.7,
|
|
803
|
-
// max_tokens: 2000,
|
|
804
|
-
// stream: false, // 默认关闭流式传输
|
|
805
|
-
...config
|
|
806
|
-
};
|
|
807
|
-
this.toolManager = null;
|
|
808
|
-
}
|
|
809
|
-
/**
|
|
810
|
-
* 设置ToolManager引用
|
|
811
|
-
*/
|
|
812
|
-
setToolManager(toolManager) {
|
|
813
|
-
this.toolManager = toolManager;
|
|
814
|
-
return this;
|
|
815
|
-
}
|
|
816
|
-
/**
|
|
817
|
-
* 构建OpenAI兼容格式的请求体
|
|
818
|
-
*/
|
|
819
|
-
buildOpenAIFormat(baseRounds, cycleRounds) {
|
|
820
|
-
const formattedMessages = MessageFormatter.formatMessages(
|
|
821
|
-
this.messages,
|
|
822
|
-
baseRounds,
|
|
823
|
-
cycleRounds
|
|
824
|
-
);
|
|
825
|
-
const filteredMessages = MessageFormatter.filterForAPI(formattedMessages);
|
|
826
|
-
const request = {
|
|
827
|
-
model: this.model,
|
|
828
|
-
messages: filteredMessages,
|
|
829
|
-
...this.config
|
|
830
|
-
};
|
|
831
|
-
let tools = [];
|
|
832
|
-
if (this.toolManager && this.toolManager.hasTools()) {
|
|
833
|
-
tools = this.toolManager.getToolDefinitions();
|
|
834
|
-
} else {
|
|
835
|
-
tools = this.messages.getTools();
|
|
836
|
-
}
|
|
837
|
-
if (tools && tools.length > 0) {
|
|
838
|
-
request.tools = tools;
|
|
839
|
-
request.tool_choice = "auto";
|
|
840
|
-
}
|
|
841
|
-
return request;
|
|
842
|
-
}
|
|
843
|
-
/**
|
|
844
|
-
* 构建请求体并返回JSON字符串
|
|
845
|
-
*/
|
|
846
|
-
toJSON(baseRounds, cycleRounds) {
|
|
847
|
-
const request = this.buildOpenAIFormat(baseRounds, cycleRounds);
|
|
848
|
-
return JSON.stringify(request);
|
|
849
|
-
}
|
|
850
|
-
/**
|
|
851
|
-
* 构建请求体并返回对象
|
|
852
|
-
*/
|
|
853
|
-
toObject(baseRounds, cycleRounds) {
|
|
854
|
-
return this.buildOpenAIFormat(baseRounds, cycleRounds);
|
|
855
|
-
}
|
|
856
|
-
/**
|
|
857
|
-
* 设置配置项
|
|
858
|
-
*/
|
|
859
|
-
setConfig(key, value) {
|
|
860
|
-
this.config[key] = value;
|
|
861
|
-
return this;
|
|
862
|
-
}
|
|
863
|
-
/**
|
|
864
|
-
* 批量设置配置项
|
|
865
|
-
*/
|
|
866
|
-
setConfigs(configs) {
|
|
867
|
-
Object.assign(this.config, configs);
|
|
868
|
-
return this;
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
function getDefaultExportFromCjs(x) {
|
|
872
|
-
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
|
|
873
|
-
}
|
|
874
|
-
var axios$2 = { exports: {} };
|
|
875
|
-
var bind;
|
|
876
|
-
var hasRequiredBind;
|
|
877
|
-
function requireBind() {
|
|
878
|
-
if (hasRequiredBind) return bind;
|
|
879
|
-
hasRequiredBind = 1;
|
|
880
|
-
bind = function bind2(fn, thisArg) {
|
|
881
|
-
return function wrap() {
|
|
882
|
-
var args = new Array(arguments.length);
|
|
883
|
-
for (var i = 0; i < args.length; i++) {
|
|
884
|
-
args[i] = arguments[i];
|
|
885
|
-
}
|
|
886
|
-
return fn.apply(thisArg, args);
|
|
887
|
-
};
|
|
888
|
-
};
|
|
889
|
-
return bind;
|
|
890
|
-
}
|
|
891
|
-
var utils;
|
|
892
|
-
var hasRequiredUtils;
|
|
893
|
-
function requireUtils() {
|
|
894
|
-
if (hasRequiredUtils) return utils;
|
|
895
|
-
hasRequiredUtils = 1;
|
|
896
|
-
var bind2 = requireBind();
|
|
897
|
-
var toString = Object.prototype.toString;
|
|
898
|
-
function isArray(val) {
|
|
899
|
-
return toString.call(val) === "[object Array]";
|
|
900
|
-
}
|
|
901
|
-
function isUndefined(val) {
|
|
902
|
-
return typeof val === "undefined";
|
|
903
|
-
}
|
|
904
|
-
function isBuffer(val) {
|
|
905
|
-
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === "function" && val.constructor.isBuffer(val);
|
|
906
|
-
}
|
|
907
|
-
function isArrayBuffer(val) {
|
|
908
|
-
return toString.call(val) === "[object ArrayBuffer]";
|
|
909
|
-
}
|
|
910
|
-
function isFormData(val) {
|
|
911
|
-
return typeof FormData !== "undefined" && val instanceof FormData;
|
|
912
|
-
}
|
|
913
|
-
function isArrayBufferView(val) {
|
|
914
|
-
var result;
|
|
915
|
-
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
|
|
916
|
-
result = ArrayBuffer.isView(val);
|
|
917
|
-
} else {
|
|
918
|
-
result = val && val.buffer && val.buffer instanceof ArrayBuffer;
|
|
919
|
-
}
|
|
920
|
-
return result;
|
|
921
|
-
}
|
|
922
|
-
function isString(val) {
|
|
923
|
-
return typeof val === "string";
|
|
924
|
-
}
|
|
925
|
-
function isNumber(val) {
|
|
926
|
-
return typeof val === "number";
|
|
927
|
-
}
|
|
928
|
-
function isObject(val) {
|
|
929
|
-
return val !== null && typeof val === "object";
|
|
930
|
-
}
|
|
931
|
-
function isPlainObject(val) {
|
|
932
|
-
if (toString.call(val) !== "[object Object]") {
|
|
933
|
-
return false;
|
|
934
|
-
}
|
|
935
|
-
var prototype = Object.getPrototypeOf(val);
|
|
936
|
-
return prototype === null || prototype === Object.prototype;
|
|
937
|
-
}
|
|
938
|
-
function isDate(val) {
|
|
939
|
-
return toString.call(val) === "[object Date]";
|
|
940
|
-
}
|
|
941
|
-
function isFile(val) {
|
|
942
|
-
return toString.call(val) === "[object File]";
|
|
943
|
-
}
|
|
944
|
-
function isBlob(val) {
|
|
945
|
-
return toString.call(val) === "[object Blob]";
|
|
946
|
-
}
|
|
947
|
-
function isFunction(val) {
|
|
948
|
-
return toString.call(val) === "[object Function]";
|
|
949
|
-
}
|
|
950
|
-
function isStream(val) {
|
|
951
|
-
return isObject(val) && isFunction(val.pipe);
|
|
952
|
-
}
|
|
953
|
-
function isURLSearchParams(val) {
|
|
954
|
-
return typeof URLSearchParams !== "undefined" && val instanceof URLSearchParams;
|
|
955
|
-
}
|
|
956
|
-
function trim(str) {
|
|
957
|
-
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, "");
|
|
958
|
-
}
|
|
959
|
-
function isStandardBrowserEnv() {
|
|
960
|
-
if (typeof navigator !== "undefined" && (navigator.product === "ReactNative" || navigator.product === "NativeScript" || navigator.product === "NS")) {
|
|
961
|
-
return false;
|
|
962
|
-
}
|
|
963
|
-
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
964
|
-
}
|
|
965
|
-
function forEach(obj, fn) {
|
|
966
|
-
if (obj === null || typeof obj === "undefined") {
|
|
967
|
-
return;
|
|
968
|
-
}
|
|
969
|
-
if (typeof obj !== "object") {
|
|
970
|
-
obj = [obj];
|
|
971
|
-
}
|
|
972
|
-
if (isArray(obj)) {
|
|
973
|
-
for (var i = 0, l = obj.length; i < l; i++) {
|
|
974
|
-
fn.call(null, obj[i], i, obj);
|
|
975
|
-
}
|
|
976
|
-
} else {
|
|
977
|
-
for (var key in obj) {
|
|
978
|
-
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
979
|
-
fn.call(null, obj[key], key, obj);
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
function merge() {
|
|
985
|
-
var result = {};
|
|
986
|
-
function assignValue(val, key) {
|
|
987
|
-
if (isPlainObject(result[key]) && isPlainObject(val)) {
|
|
988
|
-
result[key] = merge(result[key], val);
|
|
989
|
-
} else if (isPlainObject(val)) {
|
|
990
|
-
result[key] = merge({}, val);
|
|
991
|
-
} else if (isArray(val)) {
|
|
992
|
-
result[key] = val.slice();
|
|
993
|
-
} else {
|
|
994
|
-
result[key] = val;
|
|
995
|
-
}
|
|
996
|
-
}
|
|
997
|
-
for (var i = 0, l = arguments.length; i < l; i++) {
|
|
998
|
-
forEach(arguments[i], assignValue);
|
|
999
|
-
}
|
|
1000
|
-
return result;
|
|
1001
|
-
}
|
|
1002
|
-
function extend(a, b, thisArg) {
|
|
1003
|
-
forEach(b, function assignValue(val, key) {
|
|
1004
|
-
if (thisArg && typeof val === "function") {
|
|
1005
|
-
a[key] = bind2(val, thisArg);
|
|
1006
|
-
} else {
|
|
1007
|
-
a[key] = val;
|
|
1008
|
-
}
|
|
1009
|
-
});
|
|
1010
|
-
return a;
|
|
1011
|
-
}
|
|
1012
|
-
function stripBOM(content) {
|
|
1013
|
-
if (content.charCodeAt(0) === 65279) {
|
|
1014
|
-
content = content.slice(1);
|
|
1015
|
-
}
|
|
1016
|
-
return content;
|
|
1017
|
-
}
|
|
1018
|
-
utils = {
|
|
1019
|
-
isArray,
|
|
1020
|
-
isArrayBuffer,
|
|
1021
|
-
isBuffer,
|
|
1022
|
-
isFormData,
|
|
1023
|
-
isArrayBufferView,
|
|
1024
|
-
isString,
|
|
1025
|
-
isNumber,
|
|
1026
|
-
isObject,
|
|
1027
|
-
isPlainObject,
|
|
1028
|
-
isUndefined,
|
|
1029
|
-
isDate,
|
|
1030
|
-
isFile,
|
|
1031
|
-
isBlob,
|
|
1032
|
-
isFunction,
|
|
1033
|
-
isStream,
|
|
1034
|
-
isURLSearchParams,
|
|
1035
|
-
isStandardBrowserEnv,
|
|
1036
|
-
forEach,
|
|
1037
|
-
merge,
|
|
1038
|
-
extend,
|
|
1039
|
-
trim,
|
|
1040
|
-
stripBOM
|
|
1041
|
-
};
|
|
1042
|
-
return utils;
|
|
1043
|
-
}
|
|
1044
|
-
var buildURL;
|
|
1045
|
-
var hasRequiredBuildURL;
|
|
1046
|
-
function requireBuildURL() {
|
|
1047
|
-
if (hasRequiredBuildURL) return buildURL;
|
|
1048
|
-
hasRequiredBuildURL = 1;
|
|
1049
|
-
var utils2 = requireUtils();
|
|
1050
|
-
function encode(val) {
|
|
1051
|
-
return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
|
|
1052
|
-
}
|
|
1053
|
-
buildURL = function buildURL2(url, params, paramsSerializer) {
|
|
1054
|
-
if (!params) {
|
|
1055
|
-
return url;
|
|
1056
|
-
}
|
|
1057
|
-
var serializedParams;
|
|
1058
|
-
if (paramsSerializer) {
|
|
1059
|
-
serializedParams = paramsSerializer(params);
|
|
1060
|
-
} else if (utils2.isURLSearchParams(params)) {
|
|
1061
|
-
serializedParams = params.toString();
|
|
1062
|
-
} else {
|
|
1063
|
-
var parts = [];
|
|
1064
|
-
utils2.forEach(params, function serialize(val, key) {
|
|
1065
|
-
if (val === null || typeof val === "undefined") {
|
|
1066
|
-
return;
|
|
1067
|
-
}
|
|
1068
|
-
if (utils2.isArray(val)) {
|
|
1069
|
-
key = key + "[]";
|
|
1070
|
-
} else {
|
|
1071
|
-
val = [val];
|
|
1072
|
-
}
|
|
1073
|
-
utils2.forEach(val, function parseValue(v) {
|
|
1074
|
-
if (utils2.isDate(v)) {
|
|
1075
|
-
v = v.toISOString();
|
|
1076
|
-
} else if (utils2.isObject(v)) {
|
|
1077
|
-
v = JSON.stringify(v);
|
|
1078
|
-
}
|
|
1079
|
-
parts.push(encode(key) + "=" + encode(v));
|
|
1080
|
-
});
|
|
1081
|
-
});
|
|
1082
|
-
serializedParams = parts.join("&");
|
|
1083
|
-
}
|
|
1084
|
-
if (serializedParams) {
|
|
1085
|
-
var hashmarkIndex = url.indexOf("#");
|
|
1086
|
-
if (hashmarkIndex !== -1) {
|
|
1087
|
-
url = url.slice(0, hashmarkIndex);
|
|
1088
|
-
}
|
|
1089
|
-
url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
|
|
1090
|
-
}
|
|
1091
|
-
return url;
|
|
1092
|
-
};
|
|
1093
|
-
return buildURL;
|
|
1094
|
-
}
|
|
1095
|
-
var InterceptorManager_1;
|
|
1096
|
-
var hasRequiredInterceptorManager;
|
|
1097
|
-
function requireInterceptorManager() {
|
|
1098
|
-
if (hasRequiredInterceptorManager) return InterceptorManager_1;
|
|
1099
|
-
hasRequiredInterceptorManager = 1;
|
|
1100
|
-
var utils2 = requireUtils();
|
|
1101
|
-
function InterceptorManager() {
|
|
1102
|
-
this.handlers = [];
|
|
1103
|
-
}
|
|
1104
|
-
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
|
|
1105
|
-
this.handlers.push({
|
|
1106
|
-
fulfilled,
|
|
1107
|
-
rejected,
|
|
1108
|
-
synchronous: options ? options.synchronous : false,
|
|
1109
|
-
runWhen: options ? options.runWhen : null
|
|
1110
|
-
});
|
|
1111
|
-
return this.handlers.length - 1;
|
|
1112
|
-
};
|
|
1113
|
-
InterceptorManager.prototype.eject = function eject(id) {
|
|
1114
|
-
if (this.handlers[id]) {
|
|
1115
|
-
this.handlers[id] = null;
|
|
1116
|
-
}
|
|
1117
|
-
};
|
|
1118
|
-
InterceptorManager.prototype.forEach = function forEach(fn) {
|
|
1119
|
-
utils2.forEach(this.handlers, function forEachHandler(h) {
|
|
1120
|
-
if (h !== null) {
|
|
1121
|
-
fn(h);
|
|
1122
|
-
}
|
|
1123
|
-
});
|
|
1124
|
-
};
|
|
1125
|
-
InterceptorManager_1 = InterceptorManager;
|
|
1126
|
-
return InterceptorManager_1;
|
|
1127
|
-
}
|
|
1128
|
-
var normalizeHeaderName;
|
|
1129
|
-
var hasRequiredNormalizeHeaderName;
|
|
1130
|
-
function requireNormalizeHeaderName() {
|
|
1131
|
-
if (hasRequiredNormalizeHeaderName) return normalizeHeaderName;
|
|
1132
|
-
hasRequiredNormalizeHeaderName = 1;
|
|
1133
|
-
var utils2 = requireUtils();
|
|
1134
|
-
normalizeHeaderName = function normalizeHeaderName2(headers, normalizedName) {
|
|
1135
|
-
utils2.forEach(headers, function processHeader(value, name) {
|
|
1136
|
-
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
|
|
1137
|
-
headers[normalizedName] = value;
|
|
1138
|
-
delete headers[name];
|
|
1139
|
-
}
|
|
1140
|
-
});
|
|
1141
|
-
};
|
|
1142
|
-
return normalizeHeaderName;
|
|
1143
|
-
}
|
|
1144
|
-
var enhanceError;
|
|
1145
|
-
var hasRequiredEnhanceError;
|
|
1146
|
-
function requireEnhanceError() {
|
|
1147
|
-
if (hasRequiredEnhanceError) return enhanceError;
|
|
1148
|
-
hasRequiredEnhanceError = 1;
|
|
1149
|
-
enhanceError = function enhanceError2(error, config, code, request, response) {
|
|
1150
|
-
error.config = config;
|
|
1151
|
-
if (code) {
|
|
1152
|
-
error.code = code;
|
|
1153
|
-
}
|
|
1154
|
-
error.request = request;
|
|
1155
|
-
error.response = response;
|
|
1156
|
-
error.isAxiosError = true;
|
|
1157
|
-
error.toJSON = function toJSON() {
|
|
1158
|
-
return {
|
|
1159
|
-
// Standard
|
|
1160
|
-
message: this.message,
|
|
1161
|
-
name: this.name,
|
|
1162
|
-
// Microsoft
|
|
1163
|
-
description: this.description,
|
|
1164
|
-
number: this.number,
|
|
1165
|
-
// Mozilla
|
|
1166
|
-
fileName: this.fileName,
|
|
1167
|
-
lineNumber: this.lineNumber,
|
|
1168
|
-
columnNumber: this.columnNumber,
|
|
1169
|
-
stack: this.stack,
|
|
1170
|
-
// Axios
|
|
1171
|
-
config: this.config,
|
|
1172
|
-
code: this.code
|
|
1173
|
-
};
|
|
1174
|
-
};
|
|
1175
|
-
return error;
|
|
1176
|
-
};
|
|
1177
|
-
return enhanceError;
|
|
1178
|
-
}
|
|
1179
|
-
var createError;
|
|
1180
|
-
var hasRequiredCreateError;
|
|
1181
|
-
function requireCreateError() {
|
|
1182
|
-
if (hasRequiredCreateError) return createError;
|
|
1183
|
-
hasRequiredCreateError = 1;
|
|
1184
|
-
var enhanceError2 = requireEnhanceError();
|
|
1185
|
-
createError = function createError2(message, config, code, request, response) {
|
|
1186
|
-
var error = new Error(message);
|
|
1187
|
-
return enhanceError2(error, config, code, request, response);
|
|
1188
|
-
};
|
|
1189
|
-
return createError;
|
|
1190
|
-
}
|
|
1191
|
-
var settle;
|
|
1192
|
-
var hasRequiredSettle;
|
|
1193
|
-
function requireSettle() {
|
|
1194
|
-
if (hasRequiredSettle) return settle;
|
|
1195
|
-
hasRequiredSettle = 1;
|
|
1196
|
-
var createError2 = requireCreateError();
|
|
1197
|
-
settle = function settle2(resolve, reject, response) {
|
|
1198
|
-
var validateStatus = response.config.validateStatus;
|
|
1199
|
-
if (!response.status || !validateStatus || validateStatus(response.status)) {
|
|
1200
|
-
resolve(response);
|
|
1201
|
-
} else {
|
|
1202
|
-
reject(createError2(
|
|
1203
|
-
"Request failed with status code " + response.status,
|
|
1204
|
-
response.config,
|
|
1205
|
-
null,
|
|
1206
|
-
response.request,
|
|
1207
|
-
response
|
|
1208
|
-
));
|
|
1209
|
-
}
|
|
1210
|
-
};
|
|
1211
|
-
return settle;
|
|
1212
|
-
}
|
|
1213
|
-
var cookies;
|
|
1214
|
-
var hasRequiredCookies;
|
|
1215
|
-
function requireCookies() {
|
|
1216
|
-
if (hasRequiredCookies) return cookies;
|
|
1217
|
-
hasRequiredCookies = 1;
|
|
1218
|
-
var utils2 = requireUtils();
|
|
1219
|
-
cookies = utils2.isStandardBrowserEnv() ? (
|
|
1220
|
-
// Standard browser envs support document.cookie
|
|
1221
|
-
/* @__PURE__ */ (function standardBrowserEnv() {
|
|
1222
|
-
return {
|
|
1223
|
-
write: function write(name, value, expires, path, domain, secure) {
|
|
1224
|
-
var cookie = [];
|
|
1225
|
-
cookie.push(name + "=" + encodeURIComponent(value));
|
|
1226
|
-
if (utils2.isNumber(expires)) {
|
|
1227
|
-
cookie.push("expires=" + new Date(expires).toGMTString());
|
|
1228
|
-
}
|
|
1229
|
-
if (utils2.isString(path)) {
|
|
1230
|
-
cookie.push("path=" + path);
|
|
1231
|
-
}
|
|
1232
|
-
if (utils2.isString(domain)) {
|
|
1233
|
-
cookie.push("domain=" + domain);
|
|
1234
|
-
}
|
|
1235
|
-
if (secure === true) {
|
|
1236
|
-
cookie.push("secure");
|
|
1237
|
-
}
|
|
1238
|
-
document.cookie = cookie.join("; ");
|
|
1239
|
-
},
|
|
1240
|
-
read: function read(name) {
|
|
1241
|
-
var match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
|
|
1242
|
-
return match ? decodeURIComponent(match[3]) : null;
|
|
1243
|
-
},
|
|
1244
|
-
remove: function remove(name) {
|
|
1245
|
-
this.write(name, "", Date.now() - 864e5);
|
|
1246
|
-
}
|
|
1247
|
-
};
|
|
1248
|
-
})()
|
|
1249
|
-
) : (
|
|
1250
|
-
// Non standard browser env (web workers, react-native) lack needed support.
|
|
1251
|
-
/* @__PURE__ */ (function nonStandardBrowserEnv() {
|
|
1252
|
-
return {
|
|
1253
|
-
write: function write() {
|
|
1254
|
-
},
|
|
1255
|
-
read: function read() {
|
|
1256
|
-
return null;
|
|
1257
|
-
},
|
|
1258
|
-
remove: function remove() {
|
|
1259
|
-
}
|
|
1260
|
-
};
|
|
1261
|
-
})()
|
|
1262
|
-
);
|
|
1263
|
-
return cookies;
|
|
1264
|
-
}
|
|
1265
|
-
var isAbsoluteURL;
|
|
1266
|
-
var hasRequiredIsAbsoluteURL;
|
|
1267
|
-
function requireIsAbsoluteURL() {
|
|
1268
|
-
if (hasRequiredIsAbsoluteURL) return isAbsoluteURL;
|
|
1269
|
-
hasRequiredIsAbsoluteURL = 1;
|
|
1270
|
-
isAbsoluteURL = function isAbsoluteURL2(url) {
|
|
1271
|
-
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
|
|
1272
|
-
};
|
|
1273
|
-
return isAbsoluteURL;
|
|
1274
|
-
}
|
|
1275
|
-
var combineURLs;
|
|
1276
|
-
var hasRequiredCombineURLs;
|
|
1277
|
-
function requireCombineURLs() {
|
|
1278
|
-
if (hasRequiredCombineURLs) return combineURLs;
|
|
1279
|
-
hasRequiredCombineURLs = 1;
|
|
1280
|
-
combineURLs = function combineURLs2(baseURL, relativeURL) {
|
|
1281
|
-
return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
|
|
1282
|
-
};
|
|
1283
|
-
return combineURLs;
|
|
1284
|
-
}
|
|
1285
|
-
var buildFullPath;
|
|
1286
|
-
var hasRequiredBuildFullPath;
|
|
1287
|
-
function requireBuildFullPath() {
|
|
1288
|
-
if (hasRequiredBuildFullPath) return buildFullPath;
|
|
1289
|
-
hasRequiredBuildFullPath = 1;
|
|
1290
|
-
var isAbsoluteURL2 = requireIsAbsoluteURL();
|
|
1291
|
-
var combineURLs2 = requireCombineURLs();
|
|
1292
|
-
buildFullPath = function buildFullPath2(baseURL, requestedURL) {
|
|
1293
|
-
if (baseURL && !isAbsoluteURL2(requestedURL)) {
|
|
1294
|
-
return combineURLs2(baseURL, requestedURL);
|
|
1295
|
-
}
|
|
1296
|
-
return requestedURL;
|
|
1297
|
-
};
|
|
1298
|
-
return buildFullPath;
|
|
1299
|
-
}
|
|
1300
|
-
var parseHeaders;
|
|
1301
|
-
var hasRequiredParseHeaders;
|
|
1302
|
-
function requireParseHeaders() {
|
|
1303
|
-
if (hasRequiredParseHeaders) return parseHeaders;
|
|
1304
|
-
hasRequiredParseHeaders = 1;
|
|
1305
|
-
var utils2 = requireUtils();
|
|
1306
|
-
var ignoreDuplicateOf = [
|
|
1307
|
-
"age",
|
|
1308
|
-
"authorization",
|
|
1309
|
-
"content-length",
|
|
1310
|
-
"content-type",
|
|
1311
|
-
"etag",
|
|
1312
|
-
"expires",
|
|
1313
|
-
"from",
|
|
1314
|
-
"host",
|
|
1315
|
-
"if-modified-since",
|
|
1316
|
-
"if-unmodified-since",
|
|
1317
|
-
"last-modified",
|
|
1318
|
-
"location",
|
|
1319
|
-
"max-forwards",
|
|
1320
|
-
"proxy-authorization",
|
|
1321
|
-
"referer",
|
|
1322
|
-
"retry-after",
|
|
1323
|
-
"user-agent"
|
|
1324
|
-
];
|
|
1325
|
-
parseHeaders = function parseHeaders2(headers) {
|
|
1326
|
-
var parsed = {};
|
|
1327
|
-
var key;
|
|
1328
|
-
var val;
|
|
1329
|
-
var i;
|
|
1330
|
-
if (!headers) {
|
|
1331
|
-
return parsed;
|
|
1332
|
-
}
|
|
1333
|
-
utils2.forEach(headers.split("\n"), function parser(line) {
|
|
1334
|
-
i = line.indexOf(":");
|
|
1335
|
-
key = utils2.trim(line.substr(0, i)).toLowerCase();
|
|
1336
|
-
val = utils2.trim(line.substr(i + 1));
|
|
1337
|
-
if (key) {
|
|
1338
|
-
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
|
|
1339
|
-
return;
|
|
1340
|
-
}
|
|
1341
|
-
if (key === "set-cookie") {
|
|
1342
|
-
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
|
|
1343
|
-
} else {
|
|
1344
|
-
parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
});
|
|
1348
|
-
return parsed;
|
|
1349
|
-
};
|
|
1350
|
-
return parseHeaders;
|
|
1351
|
-
}
|
|
1352
|
-
var isURLSameOrigin;
|
|
1353
|
-
var hasRequiredIsURLSameOrigin;
|
|
1354
|
-
function requireIsURLSameOrigin() {
|
|
1355
|
-
if (hasRequiredIsURLSameOrigin) return isURLSameOrigin;
|
|
1356
|
-
hasRequiredIsURLSameOrigin = 1;
|
|
1357
|
-
var utils2 = requireUtils();
|
|
1358
|
-
isURLSameOrigin = utils2.isStandardBrowserEnv() ? (
|
|
1359
|
-
// Standard browser envs have full support of the APIs needed to test
|
|
1360
|
-
// whether the request URL is of the same origin as current location.
|
|
1361
|
-
(function standardBrowserEnv() {
|
|
1362
|
-
var msie = /(msie|trident)/i.test(navigator.userAgent);
|
|
1363
|
-
var urlParsingNode = document.createElement("a");
|
|
1364
|
-
var originURL;
|
|
1365
|
-
function resolveURL(url) {
|
|
1366
|
-
var href = url;
|
|
1367
|
-
if (msie) {
|
|
1368
|
-
urlParsingNode.setAttribute("href", href);
|
|
1369
|
-
href = urlParsingNode.href;
|
|
1370
|
-
}
|
|
1371
|
-
urlParsingNode.setAttribute("href", href);
|
|
1372
|
-
return {
|
|
1373
|
-
href: urlParsingNode.href,
|
|
1374
|
-
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "",
|
|
1375
|
-
host: urlParsingNode.host,
|
|
1376
|
-
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "",
|
|
1377
|
-
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "",
|
|
1378
|
-
hostname: urlParsingNode.hostname,
|
|
1379
|
-
port: urlParsingNode.port,
|
|
1380
|
-
pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname
|
|
1381
|
-
};
|
|
1382
|
-
}
|
|
1383
|
-
originURL = resolveURL(window.location.href);
|
|
1384
|
-
return function isURLSameOrigin2(requestURL) {
|
|
1385
|
-
var parsed = utils2.isString(requestURL) ? resolveURL(requestURL) : requestURL;
|
|
1386
|
-
return parsed.protocol === originURL.protocol && parsed.host === originURL.host;
|
|
1387
|
-
};
|
|
1388
|
-
})()
|
|
1389
|
-
) : (
|
|
1390
|
-
// Non standard browser envs (web workers, react-native) lack needed support.
|
|
1391
|
-
/* @__PURE__ */ (function nonStandardBrowserEnv() {
|
|
1392
|
-
return function isURLSameOrigin2() {
|
|
1393
|
-
return true;
|
|
1394
|
-
};
|
|
1395
|
-
})()
|
|
1396
|
-
);
|
|
1397
|
-
return isURLSameOrigin;
|
|
1398
|
-
}
|
|
1399
|
-
var xhr;
|
|
1400
|
-
var hasRequiredXhr;
|
|
1401
|
-
function requireXhr() {
|
|
1402
|
-
if (hasRequiredXhr) return xhr;
|
|
1403
|
-
hasRequiredXhr = 1;
|
|
1404
|
-
var utils2 = requireUtils();
|
|
1405
|
-
var settle2 = requireSettle();
|
|
1406
|
-
var cookies2 = requireCookies();
|
|
1407
|
-
var buildURL2 = requireBuildURL();
|
|
1408
|
-
var buildFullPath2 = requireBuildFullPath();
|
|
1409
|
-
var parseHeaders2 = requireParseHeaders();
|
|
1410
|
-
var isURLSameOrigin2 = requireIsURLSameOrigin();
|
|
1411
|
-
var createError2 = requireCreateError();
|
|
1412
|
-
xhr = function xhrAdapter(config) {
|
|
1413
|
-
return new Promise(function dispatchXhrRequest(resolve, reject) {
|
|
1414
|
-
var requestData = config.data;
|
|
1415
|
-
var requestHeaders = config.headers;
|
|
1416
|
-
var responseType = config.responseType;
|
|
1417
|
-
if (utils2.isFormData(requestData)) {
|
|
1418
|
-
delete requestHeaders["Content-Type"];
|
|
1419
|
-
}
|
|
1420
|
-
var request = new XMLHttpRequest();
|
|
1421
|
-
if (config.auth) {
|
|
1422
|
-
var username = config.auth.username || "";
|
|
1423
|
-
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : "";
|
|
1424
|
-
requestHeaders.Authorization = "Basic " + btoa(username + ":" + password);
|
|
1425
|
-
}
|
|
1426
|
-
var fullPath = buildFullPath2(config.baseURL, config.url);
|
|
1427
|
-
request.open(config.method.toUpperCase(), buildURL2(fullPath, config.params, config.paramsSerializer), true);
|
|
1428
|
-
request.timeout = config.timeout;
|
|
1429
|
-
function onloadend() {
|
|
1430
|
-
if (!request) {
|
|
1431
|
-
return;
|
|
1432
|
-
}
|
|
1433
|
-
var responseHeaders = "getAllResponseHeaders" in request ? parseHeaders2(request.getAllResponseHeaders()) : null;
|
|
1434
|
-
var responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
|
|
1435
|
-
var response = {
|
|
1436
|
-
data: responseData,
|
|
1437
|
-
status: request.status,
|
|
1438
|
-
statusText: request.statusText,
|
|
1439
|
-
headers: responseHeaders,
|
|
1440
|
-
config,
|
|
1441
|
-
request
|
|
1442
|
-
};
|
|
1443
|
-
settle2(resolve, reject, response);
|
|
1444
|
-
request = null;
|
|
1445
|
-
}
|
|
1446
|
-
if ("onloadend" in request) {
|
|
1447
|
-
request.onloadend = onloadend;
|
|
1448
|
-
} else {
|
|
1449
|
-
request.onreadystatechange = function handleLoad() {
|
|
1450
|
-
if (!request || request.readyState !== 4) {
|
|
1451
|
-
return;
|
|
1452
|
-
}
|
|
1453
|
-
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
|
|
1454
|
-
return;
|
|
1455
|
-
}
|
|
1456
|
-
setTimeout(onloadend);
|
|
1457
|
-
};
|
|
1458
|
-
}
|
|
1459
|
-
request.onabort = function handleAbort() {
|
|
1460
|
-
if (!request) {
|
|
1461
|
-
return;
|
|
1462
|
-
}
|
|
1463
|
-
reject(createError2("Request aborted", config, "ECONNABORTED", request));
|
|
1464
|
-
request = null;
|
|
1465
|
-
};
|
|
1466
|
-
request.onerror = function handleError() {
|
|
1467
|
-
reject(createError2("Network Error", config, null, request));
|
|
1468
|
-
request = null;
|
|
1469
|
-
};
|
|
1470
|
-
request.ontimeout = function handleTimeout() {
|
|
1471
|
-
var timeoutErrorMessage = "timeout of " + config.timeout + "ms exceeded";
|
|
1472
|
-
if (config.timeoutErrorMessage) {
|
|
1473
|
-
timeoutErrorMessage = config.timeoutErrorMessage;
|
|
1474
|
-
}
|
|
1475
|
-
reject(createError2(
|
|
1476
|
-
timeoutErrorMessage,
|
|
1477
|
-
config,
|
|
1478
|
-
config.transitional && config.transitional.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED",
|
|
1479
|
-
request
|
|
1480
|
-
));
|
|
1481
|
-
request = null;
|
|
1482
|
-
};
|
|
1483
|
-
if (utils2.isStandardBrowserEnv()) {
|
|
1484
|
-
var xsrfValue = (config.withCredentials || isURLSameOrigin2(fullPath)) && config.xsrfCookieName ? cookies2.read(config.xsrfCookieName) : void 0;
|
|
1485
|
-
if (xsrfValue) {
|
|
1486
|
-
requestHeaders[config.xsrfHeaderName] = xsrfValue;
|
|
1487
|
-
}
|
|
1488
|
-
}
|
|
1489
|
-
if ("setRequestHeader" in request) {
|
|
1490
|
-
utils2.forEach(requestHeaders, function setRequestHeader(val, key) {
|
|
1491
|
-
if (typeof requestData === "undefined" && key.toLowerCase() === "content-type") {
|
|
1492
|
-
delete requestHeaders[key];
|
|
1493
|
-
} else {
|
|
1494
|
-
request.setRequestHeader(key, val);
|
|
1495
|
-
}
|
|
1496
|
-
});
|
|
1497
|
-
}
|
|
1498
|
-
if (!utils2.isUndefined(config.withCredentials)) {
|
|
1499
|
-
request.withCredentials = !!config.withCredentials;
|
|
1500
|
-
}
|
|
1501
|
-
if (responseType && responseType !== "json") {
|
|
1502
|
-
request.responseType = config.responseType;
|
|
1503
|
-
}
|
|
1504
|
-
if (typeof config.onDownloadProgress === "function") {
|
|
1505
|
-
request.addEventListener("progress", config.onDownloadProgress);
|
|
1506
|
-
}
|
|
1507
|
-
if (typeof config.onUploadProgress === "function" && request.upload) {
|
|
1508
|
-
request.upload.addEventListener("progress", config.onUploadProgress);
|
|
1509
|
-
}
|
|
1510
|
-
if (config.cancelToken) {
|
|
1511
|
-
config.cancelToken.promise.then(function onCanceled(cancel) {
|
|
1512
|
-
if (!request) {
|
|
1513
|
-
return;
|
|
1514
|
-
}
|
|
1515
|
-
request.abort();
|
|
1516
|
-
reject(cancel);
|
|
1517
|
-
request = null;
|
|
1518
|
-
});
|
|
1519
|
-
}
|
|
1520
|
-
if (!requestData) {
|
|
1521
|
-
requestData = null;
|
|
1522
|
-
}
|
|
1523
|
-
request.send(requestData);
|
|
1524
|
-
});
|
|
1525
|
-
};
|
|
1526
|
-
return xhr;
|
|
1527
|
-
}
|
|
1528
|
-
var defaults_1;
|
|
1529
|
-
var hasRequiredDefaults;
|
|
1530
|
-
function requireDefaults() {
|
|
1531
|
-
if (hasRequiredDefaults) return defaults_1;
|
|
1532
|
-
hasRequiredDefaults = 1;
|
|
1533
|
-
var utils2 = requireUtils();
|
|
1534
|
-
var normalizeHeaderName2 = requireNormalizeHeaderName();
|
|
1535
|
-
var enhanceError2 = requireEnhanceError();
|
|
1536
|
-
var DEFAULT_CONTENT_TYPE = {
|
|
1537
|
-
"Content-Type": "application/x-www-form-urlencoded"
|
|
1538
|
-
};
|
|
1539
|
-
function setContentTypeIfUnset(headers, value) {
|
|
1540
|
-
if (!utils2.isUndefined(headers) && utils2.isUndefined(headers["Content-Type"])) {
|
|
1541
|
-
headers["Content-Type"] = value;
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
function getDefaultAdapter() {
|
|
1545
|
-
var adapter;
|
|
1546
|
-
if (typeof XMLHttpRequest !== "undefined") {
|
|
1547
|
-
adapter = requireXhr();
|
|
1548
|
-
} else if (typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]") {
|
|
1549
|
-
adapter = requireXhr();
|
|
1550
|
-
}
|
|
1551
|
-
return adapter;
|
|
1552
|
-
}
|
|
1553
|
-
function stringifySafely(rawValue, parser, encoder) {
|
|
1554
|
-
if (utils2.isString(rawValue)) {
|
|
1555
|
-
try {
|
|
1556
|
-
(parser || JSON.parse)(rawValue);
|
|
1557
|
-
return utils2.trim(rawValue);
|
|
1558
|
-
} catch (e) {
|
|
1559
|
-
if (e.name !== "SyntaxError") {
|
|
1560
|
-
throw e;
|
|
1561
|
-
}
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
|
-
return (encoder || JSON.stringify)(rawValue);
|
|
1565
|
-
}
|
|
1566
|
-
var defaults = {
|
|
1567
|
-
transitional: {
|
|
1568
|
-
silentJSONParsing: true,
|
|
1569
|
-
forcedJSONParsing: true,
|
|
1570
|
-
clarifyTimeoutError: false
|
|
1571
|
-
},
|
|
1572
|
-
adapter: getDefaultAdapter(),
|
|
1573
|
-
transformRequest: [function transformRequest(data, headers) {
|
|
1574
|
-
normalizeHeaderName2(headers, "Accept");
|
|
1575
|
-
normalizeHeaderName2(headers, "Content-Type");
|
|
1576
|
-
if (utils2.isFormData(data) || utils2.isArrayBuffer(data) || utils2.isBuffer(data) || utils2.isStream(data) || utils2.isFile(data) || utils2.isBlob(data)) {
|
|
1577
|
-
return data;
|
|
1578
|
-
}
|
|
1579
|
-
if (utils2.isArrayBufferView(data)) {
|
|
1580
|
-
return data.buffer;
|
|
1581
|
-
}
|
|
1582
|
-
if (utils2.isURLSearchParams(data)) {
|
|
1583
|
-
setContentTypeIfUnset(headers, "application/x-www-form-urlencoded;charset=utf-8");
|
|
1584
|
-
return data.toString();
|
|
1585
|
-
}
|
|
1586
|
-
if (utils2.isObject(data) || headers && headers["Content-Type"] === "application/json") {
|
|
1587
|
-
setContentTypeIfUnset(headers, "application/json");
|
|
1588
|
-
return stringifySafely(data);
|
|
1589
|
-
}
|
|
1590
|
-
return data;
|
|
1591
|
-
}],
|
|
1592
|
-
transformResponse: [function transformResponse(data) {
|
|
1593
|
-
var transitional = this.transitional;
|
|
1594
|
-
var silentJSONParsing = transitional && transitional.silentJSONParsing;
|
|
1595
|
-
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
|
|
1596
|
-
var strictJSONParsing = !silentJSONParsing && this.responseType === "json";
|
|
1597
|
-
if (strictJSONParsing || forcedJSONParsing && utils2.isString(data) && data.length) {
|
|
1598
|
-
try {
|
|
1599
|
-
return JSON.parse(data);
|
|
1600
|
-
} catch (e) {
|
|
1601
|
-
if (strictJSONParsing) {
|
|
1602
|
-
if (e.name === "SyntaxError") {
|
|
1603
|
-
throw enhanceError2(e, this, "E_JSON_PARSE");
|
|
1604
|
-
}
|
|
1605
|
-
throw e;
|
|
1606
|
-
}
|
|
1607
|
-
}
|
|
1608
|
-
}
|
|
1609
|
-
return data;
|
|
1610
|
-
}],
|
|
1611
|
-
/**
|
|
1612
|
-
* A timeout in milliseconds to abort a request. If set to 0 (default) a
|
|
1613
|
-
* timeout is not created.
|
|
1614
|
-
*/
|
|
1615
|
-
timeout: 0,
|
|
1616
|
-
xsrfCookieName: "XSRF-TOKEN",
|
|
1617
|
-
xsrfHeaderName: "X-XSRF-TOKEN",
|
|
1618
|
-
maxContentLength: -1,
|
|
1619
|
-
maxBodyLength: -1,
|
|
1620
|
-
validateStatus: function validateStatus(status) {
|
|
1621
|
-
return status >= 200 && status < 300;
|
|
1622
|
-
}
|
|
1623
|
-
};
|
|
1624
|
-
defaults.headers = {
|
|
1625
|
-
common: {
|
|
1626
|
-
"Accept": "application/json, text/plain, */*"
|
|
1627
|
-
}
|
|
1628
|
-
};
|
|
1629
|
-
utils2.forEach(["delete", "get", "head"], function forEachMethodNoData(method) {
|
|
1630
|
-
defaults.headers[method] = {};
|
|
1631
|
-
});
|
|
1632
|
-
utils2.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
|
|
1633
|
-
defaults.headers[method] = utils2.merge(DEFAULT_CONTENT_TYPE);
|
|
1634
|
-
});
|
|
1635
|
-
defaults_1 = defaults;
|
|
1636
|
-
return defaults_1;
|
|
1637
|
-
}
|
|
1638
|
-
var transformData;
|
|
1639
|
-
var hasRequiredTransformData;
|
|
1640
|
-
function requireTransformData() {
|
|
1641
|
-
if (hasRequiredTransformData) return transformData;
|
|
1642
|
-
hasRequiredTransformData = 1;
|
|
1643
|
-
var utils2 = requireUtils();
|
|
1644
|
-
var defaults = requireDefaults();
|
|
1645
|
-
transformData = function transformData2(data, headers, fns) {
|
|
1646
|
-
var context = this || defaults;
|
|
1647
|
-
utils2.forEach(fns, function transform(fn) {
|
|
1648
|
-
data = fn.call(context, data, headers);
|
|
1649
|
-
});
|
|
1650
|
-
return data;
|
|
1651
|
-
};
|
|
1652
|
-
return transformData;
|
|
1653
|
-
}
|
|
1654
|
-
var isCancel;
|
|
1655
|
-
var hasRequiredIsCancel;
|
|
1656
|
-
function requireIsCancel() {
|
|
1657
|
-
if (hasRequiredIsCancel) return isCancel;
|
|
1658
|
-
hasRequiredIsCancel = 1;
|
|
1659
|
-
isCancel = function isCancel2(value) {
|
|
1660
|
-
return !!(value && value.__CANCEL__);
|
|
1661
|
-
};
|
|
1662
|
-
return isCancel;
|
|
1663
|
-
}
|
|
1664
|
-
var dispatchRequest;
|
|
1665
|
-
var hasRequiredDispatchRequest;
|
|
1666
|
-
function requireDispatchRequest() {
|
|
1667
|
-
if (hasRequiredDispatchRequest) return dispatchRequest;
|
|
1668
|
-
hasRequiredDispatchRequest = 1;
|
|
1669
|
-
var utils2 = requireUtils();
|
|
1670
|
-
var transformData2 = requireTransformData();
|
|
1671
|
-
var isCancel2 = requireIsCancel();
|
|
1672
|
-
var defaults = requireDefaults();
|
|
1673
|
-
function throwIfCancellationRequested(config) {
|
|
1674
|
-
if (config.cancelToken) {
|
|
1675
|
-
config.cancelToken.throwIfRequested();
|
|
1676
|
-
}
|
|
1677
|
-
}
|
|
1678
|
-
dispatchRequest = function dispatchRequest2(config) {
|
|
1679
|
-
throwIfCancellationRequested(config);
|
|
1680
|
-
config.headers = config.headers || {};
|
|
1681
|
-
config.data = transformData2.call(
|
|
1682
|
-
config,
|
|
1683
|
-
config.data,
|
|
1684
|
-
config.headers,
|
|
1685
|
-
config.transformRequest
|
|
1686
|
-
);
|
|
1687
|
-
config.headers = utils2.merge(
|
|
1688
|
-
config.headers.common || {},
|
|
1689
|
-
config.headers[config.method] || {},
|
|
1690
|
-
config.headers
|
|
1691
|
-
);
|
|
1692
|
-
utils2.forEach(
|
|
1693
|
-
["delete", "get", "head", "post", "put", "patch", "common"],
|
|
1694
|
-
function cleanHeaderConfig(method) {
|
|
1695
|
-
delete config.headers[method];
|
|
1696
|
-
}
|
|
1697
|
-
);
|
|
1698
|
-
var adapter = config.adapter || defaults.adapter;
|
|
1699
|
-
return adapter(config).then(function onAdapterResolution(response) {
|
|
1700
|
-
throwIfCancellationRequested(config);
|
|
1701
|
-
response.data = transformData2.call(
|
|
1702
|
-
config,
|
|
1703
|
-
response.data,
|
|
1704
|
-
response.headers,
|
|
1705
|
-
config.transformResponse
|
|
1706
|
-
);
|
|
1707
|
-
return response;
|
|
1708
|
-
}, function onAdapterRejection(reason) {
|
|
1709
|
-
if (!isCancel2(reason)) {
|
|
1710
|
-
throwIfCancellationRequested(config);
|
|
1711
|
-
if (reason && reason.response) {
|
|
1712
|
-
reason.response.data = transformData2.call(
|
|
1713
|
-
config,
|
|
1714
|
-
reason.response.data,
|
|
1715
|
-
reason.response.headers,
|
|
1716
|
-
config.transformResponse
|
|
1717
|
-
);
|
|
1718
|
-
}
|
|
1719
|
-
}
|
|
1720
|
-
return Promise.reject(reason);
|
|
1721
|
-
});
|
|
1722
|
-
};
|
|
1723
|
-
return dispatchRequest;
|
|
1724
|
-
}
|
|
1725
|
-
var mergeConfig;
|
|
1726
|
-
var hasRequiredMergeConfig;
|
|
1727
|
-
function requireMergeConfig() {
|
|
1728
|
-
if (hasRequiredMergeConfig) return mergeConfig;
|
|
1729
|
-
hasRequiredMergeConfig = 1;
|
|
1730
|
-
var utils2 = requireUtils();
|
|
1731
|
-
mergeConfig = function mergeConfig2(config1, config2) {
|
|
1732
|
-
config2 = config2 || {};
|
|
1733
|
-
var config = {};
|
|
1734
|
-
var valueFromConfig2Keys = ["url", "method", "data"];
|
|
1735
|
-
var mergeDeepPropertiesKeys = ["headers", "auth", "proxy", "params"];
|
|
1736
|
-
var defaultToConfig2Keys = [
|
|
1737
|
-
"baseURL",
|
|
1738
|
-
"transformRequest",
|
|
1739
|
-
"transformResponse",
|
|
1740
|
-
"paramsSerializer",
|
|
1741
|
-
"timeout",
|
|
1742
|
-
"timeoutMessage",
|
|
1743
|
-
"withCredentials",
|
|
1744
|
-
"adapter",
|
|
1745
|
-
"responseType",
|
|
1746
|
-
"xsrfCookieName",
|
|
1747
|
-
"xsrfHeaderName",
|
|
1748
|
-
"onUploadProgress",
|
|
1749
|
-
"onDownloadProgress",
|
|
1750
|
-
"decompress",
|
|
1751
|
-
"maxContentLength",
|
|
1752
|
-
"maxBodyLength",
|
|
1753
|
-
"maxRedirects",
|
|
1754
|
-
"transport",
|
|
1755
|
-
"httpAgent",
|
|
1756
|
-
"httpsAgent",
|
|
1757
|
-
"cancelToken",
|
|
1758
|
-
"socketPath",
|
|
1759
|
-
"responseEncoding"
|
|
1760
|
-
];
|
|
1761
|
-
var directMergeKeys = ["validateStatus"];
|
|
1762
|
-
function getMergedValue(target, source) {
|
|
1763
|
-
if (utils2.isPlainObject(target) && utils2.isPlainObject(source)) {
|
|
1764
|
-
return utils2.merge(target, source);
|
|
1765
|
-
} else if (utils2.isPlainObject(source)) {
|
|
1766
|
-
return utils2.merge({}, source);
|
|
1767
|
-
} else if (utils2.isArray(source)) {
|
|
1768
|
-
return source.slice();
|
|
1769
|
-
}
|
|
1770
|
-
return source;
|
|
1771
|
-
}
|
|
1772
|
-
function mergeDeepProperties(prop) {
|
|
1773
|
-
if (!utils2.isUndefined(config2[prop])) {
|
|
1774
|
-
config[prop] = getMergedValue(config1[prop], config2[prop]);
|
|
1775
|
-
} else if (!utils2.isUndefined(config1[prop])) {
|
|
1776
|
-
config[prop] = getMergedValue(void 0, config1[prop]);
|
|
1777
|
-
}
|
|
1778
|
-
}
|
|
1779
|
-
utils2.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
|
|
1780
|
-
if (!utils2.isUndefined(config2[prop])) {
|
|
1781
|
-
config[prop] = getMergedValue(void 0, config2[prop]);
|
|
1782
|
-
}
|
|
1783
|
-
});
|
|
1784
|
-
utils2.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
|
|
1785
|
-
utils2.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
|
|
1786
|
-
if (!utils2.isUndefined(config2[prop])) {
|
|
1787
|
-
config[prop] = getMergedValue(void 0, config2[prop]);
|
|
1788
|
-
} else if (!utils2.isUndefined(config1[prop])) {
|
|
1789
|
-
config[prop] = getMergedValue(void 0, config1[prop]);
|
|
1790
|
-
}
|
|
1791
|
-
});
|
|
1792
|
-
utils2.forEach(directMergeKeys, function merge(prop) {
|
|
1793
|
-
if (prop in config2) {
|
|
1794
|
-
config[prop] = getMergedValue(config1[prop], config2[prop]);
|
|
1795
|
-
} else if (prop in config1) {
|
|
1796
|
-
config[prop] = getMergedValue(void 0, config1[prop]);
|
|
1797
|
-
}
|
|
1798
|
-
});
|
|
1799
|
-
var axiosKeys = valueFromConfig2Keys.concat(mergeDeepPropertiesKeys).concat(defaultToConfig2Keys).concat(directMergeKeys);
|
|
1800
|
-
var otherKeys = Object.keys(config1).concat(Object.keys(config2)).filter(function filterAxiosKeys(key) {
|
|
1801
|
-
return axiosKeys.indexOf(key) === -1;
|
|
1802
|
-
});
|
|
1803
|
-
utils2.forEach(otherKeys, mergeDeepProperties);
|
|
1804
|
-
return config;
|
|
1805
|
-
};
|
|
1806
|
-
return mergeConfig;
|
|
1807
|
-
}
|
|
1808
|
-
const version = "0.21.4";
|
|
1809
|
-
const require$$0 = {
|
|
1810
|
-
version
|
|
1
|
+
//#region src/core/EventEmitter.js
|
|
2
|
+
/**
|
|
3
|
+
* 极简事件发射器
|
|
4
|
+
* 支持同步/异步事件,handler 返回 Promise 时自动 await
|
|
5
|
+
*/
|
|
6
|
+
var EventEmitter = class {
|
|
7
|
+
constructor() {
|
|
8
|
+
this._events = /* @__PURE__ */ new Map();
|
|
9
|
+
}
|
|
10
|
+
on(event, handler) {
|
|
11
|
+
if (!this._events.has(event)) this._events.set(event, []);
|
|
12
|
+
this._events.get(event).push(handler);
|
|
13
|
+
return () => this.off(event, handler);
|
|
14
|
+
}
|
|
15
|
+
off(event, handler) {
|
|
16
|
+
if (!this._events.has(event)) return;
|
|
17
|
+
const handlers = this._events.get(event).filter((h) => h !== handler);
|
|
18
|
+
if (handlers.length) this._events.set(event, handlers);
|
|
19
|
+
else this._events.delete(event);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* 同步触发事件
|
|
23
|
+
*/
|
|
24
|
+
emit(event, data) {
|
|
25
|
+
if (!this._events.has(event)) return;
|
|
26
|
+
for (const handler of this._events.get(event)) try {
|
|
27
|
+
handler(data);
|
|
28
|
+
} catch (err) {
|
|
29
|
+
console.error(`事件 ${event} 处理出错:`, err);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 异步触发事件,逐个 await handler
|
|
34
|
+
* handler 返回 Promise 时自动等待
|
|
35
|
+
*/
|
|
36
|
+
async emitAsync(event, data) {
|
|
37
|
+
if (!this._events.has(event)) return;
|
|
38
|
+
for (const handler of this._events.get(event)) try {
|
|
39
|
+
await handler(data);
|
|
40
|
+
} catch (err) {
|
|
41
|
+
console.error(`事件 ${event} 处理出错:`, err);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
1811
44
|
};
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
}
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/core/MessageStore.js
|
|
47
|
+
/**
|
|
48
|
+
* 消息存储 - 极简实现
|
|
49
|
+
* 每条消息格式:
|
|
50
|
+
* {
|
|
51
|
+
* id?: string,
|
|
52
|
+
* role: 'user'|'assistant'|'system'|'tool',
|
|
53
|
+
* content: string,
|
|
54
|
+
* images?: Array<string>, // 图片引用(URL / id),框架不存储图片数据
|
|
55
|
+
* _ephemeral?: boolean, // 临时消息:仅底部连续时参与请求,续写后转正
|
|
56
|
+
* _complete?: boolean, // 流式是否完成(false=未完成/中断)
|
|
57
|
+
* prefix?: boolean, // 前缀续写标记
|
|
58
|
+
* toolCalls?: Array,
|
|
59
|
+
* toolCallId?: string,
|
|
60
|
+
* timestamp?: number,
|
|
61
|
+
* metadata?: any
|
|
62
|
+
* }
|
|
63
|
+
*/
|
|
64
|
+
var MessageStore = class {
|
|
65
|
+
constructor() {
|
|
66
|
+
this._messages = [];
|
|
67
|
+
this._idCounter = 0;
|
|
68
|
+
}
|
|
69
|
+
add(message) {
|
|
70
|
+
const msg = {
|
|
71
|
+
id: message.id || `msg_${Date.now()}_${++this._idCounter}`,
|
|
72
|
+
timestamp: message.timestamp || Date.now(),
|
|
73
|
+
...message
|
|
74
|
+
};
|
|
75
|
+
this._messages.push(msg);
|
|
76
|
+
return msg;
|
|
77
|
+
}
|
|
78
|
+
addUser(content, metadata = {}) {
|
|
79
|
+
return this.add({
|
|
80
|
+
role: "user",
|
|
81
|
+
content,
|
|
82
|
+
metadata
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
addAssistant(content, metadata = {}) {
|
|
86
|
+
return this.add({
|
|
87
|
+
role: "assistant",
|
|
88
|
+
content,
|
|
89
|
+
metadata
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
addSystem(content, metadata = {}) {
|
|
93
|
+
return this.add({
|
|
94
|
+
role: "system",
|
|
95
|
+
content,
|
|
96
|
+
metadata
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
addTool(content, toolCallId, metadata = {}) {
|
|
100
|
+
return this.add({
|
|
101
|
+
role: "tool",
|
|
102
|
+
content,
|
|
103
|
+
toolCallId,
|
|
104
|
+
metadata
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* 快速添加一次性的、带续写标记的 assistant 消息
|
|
109
|
+
* 适用于思维链引导、临时注入等场景
|
|
110
|
+
* @param {string} content — 引导内容
|
|
111
|
+
* @param {Object} [options] — { reasoningContent, prefix }
|
|
112
|
+
* @returns {Object} 添加的消息
|
|
113
|
+
*/
|
|
114
|
+
addOnceAssistant(content, options = {}) {
|
|
115
|
+
return this.add({
|
|
116
|
+
role: "assistant",
|
|
117
|
+
content,
|
|
118
|
+
reasoningContent: options.reasoningContent,
|
|
119
|
+
prefix: options.prefix !== false,
|
|
120
|
+
_ephemeral: true
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
getLast() {
|
|
124
|
+
return this._messages[this._messages.length - 1] || null;
|
|
125
|
+
}
|
|
126
|
+
getAll() {
|
|
127
|
+
return [...this._messages];
|
|
128
|
+
}
|
|
129
|
+
clear() {
|
|
130
|
+
this._messages = [];
|
|
131
|
+
}
|
|
132
|
+
undoToLastAssistant() {
|
|
133
|
+
let lastAssistantIndex = -1;
|
|
134
|
+
for (let i = this._messages.length - 1; i >= 0; i--) if (this._messages[i].role === "assistant") {
|
|
135
|
+
lastAssistantIndex = i;
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
if (lastAssistantIndex >= 0) return this._messages.splice(lastAssistantIndex + 1);
|
|
139
|
+
return [];
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* 更新消息:按 id 查找并合并 changes,不新增消息
|
|
143
|
+
* @param {string} id — 消息 id
|
|
144
|
+
* @param {Object} changes — 要合并的字段
|
|
145
|
+
* @returns {Object|null} 更新后的消息,未找到返回 null
|
|
146
|
+
*/
|
|
147
|
+
update(id, changes) {
|
|
148
|
+
for (const msg of this._messages) if (msg.id === id) {
|
|
149
|
+
Object.assign(msg, changes);
|
|
150
|
+
msg.timestamp = changes.timestamp || Date.now();
|
|
151
|
+
return msg;
|
|
152
|
+
}
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
//#endregion
|
|
157
|
+
//#region src/core/SystemPromptStore.js
|
|
158
|
+
/**
|
|
159
|
+
* SystemPromptStore — 系统提示词存储
|
|
160
|
+
*
|
|
161
|
+
* 职责:管理多条 system prompt 的增删改查与开关
|
|
162
|
+
* 与 MessageStore 分离,因为 system prompt 是"AI 行为准则",不是对话事件
|
|
163
|
+
*
|
|
164
|
+
* 每条记录格式:
|
|
165
|
+
* {
|
|
166
|
+
* id: string,
|
|
167
|
+
* content: string,
|
|
168
|
+
* enabled: boolean,
|
|
169
|
+
* timestamp: number
|
|
170
|
+
* }
|
|
171
|
+
*/
|
|
172
|
+
var SystemPromptStore = class {
|
|
173
|
+
constructor() {
|
|
174
|
+
this._prompts = [];
|
|
175
|
+
this._idCounter = 0;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* 添加一条 system prompt
|
|
179
|
+
* @param {string} content — 提示词内容
|
|
180
|
+
* @param {boolean} [enabled=true] — 是否启用
|
|
181
|
+
* @returns {Object} 添加的记录
|
|
182
|
+
*/
|
|
183
|
+
add(content, enabled = true) {
|
|
184
|
+
if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
|
|
185
|
+
const record = {
|
|
186
|
+
id: `sys_${Date.now()}_${++this._idCounter}`,
|
|
187
|
+
content: content.trim(),
|
|
188
|
+
enabled: Boolean(enabled),
|
|
189
|
+
timestamp: Date.now()
|
|
190
|
+
};
|
|
191
|
+
this._prompts.push(record);
|
|
192
|
+
return record;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* 删除指定索引的 system prompt
|
|
196
|
+
* @param {number} index
|
|
197
|
+
* @returns {Object} 被删除的记录
|
|
198
|
+
*/
|
|
199
|
+
remove(index) {
|
|
200
|
+
if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
|
|
201
|
+
return this._prompts.splice(index, 1)[0];
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* 切换指定索引的启用/禁用状态
|
|
205
|
+
* @param {number} index
|
|
206
|
+
* @returns {boolean} 切换后的状态
|
|
207
|
+
*/
|
|
208
|
+
toggle(index) {
|
|
209
|
+
if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
|
|
210
|
+
this._prompts[index].enabled = !this._prompts[index].enabled;
|
|
211
|
+
return this._prompts[index].enabled;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* 更新指定索引的 content
|
|
215
|
+
* @param {number} index
|
|
216
|
+
* @param {string} content
|
|
217
|
+
*/
|
|
218
|
+
update(index, content) {
|
|
219
|
+
if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
|
|
220
|
+
if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
|
|
221
|
+
this._prompts[index].content = content.trim();
|
|
222
|
+
this._prompts[index].timestamp = Date.now();
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* 清空并用一条 content 替换(便捷方法,常用于 config.system = '...')
|
|
226
|
+
* @param {string} content
|
|
227
|
+
*/
|
|
228
|
+
set(content) {
|
|
229
|
+
this._prompts = [];
|
|
230
|
+
if (content && typeof content === "string" && content.trim()) this.add(content, true);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* 按 enabled 筛选后,转为适配器可用的格式
|
|
234
|
+
* @returns {Array<{role:'system', content:string}>}
|
|
235
|
+
*/
|
|
236
|
+
getEnabled() {
|
|
237
|
+
return this._prompts.filter((p) => p.enabled).map((p) => ({
|
|
238
|
+
role: "system",
|
|
239
|
+
content: p.content
|
|
240
|
+
}));
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* 返回所有记录(含 enabled 状态,用于 UI 展示)
|
|
244
|
+
* @returns {Array}
|
|
245
|
+
*/
|
|
246
|
+
getAll() {
|
|
247
|
+
return [...this._prompts];
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* 清空所有 system prompt
|
|
251
|
+
*/
|
|
252
|
+
clear() {
|
|
253
|
+
this._prompts = [];
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region src/core/Errors.js
|
|
258
|
+
/**
|
|
259
|
+
* 自定义错误类
|
|
260
|
+
* 用于区分不同类型的错误,方便用户通过 `error.name` 或 `instanceof` 处理
|
|
261
|
+
*/
|
|
262
|
+
var APIError = class extends Error {
|
|
263
|
+
/**
|
|
264
|
+
* @param {string} message - 错误消息(通常来自 API 响应)
|
|
265
|
+
* @param {number} statusCode - HTTP 状态码
|
|
266
|
+
* @param {any} originalError - 原始错误对象或相关信息
|
|
267
|
+
* @param {string} responseText - 原始响应文本(如果有)
|
|
268
|
+
*/
|
|
269
|
+
constructor(message, statusCode, originalError, responseText) {
|
|
270
|
+
super(message);
|
|
271
|
+
this.name = "APIError";
|
|
272
|
+
this.statusCode = statusCode;
|
|
273
|
+
this.originalError = originalError;
|
|
274
|
+
this.responseText = responseText;
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
var NetworkError = class extends Error {
|
|
278
|
+
/**
|
|
279
|
+
* @param {string} message - 错误消息
|
|
280
|
+
* @param {any} originalError - 原始错误对象或相关信息
|
|
281
|
+
*/
|
|
282
|
+
constructor(message, originalError) {
|
|
283
|
+
super(message);
|
|
284
|
+
this.name = "NetworkError";
|
|
285
|
+
this.originalError = originalError;
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
var ConfigurationError = class extends Error {
|
|
289
|
+
/**
|
|
290
|
+
* @param {string} message - 错误消息
|
|
291
|
+
*/
|
|
292
|
+
constructor(message) {
|
|
293
|
+
super(message);
|
|
294
|
+
this.name = "ConfigurationError";
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
var ParsingError = class extends Error {
|
|
298
|
+
/**
|
|
299
|
+
* @param {string} message - 错误消息
|
|
300
|
+
* @param {any} originalError - 原始错误对象或相关信息
|
|
301
|
+
* @param {string} responseText - 原始响应文本(如果有)
|
|
302
|
+
**/
|
|
303
|
+
constructor(message, originalError, responseText) {
|
|
304
|
+
super(message);
|
|
305
|
+
this.name = "ParsingError";
|
|
306
|
+
this.originalError = originalError;
|
|
307
|
+
this.responseText = responseText;
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
//#endregion
|
|
311
|
+
//#region src/core/ChatService.js
|
|
312
|
+
var ChatService = class extends EventEmitter {
|
|
313
|
+
constructor(config = {}) {
|
|
314
|
+
super();
|
|
315
|
+
this.config = { ...config };
|
|
316
|
+
this.messages = new MessageStore();
|
|
317
|
+
this.systemPrompts = new SystemPromptStore();
|
|
318
|
+
this._adapter = null;
|
|
319
|
+
this._abortController = null;
|
|
320
|
+
this._isGenerating = false;
|
|
321
|
+
this._hooks = new EventEmitter();
|
|
322
|
+
this._processResponse = null;
|
|
323
|
+
const model = this.config.model || this.config.modelParams?.model;
|
|
324
|
+
if (!model || typeof model !== "string" || !model.trim()) throw new ConfigurationError("缺少 model 配置");
|
|
325
|
+
const temperature = this.config.modelParams?.temperature ?? this.config.temperature;
|
|
326
|
+
if (temperature !== void 0 && (typeof temperature !== "number" || temperature < 0 || temperature > 2)) throw new ConfigurationError(`temperature 必须在 0-2 之间,当前值: ${temperature}`);
|
|
327
|
+
const maxTokens = this.config.modelParams?.maxTokens ?? this.config.maxTokens;
|
|
328
|
+
if (maxTokens !== void 0 && (typeof maxTokens !== "number" || maxTokens < 1 || !Number.isInteger(maxTokens))) throw new ConfigurationError(`maxTokens 必须为正整数,当前值: ${maxTokens}`);
|
|
329
|
+
if (typeof config.system === "string" && config.system.trim()) this.systemPrompts.set(config.system);
|
|
330
|
+
}
|
|
331
|
+
use(plugin) {
|
|
332
|
+
plugin.install(this);
|
|
333
|
+
return this;
|
|
334
|
+
}
|
|
335
|
+
setAdapter(adapter) {
|
|
336
|
+
this._adapter = adapter;
|
|
337
|
+
}
|
|
338
|
+
abort() {
|
|
339
|
+
if (this._abortController) this._abortController.abort();
|
|
340
|
+
}
|
|
341
|
+
get isGenerating() {
|
|
342
|
+
return this._isGenerating;
|
|
343
|
+
}
|
|
344
|
+
async continueLast() {
|
|
345
|
+
const target = this._prepareContinue();
|
|
346
|
+
this.messages.update(target.id, { prefix: true });
|
|
347
|
+
try {
|
|
348
|
+
await this._request({
|
|
349
|
+
addUser: false,
|
|
350
|
+
isStream: false,
|
|
351
|
+
mergeToEntry: target.id
|
|
352
|
+
});
|
|
353
|
+
this.messages.update(target.id, {
|
|
354
|
+
_complete: true,
|
|
355
|
+
prefix: void 0,
|
|
356
|
+
_ephemeral: void 0
|
|
357
|
+
});
|
|
358
|
+
return target;
|
|
359
|
+
} catch (err) {
|
|
360
|
+
this.messages.update(target.id, { prefix: void 0 });
|
|
361
|
+
throw err;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
async continueLastStream(onProgress, onDone) {
|
|
365
|
+
const target = this._prepareContinue();
|
|
366
|
+
console.log("[DEBUG] continueLastStream target.id:", target.id);
|
|
367
|
+
this.messages.update(target.id, { prefix: true });
|
|
368
|
+
const baseLen = (target.content || "").length;
|
|
369
|
+
try {
|
|
370
|
+
await this._request({
|
|
371
|
+
addUser: false,
|
|
372
|
+
isStream: true,
|
|
373
|
+
mergeToEntry: target.id,
|
|
374
|
+
onProgress: (chunk) => {
|
|
375
|
+
if (onProgress) onProgress({
|
|
376
|
+
...chunk,
|
|
377
|
+
content: (chunk.content || "").slice(baseLen)
|
|
378
|
+
});
|
|
379
|
+
},
|
|
380
|
+
onDone: (final) => {
|
|
381
|
+
if (onDone) onDone(final);
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
this.messages.update(target.id, {
|
|
385
|
+
_complete: true,
|
|
386
|
+
prefix: void 0,
|
|
387
|
+
_ephemeral: void 0
|
|
388
|
+
});
|
|
389
|
+
return target;
|
|
390
|
+
} catch (err) {
|
|
391
|
+
this.messages.update(target.id, { prefix: void 0 });
|
|
392
|
+
throw err;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
_prepareContinue() {
|
|
396
|
+
const msgs = this.messages.getAll();
|
|
397
|
+
const last = msgs[msgs.length - 1];
|
|
398
|
+
if (last && (last.role === "assistant" || last._ephemeral)) return last;
|
|
399
|
+
throw new Error("最后一条消息不是 assistant,无法续写");
|
|
400
|
+
}
|
|
401
|
+
updateConfig(partial) {
|
|
402
|
+
Object.assign(this.config, partial);
|
|
403
|
+
if (typeof partial.system === "string") this.systemPrompts.set(partial.system);
|
|
404
|
+
this.emit("config-updated", {
|
|
405
|
+
changes: partial,
|
|
406
|
+
timestamp: Date.now()
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
async _request(options) {
|
|
410
|
+
let { userInput, addUser = true, isStream = false, onProgress, onDone, mergeToEntry } = options;
|
|
411
|
+
this.emit("sending", {
|
|
412
|
+
addUser,
|
|
413
|
+
userInput,
|
|
414
|
+
timestamp: Date.now()
|
|
415
|
+
});
|
|
416
|
+
this._addUserMessage(userInput, addUser);
|
|
417
|
+
await this._hooks.emitAsync("beforeRequest", {
|
|
418
|
+
messages: this.messages,
|
|
419
|
+
config: this.config,
|
|
420
|
+
options
|
|
421
|
+
});
|
|
422
|
+
if (this.config.ephemeralContinue && !mergeToEntry) {
|
|
423
|
+
const msgs = this.messages.getAll();
|
|
424
|
+
const last = msgs[msgs.length - 1];
|
|
425
|
+
if (last && last.prefix && (last.role === "assistant" || last._ephemeral)) mergeToEntry = last.id;
|
|
426
|
+
}
|
|
427
|
+
const body = this._adapter.buildRequest(this.messages.getAll(), this.config, this.systemPrompts.getEnabled());
|
|
428
|
+
const retryCfg = this.config.retry || {};
|
|
429
|
+
try {
|
|
430
|
+
return await this._withRetry(body, {
|
|
431
|
+
isStream,
|
|
432
|
+
onProgress,
|
|
433
|
+
onDone,
|
|
434
|
+
mergeToEntry,
|
|
435
|
+
maxRetries: retryCfg.maxRetries ?? 0,
|
|
436
|
+
retryDelay: retryCfg.retryDelay ?? 1e3
|
|
437
|
+
});
|
|
438
|
+
} catch (error) {
|
|
439
|
+
this.emit("error", {
|
|
440
|
+
error,
|
|
441
|
+
timestamp: Date.now()
|
|
442
|
+
});
|
|
443
|
+
throw error;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
_addUserMessage(userInput, addUser) {
|
|
447
|
+
if (addUser && userInput !== void 0) {
|
|
448
|
+
const msg = typeof userInput === "string" ? {
|
|
449
|
+
role: "user",
|
|
450
|
+
content: userInput
|
|
451
|
+
} : {
|
|
452
|
+
role: "user",
|
|
453
|
+
...userInput
|
|
454
|
+
};
|
|
455
|
+
this.messages.add(msg);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/** retry 循环,占位消息只 push 一次 */
|
|
459
|
+
async _withRetry(body, { isStream, onProgress, onDone, mergeToEntry, maxRetries, retryDelay }) {
|
|
460
|
+
let lastError = null;
|
|
461
|
+
const adapterOptions = { signal: this._abortController?.signal };
|
|
462
|
+
let placeholder = null;
|
|
463
|
+
let base = null;
|
|
464
|
+
if (isStream) {
|
|
465
|
+
if (mergeToEntry) {
|
|
466
|
+
placeholder = this.messages.getAll().find((m) => m.id === mergeToEntry);
|
|
467
|
+
if (placeholder) base = {
|
|
468
|
+
content: placeholder.content || "",
|
|
469
|
+
reasoning: placeholder.reasoningContent || ""
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
if (!placeholder) placeholder = this.messages.add({
|
|
473
|
+
role: "assistant",
|
|
474
|
+
content: "",
|
|
475
|
+
_complete: false
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
479
|
+
if (attempt > 0) {
|
|
480
|
+
this.emit("retry", {
|
|
481
|
+
attempt,
|
|
482
|
+
maxRetries,
|
|
483
|
+
lastError,
|
|
484
|
+
timestamp: Date.now()
|
|
485
|
+
});
|
|
486
|
+
await new Promise((r) => setTimeout(r, retryDelay));
|
|
487
|
+
}
|
|
488
|
+
try {
|
|
489
|
+
this._isGenerating = true;
|
|
490
|
+
if (isStream) return await this._stream(body, adapterOptions, {
|
|
491
|
+
placeholder,
|
|
492
|
+
base,
|
|
493
|
+
mergeToEntry,
|
|
494
|
+
onProgress,
|
|
495
|
+
onDone
|
|
496
|
+
});
|
|
497
|
+
else {
|
|
498
|
+
const resp = await this._adapter.send(body, this.config, adapterOptions);
|
|
499
|
+
let result = this._handleResult(this._adapter.parseResponse(resp), mergeToEntry);
|
|
500
|
+
if (this._processResponse && !mergeToEntry) result = await this._processResponse(result, { isStream: false });
|
|
501
|
+
return result;
|
|
502
|
+
}
|
|
503
|
+
} catch (error) {
|
|
504
|
+
lastError = error;
|
|
505
|
+
if (error.name === "AbortError" || this._abortController?.signal.aborted) {
|
|
506
|
+
this._isGenerating = false;
|
|
507
|
+
throw error;
|
|
508
|
+
}
|
|
509
|
+
if (error instanceof NetworkError && attempt < maxRetries) continue;
|
|
510
|
+
this._isGenerating = false;
|
|
511
|
+
throw error;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
this._isGenerating = false;
|
|
515
|
+
throw lastError;
|
|
516
|
+
}
|
|
517
|
+
/** 流式:ChatService 维护占位,adapter 只管解析 */
|
|
518
|
+
async _stream(body, adapterOptions, { placeholder, base, mergeToEntry, onProgress, onDone }) {
|
|
519
|
+
let finalMsg = null;
|
|
520
|
+
await this._adapter.stream(body, this.config, (snap) => {
|
|
521
|
+
placeholder.content = snap.content || "";
|
|
522
|
+
if (snap.reasoningContent) placeholder.reasoningContent = snap.reasoningContent;
|
|
523
|
+
if (snap.toolCalls) placeholder.toolCalls = [...snap.toolCalls];
|
|
524
|
+
this.emit("stream-progress", snap);
|
|
525
|
+
if (onProgress) onProgress(snap);
|
|
526
|
+
}, async (final) => {
|
|
527
|
+
finalMsg = final;
|
|
528
|
+
if (this._processResponse && !mergeToEntry) finalMsg = await this._processResponse(finalMsg, {
|
|
529
|
+
isStream: true,
|
|
530
|
+
onProgress,
|
|
531
|
+
onDone
|
|
532
|
+
});
|
|
533
|
+
if (mergeToEntry && base) {
|
|
534
|
+
const changes = {
|
|
535
|
+
content: base.content + (final.content || ""),
|
|
536
|
+
_complete: true
|
|
537
|
+
};
|
|
538
|
+
if (final.reasoningContent) changes.reasoningContent = base.reasoning + final.reasoningContent;
|
|
539
|
+
if (final.toolCalls) changes.toolCalls = final.toolCalls;
|
|
540
|
+
this.messages.update(mergeToEntry, changes);
|
|
541
|
+
const updated = this.messages.getAll().find((m) => m.id === mergeToEntry);
|
|
542
|
+
this.emit("message", updated);
|
|
543
|
+
if (onDone) onDone(updated);
|
|
544
|
+
} else {
|
|
545
|
+
placeholder._complete = true;
|
|
546
|
+
this.emit("message", finalMsg);
|
|
547
|
+
if (onDone) onDone(finalMsg);
|
|
548
|
+
}
|
|
549
|
+
}, adapterOptions);
|
|
550
|
+
return mergeToEntry || finalMsg;
|
|
551
|
+
}
|
|
552
|
+
/** 非流式结果落位 */
|
|
553
|
+
_handleResult(assistantMsg, mergeToEntry) {
|
|
554
|
+
if (mergeToEntry) {
|
|
555
|
+
const entry = this.messages.getAll().find((m) => m.id === mergeToEntry);
|
|
556
|
+
if (!entry) {
|
|
557
|
+
this.messages.add(assistantMsg);
|
|
558
|
+
this.emit("message", assistantMsg);
|
|
559
|
+
return assistantMsg;
|
|
560
|
+
}
|
|
561
|
+
const changes = {
|
|
562
|
+
content: (entry.content || "") + (assistantMsg.content || ""),
|
|
563
|
+
_complete: true
|
|
564
|
+
};
|
|
565
|
+
if (assistantMsg.reasoningContent) changes.reasoningContent = (entry.reasoningContent || "") + assistantMsg.reasoningContent;
|
|
566
|
+
if (assistantMsg.toolCalls) changes.toolCalls = assistantMsg.toolCalls;
|
|
567
|
+
this.messages.update(mergeToEntry, changes);
|
|
568
|
+
const updated = this.messages.getAll().find((m) => m.id === mergeToEntry);
|
|
569
|
+
this.emit("message", updated);
|
|
570
|
+
return updated;
|
|
571
|
+
}
|
|
572
|
+
this.messages.add(assistantMsg);
|
|
573
|
+
this.emit("message", assistantMsg);
|
|
574
|
+
return assistantMsg;
|
|
575
|
+
}
|
|
576
|
+
async send(userInput) {
|
|
577
|
+
this._abortController = new AbortController();
|
|
578
|
+
try {
|
|
579
|
+
return await this._request({
|
|
580
|
+
userInput,
|
|
581
|
+
addUser: true,
|
|
582
|
+
isStream: false
|
|
583
|
+
});
|
|
584
|
+
} finally {
|
|
585
|
+
this._abortController = null;
|
|
586
|
+
this._isGenerating = false;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
async stream(userInput, onProgress, onDone) {
|
|
590
|
+
this._abortController = new AbortController();
|
|
591
|
+
try {
|
|
592
|
+
return await this._request({
|
|
593
|
+
userInput,
|
|
594
|
+
addUser: true,
|
|
595
|
+
isStream: true,
|
|
596
|
+
onProgress,
|
|
597
|
+
onDone
|
|
598
|
+
});
|
|
599
|
+
} finally {
|
|
600
|
+
this._abortController = null;
|
|
601
|
+
this._isGenerating = false;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
async sendExisting() {
|
|
605
|
+
this._abortController = new AbortController();
|
|
606
|
+
try {
|
|
607
|
+
return await this._request({
|
|
608
|
+
addUser: false,
|
|
609
|
+
isStream: false
|
|
610
|
+
});
|
|
611
|
+
} finally {
|
|
612
|
+
this._abortController = null;
|
|
613
|
+
this._isGenerating = false;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
async sendExistingStream(onProgress, onDone) {
|
|
617
|
+
this._abortController = new AbortController();
|
|
618
|
+
try {
|
|
619
|
+
return await this._request({
|
|
620
|
+
addUser: false,
|
|
621
|
+
isStream: true,
|
|
622
|
+
onProgress,
|
|
623
|
+
onDone
|
|
624
|
+
});
|
|
625
|
+
} finally {
|
|
626
|
+
this._abortController = null;
|
|
627
|
+
this._isGenerating = false;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
//#endregion
|
|
632
|
+
//#region src/utils/url.js
|
|
633
|
+
/**
|
|
634
|
+
* URL 工具函数
|
|
635
|
+
*/
|
|
636
|
+
/**
|
|
637
|
+
* 拼接 baseUrl 和 path
|
|
638
|
+
* 注意:path 应以 '/' 开头,否则会替换 baseUrl 的最后一段
|
|
639
|
+
* @param {string} baseUrl - 基础 URL(如 https://api.deepseek.com)
|
|
640
|
+
* @param {string} path - 路径(如 /v1/chat/completions)
|
|
641
|
+
* @returns {string} 完整的 URL
|
|
642
|
+
*/
|
|
643
|
+
function joinUrl(baseUrl, path) {
|
|
644
|
+
return baseUrl.replace(/\/$/, "") + (path.startsWith("/") ? path : "/" + path);
|
|
2077
645
|
}
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
utils2.extend(instance, Axios.prototype, context);
|
|
2091
|
-
utils2.extend(instance, context);
|
|
2092
|
-
return instance;
|
|
2093
|
-
}
|
|
2094
|
-
var axios2 = createInstance(defaults);
|
|
2095
|
-
axios2.Axios = Axios;
|
|
2096
|
-
axios2.create = function create(instanceConfig) {
|
|
2097
|
-
return createInstance(mergeConfig2(axios2.defaults, instanceConfig));
|
|
2098
|
-
};
|
|
2099
|
-
axios2.Cancel = requireCancel();
|
|
2100
|
-
axios2.CancelToken = requireCancelToken();
|
|
2101
|
-
axios2.isCancel = requireIsCancel();
|
|
2102
|
-
axios2.all = function all(promises) {
|
|
2103
|
-
return Promise.all(promises);
|
|
2104
|
-
};
|
|
2105
|
-
axios2.spread = requireSpread();
|
|
2106
|
-
axios2.isAxiosError = requireIsAxiosError();
|
|
2107
|
-
axios$2.exports = axios2;
|
|
2108
|
-
axios$2.exports.default = axios2;
|
|
2109
|
-
return axios$2.exports;
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region src/utils/typeCheck.js
|
|
648
|
+
/**
|
|
649
|
+
* 类型判断工具
|
|
650
|
+
*/
|
|
651
|
+
/**
|
|
652
|
+
* 判断一个值是否为字符串
|
|
653
|
+
* @param {any} value - 要检查的值
|
|
654
|
+
* @returns {boolean} 如果是字符串则返回 true
|
|
655
|
+
*/
|
|
656
|
+
function isString(value) {
|
|
657
|
+
return typeof value === "string";
|
|
2110
658
|
}
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
659
|
+
//#endregion
|
|
660
|
+
//#region src/utils/MessageFormatter.js
|
|
661
|
+
/**
|
|
662
|
+
* MessageFormatter — 可注册的消息格式转换器
|
|
663
|
+
*
|
|
664
|
+
* 职责:
|
|
665
|
+
* 1. 内置 OpenA I兼容格式的转换逻辑
|
|
666
|
+
* 2. 支持 register(name, fn) 注册自定义格式(如 Anthropic、Gemini 等)
|
|
667
|
+
* 3. 统一处理 capabilities 过滤(reasoning、vision 等)
|
|
668
|
+
* 4. 所有适配器通过此工具获取 API 消息数组,消除重复代码
|
|
669
|
+
*
|
|
670
|
+
* 用法:
|
|
671
|
+
* import { MessageFormatter } from 'my-ai-chat-framework';
|
|
672
|
+
*
|
|
673
|
+
* // 使用内置格式
|
|
674
|
+
* const msgs = MessageFormatter.format({
|
|
675
|
+
* messages, systemPrompts, capabilities, resolveImage
|
|
676
|
+
* }); // 默认 'openai'
|
|
677
|
+
*
|
|
678
|
+
* // 注册自定义格式
|
|
679
|
+
* MessageFormatter.register('anthropic', ({ messages, systemPrompts, capabilities }) => {
|
|
680
|
+
* // 返回 Anthropic 格式的消息数组
|
|
681
|
+
* });
|
|
682
|
+
*/
|
|
683
|
+
var IS_URL = /^https?:\/\//i;
|
|
684
|
+
function defaultResolveImage(imageId) {
|
|
685
|
+
if (IS_URL.test(imageId)) return { url: imageId };
|
|
686
|
+
return null;
|
|
2118
687
|
}
|
|
2119
|
-
|
|
2120
|
-
const
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
throw new Error("无效的API Key");
|
|
2141
|
-
}
|
|
2142
|
-
this.apiKey = apiKey;
|
|
2143
|
-
this.axiosInstance.defaults.headers["Authorization"] = `Bearer ${apiKey}`;
|
|
2144
|
-
}
|
|
2145
|
-
setApiUrl(apiUrl) {
|
|
2146
|
-
if (!apiUrl || typeof apiUrl !== "string") {
|
|
2147
|
-
throw new Error("无效的API URL");
|
|
2148
|
-
}
|
|
2149
|
-
this.url = apiUrl;
|
|
2150
|
-
this.axiosInstance.defaults.baseURL = apiUrl;
|
|
2151
|
-
}
|
|
2152
|
-
async send(body) {
|
|
2153
|
-
this.isGenerating = true;
|
|
2154
|
-
this.cancelTokenSource = axios.CancelToken.source();
|
|
2155
|
-
try {
|
|
2156
|
-
this.emit("request-start", { body });
|
|
2157
|
-
const requestBody = this._buildRequestBody(body);
|
|
2158
|
-
const response = await this.axiosInstance.post("", requestBody, {
|
|
2159
|
-
cancelToken: this.cancelTokenSource.token
|
|
2160
|
-
});
|
|
2161
|
-
this.emit("request-success", { response: response.data });
|
|
2162
|
-
return response.data;
|
|
2163
|
-
} catch (error) {
|
|
2164
|
-
if (axios.isCancel(error)) {
|
|
2165
|
-
const cancelError = new Error("请求被中断");
|
|
2166
|
-
cancelError.name = "CancelError";
|
|
2167
|
-
this.emit("request-cancel", { error: cancelError });
|
|
2168
|
-
throw cancelError;
|
|
2169
|
-
}
|
|
2170
|
-
this.emit("request-error", { error });
|
|
2171
|
-
throw this._handleAxiosError(error);
|
|
2172
|
-
} finally {
|
|
2173
|
-
this.isGenerating = false;
|
|
2174
|
-
this.cancelTokenSource = null;
|
|
2175
|
-
}
|
|
2176
|
-
}
|
|
2177
|
-
async strSend(body, onProgress, onDone) {
|
|
2178
|
-
this.isGenerating = true;
|
|
2179
|
-
this.cancelTokenSource = axios.CancelToken.source();
|
|
2180
|
-
try {
|
|
2181
|
-
const safeOnProgress = typeof onProgress === "function" ? onProgress : () => {
|
|
2182
|
-
};
|
|
2183
|
-
const safeOnDone = typeof onDone === "function" ? onDone : () => {
|
|
2184
|
-
};
|
|
2185
|
-
this.emit("stream-start", { body });
|
|
2186
|
-
const requestBody = this._buildRequestBody(body);
|
|
2187
|
-
const response = await fetch(this.url, {
|
|
2188
|
-
method: "POST",
|
|
2189
|
-
headers: {
|
|
2190
|
-
"Content-Type": "application/json",
|
|
2191
|
-
"Authorization": `Bearer ${this.apiKey}`,
|
|
2192
|
-
"Accept": "text/event-stream"
|
|
2193
|
-
},
|
|
2194
|
-
body: requestBody,
|
|
2195
|
-
signal: this.cancelTokenSource.token ? new AbortController().signal : void 0
|
|
2196
|
-
});
|
|
2197
|
-
if (!response.ok) {
|
|
2198
|
-
throw new Error(`HTTP错误: ${response.status}`);
|
|
2199
|
-
}
|
|
2200
|
-
const reader = response.body.getReader();
|
|
2201
|
-
const decoder = new TextDecoder();
|
|
2202
|
-
let buffer = "";
|
|
2203
|
-
const message = {
|
|
2204
|
-
// 基础信息(符合Messages格式)
|
|
2205
|
-
role: "assistant",
|
|
2206
|
-
content: "",
|
|
2207
|
-
reasoning_content: "",
|
|
2208
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
2209
|
-
// 工具调用
|
|
2210
|
-
tool_calls: [],
|
|
2211
|
-
// 流式元数据
|
|
2212
|
-
streamMetadata: {
|
|
2213
|
-
chunkCount: 0,
|
|
2214
|
-
firstChunkTime: Date.now(),
|
|
2215
|
-
lastChunkTime: null,
|
|
2216
|
-
isStreaming: true
|
|
2217
|
-
}
|
|
2218
|
-
};
|
|
2219
|
-
while (true) {
|
|
2220
|
-
const { done, value } = await reader.read();
|
|
2221
|
-
if (done) break;
|
|
2222
|
-
buffer += decoder.decode(value, { stream: true });
|
|
2223
|
-
let lines = buffer.split(/(\r?\n){2,}/);
|
|
2224
|
-
buffer = lines.pop() || "";
|
|
2225
|
-
for (let rawChunk of lines) {
|
|
2226
|
-
const cleanChunk = rawChunk.trim().replace(/^data: /, "");
|
|
2227
|
-
if (!cleanChunk) continue;
|
|
2228
|
-
if (cleanChunk === "[DONE]") {
|
|
2229
|
-
this.emit("stream-done", { message });
|
|
2230
|
-
safeOnDone({ ...message });
|
|
2231
|
-
return;
|
|
2232
|
-
}
|
|
2233
|
-
try {
|
|
2234
|
-
const obj = JSON.parse(cleanChunk);
|
|
2235
|
-
console.log("🔍 收到流式chunk:", obj);
|
|
2236
|
-
message.streamMetadata.chunkCount++;
|
|
2237
|
-
message.streamMetadata.lastChunkTime = Date.now();
|
|
2238
|
-
if (obj.choices?.[0]?.delta?.content) {
|
|
2239
|
-
message.content += obj.choices[0].delta.content;
|
|
2240
|
-
}
|
|
2241
|
-
if (obj.choices?.[0]?.delta?.reasoning_content) {
|
|
2242
|
-
message.reasoning_content += obj.choices[0].delta.reasoning_content;
|
|
2243
|
-
}
|
|
2244
|
-
if (obj.choices?.[0]?.delta?.tool_calls) {
|
|
2245
|
-
const deltaToolCalls = obj.choices[0].delta.tool_calls;
|
|
2246
|
-
deltaToolCalls.forEach((toolCall) => {
|
|
2247
|
-
const index2 = toolCall.index || 0;
|
|
2248
|
-
if (!message.tool_calls) message.tool_calls = [];
|
|
2249
|
-
if (!message.tool_calls[index2]) {
|
|
2250
|
-
message.tool_calls[index2] = {
|
|
2251
|
-
id: "",
|
|
2252
|
-
type: "function",
|
|
2253
|
-
function: { name: "", arguments: "" }
|
|
2254
|
-
};
|
|
2255
|
-
}
|
|
2256
|
-
if (toolCall.id) message.tool_calls[index2].id = toolCall.id;
|
|
2257
|
-
if (toolCall.type) message.tool_calls[index2].type = toolCall.type;
|
|
2258
|
-
if (toolCall.function?.name) {
|
|
2259
|
-
message.tool_calls[index2].function.name += toolCall.function.name;
|
|
2260
|
-
}
|
|
2261
|
-
if (toolCall.function?.arguments) {
|
|
2262
|
-
message.tool_calls[index2].function.arguments += toolCall.function.arguments;
|
|
2263
|
-
}
|
|
2264
|
-
});
|
|
2265
|
-
}
|
|
2266
|
-
this.emit("stream-chunk", {
|
|
2267
|
-
chunk: obj,
|
|
2268
|
-
message: { ...message }
|
|
2269
|
-
// 发送副本
|
|
2270
|
-
});
|
|
2271
|
-
safeOnProgress({ ...message });
|
|
2272
|
-
} catch (e) {
|
|
2273
|
-
console.error("🔍 解析chunk错误:", e, "原始数据:", cleanChunk);
|
|
2274
|
-
}
|
|
2275
|
-
}
|
|
2276
|
-
if (!this.isGenerating) {
|
|
2277
|
-
break;
|
|
2278
|
-
}
|
|
2279
|
-
}
|
|
2280
|
-
message.streamMetadata.isStreaming = false;
|
|
2281
|
-
message.streamMetadata.completedAt = /* @__PURE__ */ new Date();
|
|
2282
|
-
this.emit("stream-done", { message: { ...message } });
|
|
2283
|
-
safeOnDone({ ...message });
|
|
2284
|
-
} catch (error) {
|
|
2285
|
-
if (error.name === "AbortError" || axios.isCancel(error)) {
|
|
2286
|
-
const cancelError = new Error("请求被中断");
|
|
2287
|
-
cancelError.name = "CancelError";
|
|
2288
|
-
this.emit("stream-cancel", { error: cancelError });
|
|
2289
|
-
throw cancelError;
|
|
2290
|
-
}
|
|
2291
|
-
this.emit("stream-error", { error });
|
|
2292
|
-
throw error;
|
|
2293
|
-
} finally {
|
|
2294
|
-
this.isGenerating = false;
|
|
2295
|
-
this.cancelTokenSource = null;
|
|
2296
|
-
}
|
|
2297
|
-
}
|
|
2298
|
-
interrupt() {
|
|
2299
|
-
if (this.isGenerating && this.cancelTokenSource) {
|
|
2300
|
-
this.cancelTokenSource.cancel("用户中断请求");
|
|
2301
|
-
this.isGenerating = false;
|
|
2302
|
-
}
|
|
2303
|
-
}
|
|
2304
|
-
_buildRequestBody(body) {
|
|
2305
|
-
if (typeof body?.toJSON === "function") {
|
|
2306
|
-
return body.toJSON();
|
|
2307
|
-
} else if (typeof body === "object" && body !== null) {
|
|
2308
|
-
return JSON.stringify(body);
|
|
2309
|
-
} else if (typeof body === "string") {
|
|
2310
|
-
try {
|
|
2311
|
-
JSON.parse(body);
|
|
2312
|
-
return body;
|
|
2313
|
-
} catch {
|
|
2314
|
-
throw new Error("字符串不是有效的JSON格式");
|
|
2315
|
-
}
|
|
2316
|
-
} else {
|
|
2317
|
-
throw new Error("无效的请求体类型,应传入对象或JSON字符串");
|
|
2318
|
-
}
|
|
2319
|
-
}
|
|
2320
|
-
_handleAxiosError(error) {
|
|
2321
|
-
if (error.response) {
|
|
2322
|
-
const status = error.response.status;
|
|
2323
|
-
const data = error.response.data;
|
|
2324
|
-
let message = `API错误 ${status}`;
|
|
2325
|
-
if (data?.error?.message) {
|
|
2326
|
-
message += `: ${data.error.message}`;
|
|
2327
|
-
}
|
|
2328
|
-
return new Error(message);
|
|
2329
|
-
} else if (error.request) {
|
|
2330
|
-
return new Error("网络错误:无法连接到API服务器");
|
|
2331
|
-
} else {
|
|
2332
|
-
return error;
|
|
2333
|
-
}
|
|
2334
|
-
}
|
|
2335
|
-
static parseCompatible(obj) {
|
|
2336
|
-
if (obj?.__format_version === 1 && obj.payload) {
|
|
2337
|
-
return {
|
|
2338
|
-
messages: obj.payload.messages || [],
|
|
2339
|
-
systems: obj.payload.systems || [],
|
|
2340
|
-
hintData: obj.payload.hintData || {
|
|
2341
|
-
name: "",
|
|
2342
|
-
toolState: {
|
|
2343
|
-
currentTime: "同步失败",
|
|
2344
|
-
currentTime_TS: 0
|
|
2345
|
-
}
|
|
2346
|
-
},
|
|
2347
|
-
tools: obj.payload.tools || []
|
|
2348
|
-
};
|
|
2349
|
-
}
|
|
2350
|
-
if (obj?.messages && Array.isArray(obj.messages)) {
|
|
2351
|
-
return {
|
|
2352
|
-
messages: obj.messages || [],
|
|
2353
|
-
systems: obj.systems || [],
|
|
2354
|
-
hintData: obj.hintData || {
|
|
2355
|
-
name: "",
|
|
2356
|
-
toolState: {
|
|
2357
|
-
currentTime: "同步失败",
|
|
2358
|
-
currentTime_TS: 0
|
|
2359
|
-
}
|
|
2360
|
-
},
|
|
2361
|
-
tools: obj.tools || []
|
|
2362
|
-
};
|
|
2363
|
-
}
|
|
2364
|
-
throw new Error("无法识别的聊天数据格式");
|
|
2365
|
-
}
|
|
688
|
+
function buildMultimodalContent(textContent, images, resolveImage) {
|
|
689
|
+
const content = [{
|
|
690
|
+
type: "text",
|
|
691
|
+
text: textContent
|
|
692
|
+
}];
|
|
693
|
+
for (const ref of images) {
|
|
694
|
+
const resolved = resolveImage(ref);
|
|
695
|
+
if (!resolved) continue;
|
|
696
|
+
if (resolved.url) content.push({
|
|
697
|
+
type: "image_url",
|
|
698
|
+
image_url: { url: resolved.url }
|
|
699
|
+
});
|
|
700
|
+
else if (resolved.data) {
|
|
701
|
+
const mime = resolved.mimeType || "image/png";
|
|
702
|
+
content.push({
|
|
703
|
+
type: "image_url",
|
|
704
|
+
image_url: { url: `data:${mime};base64,${resolved.data}` }
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return content;
|
|
2366
709
|
}
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
* 触发配置变更
|
|
2427
|
-
*/
|
|
2428
|
-
_triggerChange(path, oldValue, newValue) {
|
|
2429
|
-
this.emit("config-changed", {
|
|
2430
|
-
path,
|
|
2431
|
-
oldValue,
|
|
2432
|
-
newValue,
|
|
2433
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2434
|
-
});
|
|
2435
|
-
this.emit(`config-changed:${path}`, {
|
|
2436
|
-
oldValue,
|
|
2437
|
-
newValue,
|
|
2438
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2439
|
-
});
|
|
2440
|
-
const handlers = this._handlers.get(path);
|
|
2441
|
-
if (handlers) {
|
|
2442
|
-
handlers.forEach((handler) => {
|
|
2443
|
-
try {
|
|
2444
|
-
handler(newValue, oldValue, path);
|
|
2445
|
-
} catch (error) {
|
|
2446
|
-
console.error(`配置处理器执行失败 (${path}):`, error);
|
|
2447
|
-
}
|
|
2448
|
-
});
|
|
2449
|
-
}
|
|
2450
|
-
const pathParts = path.split(".");
|
|
2451
|
-
for (let i = pathParts.length - 1; i >= 0; i--) {
|
|
2452
|
-
const parentPath = pathParts.slice(0, i).join(".");
|
|
2453
|
-
const wildcardPath = parentPath ? `${parentPath}.*` : "*";
|
|
2454
|
-
const parentHandlers = this._handlers.get(wildcardPath);
|
|
2455
|
-
if (parentHandlers) {
|
|
2456
|
-
parentHandlers.forEach((handler) => {
|
|
2457
|
-
try {
|
|
2458
|
-
handler(newValue, oldValue, path);
|
|
2459
|
-
} catch (error) {
|
|
2460
|
-
console.error(`通配符处理器执行失败 (${wildcardPath}):`, error);
|
|
2461
|
-
}
|
|
2462
|
-
});
|
|
2463
|
-
}
|
|
2464
|
-
}
|
|
2465
|
-
}
|
|
2466
|
-
/**
|
|
2467
|
-
* 获取配置快照(非代理版本)
|
|
2468
|
-
*/
|
|
2469
|
-
getSnapshot() {
|
|
2470
|
-
return JSON.parse(JSON.stringify(this._config));
|
|
2471
|
-
}
|
|
2472
|
-
/**
|
|
2473
|
-
* 批量更新配置
|
|
2474
|
-
*/
|
|
2475
|
-
update(newConfig) {
|
|
2476
|
-
Object.keys(newConfig).forEach((key) => {
|
|
2477
|
-
this.config[key] = newConfig[key];
|
|
2478
|
-
});
|
|
2479
|
-
return this;
|
|
2480
|
-
}
|
|
2481
|
-
/**
|
|
2482
|
-
* 重置为默认值
|
|
2483
|
-
*/
|
|
2484
|
-
reset() {
|
|
2485
|
-
const oldConfig = this.getSnapshot();
|
|
2486
|
-
this._config = JSON.parse(JSON.stringify(this._defaultConfig));
|
|
2487
|
-
this.config = this._createProxy(this._config);
|
|
2488
|
-
this.emit("config-reset", {
|
|
2489
|
-
oldConfig,
|
|
2490
|
-
newConfig: this.getSnapshot(),
|
|
2491
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2492
|
-
});
|
|
2493
|
-
return this;
|
|
2494
|
-
}
|
|
710
|
+
/** OpenAI 兼容格式 */
|
|
711
|
+
function toOpenAI({ messages, systemPrompts, capabilities, resolveImage }) {
|
|
712
|
+
const rImg = typeof resolveImage === "function" ? resolveImage : defaultResolveImage;
|
|
713
|
+
const result = [];
|
|
714
|
+
for (const sp of systemPrompts) if (sp?.content && isString(sp.content) && sp.content.trim()) result.push({
|
|
715
|
+
role: "system",
|
|
716
|
+
content: sp.content.trim()
|
|
717
|
+
});
|
|
718
|
+
let ephemEnd = messages.length;
|
|
719
|
+
for (let i = messages.length - 1; i >= 0; i--) if (messages[i]._ephemeral) ephemEnd = i;
|
|
720
|
+
else break;
|
|
721
|
+
for (let i = 0; i < messages.length; i++) {
|
|
722
|
+
const msg = messages[i];
|
|
723
|
+
if (msg._ephemeral) {
|
|
724
|
+
if (i < ephemEnd) continue;
|
|
725
|
+
}
|
|
726
|
+
if (msg.role === "system" && !msg._ephemeral) continue;
|
|
727
|
+
if (msg.role === "tool") {
|
|
728
|
+
result.push({
|
|
729
|
+
role: "tool",
|
|
730
|
+
content: msg.content || "",
|
|
731
|
+
tool_call_id: msg.toolCallId
|
|
732
|
+
});
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (msg.role === "assistant" && msg.toolCalls?.length) {
|
|
736
|
+
const entry = {
|
|
737
|
+
role: "assistant",
|
|
738
|
+
content: msg.content || "",
|
|
739
|
+
tool_calls: msg.toolCalls
|
|
740
|
+
};
|
|
741
|
+
if (msg.prefix) entry.prefix = true;
|
|
742
|
+
if (capabilities?.reasoning && msg.reasoningContent) entry.reasoning_content = msg.reasoningContent;
|
|
743
|
+
result.push(entry);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
const hasText = msg.content && isString(msg.content) && msg.content.trim();
|
|
747
|
+
const hasImages = msg.images && Array.isArray(msg.images) && msg.images.length > 0;
|
|
748
|
+
if (!hasText && !hasImages) {
|
|
749
|
+
if (msg.role === "assistant" && msg.prefix) {
|
|
750
|
+
const prefixEntry = {
|
|
751
|
+
role: "assistant",
|
|
752
|
+
content: "",
|
|
753
|
+
prefix: true
|
|
754
|
+
};
|
|
755
|
+
if (capabilities?.reasoning && msg.reasoningContent) prefixEntry.reasoning_content = msg.reasoningContent;
|
|
756
|
+
result.push(prefixEntry);
|
|
757
|
+
}
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
const entry = { role: msg.role };
|
|
761
|
+
if (hasImages) {
|
|
762
|
+
if (!capabilities?.vision) throw new Error("[MessageFormatter] 消息包含图片但模型不支持视觉(capabilities.vision=false)。请切换模型或移除图片。");
|
|
763
|
+
entry.content = buildMultimodalContent(msg.content || "", msg.images, rImg);
|
|
764
|
+
} else entry.content = msg.content;
|
|
765
|
+
if (msg.prefix) entry.prefix = true;
|
|
766
|
+
result.push(entry);
|
|
767
|
+
}
|
|
768
|
+
return result;
|
|
2495
769
|
}
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
770
|
+
var MessageFormatter = {
|
|
771
|
+
_formats: new Map([["openai", toOpenAI]]),
|
|
772
|
+
register(name, fn) {
|
|
773
|
+
if (!name || typeof name !== "string" || !name.trim()) throw new Error("[MessageFormatter] 格式名称必须是非空字符串");
|
|
774
|
+
if (typeof fn !== "function") throw new Error("[MessageFormatter] 转换函数必须是 function");
|
|
775
|
+
this._formats.set(name.trim(), fn);
|
|
776
|
+
},
|
|
777
|
+
unregister(name) {
|
|
778
|
+
if (name === "openai") throw new Error("[MessageFormatter] 内置格式 \"openai\" 不可移除");
|
|
779
|
+
this._formats.delete(name);
|
|
780
|
+
},
|
|
781
|
+
listFormats() {
|
|
782
|
+
return [...this._formats.keys()];
|
|
783
|
+
},
|
|
784
|
+
format(options = {}) {
|
|
785
|
+
const formatName = options.format || "openai";
|
|
786
|
+
const fn = this._formats.get(formatName);
|
|
787
|
+
if (!fn) throw new Error(`[MessageFormatter] 未知格式 "${formatName}"。可用格式: ${[...this._formats.keys()].join(", ")}`);
|
|
788
|
+
return fn({
|
|
789
|
+
messages: options.messages || [],
|
|
790
|
+
systemPrompts: options.systemPrompts || [],
|
|
791
|
+
capabilities: options.capabilities || {},
|
|
792
|
+
resolveImage: options.resolveImage
|
|
793
|
+
});
|
|
794
|
+
}
|
|
2514
795
|
};
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
...defaultConfig,
|
|
2521
|
-
...options
|
|
2522
|
-
});
|
|
2523
|
-
this.messages = new Messages();
|
|
2524
|
-
this.apiClient = new ApiClient(
|
|
2525
|
-
this.configManager.config.api.key,
|
|
2526
|
-
this.configManager.config.api.url
|
|
2527
|
-
);
|
|
2528
|
-
this.requestBuilder = new RequestBuilder(
|
|
2529
|
-
this.configManager.config.model.name,
|
|
2530
|
-
this.messages,
|
|
2531
|
-
{
|
|
2532
|
-
temperature: this.configManager.config.model.temperature,
|
|
2533
|
-
max_tokens: this.configManager.config.model.maxTokens,
|
|
2534
|
-
stream: this.configManager.config.model.stream,
|
|
2535
|
-
reasoning_effort: this.configManager.config.model.reasoningEffort
|
|
2536
|
-
}
|
|
2537
|
-
);
|
|
2538
|
-
this.toolManager = new ToolManager();
|
|
2539
|
-
this._setupConfigHandlers();
|
|
2540
|
-
this._setupDefaultListeners();
|
|
2541
|
-
}
|
|
2542
|
-
/**
|
|
2543
|
-
* 设置配置变更处理器
|
|
2544
|
-
*/
|
|
2545
|
-
_setupConfigHandlers() {
|
|
2546
|
-
this.configManager.registerHandler("api.key", (newValue) => {
|
|
2547
|
-
this.apiClient.setApiKey(newValue);
|
|
2548
|
-
});
|
|
2549
|
-
this.configManager.registerHandler("api.url", (newValue) => {
|
|
2550
|
-
this.apiClient.setApiUrl(newValue);
|
|
2551
|
-
});
|
|
2552
|
-
this.configManager.registerHandler("model.name", (newValue) => {
|
|
2553
|
-
this.requestBuilder.model = newValue;
|
|
2554
|
-
});
|
|
2555
|
-
this.configManager.registerHandler("model.temperature", (newValue) => {
|
|
2556
|
-
this.requestBuilder.config.temperature = newValue;
|
|
2557
|
-
});
|
|
2558
|
-
this.configManager.registerHandler("model.stream", (newValue) => {
|
|
2559
|
-
this.requestBuilder.config.stream = newValue;
|
|
2560
|
-
});
|
|
2561
|
-
this.configManager.registerHandler("debug", (newValue) => {
|
|
2562
|
-
if (newValue) {
|
|
2563
|
-
console.log("🔧 调试模式已启用");
|
|
2564
|
-
}
|
|
2565
|
-
});
|
|
2566
|
-
this.configManager.on("config-changed", (data) => {
|
|
2567
|
-
this.emit("service-config-changed", data);
|
|
2568
|
-
});
|
|
2569
|
-
}
|
|
2570
|
-
/**
|
|
2571
|
-
* 便捷方法:快速设置 API
|
|
2572
|
-
*/
|
|
2573
|
-
setApi(key, url) {
|
|
2574
|
-
this.configManager.update({
|
|
2575
|
-
api: { key, url }
|
|
2576
|
-
});
|
|
2577
|
-
return this;
|
|
2578
|
-
}
|
|
2579
|
-
/**
|
|
2580
|
-
* 便捷方法:快速设置模型
|
|
2581
|
-
*/
|
|
2582
|
-
setModel(name, temperature = 0.7) {
|
|
2583
|
-
this.configManager.update({
|
|
2584
|
-
model: { name, temperature }
|
|
2585
|
-
});
|
|
2586
|
-
return this;
|
|
2587
|
-
}
|
|
2588
|
-
_setupDefaultListeners() {
|
|
2589
|
-
this.apiClient.on("request-start", (data) => {
|
|
2590
|
-
this.emit("request-start", data);
|
|
2591
|
-
});
|
|
2592
|
-
this.apiClient.on("request-success", (data) => {
|
|
2593
|
-
this.emit("request-success", data);
|
|
2594
|
-
});
|
|
2595
|
-
this.apiClient.on("request-error", (data) => {
|
|
2596
|
-
this.emit("request-error", data);
|
|
2597
|
-
});
|
|
2598
|
-
this.apiClient.on("stream-chunk", (data) => {
|
|
2599
|
-
this.emit("stream-chunk", data);
|
|
2600
|
-
});
|
|
2601
|
-
this.toolManager.on("tool-execute-start", (data) => {
|
|
2602
|
-
this.emit("tool-execute-start", data);
|
|
2603
|
-
});
|
|
2604
|
-
this.toolManager.on("tool-execute-success", (data) => {
|
|
2605
|
-
this.emit("tool-execute-success", data);
|
|
2606
|
-
});
|
|
2607
|
-
this.toolManager.on("tool-execute-error", (data) => {
|
|
2608
|
-
this.emit("tool-execute-error", data);
|
|
2609
|
-
});
|
|
2610
|
-
}
|
|
2611
|
-
/**
|
|
2612
|
-
* 注册工具
|
|
2613
|
-
*/
|
|
2614
|
-
registerTool(name, definition, executor) {
|
|
2615
|
-
this.toolManager.registerTool(name, definition, executor);
|
|
2616
|
-
this.messages.addTool(definition);
|
|
2617
|
-
return this;
|
|
2618
|
-
}
|
|
2619
|
-
/**
|
|
2620
|
-
* 发送消息(支持工具调用)
|
|
2621
|
-
*/
|
|
2622
|
-
async send(userMessage, options = {}) {
|
|
2623
|
-
try {
|
|
2624
|
-
this.emit("sending", {
|
|
2625
|
-
role: "user",
|
|
2626
|
-
content: userMessage,
|
|
2627
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
2628
|
-
eventType: "sending"
|
|
2629
|
-
});
|
|
2630
|
-
this.messages.addUserMessage(userMessage);
|
|
2631
|
-
const requestBody = this.requestBuilder.toJSON(
|
|
2632
|
-
options.baseRounds,
|
|
2633
|
-
options.cycleRounds
|
|
2634
|
-
);
|
|
2635
|
-
const response = await this.apiClient.send(requestBody);
|
|
2636
|
-
const aiMessage = response.choices[0].message;
|
|
2637
|
-
if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {
|
|
2638
|
-
return await this._handleToolCalls(aiMessage);
|
|
2639
|
-
} else {
|
|
2640
|
-
const eventData = await this._handleNormalResponse(aiMessage);
|
|
2641
|
-
return eventData.content;
|
|
2642
|
-
}
|
|
2643
|
-
} catch (error) {
|
|
2644
|
-
this.emit("error", {
|
|
2645
|
-
error,
|
|
2646
|
-
message: userMessage,
|
|
2647
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2648
|
-
});
|
|
2649
|
-
throw error;
|
|
2650
|
-
}
|
|
2651
|
-
}
|
|
2652
|
-
/**
|
|
2653
|
-
* 处理工具调用(支持循环调用)
|
|
2654
|
-
*/
|
|
2655
|
-
async _handleToolCalls(aiMessage, maxIterations = 5) {
|
|
2656
|
-
let iteration = 0;
|
|
2657
|
-
let currentMessage = aiMessage;
|
|
2658
|
-
while (iteration < maxIterations) {
|
|
2659
|
-
iteration++;
|
|
2660
|
-
this.messages.addAssistantMessage(currentMessage.content || "", {
|
|
2661
|
-
tool_calls: currentMessage.tool_calls,
|
|
2662
|
-
reasoning_content: currentMessage.reasoning_content || ""
|
|
2663
|
-
// ✅ 新增:保存思考内容
|
|
2664
|
-
});
|
|
2665
|
-
this.emit("tool-call-requested", {
|
|
2666
|
-
tool_calls: currentMessage.tool_calls,
|
|
2667
|
-
reasoning_content: currentMessage.reasoning_content,
|
|
2668
|
-
// ✅ 新增:包含思考内容
|
|
2669
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
2670
|
-
iteration
|
|
2671
|
-
});
|
|
2672
|
-
const toolResults = await this.toolManager.executeToolCalls(currentMessage.tool_calls);
|
|
2673
|
-
for (const result of toolResults) {
|
|
2674
|
-
this.messages.addToolMessage(
|
|
2675
|
-
result.result || result.error || "",
|
|
2676
|
-
result.tool_call_id
|
|
2677
|
-
);
|
|
2678
|
-
}
|
|
2679
|
-
const requestBody = this.requestBuilder.toJSON();
|
|
2680
|
-
const response = await this.apiClient.send(requestBody);
|
|
2681
|
-
currentMessage = response.choices[0].message;
|
|
2682
|
-
if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
|
|
2683
|
-
break;
|
|
2684
|
-
}
|
|
2685
|
-
}
|
|
2686
|
-
const eventData = await this._handleAssistantResponse(currentMessage, {
|
|
2687
|
-
toolIterations: iteration
|
|
2688
|
-
});
|
|
2689
|
-
return eventData.content;
|
|
2690
|
-
}
|
|
2691
|
-
/**
|
|
2692
|
-
* 处理助手回复(统一方法,用于普通和流式请求)
|
|
2693
|
-
*/
|
|
2694
|
-
async _handleAssistantResponse(aiMessage, options = {}) {
|
|
2695
|
-
const { isStreaming = false, toolIterations = 0, skipAddMessage = false } = options;
|
|
2696
|
-
const shouldAddMessage = this.autoAddMessages && !skipAddMessage;
|
|
2697
|
-
if (shouldAddMessage) {
|
|
2698
|
-
this.messages.addAssistantMessage(aiMessage.content || "", {
|
|
2699
|
-
reasoning_content: aiMessage.reasoning_content
|
|
2700
|
-
});
|
|
2701
|
-
}
|
|
2702
|
-
const eventData = {
|
|
2703
|
-
// 基础字段(Messages格式)
|
|
2704
|
-
role: "assistant",
|
|
2705
|
-
content: aiMessage.content || "",
|
|
2706
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
2707
|
-
// 扩展字段
|
|
2708
|
-
...aiMessage.reasoning_content && { reasoning_content: aiMessage.reasoning_content },
|
|
2709
|
-
...aiMessage.tool_calls && { tool_calls: aiMessage.tool_calls },
|
|
2710
|
-
...aiMessage.tool_call_id && { tool_call_id: aiMessage.tool_call_id },
|
|
2711
|
-
// 框架元数据
|
|
2712
|
-
isStreaming,
|
|
2713
|
-
toolIterations,
|
|
2714
|
-
eventType: isStreaming ? "stream-complete" : "response-complete",
|
|
2715
|
-
// 保留原始响应(只有普通请求有)
|
|
2716
|
-
...isStreaming ? {} : {
|
|
2717
|
-
response: { choices: [{ message: aiMessage }] }
|
|
2718
|
-
}
|
|
2719
|
-
};
|
|
2720
|
-
this.emit("message", eventData);
|
|
2721
|
-
return eventData;
|
|
2722
|
-
}
|
|
2723
|
-
/**
|
|
2724
|
-
* 处理普通回复
|
|
2725
|
-
*/
|
|
2726
|
-
async _handleNormalResponse(aiMessage) {
|
|
2727
|
-
return await this._handleAssistantResponse(aiMessage);
|
|
2728
|
-
}
|
|
2729
|
-
/**
|
|
2730
|
-
* 流式发送消息(支持工具调用)
|
|
2731
|
-
*/
|
|
2732
|
-
async stream(userMessage, onProgress, onDone, options = {}) {
|
|
2733
|
-
try {
|
|
2734
|
-
this.emit("sending", {
|
|
2735
|
-
role: "user",
|
|
2736
|
-
content: userMessage,
|
|
2737
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
2738
|
-
eventType: "sending"
|
|
2739
|
-
});
|
|
2740
|
-
this.messages.addUserMessage(userMessage);
|
|
2741
|
-
const requestBuilder = new RequestBuilder(this.requestBuilder.model, this.messages, {
|
|
2742
|
-
...this.requestBuilder.config,
|
|
2743
|
-
stream: true
|
|
2744
|
-
// ✅ 必须设置为true!
|
|
2745
|
-
});
|
|
2746
|
-
const requestBody = requestBuilder.toJSON(
|
|
2747
|
-
options.baseRounds,
|
|
2748
|
-
options.cycleRounds
|
|
2749
|
-
);
|
|
2750
|
-
const response = await this.apiClient.strSend(
|
|
2751
|
-
requestBody,
|
|
2752
|
-
// 如果 onProgress 是函数就调用,否则用空函数
|
|
2753
|
-
typeof onProgress === "function" ? (chunk) => {
|
|
2754
|
-
this.emit("stream-progress", chunk);
|
|
2755
|
-
onProgress(chunk);
|
|
2756
|
-
} : (chunk) => {
|
|
2757
|
-
this.emit("stream-progress", chunk);
|
|
2758
|
-
},
|
|
2759
|
-
typeof onDone === "function" ? async (finalMessage) => {
|
|
2760
|
-
if (finalMessage.tool_calls && finalMessage.tool_calls.length > 0) {
|
|
2761
|
-
await this._handleStreamToolCalls(finalMessage, onProgress, onDone);
|
|
2762
|
-
} else {
|
|
2763
|
-
const eventData = await this._handleAssistantResponse(finalMessage, {
|
|
2764
|
-
isStreaming: true,
|
|
2765
|
-
skipAddMessage: true
|
|
2766
|
-
});
|
|
2767
|
-
onDone(eventData);
|
|
2768
|
-
}
|
|
2769
|
-
} : async (finalMessage) => {
|
|
2770
|
-
if (finalMessage.tool_calls && finalMessage.tool_calls.length > 0) {
|
|
2771
|
-
await this._handleStreamToolCalls(finalMessage);
|
|
2772
|
-
} else {
|
|
2773
|
-
await this._handleAssistantResponse(finalMessage, {
|
|
2774
|
-
isStreaming: true,
|
|
2775
|
-
skipAddMessage: true
|
|
2776
|
-
});
|
|
2777
|
-
}
|
|
2778
|
-
}
|
|
2779
|
-
);
|
|
2780
|
-
return response;
|
|
2781
|
-
} catch (error) {
|
|
2782
|
-
this.emit("error", {
|
|
2783
|
-
error,
|
|
2784
|
-
message: userMessage,
|
|
2785
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2786
|
-
});
|
|
2787
|
-
throw error;
|
|
2788
|
-
}
|
|
2789
|
-
}
|
|
2790
|
-
/**
|
|
2791
|
-
* 处理流式传输中的工具调用(支持循环调用)
|
|
2792
|
-
*/
|
|
2793
|
-
async _handleStreamToolCalls(aiMessage, onProgress, onDone, maxIterations = 5) {
|
|
2794
|
-
let iteration = 0;
|
|
2795
|
-
let currentMessage = aiMessage;
|
|
2796
|
-
while (iteration < maxIterations) {
|
|
2797
|
-
iteration++;
|
|
2798
|
-
this.messages.addAssistantMessage(currentMessage.content || "", {
|
|
2799
|
-
tool_calls: currentMessage.tool_calls,
|
|
2800
|
-
reasoning_content: currentMessage.reasoning_content || ""
|
|
2801
|
-
// ✅ 新增:保存思考内容
|
|
2802
|
-
});
|
|
2803
|
-
this.emit("tool-call-requested", {
|
|
2804
|
-
tool_calls: currentMessage.tool_calls,
|
|
2805
|
-
reasoning_content: currentMessage.reasoning_content,
|
|
2806
|
-
// ✅ 新增:包含思考内容
|
|
2807
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
2808
|
-
iteration
|
|
2809
|
-
});
|
|
2810
|
-
const toolResults = await this.toolManager.executeToolCalls(currentMessage.tool_calls);
|
|
2811
|
-
for (const result of toolResults) {
|
|
2812
|
-
this.messages.addToolMessage(result.result || result.error, result.tool_call_id);
|
|
2813
|
-
}
|
|
2814
|
-
const requestBody = this.requestBuilder.toJSON();
|
|
2815
|
-
await new Promise((resolve, reject) => {
|
|
2816
|
-
this.apiClient.strSend(
|
|
2817
|
-
requestBody,
|
|
2818
|
-
typeof onProgress === "function" ? (chunk) => {
|
|
2819
|
-
this.emit("stream-progress", chunk);
|
|
2820
|
-
onProgress(chunk);
|
|
2821
|
-
} : (chunk) => {
|
|
2822
|
-
this.emit("stream-progress", chunk);
|
|
2823
|
-
},
|
|
2824
|
-
(finalMessage) => {
|
|
2825
|
-
currentMessage = finalMessage;
|
|
2826
|
-
if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
|
|
2827
|
-
resolve();
|
|
2828
|
-
} else {
|
|
2829
|
-
resolve();
|
|
2830
|
-
}
|
|
2831
|
-
}
|
|
2832
|
-
).catch(reject);
|
|
2833
|
-
});
|
|
2834
|
-
if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
|
|
2835
|
-
break;
|
|
2836
|
-
}
|
|
2837
|
-
}
|
|
2838
|
-
const eventData = await this._handleAssistantResponse(currentMessage, {
|
|
2839
|
-
isStreaming: true,
|
|
2840
|
-
toolIterations: iteration,
|
|
2841
|
-
skipAddMessage: true
|
|
2842
|
-
});
|
|
2843
|
-
if (typeof onDone === "function") {
|
|
2844
|
-
onDone(eventData);
|
|
2845
|
-
}
|
|
2846
|
-
}
|
|
2847
|
-
/**
|
|
2848
|
-
* 撤回消息
|
|
2849
|
-
*/
|
|
2850
|
-
undo() {
|
|
2851
|
-
const removed = this.messages.undoToAssistant();
|
|
2852
|
-
if (removed.length > 0) {
|
|
2853
|
-
this.emit("undo", {
|
|
2854
|
-
removedMessages: removed,
|
|
2855
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2856
|
-
});
|
|
2857
|
-
}
|
|
2858
|
-
return removed;
|
|
2859
|
-
}
|
|
2860
|
-
/**
|
|
2861
|
-
* 清空消息
|
|
2862
|
-
*/
|
|
2863
|
-
clear() {
|
|
2864
|
-
const removed = this.messages.clearMessages();
|
|
2865
|
-
this.emit("clear", {
|
|
2866
|
-
removedMessages: removed,
|
|
2867
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2868
|
-
});
|
|
2869
|
-
return removed;
|
|
2870
|
-
}
|
|
2871
|
-
/**
|
|
2872
|
-
* 导出对话数据
|
|
2873
|
-
*/
|
|
2874
|
-
export() {
|
|
2875
|
-
const data = this.messages.export();
|
|
2876
|
-
this.emit("export", {
|
|
2877
|
-
data,
|
|
2878
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2879
|
-
});
|
|
2880
|
-
return data;
|
|
2881
|
-
}
|
|
2882
|
-
/**
|
|
2883
|
-
* 导入对话数据
|
|
2884
|
-
*/
|
|
2885
|
-
import(data) {
|
|
2886
|
-
this.messages.import(data);
|
|
2887
|
-
this.emit("import", {
|
|
2888
|
-
data,
|
|
2889
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
2890
|
-
});
|
|
2891
|
-
return this;
|
|
2892
|
-
}
|
|
796
|
+
function assembleMessages(options = {}) {
|
|
797
|
+
return MessageFormatter.format({
|
|
798
|
+
...options,
|
|
799
|
+
format: "openai"
|
|
800
|
+
});
|
|
2893
801
|
}
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
802
|
+
//#endregion
|
|
803
|
+
//#region src/adapters/openai.js
|
|
804
|
+
/**
|
|
805
|
+
* OpenAI 兼容 API 适配器
|
|
806
|
+
* 支持 DeepSeek 等完全兼容 OpenAI 接口的服务
|
|
807
|
+
*/
|
|
808
|
+
var openaiAdapter = {
|
|
809
|
+
name: "openai",
|
|
810
|
+
install(chatService) {
|
|
811
|
+
chatService.setAdapter(this);
|
|
812
|
+
},
|
|
813
|
+
buildRequest(messages, config, systemPrompts = []) {
|
|
814
|
+
const model = config.model || config.modelParams?.model;
|
|
815
|
+
if (!model) throw new Error("Missing required config: model (either at top level or in modelParams)");
|
|
816
|
+
const temperature = config.modelParams?.temperature ?? config.temperature ?? .7;
|
|
817
|
+
const maxTokens = config.modelParams?.maxTokens ?? config.maxTokens ?? 2e3;
|
|
818
|
+
const reasoningEffort = config.modelParams?.reasoningEffort ?? config.reasoningEffort;
|
|
819
|
+
const requestBody = {
|
|
820
|
+
model,
|
|
821
|
+
messages: MessageFormatter.format({
|
|
822
|
+
messages,
|
|
823
|
+
systemPrompts,
|
|
824
|
+
capabilities: config.capabilities || {},
|
|
825
|
+
resolveImage: config.resolveImage,
|
|
826
|
+
format: config.messageFormat
|
|
827
|
+
}),
|
|
828
|
+
temperature,
|
|
829
|
+
max_tokens: maxTokens,
|
|
830
|
+
stream: false
|
|
831
|
+
};
|
|
832
|
+
if (config.tools && Array.isArray(config.tools) && config.tools.length > 0) {
|
|
833
|
+
requestBody.tools = config.tools;
|
|
834
|
+
requestBody.tool_choice = "auto";
|
|
835
|
+
}
|
|
836
|
+
if (reasoningEffort && model === "deepseek-reasoner") requestBody.reasoning_effort = reasoningEffort;
|
|
837
|
+
return requestBody;
|
|
838
|
+
},
|
|
839
|
+
_getUrl(config) {
|
|
840
|
+
config = config || {};
|
|
841
|
+
const { apiUrl, baseUrl, path } = config;
|
|
842
|
+
const defaultPath = "/chat/completions";
|
|
843
|
+
if (apiUrl && isString(apiUrl)) return apiUrl;
|
|
844
|
+
if (baseUrl && isString(baseUrl)) return joinUrl(baseUrl, path && isString(path) ? path : defaultPath);
|
|
845
|
+
return "https://api.openai.com/v1/chat/completions";
|
|
846
|
+
},
|
|
847
|
+
async send(requestBody, config, options = {}) {
|
|
848
|
+
try {
|
|
849
|
+
const url = this._getUrl(config);
|
|
850
|
+
const headers = {
|
|
851
|
+
"Content-Type": "application/json",
|
|
852
|
+
"Authorization": `Bearer ${config.apiKey}`,
|
|
853
|
+
...config.headers || {},
|
|
854
|
+
...options.headers || {}
|
|
855
|
+
};
|
|
856
|
+
const response = await fetch(url, {
|
|
857
|
+
method: "POST",
|
|
858
|
+
headers,
|
|
859
|
+
body: JSON.stringify(requestBody),
|
|
860
|
+
signal: options.signal
|
|
861
|
+
});
|
|
862
|
+
if (!response.ok) await this.handleErrorResponse(response);
|
|
863
|
+
return await response.json();
|
|
864
|
+
} catch (error) {
|
|
865
|
+
if (error instanceof APIError) throw error;
|
|
866
|
+
if (error.name === "AbortError") throw error;
|
|
867
|
+
if (error.name === "TypeError" && error.message.includes("fetch")) throw new NetworkError(`Request failed: ${error.message}`, error);
|
|
868
|
+
throw error;
|
|
869
|
+
}
|
|
870
|
+
},
|
|
871
|
+
parseResponse(apiResponse) {
|
|
872
|
+
if (!apiResponse || !apiResponse.choices || !apiResponse.choices[0] || !apiResponse.choices[0].message) throw new ParsingError("Invalid API response: missing choices or message", apiResponse, JSON.stringify(apiResponse));
|
|
873
|
+
const msg = apiResponse.choices[0].message;
|
|
874
|
+
const internal = {
|
|
875
|
+
role: msg.role,
|
|
876
|
+
content: msg.content || ""
|
|
877
|
+
};
|
|
878
|
+
if (msg.tool_calls) internal.toolCalls = msg.tool_calls;
|
|
879
|
+
if (msg.reasoning_content) internal.reasoningContent = msg.reasoning_content;
|
|
880
|
+
return internal;
|
|
881
|
+
},
|
|
882
|
+
async stream(requestBody, config, onProgress, onDone, options = {}) {
|
|
883
|
+
const streamBody = {
|
|
884
|
+
...requestBody,
|
|
885
|
+
stream: true
|
|
886
|
+
};
|
|
887
|
+
const url = this._getUrl(config);
|
|
888
|
+
let response;
|
|
889
|
+
const headers = {
|
|
890
|
+
"Content-Type": "application/json",
|
|
891
|
+
"Authorization": `Bearer ${config.apiKey}`,
|
|
892
|
+
"Accept": "text/event-stream",
|
|
893
|
+
...config.headers || {},
|
|
894
|
+
...options.headers || {}
|
|
895
|
+
};
|
|
896
|
+
try {
|
|
897
|
+
response = await fetch(url, {
|
|
898
|
+
method: "POST",
|
|
899
|
+
headers,
|
|
900
|
+
body: JSON.stringify(streamBody),
|
|
901
|
+
signal: options.signal
|
|
902
|
+
});
|
|
903
|
+
} catch (error) {
|
|
904
|
+
if (error.name === "AbortError") throw error;
|
|
905
|
+
if (error.name === "TypeError" && error.message.includes("fetch")) throw new NetworkError(`Stream request failed: ${error.message}`, error);
|
|
906
|
+
throw error;
|
|
907
|
+
}
|
|
908
|
+
if (!response.ok) await this.handleErrorResponse(response);
|
|
909
|
+
const reader = response.body.getReader();
|
|
910
|
+
const decoder = new TextDecoder();
|
|
911
|
+
let buffer = "";
|
|
912
|
+
let accumulated = {
|
|
913
|
+
role: "assistant",
|
|
914
|
+
content: "",
|
|
915
|
+
reasoningContent: ""
|
|
916
|
+
};
|
|
917
|
+
while (true) {
|
|
918
|
+
if (options.signal?.aborted) break;
|
|
919
|
+
const { done, value } = await reader.read();
|
|
920
|
+
if (done) break;
|
|
921
|
+
buffer += decoder.decode(value, { stream: true });
|
|
922
|
+
const lines = buffer.split(/\n\n/);
|
|
923
|
+
buffer = lines.pop();
|
|
924
|
+
for (const line of lines) {
|
|
925
|
+
const dataLine = line.replace(/^data: /, "").trim();
|
|
926
|
+
if (!dataLine) continue;
|
|
927
|
+
if (dataLine === "[DONE]") break;
|
|
928
|
+
try {
|
|
929
|
+
const delta = JSON.parse(dataLine).choices?.[0]?.delta;
|
|
930
|
+
if (!delta) continue;
|
|
931
|
+
if (delta.content) accumulated.content += delta.content;
|
|
932
|
+
if (delta.tool_calls) {
|
|
933
|
+
if (!accumulated.toolCalls) accumulated.toolCalls = [];
|
|
934
|
+
for (const toolCallDelta of delta.tool_calls) {
|
|
935
|
+
const index = toolCallDelta.index;
|
|
936
|
+
if (!accumulated.toolCalls[index]) accumulated.toolCalls[index] = {
|
|
937
|
+
id: "",
|
|
938
|
+
type: "function",
|
|
939
|
+
function: {
|
|
940
|
+
name: "",
|
|
941
|
+
arguments: ""
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
if (toolCallDelta.id) accumulated.toolCalls[index].id = toolCallDelta.id;
|
|
945
|
+
if (toolCallDelta.type) accumulated.toolCalls[index].type = toolCallDelta.type;
|
|
946
|
+
if (toolCallDelta.function?.name) accumulated.toolCalls[index].function.name += toolCallDelta.function.name;
|
|
947
|
+
if (toolCallDelta.function?.arguments) accumulated.toolCalls[index].function.arguments += toolCallDelta.function.arguments;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (delta.reasoning_content) accumulated.reasoningContent += delta.reasoning_content;
|
|
951
|
+
onProgress({ ...accumulated });
|
|
952
|
+
} catch (e) {
|
|
953
|
+
console.warn("stream parsing failed :", e, dataLine);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
onDone({
|
|
958
|
+
role: "assistant",
|
|
959
|
+
content: accumulated.content,
|
|
960
|
+
toolCalls: accumulated.toolCalls,
|
|
961
|
+
reasoningContent: accumulated.reasoningContent
|
|
962
|
+
});
|
|
963
|
+
},
|
|
964
|
+
async handleErrorResponse(response) {
|
|
965
|
+
let errorText = await response.text();
|
|
966
|
+
let errorMessage = `HTTP ${response.status}`;
|
|
967
|
+
try {
|
|
968
|
+
const errorJson = JSON.parse(errorText);
|
|
969
|
+
errorMessage = errorJson.error?.message || errorJson.message || errorText.slice(0, 200);
|
|
970
|
+
} catch (e) {
|
|
971
|
+
errorMessage = errorText.length > 200 ? errorText.slice(0, 200) + "..." : errorText;
|
|
972
|
+
}
|
|
973
|
+
throw new APIError(errorMessage, response.status, null, errorText);
|
|
974
|
+
}
|
|
975
|
+
};
|
|
976
|
+
//#endregion
|
|
977
|
+
//#region src/plugins/tool-calling.js
|
|
978
|
+
/**
|
|
979
|
+
* 工具调用插件
|
|
980
|
+
* 功能:拦截助手消息中的 tool_calls,执行对应的工具,将结果作为 tool 消息加入对话,
|
|
981
|
+
* 然后自动继续对话(通过 sendExisting / sendExistingStream),直到没有新的工具调用。
|
|
982
|
+
*
|
|
983
|
+
* 设计要点:
|
|
984
|
+
* - 支持普通请求和流式请求(通过 isStream 标志区分)
|
|
985
|
+
* - 支持多次工具调用循环(maxIterations 防止无限循环)
|
|
986
|
+
* - 串行执行工具(可后续升级为并行)
|
|
987
|
+
* - 工具执行失败时,仍然返回错误信息给 AI,而不是中断整个流程
|
|
988
|
+
* - 触发 tool-error 事件,方便用户监听工具执行异常
|
|
989
|
+
*/
|
|
990
|
+
var toolCallingPlugin = {
|
|
991
|
+
name: "tool-calling",
|
|
992
|
+
maxIterations: 5,
|
|
993
|
+
install(chatService) {
|
|
994
|
+
this.chatService = chatService;
|
|
995
|
+
this._tools = /* @__PURE__ */ new Map();
|
|
996
|
+
if (!chatService.config.tools) chatService.config.tools = [];
|
|
997
|
+
/**
|
|
998
|
+
* 注册工具
|
|
999
|
+
* @param {string} name - 工具名称(唯一标识)
|
|
1000
|
+
* @param {string} description - 工具描述(告诉 AI 何时调用)
|
|
1001
|
+
* @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
|
|
1002
|
+
* @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
|
|
1003
|
+
* @returns {ChatService} 返回 chatService 实例,支持链式调用
|
|
1004
|
+
*/
|
|
1005
|
+
chatService.registerTool = (name, description, executor, parameters = {}) => {
|
|
1006
|
+
this._tools.set(name, {
|
|
1007
|
+
executor,
|
|
1008
|
+
description
|
|
1009
|
+
});
|
|
1010
|
+
const toolDefinition = {
|
|
1011
|
+
type: "function",
|
|
1012
|
+
function: {
|
|
1013
|
+
name,
|
|
1014
|
+
description,
|
|
1015
|
+
parameters: {
|
|
1016
|
+
type: "object",
|
|
1017
|
+
properties: parameters,
|
|
1018
|
+
required: Object.keys(parameters).filter((key) => parameters[key]?.required)
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
if (!chatService.config.tools.find((t) => t.function.name === name)) chatService.config.tools.push(toolDefinition);
|
|
1023
|
+
return chatService;
|
|
1024
|
+
};
|
|
1025
|
+
chatService._processResponse = async (response, { isStream, onProgress, onDone }) => {
|
|
1026
|
+
return this._handleWithTools(response, isStream, onProgress, onDone);
|
|
1027
|
+
};
|
|
1028
|
+
},
|
|
1029
|
+
async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
|
|
1030
|
+
const self = this;
|
|
1031
|
+
const chat = this.chatService;
|
|
1032
|
+
let iteration = 0;
|
|
1033
|
+
/**
|
|
1034
|
+
* 递归处理工具调用
|
|
1035
|
+
* @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
|
|
1036
|
+
* @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
|
|
1037
|
+
*/
|
|
1038
|
+
async function processResponse(initialResponse) {
|
|
1039
|
+
let lastResponse = initialResponse;
|
|
1040
|
+
while (iteration < self.maxIterations) {
|
|
1041
|
+
const toolCalls = lastResponse?.toolCalls;
|
|
1042
|
+
if (!toolCalls || toolCalls.length === 0) break;
|
|
1043
|
+
iteration++;
|
|
1044
|
+
const toolResults = await Promise.all(toolCalls.map(async (call) => {
|
|
1045
|
+
const toolName = call.function?.name;
|
|
1046
|
+
let args;
|
|
1047
|
+
try {
|
|
1048
|
+
args = JSON.parse(call.function?.arguments || "{}");
|
|
1049
|
+
} catch (parseErr) {
|
|
1050
|
+
chat.emit("tool-error", {
|
|
1051
|
+
toolName: toolName || "unknown",
|
|
1052
|
+
error: parseErr,
|
|
1053
|
+
toolCallId: call.id,
|
|
1054
|
+
stage: "parse",
|
|
1055
|
+
timestamp: Date.now()
|
|
1056
|
+
});
|
|
1057
|
+
return {
|
|
1058
|
+
tool_call_id: call.id,
|
|
1059
|
+
error: `参数解析失败: ${parseErr.message}`,
|
|
1060
|
+
success: false
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
1063
|
+
const tool = self._tools.get(toolName);
|
|
1064
|
+
if (!tool) {
|
|
1065
|
+
chat.emit("tool-error", {
|
|
1066
|
+
toolName,
|
|
1067
|
+
error: /* @__PURE__ */ new Error(`Tool not registered: ${toolName}`),
|
|
1068
|
+
toolCallId: call.id,
|
|
1069
|
+
stage: "lookup",
|
|
1070
|
+
timestamp: Date.now()
|
|
1071
|
+
});
|
|
1072
|
+
return {
|
|
1073
|
+
tool_call_id: call.id,
|
|
1074
|
+
error: `工具 ${toolName} 未注册`,
|
|
1075
|
+
success: false
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
try {
|
|
1079
|
+
const toolTimeout = chat.config.toolTimeout;
|
|
1080
|
+
let execPromise = tool.executor(args);
|
|
1081
|
+
if (toolTimeout && typeof toolTimeout === "number" && toolTimeout > 0) {
|
|
1082
|
+
const timeoutErr = /* @__PURE__ */ new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
|
|
1083
|
+
timeoutErr.name = "ToolTimeoutError";
|
|
1084
|
+
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(timeoutErr), toolTimeout));
|
|
1085
|
+
execPromise = Promise.race([execPromise, timeoutPromise]);
|
|
1086
|
+
}
|
|
1087
|
+
const result = await execPromise;
|
|
1088
|
+
chat.emit("tool-success", {
|
|
1089
|
+
toolName,
|
|
1090
|
+
result,
|
|
1091
|
+
toolCallId: call.id,
|
|
1092
|
+
timestamp: Date.now()
|
|
1093
|
+
});
|
|
1094
|
+
return {
|
|
1095
|
+
tool_call_id: call.id,
|
|
1096
|
+
content: typeof result === "string" ? result : JSON.stringify(result),
|
|
1097
|
+
success: true
|
|
1098
|
+
};
|
|
1099
|
+
} catch (err) {
|
|
1100
|
+
const stage = err.name === "ToolTimeoutError" ? "timeout" : "execute";
|
|
1101
|
+
chat.emit("tool-error", {
|
|
1102
|
+
toolName,
|
|
1103
|
+
error: err,
|
|
1104
|
+
toolCallId: call.id,
|
|
1105
|
+
stage,
|
|
1106
|
+
timestamp: Date.now()
|
|
1107
|
+
});
|
|
1108
|
+
return {
|
|
1109
|
+
tool_call_id: call.id,
|
|
1110
|
+
error: err.message,
|
|
1111
|
+
success: false
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
}));
|
|
1115
|
+
for (const tr of toolResults) {
|
|
1116
|
+
const content = tr.success ? tr.content : tr.error || "工具执行失败";
|
|
1117
|
+
chat.messages.addTool(content, tr.tool_call_id);
|
|
1118
|
+
}
|
|
1119
|
+
if (isStream) await new Promise((resolve) => {
|
|
1120
|
+
chat.sendExistingStream((chunk) => {
|
|
1121
|
+
if (onProgress) onProgress(chunk);
|
|
1122
|
+
lastResponse = chunk;
|
|
1123
|
+
}, (final) => {
|
|
1124
|
+
lastResponse = final;
|
|
1125
|
+
resolve();
|
|
1126
|
+
});
|
|
1127
|
+
});
|
|
1128
|
+
else lastResponse = await chat.sendExisting();
|
|
1129
|
+
}
|
|
1130
|
+
return lastResponse;
|
|
1131
|
+
}
|
|
1132
|
+
return await processResponse(initialResponse);
|
|
1133
|
+
}
|
|
1134
|
+
};
|
|
1135
|
+
//#endregion
|
|
1136
|
+
//#region src/plugins/model-registry.js
|
|
1137
|
+
/**
|
|
1138
|
+
* model-registry 插件
|
|
1139
|
+
*
|
|
1140
|
+
* 职责:
|
|
1141
|
+
* 1. 内置常用模型的能力标签表(model → capabilities 映射)
|
|
1142
|
+
* 2. 安装时自动根据 config.model 查表,写入 config.capabilities
|
|
1143
|
+
* 3. 监听 config-updated 事件,切换模型时自动同步能力
|
|
1144
|
+
* 4. 提供 chat.registerModel(),允许用户追加/覆盖自定义模型
|
|
1145
|
+
*
|
|
1146
|
+
* 能力标签字段(全部可选,缺失视为 false / 未知):
|
|
1147
|
+
* {
|
|
1148
|
+
* reasoning: boolean — 是否返回 reasoning_content(思维链)
|
|
1149
|
+
* vision: boolean — 是否支持图片输入
|
|
1150
|
+
* toolCalling: boolean — 是否支持 function calling
|
|
1151
|
+
* streaming: boolean — 是否支持流式传输
|
|
1152
|
+
* maxInputTokens: number — 最大输入 token 数
|
|
1153
|
+
* maxOutputTokens: number — 最大输出 token 数
|
|
1154
|
+
* }
|
|
1155
|
+
*
|
|
1156
|
+
* 使用:
|
|
1157
|
+
* chat.use(modelRegistryPlugin);
|
|
1158
|
+
* // config.capabilities 现在已自动填充
|
|
1159
|
+
* chat.registerModel('my-custom-model', { toolCalling: true });
|
|
1160
|
+
*/
|
|
1161
|
+
var BUILTIN_MODELS = {
|
|
1162
|
+
"deepseek-chat": {
|
|
1163
|
+
reasoning: false,
|
|
1164
|
+
vision: false,
|
|
1165
|
+
toolCalling: true,
|
|
1166
|
+
streaming: true,
|
|
1167
|
+
maxInputTokens: 128e3,
|
|
1168
|
+
maxOutputTokens: 8192
|
|
1169
|
+
},
|
|
1170
|
+
"deepseek-reasoner": {
|
|
1171
|
+
reasoning: true,
|
|
1172
|
+
vision: false,
|
|
1173
|
+
toolCalling: true,
|
|
1174
|
+
streaming: true,
|
|
1175
|
+
maxInputTokens: 128e3,
|
|
1176
|
+
maxOutputTokens: 8192
|
|
1177
|
+
},
|
|
1178
|
+
"gpt-4o": {
|
|
1179
|
+
reasoning: false,
|
|
1180
|
+
vision: true,
|
|
1181
|
+
toolCalling: true,
|
|
1182
|
+
streaming: true,
|
|
1183
|
+
maxInputTokens: 128e3,
|
|
1184
|
+
maxOutputTokens: 16384
|
|
1185
|
+
},
|
|
1186
|
+
"gpt-4o-mini": {
|
|
1187
|
+
reasoning: false,
|
|
1188
|
+
vision: true,
|
|
1189
|
+
toolCalling: true,
|
|
1190
|
+
streaming: true,
|
|
1191
|
+
maxInputTokens: 128e3,
|
|
1192
|
+
maxOutputTokens: 16384
|
|
1193
|
+
},
|
|
1194
|
+
"gpt-3.5-turbo": {
|
|
1195
|
+
reasoning: false,
|
|
1196
|
+
vision: false,
|
|
1197
|
+
toolCalling: true,
|
|
1198
|
+
streaming: true,
|
|
1199
|
+
maxInputTokens: 16385,
|
|
1200
|
+
maxOutputTokens: 4096
|
|
1201
|
+
},
|
|
1202
|
+
"o1": {
|
|
1203
|
+
reasoning: true,
|
|
1204
|
+
vision: false,
|
|
1205
|
+
toolCalling: false,
|
|
1206
|
+
streaming: false,
|
|
1207
|
+
maxInputTokens: 2e5,
|
|
1208
|
+
maxOutputTokens: 1e5
|
|
1209
|
+
},
|
|
1210
|
+
"o3-mini": {
|
|
1211
|
+
reasoning: true,
|
|
1212
|
+
vision: false,
|
|
1213
|
+
toolCalling: true,
|
|
1214
|
+
streaming: true,
|
|
1215
|
+
maxInputTokens: 2e5,
|
|
1216
|
+
maxOutputTokens: 1e5
|
|
1217
|
+
},
|
|
1218
|
+
"claude-3.5-sonnet": {
|
|
1219
|
+
reasoning: false,
|
|
1220
|
+
vision: true,
|
|
1221
|
+
toolCalling: true,
|
|
1222
|
+
streaming: true,
|
|
1223
|
+
maxInputTokens: 2e5,
|
|
1224
|
+
maxOutputTokens: 8192
|
|
1225
|
+
},
|
|
1226
|
+
"claude-3.5-haiku": {
|
|
1227
|
+
reasoning: false,
|
|
1228
|
+
vision: true,
|
|
1229
|
+
toolCalling: true,
|
|
1230
|
+
streaming: true,
|
|
1231
|
+
maxInputTokens: 2e5,
|
|
1232
|
+
maxOutputTokens: 8192
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
var DEFAULT_CAPABILITIES = {
|
|
1236
|
+
streaming: true,
|
|
1237
|
+
toolCalling: false,
|
|
1238
|
+
reasoning: false,
|
|
1239
|
+
vision: false
|
|
2903
1240
|
};
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
1241
|
+
var modelRegistryPlugin = {
|
|
1242
|
+
name: "model-registry",
|
|
1243
|
+
install(chatService) {
|
|
1244
|
+
this.chat = chatService;
|
|
1245
|
+
this._registry = new Map(Object.entries(BUILTIN_MODELS));
|
|
1246
|
+
/**
|
|
1247
|
+
* 注册/覆盖一个模型的能力标签
|
|
1248
|
+
* @param {string} name — 模型名称
|
|
1249
|
+
* @param {Object} capabilities — 能力标签对象(部分字段即可,未提供的取默认值)
|
|
1250
|
+
* @returns {ChatService}
|
|
1251
|
+
*/
|
|
1252
|
+
chatService.registerModel = (name, capabilities = {}) => {
|
|
1253
|
+
if (!name || typeof name !== "string" || !name.trim()) throw new Error("[model-registry] 模型名称必须是非空字符串");
|
|
1254
|
+
const merged = {
|
|
1255
|
+
...DEFAULT_CAPABILITIES,
|
|
1256
|
+
...capabilities
|
|
1257
|
+
};
|
|
1258
|
+
this._registry.set(name.trim(), merged);
|
|
1259
|
+
if (chatService.config.model === name.trim()) this._syncCapabilities();
|
|
1260
|
+
return chatService;
|
|
1261
|
+
};
|
|
1262
|
+
/**
|
|
1263
|
+
* 列出所有已注册的模型名称
|
|
1264
|
+
* @returns {Array<string>}
|
|
1265
|
+
*/
|
|
1266
|
+
chatService.listModels = () => {
|
|
1267
|
+
return [...this._registry.keys()];
|
|
1268
|
+
};
|
|
1269
|
+
this._syncCapabilities();
|
|
1270
|
+
chatService.on("config-updated", ({ changes }) => {
|
|
1271
|
+
if ("model" in changes) this._syncCapabilities();
|
|
1272
|
+
if ("capabilities" in changes && !("model" in changes)) {
|
|
1273
|
+
const current = this._lookupCapabilities();
|
|
1274
|
+
if (current) chatService.config.capabilities = {
|
|
1275
|
+
...current,
|
|
1276
|
+
...changes.capabilities
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
});
|
|
1280
|
+
},
|
|
1281
|
+
_lookupCapabilities() {
|
|
1282
|
+
const model = this.chat.config.model;
|
|
1283
|
+
if (!model) return null;
|
|
1284
|
+
return this._registry.get(model) || null;
|
|
1285
|
+
},
|
|
1286
|
+
_syncCapabilities() {
|
|
1287
|
+
const caps = this._lookupCapabilities();
|
|
1288
|
+
if (caps) this.chat.config.capabilities = { ...caps };
|
|
1289
|
+
}
|
|
2913
1290
|
};
|
|
2914
|
-
//#
|
|
1291
|
+
//#endregion
|
|
1292
|
+
export { APIError, ChatService, ConfigurationError, EventEmitter, MessageFormatter, MessageStore, NetworkError, ParsingError, SystemPromptStore, assembleMessages, modelRegistryPlugin, openaiAdapter, toolCallingPlugin };
|
|
1293
|
+
|
|
1294
|
+
//# sourceMappingURL=my-ai-chat-framework.browser.es.js.map
|