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.
@@ -1,1665 +1,1307 @@
1
- "use strict";
2
- Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
- const axios = require("axios");
4
- class MessageFormatter {
5
- /**
6
- * 将消息转换为标准格式(不再过滤自定义元数据,只确保必需字段)
7
- */
8
- static toStandardFormat(message) {
9
- const { role, content } = message;
10
- const standardMessage = { role, content };
11
- for (const [key, value] of Object.entries(message)) {
12
- if (key !== "role" && key !== "content" && value !== void 0) {
13
- standardMessage[key] = value;
14
- }
15
- }
16
- return standardMessage;
17
- }
18
- /**
19
- * 批量转换消息为标准格式
20
- */
21
- static batchToStandardFormat(messages) {
22
- return messages.map((msg) => this.toStandardFormat(msg));
23
- }
24
- /**
25
- * 从Messages实例获取格式化后的消息数组
26
- */
27
- static formatMessages(messagesInstance, baseRounds, cycleRounds) {
28
- const systems = messagesInstance.getEnabledSystemPrompts();
29
- const hintSystem = {
30
- role: "system",
31
- content: `你的名字||标题是:${messagesInstance.getName() || "未知"}`
32
- };
33
- systems.unshift(hintSystem);
34
- const recentMessages = messagesInstance.getRecentMessages(baseRounds, cycleRounds);
35
- return [...systems, ...recentMessages];
36
- }
37
- /**
38
- * 构造工具参数
39
- */
40
- static constructParameters(array) {
41
- let paramsArray = [];
42
- if (Array.isArray(array)) {
43
- paramsArray = array;
44
- } else if (typeof array === "object" && array !== null) {
45
- paramsArray = [array];
46
- } else {
47
- throw new Error("[系统提示异常] 检测到无效的参数格式");
48
- }
49
- const parameters = {};
50
- for (let i = 0; i < paramsArray.length; i++) {
51
- const param = paramsArray[i];
52
- if (!param?.name?.trim()) {
53
- throw new Error(`[系统提示异常] 检测到空参数名称 位置: 第 ${i + 1} 个参数`);
54
- }
55
- if (!param?.type?.trim()) {
56
- throw new Error(`[系统提示异常] 检测到空参数类型 位置: 参数 "${param.name}"`);
57
- }
58
- if (!param?.description?.trim()) {
59
- throw new Error(`[系统提示异常] 检测到空参数描述 位置: 参数 "${param.name}"`);
60
- }
61
- parameters[param.name] = {
62
- type: param.type,
63
- description: param.description
64
- };
65
- }
66
- return {
67
- type: "object",
68
- properties: parameters,
69
- required: Object.keys(parameters)
70
- };
71
- }
72
- /**
73
- * 构造工具定义
74
- */
75
- static constructTool({ name, description, parameters }) {
76
- if (!name?.trim()) {
77
- throw new Error("[系统提示异常] 检测到空工具名称");
78
- }
79
- if (!description?.trim()) {
80
- throw new Error("[系统提示异常] 检测到空工具描述");
81
- }
82
- let processedParameters;
83
- try {
84
- processedParameters = this.constructParameters(parameters);
85
- } catch (error) {
86
- throw new Error(`[系统提示异常] 工具参数验证失败 工具名称: ${name} 错误详情: ${error.message}`);
87
- }
88
- return {
89
- type: "function",
90
- function: {
91
- name,
92
- description,
93
- parameters: processedParameters
94
- }
95
- };
96
- }
97
- /**
98
- * 过滤消息以供API使用(只移除空content的消息,保留所有字段)
99
- */
100
- static filterForAPI(messages) {
101
- return messages.filter((msg) => {
102
- if (msg.role === "tool") {
103
- return true;
104
- }
105
- return msg.content !== "" && msg.content !== void 0 && msg.content !== null;
106
- });
107
- }
108
- }
109
- class Messages {
110
- constructor() {
111
- this.messages = [];
112
- this.systemPrompts = [];
113
- this.tools = [];
114
- this.metadata = {
115
- name: "",
116
- createdAt: /* @__PURE__ */ new Date(),
117
- lastModified: /* @__PURE__ */ new Date()
118
- };
119
- }
120
- // ========== 核心消息方法 ==========
121
- /**
122
- * 添加消息(通用方法)
123
- * @param {string} role - 角色:user/assistant/system/tool
124
- * @param {string} content - 消息内容(允许空字符串)
125
- * @param {object} metadata - 额外元数据
126
- * @returns {number} 新消息的索引
127
- */
128
- addMessage(role, content, metadata = {}) {
129
- const validRoles = ["user", "assistant", "system", "tool"];
130
- if (!validRoles.includes(role)) {
131
- throw new Error(`无效的角色: ${role},有效值: ${validRoles.join(", ")}`);
132
- }
133
- if (role === "tool") {
134
- if (!metadata.tool_call_id) {
135
- throw new Error("tool消息必须包含tool_call_id");
136
- }
137
- } else {
138
- if (content === void 0 || content === null) {
139
- throw new Error("消息内容不能为undefined或null");
140
- }
141
- if (typeof content !== "string") {
142
- throw new Error("消息内容必须是字符串");
143
- }
144
- }
145
- const message = {
146
- role,
147
- content: content ? content.trim() : "",
148
- // 允许空字符串
149
- timestamp: /* @__PURE__ */ new Date()
150
- };
151
- if (metadata && typeof metadata === "object") {
152
- for (const [key, value] of Object.entries(metadata)) {
153
- if (value !== void 0 && value !== null) {
154
- message[key] = value;
155
- }
156
- }
157
- }
158
- return this.messages.push(message) - 1;
159
- }
160
- /**
161
- * 添加用户消息(便捷方法)
162
- */
163
- addUserMessage(content, metadata = {}) {
164
- return this.addMessage("user", content, metadata);
165
- }
166
- /**
167
- * 添加助手消息(便捷方法)
168
- */
169
- addAssistantMessage(content, metadata = {}) {
170
- return this.addMessage("assistant", content, metadata);
171
- }
172
- /**
173
- * 添加系统消息(便捷方法)
174
- */
175
- addSystemMessage(content, metadata = {}) {
176
- return this.addMessage("system", content, metadata);
177
- }
178
- /**
179
- * 添加工具消息(便捷方法)
180
- */
181
- addToolMessage(content, toolCallId, metadata = {}) {
182
- if (!toolCallId || typeof toolCallId !== "string") {
183
- throw new Error("tool_call_id不能为空");
184
- }
185
- return this.addMessage("tool", content, {
186
- tool_call_id: toolCallId,
187
- ...metadata
188
- });
189
- }
190
- /**
191
- * 批量添加消息
192
- */
193
- addMessages(messagesArray) {
194
- if (!Array.isArray(messagesArray)) {
195
- throw new Error("参数必须是数组");
196
- }
197
- const indices = [];
198
- for (const msg of messagesArray) {
199
- if (!msg.role || !msg.content) {
200
- throw new Error("消息必须包含role和content属性");
201
- }
202
- const { role, content, ...metadata } = msg;
203
- const index2 = this.addMessage(role, content, metadata);
204
- indices.push(index2);
205
- }
206
- return indices;
207
- }
208
- // ========== 消息查询 ==========
209
- /**
210
- * 获取所有消息
211
- */
212
- getMessages() {
213
- return [...this.messages];
214
- }
215
- /**
216
- * 按角色获取消息
217
- */
218
- getMessagesByRole(role) {
219
- const validRoles = ["user", "assistant", "system", "tool"];
220
- if (!validRoles.includes(role)) {
221
- throw new Error(`无效的角色: ${role}`);
222
- }
223
- return this.messages.filter((msg) => msg.role === role);
224
- }
225
- /**
226
- * 获取最后一条消息
227
- */
228
- getLastMessage() {
229
- return this.messages.length > 0 ? { ...this.messages[this.messages.length - 1] } : null;
230
- }
231
- /**
232
- * 获取最后一条用户消息
233
- */
234
- getLastUserMessage() {
235
- for (let i = this.messages.length - 1; i >= 0; i--) {
236
- if (this.messages[i].role === "user") {
237
- return { ...this.messages[i] };
238
- }
239
- }
240
- return null;
241
- }
242
- /**
243
- * 获取最后一条助手消息
244
- */
245
- getLastAssistantMessage() {
246
- for (let i = this.messages.length - 1; i >= 0; i--) {
247
- if (this.messages[i].role === "assistant") {
248
- return { ...this.messages[i] };
249
- }
250
- }
251
- return null;
252
- }
253
- /**
254
- * 获取消息数量
255
- */
256
- getMessageCount() {
257
- return this.messages.length;
258
- }
259
- // ========== 消息修改 ==========
260
- /**
261
- * 更新消息内容(允许空字符串)
262
- */
263
- updateMessage(index2, content) {
264
- if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
265
- throw new Error(`无效的消息索引: ${index2}`);
266
- }
267
- if (typeof content !== "string") {
268
- throw new Error("消息内容必须是字符串");
269
- }
270
- this.messages[index2].content = content;
271
- this.messages[index2].lastModified = /* @__PURE__ */ new Date();
272
- return this;
273
- }
274
- /**
275
- * 更新最后一条消息
276
- */
277
- updateLastMessage(content) {
278
- if (this.messages.length === 0) {
279
- throw new Error("没有消息可以修改");
280
- }
281
- return this.updateMessage(this.messages.length - 1, content);
282
- }
283
- /**
284
- * 设置消息字段
285
- */
286
- setMessageField(index2, field, value) {
287
- if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
288
- throw new Error(`无效的消息索引: ${index2}`);
289
- }
290
- this.messages[index2][field] = value;
291
- this.messages[index2].lastModified = /* @__PURE__ */ new Date();
292
- return this;
293
- }
294
- /**
295
- * 批量设置消息字段
296
- */
297
- setMessageFields(index2, fields) {
298
- if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
299
- throw new Error(`无效的消息索引: ${index2}`);
300
- }
301
- for (const [field, value] of Object.entries(fields)) {
302
- if (value !== void 0 && value !== null) {
303
- this.messages[index2][field] = value;
304
- }
305
- }
306
- this.messages[index2].lastModified = /* @__PURE__ */ new Date();
307
- return this;
308
- }
309
- /**
310
- * 批量更新最后一条消息的字段
311
- */
312
- updateLastMessageFields(fields) {
313
- if (this.messages.length === 0) {
314
- throw new Error("没有消息可以修改");
315
- }
316
- return this.setMessageFields(this.messages.length - 1, fields);
317
- }
318
- // ========== 消息删除 ==========
319
- /**
320
- * 删除消息
321
- */
322
- removeMessage(index2) {
323
- if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.messages.length) {
324
- throw new Error(`无效的消息索引: ${index2}`);
325
- }
326
- return this.messages.splice(index2, 1)[0];
327
- }
328
- /**
329
- * 删除最后一条消息
330
- */
331
- removeLastMessage() {
332
- if (this.messages.length === 0) {
333
- throw new Error("没有消息可以删除");
334
- }
335
- return this.removeMessage(this.messages.length - 1);
336
- }
337
- /**
338
- * 撤回到上一条助手消息
339
- */
340
- undoToAssistant() {
341
- if (this.messages.length === 0) {
342
- return [];
343
- }
344
- let lastAssistantIndex = -1;
345
- for (let i = this.messages.length - 1; i >= 0; i--) {
346
- if (this.messages[i].role === "assistant") {
347
- lastAssistantIndex = i;
348
- break;
349
- }
350
- }
351
- if (lastAssistantIndex >= 0) {
352
- return this.messages.splice(lastAssistantIndex + 1);
353
- } else {
354
- const removed = [...this.messages];
355
- this.messages = [];
356
- return removed;
357
- }
358
- }
359
- /**
360
- * 是否可以撤回
361
- */
362
- canUndo() {
363
- return this.messages.some((msg) => msg.role === "assistant");
364
- }
365
- /**
366
- * 清空所有消息
367
- */
368
- clearMessages() {
369
- const removed = [...this.messages];
370
- this.messages = [];
371
- this.metadata.lastModified = /* @__PURE__ */ new Date();
372
- return removed;
373
- }
374
- // ========== 系统提示管理 ==========
375
- /**
376
- * 添加系统提示
377
- */
378
- addSystemPrompt(content, enabled = true) {
379
- if (typeof content !== "string" || !content.trim()) {
380
- throw new Error("系统提示内容不能为空");
381
- }
382
- const prompt = {
383
- role: "system",
384
- content: content.trim(),
385
- enabled: Boolean(enabled),
386
- createdAt: /* @__PURE__ */ new Date()
387
- };
388
- return this.systemPrompts.push(prompt) - 1;
389
- }
390
- /**
391
- * 获取启用的系统提示
392
- */
393
- getEnabledSystemPrompts() {
394
- return this.systemPrompts.filter((prompt) => prompt.enabled).map((prompt) => ({ role: prompt.role, content: prompt.content }));
395
- }
396
- /**
397
- * 切换系统提示状态
398
- */
399
- toggleSystemPrompt(index2) {
400
- if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
401
- throw new Error(`无效的系统提示索引: ${index2}`);
402
- }
403
- this.systemPrompts[index2].enabled = !this.systemPrompts[index2].enabled;
404
- return this;
405
- }
406
- /**
407
- * 更新系统提示内容
408
- */
409
- updateSystemPrompt(index2, content) {
410
- if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
411
- throw new Error(`无效的系统提示索引: ${index2}`);
412
- }
413
- if (typeof content !== "string" || !content.trim()) {
414
- throw new Error("系统提示内容不能为空");
415
- }
416
- this.systemPrompts[index2].content = content.trim();
417
- this.systemPrompts[index2].lastModified = /* @__PURE__ */ new Date();
418
- return this;
419
- }
420
- /**
421
- * 删除系统提示
422
- */
423
- removeSystemPrompt(index2) {
424
- if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.systemPrompts.length) {
425
- throw new Error(`无效的系统提示索引: ${index2}`);
426
- }
427
- return this.systemPrompts.splice(index2, 1)[0];
428
- }
429
- // ========== 工具管理 ==========
430
- /**
431
- * 添加工具
432
- */
433
- addTool(toolDefinition) {
434
- if (typeof toolDefinition === "object" && toolDefinition !== null) {
435
- if (!toolDefinition.type || toolDefinition.type !== "function") {
436
- throw new Error(`无效的工具类型,期望: 'function',实际: '${toolDefinition.type || "undefined"}'`);
437
- }
438
- if (!toolDefinition.function?.name?.trim()) {
439
- throw new Error("工具名称不能为空");
440
- }
441
- return this.tools.push(toolDefinition) - 1;
442
- }
443
- if (toolDefinition.name && toolDefinition.description && toolDefinition.parameters) {
444
- const constructedTool = MessageFormatter.constructTool(toolDefinition);
445
- return this.tools.push(constructedTool) - 1;
446
- }
447
- throw new Error("无效的工具格式");
448
- }
449
- /**
450
- * 从定义添加工具
451
- */
452
- addToolFromDefinition(name, description, parameters) {
453
- const tool = MessageFormatter.constructTool({ name, description, parameters });
454
- return this.tools.push(tool) - 1;
455
- }
456
- /**
457
- * 获取所有工具
458
- */
459
- getTools() {
460
- return [...this.tools];
461
- }
462
- /**
463
- * 删除工具
464
- */
465
- removeTool(index2) {
466
- if (!Number.isInteger(index2) || index2 < 0 || index2 >= this.tools.length) {
467
- throw new Error(`无效的工具索引: ${index2}`);
468
- }
469
- return this.tools.splice(index2, 1)[0];
470
- }
471
- /**
472
- * 清空所有工具
473
- */
474
- clearTools() {
475
- const removed = [...this.tools];
476
- this.tools = [];
477
- return removed;
478
- }
479
- // ========== 元数据管理 ==========
480
- setName(name) {
481
- if (typeof name !== "string" || !name.trim()) {
482
- throw new Error("名称不能为空");
483
- }
484
- this.metadata.name = name.trim();
485
- this.metadata.lastModified = /* @__PURE__ */ new Date();
486
- return this;
487
- }
488
- getName() {
489
- return this.metadata.name;
490
- }
491
- // ========== 兼容性方法 ==========
492
- /**
493
- * 获取最近的消息(兼容旧方法)
494
- */
495
- getRecentMessages(baseRounds, cycleRounds) {
496
- const messages = this.messages.map((item) => {
497
- return MessageFormatter.toStandardFormat(item);
498
- });
499
- const msgTotal = messages.length;
500
- const totalRounds = msgTotal / 2;
501
- if (!baseRounds || isNaN(baseRounds) || baseRounds <= 0) {
502
- return messages;
503
- }
504
- const maxCycleRoundMultiple = cycleRounds > 0 ? Math.floor(totalRounds / cycleRounds) * cycleRounds : 0;
505
- const actualRounds = baseRounds + (totalRounds - maxCycleRoundMultiple);
506
- const actualMsgCount = actualRounds * 2;
507
- const n = Math.max(msgTotal - actualMsgCount, 0);
508
- return messages.slice(n);
509
- }
510
- /**
511
- * 获取所有格式化消息(兼容旧方法)
512
- */
513
- getMessagesFormatted(baseRounds, cycleRounds) {
514
- const systems = this.getEnabledSystemPrompts();
515
- const hintSystem = {
516
- role: "system",
517
- content: `你的名字||标题是:${this.metadata.name || "未知"}`
518
- };
519
- systems.unshift(hintSystem);
520
- const recentMessages = this.getRecentMessages(baseRounds, cycleRounds);
521
- return [...systems, ...recentMessages];
522
- }
523
- // ========== 导入导出 ==========
524
- export() {
525
- return {
526
- __format_version: 2,
527
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
528
- metadata: { ...this.metadata },
529
- payload: {
530
- messages: JSON.parse(JSON.stringify(this.messages)),
531
- systemPrompts: JSON.parse(JSON.stringify(this.systemPrompts)),
532
- tools: JSON.parse(JSON.stringify(this.tools))
533
- }
534
- };
535
- }
536
- import(data) {
537
- const obj = typeof data === "string" ? JSON.parse(data) : data;
538
- const parsed = Messages.parseCompatible(obj);
539
- this.messages = parsed.messages || [];
540
- this.systemPrompts = parsed.systemPrompts || [];
541
- this.tools = parsed.tools || [];
542
- this.metadata = parsed.metadata || {
543
- name: "",
544
- createdAt: /* @__PURE__ */ new Date(),
545
- lastModified: /* @__PURE__ */ new Date()
546
- };
547
- this.metadata.lastModified = /* @__PURE__ */ new Date();
548
- return this;
549
- }
550
- static parseCompatible(obj) {
551
- if (obj?.__format_version === 2 && obj.payload) {
552
- return {
553
- messages: obj.payload.messages || [],
554
- systemPrompts: obj.payload.systemPrompts || [],
555
- tools: obj.payload.tools || [],
556
- metadata: obj.metadata || {
557
- name: "",
558
- createdAt: /* @__PURE__ */ new Date(),
559
- lastModified: /* @__PURE__ */ new Date()
560
- }
561
- };
562
- }
563
- if (obj?.__format_version === 1 && obj.payload) {
564
- return {
565
- messages: obj.payload.messages || [],
566
- systemPrompts: obj.payload.systems || [],
567
- tools: obj.payload.tools || [],
568
- metadata: {
569
- name: obj.payload.hintData?.name || "",
570
- createdAt: /* @__PURE__ */ new Date(),
571
- lastModified: /* @__PURE__ */ new Date()
572
- }
573
- };
574
- }
575
- if (obj?.messages && Array.isArray(obj.messages)) {
576
- return {
577
- messages: obj.messages || [],
578
- systemPrompts: obj.systems || [],
579
- tools: obj.tools || [],
580
- metadata: {
581
- name: obj.hintData?.name || "",
582
- createdAt: /* @__PURE__ */ new Date(),
583
- lastModified: /* @__PURE__ */ new Date()
584
- }
585
- };
586
- }
587
- throw new Error("无法识别的聊天数据格式");
588
- }
589
- }
590
- class EventEmitter {
591
- constructor() {
592
- this.events = {};
593
- }
594
- /**
595
- * 监听事件
596
- * @param {string} eventName - 要注册的事件名称
597
- * @param {Function} callback - 事件触发时执行的回调函数
598
- */
599
- //实现一个监听事件的方法
600
- on(eventName, callback) {
601
- if (!this.events[eventName]) {
602
- this.events[eventName] = [];
603
- }
604
- this.events[eventName].push(callback);
605
- return () => this.off(eventName, callback);
606
- }
607
- /**
608
- * 触发事件
609
- * @param {string} eventName --要触发的事件名称
610
- * @param {any} data --传递给回调函数的数据
611
- */
612
- emit(eventName, data) {
613
- const callbacks = this.events[eventName];
614
- if (!callbacks) return;
615
- const callbakesCopy = callbacks.slice();
616
- for (let i = 0; i < callbakesCopy.length; i++) {
617
- try {
618
- callbakesCopy[i](data);
619
- } catch (error) {
620
- console.error(`事件 ${eventName} 的回调函数执行出错:`, error);
621
- }
622
- }
623
- }
624
- /**
625
- * 取消监听事件
626
- * @param {string} eventName --要取消的事件名称
627
- * @param {Function} callback --要移除的回调函数
628
- */
629
- off(eventName, callback) {
630
- const callbacks = this.events[eventName];
631
- if (!callbacks) return;
632
- this.events[eventName] = callbacks.filter((item) => item !== callback);
633
- if (this.events[eventName].length === 0) {
634
- delete this.events[eventName];
635
- }
636
- }
637
- /**
638
- * 只监听一次事件(触发后自动取消)
639
- * @param {string} eventName - 事件名称
640
- * @param {Function} callback - 回调函数
641
- */
642
- once(evenName, callback) {
643
- const onceCallback = (data) => {
644
- this.off(evenName, onceCallback);
645
- callback(data);
646
- };
647
- this.on(evenName, onceCallback);
648
- return () => this.off(evenName, onceCallback);
649
- }
650
- /**
651
- * 移除某个事件的所有监听器
652
- * @param {string} eventName - 事件名称
653
- */
654
- removeAllListeners(eventName) {
655
- if (eventName) {
656
- delete this.events[eventName];
657
- } else {
658
- this.events = {};
659
- }
660
- }
661
- /**
662
- * 获取某个事件的所有监听器数量
663
- * @param {string} eventName - 事件名称
664
- * @returns {number} 监听器数量
665
- */
666
- listenerCount(eventName) {
667
- const callbacks = this.events[eventName];
668
- return callbacks ? callbacks.length : 0;
669
- }
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/core/EventEmitter.js
3
+ /**
4
+ * 极简事件发射器
5
+ * 支持同步/异步事件,handler 返回 Promise 时自动 await
6
+ */
7
+ var EventEmitter = class {
8
+ constructor() {
9
+ this._events = /* @__PURE__ */ new Map();
10
+ }
11
+ on(event, handler) {
12
+ if (!this._events.has(event)) this._events.set(event, []);
13
+ this._events.get(event).push(handler);
14
+ return () => this.off(event, handler);
15
+ }
16
+ off(event, handler) {
17
+ if (!this._events.has(event)) return;
18
+ const handlers = this._events.get(event).filter((h) => h !== handler);
19
+ if (handlers.length) this._events.set(event, handlers);
20
+ else this._events.delete(event);
21
+ }
22
+ /**
23
+ * 同步触发事件
24
+ */
25
+ emit(event, data) {
26
+ if (!this._events.has(event)) return;
27
+ for (const handler of this._events.get(event)) try {
28
+ handler(data);
29
+ } catch (err) {
30
+ console.error(`事件 ${event} 处理出错:`, err);
31
+ }
32
+ }
33
+ /**
34
+ * 异步触发事件,逐个 await handler
35
+ * handler 返回 Promise 时自动等待
36
+ */
37
+ async emitAsync(event, data) {
38
+ if (!this._events.has(event)) return;
39
+ for (const handler of this._events.get(event)) try {
40
+ await handler(data);
41
+ } catch (err) {
42
+ console.error(`事件 ${event} 处理出错:`, err);
43
+ }
44
+ }
45
+ };
46
+ //#endregion
47
+ //#region src/core/MessageStore.js
48
+ /**
49
+ * 消息存储 - 极简实现
50
+ * 每条消息格式:
51
+ * {
52
+ * id?: string,
53
+ * role: 'user'|'assistant'|'system'|'tool',
54
+ * content: string,
55
+ * images?: Array<string>, // 图片引用(URL / id),框架不存储图片数据
56
+ * _ephemeral?: boolean, // 临时消息:仅底部连续时参与请求,续写后转正
57
+ * _complete?: boolean, // 流式是否完成(false=未完成/中断)
58
+ * prefix?: boolean, // 前缀续写标记
59
+ * toolCalls?: Array,
60
+ * toolCallId?: string,
61
+ * timestamp?: number,
62
+ * metadata?: any
63
+ * }
64
+ */
65
+ var MessageStore = class {
66
+ constructor() {
67
+ this._messages = [];
68
+ this._idCounter = 0;
69
+ }
70
+ add(message) {
71
+ const msg = {
72
+ id: message.id || `msg_${Date.now()}_${++this._idCounter}`,
73
+ timestamp: message.timestamp || Date.now(),
74
+ ...message
75
+ };
76
+ this._messages.push(msg);
77
+ return msg;
78
+ }
79
+ addUser(content, metadata = {}) {
80
+ return this.add({
81
+ role: "user",
82
+ content,
83
+ metadata
84
+ });
85
+ }
86
+ addAssistant(content, metadata = {}) {
87
+ return this.add({
88
+ role: "assistant",
89
+ content,
90
+ metadata
91
+ });
92
+ }
93
+ addSystem(content, metadata = {}) {
94
+ return this.add({
95
+ role: "system",
96
+ content,
97
+ metadata
98
+ });
99
+ }
100
+ addTool(content, toolCallId, metadata = {}) {
101
+ return this.add({
102
+ role: "tool",
103
+ content,
104
+ toolCallId,
105
+ metadata
106
+ });
107
+ }
108
+ /**
109
+ * 快速添加一次性的、带续写标记的 assistant 消息
110
+ * 适用于思维链引导、临时注入等场景
111
+ * @param {string} content — 引导内容
112
+ * @param {Object} [options] — { reasoningContent, prefix }
113
+ * @returns {Object} 添加的消息
114
+ */
115
+ addOnceAssistant(content, options = {}) {
116
+ return this.add({
117
+ role: "assistant",
118
+ content,
119
+ reasoningContent: options.reasoningContent,
120
+ prefix: options.prefix !== false,
121
+ _ephemeral: true
122
+ });
123
+ }
124
+ getLast() {
125
+ return this._messages[this._messages.length - 1] || null;
126
+ }
127
+ getAll() {
128
+ return [...this._messages];
129
+ }
130
+ clear() {
131
+ this._messages = [];
132
+ }
133
+ undoToLastAssistant() {
134
+ let lastAssistantIndex = -1;
135
+ for (let i = this._messages.length - 1; i >= 0; i--) if (this._messages[i].role === "assistant") {
136
+ lastAssistantIndex = i;
137
+ break;
138
+ }
139
+ if (lastAssistantIndex >= 0) return this._messages.splice(lastAssistantIndex + 1);
140
+ return [];
141
+ }
142
+ /**
143
+ * 更新消息:按 id 查找并合并 changes,不新增消息
144
+ * @param {string} id — 消息 id
145
+ * @param {Object} changes — 要合并的字段
146
+ * @returns {Object|null} 更新后的消息,未找到返回 null
147
+ */
148
+ update(id, changes) {
149
+ for (const msg of this._messages) if (msg.id === id) {
150
+ Object.assign(msg, changes);
151
+ msg.timestamp = changes.timestamp || Date.now();
152
+ return msg;
153
+ }
154
+ return null;
155
+ }
156
+ };
157
+ //#endregion
158
+ //#region src/core/SystemPromptStore.js
159
+ /**
160
+ * SystemPromptStore — 系统提示词存储
161
+ *
162
+ * 职责:管理多条 system prompt 的增删改查与开关
163
+ * 与 MessageStore 分离,因为 system prompt 是"AI 行为准则",不是对话事件
164
+ *
165
+ * 每条记录格式:
166
+ * {
167
+ * id: string,
168
+ * content: string,
169
+ * enabled: boolean,
170
+ * timestamp: number
171
+ * }
172
+ */
173
+ var SystemPromptStore = class {
174
+ constructor() {
175
+ this._prompts = [];
176
+ this._idCounter = 0;
177
+ }
178
+ /**
179
+ * 添加一条 system prompt
180
+ * @param {string} content — 提示词内容
181
+ * @param {boolean} [enabled=true] — 是否启用
182
+ * @returns {Object} 添加的记录
183
+ */
184
+ add(content, enabled = true) {
185
+ if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
186
+ const record = {
187
+ id: `sys_${Date.now()}_${++this._idCounter}`,
188
+ content: content.trim(),
189
+ enabled: Boolean(enabled),
190
+ timestamp: Date.now()
191
+ };
192
+ this._prompts.push(record);
193
+ return record;
194
+ }
195
+ /**
196
+ * 删除指定索引的 system prompt
197
+ * @param {number} index
198
+ * @returns {Object} 被删除的记录
199
+ */
200
+ remove(index) {
201
+ if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
202
+ return this._prompts.splice(index, 1)[0];
203
+ }
204
+ /**
205
+ * 切换指定索引的启用/禁用状态
206
+ * @param {number} index
207
+ * @returns {boolean} 切换后的状态
208
+ */
209
+ toggle(index) {
210
+ if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
211
+ this._prompts[index].enabled = !this._prompts[index].enabled;
212
+ return this._prompts[index].enabled;
213
+ }
214
+ /**
215
+ * 更新指定索引的 content
216
+ * @param {number} index
217
+ * @param {string} content
218
+ */
219
+ update(index, content) {
220
+ if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
221
+ if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
222
+ this._prompts[index].content = content.trim();
223
+ this._prompts[index].timestamp = Date.now();
224
+ }
225
+ /**
226
+ * 清空并用一条 content 替换(便捷方法,常用于 config.system = '...')
227
+ * @param {string} content
228
+ */
229
+ set(content) {
230
+ this._prompts = [];
231
+ if (content && typeof content === "string" && content.trim()) this.add(content, true);
232
+ }
233
+ /**
234
+ * 按 enabled 筛选后,转为适配器可用的格式
235
+ * @returns {Array<{role:'system', content:string}>}
236
+ */
237
+ getEnabled() {
238
+ return this._prompts.filter((p) => p.enabled).map((p) => ({
239
+ role: "system",
240
+ content: p.content
241
+ }));
242
+ }
243
+ /**
244
+ * 返回所有记录(含 enabled 状态,用于 UI 展示)
245
+ * @returns {Array}
246
+ */
247
+ getAll() {
248
+ return [...this._prompts];
249
+ }
250
+ /**
251
+ * 清空所有 system prompt
252
+ */
253
+ clear() {
254
+ this._prompts = [];
255
+ }
256
+ };
257
+ //#endregion
258
+ //#region src/core/Errors.js
259
+ /**
260
+ * 自定义错误类
261
+ * 用于区分不同类型的错误,方便用户通过 `error.name` 或 `instanceof` 处理
262
+ */
263
+ var APIError = class extends Error {
264
+ /**
265
+ * @param {string} message - 错误消息(通常来自 API 响应)
266
+ * @param {number} statusCode - HTTP 状态码
267
+ * @param {any} originalError - 原始错误对象或相关信息
268
+ * @param {string} responseText - 原始响应文本(如果有)
269
+ */
270
+ constructor(message, statusCode, originalError, responseText) {
271
+ super(message);
272
+ this.name = "APIError";
273
+ this.statusCode = statusCode;
274
+ this.originalError = originalError;
275
+ this.responseText = responseText;
276
+ }
277
+ };
278
+ var NetworkError = class extends Error {
279
+ /**
280
+ * @param {string} message - 错误消息
281
+ * @param {any} originalError - 原始错误对象或相关信息
282
+ */
283
+ constructor(message, originalError) {
284
+ super(message);
285
+ this.name = "NetworkError";
286
+ this.originalError = originalError;
287
+ }
288
+ };
289
+ var ConfigurationError = class extends Error {
290
+ /**
291
+ * @param {string} message - 错误消息
292
+ */
293
+ constructor(message) {
294
+ super(message);
295
+ this.name = "ConfigurationError";
296
+ }
297
+ };
298
+ var ParsingError = class extends Error {
299
+ /**
300
+ * @param {string} message - 错误消息
301
+ * @param {any} originalError - 原始错误对象或相关信息
302
+ * @param {string} responseText - 原始响应文本(如果有)
303
+ **/
304
+ constructor(message, originalError, responseText) {
305
+ super(message);
306
+ this.name = "ParsingError";
307
+ this.originalError = originalError;
308
+ this.responseText = responseText;
309
+ }
310
+ };
311
+ //#endregion
312
+ //#region src/core/ChatService.js
313
+ var ChatService = class extends EventEmitter {
314
+ constructor(config = {}) {
315
+ super();
316
+ this.config = { ...config };
317
+ this.messages = new MessageStore();
318
+ this.systemPrompts = new SystemPromptStore();
319
+ this._adapter = null;
320
+ this._abortController = null;
321
+ this._isGenerating = false;
322
+ this._hooks = new EventEmitter();
323
+ this._processResponse = null;
324
+ const model = this.config.model || this.config.modelParams?.model;
325
+ if (!model || typeof model !== "string" || !model.trim()) throw new ConfigurationError("缺少 model 配置");
326
+ const temperature = this.config.modelParams?.temperature ?? this.config.temperature;
327
+ if (temperature !== void 0 && (typeof temperature !== "number" || temperature < 0 || temperature > 2)) throw new ConfigurationError(`temperature 必须在 0-2 之间,当前值: ${temperature}`);
328
+ const maxTokens = this.config.modelParams?.maxTokens ?? this.config.maxTokens;
329
+ if (maxTokens !== void 0 && (typeof maxTokens !== "number" || maxTokens < 1 || !Number.isInteger(maxTokens))) throw new ConfigurationError(`maxTokens 必须为正整数,当前值: ${maxTokens}`);
330
+ if (typeof config.system === "string" && config.system.trim()) this.systemPrompts.set(config.system);
331
+ }
332
+ use(plugin) {
333
+ plugin.install(this);
334
+ return this;
335
+ }
336
+ setAdapter(adapter) {
337
+ this._adapter = adapter;
338
+ }
339
+ abort() {
340
+ if (this._abortController) this._abortController.abort();
341
+ }
342
+ get isGenerating() {
343
+ return this._isGenerating;
344
+ }
345
+ async continueLast() {
346
+ const target = this._prepareContinue();
347
+ this.messages.update(target.id, { prefix: true });
348
+ try {
349
+ await this._request({
350
+ addUser: false,
351
+ isStream: false,
352
+ mergeToEntry: target.id
353
+ });
354
+ this.messages.update(target.id, {
355
+ _complete: true,
356
+ prefix: void 0,
357
+ _ephemeral: void 0
358
+ });
359
+ return target;
360
+ } catch (err) {
361
+ this.messages.update(target.id, { prefix: void 0 });
362
+ throw err;
363
+ }
364
+ }
365
+ async continueLastStream(onProgress, onDone) {
366
+ const target = this._prepareContinue();
367
+ console.log("[DEBUG] continueLastStream target.id:", target.id);
368
+ this.messages.update(target.id, { prefix: true });
369
+ const baseLen = (target.content || "").length;
370
+ try {
371
+ await this._request({
372
+ addUser: false,
373
+ isStream: true,
374
+ mergeToEntry: target.id,
375
+ onProgress: (chunk) => {
376
+ if (onProgress) onProgress({
377
+ ...chunk,
378
+ content: (chunk.content || "").slice(baseLen)
379
+ });
380
+ },
381
+ onDone: (final) => {
382
+ if (onDone) onDone(final);
383
+ }
384
+ });
385
+ this.messages.update(target.id, {
386
+ _complete: true,
387
+ prefix: void 0,
388
+ _ephemeral: void 0
389
+ });
390
+ return target;
391
+ } catch (err) {
392
+ this.messages.update(target.id, { prefix: void 0 });
393
+ throw err;
394
+ }
395
+ }
396
+ _prepareContinue() {
397
+ const msgs = this.messages.getAll();
398
+ const last = msgs[msgs.length - 1];
399
+ if (last && (last.role === "assistant" || last._ephemeral)) return last;
400
+ throw new Error("最后一条消息不是 assistant,无法续写");
401
+ }
402
+ updateConfig(partial) {
403
+ Object.assign(this.config, partial);
404
+ if (typeof partial.system === "string") this.systemPrompts.set(partial.system);
405
+ this.emit("config-updated", {
406
+ changes: partial,
407
+ timestamp: Date.now()
408
+ });
409
+ }
410
+ async _request(options) {
411
+ let { userInput, addUser = true, isStream = false, onProgress, onDone, mergeToEntry } = options;
412
+ this.emit("sending", {
413
+ addUser,
414
+ userInput,
415
+ timestamp: Date.now()
416
+ });
417
+ this._addUserMessage(userInput, addUser);
418
+ await this._hooks.emitAsync("beforeRequest", {
419
+ messages: this.messages,
420
+ config: this.config,
421
+ options
422
+ });
423
+ if (this.config.ephemeralContinue && !mergeToEntry) {
424
+ const msgs = this.messages.getAll();
425
+ const last = msgs[msgs.length - 1];
426
+ if (last && last.prefix && (last.role === "assistant" || last._ephemeral)) mergeToEntry = last.id;
427
+ }
428
+ const body = this._adapter.buildRequest(this.messages.getAll(), this.config, this.systemPrompts.getEnabled());
429
+ const retryCfg = this.config.retry || {};
430
+ try {
431
+ return await this._withRetry(body, {
432
+ isStream,
433
+ onProgress,
434
+ onDone,
435
+ mergeToEntry,
436
+ maxRetries: retryCfg.maxRetries ?? 0,
437
+ retryDelay: retryCfg.retryDelay ?? 1e3
438
+ });
439
+ } catch (error) {
440
+ this.emit("error", {
441
+ error,
442
+ timestamp: Date.now()
443
+ });
444
+ throw error;
445
+ }
446
+ }
447
+ _addUserMessage(userInput, addUser) {
448
+ if (addUser && userInput !== void 0) {
449
+ const msg = typeof userInput === "string" ? {
450
+ role: "user",
451
+ content: userInput
452
+ } : {
453
+ role: "user",
454
+ ...userInput
455
+ };
456
+ this.messages.add(msg);
457
+ }
458
+ }
459
+ /** retry 循环,占位消息只 push 一次 */
460
+ async _withRetry(body, { isStream, onProgress, onDone, mergeToEntry, maxRetries, retryDelay }) {
461
+ let lastError = null;
462
+ const adapterOptions = { signal: this._abortController?.signal };
463
+ let placeholder = null;
464
+ let base = null;
465
+ if (isStream) {
466
+ if (mergeToEntry) {
467
+ placeholder = this.messages.getAll().find((m) => m.id === mergeToEntry);
468
+ if (placeholder) base = {
469
+ content: placeholder.content || "",
470
+ reasoning: placeholder.reasoningContent || ""
471
+ };
472
+ }
473
+ if (!placeholder) placeholder = this.messages.add({
474
+ role: "assistant",
475
+ content: "",
476
+ _complete: false
477
+ });
478
+ }
479
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
480
+ if (attempt > 0) {
481
+ this.emit("retry", {
482
+ attempt,
483
+ maxRetries,
484
+ lastError,
485
+ timestamp: Date.now()
486
+ });
487
+ await new Promise((r) => setTimeout(r, retryDelay));
488
+ }
489
+ try {
490
+ this._isGenerating = true;
491
+ if (isStream) return await this._stream(body, adapterOptions, {
492
+ placeholder,
493
+ base,
494
+ mergeToEntry,
495
+ onProgress,
496
+ onDone
497
+ });
498
+ else {
499
+ const resp = await this._adapter.send(body, this.config, adapterOptions);
500
+ let result = this._handleResult(this._adapter.parseResponse(resp), mergeToEntry);
501
+ if (this._processResponse && !mergeToEntry) result = await this._processResponse(result, { isStream: false });
502
+ return result;
503
+ }
504
+ } catch (error) {
505
+ lastError = error;
506
+ if (error.name === "AbortError" || this._abortController?.signal.aborted) {
507
+ this._isGenerating = false;
508
+ throw error;
509
+ }
510
+ if (error instanceof NetworkError && attempt < maxRetries) continue;
511
+ this._isGenerating = false;
512
+ throw error;
513
+ }
514
+ }
515
+ this._isGenerating = false;
516
+ throw lastError;
517
+ }
518
+ /** 流式:ChatService 维护占位,adapter 只管解析 */
519
+ async _stream(body, adapterOptions, { placeholder, base, mergeToEntry, onProgress, onDone }) {
520
+ let finalMsg = null;
521
+ await this._adapter.stream(body, this.config, (snap) => {
522
+ placeholder.content = snap.content || "";
523
+ if (snap.reasoningContent) placeholder.reasoningContent = snap.reasoningContent;
524
+ if (snap.toolCalls) placeholder.toolCalls = [...snap.toolCalls];
525
+ this.emit("stream-progress", snap);
526
+ if (onProgress) onProgress(snap);
527
+ }, async (final) => {
528
+ finalMsg = final;
529
+ if (this._processResponse && !mergeToEntry) finalMsg = await this._processResponse(finalMsg, {
530
+ isStream: true,
531
+ onProgress,
532
+ onDone
533
+ });
534
+ if (mergeToEntry && base) {
535
+ const changes = {
536
+ content: base.content + (final.content || ""),
537
+ _complete: true
538
+ };
539
+ if (final.reasoningContent) changes.reasoningContent = base.reasoning + final.reasoningContent;
540
+ if (final.toolCalls) changes.toolCalls = final.toolCalls;
541
+ this.messages.update(mergeToEntry, changes);
542
+ const updated = this.messages.getAll().find((m) => m.id === mergeToEntry);
543
+ this.emit("message", updated);
544
+ if (onDone) onDone(updated);
545
+ } else {
546
+ placeholder._complete = true;
547
+ this.emit("message", finalMsg);
548
+ if (onDone) onDone(finalMsg);
549
+ }
550
+ }, adapterOptions);
551
+ return mergeToEntry || finalMsg;
552
+ }
553
+ /** 非流式结果落位 */
554
+ _handleResult(assistantMsg, mergeToEntry) {
555
+ if (mergeToEntry) {
556
+ const entry = this.messages.getAll().find((m) => m.id === mergeToEntry);
557
+ if (!entry) {
558
+ this.messages.add(assistantMsg);
559
+ this.emit("message", assistantMsg);
560
+ return assistantMsg;
561
+ }
562
+ const changes = {
563
+ content: (entry.content || "") + (assistantMsg.content || ""),
564
+ _complete: true
565
+ };
566
+ if (assistantMsg.reasoningContent) changes.reasoningContent = (entry.reasoningContent || "") + assistantMsg.reasoningContent;
567
+ if (assistantMsg.toolCalls) changes.toolCalls = assistantMsg.toolCalls;
568
+ this.messages.update(mergeToEntry, changes);
569
+ const updated = this.messages.getAll().find((m) => m.id === mergeToEntry);
570
+ this.emit("message", updated);
571
+ return updated;
572
+ }
573
+ this.messages.add(assistantMsg);
574
+ this.emit("message", assistantMsg);
575
+ return assistantMsg;
576
+ }
577
+ async send(userInput) {
578
+ this._abortController = new AbortController();
579
+ try {
580
+ return await this._request({
581
+ userInput,
582
+ addUser: true,
583
+ isStream: false
584
+ });
585
+ } finally {
586
+ this._abortController = null;
587
+ this._isGenerating = false;
588
+ }
589
+ }
590
+ async stream(userInput, onProgress, onDone) {
591
+ this._abortController = new AbortController();
592
+ try {
593
+ return await this._request({
594
+ userInput,
595
+ addUser: true,
596
+ isStream: true,
597
+ onProgress,
598
+ onDone
599
+ });
600
+ } finally {
601
+ this._abortController = null;
602
+ this._isGenerating = false;
603
+ }
604
+ }
605
+ async sendExisting() {
606
+ this._abortController = new AbortController();
607
+ try {
608
+ return await this._request({
609
+ addUser: false,
610
+ isStream: false
611
+ });
612
+ } finally {
613
+ this._abortController = null;
614
+ this._isGenerating = false;
615
+ }
616
+ }
617
+ async sendExistingStream(onProgress, onDone) {
618
+ this._abortController = new AbortController();
619
+ try {
620
+ return await this._request({
621
+ addUser: false,
622
+ isStream: true,
623
+ onProgress,
624
+ onDone
625
+ });
626
+ } finally {
627
+ this._abortController = null;
628
+ this._isGenerating = false;
629
+ }
630
+ }
631
+ };
632
+ //#endregion
633
+ //#region src/utils/url.js
634
+ /**
635
+ * URL 工具函数
636
+ */
637
+ /**
638
+ * 拼接 baseUrl 和 path
639
+ * 注意:path 应以 '/' 开头,否则会替换 baseUrl 的最后一段
640
+ * @param {string} baseUrl - 基础 URL(如 https://api.deepseek.com)
641
+ * @param {string} path - 路径(如 /v1/chat/completions)
642
+ * @returns {string} 完整的 URL
643
+ */
644
+ function joinUrl(baseUrl, path) {
645
+ return baseUrl.replace(/\/$/, "") + (path.startsWith("/") ? path : "/" + path);
670
646
  }
671
- class ToolManager extends EventEmitter {
672
- constructor() {
673
- super();
674
- this.tools = /* @__PURE__ */ new Map();
675
- }
676
- /**
677
- * 注册工具
678
- * @param {string} name - 工具名称
679
- * @param {object} toolDefinition - 工具定义(包含描述和参数信息)
680
- * @param {Function} executor - 工具执行函数,接受参数对象并返回结果
681
- */
682
- registerTool(name, toolDefinition, executor) {
683
- if (this.tools.has(name)) {
684
- throw new Error(`[系统提示异常] 工具 "${name}" 已经注册过了`);
685
- }
686
- this.tools.set(name, {
687
- definition: toolDefinition,
688
- executor
689
- });
690
- this.emit("tool-registered", { name, definition: toolDefinition });
691
- return this;
692
- }
693
- /**
694
- * 执行工具调用
695
- * @param {object} toolCall - 工具调用信息,包含工具名称和参数
696
- * @returns {Promise<any>} - 工具执行结果
697
- */
698
- async executeToolCall(toolCall) {
699
- const { id, function: func } = toolCall;
700
- const { name, arguments: argsStr } = func;
701
- if (!this.tools.has(name)) {
702
- throw new Error(`未找到工具: ${name}`);
703
- }
704
- const tool = this.tools.get(name);
705
- try {
706
- const args = JSON.parse(argsStr);
707
- this.emit("tool-execute-start", { name, args });
708
- const result = await tool.executor(args);
709
- this.emit("tool-execute-success", { name, args, result });
710
- return {
711
- tool_call_id: id,
712
- // 必须包含tool_call_id
713
- name,
714
- result: JSON.stringify(result),
715
- success: true
716
- };
717
- } catch (error) {
718
- this.emit("tool-execute-error", { name, error });
719
- return {
720
- tool_call_id: id,
721
- name,
722
- error: error.message,
723
- success: false
724
- };
725
- }
726
- }
727
- /**
728
- * 获取所有工具定义(用于发送给AI)
729
- */
730
- getToolDefinitions() {
731
- const definitions = [];
732
- for (const [name, tool] of this.tools) {
733
- definitions.push(tool.definition);
734
- }
735
- return definitions;
736
- }
737
- /**
738
- * 检查是否有工具
739
- */
740
- hasTools() {
741
- return this.tools.size > 0;
742
- }
743
- /**
744
- * 批量执行工具调用
745
- * @param {Array} toolCalls - 工具调用数组
746
- * @returns {Promise<Array>} - 所有工具的执行结果
747
- */
748
- async executeToolCalls(toolCalls) {
749
- if (!Array.isArray(toolCalls)) {
750
- throw new Error("toolCalls必须是数组");
751
- }
752
- const results = [];
753
- const promises = toolCalls.map(async (toolCall) => {
754
- try {
755
- const result = await this.executeToolCall(toolCall);
756
- return result;
757
- } catch (error) {
758
- return {
759
- tool_call_id: toolCall.id,
760
- name: toolCall.function.name,
761
- error: error.message,
762
- success: false
763
- };
764
- }
765
- });
766
- const settledResults = await Promise.allSettled(promises);
767
- for (const settled of settledResults) {
768
- if (settled.status === "fulfilled") {
769
- results.push(settled.value);
770
- } else {
771
- results.push({
772
- error: settled.reason.message,
773
- success: false
774
- });
775
- }
776
- }
777
- return results;
778
- }
779
- /**
780
- * 串行执行工具调用(如果需要顺序执行)
781
- */
782
- async executeToolCallsSequentially(toolCalls) {
783
- const results = [];
784
- for (const toolCall of toolCalls) {
785
- try {
786
- const result = await this.executeToolCall(toolCall);
787
- results.push(result);
788
- } catch (error) {
789
- results.push({
790
- tool_call_id: toolCall.id,
791
- name: toolCall.function.name,
792
- error: error.message,
793
- success: false
794
- });
795
- }
796
- }
797
- return results;
798
- }
647
+ //#endregion
648
+ //#region src/utils/typeCheck.js
649
+ /**
650
+ * 类型判断工具
651
+ */
652
+ /**
653
+ * 判断一个值是否为字符串
654
+ * @param {any} value - 要检查的值
655
+ * @returns {boolean} 如果是字符串则返回 true
656
+ */
657
+ function isString(value) {
658
+ return typeof value === "string";
799
659
  }
800
- class RequestBuilder {
801
- constructor(model, messagesInstance, config = {}) {
802
- this.model = model;
803
- this.messages = messagesInstance;
804
- this.config = {
805
- // temperature: 0.7,
806
- // max_tokens: 2000,
807
- // stream: false, // 默认关闭流式传输
808
- ...config
809
- };
810
- this.toolManager = null;
811
- }
812
- /**
813
- * 设置ToolManager引用
814
- */
815
- setToolManager(toolManager) {
816
- this.toolManager = toolManager;
817
- return this;
818
- }
819
- /**
820
- * 构建OpenAI兼容格式的请求体
821
- */
822
- buildOpenAIFormat(baseRounds, cycleRounds) {
823
- const formattedMessages = MessageFormatter.formatMessages(
824
- this.messages,
825
- baseRounds,
826
- cycleRounds
827
- );
828
- const filteredMessages = MessageFormatter.filterForAPI(formattedMessages);
829
- const request = {
830
- model: this.model,
831
- messages: filteredMessages,
832
- ...this.config
833
- };
834
- let tools = [];
835
- if (this.toolManager && this.toolManager.hasTools()) {
836
- tools = this.toolManager.getToolDefinitions();
837
- } else {
838
- tools = this.messages.getTools();
839
- }
840
- if (tools && tools.length > 0) {
841
- request.tools = tools;
842
- request.tool_choice = "auto";
843
- }
844
- return request;
845
- }
846
- /**
847
- * 构建请求体并返回JSON字符串
848
- */
849
- toJSON(baseRounds, cycleRounds) {
850
- const request = this.buildOpenAIFormat(baseRounds, cycleRounds);
851
- return JSON.stringify(request);
852
- }
853
- /**
854
- * 构建请求体并返回对象
855
- */
856
- toObject(baseRounds, cycleRounds) {
857
- return this.buildOpenAIFormat(baseRounds, cycleRounds);
858
- }
859
- /**
860
- * 设置配置项
861
- */
862
- setConfig(key, value) {
863
- this.config[key] = value;
864
- return this;
865
- }
866
- /**
867
- * 批量设置配置项
868
- */
869
- setConfigs(configs) {
870
- Object.assign(this.config, configs);
871
- return this;
872
- }
660
+ //#endregion
661
+ //#region src/utils/MessageFormatter.js
662
+ /**
663
+ * MessageFormatter — 可注册的消息格式转换器
664
+ *
665
+ * 职责:
666
+ * 1. 内置 OpenA I兼容格式的转换逻辑
667
+ * 2. 支持 register(name, fn) 注册自定义格式(如 Anthropic、Gemini 等)
668
+ * 3. 统一处理 capabilities 过滤(reasoning、vision 等)
669
+ * 4. 所有适配器通过此工具获取 API 消息数组,消除重复代码
670
+ *
671
+ * 用法:
672
+ * import { MessageFormatter } from 'my-ai-chat-framework';
673
+ *
674
+ * // 使用内置格式
675
+ * const msgs = MessageFormatter.format({
676
+ * messages, systemPrompts, capabilities, resolveImage
677
+ * }); // 默认 'openai'
678
+ *
679
+ * // 注册自定义格式
680
+ * MessageFormatter.register('anthropic', ({ messages, systemPrompts, capabilities }) => {
681
+ * // 返回 Anthropic 格式的消息数组
682
+ * });
683
+ */
684
+ var IS_URL = /^https?:\/\//i;
685
+ function defaultResolveImage(imageId) {
686
+ if (IS_URL.test(imageId)) return { url: imageId };
687
+ return null;
873
688
  }
874
- class ApiClient extends EventEmitter {
875
- constructor(apiKey, apiUrl = "https://api.deepseek.com/v1/chat/completions") {
876
- super();
877
- this.apiKey = apiKey;
878
- this.url = apiUrl;
879
- this.isGenerating = false;
880
- this.cancelTokenSource = null;
881
- this.axiosInstance = axios.create({
882
- baseURL: apiUrl,
883
- headers: {
884
- "Authorization": `Bearer ${apiKey}`,
885
- "Content-Type": "application/json"
886
- },
887
- timeout: 3e4
888
- // 30秒超时
889
- });
890
- }
891
- setApiKey(apiKey) {
892
- if (!apiKey || typeof apiKey !== "string") {
893
- throw new Error("无效的API Key");
894
- }
895
- this.apiKey = apiKey;
896
- this.axiosInstance.defaults.headers["Authorization"] = `Bearer ${apiKey}`;
897
- }
898
- setApiUrl(apiUrl) {
899
- if (!apiUrl || typeof apiUrl !== "string") {
900
- throw new Error("无效的API URL");
901
- }
902
- this.url = apiUrl;
903
- this.axiosInstance.defaults.baseURL = apiUrl;
904
- }
905
- async send(body) {
906
- this.isGenerating = true;
907
- this.cancelTokenSource = axios.CancelToken.source();
908
- try {
909
- this.emit("request-start", { body });
910
- const requestBody = this._buildRequestBody(body);
911
- const response = await this.axiosInstance.post("", requestBody, {
912
- cancelToken: this.cancelTokenSource.token
913
- });
914
- this.emit("request-success", { response: response.data });
915
- return response.data;
916
- } catch (error) {
917
- if (axios.isCancel(error)) {
918
- const cancelError = new Error("请求被中断");
919
- cancelError.name = "CancelError";
920
- this.emit("request-cancel", { error: cancelError });
921
- throw cancelError;
922
- }
923
- this.emit("request-error", { error });
924
- throw this._handleAxiosError(error);
925
- } finally {
926
- this.isGenerating = false;
927
- this.cancelTokenSource = null;
928
- }
929
- }
930
- async strSend(body, onProgress, onDone) {
931
- this.isGenerating = true;
932
- this.cancelTokenSource = axios.CancelToken.source();
933
- try {
934
- const safeOnProgress = typeof onProgress === "function" ? onProgress : () => {
935
- };
936
- const safeOnDone = typeof onDone === "function" ? onDone : () => {
937
- };
938
- this.emit("stream-start", { body });
939
- const requestBody = this._buildRequestBody(body);
940
- const response = await fetch(this.url, {
941
- method: "POST",
942
- headers: {
943
- "Content-Type": "application/json",
944
- "Authorization": `Bearer ${this.apiKey}`,
945
- "Accept": "text/event-stream"
946
- },
947
- body: requestBody,
948
- signal: this.cancelTokenSource.token ? new AbortController().signal : void 0
949
- });
950
- if (!response.ok) {
951
- throw new Error(`HTTP错误: ${response.status}`);
952
- }
953
- const reader = response.body.getReader();
954
- const decoder = new TextDecoder();
955
- let buffer = "";
956
- const message = {
957
- // 基础信息(符合Messages格式)
958
- role: "assistant",
959
- content: "",
960
- reasoning_content: "",
961
- timestamp: /* @__PURE__ */ new Date(),
962
- // 工具调用
963
- tool_calls: [],
964
- // 流式元数据
965
- streamMetadata: {
966
- chunkCount: 0,
967
- firstChunkTime: Date.now(),
968
- lastChunkTime: null,
969
- isStreaming: true
970
- }
971
- };
972
- while (true) {
973
- const { done, value } = await reader.read();
974
- if (done) break;
975
- buffer += decoder.decode(value, { stream: true });
976
- let lines = buffer.split(/(\r?\n){2,}/);
977
- buffer = lines.pop() || "";
978
- for (let rawChunk of lines) {
979
- const cleanChunk = rawChunk.trim().replace(/^data: /, "");
980
- if (!cleanChunk) continue;
981
- if (cleanChunk === "[DONE]") {
982
- this.emit("stream-done", { message });
983
- safeOnDone({ ...message });
984
- return;
985
- }
986
- try {
987
- const obj = JSON.parse(cleanChunk);
988
- console.log("🔍 收到流式chunk:", obj);
989
- message.streamMetadata.chunkCount++;
990
- message.streamMetadata.lastChunkTime = Date.now();
991
- if (obj.choices?.[0]?.delta?.content) {
992
- message.content += obj.choices[0].delta.content;
993
- }
994
- if (obj.choices?.[0]?.delta?.reasoning_content) {
995
- message.reasoning_content += obj.choices[0].delta.reasoning_content;
996
- }
997
- if (obj.choices?.[0]?.delta?.tool_calls) {
998
- const deltaToolCalls = obj.choices[0].delta.tool_calls;
999
- deltaToolCalls.forEach((toolCall) => {
1000
- const index2 = toolCall.index || 0;
1001
- if (!message.tool_calls) message.tool_calls = [];
1002
- if (!message.tool_calls[index2]) {
1003
- message.tool_calls[index2] = {
1004
- id: "",
1005
- type: "function",
1006
- function: { name: "", arguments: "" }
1007
- };
1008
- }
1009
- if (toolCall.id) message.tool_calls[index2].id = toolCall.id;
1010
- if (toolCall.type) message.tool_calls[index2].type = toolCall.type;
1011
- if (toolCall.function?.name) {
1012
- message.tool_calls[index2].function.name += toolCall.function.name;
1013
- }
1014
- if (toolCall.function?.arguments) {
1015
- message.tool_calls[index2].function.arguments += toolCall.function.arguments;
1016
- }
1017
- });
1018
- }
1019
- this.emit("stream-chunk", {
1020
- chunk: obj,
1021
- message: { ...message }
1022
- // 发送副本
1023
- });
1024
- safeOnProgress({ ...message });
1025
- } catch (e) {
1026
- console.error("🔍 解析chunk错误:", e, "原始数据:", cleanChunk);
1027
- }
1028
- }
1029
- if (!this.isGenerating) {
1030
- break;
1031
- }
1032
- }
1033
- message.streamMetadata.isStreaming = false;
1034
- message.streamMetadata.completedAt = /* @__PURE__ */ new Date();
1035
- this.emit("stream-done", { message: { ...message } });
1036
- safeOnDone({ ...message });
1037
- } catch (error) {
1038
- if (error.name === "AbortError" || axios.isCancel(error)) {
1039
- const cancelError = new Error("请求被中断");
1040
- cancelError.name = "CancelError";
1041
- this.emit("stream-cancel", { error: cancelError });
1042
- throw cancelError;
1043
- }
1044
- this.emit("stream-error", { error });
1045
- throw error;
1046
- } finally {
1047
- this.isGenerating = false;
1048
- this.cancelTokenSource = null;
1049
- }
1050
- }
1051
- interrupt() {
1052
- if (this.isGenerating && this.cancelTokenSource) {
1053
- this.cancelTokenSource.cancel("用户中断请求");
1054
- this.isGenerating = false;
1055
- }
1056
- }
1057
- _buildRequestBody(body) {
1058
- if (typeof body?.toJSON === "function") {
1059
- return body.toJSON();
1060
- } else if (typeof body === "object" && body !== null) {
1061
- return JSON.stringify(body);
1062
- } else if (typeof body === "string") {
1063
- try {
1064
- JSON.parse(body);
1065
- return body;
1066
- } catch {
1067
- throw new Error("字符串不是有效的JSON格式");
1068
- }
1069
- } else {
1070
- throw new Error("无效的请求体类型,应传入对象或JSON字符串");
1071
- }
1072
- }
1073
- _handleAxiosError(error) {
1074
- if (error.response) {
1075
- const status = error.response.status;
1076
- const data = error.response.data;
1077
- let message = `API错误 ${status}`;
1078
- if (data?.error?.message) {
1079
- message += `: ${data.error.message}`;
1080
- }
1081
- return new Error(message);
1082
- } else if (error.request) {
1083
- return new Error("网络错误:无法连接到API服务器");
1084
- } else {
1085
- return error;
1086
- }
1087
- }
1088
- static parseCompatible(obj) {
1089
- if (obj?.__format_version === 1 && obj.payload) {
1090
- return {
1091
- messages: obj.payload.messages || [],
1092
- systems: obj.payload.systems || [],
1093
- hintData: obj.payload.hintData || {
1094
- name: "",
1095
- toolState: {
1096
- currentTime: "同步失败",
1097
- currentTime_TS: 0
1098
- }
1099
- },
1100
- tools: obj.payload.tools || []
1101
- };
1102
- }
1103
- if (obj?.messages && Array.isArray(obj.messages)) {
1104
- return {
1105
- messages: obj.messages || [],
1106
- systems: obj.systems || [],
1107
- hintData: obj.hintData || {
1108
- name: "",
1109
- toolState: {
1110
- currentTime: "同步失败",
1111
- currentTime_TS: 0
1112
- }
1113
- },
1114
- tools: obj.tools || []
1115
- };
1116
- }
1117
- throw new Error("无法识别的聊天数据格式");
1118
- }
689
+ function buildMultimodalContent(textContent, images, resolveImage) {
690
+ const content = [{
691
+ type: "text",
692
+ text: textContent
693
+ }];
694
+ for (const ref of images) {
695
+ const resolved = resolveImage(ref);
696
+ if (!resolved) continue;
697
+ if (resolved.url) content.push({
698
+ type: "image_url",
699
+ image_url: { url: resolved.url }
700
+ });
701
+ else if (resolved.data) {
702
+ const mime = resolved.mimeType || "image/png";
703
+ content.push({
704
+ type: "image_url",
705
+ image_url: { url: `data:${mime};base64,${resolved.data}` }
706
+ });
707
+ }
708
+ }
709
+ return content;
1119
710
  }
1120
- class ConfigManager extends EventEmitter {
1121
- constructor(defaultConfig2 = {}) {
1122
- super();
1123
- this._config = JSON.parse(JSON.stringify(defaultConfig2));
1124
- this._handlers = /* @__PURE__ */ new Map();
1125
- this.config = this._createProxy(this._config);
1126
- }
1127
- /**
1128
- * 创建配置代理
1129
- */
1130
- _createProxy(target, path = "") {
1131
- return new Proxy(target, {
1132
- set: (obj, prop, value) => {
1133
- const oldValue = obj[prop];
1134
- const fullPath = path ? `${path}.${prop}` : prop;
1135
- if (value && typeof value === "object" && !Array.isArray(value)) {
1136
- value = this._createProxy(value, fullPath);
1137
- }
1138
- obj[prop] = value;
1139
- this._triggerChange(fullPath, oldValue, value);
1140
- return true;
1141
- },
1142
- deleteProperty: (obj, prop) => {
1143
- const oldValue = obj[prop];
1144
- const fullPath = path ? `${path}.${prop}` : prop;
1145
- delete obj[prop];
1146
- this.emit("config-deleted", {
1147
- path: fullPath,
1148
- oldValue,
1149
- timestamp: /* @__PURE__ */ new Date()
1150
- });
1151
- return true;
1152
- }
1153
- });
1154
- }
1155
- /**
1156
- * 注册配置处理器
1157
- */
1158
- registerHandler(path, handler) {
1159
- if (!this._handlers.has(path)) {
1160
- this._handlers.set(path, []);
1161
- }
1162
- this._handlers.get(path).push(handler);
1163
- return this;
1164
- }
1165
- /**
1166
- * 移除配置处理器
1167
- */
1168
- removeHandler(path, handler) {
1169
- const handlers = this._handlers.get(path);
1170
- if (handlers) {
1171
- const index2 = handlers.indexOf(handler);
1172
- if (index2 > -1) {
1173
- handlers.splice(index2, 1);
1174
- }
1175
- }
1176
- return this;
1177
- }
1178
- /**
1179
- * 触发配置变更
1180
- */
1181
- _triggerChange(path, oldValue, newValue) {
1182
- this.emit("config-changed", {
1183
- path,
1184
- oldValue,
1185
- newValue,
1186
- timestamp: /* @__PURE__ */ new Date()
1187
- });
1188
- this.emit(`config-changed:${path}`, {
1189
- oldValue,
1190
- newValue,
1191
- timestamp: /* @__PURE__ */ new Date()
1192
- });
1193
- const handlers = this._handlers.get(path);
1194
- if (handlers) {
1195
- handlers.forEach((handler) => {
1196
- try {
1197
- handler(newValue, oldValue, path);
1198
- } catch (error) {
1199
- console.error(`配置处理器执行失败 (${path}):`, error);
1200
- }
1201
- });
1202
- }
1203
- const pathParts = path.split(".");
1204
- for (let i = pathParts.length - 1; i >= 0; i--) {
1205
- const parentPath = pathParts.slice(0, i).join(".");
1206
- const wildcardPath = parentPath ? `${parentPath}.*` : "*";
1207
- const parentHandlers = this._handlers.get(wildcardPath);
1208
- if (parentHandlers) {
1209
- parentHandlers.forEach((handler) => {
1210
- try {
1211
- handler(newValue, oldValue, path);
1212
- } catch (error) {
1213
- console.error(`通配符处理器执行失败 (${wildcardPath}):`, error);
1214
- }
1215
- });
1216
- }
1217
- }
1218
- }
1219
- /**
1220
- * 获取配置快照(非代理版本)
1221
- */
1222
- getSnapshot() {
1223
- return JSON.parse(JSON.stringify(this._config));
1224
- }
1225
- /**
1226
- * 批量更新配置
1227
- */
1228
- update(newConfig) {
1229
- Object.keys(newConfig).forEach((key) => {
1230
- this.config[key] = newConfig[key];
1231
- });
1232
- return this;
1233
- }
1234
- /**
1235
- * 重置为默认值
1236
- */
1237
- reset() {
1238
- const oldConfig = this.getSnapshot();
1239
- this._config = JSON.parse(JSON.stringify(this._defaultConfig));
1240
- this.config = this._createProxy(this._config);
1241
- this.emit("config-reset", {
1242
- oldConfig,
1243
- newConfig: this.getSnapshot(),
1244
- timestamp: /* @__PURE__ */ new Date()
1245
- });
1246
- return this;
1247
- }
711
+ /** OpenAI 兼容格式 */
712
+ function toOpenAI({ messages, systemPrompts, capabilities, resolveImage }) {
713
+ const rImg = typeof resolveImage === "function" ? resolveImage : defaultResolveImage;
714
+ const result = [];
715
+ for (const sp of systemPrompts) if (sp?.content && isString(sp.content) && sp.content.trim()) result.push({
716
+ role: "system",
717
+ content: sp.content.trim()
718
+ });
719
+ let ephemEnd = messages.length;
720
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i]._ephemeral) ephemEnd = i;
721
+ else break;
722
+ for (let i = 0; i < messages.length; i++) {
723
+ const msg = messages[i];
724
+ if (msg._ephemeral) {
725
+ if (i < ephemEnd) continue;
726
+ }
727
+ if (msg.role === "system" && !msg._ephemeral) continue;
728
+ if (msg.role === "tool") {
729
+ result.push({
730
+ role: "tool",
731
+ content: msg.content || "",
732
+ tool_call_id: msg.toolCallId
733
+ });
734
+ continue;
735
+ }
736
+ if (msg.role === "assistant" && msg.toolCalls?.length) {
737
+ const entry = {
738
+ role: "assistant",
739
+ content: msg.content || "",
740
+ tool_calls: msg.toolCalls
741
+ };
742
+ if (msg.prefix) entry.prefix = true;
743
+ if (capabilities?.reasoning && msg.reasoningContent) entry.reasoning_content = msg.reasoningContent;
744
+ result.push(entry);
745
+ continue;
746
+ }
747
+ const hasText = msg.content && isString(msg.content) && msg.content.trim();
748
+ const hasImages = msg.images && Array.isArray(msg.images) && msg.images.length > 0;
749
+ if (!hasText && !hasImages) {
750
+ if (msg.role === "assistant" && msg.prefix) {
751
+ const prefixEntry = {
752
+ role: "assistant",
753
+ content: "",
754
+ prefix: true
755
+ };
756
+ if (capabilities?.reasoning && msg.reasoningContent) prefixEntry.reasoning_content = msg.reasoningContent;
757
+ result.push(prefixEntry);
758
+ }
759
+ continue;
760
+ }
761
+ const entry = { role: msg.role };
762
+ if (hasImages) {
763
+ if (!capabilities?.vision) throw new Error("[MessageFormatter] 消息包含图片但模型不支持视觉(capabilities.vision=false)。请切换模型或移除图片。");
764
+ entry.content = buildMultimodalContent(msg.content || "", msg.images, rImg);
765
+ } else entry.content = msg.content;
766
+ if (msg.prefix) entry.prefix = true;
767
+ result.push(entry);
768
+ }
769
+ return result;
1248
770
  }
1249
- const defaultConfig = {
1250
- api: {
1251
- key: "",
1252
- url: "https://api.deepseek.com/v1/chat/completions",
1253
- timeout: 3e4
1254
- },
1255
- model: {
1256
- name: "deepseek-chat",
1257
- temperature: 0.7,
1258
- // maxTokens: 2000,
1259
- stream: false,
1260
- reasoningEffort: "medium"
1261
- },
1262
- conversation: {
1263
- baseRounds: 10,
1264
- cycleRounds: 5
1265
- },
1266
- debug: false
771
+ var MessageFormatter = {
772
+ _formats: new Map([["openai", toOpenAI]]),
773
+ register(name, fn) {
774
+ if (!name || typeof name !== "string" || !name.trim()) throw new Error("[MessageFormatter] 格式名称必须是非空字符串");
775
+ if (typeof fn !== "function") throw new Error("[MessageFormatter] 转换函数必须是 function");
776
+ this._formats.set(name.trim(), fn);
777
+ },
778
+ unregister(name) {
779
+ if (name === "openai") throw new Error("[MessageFormatter] 内置格式 \"openai\" 不可移除");
780
+ this._formats.delete(name);
781
+ },
782
+ listFormats() {
783
+ return [...this._formats.keys()];
784
+ },
785
+ format(options = {}) {
786
+ const formatName = options.format || "openai";
787
+ const fn = this._formats.get(formatName);
788
+ if (!fn) throw new Error(`[MessageFormatter] 未知格式 "${formatName}"。可用格式: ${[...this._formats.keys()].join(", ")}`);
789
+ return fn({
790
+ messages: options.messages || [],
791
+ systemPrompts: options.systemPrompts || [],
792
+ capabilities: options.capabilities || {},
793
+ resolveImage: options.resolveImage
794
+ });
795
+ }
1267
796
  };
1268
- class ChatService extends EventEmitter {
1269
- constructor(options = {}) {
1270
- super();
1271
- this.autoAddMessages = options.autoAddMessages ?? true;
1272
- this.configManager = new ConfigManager({
1273
- ...defaultConfig,
1274
- ...options
1275
- });
1276
- this.messages = new Messages();
1277
- this.apiClient = new ApiClient(
1278
- this.configManager.config.api.key,
1279
- this.configManager.config.api.url
1280
- );
1281
- this.requestBuilder = new RequestBuilder(
1282
- this.configManager.config.model.name,
1283
- this.messages,
1284
- {
1285
- temperature: this.configManager.config.model.temperature,
1286
- max_tokens: this.configManager.config.model.maxTokens,
1287
- stream: this.configManager.config.model.stream,
1288
- reasoning_effort: this.configManager.config.model.reasoningEffort
1289
- }
1290
- );
1291
- this.toolManager = new ToolManager();
1292
- this._setupConfigHandlers();
1293
- this._setupDefaultListeners();
1294
- }
1295
- /**
1296
- * 设置配置变更处理器
1297
- */
1298
- _setupConfigHandlers() {
1299
- this.configManager.registerHandler("api.key", (newValue) => {
1300
- this.apiClient.setApiKey(newValue);
1301
- });
1302
- this.configManager.registerHandler("api.url", (newValue) => {
1303
- this.apiClient.setApiUrl(newValue);
1304
- });
1305
- this.configManager.registerHandler("model.name", (newValue) => {
1306
- this.requestBuilder.model = newValue;
1307
- });
1308
- this.configManager.registerHandler("model.temperature", (newValue) => {
1309
- this.requestBuilder.config.temperature = newValue;
1310
- });
1311
- this.configManager.registerHandler("model.stream", (newValue) => {
1312
- this.requestBuilder.config.stream = newValue;
1313
- });
1314
- this.configManager.registerHandler("debug", (newValue) => {
1315
- if (newValue) {
1316
- console.log("🔧 调试模式已启用");
1317
- }
1318
- });
1319
- this.configManager.on("config-changed", (data) => {
1320
- this.emit("service-config-changed", data);
1321
- });
1322
- }
1323
- /**
1324
- * 便捷方法:快速设置 API
1325
- */
1326
- setApi(key, url) {
1327
- this.configManager.update({
1328
- api: { key, url }
1329
- });
1330
- return this;
1331
- }
1332
- /**
1333
- * 便捷方法:快速设置模型
1334
- */
1335
- setModel(name, temperature = 0.7) {
1336
- this.configManager.update({
1337
- model: { name, temperature }
1338
- });
1339
- return this;
1340
- }
1341
- _setupDefaultListeners() {
1342
- this.apiClient.on("request-start", (data) => {
1343
- this.emit("request-start", data);
1344
- });
1345
- this.apiClient.on("request-success", (data) => {
1346
- this.emit("request-success", data);
1347
- });
1348
- this.apiClient.on("request-error", (data) => {
1349
- this.emit("request-error", data);
1350
- });
1351
- this.apiClient.on("stream-chunk", (data) => {
1352
- this.emit("stream-chunk", data);
1353
- });
1354
- this.toolManager.on("tool-execute-start", (data) => {
1355
- this.emit("tool-execute-start", data);
1356
- });
1357
- this.toolManager.on("tool-execute-success", (data) => {
1358
- this.emit("tool-execute-success", data);
1359
- });
1360
- this.toolManager.on("tool-execute-error", (data) => {
1361
- this.emit("tool-execute-error", data);
1362
- });
1363
- }
1364
- /**
1365
- * 注册工具
1366
- */
1367
- registerTool(name, definition, executor) {
1368
- this.toolManager.registerTool(name, definition, executor);
1369
- this.messages.addTool(definition);
1370
- return this;
1371
- }
1372
- /**
1373
- * 发送消息(支持工具调用)
1374
- */
1375
- async send(userMessage, options = {}) {
1376
- try {
1377
- this.emit("sending", {
1378
- role: "user",
1379
- content: userMessage,
1380
- timestamp: /* @__PURE__ */ new Date(),
1381
- eventType: "sending"
1382
- });
1383
- this.messages.addUserMessage(userMessage);
1384
- const requestBody = this.requestBuilder.toJSON(
1385
- options.baseRounds,
1386
- options.cycleRounds
1387
- );
1388
- const response = await this.apiClient.send(requestBody);
1389
- const aiMessage = response.choices[0].message;
1390
- if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {
1391
- return await this._handleToolCalls(aiMessage);
1392
- } else {
1393
- const eventData = await this._handleNormalResponse(aiMessage);
1394
- return eventData.content;
1395
- }
1396
- } catch (error) {
1397
- this.emit("error", {
1398
- error,
1399
- message: userMessage,
1400
- timestamp: /* @__PURE__ */ new Date()
1401
- });
1402
- throw error;
1403
- }
1404
- }
1405
- /**
1406
- * 处理工具调用(支持循环调用)
1407
- */
1408
- async _handleToolCalls(aiMessage, maxIterations = 5) {
1409
- let iteration = 0;
1410
- let currentMessage = aiMessage;
1411
- while (iteration < maxIterations) {
1412
- iteration++;
1413
- this.messages.addAssistantMessage(currentMessage.content || "", {
1414
- tool_calls: currentMessage.tool_calls,
1415
- reasoning_content: currentMessage.reasoning_content || ""
1416
- // ✅ 新增:保存思考内容
1417
- });
1418
- this.emit("tool-call-requested", {
1419
- tool_calls: currentMessage.tool_calls,
1420
- reasoning_content: currentMessage.reasoning_content,
1421
- // ✅ 新增:包含思考内容
1422
- timestamp: /* @__PURE__ */ new Date(),
1423
- iteration
1424
- });
1425
- const toolResults = await this.toolManager.executeToolCalls(currentMessage.tool_calls);
1426
- for (const result of toolResults) {
1427
- this.messages.addToolMessage(
1428
- result.result || result.error || "",
1429
- result.tool_call_id
1430
- );
1431
- }
1432
- const requestBody = this.requestBuilder.toJSON();
1433
- const response = await this.apiClient.send(requestBody);
1434
- currentMessage = response.choices[0].message;
1435
- if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
1436
- break;
1437
- }
1438
- }
1439
- const eventData = await this._handleAssistantResponse(currentMessage, {
1440
- toolIterations: iteration
1441
- });
1442
- return eventData.content;
1443
- }
1444
- /**
1445
- * 处理助手回复(统一方法,用于普通和流式请求)
1446
- */
1447
- async _handleAssistantResponse(aiMessage, options = {}) {
1448
- const { isStreaming = false, toolIterations = 0, skipAddMessage = false } = options;
1449
- const shouldAddMessage = this.autoAddMessages && !skipAddMessage;
1450
- if (shouldAddMessage) {
1451
- this.messages.addAssistantMessage(aiMessage.content || "", {
1452
- reasoning_content: aiMessage.reasoning_content
1453
- });
1454
- }
1455
- const eventData = {
1456
- // 基础字段(Messages格式)
1457
- role: "assistant",
1458
- content: aiMessage.content || "",
1459
- timestamp: /* @__PURE__ */ new Date(),
1460
- // 扩展字段
1461
- ...aiMessage.reasoning_content && { reasoning_content: aiMessage.reasoning_content },
1462
- ...aiMessage.tool_calls && { tool_calls: aiMessage.tool_calls },
1463
- ...aiMessage.tool_call_id && { tool_call_id: aiMessage.tool_call_id },
1464
- // 框架元数据
1465
- isStreaming,
1466
- toolIterations,
1467
- eventType: isStreaming ? "stream-complete" : "response-complete",
1468
- // 保留原始响应(只有普通请求有)
1469
- ...isStreaming ? {} : {
1470
- response: { choices: [{ message: aiMessage }] }
1471
- }
1472
- };
1473
- this.emit("message", eventData);
1474
- return eventData;
1475
- }
1476
- /**
1477
- * 处理普通回复
1478
- */
1479
- async _handleNormalResponse(aiMessage) {
1480
- return await this._handleAssistantResponse(aiMessage);
1481
- }
1482
- /**
1483
- * 流式发送消息(支持工具调用)
1484
- */
1485
- async stream(userMessage, onProgress, onDone, options = {}) {
1486
- try {
1487
- this.emit("sending", {
1488
- role: "user",
1489
- content: userMessage,
1490
- timestamp: /* @__PURE__ */ new Date(),
1491
- eventType: "sending"
1492
- });
1493
- this.messages.addUserMessage(userMessage);
1494
- const requestBuilder = new RequestBuilder(this.requestBuilder.model, this.messages, {
1495
- ...this.requestBuilder.config,
1496
- stream: true
1497
- // ✅ 必须设置为true!
1498
- });
1499
- const requestBody = requestBuilder.toJSON(
1500
- options.baseRounds,
1501
- options.cycleRounds
1502
- );
1503
- const response = await this.apiClient.strSend(
1504
- requestBody,
1505
- // 如果 onProgress 是函数就调用,否则用空函数
1506
- typeof onProgress === "function" ? (chunk) => {
1507
- this.emit("stream-progress", chunk);
1508
- onProgress(chunk);
1509
- } : (chunk) => {
1510
- this.emit("stream-progress", chunk);
1511
- },
1512
- typeof onDone === "function" ? async (finalMessage) => {
1513
- if (finalMessage.tool_calls && finalMessage.tool_calls.length > 0) {
1514
- await this._handleStreamToolCalls(finalMessage, onProgress, onDone);
1515
- } else {
1516
- const eventData = await this._handleAssistantResponse(finalMessage, {
1517
- isStreaming: true,
1518
- skipAddMessage: true
1519
- });
1520
- onDone(eventData);
1521
- }
1522
- } : async (finalMessage) => {
1523
- if (finalMessage.tool_calls && finalMessage.tool_calls.length > 0) {
1524
- await this._handleStreamToolCalls(finalMessage);
1525
- } else {
1526
- await this._handleAssistantResponse(finalMessage, {
1527
- isStreaming: true,
1528
- skipAddMessage: true
1529
- });
1530
- }
1531
- }
1532
- );
1533
- return response;
1534
- } catch (error) {
1535
- this.emit("error", {
1536
- error,
1537
- message: userMessage,
1538
- timestamp: /* @__PURE__ */ new Date()
1539
- });
1540
- throw error;
1541
- }
1542
- }
1543
- /**
1544
- * 处理流式传输中的工具调用(支持循环调用)
1545
- */
1546
- async _handleStreamToolCalls(aiMessage, onProgress, onDone, maxIterations = 5) {
1547
- let iteration = 0;
1548
- let currentMessage = aiMessage;
1549
- while (iteration < maxIterations) {
1550
- iteration++;
1551
- this.messages.addAssistantMessage(currentMessage.content || "", {
1552
- tool_calls: currentMessage.tool_calls,
1553
- reasoning_content: currentMessage.reasoning_content || ""
1554
- // ✅ 新增:保存思考内容
1555
- });
1556
- this.emit("tool-call-requested", {
1557
- tool_calls: currentMessage.tool_calls,
1558
- reasoning_content: currentMessage.reasoning_content,
1559
- // ✅ 新增:包含思考内容
1560
- timestamp: /* @__PURE__ */ new Date(),
1561
- iteration
1562
- });
1563
- const toolResults = await this.toolManager.executeToolCalls(currentMessage.tool_calls);
1564
- for (const result of toolResults) {
1565
- this.messages.addToolMessage(result.result || result.error, result.tool_call_id);
1566
- }
1567
- const requestBody = this.requestBuilder.toJSON();
1568
- await new Promise((resolve, reject) => {
1569
- this.apiClient.strSend(
1570
- requestBody,
1571
- typeof onProgress === "function" ? (chunk) => {
1572
- this.emit("stream-progress", chunk);
1573
- onProgress(chunk);
1574
- } : (chunk) => {
1575
- this.emit("stream-progress", chunk);
1576
- },
1577
- (finalMessage) => {
1578
- currentMessage = finalMessage;
1579
- if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
1580
- resolve();
1581
- } else {
1582
- resolve();
1583
- }
1584
- }
1585
- ).catch(reject);
1586
- });
1587
- if (!currentMessage.tool_calls || currentMessage.tool_calls.length === 0) {
1588
- break;
1589
- }
1590
- }
1591
- const eventData = await this._handleAssistantResponse(currentMessage, {
1592
- isStreaming: true,
1593
- toolIterations: iteration,
1594
- skipAddMessage: true
1595
- });
1596
- if (typeof onDone === "function") {
1597
- onDone(eventData);
1598
- }
1599
- }
1600
- /**
1601
- * 撤回消息
1602
- */
1603
- undo() {
1604
- const removed = this.messages.undoToAssistant();
1605
- if (removed.length > 0) {
1606
- this.emit("undo", {
1607
- removedMessages: removed,
1608
- timestamp: /* @__PURE__ */ new Date()
1609
- });
1610
- }
1611
- return removed;
1612
- }
1613
- /**
1614
- * 清空消息
1615
- */
1616
- clear() {
1617
- const removed = this.messages.clearMessages();
1618
- this.emit("clear", {
1619
- removedMessages: removed,
1620
- timestamp: /* @__PURE__ */ new Date()
1621
- });
1622
- return removed;
1623
- }
1624
- /**
1625
- * 导出对话数据
1626
- */
1627
- export() {
1628
- const data = this.messages.export();
1629
- this.emit("export", {
1630
- data,
1631
- timestamp: /* @__PURE__ */ new Date()
1632
- });
1633
- return data;
1634
- }
1635
- /**
1636
- * 导入对话数据
1637
- */
1638
- import(data) {
1639
- this.messages.import(data);
1640
- this.emit("import", {
1641
- data,
1642
- timestamp: /* @__PURE__ */ new Date()
1643
- });
1644
- return this;
1645
- }
797
+ function assembleMessages(options = {}) {
798
+ return MessageFormatter.format({
799
+ ...options,
800
+ format: "openai"
801
+ });
1646
802
  }
1647
- const index = {
1648
- Messages,
1649
- RequestBuilder,
1650
- ApiClient,
1651
- EventEmitter,
1652
- MessageFormatter,
1653
- ToolManager,
1654
- ChatService,
1655
- defaultConfig
803
+ //#endregion
804
+ //#region src/adapters/openai.js
805
+ /**
806
+ * OpenAI 兼容 API 适配器
807
+ * 支持 DeepSeek 等完全兼容 OpenAI 接口的服务
808
+ */
809
+ var openaiAdapter = {
810
+ name: "openai",
811
+ install(chatService) {
812
+ chatService.setAdapter(this);
813
+ },
814
+ buildRequest(messages, config, systemPrompts = []) {
815
+ const model = config.model || config.modelParams?.model;
816
+ if (!model) throw new Error("Missing required config: model (either at top level or in modelParams)");
817
+ const temperature = config.modelParams?.temperature ?? config.temperature ?? .7;
818
+ const maxTokens = config.modelParams?.maxTokens ?? config.maxTokens ?? 2e3;
819
+ const reasoningEffort = config.modelParams?.reasoningEffort ?? config.reasoningEffort;
820
+ const requestBody = {
821
+ model,
822
+ messages: MessageFormatter.format({
823
+ messages,
824
+ systemPrompts,
825
+ capabilities: config.capabilities || {},
826
+ resolveImage: config.resolveImage,
827
+ format: config.messageFormat
828
+ }),
829
+ temperature,
830
+ max_tokens: maxTokens,
831
+ stream: false
832
+ };
833
+ if (config.tools && Array.isArray(config.tools) && config.tools.length > 0) {
834
+ requestBody.tools = config.tools;
835
+ requestBody.tool_choice = "auto";
836
+ }
837
+ if (reasoningEffort && model === "deepseek-reasoner") requestBody.reasoning_effort = reasoningEffort;
838
+ return requestBody;
839
+ },
840
+ _getUrl(config) {
841
+ config = config || {};
842
+ const { apiUrl, baseUrl, path } = config;
843
+ const defaultPath = "/chat/completions";
844
+ if (apiUrl && isString(apiUrl)) return apiUrl;
845
+ if (baseUrl && isString(baseUrl)) return joinUrl(baseUrl, path && isString(path) ? path : defaultPath);
846
+ return "https://api.openai.com/v1/chat/completions";
847
+ },
848
+ async send(requestBody, config, options = {}) {
849
+ try {
850
+ const url = this._getUrl(config);
851
+ const headers = {
852
+ "Content-Type": "application/json",
853
+ "Authorization": `Bearer ${config.apiKey}`,
854
+ ...config.headers || {},
855
+ ...options.headers || {}
856
+ };
857
+ const response = await fetch(url, {
858
+ method: "POST",
859
+ headers,
860
+ body: JSON.stringify(requestBody),
861
+ signal: options.signal
862
+ });
863
+ if (!response.ok) await this.handleErrorResponse(response);
864
+ return await response.json();
865
+ } catch (error) {
866
+ if (error instanceof APIError) throw error;
867
+ if (error.name === "AbortError") throw error;
868
+ if (error.name === "TypeError" && error.message.includes("fetch")) throw new NetworkError(`Request failed: ${error.message}`, error);
869
+ throw error;
870
+ }
871
+ },
872
+ parseResponse(apiResponse) {
873
+ 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));
874
+ const msg = apiResponse.choices[0].message;
875
+ const internal = {
876
+ role: msg.role,
877
+ content: msg.content || ""
878
+ };
879
+ if (msg.tool_calls) internal.toolCalls = msg.tool_calls;
880
+ if (msg.reasoning_content) internal.reasoningContent = msg.reasoning_content;
881
+ return internal;
882
+ },
883
+ async stream(requestBody, config, onProgress, onDone, options = {}) {
884
+ const streamBody = {
885
+ ...requestBody,
886
+ stream: true
887
+ };
888
+ const url = this._getUrl(config);
889
+ let response;
890
+ const headers = {
891
+ "Content-Type": "application/json",
892
+ "Authorization": `Bearer ${config.apiKey}`,
893
+ "Accept": "text/event-stream",
894
+ ...config.headers || {},
895
+ ...options.headers || {}
896
+ };
897
+ try {
898
+ response = await fetch(url, {
899
+ method: "POST",
900
+ headers,
901
+ body: JSON.stringify(streamBody),
902
+ signal: options.signal
903
+ });
904
+ } catch (error) {
905
+ if (error.name === "AbortError") throw error;
906
+ if (error.name === "TypeError" && error.message.includes("fetch")) throw new NetworkError(`Stream request failed: ${error.message}`, error);
907
+ throw error;
908
+ }
909
+ if (!response.ok) await this.handleErrorResponse(response);
910
+ const reader = response.body.getReader();
911
+ const decoder = new TextDecoder();
912
+ let buffer = "";
913
+ let accumulated = {
914
+ role: "assistant",
915
+ content: "",
916
+ reasoningContent: ""
917
+ };
918
+ while (true) {
919
+ if (options.signal?.aborted) break;
920
+ const { done, value } = await reader.read();
921
+ if (done) break;
922
+ buffer += decoder.decode(value, { stream: true });
923
+ const lines = buffer.split(/\n\n/);
924
+ buffer = lines.pop();
925
+ for (const line of lines) {
926
+ const dataLine = line.replace(/^data: /, "").trim();
927
+ if (!dataLine) continue;
928
+ if (dataLine === "[DONE]") break;
929
+ try {
930
+ const delta = JSON.parse(dataLine).choices?.[0]?.delta;
931
+ if (!delta) continue;
932
+ if (delta.content) accumulated.content += delta.content;
933
+ if (delta.tool_calls) {
934
+ if (!accumulated.toolCalls) accumulated.toolCalls = [];
935
+ for (const toolCallDelta of delta.tool_calls) {
936
+ const index = toolCallDelta.index;
937
+ if (!accumulated.toolCalls[index]) accumulated.toolCalls[index] = {
938
+ id: "",
939
+ type: "function",
940
+ function: {
941
+ name: "",
942
+ arguments: ""
943
+ }
944
+ };
945
+ if (toolCallDelta.id) accumulated.toolCalls[index].id = toolCallDelta.id;
946
+ if (toolCallDelta.type) accumulated.toolCalls[index].type = toolCallDelta.type;
947
+ if (toolCallDelta.function?.name) accumulated.toolCalls[index].function.name += toolCallDelta.function.name;
948
+ if (toolCallDelta.function?.arguments) accumulated.toolCalls[index].function.arguments += toolCallDelta.function.arguments;
949
+ }
950
+ }
951
+ if (delta.reasoning_content) accumulated.reasoningContent += delta.reasoning_content;
952
+ onProgress({ ...accumulated });
953
+ } catch (e) {
954
+ console.warn("stream parsing failed :", e, dataLine);
955
+ }
956
+ }
957
+ }
958
+ onDone({
959
+ role: "assistant",
960
+ content: accumulated.content,
961
+ toolCalls: accumulated.toolCalls,
962
+ reasoningContent: accumulated.reasoningContent
963
+ });
964
+ },
965
+ async handleErrorResponse(response) {
966
+ let errorText = await response.text();
967
+ let errorMessage = `HTTP ${response.status}`;
968
+ try {
969
+ const errorJson = JSON.parse(errorText);
970
+ errorMessage = errorJson.error?.message || errorJson.message || errorText.slice(0, 200);
971
+ } catch (e) {
972
+ errorMessage = errorText.length > 200 ? errorText.slice(0, 200) + "..." : errorText;
973
+ }
974
+ throw new APIError(errorMessage, response.status, null, errorText);
975
+ }
976
+ };
977
+ //#endregion
978
+ //#region src/plugins/tool-calling.js
979
+ /**
980
+ * 工具调用插件
981
+ * 功能:拦截助手消息中的 tool_calls,执行对应的工具,将结果作为 tool 消息加入对话,
982
+ * 然后自动继续对话(通过 sendExisting / sendExistingStream),直到没有新的工具调用。
983
+ *
984
+ * 设计要点:
985
+ * - 支持普通请求和流式请求(通过 isStream 标志区分)
986
+ * - 支持多次工具调用循环(maxIterations 防止无限循环)
987
+ * - 串行执行工具(可后续升级为并行)
988
+ * - 工具执行失败时,仍然返回错误信息给 AI,而不是中断整个流程
989
+ * - 触发 tool-error 事件,方便用户监听工具执行异常
990
+ */
991
+ var toolCallingPlugin = {
992
+ name: "tool-calling",
993
+ maxIterations: 5,
994
+ install(chatService) {
995
+ this.chatService = chatService;
996
+ this._tools = /* @__PURE__ */ new Map();
997
+ if (!chatService.config.tools) chatService.config.tools = [];
998
+ /**
999
+ * 注册工具
1000
+ * @param {string} name - 工具名称(唯一标识)
1001
+ * @param {string} description - 工具描述(告诉 AI 何时调用)
1002
+ * @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
1003
+ * @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
1004
+ * @returns {ChatService} 返回 chatService 实例,支持链式调用
1005
+ */
1006
+ chatService.registerTool = (name, description, executor, parameters = {}) => {
1007
+ this._tools.set(name, {
1008
+ executor,
1009
+ description
1010
+ });
1011
+ const toolDefinition = {
1012
+ type: "function",
1013
+ function: {
1014
+ name,
1015
+ description,
1016
+ parameters: {
1017
+ type: "object",
1018
+ properties: parameters,
1019
+ required: Object.keys(parameters).filter((key) => parameters[key]?.required)
1020
+ }
1021
+ }
1022
+ };
1023
+ if (!chatService.config.tools.find((t) => t.function.name === name)) chatService.config.tools.push(toolDefinition);
1024
+ return chatService;
1025
+ };
1026
+ chatService._processResponse = async (response, { isStream, onProgress, onDone }) => {
1027
+ return this._handleWithTools(response, isStream, onProgress, onDone);
1028
+ };
1029
+ },
1030
+ async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
1031
+ const self = this;
1032
+ const chat = this.chatService;
1033
+ let iteration = 0;
1034
+ /**
1035
+ * 递归处理工具调用
1036
+ * @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
1037
+ * @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
1038
+ */
1039
+ async function processResponse(initialResponse) {
1040
+ let lastResponse = initialResponse;
1041
+ while (iteration < self.maxIterations) {
1042
+ const toolCalls = lastResponse?.toolCalls;
1043
+ if (!toolCalls || toolCalls.length === 0) break;
1044
+ iteration++;
1045
+ const toolResults = await Promise.all(toolCalls.map(async (call) => {
1046
+ const toolName = call.function?.name;
1047
+ let args;
1048
+ try {
1049
+ args = JSON.parse(call.function?.arguments || "{}");
1050
+ } catch (parseErr) {
1051
+ chat.emit("tool-error", {
1052
+ toolName: toolName || "unknown",
1053
+ error: parseErr,
1054
+ toolCallId: call.id,
1055
+ stage: "parse",
1056
+ timestamp: Date.now()
1057
+ });
1058
+ return {
1059
+ tool_call_id: call.id,
1060
+ error: `参数解析失败: ${parseErr.message}`,
1061
+ success: false
1062
+ };
1063
+ }
1064
+ const tool = self._tools.get(toolName);
1065
+ if (!tool) {
1066
+ chat.emit("tool-error", {
1067
+ toolName,
1068
+ error: /* @__PURE__ */ new Error(`Tool not registered: ${toolName}`),
1069
+ toolCallId: call.id,
1070
+ stage: "lookup",
1071
+ timestamp: Date.now()
1072
+ });
1073
+ return {
1074
+ tool_call_id: call.id,
1075
+ error: `工具 ${toolName} 未注册`,
1076
+ success: false
1077
+ };
1078
+ }
1079
+ try {
1080
+ const toolTimeout = chat.config.toolTimeout;
1081
+ let execPromise = tool.executor(args);
1082
+ if (toolTimeout && typeof toolTimeout === "number" && toolTimeout > 0) {
1083
+ const timeoutErr = /* @__PURE__ */ new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
1084
+ timeoutErr.name = "ToolTimeoutError";
1085
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(timeoutErr), toolTimeout));
1086
+ execPromise = Promise.race([execPromise, timeoutPromise]);
1087
+ }
1088
+ const result = await execPromise;
1089
+ chat.emit("tool-success", {
1090
+ toolName,
1091
+ result,
1092
+ toolCallId: call.id,
1093
+ timestamp: Date.now()
1094
+ });
1095
+ return {
1096
+ tool_call_id: call.id,
1097
+ content: typeof result === "string" ? result : JSON.stringify(result),
1098
+ success: true
1099
+ };
1100
+ } catch (err) {
1101
+ const stage = err.name === "ToolTimeoutError" ? "timeout" : "execute";
1102
+ chat.emit("tool-error", {
1103
+ toolName,
1104
+ error: err,
1105
+ toolCallId: call.id,
1106
+ stage,
1107
+ timestamp: Date.now()
1108
+ });
1109
+ return {
1110
+ tool_call_id: call.id,
1111
+ error: err.message,
1112
+ success: false
1113
+ };
1114
+ }
1115
+ }));
1116
+ for (const tr of toolResults) {
1117
+ const content = tr.success ? tr.content : tr.error || "工具执行失败";
1118
+ chat.messages.addTool(content, tr.tool_call_id);
1119
+ }
1120
+ if (isStream) await new Promise((resolve) => {
1121
+ chat.sendExistingStream((chunk) => {
1122
+ if (onProgress) onProgress(chunk);
1123
+ lastResponse = chunk;
1124
+ }, (final) => {
1125
+ lastResponse = final;
1126
+ resolve();
1127
+ });
1128
+ });
1129
+ else lastResponse = await chat.sendExisting();
1130
+ }
1131
+ return lastResponse;
1132
+ }
1133
+ return await processResponse(initialResponse);
1134
+ }
1135
+ };
1136
+ //#endregion
1137
+ //#region src/plugins/model-registry.js
1138
+ /**
1139
+ * model-registry 插件
1140
+ *
1141
+ * 职责:
1142
+ * 1. 内置常用模型的能力标签表(model → capabilities 映射)
1143
+ * 2. 安装时自动根据 config.model 查表,写入 config.capabilities
1144
+ * 3. 监听 config-updated 事件,切换模型时自动同步能力
1145
+ * 4. 提供 chat.registerModel(),允许用户追加/覆盖自定义模型
1146
+ *
1147
+ * 能力标签字段(全部可选,缺失视为 false / 未知):
1148
+ * {
1149
+ * reasoning: boolean — 是否返回 reasoning_content(思维链)
1150
+ * vision: boolean — 是否支持图片输入
1151
+ * toolCalling: boolean — 是否支持 function calling
1152
+ * streaming: boolean — 是否支持流式传输
1153
+ * maxInputTokens: number — 最大输入 token 数
1154
+ * maxOutputTokens: number — 最大输出 token 数
1155
+ * }
1156
+ *
1157
+ * 使用:
1158
+ * chat.use(modelRegistryPlugin);
1159
+ * // config.capabilities 现在已自动填充
1160
+ * chat.registerModel('my-custom-model', { toolCalling: true });
1161
+ */
1162
+ var BUILTIN_MODELS = {
1163
+ "deepseek-chat": {
1164
+ reasoning: false,
1165
+ vision: false,
1166
+ toolCalling: true,
1167
+ streaming: true,
1168
+ maxInputTokens: 128e3,
1169
+ maxOutputTokens: 8192
1170
+ },
1171
+ "deepseek-reasoner": {
1172
+ reasoning: true,
1173
+ vision: false,
1174
+ toolCalling: true,
1175
+ streaming: true,
1176
+ maxInputTokens: 128e3,
1177
+ maxOutputTokens: 8192
1178
+ },
1179
+ "gpt-4o": {
1180
+ reasoning: false,
1181
+ vision: true,
1182
+ toolCalling: true,
1183
+ streaming: true,
1184
+ maxInputTokens: 128e3,
1185
+ maxOutputTokens: 16384
1186
+ },
1187
+ "gpt-4o-mini": {
1188
+ reasoning: false,
1189
+ vision: true,
1190
+ toolCalling: true,
1191
+ streaming: true,
1192
+ maxInputTokens: 128e3,
1193
+ maxOutputTokens: 16384
1194
+ },
1195
+ "gpt-3.5-turbo": {
1196
+ reasoning: false,
1197
+ vision: false,
1198
+ toolCalling: true,
1199
+ streaming: true,
1200
+ maxInputTokens: 16385,
1201
+ maxOutputTokens: 4096
1202
+ },
1203
+ "o1": {
1204
+ reasoning: true,
1205
+ vision: false,
1206
+ toolCalling: false,
1207
+ streaming: false,
1208
+ maxInputTokens: 2e5,
1209
+ maxOutputTokens: 1e5
1210
+ },
1211
+ "o3-mini": {
1212
+ reasoning: true,
1213
+ vision: false,
1214
+ toolCalling: true,
1215
+ streaming: true,
1216
+ maxInputTokens: 2e5,
1217
+ maxOutputTokens: 1e5
1218
+ },
1219
+ "claude-3.5-sonnet": {
1220
+ reasoning: false,
1221
+ vision: true,
1222
+ toolCalling: true,
1223
+ streaming: true,
1224
+ maxInputTokens: 2e5,
1225
+ maxOutputTokens: 8192
1226
+ },
1227
+ "claude-3.5-haiku": {
1228
+ reasoning: false,
1229
+ vision: true,
1230
+ toolCalling: true,
1231
+ streaming: true,
1232
+ maxInputTokens: 2e5,
1233
+ maxOutputTokens: 8192
1234
+ }
1235
+ };
1236
+ var DEFAULT_CAPABILITIES = {
1237
+ streaming: true,
1238
+ toolCalling: false,
1239
+ reasoning: false,
1240
+ vision: false
1241
+ };
1242
+ var modelRegistryPlugin = {
1243
+ name: "model-registry",
1244
+ install(chatService) {
1245
+ this.chat = chatService;
1246
+ this._registry = new Map(Object.entries(BUILTIN_MODELS));
1247
+ /**
1248
+ * 注册/覆盖一个模型的能力标签
1249
+ * @param {string} name — 模型名称
1250
+ * @param {Object} capabilities — 能力标签对象(部分字段即可,未提供的取默认值)
1251
+ * @returns {ChatService}
1252
+ */
1253
+ chatService.registerModel = (name, capabilities = {}) => {
1254
+ if (!name || typeof name !== "string" || !name.trim()) throw new Error("[model-registry] 模型名称必须是非空字符串");
1255
+ const merged = {
1256
+ ...DEFAULT_CAPABILITIES,
1257
+ ...capabilities
1258
+ };
1259
+ this._registry.set(name.trim(), merged);
1260
+ if (chatService.config.model === name.trim()) this._syncCapabilities();
1261
+ return chatService;
1262
+ };
1263
+ /**
1264
+ * 列出所有已注册的模型名称
1265
+ * @returns {Array<string>}
1266
+ */
1267
+ chatService.listModels = () => {
1268
+ return [...this._registry.keys()];
1269
+ };
1270
+ this._syncCapabilities();
1271
+ chatService.on("config-updated", ({ changes }) => {
1272
+ if ("model" in changes) this._syncCapabilities();
1273
+ if ("capabilities" in changes && !("model" in changes)) {
1274
+ const current = this._lookupCapabilities();
1275
+ if (current) chatService.config.capabilities = {
1276
+ ...current,
1277
+ ...changes.capabilities
1278
+ };
1279
+ }
1280
+ });
1281
+ },
1282
+ _lookupCapabilities() {
1283
+ const model = this.chat.config.model;
1284
+ if (!model) return null;
1285
+ return this._registry.get(model) || null;
1286
+ },
1287
+ _syncCapabilities() {
1288
+ const caps = this._lookupCapabilities();
1289
+ if (caps) this.chat.config.capabilities = { ...caps };
1290
+ }
1656
1291
  };
1657
- exports.ApiClient = ApiClient;
1292
+ //#endregion
1293
+ exports.APIError = APIError;
1658
1294
  exports.ChatService = ChatService;
1295
+ exports.ConfigurationError = ConfigurationError;
1659
1296
  exports.EventEmitter = EventEmitter;
1660
1297
  exports.MessageFormatter = MessageFormatter;
1661
- exports.Messages = Messages;
1662
- exports.RequestBuilder = RequestBuilder;
1663
- exports.ToolManager = ToolManager;
1664
- exports.default = index;
1665
- //# sourceMappingURL=my-ai-chat-framework.node.cjs.js.map
1298
+ exports.MessageStore = MessageStore;
1299
+ exports.NetworkError = NetworkError;
1300
+ exports.ParsingError = ParsingError;
1301
+ exports.SystemPromptStore = SystemPromptStore;
1302
+ exports.assembleMessages = assembleMessages;
1303
+ exports.modelRegistryPlugin = modelRegistryPlugin;
1304
+ exports.openaiAdapter = openaiAdapter;
1305
+ exports.toolCallingPlugin = toolCallingPlugin;
1306
+
1307
+ //# sourceMappingURL=my-ai-chat-framework.node.cjs.js.map